diff --git a/plotFigures.m b/plotFigures.m
index c28605aa7141054fa769951d996d5f784e8b4274..08b88f5776ead5d8e234fe1a8a6a64f973ea1fd4 100644
--- a/plotFigures.m
+++ b/plotFigures.m
@@ -8,13 +8,18 @@ cd('scripts')
 % install IQMtoolbox and compile models
 Setup()
 
-% add necessary paths
+%% fig 7 - fit to Brännmark data
+plotBrannmark 
+clear all
+
+%% add necessary paths
 addpath('./Models')
 addpath('./data')
 addpath('./results')
-addpath('./suport')
+addpath(genpath('./suport'))
+
 
-% load data
+%% load data and parameters
 load('Coppack.mat');
 load('iozzo.mat');
 load('EGP.mat');
@@ -22,7 +27,10 @@ load('Ra.mat');
 load('INS.mat');
 load('GLUT4m');
 
-% nice colors
+load('./results/opt(12.92335).mat'); % optParam
+load('./results/allAcceptableParams.mat'); % allParams
+
+%% nice colors
 colorM=[1.0000, 0.1020, 0]; % muscle
 colorA=[0.9290, 0.6940, 0.1250]; % adipose
 colorMA=[1.0000 0.5137 0]; % muscle + adipose
@@ -30,25 +38,25 @@ colorL=[0.3961, 0.1843, 0.1098]; % liver
 colorII=[1.0000, 0.7529, 0.7961]; % red blood cells and CNS
 colorTOT=[0, 0, 0]; % total
 
-% time
+%% time
 sim_time = [DATA.time(1):0.001:DATA.time(end)];
 
 %% fig2
 % sim
 model_name='M0';
 model=str2func(model_name);
-[~,paramsAll]=IQMparameters(model);
-[inits] = simulateSteadyState(model, paramsAll);
-sim = model(sim_time, inits, paramsAll); 
+[~,paramsMod]=IQMparameters(model);
+[inits] = simulateSteadyStated(model, paramsMod);
+sim = model(sim_time, inits, paramsMod); 
 sim_muscle0 = sim.variablevalues(:,ismember(IQMvariables(model),'U_idm'))'; 
 sim_adipose0 = sim.variablevalues(:,ismember(IQMvariables(model),'U_idf'))';
 simM0=sim_muscle0+sim_adipose0;
 
 model_name='M1';
 model=str2func(model_name);
-[~,paramsAll]=IQMparameters(model);
-[inits] = simulateSteadyState(model, paramsAll);
-sim = model(sim_time, inits, paramsAll); 
+[~,paramsMod]=IQMparameters(model);
+[inits] = simulateSteadyStated(model, paramsMod);
+sim = model(sim_time, inits, paramsMod); 
 sim_muscle1 = sim.variablevalues(:,ismember(IQMvariables(model),'U_idm'))'; 
 sim_adipose1 = sim.variablevalues(:,ismember(IQMvariables(model),'U_idf'))'; 
 simM1=sim_muscle1+sim_adipose1;
@@ -140,32 +148,42 @@ legend('framed: simulation','filled: data')
 set(gca,'FontSize',20);
 box on
 
-saveas(gcf, '../../results/fig2D.png')
+saveas(gcf, './results/fig2D.png')
 
-%% fig 3
+%% fig 3 - glucose uptake in adipose and muscle tissue, comparison model M2a and M2b
 model_names={'M1','M4m'};
-load('./results/M4m_opt(28.86930).mat'); % optParam
-load('./results/M4m_allGoodParams'); % allParams
 
 model=str2func(model_names{1});
-[~,paramsAllA]=IQMparameters(model);
-[inits] = simulateSteadyState(model, paramsAllA);
-sim = model(sim_time, inits, paramsAllA); 
+[~,paramsModA]=IQMparameters(model);
+[inits] = simulateSteadyStated(model, paramsModA);
+sim = model(sim_time, inits, paramsModA); 
 sim_adiposeA = sim.variablevalues(:,ismember(IQMvariables(model),'U_idf'))'; 
 sim_muscleA = sim.variablevalues(:,ismember(IQMvariables(model),'U_idm'))'; 
 
 model=str2func(model_names{2}); 
-[pNames,paramsAllB]=IQMparameters(model); 
-[inits] = simulateSteadyState(model, paramsAllB);
-paramsFixed = [paramsAllB(1:find(contains(pNames,'EGP1'))-1)' EGP' Ra' INS' GLUT4m'];
-paramsAllB=[paramsFixed optParam];
-sim = model(sim_time, inits, paramsAllB);
+[pNames,paramsModB]=IQMparameters(model); 
+paramsFixed = [paramsModB(1:find(contains(pNames,'EGP1'))-1)' EGP Ra INS GLUT4m];
+paramsAllB = [paramsFixed optParam];
+[initsModB] = simulateSteadyState(model, paramsAllB);
+sim = model(sim_time, initsModB, paramsAllB);
 sim_adiposeB = sim.variablevalues(:,ismember(IQMvariables(model),'U_idf'))';
 sim_muscleB = sim.variablevalues(:,ismember(IQMvariables(model),'U_idm'))'; 
 
+
+sim = model(DATA.time, initsModB, paramsAllB);
+sim_adiposeDATA = sim.variablevalues(:,ismember(IQMvariables(model),'U_idf'))';
+sim_muscleDATA = sim.variablevalues(:,ismember(IQMvariables(model),'U_idm'))'; 
+
+limit = chi2inv(0.95,numel(DATA.Muscle)+numel(DATA.Adipose))
+
+costMuscle = nansum((((DATA.Muscle-sim_muscleDATA').^2)./(DATA.SEM1.^2)))
+costAdipose = nansum((((DATA.Adipose-sim_adiposeDATA').^2)./(DATA.SEM2.^2)))
+
+cost = costMuscle + costAdipose
+
 % find min and max
-[sampledParams] = sample_params(100,allParams);
-boundries=get_maxmin(sim_time, model, squeeze(sampledParams),paramsFixed);
+[sampledParams] = sampleParams(100,allParams);
+boundries=getMaxMin(sim_time, model, squeeze(sampledParams),paramsFixed);
 
 % adipose
 figure()
@@ -188,10 +206,10 @@ plotErrorbar(colorA,DATA.time,DATA.Adipose,DATA.SEM2);
 title('M2b','FontSize',12);
 yticks([0:1:3])
 set(gca,'FontSize',15);
-legend('uncertainty','data','simulation','Location', 'northeast')
+legend('uncertainty','simulation','data','Location', 'northeast')
 set(gca,'linewidth',1.4)
 
-saveas(gcf, '../../results/fig3Badipose.png')
+saveas(gcf, './results/fig3Badipose.png')
 
 % muscle
 figure()
@@ -210,20 +228,20 @@ set(gca,'linewidth',1.4);
 
 subplot(1,2,2);
 plotUncertainty(colorM,boundries,sim_time,'m'); hold on
-plotErrorbar(colorM,DATA.time,DATA.Muscle,DATA.SEM1); 
 plotSim(colorM,sim_muscleB,sim_time); 
+plotErrorbar(colorM,DATA.time,DATA.Muscle,DATA.SEM1); 
 title('M2b','FontSize',12);
 yticks([0:1:3])
 ylim([0 3.5])
 set(gca,'FontSize',15);
 set(gca,'linewidth',1.4)
-legend('uncertainty','data','simulation','Location', 'northeast')
+legend('uncertainty','simulation','data','Location', 'northeast')
  
-saveas(gcf, '../../results/fig3Bmuscle.png')
+saveas(gcf, './results/fig3Bmuscle.png')
 
-%% fig 4
+%% fig 4 - blood flow and glucose uptake adipose tissue
 
-model_name='M4';
+model_name='M3m';
 model=str2func(model_name);
 
 % normalize data
@@ -231,15 +249,21 @@ iozzo.uptake=100*iozzo.uptake/iozzo.uptake(1);
 iozzo.clearance=100*iozzo.clearance/iozzo.clearance(1);
 
 % simulate experiments
-[~,paramsAll]=IQMparameters(model);
-[paramsBI,paramsI,paramsB,params]=deal(paramsAll);
-
-params(90) = 0; 
-paramsB(90) = 0; 
-paramsBI(99) = 30*paramsBI(99); % adding bradykinin, increases blood foow two-folds
+[pNames,paramsMod]=IQMparameters(model);
+paramsFixed = [paramsMod(1:find(contains(pNames,'EGP1'))-1)' EGP Ra INS GLUT4m];
+paramsAll=[paramsFixed optParam];
+[paramsI,paramsB,params]=deal(paramsAll);
+
+params(ismember(pNames,'INS_offset')) = 0; 
+paramsB(ismember(pNames,'INS_offset')) = 0; 
+paramsB(ismember(pNames,'p_bf')) = 5; 
+paramsB(ismember(pNames,'INS_b')) = 0.8549; 
+paramsB(ismember(pNames,'bf_b')) = 3; 
+paramsBI = paramsB;
+paramsBI(ismember(pNames,'bradykinin')) = 10*paramsBI(ismember(pNames,'bradykinin')); % adding bradykinin, increases blood foow two-folds
 
 [initsI] = simulateSteadyState(model, paramsI);
-simI = model(sim_time, initsI, paramsAll); 
+simI = model(sim_time, initsI, paramsI); 
 sim_uptakeI = simI.variablevalues(:,ismember(IQMvariables(model),'U_idf'))'; 
 AUCsim_uI = trapz(sim_time,sim_uptakeI);
 
@@ -259,6 +283,7 @@ sim_uptake_BI = simBI.variablevalues(:,ismember(IQMvariables(model),'U_idf'))';
 AUCsim_uB = trapz(sim_time,sim_uptake_BI);
 
 % plot
+% glucose clearance, without insulin
 figure()
 set(gcf, 'Units', 'Normalized', 'OuterPosition', [0, 0.04, 0.4, 0.5]);
 subplot(2,2,3)
@@ -270,6 +295,7 @@ title('Glucose clearance','FontSize',20);
 set(gca,'FontSize',20);
 ylim([0 180])
 
+% glucose uptake, with insulin
 subplot(2,2,4)
 bar([1 2],[100*AUCsim_uI/AUCsim_uI  100*AUCsim_uB/AUCsim_uI],'FaceColor',colorA,'FaceAlpha',0.3,'EdgeColor',colorA,'LineWidth',2);hold on
 set(gca,'xtick',[])
@@ -313,16 +339,17 @@ yticks([0:50:150])
 ylim([0 180])
 
 
-saveas(gcf, '../../results/fig4.png')
+saveas(gcf, './results/fig4.png')
+
+%% fig 5 - time-curves and total glucose uptake compared with data for all tissues
 
-%% fig 5
 clear model_name
 model_name='M4m';
 model=str2func(model_name);
 
 [pNames,paramsMod]=IQMparameters(model); 
 pNames = pNames';
-paramsFixed = [paramsMod(1:find(contains(pNames,'EGP1'))-1)' EGP' Ra' INS' GLUT4m'];
+paramsFixed = [paramsMod(1:find(contains(pNames,'EGP1'))-1)' EGP Ra INS GLUT4m];
 
 [sim_muscle,sim_adipose,sim_liver,sim_ii] = simulateModel(sim_time, model, optParam, paramsFixed);
 sim_tot = sim_muscle + sim_adipose + sim_liver + sim_ii;
@@ -407,9 +434,73 @@ title('Total postprandial uptake','FontSize',20);
 legend('framed: simulation AUC [0-360 min]','filled: data AUC [0-360 min]','Location', 'northwest')
 set(gca,'Xtick',1:13,'XTickLabel',{'             muscle',[],[],'               adipose',[],[],'              liver',[],[],'               brain + kidneys',[],[],'total',[],[]});
 
-saveas(gcf, '../../results/fig5.png')
+saveas(gcf, './results/fig5.png')
+
+% C - Validation, plasma insulin and glucose
+
+load Adams.mat OGTT
+[~,I] = mink(OGTT.SEMg(2:end),1); 
+OGTT.SEMg(I+1) = mean(OGTT.SEMg(2:end)); % changing the smallest SEM to that of the mean SEM
+
+model_name='M1';
+model=str2func(model_name);
+
+[pNames,paramsMod]=IQMparameters(model); 
+[inits] = simulateSteadyStated(model, paramsMod);
+inits(28) = OGTT.Glucose(1)*1.88; % G_p
+inits(31) = OGTT.Insulin(1)*0.05; % I_p
+sim_time = [OGTT.time(1):0.1:OGTT.time(end)];
+sim = model(OGTT.time, inits, paramsMod'); 
+IpVal = sim.variablevalues(:,ismember(IQMvariables(model),'I'))'; 
+GpVal = sim.variablevalues(:,ismember(IQMvariables(model),'G'))'; 
+
+simPlot = model(sim_time, inits, paramsMod');  
+Gp = simPlot.variablevalues(:,ismember(IQMvariables(model),'G'))'; 
+Ip = simPlot.variablevalues(:,ismember(IQMvariables(model),'I'))'; 
+
+% cost
+limit_95 = chi2inv(0.95,numel(OGTT.Glucose(2:end-1))+numel(OGTT.Insulin(2:end))) % The first data point is removed since it is used as initial value
 
-%% figure 6
+cost1 = nansum((((OGTT.Glucose(2:end-1)-GpVal(2:end-1)').^2)./(OGTT.SEMg(2:end-1).^2)))
+cost2 = nansum((((OGTT.Insulin(2:end)-IpVal(2:end)').^2)./(OGTT.SEMi(2:end).^2)))
+
+cost = cost1 + cost2
+
+% plot
+colorData = [0, 0, 0]; % total
+colorSim = [0, 0.5020, 0]; 
+
+figure()
+set(0,'DefaultLineLineWidth',3)
+
+% plasma glucose
+subplot(1,2,1);
+plotErrorbar(colorData,OGTT.time(1:end-1),OGTT.Glucose(1:end-1),OGTT.SEMg(1:end-1)); hold on
+plotSim(colorSim,Gp,sim_time); 
+title('Plasma glucose','FontSize',15);
+set(gca,'FontSize',15);
+ylabel('mg/dl');
+legend('data','simulation','Location', 'northeast')
+set(gca,'linewidth',1.4)
+
+
+% plasma insulin
+subplot(1,2,2);
+plotErrorbar(colorData,OGTT.time,OGTT.Insulin,OGTT.SEMi); hold on
+plotSim(colorSim,Ip,sim_time); 
+title('Plasma Insulin','FontSize',15);
+% yticks([0:1:3])
+% ylim([0 3.5])
+ylabel('pmol/L');
+set(gca,'FontSize',15);
+set(gca,'linewidth',1.4)
+legend('data','simulation','Location', 'northeast')
+
+
+saveas(gcf, './results/GlucoseInsulin.png')
+
+
+%% fig 6 - fit to Dalla Man data
 load('EGP_ori.mat');
 load('EGP_dalla.mat');
 load('EGP_high.mat');
@@ -444,10 +535,10 @@ load('GU_low.mat');
 clear model_name
 model_name='M1';
 model=str2func(model_name);
-[pNames,paramsAll]=IQMparameters(model); 
+[pNames,paramsMod]=IQMparameters(model); 
 sim_time = [pg_dalla(1,1):0.01:pg_dalla(end,1)];
-[inits] = simulateSteadyState(model, paramsAll);
-simModel = model(sim_time, inits, paramsAll); 
+[inits] = simulateSteadyStated(model, paramsMod);
+simModel = model(sim_time, inits, paramsMod); 
 
 % plot
 figure()
@@ -513,7 +604,7 @@ plotUncertaintyD(GU_high,GU_low,sim_time)
 title('Glucose utilization')
 
 cd ..
-%------------functions---------------
+%----------------functions-----------------------
 
 function []= plotSim(color,simO,sim_time)
     plot(sim_time,simO,'color',color); 
@@ -552,7 +643,6 @@ function plotBar(color,AUCdata,AUCsim,i)
     
 end
 
-
 function [AUC_m, AUCsim_m, AUC_a, AUCsim_a,AUCsim_l,AUCsim_ii,AUCsim_tot] = getAUC(DATA,sim_time,sim_muscle,sim_adipose,sim_liver,sim_ii,sim_tot)
 
     AUC_m = trapz(DATA.time,DATA.Muscle);
diff --git a/scripts/CSVtoMATmerge.m b/scripts/CSVtoMATmerge.m
new file mode 100644
index 0000000000000000000000000000000000000000..6fca74521fa927bb94952e783ec37564c9152091
--- /dev/null
+++ b/scripts/CSVtoMATmerge.m
@@ -0,0 +1,13 @@
+
+
+% merge csvs, run from file containing results you want to merge
+% first, in powershell, write: type *csv > merged.csv 
+
+% convert to .mat
+FileListCSV = dir('*.csv');
+for iFile = 1:numel(FileListCSV)
+allParams = readtable(FileListCSV(iFile).name);
+allParams = table2array(allParams);
+save([erase(FileListCSV(iFile).name,'.csv') '.mat'],'allParams')
+end 
+
diff --git a/scripts/EstimateParametersInput.m b/scripts/EstimateParametersInput.m
new file mode 100644
index 0000000000000000000000000000000000000000..410566dd397aecd9ad0c32cae72508e38f0e6b6e
--- /dev/null
+++ b/scripts/EstimateParametersInput.m
@@ -0,0 +1,63 @@
+function [] =  EstimateParametersInput(worker,now)
+% estimates parameters, runs from file it is placed in
+ s=rng('shuffle'); %do not note remove this line
+ s=rng(s.Seed+worker); %do not note remove this line
+
+addpath('./data')
+addpath('./Models')
+addpath(genpath('./results'))
+addpath(genpath('./../MATLAB/IQMtools/'))
+
+% load data
+load ('Coppack.mat'); 
+load('EGP.mat')
+load('Ra.mat')
+load('INS.mat')
+load('GLUT4m.mat')
+
+model_name={'M4m'}; 
+
+for k=1:length(model_name)
+
+% make model
+model=str2func(model_name{k});
+% params
+[pNames,paramsMod]=IQMparameters(model); 
+
+paramsFixed = [paramsMod(1:find(contains(pNames,'EGP1'))-1)' EGP Ra INS GLUT4m]; % G_t'
+startParam = paramsMod(length(paramsFixed)+1:end)';
+nparams=length(startParam);
+optNames = pNames(length(paramsFixed)+1:end);
+
+limit=chi2inv(0.95,numel(DATA.Adipose)+numel(DATA.Muscle));
+folder=sprintf('./results/%s/%s/',model_name{k},now);
+
+if ~exist(folder,'dir')
+    mkdir(folder)
+end
+
+%% optimize
+
+options_ps=optimoptions(@particleswarm, 'Display','iter');
+options_s=optimoptions(@simulannealbnd, 'Display','iter','HybridFcn',@fmincon);
+
+ub = log(startParam.*10000);
+lb = log(startParam./10000);
+
+fid=fopen(sprintf('%s/validParams-%s-%i.csv', folder, model_name{k},s.Seed),'at');
+
+costfunc = @(p) costFun(DATA,model,p,fid,limit,paramsFixed);
+
+[optParam_ps, mincost_ps] = particleswarm(costfunc, nparams, lb, ub, options_ps);
+[optParam, mincost] = simulannealbnd(costfunc,optParam_ps, lb, ub, options_s);
+fclose(fid);
+
+% Save results
+save(sprintf('%s/opt(%.5f)-%i.mat',folder,mincost,s.Seed) ,'optParam')
+
+if numel(dir(sprintf('%s/optNames.mat',folder)))==0
+    save(sprintf('%s/optNames.mat',folder),'optNames')
+end
+    
+end
+end
\ No newline at end of file
diff --git a/scripts/Models/M0.txt b/scripts/Models/M0.txt
index abc295c1f7c516000a8a8d0e3445a201c103c752..69758184b00e78b9f949462cbd1b6d6730fb26b7 100644
--- a/scripts/Models/M0.txt
+++ b/scripts/Models/M0.txt
@@ -33,9 +33,9 @@ d/dt(S6Kp)              = v9f1-v9b1             %%27
 d/dt(S6)                = v9b2-v9f2             %%28
 d/dt(S6p)               = v9f2-v9b2             %%29                                               
 d/dt(G_p) = EGP+Ra-E-U_ii-k_1*G_p+k_2*G_t                                        
-d/dt(G_t) = (-U_id_M0)+k_1*G_p-k_2*G_t                                        
-d/dt(I_l) = (-m_1*I_l)-m_3*I_l+m_2*I_p+S                                         
-d/dt(I_p) = (-m_2*I_p)-m_4*I_p+m_1*I_l                                         
+d/dt(G_t) = (-U_id)+k_1*G_p-k_2*G_t                                          
+d/dt(I_p) = (-m_2*I_p)-m_4*I_p+m_1*I_l                                        
+d/dt(I_l) = (-m_1*I_l)-m_3*I_l+m_2*I_p+S                                        
 d/dt(Q_sto1) = -k_gri*Q_sto1                                                     
 d/dt(Q_sto2) = (-k_empt*Q_sto2)+k_gri*Q_sto1                                     
 d/dt(Q_gut) = (-k_abs*Q_gut)+k_empt*Q_sto2                                       
@@ -177,12 +177,7 @@ gamma = 0.5  %%85
 k_e1 = 0.0005  %%86                                                              
 k_e2 = 339  %%87                                                                 
 D = 78000  %%88    
-
-
-K_l0 = 225.59
-V_l0 = 2.5                                                                       
-V_lX = 0.047    
-
+   
 ********** MODEL VARIABLES
 aa = 5/2/(1-b)/D                                                                 
 cc = 5/2/d/D                                                                     
@@ -200,12 +195,10 @@ Ra = f*k_abs*Q_gut/BW
 k_empt = k_min+(k_max-k_min)/2*(tanh(aa*(Q_sto-b*D))-tanh(cc*(Q_sto-d*D))+2)     
 U_idm = V_mmax*G_t/(K_m0+G_t)
 U_idf = scaleModel*(k8*GLUT4m*G_t/34 + glut1*G_t/34 + kbf*(INS+5)*1e-3)                                                
-U_id_M0 = U_idm+U_idf                                                               
-U = U_ii+U_id_M0                                                                    
+U_id = U_idm+U_idf                                                               
+U = U_ii+U_id                                                                    
 S_po = Y+K*(EGP+Ra-E-U_ii-k_1*G_p+k_2*G_t)/V_G+S_b
 
-
-
 ********** MODEL REACTIONS                                                                                                          
 v1a      = IR*k1a*(INS+5)*1e-3
 v1basal  = k1basal*IR
diff --git a/scripts/Models/M1.txt b/scripts/Models/M1.txt
index eff9181393930c4444c7c6a339ce0a6bb0c00ac4..ea7d9d8d4106bb2cf39a965b178aeb3118a368fa 100644
--- a/scripts/Models/M1.txt
+++ b/scripts/Models/M1.txt
@@ -31,11 +31,11 @@ d/dt(GLUT4)             = -v7f+v7b              %%24
 d/dt(S6K)               = v9b1-v9f1             %%26
 d/dt(S6Kp)              = v9f1-v9b1             %%27
 d/dt(S6)                = v9b2-v9f2             %%28
-d/dt(S6p)               = v9f2-v9b2             %%29                                               
+d/dt(S6p)               = v9f2-v9b2             %%29                                           
 d/dt(G_p) = EGP+Ra-E-U_ii-k_1*G_p+k_2*G_t                                        
-d/dt(G_t) = (-U_id)+k_1*G_p-k_2*G_t                                        
+d/dt(G_t) = (-U_id)+k_1*G_p-k_2*G_t                                     
+d/dt(I_p) = (-m_2*I_p)-m_4*I_p+m_1*I_l                                                
 d/dt(I_l) = (-m_1*I_l)-m_3*I_l+m_2*I_p+S                                         
-d/dt(I_p) = (-m_2*I_p)-m_4*I_p+m_1*I_l                                         
 d/dt(Q_sto1) = -k_gri*Q_sto1                                                     
 d/dt(Q_sto2) = (-k_empt*Q_sto2)+k_gri*Q_sto1                                     
 d/dt(Q_gut) = (-k_abs*Q_gut)+k_empt*Q_sto2                                       
@@ -73,7 +73,8 @@ GLUT4(0)            = 100
 S6K(0)              = 100
 S6Kp(0)             = 0
 S6(0)               = 100
-S6p(0)              = 0                               
+S6p(0)              = 0 
+                              
 G_p(0) = 178                                                                   
 G_t(0) = 130                                                                     
 I_l(0) = 4.5                                                                 
@@ -135,7 +136,7 @@ k9b2 = 30.9967  %%42
 km9 = 5872.68  %%43                                                              
 n9 = 0.985466  %%44                                                              
 kbf = 1e+06  %%45                                                                
-scaleModel = 2.1e-06  %%46  
+nC = 2.1e-06  %%46  
                                                      
 V_G = 1.88  %%47                                                                 
 k_1 = 0.065  %%48                                                                
@@ -164,25 +165,25 @@ k_p3 = 0.009  %%70
 k_p4 = 0.0618  %%71                                                              
 k_i = 0.0079  %%72                                                               
 
-V_m0 = 2.5    %%74                                                                   
-V_mX = 0.047  %%75                                                                
-K_m0 = 225.59  %%76                                             
-V_f0 = 2.5  %%77                                                                 
-V_fX = 0.047  %%78                                                               
-K_f0 = 225.59  %%79                                                              
-p_2U = 0.0331  %%80                                                              
-part = 0.2  %%81                                                                 
-K = 2.3  %%82                                                                    
-alpha = 0.05  %%83                                                               
-beta = 0.11  %%84                                                                
-gamma = 0.5  %%85                                                                
-k_e1 = 0.0005  %%86                                                              
-k_e2 = 339  %%87                                                                 
-D = 78000  %%88    
+V_m0 = 2.5    %%73                                                                   
+V_mX = 0.047  %%74                                                                
+K_m0 = 225.59  %%75                                             
+V_f0 = 2.5  %%76                                                                 
+V_fX = 0.047  %%77                                                               
+K_f0 = 225.59  %%78                                                              
+p_2U = 0.0331  %%79                                                              
+part = 0.2  %%80                                                                 
+K = 2.3  %%81                                                                   
+alpha = 0.05  %%82                                                               
+beta = 0.11  %%83                                                                
+gamma = 0.5  %%84                                                                
+k_e1 = 0.0005  %%85                                                              
+k_e2 = 339  %%86                                                                 
+D = 78000  %%87    
 
-K_l0 = 225.59
-V_l0 = 2.5                                                                       
-V_lX = 0.047  
+K_l0 = 225.59 %%88
+V_l0 = 2.5    %%89                                                                   
+V_lX = 0.047  %%90
 
 ********** MODEL VARIABLES
 aa = 5/2/(1-b)/D                                                                 
@@ -190,7 +191,7 @@ cc = 5/2/d/D
 EGP = k_p1-k_p2*G_p-k_p3*I_d-k_p4*I_po                                           
 V_mmax = (1-part)*(V_m0+V_mX*INS)                                                
 V_fmax = part*(V_f0+V_fX*INS) 
-V_lmax = (1-part)*(V_l0+V_lX*G_t)                                                   
+V_lmax = (1-part)*(V_l0+V_lX*INS)                                                   
 Ee = k_e1*(G_p - k_e2)                                                                            
 S = gamma*I_po                                                                                                                       
 I = I_p/V_I                                                                      
@@ -201,7 +202,7 @@ Q_sto = Q_sto1+Q_sto2
 Ra = f*k_abs*Q_gut/BW                                                           
 k_empt = k_min+(k_max-k_min)/2*(tanh(aa*(Q_sto-b*D))-tanh(cc*(Q_sto-d*D))+2)     
 U_idm = 0.5*V_mmax*G_t/(K_m0+G_t)
-U_idf = 0.5*scaleModel*(k8*GLUT4m*G_t/34 + glut1*G_t/34 + kbf*(INS+5)*1e-3)                                                                                                              
+U_idf = 0.5*nC*(k8*GLUT4m*G_t/34 + glut1*G_t/34 + kbf*(INS+5)*1e-3)                                                                                                              
 U = U_ii+U_id                                                                    
 S_po = Y+K*(EGP+Ra-E-U_ii-k_1*G_p+k_2*G_t)/V_G+S_b
 U_liver = 45*U_idm/27
diff --git a/scripts/Models/M2a.txt b/scripts/Models/M2a.txt
index 8409c6ee5a86190cdd26d4ef4db84cf09a89455a..a640722cc7cf31a0eb50a2b2bb80e315a9d4bb2e 100644
--- a/scripts/Models/M2a.txt
+++ b/scripts/Models/M2a.txt
@@ -31,11 +31,11 @@ d/dt(GLUT4)             = -v7f+v7b              %%24
 d/dt(S6K)               = v9b1-v9f1             %%26
 d/dt(S6Kp)              = v9f1-v9b1             %%27
 d/dt(S6)                = v9b2-v9f2             %%28
-d/dt(S6p)               = v9f2-v9b2             %%29                                               
+d/dt(S6p)               = v9f2-v9b2             %%29                                             
 d/dt(G_p) = EGP+Ra-E-U_ii-k_1*G_p+k_2*G_t                                        
-d/dt(G_t) = (-U_id)+k_1*G_p-k_2*G_t                                        
+d/dt(G_t) = (-U_id)+k_1*G_p-k_2*G_t                                            
+d/dt(I_p) = (-m_2*I_p)-m_4*I_p+m_1*I_l                                       
 d/dt(I_l) = (-m_1*I_l)-m_3*I_l+m_2*I_p+S                                         
-d/dt(I_p) = (-m_2*I_p)-m_4*I_p+m_1*I_l                                         
 d/dt(Q_sto1) = -k_gri*Q_sto1                                                     
 d/dt(Q_sto2) = (-k_empt*Q_sto2)+k_gri*Q_sto1                                     
 d/dt(Q_gut) = (-k_abs*Q_gut)+k_empt*Q_sto2                                       
@@ -47,7 +47,6 @@ d/dt(Y) = -alpha*(Y-beta*(G-G_b))
 d/dt(INS_new) = (-k1*INS_new)+k2*(I-I_b)
 d/dt(INS_f) = (-C1_f*INS_f)+C2_f*(I-I_b)
 d/dt(INS_f_bf) = (-C1_bf*INS_f_bf)+C2_bf*(I-I_b)
-d/dt(time)     = 1
 
 
 IR(0)               = 100
diff --git a/scripts/Models/M2b.txt b/scripts/Models/M2b.txt
index de84cb5c2d5283609299b337eabc29f06e57ed12..1cf9b1df20cc8444d13df1ccf8c8148538d923e3 100644
--- a/scripts/Models/M2b.txt
+++ b/scripts/Models/M2b.txt
@@ -33,11 +33,11 @@ d/dt(S6K)               = v9b1-v9f1             %%26
 d/dt(S6Kp)              = v9f1-v9b1             %%27
 d/dt(S6)                = v9b2-v9f2             %%28
 d/dt(S6p)               = v9f2-v9b2             %%29                
-                 
+                                                      
 d/dt(G_p) = EGP+Ra-E-U_ii-k_1*G_p+k_2*G_t                                        
-d/dt(G_t) = (-U_id)+k_1*G_p-k_2*G_t-0.6*(U_liver)                                        
+d/dt(G_t) = (-U_id)+k_1*G_p-k_2*G_t-0.6*(U_liver) 
+d/dt(I_p) = (-m_2*I_p)-m_4*I_p+m_1*I_l                                           
 d/dt(I_l) = (-m_1*I_l)-m_3*I_l+m_2*I_p+S                                         
-d/dt(I_p) = (-m_2*I_p)-m_4*I_p+m_1*I_l                                         
 d/dt(Q_sto1) = -k_gri*Q_sto1                                                     
 d/dt(Q_sto2) = (-k_empt*Q_sto2)+k_gri*Q_sto1                                     
 d/dt(Q_gut) = (-k_abs*Q_gut)+k_empt*Q_sto2                                       
diff --git a/scripts/Models/M3m.txt b/scripts/Models/M3m.txt
new file mode 100644
index 0000000000000000000000000000000000000000..a644fec5a77e880a7d59a846b1218682ed514132
--- /dev/null
+++ b/scripts/Models/M3m.txt
@@ -0,0 +1,128 @@
+********** MODEL NAME
+M3m
+
+********** MODEL NOTES
+sub-model version of M3, with EGP, Ra, GLUT4m, and INS as input curves
+
+********** MODEL STATES
+          
+d/dt(G_p) = EGP+Ra-E-U_ii-k_1*G_p+k_2*G_t
+d/dt(G_t) = (-U_id)+k_1*G_p-k_2*G_t    
+d/dt(Glu_in) = p1*(V_in-V_out)-V_G6P 
+d/dt(G6P) = V_G6P-V_met   
+
+G_p(0) = 178                                                                   
+G_t(0) = 130  
+Glu_in(0) = 0
+G6P(0) = 0
+
+********** MODEL PARAMETERS
+            
+bradykinin = 1   
+kbf = 0.01
+INS_offset = 7 
+be = 3                                                            
+nC = 2.1e-06 
+k8 = 724.242                                        
+glut1 = 7042.19
+k_1 = 0.065
+k_2 = 0.079 
+pf = 34
+INS_b = 0
+p_bf = 1                                      
+bf_b = 3 
+
+EGP1 = 1
+EGP2 = 1
+EGP3 = 1
+EGP4 = 1
+EGP5 = 1
+EGP6 = 1
+EGP7 = 1
+EGP8 = 1
+EGP9 = 1
+
+Ra1 = 1
+Ra2 = 1
+Ra3 = 1
+Ra4 = 1
+Ra5 = 1
+Ra6 = 1
+Ra7 = 1
+Ra8 = 1
+Ra9 = 1
+
+INS1 = 1
+INS2 = 1
+INS3 = 1
+INS4 = 1
+INS5 = 1
+INS6 = 1
+INS7 = 1
+INS8 = 1
+INS9 = 1
+
+GLm1 = 1
+GLm2 = 1 
+GLm3 = 1 
+GLm4 = 1 
+GLm5 = 1 
+GLm6 = 1 
+GLm7 = 1 
+GLm8 = 1 
+GLm9 = 1
+ 
+V_m = 2.5 
+V_mx = 0.047 
+K_m = 225.59 
+part_l = 0.5
+K_l = 225.59
+p1 = 1 
+p2 = 2.4 
+p3 = 0.7
+p4 = 1.8 
+part_f = 14  
+k_gluin = 1300
+k_G6P = 15 
+V_G6Pmax = 90 
+U_ii = 1.23
+
+********** MODEL VARIABLES
+
+INS = interpcsIQM([0,30,60,90,120,180,240,300,360],[INS1,INS2,INS3,INS4,INS5,INS6,INS7,INS8,INS9],time)
+EGP = interpcsIQM([0,30,60,90,120,180,240,300,360],[EGP1,EGP2,EGP3,EGP4,EGP5,EGP6,EGP7,EGP8,EGP9],time)
+Ra = interpcsIQM([0,30,60,90,120,180,240,300,360],[Ra1,Ra2,Ra3,Ra4,Ra5,Ra6,Ra7,Ra8,Ra9],time)
+GLUT4m = interpcsIQM([0,30,60,90,120,180,240,300,360],[GLm1,GLm2,GLm3,GLm4,GLm5,GLm6,GLm7,GLm8,GLm9],time)
+
+E = 0
+
+bf_f = bradykinin*(be+kbf*(INS+INS_offset))
+bfe_f = (bf_f-bf_b)*(INS-INS_b)*p_bf  
+
+part_m = 1-part_l                                     
+V_mmax = part_m*(V_m+V_mx*INS)
+V_lmax = part_l*V_mmax %(V_l+V_lx*INS) 
+
+INS_fe = nC*(k8*GLUT4m/pf + glut1/pf + bfe_f)
+V_in = p4*G_t*INS_fe
+V_out = p3*Glu_in
+
+U_idm = V_mmax*G_t/(K_m+G_t)
+U_idl = V_lmax*G_t/(K_l+G_t)
+U_idf = part_f*(V_in-V_out) 
+
+U_id = U_idf + U_idm + U_idl
+
+V_G = 1.88
+G = G_p/V_G
+
+********** MODEL REACTIONS                                                                                                                                
+
+V_G6P = V_G6Pmax*Glu_in/(k_gluin+Glu_in)*1/(k_G6P+G6P)
+V_met = p2*G6P
+
+********** MODEL FUNCTIONS
+
+********** MODEL EVENTS
+
+********** MODEL MATLAB FUNCTIONS
\ No newline at end of file
diff --git a/scripts/Models/M4m.txt b/scripts/Models/M4m.txt
index 8db52262d2790d42c253544f151553b4be41cd14..2f7a84705df6f8811443a3cac5927e6f9ee7bbf7 100644
--- a/scripts/Models/M4m.txt
+++ b/scripts/Models/M4m.txt
@@ -5,11 +5,11 @@ M4m
 sub-model version of M4, with EGP, Ra, GLUT4m, and INS as input curves
 
 ********** MODEL STATES
-
+          
 d/dt(G_p) = EGP+Ra-E-U_ii-k_1*G_p+k_2*G_t
-d/dt(G_t) = (-U_id)+k_1*G_p-k_2*G_t            
+d/dt(G_t) = (-U_id)+k_1*G_p-k_2*G_t    
 d/dt(Glu_in) = p1*(V_in-V_out)-V_G6P 
-d/dt(G6P) = V_G6P-V_met     
+d/dt(G6P) = V_G6P-V_met   
 
 G_p(0) = 178                                                                   
 G_t(0) = 130  
@@ -28,6 +28,8 @@ glut1 = 7042.19
 k_1 = 0.065
 k_2 = 0.079 
 pf = 34
+INS_b = 0
+p_bf = 1
 
 EGP1 = 1
 EGP2 = 1
@@ -73,8 +75,7 @@ V_m = 2.5
 V_mx = 0.047 
 K_m = 225.59 
 part_l = 0.5
-K_l = 225.59                                      
-bf_b = 3 
+K_l = 225.59    
 p1 = 1 
 p2 = 2.4 
 p3 = 0.7
diff --git a/scripts/Models/model_diabetes.txt b/scripts/Models/model_diabetes.txt
new file mode 100644
index 0000000000000000000000000000000000000000..d71490da683913833f7d93d2d82848590b64a357
--- /dev/null
+++ b/scripts/Models/model_diabetes.txt
@@ -0,0 +1,180 @@
+********** MODEL NAME
+model_diabetes
+
+********** MODEL NOTES
+
+
+********** MODEL STATES
+
+d/dt(IR)                = -v1a-v1basal+v1r+v1g  %%1 
+d/dt(IRp)               = v1basal+v1c-v1d-v1g   %%2
+d/dt(IRins)             = v1a-v1c               %%3
+d/dt(IRip)              = v1d-v1e               %%4
+d/dt(IRi)               = v1e-v1r               %%5
+d/dt(IRS1)              = v2b+v2g-v2a-v2basal   %%6
+d/dt(IRS1p)             = v2a+v2d-v2b-v2c       %%7
+d/dt(IRS1p307)          = v2c-v2d-v2f           %%8
+d/dt(IRS1307)           = v2basal+v2f-v2g       %%9
+d/dt(X)                 = v3b-v3a               %%10
+d/dt(Xp)                = v3a-v3b               %%11
+d/dt(PKB)               = -v4a+v4b+v4h          %%12   
+d/dt(PKB308p)           = v4a-v4b-v4c           %%13
+d/dt(PKB473p)           = -v4e+v4f-v4h          %%14
+d/dt(PKB308p473p)       = v4c+v4e-v4f           %%15
+d/dt(mTORC1)            = v5b-v5a               %%16         
+d/dt(mTORC1a)           = v5a-v5b               %%17
+d/dt(mTORC2)            = -v5c+v5d              %%18
+d/dt(mTORC2a)           = v5c-v5d               %%19
+d/dt(AS160)             = v6b1-v6f1             %%20
+d/dt(AS160p)            = v6f1-v6b1             %%21
+d/dt(GLUT4m)            = v7f-v7b               %%22
+d/dt(GLUT4)             = -v7f+v7b              %%23
+d/dt(GLUCOSE)           = v8                    %%24
+d/dt(S6K)               = v9b1-v9f1             %%25
+d/dt(S6Kp)              = v9f1-v9b1             %%26
+d/dt(S6)                = v9b2-v9f2             %%27
+d/dt(S6p)               = v9f2-v9b2             %%28
+
+IR(0)               = 100
+IRp(0)              = 0
+IRins(0)            = 0          
+IRip(0)             = 0
+IRi(0)              = 0 
+IRS1(0)             = 100
+IRS1p(0)            = 0
+IRS1p307(0)         = 0
+IRS1307(0)          = 0
+X(0)                = 100
+Xp(0)               = 0
+PKB(0)              = 100
+PKB308p(0)          = 0
+PKB473p(0)          = 0
+PKB308p473p(0)      = 0
+mTORC1(0)           = 100
+mTORC1a(0)          = 0
+mTORC2(0)           = 100
+mTORC2a(0)          = 0
+AS160(0)            = 100
+AS160p(0)           = 0
+GLUT4m(0)           = 0
+GLUT4(0)            = 100
+GLUCOSE(0)          = 0
+S6K(0)              = 100
+S6Kp(0)             = 0
+S6(0)               = 100
+S6p(0)              = 0
+
+********** MODEL PARAMETERS
+
+diabetes = 0.154849954405789                    %%1
+k1a = 0.63314061884636696                       %%2
+k1basal = 0.036833798363842297                  %%3
+k1c = 0.87680517317052997                       %%4
+k1d = 31.011989181795499                        %%5                   
+k1f = 1839.5780254297499                        %%6                   
+k1g = 1944.11248585778                          %%7                   
+k1r = 0.54706126449352699                       %%8                   
+k2a = 3.22728117534023                          %%9                   
+k2c = 5758.7801540329501                        %%10                   
+k2basal = 0.042276820924940998                  %%11                   
+k2b = 3424.35105179637                          %%12                   
+k2d = 280.75302729081                           %%13                   
+k2f = 2.9131018076766999                        %%14                   
+k2g = 0.26708885317814102                       %%15                   
+k3a = 0.0013773095504517                        %%16                   
+k3b = 0.098755761256669697                      %%17                   
+k4a = 5790.1696277874598                        %%18                   
+k4b = 34.796456947358003                        %%19                   
+k4c = 4.4558117735742799                        %%20                   
+k4e = 42.8395365309255                          %%21                   
+k4f = 143.59653904756701                        %%22                   
+k4h = 0.53614481760916999                       %%23                   
+k5a1 = 1.84229972823887                         %%24                   
+k5a2 = 0.055063962982614997                     %%25                   
+k5b = 24.825982671415801                        %%26                   
+k5d = 1.0601266025276801                        %%27                   
+km5 = 2.6498800411248702                        %%28                   
+k5c = 0.085751495958875101                      %%29                   
+k6f1 = 2.6516792602958001                       %%30                   
+k6f2 = 36.934796896437597                       %%31                   
+km6 = 30.542412782576498                        %%32                   
+n6 = 2.1370656457036898                         %%33                   
+k6b = 65.184144774092204                        %%34                   
+k7f = 50.982924096637703                        %%35                   
+k7b = 2285.9651698284401                        %%36                   
+k8 = 724.24184117484799                         %%37                   
+glut1 = 7042.19095853202                        %%38                   
+k9f1 = 0.12980989054192801                      %%39                   
+k9b1 = 0.044409208098250802                     %%40                   
+k9f2 = 3.3289049832069799                       %%41                   
+k9b2 = 30.996651018025801                       %%42                   
+km9 = 5872.6843959552198                        %%43                   
+n9 = 0.98546562910023705                        %%44                   
+cure_diabetes = 1
+gluc = 0                                        %%45                   
+insulin = 0                                     %%46
+
+********** MODEL VARIABLES
+
+measuredIRp            = IRp + IRip             %%1
+measuredIRS1p          = IRS1p + IRS1p307       %%2
+measuredIRS1307        = IRS1p307 + IRS1307     %%3
+measuredPKB308p        = PKB308p+PKB308p473p    %%4              
+measuredPKB473p        = PKB473p+PKB308p473p    %%5
+measuredAS160p         = AS160p                 %%6
+measuredmTORC1a        = mTORC1a                %%7
+measuredS6Kp           = S6Kp                   %%8
+measuredS6p            = S6p                    %%9
+measuredGLUT4          = GLUT4m                 %%10      
+measuredGLUCOSE        = GLUCOSE                %%11     
+fractionIRi            = (IRi+IRip)/100         %%12
+measuredmTORC2a        = mTORC2a                %%13
+
+********** MODEL REACTIONS
+ 
+v1a      = IR*k1a*insulin
+v1basal  = k1basal*IR
+v1c      = IRins*k1c
+v1d      = IRp*k1d
+v1e      = IRip*k1f*Xp
+v1g      = IRp*k1g
+v1r      = IRi*k1r
+v2a      = IRS1*k2a*IRip
+v2b      = IRS1p*k2b
+v2c      = IRS1p*k2c*mTORC1a*diabetes
+v2d      = IRS1p307*k2d*cure_diabetes
+v2f 	 = IRS1p307*k2f
+v2basal  = IRS1*k2basal
+v2g 	 = IRS1307*k2g
+v3a      = X*k3a*IRS1p
+v3b      = Xp*k3b
+
+v5a      = mTORC1*(k5a1*PKB308p473p+k5a2*PKB308p)
+v5b      = mTORC1a*k5b
+v5c      = mTORC2*k5c*IRip
+v5d      = k5d*mTORC2a
+v4a      = k4a*PKB*IRS1p
+v4b      = k4b*PKB308p
+v4c      = k4c*PKB308p*mTORC2a
+v4e      = k4e*PKB473p*IRS1p307
+v4f      = k4f*PKB308p473p
+v4h      = k4h*PKB473p
+
+v6f1     = AS160*(k6f1*PKB308p473p+k6f2*PKB473p^n6/(km6^n6+PKB473p^n6))
+v6b1     = AS160p*k6b
+v7f      = GLUT4*k7f*AS160p
+v7b      = GLUT4m*k7b
+v8       = k8*GLUT4m*gluc + glut1*gluc 
+
+v9f1     = S6K*k9f1*mTORC1a^n9/(km9^n9+mTORC1a^n9)
+v9b1     = S6Kp*k9b1
+v9f2     = S6*k9f2*S6Kp
+v9b2     = S6p*k9b2
+
+********** MODEL FUNCTIONS
+
+
+********** MODEL EVENTS
+
+
+********** MODEL MATLAB FUNCTIONS
\ No newline at end of file
diff --git a/scripts/costFun.m b/scripts/costFun.m
index b373bc7239fe80ead1694635db3b5eb9bdacc379..0cf965e0f698774db94c8b5226496b20e623e84f 100644
--- a/scripts/costFun.m
+++ b/scripts/costFun.m
@@ -1,5 +1,5 @@
 
-function cost = costFun(DATA,model,params,fid,limit,paramsFixed)
+function cost = costFun(params,DATA,model,fid,limit,paramsFixed)
 
 try
 [sim_muscle, sim_adipose, sim_liver,sim_ii]=simulateModel(DATA.time,model,exp(params),paramsFixed);
@@ -9,7 +9,7 @@ cost2 = nansum((((DATA.Adipose'-sim_adipose).^2)./(DATA.SEM2'.^2)));
 
 cost = cost2+cost1;
 
-if trapz(DATA.time,sim_liver)<0.4*(trapz(DATA.time,sim_adipose)+trapz(DATA.time,sim_muscle)+trapz(DATA.time,sim_ii)+trapz(DATA.time,sim_liver))
+if trapz(DATA.time,sim_liver)<0.38*(trapz(DATA.time,sim_adipose)+trapz(DATA.time,sim_muscle)+trapz(DATA.time,sim_ii)+trapz(DATA.time,sim_liver))
 cost=1000+abs(1/(trapz(DATA.time,sim_liver)+1));
 end
 
@@ -17,11 +17,11 @@ if trapz(DATA.time,sim_liver)>0.55*(trapz(DATA.time,sim_adipose)+trapz(DATA.time
 cost=1000+abs(0.1*(trapz(DATA.time,sim_liver)));
 end
 
-if trapz(DATA.time,sim_ii)<0.15*(trapz(DATA.time,sim_adipose)+trapz(DATA.time,sim_muscle)+trapz(DATA.time,sim_ii)+trapz(DATA.time,sim_liver))
+if trapz(DATA.time,sim_ii)<0.16*(trapz(DATA.time,sim_adipose)+trapz(DATA.time,sim_muscle)+trapz(DATA.time,sim_ii)+trapz(DATA.time,sim_liver))
 cost=1000+abs(1/(trapz(DATA.time,sim_ii)+1));
 end
 
-if trapz(DATA.time,sim_ii)>0.28*(trapz(DATA.time,sim_adipose)+trapz(DATA.time,sim_muscle)+trapz(DATA.time,sim_ii)+trapz(DATA.time,sim_liver))
+if trapz(DATA.time,sim_ii)>0.30*(trapz(DATA.time,sim_adipose)+trapz(DATA.time,sim_muscle)+trapz(DATA.time,sim_ii)+trapz(DATA.time,sim_liver))
 cost=1000+abs(0.1*(trapz(DATA.time,sim_ii)));
 end
 
diff --git a/scripts/data/Adams.mat b/scripts/data/Adams.mat
new file mode 100644
index 0000000000000000000000000000000000000000..d971a0acdfd1cc6f65da005c2f78547448cf8711
Binary files /dev/null and b/scripts/data/Adams.mat differ
diff --git a/scripts/data/EGP.mat b/scripts/data/EGP.mat
index 5309ab6936dab12a686a704cf0bcd18b4f111a27..bfc43bd234fb622d2e6907a832a52e94133679e3 100644
Binary files a/scripts/data/EGP.mat and b/scripts/data/EGP.mat differ
diff --git a/scripts/data/GLUT4m.mat b/scripts/data/GLUT4m.mat
index 0e265f67b1f45e320d0cfb18e4b803d8f9e289e8..2de30ec9cfeda248cbec29ff69e70a8db75ff3dd 100644
Binary files a/scripts/data/GLUT4m.mat and b/scripts/data/GLUT4m.mat differ
diff --git a/scripts/data/INS.mat b/scripts/data/INS.mat
index 156ad7a25a987bd1cca26d163685230b827a25f3..ed9e22e5e8ca8dd698092012c71a9f3f66154de2 100644
Binary files a/scripts/data/INS.mat and b/scripts/data/INS.mat differ
diff --git a/scripts/data/Ra.mat b/scripts/data/Ra.mat
index 9cded26b939408df7dd73e6749f1128b504e6e1c..2d7cd7dfaf054d20a0a123ddbce55e52d62327e4 100644
Binary files a/scripts/data/Ra.mat and b/scripts/data/Ra.mat differ
diff --git a/scripts/getMaxMin.m b/scripts/getMaxMin.m
new file mode 100644
index 0000000000000000000000000000000000000000..87e19be947d986d4b8caaab5bedc080846266c97
--- /dev/null
+++ b/scripts/getMaxMin.m
@@ -0,0 +1,32 @@
+function [boundries,optParams]=getMaxMin(simTime, model, params,paramsFixed)
+simVal=inf(2,length(simTime));
+
+minVal=simVal;
+maxVal=zeros(2,length(simTime));
+optParams = nan(size(params(1,:)));
+
+    for k=1:size(params,1)
+          try
+             [sim_muscle,sim_adipose,~,~] = simulateModel(simTime, model, params(k,:),paramsFixed);
+             simVal=[sim_muscle;sim_adipose];
+          catch error
+              disp(error)
+          end
+
+            if k == 1
+                minVal=simVal;
+                maxVal=minVal;
+            end
+            if max(abs(simVal(:,:)))<inf
+                    maxVal(maxVal<simVal)=simVal(maxVal<simVal);
+                    minVal(minVal>simVal)=simVal(minVal>simVal);
+            if maxVal(2,:)>0.3
+                optParams = params(k,:);
+            end
+
+            end
+    end
+        
+boundries=table(maxVal,minVal,'VariableNames',{'Max','Min'},'RowNames',{'m','a'});
+
+end
\ No newline at end of file
diff --git a/scripts/plotBrannmark.m b/scripts/plotBrannmark.m
new file mode 100644
index 0000000000000000000000000000000000000000..abe73583ec94f9a80c71445086abb08f36a1fec2
--- /dev/null
+++ b/scripts/plotBrannmark.m
@@ -0,0 +1,621 @@
+%% Plot script
+restoredefaultpath
+addpath(genpath('./suport/SBPOP_PACKAGE_Rev_98'))
+addpath(genpath('./Models'))
+addpath(genpath('./Data'))
+
+wd = cd;
+try
+run('./suport/SBPOP_PACKAGE_Rev_98/installSBPOPpackageInitial.m')
+catch
+cd(wd);
+run('./suport/SBPOP_PACKAGE_Rev_98/installSBPOPpackage.m')
+end
+
+format shortg
+
+%% Load data
+wd = cd; % saves current directory
+cd data % Data directory
+load expdata_IR_dr.mat
+load expdata_IR_time.mat
+load expdata_IR_2p.mat
+load expdata_IR_int.mat
+load expdata_IRS1_dr.mat
+load expdata_IRS1_2p.mat
+load expdata_IRS1_time_3.mat
+load expdata_IRS1_time_30.mat
+load expdata_IRS1_time_180.mat
+load expdata_IRS1_ds.mat
+load expdata_IRS1307_dr.mat
+load expdata_IRS1307_time.mat
+load expdata_PKB308_dr.mat
+load expdata_PKB308_time.mat
+load expdata_PKB473_dr.mat
+load expdata_PKB473_time.mat
+load expdata_PKB473_2p.mat
+load expdata_PKB473_time_renorm.mat
+load expdata_AS160_dr.mat
+load expdata_AS160_time.mat
+load expdata_GLUCOSE_dr.mat
+load expdata_GLUCOSE_2p.mat
+load expdata_GLU_time.mat
+load expdata_S6K_time.mat
+load expdata_S6_time.mat
+load expdata_EC50.mat
+cd(wd) % returns to previous directory
+
+%% Load the model
+cd Models
+modelName = 'model_diabetes';
+optModel = SBmodel(strcat(modelName,'.txt'));
+tmpModel = optModel;
+SBPDmakeMEXmodel(optModel,modelName);
+cd ..
+
+%% Simulation options
+simOptions              = [];
+simOptions.method       = 'stiff';
+simOptions.maxnumsteps  = 1e6;
+simOptions.reltol       = 1e-12;
+simOptions.abstol       = 1e-9;
+simOptions.minstep      = 1e-10;
+
+[paramNames, param] = SBparameters(optModel);
+[stateNames,ODEs,initcond] = SBstates(optModel);
+[reactionNames] = SBreactions(optModel);
+figsize = [500 0 900 800];
+
+%% Defining parameter values
+
+size(param);
+tempParam = param';
+
+index_diabetes = ismember(paramNames,'diabetes')==1;
+index_ins = ismember(paramNames,'insulin')==1;
+index_gluc = ismember(paramNames,'gluc')==1;
+
+index_IR = ismember(stateNames,'IR')==1;
+index_GLUT4 = ismember(stateNames,'GLUT4')==1;
+index_cure_diabetes = ismember(paramNames,'cure_diabetes')==1;
+
+
+%% Baseline simulations
+% Parameters for Controls
+param_n = tempParam;                                % Parameter values
+param_n(index_diabetes)     = 1;                    % No diabetes feedback
+
+% Parameters for Diabetics
+param_d = tempParam;                                % Parameter values for diabetes
+param_d(index_diabetes) = 15.5/100;                 % Diabetes feedback 15.5 % of controls
+param_d(index_cure_diabetes) = 1;                   % Deacrese the dephosphorylation
+initcond_0_d = initcond;                            % Initial conditions
+initcond_0_d(index_IR) = 55;                        % Diabetes IR amount 55 % of controls
+initcond_0_d(index_GLUT4) = 50;                     % Diabetes GLUT4 amount 50 % of controls
+
+% Baseline simulations
+simdata_0_n = model_diabetes(0:50:500, initcond, param_n, simOptions);      % baseline simulation controls
+simdata_0_d = model_diabetes(0:50:500, initcond_0_d, param_d, simOptions);  % baseline simulation diabetes
+ 
+%% Insulin stimulation simulations
+ins_conc = [0.01 0.03 0.1 0.3 1 10 100];
+ins_conc_highres = interp1([1:1:7],ins_conc,[1:0.1:7]);
+
+% Controls
+initcond_n = simdata_0_n.statevalues(end,:);    % using the steady state values from the baseline-simulation
+simdata_dr_n1a = model_diabetes(0:0.01:15, initcond_n, [param_n(1:end-1) ins_conc(1)], simOptions);   % 15 min simulation with 0.01 nM insulin
+simdata_dr_n1b = model_diabetes(0:0.01:15, initcond_n, [param_n(1:end-1) ins_conc(2)], simOptions);   % 15 min simulation with 0.03 nM insulin
+simdata_dr_n2 = model_diabetes(0:0.01:15, initcond_n, [param_n(1:end-1) ins_conc(3)], simOptions);    % 15 min simulation with 0.1 nM insulin
+simdata_dr_n3 = model_diabetes(0:0.01:15, initcond_n, [param_n(1:end-1) ins_conc(4)], simOptions);    % 15 min simulation with 0.3 nM insulin
+simdata_dr_n4 = model_diabetes(0:0.01:15, initcond_n, [param_n(1:end-1) ins_conc(5)], simOptions);    % 15 min simulation with 1 nM insulin
+simdata_60_n = model_diabetes(0:0.01:60, initcond_n, [param_n(1:end-1) ins_conc(6)], simOptions);     % 60 min simulation with 10 nM insulin
+simdata_180_n = model_diabetes(0:0.01:30, initcond_n, [param_n(1:end-1) ins_conc(7)], simOptions);   % 180 min simulation with 100 nM insulin
+simdata_ds1_n = model_diabetes(0:0.01:4, initcond_n, [param_n(1:end-1) 1.2], simOptions);       % 4 min simulation with 1.2 nM insulin for double step data
+initcond2_n = simdata_ds1_n.statevalues(end,:);                                 % using the statevalues from the ds1 simulation as initial conditions
+simdata_ds2_n = model_diabetes(0:0.01:4, initcond2_n, [param_n(1:end-1) 10], simOptions);        % 4 min simulation with 10 nM insulin for double step data
+
+% Diabetes
+initcond_d = simdata_0_d.statevalues(end,:);                                % using the steady state values from the baseline-simulation
+simdata_dr_d1a = model_diabetes(0:0.01:15, initcond_d, [param_d(1:end-1) ins_conc(1)], simOptions);   % 15 min simulation with 0.01 nM insulin   
+simdata_dr_d1b = model_diabetes(0:0.01:15, initcond_d, [param_d(1:end-1) ins_conc(2)], simOptions);   % 15 min simulation with 0.03 nM insulin
+simdata_dr_d2 = model_diabetes(0:0.01:15, initcond_d, [param_d(1:end-1) ins_conc(3)], simOptions);    % 15 min simulation with 0.1 nM insulin
+simdata_dr_d3 = model_diabetes(0:0.01:15, initcond_d, [param_d(1:end-1) ins_conc(4)], simOptions);    % 15 min simulation with 0.3 nM insulin
+simdata_dr_d4 = model_diabetes(0:0.01:15, initcond_d, [param_d(1:end-1) ins_conc(5)], simOptions);    % 15 min simulation with 1 nM insulin
+simdata_60_d = model_diabetes(0:0.01:60, initcond_d, [param_d(1:end-1) ins_conc(6)], simOptions);     % 60 min simulation with 10 nM insulin
+simdata_180_d = model_diabetes(0:0.01:30, initcond_d, [param_d(1:end-1) ins_conc(7)], simOptions);   % 180 min simulation with 100 nM insulin
+simdata_ds1_d = model_diabetes(0:0.01:4, initcond_d, [param_d(1:end-1) 1.2], simOptions);       % 4 min simulation with 1.2 nM insulin for double step data
+initcond2_d = simdata_ds1_d.statevalues(end,:);                                 % using the statevalues from the ds1 simulation as initial conditions
+simdata_ds2_d = model_diabetes(0:0.01:4, initcond2_d, [param_d(1:end-1) 10], simOptions);        % 4 min simulation with 10 nM insulin for double step data
+
+dose_n_highres = nan(length(ins_conc_highres)+1,13);
+dose_n_highres(1,:) = simdata_0_n.variablevalues(end,:);
+
+dose_d_highres = nan(length(ins_conc_highres)+1,13);
+dose_d_highres(1,:) = simdata_0_d.variablevalues(end,:);
+
+for k = 1:length(ins_conc_highres)
+simdata_n = model_diabetes(0:0.01:30, initcond_n, [param_n(1:end-1) ins_conc_highres(k)], simOptions);   % 180 min simulation with k nM insulin
+dose_n_highres(k+1,:) = simdata_n.variablevalues(1001,:);
+end
+
+for k = 1:length(ins_conc_highres)
+simdata_d = model_diabetes(0:0.01:30, initcond_d, [param_d(1:end-1) ins_conc_highres(k)], simOptions);   % 180 min simulation with k nM insulin
+dose_d_highres(k+1,:) = simdata_d.variablevalues(1001,:);
+end
+
+%% Glucose stimulation simulations
+% Controls
+param_n(index_gluc)=0.05; % Stimulating with 0.05 mM glucose
+simdata_dr_gluc_n0 = model_diabetes(0:0.01:30, initcond_n, [param_n(1:end-1) 0], simOptions);     % initial conditions from baseline simulation, 30 min simulation without insulin
+initcond_n1a = simdata_dr_n1a.statevalues(end,:);                                   % initial conditions from 0.01 nM insulin simulation (dr_n1a)
+simdata_dr_gluc_n1a = model_diabetes(0:0.01:30, initcond_n1a, [param_n(1:end-1) ins_conc(1)], simOptions);  % 30 min simulation with 0.01 nM insulin
+initcond_n1b = simdata_dr_n1b.statevalues(end,:);                                   % initial conditions from 0.03 nM insulin simulation (dr_n1b)
+simdata_dr_gluc_n1b = model_diabetes(0:0.01:30, initcond_n1b, [param_n(1:end-1) ins_conc(2)], simOptions);  % 30 min simulation with 0.03 nM insulin 
+initcond_n2 = simdata_dr_n2.statevalues(end,:);                                     % initial conditions from 0.1 nM insulin simulation (dr_n2)
+simdata_dr_gluc_n2 = model_diabetes(0:0.01:30, initcond_n2, [param_n(1:end-1) ins_conc(3)], simOptions);    % 30 min simulation with 0.1 nM insulin 
+initcond_n3 = simdata_dr_n3.statevalues(end,:);                                     % initial conditions from 0.3 nM insulin simulation (dr_n3)
+simdata_dr_gluc_n3 = model_diabetes(0:0.01:30, initcond_n3, [param_n(1:end-1) ins_conc(4)], simOptions);    % 30 min simulation with 0.3 nM insulin 
+initcond_n4 = simdata_dr_n4.statevalues(end,:);                                     % initial conditions from .01 nM insulin simulation (dr_n4)
+simdata_dr_gluc_n4 = model_diabetes(0:0.01:30, initcond_n4, [param_n(1:end-1) ins_conc(5)], simOptions);    % 30 min simulation with 1 nM insulin 
+initcond_n5 = simdata_60_n.statevalues(1501,:);                                      % initial conditions from 10 nM insulin simulation (60_n)
+simdata_dr_gluc_n5 = model_diabetes(0:0.01:30, initcond_n5, [param_n(1:end-1) ins_conc(6)], simOptions);    % 30 min simulation with 10 nM insulin 
+initcond_n6 = simdata_180_n.statevalues(1501,:);                                     % initial conditions from 100 nM insulin simulation (180_n)
+simdata_dr_gluc_n6 = model_diabetes(0:0.01:30, initcond_n6, [param_n(1:end-1) ins_conc(7)], simOptions);    % 30 min simulation with 100 nM insulin 
+
+% Diabetes
+param_d(index_gluc)=0.05; % Stimulating with 0.05 mM glucose
+simdata_dr_gluc_d0 = model_diabetes(0:0.01:30, initcond_d, [param_d(1:end-1) 0], simOptions);     % initial conditions from baseline simulation, 30 min simulation without insulin
+initcond_d1a = simdata_dr_d1a.statevalues(end,:);                                   % initial conditions from 0.01 nM insulin simulation (dr_d1a)
+simdata_dr_gluc_d1a = model_diabetes(0:0.01:30, initcond_d1a, [param_d(1:end-1) ins_conc(1)], simOptions);  % 30 min simulation with 0.01 nM insulin 
+initcond_d1b = simdata_dr_d1b.statevalues(end,:);                                   % initial conditions from 0.03 nM insulin simulation (dr_d1b)
+simdata_dr_gluc_d1b = model_diabetes(0:0.01:30, initcond_d1b, [param_d(1:end-1) ins_conc(2)], simOptions);  % 30 min simulation with 0.03 nM insulin 
+initcond_d2 = simdata_dr_d2.statevalues(end,:);                                     % initial conditions from 0.1 nM insulin simulation (dr_d2)
+simdata_dr_gluc_d2 = model_diabetes(0:0.01:30, initcond_d2, [param_d(1:end-1) ins_conc(3)], simOptions);    % 30 min simulation with 0.1 nM insulin 
+initcond_d3 = simdata_dr_d3.statevalues(end,:);                                     % initial conditions from 0.3 nM insulin simulation (dr_d3)
+simdata_dr_gluc_d3 = model_diabetes(0:0.01:30, initcond_d3, [param_d(1:end-1) ins_conc(4)], simOptions);    % 30 min simulation with 0.3 nM insulin 
+initcond_d4 = simdata_dr_d4.statevalues(end,:);                                     % initial conditions from .01 nM insulin simulation (dr_d4)
+simdata_dr_gluc_d4 = model_diabetes(0:0.01:30, initcond_d4, [param_d(1:end-1) ins_conc(5)], simOptions);    % 30 min simulation with 1 nM insulin 
+initcond_d5 = simdata_60_d.statevalues(1501,:);                                      % initial conditions from 10 nM insulin simulation (60_d)
+simdata_dr_gluc_d5 = model_diabetes(0:0.01:30, initcond_d5, [param_d(1:end-1) ins_conc(6)], simOptions);    % 30 min simulation with 10 nM insulin 
+initcond_d6 = simdata_180_d.statevalues(1501,:);                                     % initial conditions from 100 nM insulin simulation (180_d)
+simdata_dr_gluc_d6 = model_diabetes(0:0.01:30, initcond_d6, [param_d(1:end-1) ins_conc(7)], simOptions);    % 30 min simulation with 100 nM insulin 
+
+
+%% ExpData and SimData normalisations
+
+% Dose response
+% Collecting simulation data for variable values
+% Controls
+dose_n = [simdata_0_n.variablevalues(end,:);simdata_dr_n1a.variablevalues(1001,:); simdata_dr_n1b.variablevalues(1001,:); simdata_dr_n2.variablevalues(1001,:); simdata_dr_n3.variablevalues(1001,:); simdata_dr_n4.variablevalues(1001,:); simdata_60_n.variablevalues(1001,:); simdata_180_n.variablevalues(1001,:)];
+% Diabetes
+dose_d = [simdata_0_d.variablevalues(end,:);simdata_dr_d1a.variablevalues(1001,:); simdata_dr_d1b.variablevalues(1001,:); simdata_dr_d2.variablevalues(1001,:); simdata_dr_d3.variablevalues(1001,:); simdata_dr_d4.variablevalues(1001,:); simdata_60_d.variablevalues(1001,:); simdata_180_d.variablevalues(1001,:)];
+
+% Saving dose response data for IRp + IRip (variablevalue 1)
+%                               IRS1p (variablevalue 2)
+%                               IRS1307 (variablevalue 3)
+%                               PKB308 (variablevalue 4)
+%                               PKB473 (variablevalue 5)
+%                               AS160 (variablevalue 6)
+%                               S6 (variablevalue 9)
+% The doseresponse curves are normalized to 100 at maximum value
+% Baselines removed since data was treated that way
+% All dose response curves in this loop have insulin concentrations:
+% 1E-11,1E-10,3E-10,1E-9,1E-8,1E-7
+
+dr_n = zeros(length(ins_conc_highres),8);
+dr_d = zeros(length(ins_conc_highres),8);
+
+dr_variables = [1:6 9 7];
+
+%Controls
+for n = 1:8 
+dr_n(:,n) = [dose_n_highres(1,dr_variables(n)); dose_n_highres(3:end,dr_variables(n))];
+dr_n(:,n) = dr_n(:,n) - simdata_0_n.variablevalues(end,dr_variables(n)); %baseline removal
+dr_n(:,n) = dr_n(:,n)*100/max(dr_n(:,n));
+end
+
+%Diabetes
+for n = 1:8
+dr_d(:,n) = [dose_d_highres(1,dr_variables(n)); dose_d_highres(3:end,dr_variables(n))];
+dr_d(:,n) = dr_d(:,n) - simdata_0_d.variablevalues(end,dr_variables(n)); %baseline removal
+dr_d(:,n) = dr_d(:,n)*100/max(dr_d(:,n));
+end
+
+% Saving dose response data for GLUCOSE (variablevalue 11)
+% The doseresponse curve is normalized to 100 at its maximum value
+% Insulin concentrations: 1E-11,3E-11,1E-10,3E-10,1E-9,1E-8,1E-7
+% 
+% Collecting simulation data for glucose after insulin and glucose stimulation
+GLUCOSE_dr_n1 = [simdata_dr_gluc_n0.variablevalues(end,11) simdata_dr_gluc_n1a.variablevalues(end,11) simdata_dr_gluc_n1b.variablevalues(end,11) simdata_dr_gluc_n2.variablevalues(end,11) simdata_dr_gluc_n3.variablevalues(end,11) simdata_dr_gluc_n4.variablevalues(end,11) simdata_dr_gluc_n5.variablevalues(end,11) simdata_dr_gluc_n6.variablevalues(end,11)];
+GLUCOSE_dr_d1 = [simdata_dr_gluc_d0.variablevalues(end,11) simdata_dr_gluc_d1a.variablevalues(end,11) simdata_dr_gluc_d1b.variablevalues(end,11) simdata_dr_gluc_d2.variablevalues(end,11) simdata_dr_gluc_d3.variablevalues(end,11) simdata_dr_gluc_d4.variablevalues(end,11) simdata_dr_gluc_d5.variablevalues(end,11) simdata_dr_gluc_d6.variablevalues(end,11)];
+
+GLUCOSE_dr_n = GLUCOSE_dr_n1 - simdata_dr_gluc_n0.variablevalues(end,11);
+GLUCOSE_dr_n = GLUCOSE_dr_n*100/max(GLUCOSE_dr_n);
+GLUCOSE_dr_d = GLUCOSE_dr_d1 - simdata_dr_gluc_d0.variablevalues(end,11);
+GLUCOSE_dr_d = GLUCOSE_dr_d*100/max(GLUCOSE_dr_d);
+
+% Time curves
+
+% IRp + IRip
+% IR time has baseline subtracted and is normalised to max 100
+% 2p IR data is not normalised
+% Here, the data is combined to a 30 min dataset with baseline
+% Combination: Multiply expdata_time with expdata_2p without baseline divided by expdata_time at 10 min => expdata_time(1) = 0, expdata_time(9)=1. 
+%              Then add baseline from expdata_2p.
+comb_expdata_IR_time.response = expdata_IR_time.response*(expdata_IR_2p.response_n(2)-expdata_IR_2p.response_n(1))/expdata_IR_time.response(9); % normalising the 30 min data to the 10 min 2p data point
+comb_expdata_IR_time.response = comb_expdata_IR_time.response + expdata_IR_2p.response_n(1); % adding the baseline from the 2p data
+comb_expdata_IR_time.sem = expdata_IR_time.sem*(expdata_IR_2p.response_n(2)-expdata_IR_2p.response_n(1))/expdata_IR_time.response(9);
+IR_timep_n = simdata_180_n.variablevalues(1:3001,1);
+IR_time_n = IR_timep_n(round(expdata_IR_time.time*100)+1);
+IR_timep_d = simdata_180_d.variablevalues(1:3001,1);
+IR_time_d = IR_timep_d(round(expdata_IR_time.time*100)+1);
+scaleIR = lscov(IR_time_n,comb_expdata_IR_time.response); 
+
+% IRS1 
+% IRS1 time has baseline subtracted and is normalised to max 100
+% 2p IRS1 data is not normalised
+% Here, the data is combined to a 30 min dataset with baseline
+% Combination: Multiply expdata_time with expdata_2p without baseline divided by expdata_time at 10 min => expdata_time(1) = 0, expdata_time(9)=1. 
+%              Then add baseline from expdata_2p.
+comb_expdata_IRS1_time.response = expdata_IRS1_time_30.response*(expdata_IRS1_2p.response_n(2)-expdata_IRS1_2p.response_n(1))/expdata_IRS1_time_30.response(9); % normalising the 30 min data to the 10 min 2p data point
+comb_expdata_IRS1_time.response = comb_expdata_IRS1_time.response + expdata_IRS1_2p.response_n(1); % adding the baseline from the 2p data
+comb_expdata_IRS1_time.sem = expdata_IRS1_time_30.sem*(expdata_IRS1_2p.response_n(2)-expdata_IRS1_2p.response_n(1))/expdata_IRS1_time_30.response(9);
+IRS1_timep_n = simdata_180_n.variablevalues(1:3001,2);
+IRS1_time_n = IRS1_timep_n(round(expdata_IRS1_time_30.time*100)+1);
+IRS1_timep_d = simdata_180_d.variablevalues(1:3001,2);
+IRS1_time_d = IRS1_timep_d(round(expdata_IRS1_time_30.time*100)+1);
+scaleIRS1 = lscov(IRS1_time_n,comb_expdata_IRS1_time.response); 
+
+% IRS1p 10nm insulin 3 min 
+% baseline not subtracted
+% data normalised to max 100, simdata scaled with lscov
+IRS1_time3p = simdata_60_n.variablevalues(1:301,2);
+IRS1_time3 = IRS1_time3p(round(expdata_IRS1_time_3.time.*100)+1);
+scaleIRS1_10 = lscov(IRS1_time3,expdata_IRS1_time_3.response);
+
+% IRS1p double step (1.2 + 10 nm)
+% baseline not subtracted
+% simdata scaled with lscov
+IRS1_dsp = [simdata_ds1_n.variablevalues(:,2); simdata_ds2_n.variablevalues(:,2)];
+IRS1_ds = IRS1_dsp(round(expdata_IRS1_ds.time.*100)+1); 
+scaleIRS1ds = lscov(IRS1_ds,expdata_IRS1_ds.response);
+
+% IRS1307
+% 10nm insulin 60min normal (n) and diabetes (d)
+% baseline not subtracted, simulation scaled with lscov
+IRS1307_time_n = simdata_60_n.variablevalues(:,3);
+IRS1307_time_n = IRS1307_time_n(round(expdata_IRS1307_time.time*100)+1); %choosing correct values
+IRS1307_time_d = simdata_60_d.variablevalues(:,3);
+IRS1307_time_d = IRS1307_time_d(round(expdata_IRS1307_time.time*100)+1);
+scaleIRS1307 = lscov(IRS1307_time_n,expdata_IRS1307_time.response_n); %scale parameter for IRS1307
+
+% PKB308 
+% 10nm insulin 60min normal (n) and diabetes (d)
+% baseline not subtracted, simulation scaled with lscov
+PKB308_time_n = simdata_60_n.variablevalues(:,4);
+PKB308_time_n = PKB308_time_n(round(expdata_PKB308_time.time*100+1));
+PKB308_time_d = simdata_60_d.variablevalues(:,4);
+PKB308_time_d = PKB308_time_d(round(expdata_PKB308_time.time*100+1));
+scalePKB308 = lscov(PKB308_time_n,expdata_PKB308_time.response_n);
+
+% PKB473
+% 10nm insulin 60min normal (n) and diabetes (d)
+% baseline not subtracted, ExpData normalised to max 100. Normalised to 10 point in 2p ExpData to get relationship between n and d
+% simulation scaled with lscov
+% Combination: Multiply expdata_time with expdata_2p divided by expdata_time at 10 min => expdata_time(9)=1. 
+comb_expdata_PKB473_time.response_n = expdata_PKB473_time_renorm.response_n*expdata_PKB473_2p.response_n(2); % normalising the 60 min data to the 10 min 2p data point
+comb_expdata_PKB473_time.sem_n = expdata_PKB473_time_renorm.sem_n*expdata_PKB473_2p.response_n(2);
+comb_expdata_PKB473_time.response_d = expdata_PKB473_time_renorm.response_d*expdata_PKB473_2p.response_d(2); % normalising the 60 min data to the 10 min 2p data point
+comb_expdata_PKB473_time.sem_d = expdata_PKB473_time_renorm.sem_d*expdata_PKB473_2p.response_d(2);
+
+PKB473_time_n = simdata_60_n.variablevalues(:,5);
+PKB473_time_n = PKB473_time_n(round(expdata_PKB473_time_renorm.time*100+1));
+PKB473_time_d = simdata_60_d.variablevalues(:,5);
+PKB473_time_d = PKB473_time_d(round(expdata_PKB473_time_renorm.time*100+1));
+scalePKB473 = lscov(PKB473_time_n,comb_expdata_PKB473_time.response_n);
+
+% AS160
+% 10nm insulin 60min normal (n) and diabetes (d)
+% baseline not subtracted, simulation scaled with lscov
+AS160_time_n = simdata_60_n.variablevalues(:,6);
+AS160_time_n = AS160_time_n(round(expdata_AS160_time.time*100+1));
+AS160_time_d = simdata_60_d.variablevalues(:,6);
+AS160_time_d = AS160_time_d(round(expdata_AS160_time.time*100+1));
+scaleAS160 = lscov(AS160_time_n,expdata_AS160_time.response_n);
+
+% Glucose uptake
+% 0 and 100 nM insulin 15 min followed by 0.05 nM glucose 30 min
+GLUCOSE_n = [simdata_dr_gluc_n0.variablevalues(end,11); simdata_dr_gluc_n6.variablevalues(end,11)];
+GLUCOSE_d = [simdata_dr_gluc_d0.variablevalues(end,11); simdata_dr_gluc_d6.variablevalues(end,11)];
+scaleGLUCOSE = lscov(GLUCOSE_n,expdata_GLUCOSE_2p.response_n);
+
+% S6K 
+% 10nm insulin 60min normal (n) and diabetes (d)
+% baseline not subtracted, simulation scaled with lscov
+S6K_time_n = simdata_60_n.variablevalues(:,8);
+S6K_time_n = S6K_time_n(round(expdata_S6K_time.time*100)+1);
+S6K_time_d = simdata_60_d.variablevalues(:,8);
+S6K_time_d = S6K_time_d(round(expdata_S6K_time.time*100)+1);
+scaleS6K = lscov(S6K_time_n, expdata_S6K_time.response_n);
+
+% S6
+% 10nm insulin 60min normal (n) and diabetes (d)
+% baseline not subtracted, simulation scaled with lscov
+S6_time_n = simdata_60_n.variablevalues(:,9);
+S6_time_n = S6_time_n(round(expdata_S6_time.time*100)+1);
+S6_time_d = simdata_60_d.variablevalues(:,9);
+S6_time_d = S6_time_d(round(expdata_S6_time.time*100)+1);
+scaleS6 = lscov(S6_time_n, expdata_S6_time.response_n);
+
+%% Plot
+time10 = 0:0.01:10;
+time15 = 0:0.01:15;
+time30 = 0:0.01:30;
+time60 = 0:0.01:60;
+conc = 1e-9*[1e-3 ins_conc([1 3:end])];
+conc_highres = interp1([1:1:7],conc,[1:0.1:7]);
+
+opengl hardware
+set(0,'DefaultLineLineSmoothing','on');
+set(0,'DefaultPatchLineSmoothing','on');
+opengl('OpenGLLineSmoothingBug',1);
+
+set(figure(11),'Position', figsize);
+figure(11)
+% Dose response
+subplot(5,4,1)
+semilogx(conc_highres, dr_n(:,1)','b-', 'Linewidth',2)
+hold on
+plot(conc_highres, dr_d(:,1)','r-', 'Linewidth',2)
+errorbar(conc,expdata_IR_dr.response_n,expdata_IR_dr.sem_n,'bo','MarkerFaceColor','b','MarkerSize',6)
+errorbar(conc,expdata_IR_dr.response_d,expdata_IR_dr.sem_d,'ro','MarkerFaceColor','r','MarkerSize',6)
+axis([1e-12 1e-7 0 100])
+set(gca,'YTick',[0 50 100],'XTick',[1e-11 1e-10 1e-9 1e-8 1e-7],'FontSize',8)
+box off
+xlabel('[Insulin], M','FontSize',8)
+ylabel('IR-YP, % of max','FontSize',8)
+text(2e-12,95,'IR-YP','FontSize',9)
+
+subplot(5,4,2)
+errorbar(expdata_IR_time.time,comb_expdata_IR_time.response,comb_expdata_IR_time.sem,'bo','MarkerFaceColor','b','MarkerSize',6)
+hold on
+errorbar([0 10],expdata_IR_2p.response_d,expdata_IR_2p.sem_d,'ro','MarkerFaceColor','r','MarkerSize',6)
+plot(time30,simdata_180_n.variablevalues(1:3001,1)*scaleIR,'b-', 'Linewidth',2)
+plot(time30,simdata_180_d.variablevalues(1:3001,1)*scaleIR,'r-', 'Linewidth',2)
+axis([0 30 0 2.5])
+set(gca,'YTick',[0 1 2 3 4 5],'XTick',[0 10 20 30],'FontSize',8)
+box off
+xlabel('Time, min','FontSize',8)
+ylabel('IR-YP, a.u.','FontSize',8)
+text(15,0.95*2.5,'IR-YP','FontSize',9)
+
+subplot(5,4,3)
+errorbar(expdata_IR_int.time,expdata_IR_int.response, expdata_IR_int.sem,'bo','MarkerFaceColor','b','MarkerSize',6)
+hold on
+plot(time30,simdata_60_n.variablevalues(1:3001,12)*100,'b-', 'Linewidth',2)
+plot(time30,simdata_60_d.variablevalues(1:3001,12)*100,'r-', 'Linewidth',2)
+axis([0 30 0 4])
+set(gca,'YTick',[0 1 2 3 4 5],'XTick',[0 10 20 30],'FontSize',8)
+box off
+xlabel('Time, min','FontSize',8)
+ylabel('Internalized IR, a.u.','FontSize',8)
+text(1.5,0.95*4,'Internalized IR','FontSize',9)
+
+subplot(5,4,4)
+errorbar(expdata_IRS1_ds.time,expdata_IRS1_ds.response,expdata_IRS1_ds.sem,'bo','MarkerFaceColor','b','MarkerSize',6)
+hold on
+plot([simdata_ds1_n.time 4+simdata_ds2_n.time]',scaleIRS1ds*[simdata_ds1_n.variablevalues(:,2); simdata_ds2_n.variablevalues(:,2)],'b-', 'Linewidth',2)
+plot([simdata_ds1_d.time 4+simdata_ds2_d.time]',scaleIRS1ds*[simdata_ds1_d.variablevalues(:,2); simdata_ds2_d.variablevalues(:,2)],'r-', 'Linewidth',2)
+axis([0 8 0 125])
+set(gca,'YTick',[0 50 100],'XTick',[0 4 8],'FontSize',8)
+box off
+xlabel('Time, min','FontSize',8)
+ylabel('IRS1-YP, a.u.','FontSize',8)
+text(4,0.95*125,'IRS1-YP','FontSize',9)
+
+subplot(5,4,5)
+semilogx(conc_highres, dr_n(:,2)','b-', 'Linewidth',2)
+hold on
+plot(conc_highres, dr_d(:,2)','r-', 'Linewidth',2)
+errorbar(conc,expdata_IRS1_dr.response_n,expdata_IRS1_dr.sem_n,'bo','MarkerFaceColor','b','MarkerSize',6)
+errorbar(conc,expdata_IRS1_dr.response_d,expdata_IRS1_dr.sem_d,'ro','MarkerFaceColor','r','MarkerSize',6)
+axis([1e-12 1e-7 0 100])
+set(gca,'YTick',[0 50 100],'XTick',[1e-11 1e-10 1e-9 1e-8 1e-7],'FontSize',8)
+box off
+xlabel('[Insulin], M','FontSize',8)
+ylabel('IRS1-YP, % of max','FontSize',8)
+text(2e-12,95,'IRS1-YP','FontSize',9)
+
+subplot(5,4,6)
+errorbar(expdata_IRS1_time_30.time,comb_expdata_IRS1_time.response,comb_expdata_IRS1_time.sem,'bo','MarkerFaceColor','b','MarkerSize',6)
+hold on
+errorbar([0 10],expdata_IRS1_2p.response_d,expdata_IRS1_2p.sem_d,'ro','MarkerFaceColor','r','MarkerSize',6)
+plot(time30,scaleIRS1*simdata_180_n.variablevalues(1:3001,2),'b-', 'Linewidth',2)
+plot(time30,scaleIRS1*simdata_180_d.variablevalues(1:3001,2),'r-', 'Linewidth',2)
+axis([0 30 0 5])
+set(gca,'YTick',[0 1 2 3 4 5],'XTick',[0 10 20 30],'FontSize',8)
+box off
+xlabel('Time, min','FontSize',8)
+ylabel('IRS1-YP, a.u.','FontSize',8)
+text(15,0.95*5,'IRS1-YP','FontSize',9)
+
+subplot(5,4,7)
+semilogx(conc_highres, dr_n(:,3)','b-', 'Linewidth',2)
+hold on
+plot(conc_highres, dr_d(:,3)','r-', 'Linewidth',2)
+errorbar(conc,expdata_IRS1307_dr.response_n,expdata_IRS1307_dr.sem_n,'bo','MarkerFaceColor','b','MarkerSize',6)
+errorbar(conc,expdata_IRS1307_dr.response_d,expdata_IRS1307_dr.sem_d,'ro','MarkerFaceColor','r','MarkerSize',6)
+axis([1e-12 1e-7 0 100])
+set(gca,'YTick',[0 50 100],'XTick',[1e-11 1e-10 1e-9 1e-8 1e-7],'FontSize',8)
+box off
+xlabel('[Insulin], M','FontSize',8)
+ylabel('IRS1-S307P, % of max','FontSize',8)
+text(2e-12,95,'IRS1-S307P','FontSize',9)
+
+subplot(5,4,8)
+plot(time30,scaleIRS1307*simdata_60_n.variablevalues(1:3001,3),'b-', 'Linewidth',2)
+hold on
+plot(time30,scaleIRS1307*simdata_60_d.variablevalues(1:3001,3),'r-', 'Linewidth',2)
+errorbar(expdata_IRS1307_time.time,expdata_IRS1307_time.response_n,expdata_IRS1307_time.sem_n,'bo','MarkerFaceColor','b','MarkerSize',6)
+errorbar(expdata_IRS1307_time.time,expdata_IRS1307_time.response_d,expdata_IRS1307_time.sem_d,'ro','MarkerFaceColor','r','MarkerSize',6)
+axis([0 30 0 5.5])
+set(gca,'YTick',[0 1 2 3 4 5],'XTick',[0 10 20 30],'FontSize',8);
+box off
+xlabel('Time, min','FontSize',8)
+ylabel('IRS1-S307P, % of max','FontSize',8)
+text(15,0.95*5.5,'IRS1-S307P','FontSize',9)
+
+subplot(5,4,9)
+semilogx(conc_highres, dr_n(:,4)', 'b-', 'Linewidth',2)
+hold on
+plot(conc_highres, dr_d(:,4)', 'r-', 'Linewidth',2)
+errorbar(conc, expdata_PKB308_dr.response_n,expdata_PKB308_dr.sem_n,'bo','MarkerFaceColor','b','MarkerSize',6)
+errorbar(conc, expdata_PKB308_dr.response_d,expdata_PKB308_dr.sem_d,'ro','MarkerFaceColor','r','MarkerSize',6)
+axis([1e-12 1e-7 0 100])
+set(gca,'YTick',[0 50 100],'XTick',[1e-11 1e-10 1e-9 1e-8 1e-7],'FontSize',8);
+box off
+xlabel('[Insulin], M','FontSize',8)
+ylabel('PKB-T308P, % of max','FontSize',8)
+text(2e-12,95,'PKB-T308P','FontSize',9)
+
+subplot(5,4,10)
+plot(time30,scalePKB308.*simdata_60_n.variablevalues(1:3001,4),'b-', 'Linewidth',2)
+hold on
+plot(time30,scalePKB308.*simdata_60_d.variablevalues(1:3001,4),'r-', 'Linewidth',2)
+errorbar(expdata_PKB308_time.time,expdata_PKB308_time.response_n,expdata_PKB308_time.sem_n,'bo','MarkerFaceColor','b','MarkerSize',6)
+errorbar(expdata_PKB308_time.time,expdata_PKB308_time.response_d,expdata_PKB308_time.sem_d,'ro','MarkerFaceColor','r','MarkerSize',6)
+axis([0 30 0 3.5])
+set(gca,'YTick',[0 1 2 3 4 5],'XTick',[0 10 20 30],'FontSize',8);
+box off
+xlabel('Time, min','FontSize',8)
+ylabel('PKB-T308P, a.u.','FontSize',8)
+text(15,0.95*3.5,'PKB-T308P','FontSize',9)
+
+subplot(5,4,11)
+semilogx(conc_highres, dr_n(:,5)', 'b-', 'Linewidth',2)
+hold on
+plot(conc_highres, dr_d(:,5)', 'r-', 'Linewidth',2)
+errorbar(conc, expdata_PKB473_dr.response_n,expdata_PKB473_dr.sem_n,'bo','MarkerFaceColor','b','MarkerSize',6)
+errorbar(conc, expdata_PKB473_dr.response_d,expdata_PKB473_dr.sem_d,'ro','MarkerFaceColor','r','MarkerSize',6)
+axis([1e-12 1e-7 0 100])
+set(gca,'YTick',[0 50 100],'XTick',[1e-11 1e-10 1e-9 1e-8 1e-7],'FontSize',8);
+box off
+xlabel('[Insulin], M','FontSize',8)
+ylabel('PKB-S473P, % of max','FontSize',8)
+text(2e-12,95,'PKB-S473P','FontSize',9)
+
+subplot(5,4,12)
+plot(time30,scalePKB473*simdata_60_n.variablevalues(1:3001,5),'b-', 'Linewidth',2)
+hold on
+plot(time30,scalePKB473*simdata_60_d.variablevalues(1:3001,5),'r-', 'Linewidth',2)
+errorbar(expdata_PKB473_time_renorm.time,comb_expdata_PKB473_time.response_n,comb_expdata_PKB473_time.sem_n,'bo','MarkerFaceColor','b','MarkerSize',6)
+errorbar(expdata_PKB473_time_renorm.time,comb_expdata_PKB473_time.response_d,comb_expdata_PKB473_time.sem_d,'ro','MarkerFaceColor','r','MarkerSize',6)
+axis([0 30 0 2.5])
+set(gca,'YTick',[0 1 2 3 4 5],'XTick',[0 10 20 30],'FontSize',8);
+box off
+xlabel('Time, min','FontSize',8)
+ylabel('PKB-S473P, a.u.','FontSize',8)
+text(15,0.95*2.5,'PKB-S473P','FontSize',9)
+
+subplot(5,4,15)
+plot(time30,simdata_60_n.variablevalues(1:3001,7),'b-', 'Linewidth',2)
+hold on
+plot(time30,simdata_60_d.variablevalues(1:3001,7),'r-', 'Linewidth',2)
+axis([0 30 0 100])
+set(gca,'YTick',[0 50 100],'XTick',[0 10 20 30],'FontSize',8);
+box off
+xlabel('Time, min','FontSize',8)
+ylabel('Active mTORC1, a.u.','FontSize',8)
+text(2,0.95*100,'Active mTORC1','FontSize',9)
+
+subplot(5,4,13)
+semilogx(conc_highres, dr_n(:,6)', 'b-', 'Linewidth',2)
+hold on
+plot(conc_highres, dr_d(:,6)', 'r-', 'Linewidth',2)
+errorbar(conc, expdata_AS160_dr.response_n,expdata_AS160_dr.sem_n,'bo','MarkerFaceColor','b','MarkerSize',6)
+errorbar(conc, expdata_AS160_dr.response_d,expdata_AS160_dr.sem_d,'ro','MarkerFaceColor','r','MarkerSize',6)
+axis([1e-12 1e-7 0 100])
+set(gca,'YTick',[0 50 100],'XTick',[1e-11 1e-10 1e-9 1e-8 1e-7],'FontSize',8);
+box off
+xlabel('[Insulin], M','FontSize',8)
+ylabel('AS160-T642P, % of max','FontSize',8)
+text(2e-12,90,{'AS160-';'T642P'},'FontSize',9)
+
+subplot(5,4,14)
+plot(time30,scaleAS160*simdata_60_n.variablevalues(1:3001,6),'b-', 'Linewidth',2)
+hold on
+plot(time30,scaleAS160*simdata_60_d.variablevalues(1:3001,6),'r-', 'Linewidth',2)
+errorbar(expdata_AS160_time.time,expdata_AS160_time.response_n,expdata_AS160_time.sem_n,'bo','MarkerFaceColor','b','MarkerSize',6)
+errorbar(expdata_AS160_time.time,expdata_AS160_time.response_d,expdata_AS160_time.sem_d,'ro','MarkerFaceColor','r','MarkerSize',6)
+axis([0 30 0 3])
+set(gca,'YTick',[0 1 2 3 4 5],'XTick',[0 10 20 30],'FontSize',8);
+box off
+xlabel('Time, min','FontSize',8)
+ylabel('AS160-T642P, a.u.','FontSize',8)
+text(15,0.95*3,'AS160-T642P','FontSize',9)
+
+subplot(5,4,17)
+semilogx(expdata_GLUCOSE_dr.conc,GLUCOSE_dr_n,'b-', 'Linewidth',2)
+hold on
+plot(expdata_GLUCOSE_dr.conc,GLUCOSE_dr_d,'r-', 'Linewidth',2)
+errorbar(expdata_GLUCOSE_dr.conc,expdata_GLUCOSE_dr.response_n,expdata_GLUCOSE_dr.sem_n,'bo','MarkerFaceColor','b','MarkerSize',6)
+errorbar(expdata_GLUCOSE_dr.conc,expdata_GLUCOSE_dr.response_d,expdata_GLUCOSE_dr.sem_d,'ro','MarkerFaceColor','r','MarkerSize',6)
+axis([1e-12 1e-7 0 100])
+set(gca,'YTick',[0 50 100],'XTick',[1e-11 1e-10 1e-9 1e-8 1e-7],'FontSize',8);
+box off
+xlabel('[Insulin], M','FontSize',8)
+ylabel('Glucose uptake, % of max','FontSize',8)
+text(2e-12,90,{'Glucose';'uptake'},'FontSize',9)
+
+subplot(5,4,18)
+errorbar(1,1e-3*expdata_GLUCOSE_2p.response_n(1),1e-3*expdata_GLUCOSE_2p.sem_n(1),'k')
+hold on
+errorbar(3,1e-3*expdata_GLUCOSE_2p.response_n(2),1e-3*expdata_GLUCOSE_2p.sem_n(2),'k')
+bar([1 3 2 4],[1e-3*expdata_GLUCOSE_2p.response_n;1e-3*scaleGLUCOSE*GLUCOSE_n],'b')
+errorbar(6,1e-3*expdata_GLUCOSE_2p.response_d(1),1e-3*expdata_GLUCOSE_2p.sem_d(2),'k')
+errorbar(8,1e-3*expdata_GLUCOSE_2p.response_d(2),1e-3*expdata_GLUCOSE_2p.sem_d(2),'k')
+bar([6 8 7 9],[1e-3*expdata_GLUCOSE_2p.response_d;1e-3*scaleGLUCOSE*GLUCOSE_d],'r')
+xlabel({'-       +           -       +';'Insulin'},'FontSize',8)
+box off
+ylabel('Glucose uptake, cpm*1e-3','FontSize',8)
+set(gca,'YTick',[0 1 2 3 4],'XTick',[],'FontSize',8);
+text(1,0.95*4,'Glucose uptake','FontSize',9)
+
+subplot(5,4,16)
+plot(time30,scaleS6K*simdata_60_n.variablevalues(1:3001,8),'b-', 'Linewidth',2)
+hold on
+plot(time30,scaleS6K*simdata_60_d.variablevalues(1:3001,8),'r-', 'Linewidth',2)   
+errorbar(expdata_S6K_time.time,expdata_S6K_time.response_n,expdata_S6K_time.sem_n,'bo','MarkerFaceColor','b','MarkerSize',6)        
+errorbar(expdata_S6K_time.time,expdata_S6K_time.response_d,expdata_S6K_time.sem_d,'ro','MarkerFaceColor','r','MarkerSize',6')  
+axis([0 30 0 3.5])
+set(gca,'YTick',[0 1 2 3 4 5],'XTick',[0 10 20 30],'FontSize',8);
+box off
+xlabel('Time, min','FontSize',8)
+ylabel('S6K-T389P, a.u.','FontSize',8)
+text(15,0.95*3.5,'S6K-T389P','FontSize',9)
+
+subplot(5,4,19)
+plot(time30,simdata_60_n.variablevalues(1:3001,13),'b-', 'Linewidth',2)
+hold on
+plot(time30,simdata_60_d.variablevalues(1:3001,13),'r-', 'Linewidth',2)
+axis([0 30 0 2.5])
+set(gca,'YTick',[0 1 2],'XTick',[0 10 20 30],'FontSize',8);
+box off
+xlabel('Time, min','FontSize',8)
+ylabel('Active mTORC2, a.u.','FontSize',8)
+text(5,0.95*2.5,'Active mTORC2','FontSize',9)
+
+subplot(5,4,20)
+plot(time30,scaleS6*simdata_60_n.variablevalues(1:3001,9),'b-', 'Linewidth',2) 
+hold on
+plot(time30,scaleS6*simdata_60_d.variablevalues(1:3001,9),'r-', 'Linewidth',2) 
+errorbar(expdata_S6_time.time,expdata_S6_time.response_n,expdata_S6_time.sem_n,'bo','MarkerFaceColor','b','MarkerSize',6)
+errorbar(expdata_S6_time.time,expdata_S6_time.response_d,expdata_S6_time.sem_d,'ro','MarkerFaceColor','r','MarkerSize',6) 
+axis([0 30 0 4])
+set(gca,'YTick',[0 1 2 3 4 5],'XTick',[0 10 20 30],'FontSize',8);
+box off
+xlabel('Time, min','FontSize',8)
+ylabel('S6-S235/236P, a.u.','FontSize',8)
+text(15,0.9*4,{'S6-S235/','236P'},'FontSize',9)
+
+
diff --git a/scripts/results/allAcceptableParams.mat b/scripts/results/allAcceptableParams.mat
new file mode 100644
index 0000000000000000000000000000000000000000..7d55b9dde43e2e09e890192f74c57c86634dfccb
Binary files /dev/null and b/scripts/results/allAcceptableParams.mat differ
diff --git a/scripts/results/opt(12.92335).mat b/scripts/results/opt(12.92335).mat
new file mode 100644
index 0000000000000000000000000000000000000000..bba2ba9a18534124f99e84b35807718ac52fcbc2
Binary files /dev/null and b/scripts/results/opt(12.92335).mat differ
diff --git a/scripts/simulateSteadyState.m b/scripts/simulateSteadyState.m
index 4aa6aa98a81b98b3f16047b0a9cd879ab2ae0281..ed874701d9b143984838a31b01684302ed3c4a55 100644
--- a/scripts/simulateSteadyState.m
+++ b/scripts/simulateSteadyState.m
@@ -1,9 +1,9 @@
 function [inits] = simulateSteadyState(model, paramsAll)
 
 simTimeEnd=10000;
-
 time=[1:simTimeEnd-100:simTimeEnd];
 sim = model(time, [], paramsAll); 
-inits = sim.statevalues(1,:);
+
+inits = sim.statevalues(end,:);
 
 end
diff --git a/scripts/simulateSteadyStated.m b/scripts/simulateSteadyStated.m
new file mode 100644
index 0000000000000000000000000000000000000000..265bcf4bc80f42f683a8a1a819f4e519d9303bde
--- /dev/null
+++ b/scripts/simulateSteadyStated.m
@@ -0,0 +1,11 @@
+function [inits] = simulateSteadyStated(model, paramsAll)
+
+simTimeEnd=10000;
+ICorig = IQMinitialconditions(model);
+time=[1:simTimeEnd-100:simTimeEnd];
+sim = model(time, [], paramsAll); 
+
+iGp = find(ismember(IQMstates(model),'G_p'));
+inits = [sim.statevalues(end,1:iGp-1) ICorig(iGp:end)'];
+
+end
diff --git a/scripts/suport/IQMtools/IQMlite/classeshandling/modelhandling/auxiliary/SBMLexport/M1.txt b/scripts/suport/IQMtools/IQMlite/classeshandling/modelhandling/auxiliary/SBMLexport/M1.txt
new file mode 100644
index 0000000000000000000000000000000000000000..eff9181393930c4444c7c6a339ce0a6bb0c00ac4
--- /dev/null
+++ b/scripts/suport/IQMtools/IQMlite/classeshandling/modelhandling/auxiliary/SBMLexport/M1.txt
@@ -0,0 +1,257 @@
+********** MODEL NAME
+M1
+
+********** MODEL NOTES
+
+
+********** MODEL STATES
+d/dt(IR)                = -v1a-v1basal+v1r+v1g  %%1 
+d/dt(IRp)               = v1basal+v1c-v1d-v1g   %%2
+d/dt(IRins)             = v1a-v1c               %%3
+d/dt(IRip)              = v1d-v1e               %%4
+d/dt(IRi)               = v1e-v1r               %%5
+d/dt(IRS1)              = v2b+v2g-v2a-v2basal   %%6
+d/dt(IRS1p)             = v2a+v2d-v2b-v2c       %%7
+d/dt(IRS1p307)          = v2c-v2d-v2f           %%8
+d/dt(IRS1307)           = v2basal+v2f-v2g       %%9 
+d/dt(X)                 = v3b-v3a               %%10
+d/dt(Xp)                = v3a-v3b               %%12
+d/dt(PKB)               = -v4a+v4b+v4h          %%13   
+d/dt(PKB308p)           = v4a-v4b-v4c           %%14
+d/dt(PKB473p)           = -v4e+v4f-v4h          %%15
+d/dt(PKB308p473p)       = v4c+v4e-v4f           %%16
+d/dt(mTORC1)            = v5b-v5a               %%17         
+d/dt(mTORC1a)           = v5a-v5b               %%18
+d/dt(mTORC2)            = -v5c+v5d              %%19
+d/dt(mTORC2a)           = v5c-v5d               %%20
+d/dt(AS160)             = v6b1-v6f1             %%21
+d/dt(AS160p)            = v6f1-v6b1             %%22
+d/dt(GLUT4m)            = (v7f-v7b)             %%23
+d/dt(GLUT4)             = -v7f+v7b              %%24
+d/dt(S6K)               = v9b1-v9f1             %%26
+d/dt(S6Kp)              = v9f1-v9b1             %%27
+d/dt(S6)                = v9b2-v9f2             %%28
+d/dt(S6p)               = v9f2-v9b2             %%29                                               
+d/dt(G_p) = EGP+Ra-E-U_ii-k_1*G_p+k_2*G_t                                        
+d/dt(G_t) = (-U_id)+k_1*G_p-k_2*G_t                                        
+d/dt(I_l) = (-m_1*I_l)-m_3*I_l+m_2*I_p+S                                         
+d/dt(I_p) = (-m_2*I_p)-m_4*I_p+m_1*I_l                                         
+d/dt(Q_sto1) = -k_gri*Q_sto1                                                     
+d/dt(Q_sto2) = (-k_empt*Q_sto2)+k_gri*Q_sto1                                     
+d/dt(Q_gut) = (-k_abs*Q_gut)+k_empt*Q_sto2                                       
+d/dt(I_1) = -k_i*(I_1-I)                                                         
+d/dt(I_d) = -k_i*(I_d-I_1)                                                       
+d/dt(INS) = (-p_2U*INS)+p_2U*(I-I_b)                                             
+d/dt(I_po) = (-gamma*I_po)+S_po                                                  
+d/dt(Y) = -alpha*(Y-beta*(G-G_b))  
+d/dt(E) = 0                                              
+
+
+IR(0)               = 100
+IRp(0)              = 0
+IRins(0)            = 0         
+IRip(0)             = 0
+IRi(0)              = 0 
+IRS1(0)             = 100
+IRS1p(0)            = 0
+IRS1p307(0)         = 0
+IRS1307(0)          = 0
+X(0)                = 100
+Xp(0)               = 0
+PKB(0)              = 100
+PKB308p(0)          = 0
+PKB473p(0)          = 0
+PKB308p473p(0)      = 0
+mTORC1(0)           = 100
+mTORC1a(0)          = 0
+mTORC2(0)           = 100
+mTORC2a(0)          = 0
+AS160(0)            = 100
+AS160p(0)           = 0
+GLUT4m(0)           = 0
+GLUT4(0)            = 100
+S6K(0)              = 100
+S6Kp(0)             = 0
+S6(0)               = 100
+S6p(0)              = 0                               
+G_p(0) = 178                                                                   
+G_t(0) = 130                                                                     
+I_l(0) = 4.5                                                                 
+I_p(0) = 1.25                                                                 
+Q_sto1(0) = 78000                                                                
+Q_sto2(0) = 0                                                                    
+Q_gut(0) = 0                                                                     
+I_1(0) = 25                                                                      
+I_d(0) = 25                                                                      
+INS(0) = 0                                                                     
+I_po(0) = 3.6                                                  
+Y(0) = 0
+E(0) = 0
+
+********** MODEL PARAMETERS
+
+diabetes = 1  %%1                                                                
+k1a = 0.633141  %%2                                                              
+k1basal = 0.0331338  %%3                                                         
+k1c = 0.876805  %%4                                                              
+k1d = 31.012  %%5                                                                
+k1f = 1839.58  %%6                                                               
+k1g = 1944.11  %%7                                                               
+k1r = 0.547061  %%8                                                              
+k2a = 3.22728  %%9                                                               
+k2c = 5758.78  %%10                                                              
+k2basal = 0.0422768  %%11                                                        
+k2b = 3424.35  %%12                                                              
+k2d = 280.753  %%13                                                              
+k2f = 2.9131  %%14                                                               
+k2g = 0.267089  %%15                                                             
+k3a = 0.00137731  %%16                                                           
+k3b = 0.0987558  %%17                                                            
+k4a = 5790.17  %%18                                                              
+k4b = 34.7965  %%19                                                              
+k4c = 4.45581  %%20                                                              
+k4e = 42.8395  %%21                                                              
+k4f = 143.597  %%22                                                              
+k4h = 0.536145  %%23                                                             
+k5a1 = 1.8423  %%24                                                              
+k5a2 = 0.055064  %%25                                                            
+k5b = 24.826  %%26                                                               
+k5d = 1.06013  %%27                                                              
+km5 = 2.64988  %%28                                                              
+k5c = 0.0857515  %%29                                                            
+k6f1 = 2.65168  %%30                                                             
+k6f2 = 36.9348  %%31                                                             
+km6 = 30.5424  %%32                                                              
+n6 = 2.13707  %%33                                                               
+k6b = 65.1841  %%34                                                              
+k7f = 50.9829  %%35                                                              
+k7b = 2285.97  %%36                                                              
+k8 = 724.242  %%37                                                               
+glut1 = 7042.19  %%38                                                            
+k9f1 = 0.12981  %%39                                                             
+k9b1 = 0.0444092  %%40                                                           
+k9f2 = 3.3289  %%41                                                              
+k9b2 = 30.9967  %%42                                                             
+km9 = 5872.68  %%43                                                              
+n9 = 0.985466  %%44                                                              
+kbf = 1e+06  %%45                                                                
+scaleModel = 2.1e-06  %%46  
+                                                     
+V_G = 1.88  %%47                                                                 
+k_1 = 0.065  %%48                                                                
+k_2 = 0.079  %%49                                                                
+G_b = 95  %%50                                                                   
+V_I = 0.05  %%51                                                                 
+m_1 = 0.19  %%52                                                                 
+m_2 = 0.484    %% 53                                                                  
+m_4 = 0.194    %% 54                                                                  
+m_5 = 0.0304  %%55                                                               
+m_6 = 0.6471   %% 56                                                                  
+HE_b = 0.6  %%57                                                                 
+I_b = 25  %%58                                                                   
+S_b = 1.8  %%59                                                                  
+k_max = 0.0558  %%60                                                             
+k_min = 0.008  %%61                                                              
+k_abs = 0.057  %%62                                                              
+k_gri = 0.0558  %%63                                                             
+f = 0.9  %%64                                                                    
+b = 0.82  %%65                                                                   
+d = 0.01  %%66                                                                   
+BW = 78  %%67                                                                    
+k_p1 = 2.7  %%68                                                                 
+k_p2 = 0.0021  %%69                                                              
+k_p3 = 0.009  %%70                                                               
+k_p4 = 0.0618  %%71                                                              
+k_i = 0.0079  %%72                                                               
+
+V_m0 = 2.5    %%74                                                                   
+V_mX = 0.047  %%75                                                                
+K_m0 = 225.59  %%76                                             
+V_f0 = 2.5  %%77                                                                 
+V_fX = 0.047  %%78                                                               
+K_f0 = 225.59  %%79                                                              
+p_2U = 0.0331  %%80                                                              
+part = 0.2  %%81                                                                 
+K = 2.3  %%82                                                                    
+alpha = 0.05  %%83                                                               
+beta = 0.11  %%84                                                                
+gamma = 0.5  %%85                                                                
+k_e1 = 0.0005  %%86                                                              
+k_e2 = 339  %%87                                                                 
+D = 78000  %%88    
+
+K_l0 = 225.59
+V_l0 = 2.5                                                                       
+V_lX = 0.047  
+
+********** MODEL VARIABLES
+aa = 5/2/(1-b)/D                                                                 
+cc = 5/2/d/D                                                                     
+EGP = k_p1-k_p2*G_p-k_p3*I_d-k_p4*I_po                                           
+V_mmax = (1-part)*(V_m0+V_mX*INS)                                                
+V_fmax = part*(V_f0+V_fX*INS) 
+V_lmax = (1-part)*(V_l0+V_lX*G_t)                                                   
+Ee = k_e1*(G_p - k_e2)                                                                            
+S = gamma*I_po                                                                                                                       
+I = I_p/V_I                                                                      
+G = G_p/V_G                                                                      
+HE = (-m_5*S)+m_6                                                                
+m_3 = HE*m_1/(1-HE)                                                              
+Q_sto = Q_sto1+Q_sto2                                                            
+Ra = f*k_abs*Q_gut/BW                                                           
+k_empt = k_min+(k_max-k_min)/2*(tanh(aa*(Q_sto-b*D))-tanh(cc*(Q_sto-d*D))+2)     
+U_idm = 0.5*V_mmax*G_t/(K_m0+G_t)
+U_idf = 0.5*scaleModel*(k8*GLUT4m*G_t/34 + glut1*G_t/34 + kbf*(INS+5)*1e-3)                                                                                                              
+U = U_ii+U_id                                                                    
+S_po = Y+K*(EGP+Ra-E-U_ii-k_1*G_p+k_2*G_t)/V_G+S_b
+U_liver = 45*U_idm/27
+U_ii = 23*U_liver/45
+U_id = U_idm+U_idf+U_liver
+
+********** MODEL REACTIONS                                                                                                          
+v1a      = IR*k1a*(INS+5)*1e-3
+v1basal  = k1basal*IR
+v1c      = IRins*k1c
+v1d      = IRp*k1d
+v1e      = IRip*k1f*Xp
+v1g      = IRp*k1g
+v1r      = IRi*k1r
+v2a      = IRS1*k2a*IRip
+v2b      = IRS1p*k2b
+v2c      = IRS1p*k2c*mTORC1a*diabetes
+v2d      = IRS1p307*k2d
+v2f 	 = IRS1p307*k2f
+v2basal  = IRS1*k2basal
+v2g 	 = IRS1307*k2g
+v3a      = X*k3a*IRS1p
+v3b      = Xp*k3b
+
+v5a      = mTORC1*(k5a1*PKB308p473p+k5a2*PKB308p)
+v5b      = mTORC1a*k5b
+v5c      = mTORC2*k5c*IRip
+v5d      = k5d*mTORC2a
+v4a      = k4a*PKB*IRS1p
+v4b      = k4b*PKB308p
+v4c      = k4c*PKB308p*mTORC2a
+v4e      = k4e*PKB473p*IRS1p307
+v4f      = k4f*PKB308p473p
+v4h      = k4h*PKB473p
+
+v6f1     = AS160*(k6f1*PKB308p473p+k6f2*PKB473p^n6/(km6^n6+PKB473p^n6))
+v6b1     = AS160p*k6b
+v7f      = GLUT4*k7f*AS160p
+v7b      = GLUT4m*k7b
+
+v9f1     = S6K*k9f1*mTORC1a^n9/(km9^n9+mTORC1a^n9)
+v9b1     = S6Kp*k9b1
+v9f2     = S6*k9f2*S6Kp
+v9b2     = S6p*k9b2
+
+glucoseuptake = k8*GLUT4m*(G_t*5/170) + glut1*(G_t*5/170) + kbf*((INS+5)*1e-3)
+
+********** MODEL FUNCTIONS
+
+********** MODEL EVENTS
+event1 = gt(G_p,339),E,Ee
+event2 = lt(G_p,339),E,0
+********** MODEL MATLAB FUNCTIONS
\ No newline at end of file
diff --git a/scripts/suport/IQMtools/IQMpro/tools/01-MEXmodels/CVODEMEX/lib/CVODEmex25.lib b/scripts/suport/IQMtools/IQMpro/tools/01-MEXmodels/CVODEMEX/lib/CVODEmex25.lib
index 09592f8f96cb4a4826d2b297e7f86e704de949ec..d0f44f34af0dfe7ca377c46f1bf1f8ab04af6927 100644
Binary files a/scripts/suport/IQMtools/IQMpro/tools/01-MEXmodels/CVODEMEX/lib/CVODEmex25.lib and b/scripts/suport/IQMtools/IQMpro/tools/01-MEXmodels/CVODEMEX/lib/CVODEmex25.lib differ
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/README.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/README.txt
new file mode 100644
index 0000000000000000000000000000000000000000..0e35d9319f352b925fa8b6386c60e8e2bdcf7bf3
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/README.txt
@@ -0,0 +1,25 @@
+Installation of the SBPOP Package:
+==================================
+
+- Start MATLAB
+- The first time you install a new version of the SBPOP package, please run 
+  the script: "installSBPOPpackageInitial". This will compile all needed 
+  libraries and executables for your system.
+- If you do not install it for the first time, then just execute the script
+  "installSBPOPpackage". Alternatively you just need to add the SBPOP 
+  Package folder and all subfolders to the MATLAB path.
+- If your system is allowed to store the MATLAB path between MATLAB 
+  sessions, you do not need to call these installation scripts again. If 
+  your MATLAB path is not stored, then you will need to do that each time
+  you start MATLAB and want to use the SBPOP Package.
+
+Handling of NLME tools:
+=======================
+
+If you want to use NLME tools (MONOLIX and/or NONMEM), then please do the following:
+
+- Open the file "SETUP_NLME_TOOLS.m"
+- Follow the instructions in the file, which essentially means to provide the 
+  paths and names of the executables for NONMEM and MONOLIX
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/Contents.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/Contents.m
new file mode 100644
index 0000000000000000000000000000000000000000..cf053caff5f7f8c9c228947d89ff91c2af390e69
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/Contents.m
@@ -0,0 +1,222 @@
+% SBPD
+% Version $Rev: 1606 $ (R2010b-R2014a) $Date: 2014-08-05 18:50:55 +0200 (Tue, 05 Aug 2014) $
+% 
+% Installation of package
+% =======================
+%   installSBPD         - Installation script for the SBPD package. Just
+%                         run it from within its folder
+%   lookforSBPD         - Searches SBPD functions for strings and
+%                         opens the documents in which these strings appear
+%
+% Project creation and handling
+% =============================
+%   SBPDproject             - Creating a new SBPDproject
+%   SBPDgui                 - Graphical User Interface for parameter
+%                             estimation on projects
+%   SBPDstruct              - Returns the internal data structure of an SBPDproject
+%   SBPDexportproject       - Export a project to a directory structure
+%   SBPDsaveproject         - Save a project in a MAT file (extension: .sbp)
+%   isSBPDproject           - Checks if the given argument is an SBPDproject
+%   SBPDinfo                - Display information about the project
+%   SBPDplotmeasurements    - Visualize all measurements in the project
+%   SBPDgetmodel            - Get specified model from project
+%   SBPDgetexperiment       - Get specified experiment from project
+%   SBPDgetmeasurement      - Get specified measurement from project
+%   SBPDcomparemeasurements - Compare measurements to model in project
+%   SBPDupdatemodel         - Update or add a model in a project
+%   SBPDupdateexperiment    - Update or add an experiment in a project
+%   SBPDupdatemeasurement   - Update or add a measurement in a project
+%   SBPDexportestimation    - Export estimation settings to a flat file
+%
+% MEX model creation and handling
+% ===============================
+%   SBPDmakeMEXmodel          - Creates an executable simulation MEX file 
+%                                 for a specified SBmodel. The function can
+%                                 also be used to create C model files (no
+%                                 compilation)
+%   makeTempMEXmodelSBPD      - Creates a temporary executable simulation MEX
+%                                 file for a specified SBmodel
+%   mexcompileSBPD         - Creates an executable simulation MEX file 
+%                                 for an existing C model files. These files
+%                                 might be written by hand or obtained by the 
+%                                 SBPDmakeMEXmodel function
+%   makeparamvecSBPD            - this function can be used to create a full
+%                                 parameter vector for the given model,
+%                                 where the given parameters are changed to
+%                                 given values. All other parameters remain
+%                                 unchanged
+%   makeinicondvectorSBPD       - this function can be used to create a full
+%                                 state initial condition vector for the
+%                                 given model, where the given states are
+%                                 changed to given values. All other states
+%                                 remain unchanged
+%   getparamindicesSBPD         - returns a vector containing the indices
+%                                 of the given model parameters
+%   getstateindicesSBPD         - returns a vector containing the indices
+%                                 of the given model states
+%
+% Modelling
+% =========
+%   SBPDdirectoptss     - Tune a model to a desired steady-state by
+%                         adjusting the velocity parameters of the reaction
+%                         kinetics 
+% 
+% Additionally, the SBPD package features several inbuild kinetic rate
+% laws, which are documented below. 
+%
+% Simulation & sensitivity analysis
+% =================================
+%   SBPDsimulate        - Wrapper function for simulation MEX files.
+%                         Can also be used on SBmodels
+%   SBPDsensitivity     - Function for computing sensitivities of states,
+%                         variables, and reactions in the model with respect 
+%                         to parameters 
+%   SBPDinsilicoexp     - Performs an insilico experiment for given
+%                         SBmodel and SBexperiment. Visualizes result
+%                         or exports it to a SBmeasurement
+%                         representation. Also Excel or CSV measurement
+%                         files can directly be generated.
+%   SBPDinsilicoexpproj - Performs an in-silico experiment directly on a
+%                         model and experiment within a project. Per
+%                         default a CSV measurement files is created.
+%
+% Parameter identifiability
+% =========================
+%   SBPDidentifiability       - Function for determining parameter
+%                               identifiability based on correlation
+%                               analysis of sensitivity trajectories.
+%                               Directly applicable to SBPDprojects.   
+%   SBPDparametercorrelation  - Function for determining parameter
+%                               correlations based on parametric
+%                               sensitivities. 
+%
+% Model reduction (requires the symbolic toolbox)
+% ===============================================
+%   SBPDreducerateexpression    - Reduce the reaction rate expression of a
+%                                 model, defined in a project
+%
+% Parameter estimation
+% ====================
+% SBPDmanualtuning          - Graphical user interface allowing to manually
+%                             tune the models present in a project
+% SBPDmodeltuning           - Allows to compare and tune a model to one or
+%                             more sets of data. No experiment description
+%                             is required 
+% SBPDparameterestimation   - Allows to estimate parameters for the models 
+%                             in a project, using the experiments and
+%                             measurements that are defined in the project
+% getparamictextSBPD        - Auxiliary function to easily construct the
+%                             text that is necessary to define the
+%                             parameters and initial conditions to estimate
+%                             + their upper and lower bounds
+% createrunestimationscriptSBPD - Auxiliary function creating a template
+%                             m-script for running parameter estimations on
+%                             a given project 
+% SBPDanalyzeresiduals      - Determines and analyzes the residuals for a 
+%                             given project
+% SBPDparameterfitanalysis  - Generates data to analyze the obtained
+%                             parameter fit with respect to correlations, 
+%                             local minima, etc.
+% SBPDfahist                - Plots histograms for the parameter values that 
+%                             have been estimated using the SBPDparameterfitanalysis 
+%                             function 
+% SBPDfaclustering          - Performs hierarchical clustering based on
+%                             Euclidean distance of the parameter sets
+%                             estimated using the SBPDparameterfitanalysis
+%                             function
+% SBPDfaboxplot             - Plots a box-and-whisker diagram for the
+%                             estimation data, obtained using the
+%                             SBPDparameterfitanalysis function 
+% SBPDfacorr                - Determines the correlation matrix for the
+%                             parameter sets determined with the
+%                             SBPDparameterfitanalysis function 
+% SBPDfasigncorr            - Determines a matrix of p-values for testing
+%                             the hypothesis of no significant correlation
+%                             based on the results generated by
+%                             SBPDparameterfitanalysis 
+% SBPDfadetcorr            - Plots detailed pairwise correlations between
+%                             parameters.
+% cutoffdataSBPD           - Used to select a cut-off threshold for the
+%                             estimation data collected during the fit
+%                             analysis
+% 
+% Symbolic Math Functions (require the symbolic toolbox)
+% ======================================================
+%   SBPDsymjacobian         - determines the Jacobian of an SBmodel
+%                             symbolically
+%
+% Inbuild kinetic rate laws
+% =========================
+%   kin_allosteric_inihib_empirical_rev  - see function documentation
+%   kin_allosteric_inihib_mwc_irr        - see function documentation 
+%   kin_catalytic_activation_irr         - see function documentation
+%   kin_catalytic_activation_rev         - see function documentation
+%   kin_comp_inihib_irr                  - see function documentation
+%   kin_comp_inihib_rev                  - see function documentation 
+%   kin_constantflux                     - see function documentation 
+%   kin_degradation                      - see function documentation 
+%   kin_hill_1_modifier_rev              - see function documentation 
+%   kin_hill_2_modifiers_rev             - see function documentation 
+%   kin_hill_cooperativity_irr           - see function documentation 
+%   kin_hill_rev                         - see function documentation 
+%   kin_hyperbolic_modifier_irr          - see function documentation 
+%   kin_hyperbolic_modifier_rev          - see function documentation 
+%   kin_iso_uni_uni_rev                  - see function documentation 
+%   kin_mass_action_irr                  - see function documentation 
+%   kin_mass_action_rev                  - see function documentation 
+%   kin_michaelis_menten_irr             - see function documentation 
+%   kin_michaelis_menten_rev             - see function documentation 
+%   kin_mixed_activation_irr             - see function documentation 
+%   kin_mixed_activation_rev             - see function documentation 
+%   kin_mixed_inihib_irr                 - see function documentation 
+%   kin_mixed_inihib_rev                 - see function documentation 
+%   kin_noncomp_inihib_irr               - see function documentation 
+%   kin_noncomp_inihib_rev               - see function documentation 
+%   kin_ordered_bi_bi_rev                - see function documentation 
+%   kin_ordered_bi_uni_rev               - see function documentation 
+%   kin_ordered_uni_bi_rev               - see function documentation 
+%   kin_ping_pong_bi_bi_rev              - see function documentation 
+%   kin_specific_activation_irr          - see function documentation 
+%   kin_specific_activation_rev          - see function documentation 
+%   kin_substrate_activation_irr         - see function documentation 
+%   kin_substrate_inihib_irr             - see function documentation 
+%   kin_substrate_inihib_rev             - see function documentation 
+%   kin_uncomp_inihib_irr                - see function documentation 
+%   kin_uncomp_inihib_rev                - see function documentation 
+%   kin_uni_uni_rev                      - see function documentation 
+%
+% Parameter Estimation Benchmarks
+% ===============================
+% The SBPD package includes several SBPDprojects that can be used as
+% benchmarks for the evaluation of parameter estimation methods.
+% These projects are located in the SBPD/examples/benchmarkproblems
+% folder and can be run using the following scripts:
+%
+%   run_ex1         - Isomerization of alpha-pinene
+%   run_ex2         - Irreversible inhibition of HIV proteinase
+%   run_ex3         - Three-step biochemical pathway
+%
+% To execute these scripts, please change into the
+% SBPD/examples/benchmarkproblems folder, open the desired script and 
+% run it step by step. (Here the Cell-mode of the MATLAB editor is very
+% useful!).
+
+% Information:
+% ============
+% Copyright (C) 2005-2013 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/FitAnalysis/demodata.mat b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/FitAnalysis/demodata.mat
new file mode 100644
index 0000000000000000000000000000000000000000..eba255c6f3ef7b2baa16b4812225724df438cfc8
Binary files /dev/null and b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/FitAnalysis/demodata.mat differ
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/FitAnalysis/runAnalysis.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/FitAnalysis/runAnalysis.m
new file mode 100644
index 0000000000000000000000000000000000000000..4715b1db5f4deed69b2e597ca106cdcb49bc879a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/FitAnalysis/runAnalysis.m
@@ -0,0 +1,46 @@
+% Parameterfit analysis example script
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+%% Perform a parameter fit analysis
+% Idea: the optimized parameters of a given project (sbpopt) are 
+% randomly perturbed and a new estimation is performed. This is 
+% repeated a couple of times (nrestimations) in order to collect
+% data that can be analyzed in order to detect local minima, 
+% correlations, etc.
+%
+% The code to run is the following (after the definition 
+% of sbpopt and estimation, done in the example script 'runEstimation.m'
+% in the SBPD/examples/Projects folder.
+nrestimations = 100;
+perttype = 0.5;
+[estdata] = SBPDparameterfitanalysis(sbpopt,estimation,nrestimations,perttype)  
+
+%% ALTERNATIVELY: load sample estimation data (also defines the "estdata" variable)
+load demodata
+
+%% Selecting a suitable cut-off. The reminaing parameter sets
+% should have a relatively similar optimal cost function value.
+estdata = cutoffdataSBPD(estdata)
+
+%% Boxplot
+SBPDfaboxplot(estdata)
+
+%% Histogram
+SBPDfahist(estdata,15)
+
+%% Clustering
+SBPDfaclustering(estdata)
+
+%% Parameter correlation
+SBPDfacorr(estdata)
+
+%% Significant correlations (p-values)
+SBPDfasigncorr(estdata)
+
+%% Detailed correlations
+SBPDfadetcorr(estdata)
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/ModredExample/HynneProject/experiments/firstexp/HynneGlycolysisModel_Referenceexperiment.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/ModredExample/HynneProject/experiments/firstexp/HynneGlycolysisModel_Referenceexperiment.csv
new file mode 100644
index 0000000000000000000000000000000000000000..77719ce477ad8fe81ce99c0feb65abd6036b9632
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/ModredExample/HynneProject/experiments/firstexp/HynneGlycolysisModel_Referenceexperiment.csv
@@ -0,0 +1,1834 @@
+% Measurement file generated: 30-Jul-2007
+
+[Name]
+HynneGlycolysisModel_Reference experiment
+
+[Notes]
+Insilico experiment measurements
+================================
+Model notes:
+------------
+Full-scale model of glycolysis in Saccharomyces cerevisiae                                                                             
+F. Hynne, S. Dano, and PG, Sorensen                                                                                                    
+Biophysical Chemistry 94 (2001) 121-163                                                                                                
+                                                                                                                                       
+Time units: minutes                                                                                                                    
+Species units: mM                                                                                                                      
+                                                                                                                                       
+Initialconditions do not give a steady-state, but a state-that allows                                                                  
+to see the oscillations when simulating.
+
+Experiment notes:
+-----------------
+Reference experiment for Hynne model that is used to generate in-silico 
+measurement data that the reduced model should be able to reproduce.
+
+Pretty complicated experiment definition ... :)
+
+[Components]
+time,Glcx,Glc,ATP,G6P,ADP,F6P,FBP,GAP,DHAP,NADplus,BPG,NADH,PEP,Pyr,ACA,EtOH,EtOHx,Glyc,Glycx,ACAx,CNxminus,AMP
+
+[Componentnotes]
+
+[Values]
+0.000000,1.244479,0.408097,2.102544,4.148672,1.498510,0.484555,4.454132,0.112714,2.887661,0.652702,0.000267,0.327298,0.039503,6.602917,1.448285,19.059340,16.298700,4.103154,1.647506,1.259385,5.211879,0.328946
+0.100000,1.244479,0.408102,2.102498,4.148624,1.498537,0.484547,4.454168,0.112714,2.887670,0.652698,0.000267,0.327302,0.039503,6.602909,1.448283,19.059339,16.298700,4.103149,1.647506,1.259385,5.211879,0.328965
+0.200000,1.244479,0.408109,2.102474,4.148560,1.498551,0.484539,4.454253,0.112716,2.887696,0.652694,0.000267,0.327306,0.039503,6.602917,1.448279,19.059343,16.298700,4.103150,1.647506,1.259385,5.211879,0.328975
+0.300000,1.244479,0.408112,2.102490,4.148532,1.498541,0.484536,4.454320,0.112717,2.887719,0.652693,0.000267,0.327307,0.039503,6.602933,1.448277,19.059346,16.298700,4.103156,1.647506,1.259385,5.211879,0.328968
+0.400000,1.244479,0.408109,2.102532,4.148561,1.498517,0.484542,4.454311,0.112716,2.887719,0.652695,0.000267,0.327305,0.039503,6.602944,1.448279,19.059346,16.298700,4.103162,1.647506,1.259385,5.211879,0.328951
+0.500000,1.244479,0.408102,2.102564,4.148625,1.498498,0.484550,4.454235,0.112715,2.887697,0.652700,0.000267,0.327300,0.039503,6.602940,1.448282,19.059341,16.298700,4.103163,1.647506,1.259385,5.211879,0.328938
+0.600000,1.244479,0.408097,2.102558,4.148668,1.498502,0.484555,4.454153,0.112714,2.887669,0.652702,0.000267,0.327298,0.039503,6.602925,1.448285,19.059337,16.298700,4.103158,1.647506,1.259385,5.211879,0.328940
+0.700000,1.244479,0.408099,2.102517,4.148653,1.498526,0.484551,4.454138,0.112714,2.887661,0.652700,0.000267,0.327300,0.039503,6.602910,1.448285,19.059336,16.298700,4.103151,1.647506,1.259385,5.211879,0.328957
+0.800000,1.244479,0.408106,2.102476,4.148587,1.498550,0.484542,4.454208,0.112715,2.887681,0.652696,0.000267,0.327304,0.039503,6.602910,1.448281,19.059340,16.298700,4.103148,1.647506,1.259385,5.211879,0.328974
+0.900000,1.244479,0.408112,2.102471,4.148528,1.498553,0.484535,4.454306,0.112716,2.887713,0.652693,0.000267,0.327307,0.039503,6.602925,1.448277,19.059346,16.298700,4.103153,1.647506,1.259385,5.211879,0.328976
+1.000000,1.244479,0.408112,2.102509,4.148529,1.498530,0.484537,4.454345,0.112717,2.887728,0.652693,0.000267,0.327307,0.039503,6.602943,1.448277,19.059348,16.298700,4.103161,1.647506,1.259385,5.211879,0.328960
+1.100000,1.244479,0.408105,2.102559,4.148592,1.498501,0.484546,4.454286,0.112716,2.887713,0.652698,0.000267,0.327302,0.039503,6.602948,1.448280,19.059344,16.298700,4.103165,1.647506,1.259385,5.211879,0.328940
+1.200000,1.244479,0.408098,2.102577,4.148665,1.498491,0.484556,4.454177,0.112715,2.887679,0.652702,0.000267,0.327298,0.039503,6.602935,1.448284,19.059338,16.298700,4.103162,1.647506,1.259385,5.211879,0.328932
+1.300000,1.244479,0.408096,2.102544,4.148684,1.498510,0.484556,4.454112,0.112714,2.887655,0.652702,0.000267,0.327298,0.039503,6.602914,1.448286,19.059335,16.298700,4.103154,1.647506,1.259385,5.211879,0.328946
+1.400000,1.244479,0.408102,2.102487,4.148627,1.498543,0.484547,4.454151,0.112714,2.887663,0.652698,0.000267,0.327302,0.039503,6.602904,1.448283,19.059337,16.298700,4.103147,1.647506,1.259385,5.211879,0.328969
+1.500000,1.244479,0.408110,2.102456,4.148542,1.498562,0.484536,4.454267,0.112716,2.887699,0.652693,0.000267,0.327307,0.039503,6.602914,1.448278,19.059344,16.298700,4.103148,1.647506,1.259385,5.211879,0.328982
+1.600000,1.244479,0.408115,2.102480,4.148502,1.498548,0.484532,4.454360,0.112717,2.887731,0.652691,0.000267,0.327309,0.039503,6.602937,1.448276,19.059349,16.298700,4.103157,1.647506,1.259385,5.211879,0.328973
+1.700000,1.244479,0.408110,2.102540,4.148546,1.498512,0.484540,4.454346,0.112717,2.887731,0.652695,0.000267,0.327305,0.039503,6.602953,1.448278,19.059347,16.298700,4.103165,1.647506,1.259385,5.211879,0.328947
+1.800000,1.244479,0.408100,2.102586,4.148641,1.498485,0.484553,4.454230,0.112715,2.887697,0.652701,0.000267,0.327299,0.039503,6.602947,1.448283,19.059341,16.298700,4.103166,1.647506,1.259385,5.211879,0.328928
+1.900000,1.244479,0.408094,2.102575,4.148704,1.498492,0.484560,4.454110,0.112714,2.887656,0.652704,0.000267,0.327296,0.039503,6.602923,1.448287,19.059334,16.298700,4.103158,1.647506,1.259385,5.211879,0.328933
+2.000000,1.244479,0.408097,2.102513,4.148676,1.498528,0.484554,4.454093,0.112713,2.887646,0.652702,0.000267,0.327298,0.039503,6.602902,1.448286,19.059334,16.298700,4.103148,1.647506,1.259385,5.211879,0.328958
+2.100000,1.244479,0.408107,2.102453,4.148578,1.498563,0.484539,4.454201,0.112715,2.887677,0.652695,0.000267,0.327305,0.039503,6.602902,1.448281,19.059340,16.298700,4.103144,1.647506,1.259385,5.211879,0.328983
+2.200000,1.244479,0.408116,2.102448,4.148492,1.498566,0.484530,4.454346,0.112717,2.887724,0.652690,0.000267,0.327310,0.039503,6.602925,1.448275,19.059348,16.298700,4.103151,1.647506,1.259385,5.211879,0.328985
+2.300000,1.244479,0.408115,2.102507,4.148496,1.498531,0.484533,4.454398,0.112718,2.887746,0.652691,0.000267,0.327309,0.039503,6.602952,1.448275,19.059351,16.298700,4.103163,1.647506,1.259385,5.211879,0.328961
+2.400000,1.244479,0.408105,2.102581,4.148593,1.498488,0.484548,4.454307,0.112716,2.887722,0.652698,0.000267,0.327302,0.039503,6.602958,1.448280,19.059345,16.298700,4.103170,1.647506,1.259385,5.211879,0.328931
+2.500000,1.244479,0.408094,2.102604,4.148701,1.498475,0.484561,4.454144,0.112714,2.887670,0.652705,0.000267,0.327295,0.039503,6.602938,1.448286,19.059336,16.298700,4.103165,1.647506,1.259385,5.211879,0.328921
+2.600000,1.244479,0.408092,2.102553,4.148725,1.498505,0.484561,4.454050,0.112713,2.887635,0.652705,0.000267,0.327295,0.039503,6.602907,1.448289,19.059331,16.298700,4.103152,1.647506,1.259385,5.211879,0.328942
+2.700000,1.244479,0.408101,2.102469,4.148636,1.498554,0.484547,4.454116,0.112714,2.887650,0.652699,0.000267,0.327301,0.039503,6.602893,1.448284,19.059336,16.298700,4.103142,1.647506,1.259385,5.211879,0.328977
+2.800000,1.244479,0.408114,2.102424,4.148509,1.498580,0.484530,4.454290,0.112716,2.887704,0.652691,0.000267,0.327309,0.039503,6.602909,1.448277,19.059345,16.298700,4.103145,1.647506,1.259385,5.211879,0.328995
+2.900000,1.244479,0.408120,2.102463,4.148454,1.498557,0.484526,4.454426,0.112718,2.887752,0.652688,0.000267,0.327312,0.039503,6.602943,1.448273,19.059353,16.298700,4.103158,1.647506,1.259385,5.211879,0.328980
+3.000000,1.244479,0.408112,2.102554,4.148525,1.498504,0.484539,4.454397,0.112717,2.887749,0.652694,0.000267,0.327306,0.039503,6.602966,1.448276,19.059350,16.298700,4.103170,1.647506,1.259385,5.211879,0.328942
+3.100000,1.244479,0.408098,2.102621,4.148667,1.498465,0.484558,4.454221,0.112715,2.887696,0.652703,0.000267,0.327297,0.039503,6.602956,1.448284,19.059340,16.298701,4.103171,1.647506,1.259385,5.211879,0.328914
+3.200000,1.244479,0.408088,2.102600,4.148756,1.498477,0.484567,4.454044,0.112713,2.887637,0.652707,0.000267,0.327293,0.039503,6.602920,1.448290,19.059330,16.298700,4.103159,1.647506,1.259385,5.211879,0.328922
+3.300000,1.244479,0.408093,2.102506,4.148711,1.498532,0.484557,4.454026,0.112713,2.887624,0.652703,0.000267,0.327297,0.039503,6.602889,1.448288,19.059330,16.298700,4.103143,1.647506,1.259385,5.211879,0.328961
+3.400000,1.244479,0.408108,2.102418,4.148561,1.498584,0.484536,4.454194,0.112715,2.887672,0.652693,0.000267,0.327307,0.039503,6.602891,1.448280,19.059340,16.298700,4.103139,1.647506,1.259385,5.211879,0.328998
+3.500000,1.244479,0.408121,2.102415,4.148436,1.498585,0.484522,4.454407,0.112718,2.887742,0.652687,0.000267,0.327313,0.039503,6.602926,1.448272,19.059352,16.298700,4.103149,1.647506,1.259385,5.211879,0.328999
+3.600000,1.244479,0.408120,2.102505,4.148449,1.498532,0.484528,4.454479,0.112719,2.887772,0.652689,0.000267,0.327311,0.039503,6.602965,1.448272,19.059355,16.298700,4.103167,1.647506,1.259385,5.211879,0.328962
+3.700000,1.244479,0.408105,2.102614,4.148597,1.498469,0.484550,4.454334,0.112717,2.887733,0.652699,0.000267,0.327301,0.039503,6.602973,1.448280,19.059346,16.298701,4.103176,1.647506,1.259385,5.211879,0.328917
+3.800000,1.244479,0.408089,2.102645,4.148756,1.498451,0.484569,4.454091,0.112713,2.887655,0.652708,0.000267,0.327292,0.039503,6.602941,1.448289,19.059333,16.298701,4.103168,1.647506,1.259385,5.211879,0.328904
+3.900000,1.244479,0.408085,2.102565,4.148784,1.498498,0.484568,4.453960,0.112712,2.887606,0.652708,0.000267,0.327292,0.039503,6.602895,1.448292,19.059326,16.298700,4.103149,1.647506,1.259385,5.211879,0.328937
+4.000000,1.244479,0.408099,2.102439,4.148648,1.498572,0.484547,4.454065,0.112713,2.887631,0.652699,0.000267,0.327301,0.039503,6.602875,1.448285,19.059333,16.298700,4.103135,1.647506,1.259385,5.211879,0.328989
+4.100000,1.244479,0.408119,2.102377,4.148459,1.498608,0.484522,4.454329,0.112717,2.887713,0.652687,0.000267,0.327313,0.039503,6.602902,1.448274,19.059348,16.298700,4.103140,1.647506,1.259385,5.211879,0.329015
+4.200000,1.244479,0.408127,2.102439,4.148384,1.498571,0.484517,4.454523,0.112719,2.887782,0.652684,0.000267,0.327316,0.039503,6.602953,1.448269,19.059358,16.298700,4.103159,1.647506,1.259385,5.211879,0.328990
+4.300000,1.244479,0.408116,2.102577,4.148496,1.498490,0.484537,4.454471,0.112718,2.887775,0.652693,0.000267,0.327307,0.039503,6.602985,1.448274,19.059354,16.298701,4.103177,1.647506,1.259384,5.211879,0.328933
+4.400000,1.244479,0.408094,2.102672,4.148708,1.498435,0.484565,4.454202,0.112715,2.887694,0.652706,0.000267,0.327294,0.039503,6.602967,1.448286,19.059338,16.298701,4.103178,1.647506,1.259384,5.211879,0.328893
+4.500000,1.244479,0.408080,2.102637,4.148836,1.498456,0.484578,4.453944,0.112711,2.887606,0.652713,0.000267,0.327287,0.039503,6.602914,1.448294,19.059325,16.298701,4.103159,1.647506,1.259385,5.211879,0.328907
+4.600000,1.244479,0.408088,2.102494,4.148759,1.498540,0.484562,4.453930,0.112711,2.887591,0.652706,0.000267,0.327294,0.039503,6.602869,1.448291,19.059325,16.298700,4.103136,1.647506,1.259385,5.211879,0.328966
+4.700000,1.244479,0.408111,2.102365,4.148534,1.498615,0.484530,4.454186,0.112715,2.887665,0.652691,0.000267,0.327309,0.039503,6.602874,1.448279,19.059340,16.298700,4.103130,1.647506,1.259386,5.211879,0.329020
+4.800000,1.244479,0.408130,2.102366,4.148352,1.498614,0.484510,4.454502,0.112719,2.887769,0.652681,0.000267,0.327319,0.039503,6.602928,1.448268,19.059358,16.298700,4.103147,1.647506,1.259385,5.211879,0.329019
+4.900000,1.244479,0.408127,2.102505,4.148381,1.498532,0.484520,4.454596,0.112720,2.887811,0.652685,0.000267,0.327315,0.039503,6.602985,1.448268,19.059362,16.298701,4.103173,1.647506,1.259385,5.211879,0.328962
+5.000000,1.244479,0.408104,2.102666,4.148606,1.498438,0.484553,4.454373,0.112717,2.887750,0.652700,0.000267,0.327300,0.039503,6.602995,1.448280,19.059348,16.298701,4.103186,1.647506,1.259384,5.211879,0.328896
+5.100000,1.244479,0.408080,2.102705,4.148839,1.498416,0.484582,4.454009,0.112712,2.887633,0.652714,0.000267,0.327286,0.039503,6.602945,1.448294,19.059328,16.298701,4.103173,1.647506,1.259385,5.211879,0.328879
+5.200000,1.244479,0.408076,2.102581,4.148872,1.498489,0.484579,4.453823,0.112710,2.887562,0.652714,0.000267,0.327286,0.039503,6.602877,1.448297,19.059319,16.298700,4.103144,1.647506,1.259385,5.211879,0.328930
+5.300000,1.244479,0.408098,2.102393,4.148661,1.498599,0.484546,4.453995,0.112712,2.887605,0.652699,0.000267,0.327301,0.039503,6.602850,1.448287,19.059330,16.298700,4.103124,1.647506,1.259386,5.211879,0.329008
+5.400000,1.244479,0.408127,2.102307,4.148382,1.498649,0.484510,4.454390,0.112718,2.887728,0.652682,0.000267,0.327318,0.039503,6.602891,1.448270,19.059352,16.298700,4.103132,1.647506,1.259386,5.211879,0.329044
+5.500000,1.244479,0.408138,2.102406,4.148278,1.498590,0.484504,4.454671,0.112721,2.887828,0.652678,0.000267,0.327322,0.039503,6.602968,1.448263,19.059367,16.298700,4.103162,1.647506,1.259385,5.211879,0.329004
+5.600000,1.244479,0.408120,2.102613,4.148457,1.498469,0.484534,4.454576,0.112720,2.887812,0.652691,0.000267,0.327309,0.039503,6.603013,1.448271,19.059360,16.298701,4.103188,1.647506,1.259384,5.211879,0.328918
+5.700000,1.244479,0.408087,2.102749,4.148773,1.498390,0.484576,4.454170,0.112714,2.887689,0.652711,0.000267,0.327289,0.039503,6.602985,1.448289,19.059336,16.298701,4.103188,1.647506,1.259384,5.211879,0.328861
+5.800000,1.244479,0.408068,2.102688,4.148953,1.498426,0.484593,4.453793,0.112709,2.887561,0.652720,0.000267,0.327280,0.039502,6.602903,1.448301,19.059316,16.298701,4.103159,1.647506,1.259385,5.211879,0.328886
+5.900000,1.244479,0.408080,2.102473,4.148829,1.498553,0.484568,4.453787,0.112709,2.887542,0.652709,0.000267,0.327291,0.039503,6.602838,1.448296,19.059318,16.298700,4.103126,1.647506,1.259386,5.211879,0.328974
+6.000000,1.244479,0.408115,2.102285,4.148488,1.498662,0.484521,4.454182,0.112715,2.887658,0.652687,0.000267,0.327313,0.039503,6.602849,1.448277,19.059341,16.298700,4.103118,1.647506,1.259386,5.211879,0.329053
+6.100000,1.244479,0.408143,2.102296,4.148226,1.498655,0.484492,4.454647,0.112721,2.887812,0.652673,0.000267,0.327327,0.039504,6.602931,1.448261,19.059366,16.298700,4.103144,1.647506,1.259385,5.211879,0.329049
+6.200000,1.244479,0.408138,2.102508,4.148281,1.498530,0.484509,4.454773,0.112723,2.887869,0.652680,0.000267,0.327320,0.039504,6.603015,1.448261,19.059371,16.298701,4.103183,1.647506,1.259384,5.211879,0.328962
+6.300000,1.244479,0.408102,2.102744,4.148625,1.498392,0.484560,4.454420,0.112718,2.887771,0.652703,0.000267,0.327297,0.039503,6.603026,1.448280,19.059350,16.298701,4.103200,1.647506,1.259384,5.211879,0.328864
+6.400000,1.244479,0.408067,2.102794,4.148967,1.498364,0.484600,4.453880,0.112710,2.887597,0.652723,0.000267,0.327277,0.039502,6.602949,1.448300,19.059320,16.298701,4.103180,1.647506,1.259384,5.211879,0.328842
+6.500000,1.244479,0.408063,2.102600,4.149000,1.498478,0.484594,4.453622,0.112707,2.887498,0.652721,0.000267,0.327279,0.039502,6.602848,1.448305,19.059307,16.298700,4.103136,1.647506,1.259385,5.211879,0.328922
+6.600000,1.244479,0.408096,2.102323,4.148677,1.498641,0.484544,4.453894,0.112711,2.887566,0.652698,0.000267,0.327302,0.039503,6.602812,1.448289,19.059325,16.298700,4.103108,1.647506,1.259386,5.211879,0.329037
+6.700000,1.244479,0.408139,2.102203,4.148262,1.498710,0.484491,4.454490,0.112719,2.887753,0.652673,0.000267,0.327327,0.039503,6.602877,1.448264,19.059359,16.298700,4.103121,1.647506,1.259386,5.211879,0.329087
+6.800000,1.244479,0.408154,2.102360,4.148124,1.498617,0.484484,4.454892,0.112724,2.887897,0.652668,0.000267,0.327332,0.039504,6.602992,1.448254,19.059379,16.298700,4.103166,1.647506,1.259385,5.211879,0.329023
+6.900000,1.244479,0.408126,2.102670,4.148401,1.498435,0.484531,4.454731,0.112722,2.887868,0.652689,0.000267,0.327311,0.039503,6.603056,1.448267,19.059368,16.298701,4.103205,1.647506,1.259384,5.211879,0.328895
+7.000000,1.244479,0.408077,2.102864,4.148875,1.498322,0.484594,4.454111,0.112713,2.887678,0.652719,0.000267,0.327281,0.039503,6.603009,1.448294,19.059332,16.298702,4.103202,1.647506,1.259384,5.211879,0.328814
+7.100000,1.244479,0.408049,2.102763,4.149132,1.498382,0.484617,4.453562,0.112706,2.887491,0.652731,0.000267,0.327269,0.039502,6.602886,1.448311,19.059303,16.298701,4.103158,1.647506,1.259385,5.211879,0.328854
+7.200000,1.244479,0.408070,2.102435,4.148925,1.498575,0.484577,4.453581,0.112707,2.887472,0.652714,0.000267,0.327286,0.039502,6.602792,1.448303,19.059307,16.298700,4.103109,1.647506,1.259386,5.211879,0.328989
+7.300000,1.244478,0.408123,2.102163,4.148415,1.498734,0.484506,4.454184,0.112715,2.887649,0.652681,0.000267,0.327319,0.039503,6.602814,1.448274,19.059342,16.298699,4.103099,1.647506,1.259386,5.211879,0.329103
+7.400000,1.244479,0.408163,2.102193,4.148035,1.498715,0.484465,4.454872,0.112724,2.887878,0.652660,0.000267,0.327340,0.039504,6.602938,1.448250,19.059380,16.298700,4.103140,1.647506,1.259385,5.211879,0.329092
+7.500000,1.244479,0.408153,2.102518,4.148139,1.498524,0.484494,4.455028,0.112726,2.887954,0.652672,0.000267,0.327328,0.039504,6.603061,1.448253,19.059385,16.298701,4.103198,1.647506,1.259384,5.211879,0.328958
+7.600000,1.244479,0.408099,2.102864,4.148659,1.498321,0.484570,4.454485,0.112718,2.887802,0.652707,0.000267,0.327293,0.039503,6.603072,1.448280,19.059352,16.298702,4.103222,1.647506,1.259383,5.211879,0.328814
+7.700000,1.244479,0.408047,2.102923,4.149160,1.498288,0.484629,4.453679,0.112707,2.887541,0.652736,0.000267,0.327264,0.039502,6.602953,1.448311,19.059308,16.298701,4.103189,1.647506,1.259384,5.211879,0.328788
+7.800000,1.244479,0.408044,2.102619,4.149179,1.498468,0.484615,4.453331,0.112703,2.887403,0.652731,0.000267,0.327269,0.039502,6.602804,1.448316,19.059291,16.298700,4.103124,1.647506,1.259386,5.211879,0.328913
+7.900000,1.244478,0.408097,2.102207,4.148659,1.498709,0.484536,4.453806,0.112710,2.887528,0.652695,0.000267,0.327305,0.039503,6.602762,1.448289,19.059321,16.298699,4.103086,1.647506,1.259386,5.211879,0.329084
+8.000000,1.244478,0.408159,2.102078,4.148071,1.498783,0.484464,4.454691,0.112722,2.887810,0.652660,0.000267,0.327340,0.039504,6.602874,1.448254,19.059371,16.298699,4.103113,1.647506,1.259386,5.211879,0.329139
+8.100000,1.244479,0.408171,2.102356,4.147962,1.498619,0.484466,4.455169,0.112728,2.887988,0.652659,0.000267,0.327341,0.039504,6.603037,1.448244,19.059394,16.298701,4.103180,1.647506,1.259385,5.211879,0.329025
+8.200000,1.244479,0.408122,2.102793,4.148444,1.498363,0.484542,4.454785,0.112722,2.887895,0.652694,0.000267,0.327306,0.039503,6.603102,1.448268,19.059370,16.298702,4.103227,1.647506,1.259383,5.211879,0.328844
+8.300000,1.244479,0.408055,2.102985,4.149080,1.498252,0.484623,4.453880,0.112710,2.887612,0.652732,0.000267,0.327268,0.039502,6.603005,1.448305,19.059318,16.298702,4.103209,1.647506,1.259384,5.211879,0.328763
+8.400000,1.244479,0.408034,2.102746,4.149282,1.498393,0.484633,4.453284,0.112702,2.887398,0.652739,0.000267,0.327261,0.039502,6.602834,1.448321,19.059288,16.298701,4.103141,1.647506,1.259385,5.211879,0.328861
+8.500000,1.244478,0.408077,2.102292,4.148852,1.498659,0.484562,4.453560,0.112707,2.887454,0.652707,0.000267,0.327293,0.039502,6.602746,1.448300,19.059307,16.298699,4.103086,1.647506,1.259386,5.211879,0.329049
+8.600000,1.244478,0.408147,2.102040,4.148177,1.498806,0.484473,4.454469,0.112719,2.887734,0.652665,0.000267,0.327335,0.039503,6.602825,1.448261,19.059359,16.298699,4.103095,1.647506,1.259386,5.211879,0.329154
+8.700000,1.244479,0.408179,2.102229,4.147880,1.498693,0.484450,4.455178,0.112728,2.887981,0.652652,0.000267,0.327348,0.039504,6.603001,1.448240,19.059396,16.298700,4.103161,1.647506,1.259385,5.211879,0.329077
+8.800000,1.244479,0.408142,2.102693,4.148247,1.498421,0.484515,4.455023,0.112726,2.887965,0.652681,0.000267,0.327319,0.039504,6.603112,1.448257,19.059383,16.298702,4.103224,1.647506,1.259383,5.211879,0.328886
+8.900000,1.244479,0.408069,2.103005,4.148949,1.498239,0.484609,4.454129,0.112713,2.887695,0.652725,0.000267,0.327275,0.039503,6.603053,1.448296,19.059332,16.298702,4.103225,1.647506,1.259383,5.211879,0.328755
+9.000000,1.244479,0.408028,2.102872,4.149340,1.498319,0.484646,4.453313,0.112703,2.887417,0.652745,0.000267,0.327255,0.039502,6.602876,1.448323,19.059288,16.298701,4.103162,1.647506,1.259385,5.211879,0.328809
+9.100000,1.244478,0.408057,2.102407,4.149049,1.498592,0.484590,4.453338,0.112703,2.887390,0.652720,0.000267,0.327280,0.039502,6.602742,1.448311,19.059294,16.298700,4.103092,1.647506,1.259386,5.211879,0.329001
+9.200000,1.244478,0.408131,2.102037,4.148332,1.498808,0.484491,4.454197,0.112715,2.887644,0.652674,0.000267,0.327326,0.039503,6.602778,1.448271,19.059344,16.298699,4.103081,1.647506,1.259387,5.211879,0.329155
+9.300000,1.244479,0.408182,2.102109,4.147849,1.498764,0.484440,4.455108,0.112727,2.887949,0.652649,0.000267,0.327351,0.039504,6.602953,1.448240,19.059393,16.298700,4.103139,1.647506,1.259385,5.211879,0.329127
+9.400000,1.244479,0.408162,2.102564,4.148053,1.498497,0.484487,4.455225,0.112729,2.888022,0.652668,0.000267,0.327332,0.039504,6.603108,1.448247,19.059396,16.298701,4.103215,1.647506,1.259384,5.211879,0.328939
+9.500000,1.244479,0.408088,2.102988,4.148771,1.498249,0.484589,4.454420,0.112717,2.887789,0.652715,0.000267,0.327285,0.039503,6.603097,1.448285,19.059348,16.298702,4.103237,1.647506,1.259383,5.211879,0.328763
+9.600000,1.244479,0.408028,2.102985,4.149344,1.498252,0.484652,4.453424,0.112704,2.887462,0.652747,0.000267,0.327253,0.039502,6.602928,1.448321,19.059293,16.298702,4.103185,1.647506,1.259384,5.211879,0.328763
+9.700000,1.244479,0.408038,2.102548,4.149234,1.498510,0.484618,4.453161,0.112701,2.887342,0.652733,0.000267,0.327267,0.039502,6.602754,1.448320,19.059283,16.298700,4.103104,1.647506,1.259386,5.211879,0.328943
+9.800000,1.244478,0.408110,2.102075,4.148531,1.498786,0.484515,4.453891,0.112711,2.887546,0.652686,0.000267,0.327314,0.039503,6.602737,1.448283,19.059327,16.298699,4.103070,1.647506,1.259387,5.211879,0.329139
+9.900000,1.244478,0.408179,2.102007,4.147876,1.498824,0.484438,4.454955,0.112725,2.887891,0.652648,0.000267,0.327352,0.039504,6.602897,1.448243,19.059386,16.298699,4.103116,1.647506,1.259386,5.211879,0.329169
+10.000000,1.553067,0.573064,2.100013,4.200046,1.499993,0.490006,4.639941,0.114999,2.949984,0.650003,0.000270,0.329997,0.040000,8.699937,1.481537,19.237910,16.451410,4.195995,1.684783,1.288364,5.203581,0.329994
+10.100000,1.553067,0.573067,2.099986,4.200014,1.500009,0.490001,4.639969,0.115000,2.949991,0.650000,0.000270,0.330000,0.040000,8.699934,1.481535,19.237914,16.451410,4.195992,1.684783,1.288364,5.203581,0.330005
+10.200000,1.553067,0.573071,2.099976,4.199980,1.500014,0.489997,4.640019,0.115000,2.950006,0.649998,0.000270,0.330002,0.040000,8.699939,1.481533,19.237917,16.451410,4.195993,1.684783,1.288364,5.203581,0.330009
+10.300000,1.553067,0.573073,2.099986,4.199967,1.500008,0.489996,4.640051,0.115001,2.950017,0.649998,0.000270,0.330002,0.040000,8.699948,1.481532,19.237919,16.451410,4.195997,1.684783,1.288364,5.203581,0.330005
+10.400000,1.553067,0.573071,2.100006,4.199981,1.499997,0.489998,4.640046,0.115001,2.950017,0.649999,0.000270,0.330001,0.040000,8.699953,1.481533,19.237919,16.451410,4.195999,1.684783,1.288364,5.203581,0.329997
+10.500000,1.553067,0.573068,2.100020,4.200008,1.499989,0.490002,4.640013,0.115000,2.950008,0.650001,0.000270,0.329999,0.040000,8.699951,1.481534,19.237917,16.451410,4.196000,1.684783,1.288364,5.203581,0.329991
+10.600000,1.553067,0.573066,2.100020,4.200028,1.499989,0.490004,4.639978,0.115000,2.949996,0.650002,0.000270,0.329998,0.040000,8.699946,1.481536,19.237915,16.451410,4.195998,1.684783,1.288364,5.203581,0.329991
+10.700000,1.553067,0.573066,2.100007,4.200029,1.499997,0.490004,4.639964,0.114999,2.949991,0.650002,0.000270,0.329998,0.040000,8.699939,1.481536,19.237914,16.451410,4.195995,1.684783,1.288364,5.203581,0.329997
+10.800000,1.553067,0.573068,2.099990,4.200010,1.500006,0.490001,4.639980,0.115000,2.949995,0.650000,0.000270,0.330000,0.040000,8.699937,1.481535,19.237915,16.451410,4.195993,1.684783,1.288364,5.203581,0.330004
+10.900000,1.553067,0.573070,2.099983,4.199988,1.500011,0.489998,4.640011,0.115000,2.950004,0.649999,0.000270,0.330001,0.040000,8.699940,1.481534,19.237917,16.451410,4.195994,1.684783,1.288364,5.203581,0.330007
+11.000000,1.553067,0.573072,2.099988,4.199977,1.500008,0.489997,4.640035,0.115000,2.950012,0.649998,0.000270,0.330002,0.040000,8.699946,1.481533,19.237918,16.451410,4.195996,1.684783,1.288364,5.203581,0.330005
+11.100000,1.553067,0.573071,2.100001,4.199984,1.500000,0.489998,4.640036,0.115000,2.950014,0.649999,0.000270,0.330001,0.040000,8.699950,1.481533,19.237918,16.451410,4.195998,1.684783,1.288364,5.203581,0.329999
+11.200000,1.553067,0.573069,2.100012,4.200002,1.499993,0.490001,4.640016,0.115000,2.950008,0.650000,0.000270,0.330000,0.040000,8.699950,1.481534,19.237917,16.451410,4.195999,1.684783,1.288364,5.203581,0.329995
+11.300000,1.553067,0.573067,2.100015,4.200018,1.499992,0.490003,4.639990,0.115000,2.950000,0.650001,0.000270,0.329999,0.040000,8.699946,1.481535,19.237916,16.451410,4.195998,1.684783,1.288364,5.203581,0.329994
+11.400000,1.553067,0.573067,2.100007,4.200022,1.499996,0.490003,4.639977,0.115000,2.949995,0.650001,0.000270,0.329999,0.040000,8.699942,1.481535,19.237915,16.451410,4.195996,1.684783,1.288364,5.203581,0.329997
+11.500000,1.553067,0.573068,2.099996,4.200011,1.500003,0.490001,4.639983,0.115000,2.949996,0.650000,0.000270,0.330000,0.040000,8.699940,1.481535,19.237915,16.451410,4.195994,1.684783,1.288364,5.203581,0.330001
+11.600000,1.553067,0.573069,2.099989,4.199995,1.500007,0.489999,4.640004,0.115000,2.950002,0.649999,0.000270,0.330001,0.040000,8.699941,1.481534,19.237917,16.451410,4.195994,1.684783,1.288364,5.203581,0.330004
+11.700000,1.553067,0.573071,2.099990,4.199985,1.500006,0.489998,4.640023,0.115000,2.950009,0.649999,0.000270,0.330001,0.040000,8.699945,1.481533,19.237918,16.451410,4.195996,1.684783,1.288364,5.203581,0.330004
+11.800000,1.553067,0.573071,2.099998,4.199987,1.500001,0.489998,4.640028,0.115000,2.950011,0.649999,0.000270,0.330001,0.040000,8.699948,1.481533,19.237918,16.451410,4.195997,1.684783,1.288364,5.203581,0.330000
+11.900000,1.553067,0.573069,2.100007,4.199999,1.499996,0.490000,4.640017,0.115000,2.950008,0.650000,0.000270,0.330000,0.040000,8.699949,1.481534,19.237917,16.451410,4.195998,1.684783,1.288364,5.203581,0.329997
+12.000000,1.553067,0.573068,2.100011,4.200011,1.499994,0.490002,4.639999,0.115000,2.950002,0.650001,0.000270,0.329999,0.040000,8.699947,1.481535,19.237916,16.451410,4.195997,1.684783,1.288364,5.203581,0.329995
+12.100000,1.553067,0.573067,2.100007,4.200016,1.499996,0.490002,4.639986,0.115000,2.949998,0.650001,0.000270,0.329999,0.040000,8.699944,1.481535,19.237915,16.451410,4.195996,1.684783,1.288364,5.203581,0.329997
+12.200000,1.553067,0.573068,2.099999,4.200011,1.500001,0.490001,4.639988,0.115000,2.949998,0.650000,0.000270,0.330000,0.040000,8.699942,1.481535,19.237916,16.451410,4.195995,1.684783,1.288364,5.203581,0.330000
+12.300000,1.553067,0.573069,2.099993,4.200000,1.500005,0.490000,4.640001,0.115000,2.950002,0.650000,0.000270,0.330000,0.040000,8.699942,1.481534,19.237916,16.451410,4.195995,1.684783,1.288364,5.203581,0.330003
+12.400000,1.553067,0.573070,2.099993,4.199991,1.500005,0.489999,4.640015,0.115000,2.950006,0.649999,0.000270,0.330001,0.040000,8.699944,1.481534,19.237917,16.451410,4.195995,1.684783,1.288364,5.203581,0.330003
+12.500000,1.553067,0.573070,2.099998,4.199991,1.500002,0.489999,4.640021,0.115000,2.950009,0.649999,0.000270,0.330001,0.040000,8.699947,1.481533,19.237917,16.451410,4.195997,1.684783,1.288364,5.203581,0.330001
+12.600000,1.553067,0.573069,2.100004,4.199998,1.499998,0.490000,4.640016,0.115000,2.950007,0.650000,0.000270,0.330000,0.040000,8.699948,1.481534,19.237917,16.451410,4.195997,1.684783,1.288364,5.203581,0.329998
+12.700000,1.553067,0.573068,2.100008,4.200007,1.499996,0.490001,4.640004,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699947,1.481534,19.237916,16.451410,4.195997,1.684783,1.288364,5.203581,0.329997
+12.800000,1.553067,0.573068,2.100006,4.200011,1.499997,0.490002,4.639993,0.115000,2.950000,0.650001,0.000270,0.329999,0.040000,8.699945,1.481535,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329997
+12.900000,1.553067,0.573068,2.100001,4.200009,1.500000,0.490001,4.639992,0.115000,2.949999,0.650000,0.000270,0.330000,0.040000,8.699943,1.481535,19.237916,16.451410,4.195995,1.684783,1.288364,5.203581,0.329999
+13.000000,1.553067,0.573069,2.099997,4.200003,1.500002,0.490000,4.639998,0.115000,2.950001,0.650000,0.000270,0.330000,0.040000,8.699943,1.481534,19.237916,16.451410,4.195995,1.684783,1.288364,5.203581,0.330001
+13.100000,1.553067,0.573069,2.099995,4.199997,1.500003,0.489999,4.640007,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699944,1.481534,19.237917,16.451410,4.195995,1.684783,1.288364,5.203581,0.330002
+13.200000,1.553067,0.573070,2.099996,4.199994,1.500002,0.489999,4.640014,0.115000,2.950006,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237917,16.451410,4.195996,1.684783,1.288364,5.203581,0.330001
+13.300000,1.553067,0.573070,2.100000,4.199996,1.500000,0.490000,4.640015,0.115000,2.950007,0.650000,0.000270,0.330000,0.040000,8.699946,1.481534,19.237917,16.451410,4.195997,1.684783,1.288364,5.203581,0.330000
+13.400000,1.553067,0.573069,2.100003,4.200000,1.499999,0.490000,4.640010,0.115000,2.950005,0.650000,0.000270,0.330000,0.040000,8.699947,1.481534,19.237917,16.451410,4.195997,1.684783,1.288364,5.203581,0.329998
+13.500000,1.553067,0.573069,2.100004,4.200004,1.499998,0.490001,4.640004,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699946,1.481534,19.237916,16.451410,4.195997,1.684783,1.288364,5.203581,0.329998
+13.600000,1.553067,0.573068,2.100003,4.200007,1.499998,0.490001,4.639999,0.115000,2.950002,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329998
+13.700000,1.553067,0.573068,2.100001,4.200006,1.500000,0.490001,4.639999,0.115000,2.950002,0.650000,0.000270,0.330000,0.040000,8.699944,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+13.800000,1.553067,0.573069,2.099999,4.200003,1.500001,0.490000,4.640001,0.115000,2.950002,0.650000,0.000270,0.330000,0.040000,8.699944,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.330000
+13.900000,1.553067,0.573069,2.099998,4.200000,1.500002,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699944,1.481534,19.237917,16.451410,4.195996,1.684783,1.288364,5.203581,0.330001
+14.000000,1.553067,0.573069,2.099998,4.199998,1.500001,0.490000,4.640009,0.115000,2.950005,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237917,16.451410,4.195996,1.684783,1.288364,5.203581,0.330000
+14.100000,1.553067,0.573069,2.100000,4.199999,1.500000,0.490000,4.640010,0.115000,2.950005,0.650000,0.000270,0.330000,0.040000,8.699946,1.481534,19.237917,16.451410,4.195996,1.684783,1.288364,5.203581,0.330000
+14.200000,1.553067,0.573069,2.100001,4.200000,1.500000,0.490000,4.640008,0.115000,2.950005,0.650000,0.000270,0.330000,0.040000,8.699946,1.481534,19.237917,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+14.300000,1.553067,0.573069,2.100002,4.200002,1.499999,0.490000,4.640006,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699946,1.481534,19.237917,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+14.400000,1.553067,0.573069,2.100002,4.200003,1.499999,0.490000,4.640004,0.115000,2.950003,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+14.500000,1.553067,0.573069,2.100002,4.200004,1.499999,0.490000,4.640003,0.115000,2.950003,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+14.600000,1.553067,0.573069,2.100001,4.200003,1.500000,0.490000,4.640003,0.115000,2.950003,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+14.700000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640003,0.115000,2.950003,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.330000
+14.800000,1.553067,0.573069,2.100000,4.200001,1.500001,0.490000,4.640005,0.115000,2.950003,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.330000
+14.900000,1.553067,0.573069,2.100000,4.200001,1.500001,0.490000,4.640006,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.330000
+15.000000,1.553067,0.573069,2.100000,4.200001,1.500000,0.490000,4.640006,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237917,16.451410,4.195996,1.684783,1.288364,5.203581,0.330000
+15.100000,1.553067,0.573069,2.100000,4.200001,1.500000,0.490000,4.640006,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237917,16.451410,4.195996,1.684783,1.288364,5.203581,0.330000
+15.200000,1.553067,0.573069,2.100001,4.200001,1.500000,0.490000,4.640006,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+15.300000,1.553067,0.573069,2.100001,4.200001,1.500000,0.490000,4.640006,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+15.400000,1.553067,0.573069,2.100001,4.200002,1.500000,0.490000,4.640006,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+15.500000,1.553067,0.573069,2.100001,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+15.600000,1.553067,0.573069,2.100001,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+15.700000,1.553067,0.573069,2.100001,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+15.800000,1.553067,0.573069,2.100001,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+15.900000,1.553067,0.573069,2.100001,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+16.000000,1.553067,0.573069,2.100001,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+16.100000,1.553067,0.573069,2.100001,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+16.200000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+16.300000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+16.400000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+16.500000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+16.600000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+16.700000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+16.800000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+16.900000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+17.000000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+17.100000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+17.200000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+17.300000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+17.400000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+17.500000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+17.600000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+17.700000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+17.800000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+17.900000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+18.000000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+18.100000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+18.200000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+18.300000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+18.400000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+18.500000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+18.600000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+18.700000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+18.800000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+18.900000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+19.000000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+19.100000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+19.200000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+19.300000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+19.400000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+19.500000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+19.600000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+19.700000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+19.800000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+19.900000,1.553067,0.573069,2.100000,4.200002,1.500000,0.490000,4.640005,0.115000,2.950004,0.650000,0.000270,0.330000,0.040000,8.699945,1.481534,19.237916,16.451410,4.195996,1.684783,1.288364,5.203581,0.329999
+20.000000,2.802425,1.232681,2.075232,4.104630,1.513974,0.477919,5.185798,0.121745,3.121903,0.637149,0.000271,0.342851,0.040915,14.557730,1.515910,19.481450,16.647280,4.332919,1.734484,1.326834,5.192535,0.340794
+20.100000,2.802683,1.209398,2.199515,4.265940,1.439794,0.502647,5.020791,0.119566,3.080558,0.648304,0.000295,0.331696,0.040709,14.567484,1.524012,19.471675,16.647572,4.342754,1.734547,1.326577,5.192536,0.290692
+20.200000,2.802902,1.178362,2.237930,4.455817,1.416189,0.526356,4.717573,0.115638,2.988633,0.659194,0.000302,0.320806,0.040412,14.527589,1.535392,19.455720,16.647469,4.332007,1.734608,1.326763,5.192536,0.275881
+20.300000,2.802827,1.170472,2.128955,4.472508,1.483387,0.521786,4.581792,0.113966,2.936181,0.657470,0.000278,0.322530,0.040345,14.474939,1.537925,19.449758,16.647024,4.309474,1.734610,1.327264,5.192536,0.317658
+20.400000,2.802505,1.195410,1.989129,4.300739,1.563080,0.495650,4.747157,0.116262,2.979227,0.645432,0.000253,0.334568,0.040568,14.462228,1.528474,19.460818,16.646679,4.297353,1.734552,1.327574,5.192536,0.377791
+20.500000,2.802307,1.225051,1.953956,4.128013,1.581602,0.475004,5.018617,0.119758,3.062456,0.635810,0.000249,0.344190,0.040825,14.494415,1.518329,19.475465,16.646743,4.305450,1.734487,1.327429,5.192535,0.394443
+20.600000,2.802355,1.235529,2.028097,4.079927,1.540800,0.472921,5.181678,0.121735,3.117421,0.634881,0.000262,0.345119,0.040933,14.542711,1.514942,19.482047,16.647115,4.325391,1.734472,1.327004,5.192535,0.361103
+20.700000,2.802575,1.220685,2.155018,4.190202,1.466907,0.491633,5.112745,0.120763,3.105402,0.643333,0.000287,0.336667,0.040813,14.569708,1.520026,19.476759,16.647495,4.341130,1.734519,1.326633,5.192535,0.308076
+20.800000,2.802839,1.189413,2.240305,4.392317,1.414517,0.519331,4.833687,0.117140,3.025556,0.655909,0.000303,0.324091,0.040518,14.547797,1.531299,19.461747,16.647564,4.338561,1.734589,1.326635,5.192536,0.275178
+20.900000,2.802900,1.169119,2.184991,4.494852,1.449402,0.527525,4.596653,0.114105,2.945486,0.659963,0.000289,0.320037,0.040328,14.492783,1.538660,19.449863,16.647213,4.318176,1.734618,1.327063,5.192536,0.295607
+21.000000,2.802635,1.183272,2.035278,4.378156,1.537621,0.506389,4.656387,0.115038,2.953279,0.650439,0.000261,0.329561,0.040463,14.460959,1.532908,19.455173,16.646772,4.299702,1.734579,1.327506,5.192536,0.357101
+21.100000,2.802354,1.214991,1.952725,4.184561,1.582429,0.481212,4.916451,0.118466,3.030481,0.638684,0.000248,0.341316,0.040736,14.478122,1.521683,19.470327,16.646669,4.300173,1.734509,1.327535,5.192535,0.394846
+21.200000,2.802311,1.234437,1.989304,4.079975,1.562329,0.471186,5.141349,0.121266,3.102551,0.634077,0.000255,0.345923,0.040917,14.524442,1.515275,19.480812,16.646951,4.317224,1.734470,1.327181,5.192535,0.378367
+21.300000,2.802475,1.229265,2.104612,4.129993,1.496881,0.482225,5.170161,0.121525,3.119226,0.639093,0.000277,0.340907,0.040887,14.564087,1.517070,19.480249,16.647368,4.336595,1.734495,1.326748,5.192535,0.328507
+21.400000,2.802744,1.202099,2.219752,4.313315,1.427280,0.509172,4.955525,0.118719,3.061955,0.651263,0.000299,0.328737,0.040640,14.562427,1.526644,19.468179,16.647589,4.342177,1.734563,1.326577,5.192536,0.282968
+21.500000,2.802917,1.173538,2.225037,4.480225,1.424399,0.528311,4.661474,0.114917,2.969646,0.660163,0.000299,0.319837,0.040367,14.514620,1.537156,19.452887,16.647387,4.327215,1.734615,1.326864,5.192536,0.280564
+21.600000,2.802763,1.173877,2.093448,4.444407,1.504331,0.516716,4.596749,0.114199,2.938286,0.655187,0.000271,0.324813,0.040378,14.467603,1.536526,19.451059,16.646921,4.305158,1.734601,1.327368,5.192536,0.332222
+21.700000,2.802440,1.202837,1.970313,4.255705,1.573189,0.489834,4.807946,0.117063,2.997348,0.642710,0.000250,0.337290,0.040632,14.466356,1.525853,19.464370,16.646657,4.297512,1.734535,1.327580,5.192536,0.386497
+21.800000,2.802298,1.229504,1.962659,4.104061,1.576866,0.472715,5.070485,0.120403,3.079061,0.634762,0.000250,0.345238,0.040866,14.505186,1.516870,19.477865,16.646809,4.309427,1.734478,1.327347,5.192535,0.390476
+21.900000,2.802392,1.234336,2.054718,4.091360,1.525739,0.475446,5.188561,0.121797,3.121324,0.636022,0.000267,0.343978,0.040928,14.551979,1.515347,19.481926,16.647212,4.329898,1.734478,1.326903,5.192535,0.349544
+22.000000,2.802637,1.214387,2.181953,4.232824,1.450564,0.497917,5.062934,0.120113,3.092173,0.646169,0.000292,0.333831,0.040756,14.569420,1.522236,19.473976,16.647547,4.342451,1.734535,1.326593,5.192535,0.297483
+22.100000,2.802880,1.182686,2.241816,4.431781,1.413660,0.523883,4.764357,0.116242,3.003807,0.658023,0.000303,0.321977,0.040454,14.536584,1.533791,19.458134,16.647517,4.335059,1.734601,1.326701,5.192536,0.274525
+22.200000,2.802864,1.169223,2.153741,4.485994,1.468495,0.524699,4.582031,0.113944,2.938226,0.658756,0.000283,0.321244,0.040332,14.481834,1.538492,19.449453,16.647104,4.313009,1.734615,1.327181,5.192536,0.307764
+22.300000,2.802558,1.190122,2.006731,4.333784,1.553474,0.500114,4.706342,0.115716,2.967350,0.647518,0.000256,0.332482,0.040523,14.460865,1.530380,19.458335,16.646711,4.297969,1.734564,1.327553,5.192536,0.369795
+22.400000,2.802321,1.221132,1.951355,4.149754,1.583056,0.477303,4.977086,0.119236,3.049369,0.636871,0.000248,0.343129,0.040790,14.487210,1.519626,19.473434,16.646706,4.302975,1.734496,1.327479,5.192535,0.395589
+22.500000,2.802332,1.235527,2.010586,4.077071,1.550579,0.471807,5.168659,0.121588,3.112287,0.634370,0.000259,0.345630,0.040930,14.535334,1.514932,19.481736,16.647045,4.321979,1.734470,1.327078,5.192535,0.368835
+22.600000,2.802531,1.224666,2.134107,4.162629,1.479439,0.487415,5.141318,0.121139,3.112578,0.641432,0.000282,0.338568,0.040848,14.568254,1.518646,19.478432,16.647447,4.339529,1.734508,1.326675,5.192535,0.316454
+22.700000,2.802801,1.194687,2.234063,4.360033,1.418382,0.515305,4.885558,0.117812,3.041309,0.654057,0.000302,0.325943,0.040570,14.554817,1.529353,19.464475,16.647583,4.340467,1.734579,1.326601,5.192536,0.277555
+22.800000,2.802914,1.170343,2.204276,4.493010,1.437439,0.528478,4.618596,0.114373,2.954151,0.660328,0.000293,0.319672,0.040341,14.501789,1.538277,19.450825,16.647290,4.322041,1.734619,1.326976,5.192536,0.288286
+22.900000,2.802690,1.178866,2.058860,4.408146,1.524281,0.510889,4.626765,0.114627,2.945419,0.652519,0.000265,0.327481,0.040424,14.462889,1.534576,19.453200,16.646829,4.301672,1.734589,1.327454,5.192536,0.346859
+23.000000,2.802385,1.210046,1.957883,4.213162,1.579756,0.484593,4.870842,0.117880,3.016455,0.640261,0.000248,0.339739,0.040693,14.472607,1.523363,19.467882,16.646657,4.298720,1.734520,1.327561,5.192535,0.392362
+23.100000,2.802301,1.232793,1.976485,4.087404,1.569344,0.471456,5.114689,0.120944,3.093551,0.634192,0.000253,0.345808,0.040899,14.516398,1.515802,19.479763,16.646888,4.313849,1.734473,1.327253,5.192535,0.384172
+23.200000,2.802437,1.231841,2.083216,4.110968,1.509357,0.479020,5.182559,0.121698,3.121476,0.637648,0.000272,0.342352,0.040909,14.559721,1.516194,19.481174,16.647306,4.333985,1.734487,1.326809,5.192535,0.337427
+23.300000,2.802699,1.207425,2.205459,4.278831,1.436129,0.504444,5.003464,0.119341,3.075674,0.649118,0.000297,0.330882,0.040690,14.566411,1.524719,19.470744,16.647580,4.342695,1.734552,1.326574,5.192536,0.288412
+23.400000,2.802907,1.176930,2.235055,4.463322,1.418029,0.527025,4.701358,0.115429,2.983227,0.659518,0.000301,0.320482,0.040398,14.524168,1.535917,19.454896,16.647449,4.330747,1.734611,1.326788,5.192536,0.276916
+23.500000,2.802810,1.171270,2.119253,4.465519,1.489155,0.520467,4.584680,0.114014,2.936359,0.656880,0.000276,0.323120,0.040353,14.472849,1.537589,19.450046,16.646996,4.308247,1.734609,1.327293,5.192536,0.321592
+23.600000,2.802486,1.197447,1.983521,4.288272,1.566110,0.494019,4.763573,0.116479,2.984094,0.644668,0.000252,0.335332,0.040586,14.463308,1.527749,19.461791,16.646673,4.297328,1.734548,1.327577,5.192536,0.380370
+23.700000,2.802302,1.226351,1.955952,4.120942,1.580514,0.474304,5.033313,0.119942,3.067140,0.635489,0.000249,0.344511,0.040837,14.497432,1.517900,19.476158,16.646761,4.306509,1.734485,1.327407,5.192535,0.393535
+23.800000,2.802363,1.235303,2.035189,4.082413,1.536812,0.473527,5.184530,0.121764,3.118766,0.635157,0.000264,0.344843,0.040932,14.545459,1.515020,19.482061,16.647143,4.326656,1.734474,1.326975,5.192535,0.358000
+23.900000,2.802590,1.219030,2.162564,4.201468,1.462351,0.493311,5.100021,0.120597,3.102075,0.644089,0.000288,0.335911,0.040798,14.569961,1.520603,19.476040,16.647512,4.341580,1.734524,1.326619,5.192535,0.305085
+24.000000,2.802850,1.187525,2.241341,4.403557,1.413889,0.520664,4.814516,0.116892,3.019607,0.656526,0.000303,0.323474,0.040500,14.544990,1.531997,19.460747,16.647554,4.337687,1.734593,1.326650,5.192536,0.274771
+24.100000,2.802890,1.168997,2.176840,4.493373,1.454416,0.526874,4.591376,0.114044,2.943116,0.659690,0.000288,0.320310,0.040327,14.489809,1.538671,19.449677,16.647185,4.316762,1.734618,1.327094,5.192536,0.298744
+24.200000,2.802612,1.185084,2.027143,4.366231,1.542172,0.504675,4.669359,0.115215,2.956883,0.649642,0.000259,0.330358,0.040480,14.460877,1.532231,19.456007,16.646755,4.299161,1.734575,1.327519,5.192536,0.360685
+24.300000,2.802342,1.216729,1.951900,4.174644,1.582840,0.480079,4.933261,0.118680,3.035702,0.638158,0.000248,0.341842,0.040751,14.480646,1.521097,19.471203,16.646679,4.300889,1.734506,1.327520,5.192535,0.395260
+24.400000,2.802314,1.234832,1.994839,4.078564,1.559288,0.471272,5.149625,0.121364,3.105442,0.634119,0.000256,0.345881,0.040921,14.527599,1.515149,19.481110,16.646978,4.318530,1.734471,1.327152,5.192535,0.375873
+24.500000,2.802489,1.228099,2.112672,4.138337,1.492143,0.483572,5.163332,0.121432,3.117726,0.639701,0.000278,0.340299,0.040878,14.565553,1.517466,19.479803,16.647392,4.337468,1.734499,1.326725,5.192535,0.325185
+24.600000,2.802759,1.200078,2.224162,4.326162,1.424543,0.510884,4.936749,0.118476,3.056473,0.652041,0.000300,0.327959,0.040621,14.560703,1.527378,19.467185,16.647591,4.341811,1.734568,1.326580,5.192536,0.281295
+24.700000,2.802916,1.172525,2.219987,4.484691,1.427587,0.528503,4.648612,0.114754,2.965102,0.660275,0.000297,0.319725,0.040357,14.511237,1.537516,19.452258,16.647363,4.325834,1.734617,1.326892,5.192536,0.282426
+24.800000,2.802742,1.175132,2.083827,4.435001,1.509922,0.515161,4.603912,0.114302,2.939877,0.654478,0.000269,0.325522,0.040390,14.466267,1.536029,19.451588,16.646896,4.304145,1.734599,1.327392,5.192536,0.336251
+24.900000,2.802422,1.204841,1.966440,4.243792,1.575244,0.488348,4.825143,0.117287,3.002552,0.642015,0.000250,0.337985,0.040649,14.468092,1.525155,19.465345,16.646657,4.297780,1.734532,1.327575,5.192536,0.388316
+25.000000,2.802296,1.230491,1.966105,4.098955,1.574995,0.472295,5.083197,0.120559,3.083200,0.634571,0.000251,0.345429,0.040876,14.508403,1.516548,19.478424,16.646831,4.310622,1.734478,1.327320,5.192535,0.388901
+25.100000,2.802402,1.233750,2.062381,4.096103,1.521361,0.476341,5.187929,0.121783,3.121657,0.636435,0.000269,0.343565,0.040923,14.554385,1.515547,19.481767,16.647239,4.331063,1.734481,1.326875,5.192535,0.346258
+25.200000,2.802652,1.212533,2.188673,4.245147,1.446453,0.499686,5.047436,0.119912,3.087927,0.646964,0.000293,0.333036,0.040738,14.568988,1.522892,19.473129,16.647559,4.342615,1.734541,1.326585,5.192535,0.294875
+25.300000,2.802886,1.181025,2.240646,4.441096,1.414428,0.524862,4.746540,0.116012,2.998062,0.658484,0.000303,0.321516,0.040438,14.533442,1.534405,19.457216,16.647502,4.333949,1.734605,1.326722,5.192536,0.274926
+25.400000,2.802848,1.169635,2.144469,4.481227,1.474091,0.523635,4.581460,0.113946,2.937299,0.658289,0.000281,0.321711,0.040336,14.479383,1.538298,19.449541,16.647075,4.311676,1.734615,1.327211,5.192536,0.311439
+25.500000,2.802535,1.192113,1.999926,4.321268,1.557202,0.498413,4.721658,0.115921,2.971796,0.646723,0.000255,0.333277,0.040540,14.461542,1.529657,19.459273,16.646701,4.297724,1.734560,1.327560,5.192536,0.372872
+25.600000,2.802313,1.222640,1.952206,4.141361,1.582577,0.476409,4.992941,0.119436,3.054363,0.636458,0.000248,0.343542,0.040804,14.490138,1.519124,19.474217,16.646721,4.303910,1.734494,1.327459,5.192535,0.395217
+25.700000,2.802338,1.235563,2.017126,4.077910,1.546939,0.472195,5.173920,0.121648,3.114325,0.634548,0.000260,0.345452,0.040932,14.538378,1.514923,19.481873,16.647074,4.323288,1.734472,1.327048,5.192535,0.365935
+25.800000,2.802545,1.223195,2.142030,4.172826,1.474707,0.488981,5.130943,0.121002,3.109996,0.642138,0.000284,0.337862,0.040835,14.569117,1.519153,19.477822,16.647468,4.340176,1.734514,1.326657,5.192535,0.313263
+25.900000,2.802813,1.192691,2.236643,4.372292,1.416785,0.516845,4.866056,0.117560,3.035412,0.654766,0.000303,0.325234,0.040550,14.552481,1.530086,19.463452,16.647579,4.339797,1.734584,1.326611,5.192536,0.276572
+26.000000,2.802907,1.169822,2.197228,4.494092,1.441827,0.528174,4.609841,0.114267,2.950748,0.660217,0.000292,0.319783,0.040333,14.498613,1.538443,19.450437,16.647264,4.320602,1.734620,1.327007,5.192536,0.290945
+26.100000,2.802666,1.180497,2.049862,4.396929,1.529395,0.509192,4.637665,0.114779,2.948286,0.651735,0.000263,0.328265,0.040439,14.462347,1.533953,19.453933,16.646810,4.300918,1.734587,1.327472,5.192536,0.350743
+26.200000,2.802370,1.211932,1.955767,4.202219,1.580862,0.483293,4.888143,0.118103,3.021771,0.639657,0.000248,0.340343,0.040708,14.474907,1.522720,19.468815,16.646663,4.299261,1.734517,1.327550,5.192535,0.393371
+26.300000,2.802301,1.233445,1.981246,4.084394,1.566746,0.471327,5.125013,0.121070,3.097025,0.634133,0.000254,0.345867,0.040905,14.519712,1.515588,19.480181,16.646914,4.315136,1.734474,1.327224,5.192535,0.382008
+26.400000,2.802449,1.230906,2.091265,4.117886,1.504682,0.480196,5.178319,0.121638,3.120755,0.638179,0.000274,0.341821,0.040901,14.561698,1.516510,19.480847,16.647332,4.335006,1.734492,1.326783,5.192535,0.334054
+26.500000,2.802713,1.205442,2.211030,4.291701,1.432687,0.506220,4.985790,0.119112,3.070645,0.649923,0.000298,0.330077,0.040671,14.565302,1.525432,19.469799,16.647587,4.342564,1.734558,1.326572,5.192536,0.286284
+26.600000,2.802908,1.175594,2.231753,4.470150,1.420135,0.527591,4.685943,0.115231,2.978033,0.659797,0.000300,0.320203,0.040386,14.520905,1.536405,19.454119,16.647429,4.329474,1.734614,1.326814,5.192536,0.278112
+26.700000,2.802790,1.172141,2.109689,4.458194,1.494808,0.519126,4.588272,0.114071,2.936782,0.656277,0.000274,0.323723,0.040362,14.471035,1.537228,19.450374,16.646970,4.307072,1.734608,1.327320,5.192536,0.325503
+26.800000,2.802465,1.199453,1.978231,4.276054,1.568958,0.492432,4.779870,0.116694,2.988938,0.643926,0.000251,0.336074,0.040603,14.464578,1.527038,19.462750,16.646668,4.297342,1.734545,1.327577,5.192536,0.382812
+26.900000,2.802297,1.227596,1.958109,4.114200,1.579338,0.473648,5.047604,0.120119,3.071703,0.635188,0.000249,0.344812,0.040849,14.500553,1.517491,19.476827,16.646780,4.307573,1.734484,1.327383,5.192535,0.392553
+27.000000,2.802371,1.235026,2.042315,4.085215,1.532786,0.474172,5.186847,0.121787,3.119954,0.635452,0.000265,0.344548,0.040931,14.548237,1.515114,19.482052,16.647171,4.327893,1.734477,1.326946,5.192535,0.354899
+27.100000,2.802605,1.217351,2.169969,4.212862,1.457863,0.495001,5.086915,0.120425,3.098620,0.644851,0.000289,0.335149,0.040782,14.570199,1.521190,19.475305,16.647528,4.341979,1.734530,1.326606,5.192535,0.302169
+27.200000,2.802859,1.185669,2.242070,4.414522,1.413454,0.521949,4.795551,0.116646,3.013689,0.657121,0.000303,0.322879,0.040482,14.542223,1.532684,19.459758,16.647544,4.336776,1.734598,1.326666,5.192536,0.274477
+27.300000,2.802879,1.168941,2.168534,4.491484,1.459501,0.526174,4.586669,0.113990,2.940919,0.659393,0.000286,0.320607,0.040328,14.486969,1.538657,19.449524,16.647157,4.315348,1.734619,1.327125,5.192536,0.301965
+27.400000,2.802589,1.186916,2.019175,4.354281,1.546605,0.502969,4.682542,0.115395,2.960566,0.648849,0.000258,0.331151,0.040495,14.460936,1.531552,19.456850,16.646740,4.298642,1.734573,1.327532,5.192536,0.364220
+27.500000,2.802331,1.218432,1.951263,4.164956,1.583150,0.478981,4.949877,0.118892,3.040864,0.637648,0.000248,0.342352,0.040766,14.483252,1.520525,19.472062,16.646690,4.301615,1.734504,1.327505,5.192535,0.395587
+27.600000,2.802318,1.235180,2.000474,4.077445,1.556180,0.471397,5.157490,0.121458,3.108214,0.634178,0.000257,0.345822,0.040925,14.530772,1.515038,19.481387,16.647005,4.319820,1.734472,1.327123,5.192535,0.373346
+27.700000,2.802501,1.226889,2.120726,4.146971,1.487387,0.484957,5.155961,0.121333,3.116064,0.640325,0.000280,0.339675,0.040867,14.566962,1.517880,19.479333,16.647416,4.338297,1.734504,1.326704,5.192535,0.321887
+27.800000,2.802772,1.198054,2.228308,4.338972,1.421964,0.512578,4.917785,0.118230,3.050901,0.652814,0.000301,0.327186,0.040601,14.558900,1.528117,19.466180,16.647592,4.341385,1.734574,1.326585,5.192536,0.279728
+27.900000,2.802914,1.171586,2.214611,4.488645,1.430971,0.528618,4.636368,0.114598,2.960725,0.660352,0.000296,0.319648,0.040349,14.507901,1.537849,19.451665,16.647339,4.324433,1.734620,1.326922,5.192536,0.284419
+28.000000,2.802720,1.176425,2.074350,4.425460,1.515403,0.513605,4.611451,0.114411,2.941609,0.653767,0.000268,0.326233,0.040402,14.465041,1.535519,19.452139,16.646872,4.303155,1.734597,1.327416,5.192536,0.340247
+28.100000,2.802405,1.206819,1.962750,4.232069,1.577198,0.486892,4.842207,0.117509,3.007719,0.641334,0.000249,0.338666,0.040666,14.469866,1.524470,19.466306,16.646657,4.298058,1.734529,1.327570,5.192536,0.390052
+28.200000,2.802294,1.231442,1.969644,4.094068,1.573069,0.471903,5.095636,0.120712,3.087257,0.634394,0.000252,0.345606,0.040885,14.511611,1.516238,19.478967,16.646854,4.311807,1.734478,1.327295,5.192535,0.387287
+28.300000,2.802413,1.233123,2.070104,4.101119,1.516928,0.477276,5.186847,0.121762,3.121864,0.636859,0.000270,0.343141,0.040918,14.556731,1.515759,19.481590,16.647267,4.332197,1.734485,1.326849,5.192535,0.342968
+28.400000,2.802667,1.210649,2.195279,4.257646,1.442400,0.501469,5.031509,0.119705,3.083533,0.647771,0.000295,0.332229,0.040720,14.568430,1.523563,19.472263,16.647570,4.342724,1.734547,1.326578,5.192536,0.292322
+28.500000,2.802893,1.179399,2.239148,4.450121,1.415401,0.525789,4.728936,0.115785,2.992348,0.658924,0.000302,0.321076,0.040422,14.530229,1.535007,19.456309,16.647485,4.332796,1.734609,1.326745,5.192536,0.275451
+28.600000,2.802832,1.170105,2.135154,4.476156,1.479684,0.522541,4.581370,0.113954,2.936533,0.657805,0.000279,0.322195,0.040341,14.476969,1.538085,19.449658,16.647047,4.310346,1.734614,1.327242,5.192536,0.315163
+28.700000,2.802514,1.194098,1.993307,4.308863,1.560812,0.496738,4.736971,0.116126,2.976250,0.645940,0.000254,0.334060,0.040557,14.462220,1.528942,19.460207,16.646691,4.297489,1.734557,1.327568,5.192536,0.375881
+28.800000,2.802306,1.224113,1.953171,4.133185,1.582037,0.475544,5.008552,0.119632,3.059280,0.636059,0.000248,0.343941,0.040817,14.493011,1.518637,19.474981,16.646737,4.304836,1.734492,1.327440,5.192535,0.394792
+28.900000,2.802345,1.235563,2.023709,4.078987,1.543260,0.472615,5.178812,0.121703,3.116254,0.634741,0.000262,0.345259,0.040933,14.541315,1.514927,19.481991,16.647101,4.324569,1.734475,1.327020,5.192535,0.363031
+29.000000,2.802560,1.221693,2.149905,4.183227,1.469984,0.490572,5.120152,0.120860,3.107285,0.642855,0.000286,0.337145,0.040822,14.569818,1.519673,19.477192,16.647487,4.340774,1.734519,1.326641,5.192535,0.310111
+29.100000,2.802825,1.190702,2.238981,4.384460,1.415336,0.518362,4.846492,0.117306,3.029469,0.655463,0.000303,0.324537,0.040531,14.549984,1.530820,19.462425,16.647573,4.339073,1.734589,1.326624,5.192536,0.275683
+29.200000,2.802900,1.169364,2.189935,4.494754,1.446348,0.527809,4.601610,0.114166,2.947492,0.660076,0.000291,0.319924,0.040330,14.495371,1.538586,19.450077,16.647236,4.319142,1.734621,1.327039,5.192536,0.293717
+29.300000,2.802644,1.182166,2.040971,4.385585,1.534419,0.507493,4.648903,0.114935,2.951273,0.650950,0.000262,0.329050,0.040454,14.461779,1.533322,19.454682,16.646789,4.300176,1.734584,1.327491,5.192536,0.354610
+29.400000,2.802356,1.213789,1.953876,4.191476,1.581836,0.482025,4.905315,0.118323,3.027054,0.639063,0.000248,0.340937,0.040726,14.477146,1.522088,19.469738,16.646670,4.299813,1.734514,1.327539,5.192535,0.394288
+29.500000,2.802303,1.234056,1.986080,4.081639,1.564099,0.471231,5.135003,0.121190,3.100399,0.634096,0.000255,0.345904,0.040912,14.522877,1.515395,19.480570,16.646940,4.316405,1.734474,1.327197,5.192535,0.379821
+29.600000,2.802461,1.229925,2.099327,4.125119,1.499977,0.481411,5.173541,0.121571,3.119875,0.638727,0.000276,0.341273,0.040893,14.563470,1.516843,19.480496,16.647357,4.335982,1.734496,1.326760,5.192535,0.330696
+29.700000,2.802729,1.203418,2.216362,4.304783,1.429386,0.508008,4.967528,0.118875,3.065410,0.650734,0.000299,0.329266,0.040652,14.563892,1.526163,19.468825,16.647592,4.342348,1.734563,1.326573,5.192536,0.284253
+29.800000,2.802910,1.174332,2.227725,4.476351,1.422698,0.528038,4.670987,0.115039,2.972914,0.660026,0.000299,0.319974,0.040374,14.517386,1.536866,19.453368,16.647407,4.328110,1.734617,1.326843,5.192536,0.279577
+29.900000,2.802770,1.173190,2.099792,4.449813,1.500622,0.517657,4.593404,0.114148,2.937685,0.655613,0.000272,0.324387,0.040372,14.469247,1.536801,19.450792,16.646943,4.305912,1.734606,1.327348,5.192536,0.329586
+30.000000,4.707406,2.067248,2.100316,4.132511,1.499337,0.482211,5.320994,0.123296,3.165687,0.636383,0.000278,0.343617,0.041176,19.364770,1.532642,19.568670,16.721140,4.386919,1.753622,1.341603,5.188295,0.330348
+30.100000,4.707866,2.028684,2.235482,4.339718,1.417361,0.513012,5.079267,0.120175,3.102558,0.650251,0.000305,0.329749,0.040899,19.364878,1.543379,19.555140,16.721404,4.393989,1.753702,1.341391,5.188296,0.277157
+30.200000,4.708326,1.981187,2.249424,4.540681,1.409032,0.536579,4.727895,0.115668,2.994029,0.661095,0.000306,0.318905,0.040573,19.309926,1.555978,19.537034,16.721182,4.377072,1.753765,1.341710,5.188296,0.271545
+30.300000,4.708270,1.973145,2.097493,4.508569,1.502060,0.524008,4.636760,0.114630,2.952595,0.655719,0.000273,0.324281,0.040570,19.253322,1.555818,19.534197,16.720632,4.350927,1.753751,1.342308,5.188296,0.330447
+30.400000,4.707733,2.014264,1.949975,4.292369,1.584134,0.492959,4.875723,0.117858,3.018551,0.641298,0.000248,0.338702,0.040857,19.249448,1.543482,19.549530,16.720308,4.341058,1.753675,1.342576,5.188296,0.395891
+30.500000,4.707318,2.058905,1.935263,4.114409,1.591397,0.472670,5.182023,0.121723,3.112735,0.631922,0.000247,0.348078,0.041130,19.292315,1.532981,19.565221,16.720466,4.353913,1.753606,1.342327,5.188295,0.403341
+30.600000,4.707291,2.073519,2.033972,4.085846,1.537427,0.473780,5.337472,0.123555,3.166074,0.632551,0.000265,0.347449,0.041220,19.347085,1.530608,19.570600,16.720924,4.377498,1.753600,1.341819,5.188295,0.358602
+30.700000,4.707628,2.049825,2.180393,4.231765,1.451446,0.497630,5.221241,0.121996,3.141504,0.643322,0.000294,0.336678,0.041051,19.372447,1.537548,19.562752,16.721333,4.393636,1.753663,1.341430,5.188295,0.298162
+30.800000,4.708149,2.001003,2.265863,4.466217,1.398314,0.529202,4.878850,0.117602,3.042992,0.657618,0.000310,0.322382,0.040703,19.339836,1.550916,19.544701,16.721348,4.387467,1.753743,1.341499,5.188296,0.265823
+30.900000,4.708381,1.969470,2.180377,4.558422,1.452343,0.534300,4.628768,0.114441,2.956578,0.660294,0.000290,0.319706,0.040518,19.274628,1.558080,19.532597,16.720891,4.362228,1.753768,1.342040,5.188297,0.297281
+31.000000,4.707999,1.991822,2.004038,4.398437,1.555073,0.507089,4.740517,0.116072,2.979158,0.647911,0.000256,0.332089,0.040711,19.243868,1.549674,19.541346,16.720399,4.342540,1.753714,1.342521,5.188296,0.370889
+31.100000,4.707464,2.040921,1.924866,4.181351,1.597059,0.479658,5.049857,0.120083,3.071446,0.635106,0.000245,0.344894,0.041020,19.268825,1.536955,19.558948,16.720338,4.345710,1.753632,1.342494,5.188295,0.408075
+31.200000,4.707254,2.071528,1.978215,4.077083,1.568289,0.470318,5.295076,0.123082,3.149707,0.630923,0.000255,0.349077,0.041208,19.323130,1.530556,19.569705,16.720697,4.366482,1.753593,1.342060,5.188295,0.383497
+31.300000,4.707435,2.065224,2.113030,4.145017,1.491871,0.484262,5.311210,0.123165,3.163654,0.637308,0.000280,0.342692,0.041161,19.367038,1.533231,19.568011,16.721176,4.388345,1.753627,1.341568,5.188295,0.325099
+31.400000,4.707911,2.024410,2.243254,4.360430,1.412491,0.515824,5.049197,0.119789,3.093952,0.651522,0.000306,0.328478,0.040869,19.362068,1.544554,19.553560,16.721406,4.393477,1.753709,1.341396,5.188296,0.274256
+31.500000,4.708347,1.978332,2.242015,4.549165,1.413768,0.537066,4.705389,0.115382,2.986242,0.661350,0.000304,0.318650,0.040556,19.304126,1.556638,19.535929,16.721141,4.374847,1.753767,1.341758,5.188296,0.274217
+31.600000,4.708236,1.975126,2.081784,4.494274,1.511205,0.521579,4.646800,0.114777,2.954644,0.654613,0.000270,0.325387,0.040587,19.250617,1.555061,19.534983,16.720589,4.349187,1.753747,1.342350,5.188296,0.337011
+31.700000,4.707686,2.018575,1.943156,4.273478,1.587703,0.490586,4.902686,0.118208,3.026618,0.640187,0.000247,0.339813,0.040884,19.251608,1.542373,19.551070,16.720302,4.341332,1.753668,1.342573,5.188296,0.399142
+31.800000,4.707300,2.061562,1.939862,4.105325,1.588940,0.471850,5.203362,0.121983,3.119524,0.631556,0.000248,0.348444,0.041146,19.297006,1.532429,19.566151,16.720496,4.355715,1.753602,1.342289,5.188295,0.401199
+31.900000,4.707307,2.073008,2.045590,4.091521,1.530863,0.474956,5.339229,0.123567,3.167379,0.633092,0.000267,0.346908,0.041217,19.350928,1.530827,19.570468,16.720965,4.379409,1.753603,1.341776,5.188295,0.353548
+32.000000,4.707670,2.046287,2.191912,4.250568,1.444392,0.500399,5.198508,0.121704,3.135499,0.644568,0.000296,0.335432,0.041026,19.372051,1.538529,19.561504,16.721353,4.394104,1.753670,1.341414,5.188295,0.293697
+32.100000,4.708188,1.996908,2.265959,4.483143,1.398298,0.531125,4.848216,0.117209,3.033406,0.658506,0.000310,0.321494,0.040675,19.334673,1.552004,19.543122,16.721324,4.385824,1.753748,1.341530,5.188296,0.265744
+32.200000,4.708372,1.969176,2.166011,4.553403,1.461136,0.532884,4.623764,0.114390,2.953796,0.659682,0.000287,0.320318,0.040521,19.269871,1.557933,19.532515,16.720841,4.359953,1.753766,1.342092,5.188297,0.302853
+32.300000,4.707950,1.995698,1.991936,4.378912,1.561688,0.504370,4.763250,0.116377,2.985600,0.646640,0.000254,0.333360,0.040738,19.243978,1.548543,19.542783,16.720374,4.341862,1.753707,1.342540,5.188296,0.376376
+32.400000,4.707431,2.044658,1.924724,4.166829,1.597089,0.478047,5.075976,0.120410,3.079519,0.634365,0.000245,0.345635,0.041043,19.272760,1.536099,19.560252,16.720355,4.346972,1.753626,1.342468,5.188295,0.408187
+32.500000,4.707255,2.072518,1.987372,4.075826,1.563292,0.470573,5.306990,0.123221,3.153878,0.631051,0.000257,0.348949,0.041214,19.327806,1.530417,19.570078,16.720738,4.368550,1.753593,1.342015,5.188295,0.379337
+32.600000,4.707466,2.062921,2.125795,4.158757,1.484322,0.486464,5.299183,0.123006,3.160961,0.638301,0.000283,0.341699,0.041145,19.368908,1.533889,19.567246,16.721209,4.389642,1.753633,1.341536,5.188295,0.319883
+32.700000,4.707957,2.020066,2.250001,4.381057,1.408251,0.518571,5.018259,0.119392,3.084974,0.652766,0.000308,0.327234,0.040837,19.358774,1.545745,19.551940,16.721404,4.392763,1.753716,1.341406,5.188296,0.271749
+32.800000,4.708364,1.975829,2.233182,4.555554,1.419385,0.537229,4.685293,0.115128,2.979086,0.661460,0.000302,0.318540,0.040542,19.298329,1.557181,19.534965,16.721098,4.372553,1.753769,1.341807,5.188296,0.277434
+32.900000,4.708199,1.977516,2.066287,4.478564,1.520132,0.519026,4.659514,0.114959,2.957588,0.653444,0.000267,0.326556,0.040607,19.248353,1.554207,19.535917,16.720547,4.347597,1.753741,1.342389,5.188296,0.343582
+33.000000,4.707641,2.022873,1.937463,4.255044,1.590661,0.488313,4.929989,0.118560,3.034842,0.639125,0.000246,0.340875,0.040910,19.254111,1.541289,19.552597,16.720301,4.341789,1.753661,1.342566,5.188295,0.401877
+33.100000,4.707285,2.063968,1.945335,4.097455,1.586017,0.471201,5.223429,0.122227,3.125967,0.631270,0.000249,0.348730,0.041161,19.301761,1.531943,19.566995,16.720529,4.357596,1.753599,1.342249,5.188295,0.398649
+33.200000,4.707325,2.072195,2.057560,4.098559,1.524054,0.476309,5.338822,0.123552,3.168066,0.633708,0.000270,0.346292,0.041210,19.354518,1.531118,19.570233,16.721006,4.381256,1.753606,1.341734,5.188295,0.348386
+33.300000,4.707713,2.042571,2.202922,4.269966,1.437612,0.503216,5.174130,0.121391,3.128948,0.645835,0.000298,0.334165,0.040999,19.371208,1.539553,19.560183,16.721370,4.394404,1.753677,1.341401,5.188295,0.289467
+33.400000,4.708225,1.992965,2.264762,4.498886,1.399109,0.532832,4.818491,0.116827,3.023969,0.659299,0.000310,0.320701,0.040648,19.329310,1.553037,19.541598,16.721298,4.384058,1.753753,1.341565,5.188296,0.266129
+33.500000,4.708357,1.969291,2.151119,4.546542,1.470173,0.531246,4.621511,0.114376,2.951870,0.658964,0.000284,0.321036,0.040527,19.265423,1.557669,19.532594,16.720792,4.357745,1.753764,1.342144,5.188296,0.308708
+33.600000,4.707901,1.999709,1.980702,4.359305,1.567774,0.501695,4.786995,0.116694,2.992418,0.645388,0.000253,0.334612,0.040764,19.244457,1.547403,19.544257,16.720351,4.341352,1.753699,1.342555,5.188296,0.381524
+33.700000,4.707401,2.048223,1.925448,4.153209,1.596669,0.476569,5.101396,0.120727,3.087406,0.633688,0.000245,0.346312,0.041065,19.276840,1.535295,19.561494,16.720374,4.348340,1.753620,1.342441,5.188295,0.407883
+33.800000,4.707259,2.073252,1.996997,4.075746,1.558009,0.470985,5.317247,0.123338,3.157581,0.631250,0.000258,0.348750,0.041219,19.332361,1.530339,19.570365,16.720778,4.370605,1.753593,1.341970,5.188295,0.374994
+33.900000,4.707500,2.060389,2.138465,4.173495,1.476777,0.488787,5.285205,0.122823,3.157678,0.639346,0.000285,0.340654,0.041127,19.370391,1.534606,19.566393,16.721241,4.390807,1.753639,1.341507,5.188295,0.314759
+34.000000,4.708003,2.015702,2.255690,4.401376,1.404667,0.521222,4.986853,0.118989,3.075737,0.653970,0.000309,0.326030,0.040806,19.355055,1.546941,19.550298,16.721397,4.391865,1.753722,1.341419,5.188296,0.269643
+34.100000,4.708377,1.973692,2.223100,4.559874,1.425755,0.537082,4.667722,0.114909,2.972623,0.661431,0.000299,0.318569,0.040531,19.292597,1.557604,19.534148,16.721052,4.370219,1.753769,1.341859,5.188296,0.281146
+34.200000,4.708158,1.980246,2.051213,4.461818,1.528731,0.516399,4.674457,0.115169,2.961295,0.652234,0.000265,0.327766,0.040629,19.246510,1.553280,19.536971,16.720508,4.346161,1.753735,1.342425,5.188296,0.350057
+34.300000,4.707598,2.027105,1.932835,4.237226,1.593044,0.486155,4.957285,0.118908,3.043110,0.638115,0.000245,0.341885,0.040940,19.256887,1.540241,19.554095,16.720302,4.342405,1.753653,1.342556,5.188295,0.404122
+34.400000,4.707274,2.066127,1.951513,4.090734,1.582709,0.470710,5.242169,0.122453,3.132039,0.631058,0.000250,0.348942,0.041174,19.306510,1.531520,19.567753,16.720564,4.359524,1.753596,1.342208,5.188295,0.395779
+34.500000,4.707346,2.071115,2.069761,4.106828,1.517062,0.477822,5.336387,0.123511,3.168172,0.634396,0.000272,0.345604,0.041203,19.357804,1.531474,19.569904,16.721045,4.383019,1.753609,1.341693,5.188295,0.343177
+34.600000,4.707757,2.038703,2.213330,4.289841,1.431169,0.506063,5.148259,0.121059,3.121888,0.647117,0.000300,0.332883,0.040971,19.369867,1.540622,19.558792,16.721384,4.394517,1.753683,1.341393,5.188296,0.285501
+34.700000,4.708259,1.989237,2.262174,4.513124,1.400804,0.534278,4.790167,0.116464,3.014826,0.659979,0.000309,0.320021,0.040623,19.323758,1.553998,19.540152,16.721267,4.382172,1.753756,1.341603,5.188296,0.267022
+34.800000,4.708339,1.969835,2.135931,4.537895,1.479311,0.529407,4.622131,0.114399,2.950862,0.658150,0.000281,0.321850,0.040536,19.261314,1.557287,19.532838,16.720743,4.355632,1.753760,1.342194,5.188296,0.314759
+34.900000,4.707853,2.003796,1.970513,4.339876,1.573248,0.499095,4.811470,0.117018,2.999531,0.644171,0.000251,0.335829,0.040791,19.245272,1.546269,19.545748,16.720333,4.341017,1.753692,1.342567,5.188296,0.386240
+35.000000,4.707374,2.051571,1.927049,4.140667,1.595792,0.475247,5.125810,0.121031,3.095012,0.633090,0.000246,0.346910,0.041084,19.280989,1.534553,19.562659,16.720396,4.349799,1.753615,1.342411,5.188295,0.407159
+35.100000,4.707265,2.073711,2.007003,4.076898,1.552486,0.471556,5.325649,0.123433,3.160751,0.631522,0.000260,0.348478,0.041221,19.336700,1.530325,19.570560,16.720818,4.372620,1.753594,1.341926,5.188295,0.370512
+35.200000,4.707536,2.057650,2.150867,4.189064,1.469341,0.491201,5.269396,0.122617,3.153831,0.640431,0.000288,0.339569,0.041107,19.371425,1.535376,19.565461,16.721269,4.391818,1.753645,1.341481,5.188295,0.309792
+35.300000,4.708048,2.011402,2.260225,4.420983,1.401817,0.523724,4.955620,0.118588,3.066434,0.655109,0.000310,0.324891,0.040776,19.350991,1.548115,19.548670,16.721387,4.390811,1.753728,1.341437,5.188296,0.267959
+35.400000,4.708386,1.971945,2.212109,4.562202,1.432659,0.536660,4.652873,0.114725,2.966945,0.661278,0.000297,0.318722,0.040523,19.287043,1.557908,19.533486,16.721006,4.367904,1.753769,1.341910,5.188296,0.285233
+35.500000,4.708116,1.983225,2.036795,4.444473,1.536876,0.513757,4.691085,0.115399,2.965603,0.651012,0.000262,0.328988,0.040651,19.245050,1.552307,19.538110,16.720471,4.344890,1.753729,1.342458,5.188296,0.356330
+35.600000,4.707557,2.031223,1.929201,4.220200,1.594905,0.484126,4.984240,0.119253,3.051309,0.637175,0.000245,0.342825,0.040961,19.259850,1.539241,19.555544,16.720307,4.343156,1.753646,1.342543,5.188295,0.405895
+35.700000,4.707266,2.068019,1.958330,4.085237,1.579048,0.470383,5.259342,0.122659,3.137664,0.630922,0.000251,0.349078,0.041186,19.311187,1.531159,19.568427,16.720599,4.361479,1.753594,1.342167,5.188295,0.392623
+35.800000,4.707370,2.069765,2.082038,4.116279,1.509979,0.479481,5.331844,0.123445,3.167658,0.635151,0.000274,0.344849,0.041193,19.360731,1.531897,19.569479,16.721083,4.384676,1.753613,1.341655,5.188295,0.337984
+35.900000,4.707802,2.034714,2.222951,4.309980,1.425187,0.508903,5.121108,0.120711,3.114364,0.648396,0.000302,0.331604,0.040943,19.368034,1.541721,19.557346,16.721393,4.394440,1.753690,1.341390,5.188296,0.281862
+36.000000,4.708291,1.985752,2.258013,4.525666,1.403504,0.535430,4.763422,0.116121,3.006021,0.660529,0.000308,0.319471,0.040601,19.318016,1.554874,19.538799,16.721232,4.380156,1.753759,1.341645,5.188296,0.268483
+36.100000,4.708316,1.970880,2.120296,4.527106,1.488629,0.527323,4.626095,0.114467,2.950913,0.657217,0.000277,0.322783,0.040548,19.257601,1.556766,19.533276,16.720695,4.353621,1.753756,1.342242,5.188296,0.321075
+36.200000,4.707805,2.008037,1.961370,4.320300,1.578119,0.496533,4.837260,0.117357,3.007118,0.642970,0.000250,0.337030,0.040818,19.246557,1.545122,19.547285,16.720318,4.340900,1.753684,1.342574,5.188296,0.390511
+36.300000,4.707350,2.054725,1.929771,4.129165,1.594330,0.474082,5.149507,0.121323,3.102453,0.632556,0.000246,0.347444,0.041104,19.285381,1.533868,19.563758,16.720421,4.351409,1.753610,1.342378,5.188295,0.405899
+36.400000,4.707275,2.073840,2.017712,4.079598,1.546535,0.472339,5.331919,0.123501,3.163334,0.631885,0.000262,0.348115,0.041222,19.340928,1.530391,19.570644,16.720860,4.374640,1.753595,1.341882,5.188295,0.365754
+36.500000,4.707574,2.054614,2.163163,4.205876,1.461922,0.493760,5.251139,0.122381,3.149241,0.641581,0.000290,0.338419,0.041086,19.372019,1.536219,19.564418,16.721295,4.392679,1.753651,1.341458,5.188295,0.304915
+36.600000,4.708092,2.007094,2.263504,4.440120,1.399766,0.526097,4.924004,0.118182,3.056881,0.656193,0.000310,0.323807,0.040746,19.346524,1.549282,19.547030,16.721372,4.389566,1.753733,1.341459,5.188296,0.266731
+36.700000,4.708389,1.970610,2.199833,4.562272,1.440317,0.535912,4.640810,0.114579,2.962052,0.660976,0.000294,0.319024,0.040518,19.281640,1.558078,19.532991,16.720957,4.365564,1.753768,1.341963,5.188296,0.289851
+36.800000,4.708071,1.986552,2.022855,4.426085,1.544672,0.511041,4.709996,0.115659,2.970688,0.649752,0.000260,0.330248,0.040675,19.244083,1.551263,19.539369,16.720437,4.343793,1.753722,1.342487,5.188296,0.362474
+36.900000,4.707519,2.035281,1.926651,4.203732,1.596193,0.482203,5.011304,0.119597,3.059585,0.636282,0.000245,0.343718,0.040986,19.263176,1.538272,19.556968,16.720315,4.344087,1.753639,1.342525,5.188295,0.407156
+37.000000,4.707260,2.069658,1.965953,4.080951,1.574938,0.470226,5.275156,0.122847,3.142923,0.630863,0.000253,0.349137,0.041196,19.315944,1.530863,19.569016,16.720636,4.363501,1.753592,1.342124,5.188295,0.389110
+37.100000,4.707396,2.068117,2.094639,4.127109,1.502654,0.481320,5.325039,0.123351,3.166501,0.635980,0.000277,0.344020,0.041181,19.363417,1.532390,19.568953,16.721120,4.386257,1.753618,1.341618,5.188295,0.332707
+37.200000,4.707848,2.030567,2.231907,4.330563,1.419599,0.511762,5.092441,0.120343,3.106310,0.649686,0.000304,0.330314,0.040913,19.365767,1.542863,19.555829,16.721399,4.394181,1.753697,1.341389,5.188296,0.278495
+37.300000,4.708318,1.982497,2.252482,4.536649,1.407072,0.536318,4.738173,0.115799,2.997551,0.660962,0.000306,0.319038,0.040580,19.312195,1.555670,19.537536,16.721195,4.378038,1.753762,1.341689,5.188296,0.270447
+37.400000,4.708288,1.972323,2.104522,4.514771,1.497941,0.525079,4.632627,0.114569,2.951800,0.656205,0.000274,0.323795,0.040563,19.254282,1.556142,19.533862,16.720648,4.351711,1.753752,1.342288,5.188296,0.327538
+37.500000,4.707757,2.012320,1.953173,4.300963,1.582454,0.494045,4.863586,0.117701,3.014922,0.641805,0.000248,0.338195,0.040845,19.248195,1.543988,19.548828,16.720307,4.340942,1.753676,1.342576,5.188296,0.394373
+37.600000,4.707329,2.057680,1.933262,4.118635,1.592464,0.473057,5.172272,0.121603,3.109634,0.632094,0.000247,0.347906,0.041122,19.289888,1.533237,19.564788,16.720448,4.353098,1.753605,1.342343,5.188295,0.404274
+37.700000,4.707288,2.073715,2.028787,4.083479,1.540340,0.473277,5.336407,0.123547,3.165411,0.632319,0.000264,0.347681,0.041221,19.345000,1.530518,19.570643,16.720901,4.376617,1.753596,1.341838,5.188295,0.360873
+37.800000,4.707613,2.051371,2.175171,4.223529,1.454631,0.496411,5.231041,0.122122,3.144073,0.642774,0.000293,0.337226,0.041062,19.372200,1.537121,19.563289,16.721319,4.393380,1.753657,1.341437,5.188295,0.300198
+37.900000,4.708134,2.002847,2.265509,4.458484,1.398523,0.528304,4.892578,0.117779,3.047252,0.657204,0.000310,0.322796,0.040716,19.341718,1.550426,19.545403,16.721353,4.388146,1.753739,1.341486,5.188296,0.265968
+38.000000,4.708387,1.969708,2.186571,4.560160,1.448529,0.534868,4.631701,0.114473,2.958029,0.660537,0.000291,0.319463,0.040517,19.276460,1.558113,19.532669,16.720908,4.363236,1.753767,1.342017,5.188296,0.294900
+38.100000,4.708024,1.990140,2.009647,4.407095,1.551987,0.508310,4.730692,0.115939,2.976401,0.648480,0.000257,0.331520,0.040700,19.243567,1.550173,19.540714,16.720407,4.342872,1.753715,1.342511,5.188296,0.368366
+38.200000,4.707483,2.039213,1.925144,4.188056,1.596934,0.480410,5.038046,0.119934,3.067801,0.635453,0.000245,0.344547,0.041010,19.266760,1.537349,19.558345,16.720327,4.345163,1.753632,1.342504,5.188295,0.407922
+38.300000,4.707257,2.071026,1.974240,4.077928,1.570449,0.470242,5.289373,0.123015,3.147736,0.630882,0.000254,0.349118,0.041205,19.320668,1.530632,19.569514,16.720675,4.365549,1.753591,1.342080,5.188295,0.385311
+38.400000,4.707425,2.066191,2.107333,4.139175,1.495224,0.483315,5.316053,0.123230,3.164702,0.636881,0.000279,0.343119,0.041168,19.365756,1.532953,19.568325,16.721156,4.387724,1.753623,1.341583,5.188295,0.327444
+38.500000,4.707894,2.026327,2.239975,4.351227,1.414546,0.514584,5.062745,0.119963,3.097850,0.650961,0.000306,0.329039,0.040882,19.363053,1.544029,19.554265,16.721402,4.393732,1.753704,1.341393,5.188296,0.275480
+38.600000,4.708342,1.979548,2.245540,4.545720,1.411518,0.536901,4.715039,0.115504,2.989611,0.661260,0.000305,0.318740,0.040563,19.306359,1.556363,19.536394,16.721155,4.375842,1.753764,1.341736,5.188296,0.272942
+38.700000,4.708255,1.974186,2.088767,4.500862,1.507152,0.522682,4.641942,0.114707,2.953604,0.655117,0.000271,0.324883,0.040579,19.251413,1.555412,19.534606,16.720604,4.349936,1.753746,1.342331,5.188296,0.334081
+38.800000,4.707710,2.016638,1.946071,4.281932,1.586181,0.491641,4.890494,0.118050,3.022963,0.640680,0.000247,0.339320,0.040872,19.250232,1.542869,19.550373,16.720300,4.341175,1.753669,1.342575,5.188295,0.397749
+38.900000,4.707311,2.060408,1.937641,4.109215,1.590126,0.472190,5.193985,0.121869,3.116533,0.631707,0.000248,0.348293,0.041139,19.294530,1.532669,19.565739,16.720478,4.354885,1.753601,1.342306,5.188295,0.402234
+39.000000,4.707302,2.073298,2.040277,4.088700,1.533870,0.474392,5.338890,0.123567,3.166921,0.632831,0.000266,0.347169,0.041218,19.348885,1.530715,19.570541,16.720942,4.378553,1.753599,1.341795,5.188295,0.355854
+39.100000,4.707654,2.047929,2.186815,4.241930,1.447517,0.499136,5.209186,0.121841,3.138343,0.643999,0.000295,0.336001,0.041038,19.371971,1.538074,19.562080,16.721340,4.393926,1.753664,1.341420,5.188295,0.295669
+39.200000,4.708174,1.998742,2.266238,4.475704,1.398103,0.530300,4.862023,0.117386,3.037757,0.658124,0.000310,0.321876,0.040688,19.336733,1.551519,19.543825,16.721332,4.386607,1.753744,1.341515,5.188296,0.265660
+39.300000,4.708381,1.969196,2.172798,4.556265,1.456992,0.533606,4.625281,0.114403,2.954836,0.659996,0.000288,0.320004,0.040519,19.271618,1.558034,19.532502,16.720859,4.360981,1.753765,1.342068,5.188296,0.300211
+39.400000,4.707977,1.993841,1.997302,4.388108,1.558764,0.505634,4.752233,0.116230,2.982445,0.647231,0.000255,0.332769,0.040725,19.243418,1.549078,19.542091,16.720380,4.342112,1.753708,1.342533,5.188296,0.373935
+39.500000,4.707449,2.042968,1.924453,4.173315,1.597251,0.478753,5.063983,0.120260,3.075795,0.634689,0.000245,0.345311,0.041033,19.270478,1.536482,19.559656,16.720342,4.346333,1.753626,1.342481,5.188295,0.408297
+39.600000,4.707257,2.072147,1.982911,4.076012,1.565729,0.470401,5.301991,0.123163,3.152089,0.630967,0.000256,0.349033,0.041212,19.325273,1.530460,19.569929,16.720714,4.367576,1.753590,1.342036,5.188295,0.381360
+39.700000,4.707455,2.064067,2.119884,4.152085,1.487824,0.485409,5.305351,0.123087,3.162387,0.637825,0.000281,0.342175,0.041153,19.367756,1.533565,19.567623,16.721189,4.389065,1.753628,1.341551,5.188295,0.322292
+39.800000,4.707940,2.022082,2.247129,4.371601,1.410054,0.517325,5.032683,0.119577,3.089183,0.652201,0.000307,0.327799,0.040852,19.359993,1.545196,19.552686,16.721401,4.393124,1.753710,1.341401,5.188296,0.272818
+39.900000,4.708361,1.976909,2.237521,4.553037,1.416630,0.537218,4.694063,0.115239,2.982250,0.661439,0.000303,0.318561,0.040548,19.300592,1.556956,19.535374,16.721114,4.373612,1.753766,1.341784,5.188296,0.275849
+40.000000,6.671025,2.779759,1.970142,4.078857,1.572638,0.470145,5.345308,0.123668,3.164761,0.629785,0.000254,0.350215,0.041313,22.072750,1.536590,19.603080,16.748660,4.384283,1.760923,1.347767,5.186677,0.387221
+40.100000,6.671141,2.777980,2.109123,4.144871,1.494153,0.484014,5.369334,0.123844,3.181237,0.636165,0.000280,0.343835,0.041272,22.119381,1.539146,19.601584,16.749161,4.407300,1.760958,1.347251,5.186677,0.326725
+40.200000,6.671737,2.730460,2.247056,4.366485,1.410057,0.516710,5.102067,0.120414,3.110919,0.650873,0.000308,0.329127,0.040973,22.116012,1.550735,19.586832,16.749412,4.413303,1.761043,1.347058,5.186678,0.272887
+40.300000,6.672417,2.669516,2.252058,4.569370,1.407399,0.539957,4.736624,0.115744,2.997468,0.661576,0.000307,0.318424,0.040639,22.056206,1.563643,19.568140,16.749149,4.394340,1.761106,1.347422,5.186679,0.270544
+40.400000,6.672457,2.656211,2.086518,4.520588,1.508489,0.524731,4.661807,0.114934,2.960243,0.654983,0.000271,0.325017,0.040658,21.998700,1.562523,19.566454,16.748568,4.367150,1.761087,1.348048,5.186679,0.334994
+40.500000,6.671791,2.705786,1.937610,4.291719,1.590661,0.492350,4.923304,0.118440,3.033159,0.639913,0.000246,0.340087,0.040963,21.997650,1.549348,19.583067,16.748252,4.358069,1.761005,1.348301,5.186678,0.401729
+40.600000,6.671166,2.763326,1.929149,4.112648,1.594574,0.472205,5.240122,0.122410,3.130495,0.630637,0.000247,0.349363,0.041241,22.043731,1.538778,19.599014,16.748439,4.372389,1.760934,1.348020,5.186677,0.406277
+40.700000,6.671017,2.785114,2.034987,4.089356,1.536833,0.474190,5.394282,0.124211,3.183590,0.631700,0.000266,0.348300,0.041326,22.100584,1.536681,19.604052,16.748923,4.397110,1.760931,1.347487,5.186677,0.358181
+40.800000,6.671400,2.758315,2.187576,4.245479,1.447029,0.499548,5.264591,0.122489,3.155593,0.643150,0.000296,0.336850,0.041145,22.125721,1.544149,19.595474,16.749343,4.413461,1.760999,1.347090,5.186678,0.295395
+40.900000,6.672120,2.697200,2.274044,4.490342,1.393083,0.532425,4.902004,0.117855,3.051354,0.658017,0.000313,0.321983,0.040780,22.089988,1.558187,19.576470,16.749344,4.406272,1.761083,1.347178,5.186678,0.262873
+41.000000,6.672551,2.653557,2.180014,4.580909,1.452597,0.536771,4.645427,0.114625,2.962333,0.660357,0.000290,0.319643,0.040593,22.021463,1.565374,19.564196,16.748854,4.379517,1.761107,1.347754,5.186679,0.297389
+41.100000,6.672160,2.676612,1.995178,4.408894,1.559962,0.507815,4.770916,0.116439,2.988664,0.647155,0.000255,0.332845,0.040802,21.990550,1.556220,19.573906,16.748344,4.359289,1.761049,1.348251,5.186678,0.374861
+41.200000,6.671425,2.737928,1.915749,4.184398,1.601788,0.479611,5.095175,0.120622,3.085328,0.633993,0.000244,0.346007,0.041122,22.017423,1.543031,19.592252,16.748292,4.363072,1.760963,1.348211,5.186677,0.412463
+41.300000,6.671022,2.780319,1.972809,4.078213,1.571192,0.470186,5.349308,0.123714,3.166129,0.629809,0.000255,0.350191,0.041315,22.074147,1.536535,19.603215,16.748672,4.384911,1.760922,1.347754,5.186677,0.385999
+41.400000,6.671151,2.777313,2.113040,4.148804,1.491847,0.484656,5.366146,0.123801,3.180564,0.636454,0.000281,0.343546,0.041267,22.119998,1.539332,19.601373,16.749171,4.407726,1.760959,1.347242,5.186677,0.325114
+41.500000,6.671757,2.728866,2.249400,4.372951,1.408584,0.517585,5.092544,0.120292,3.108196,0.651268,0.000309,0.328732,0.040964,22.115027,1.551104,19.586335,16.749412,4.413116,1.761045,1.347061,5.186678,0.272016
+41.600000,6.672429,2.668342,2.249521,4.571803,1.409022,0.540068,4.729737,0.115656,2.995064,0.661637,0.000306,0.318363,0.040634,22.054298,1.563840,19.567806,16.749135,4.393617,1.761106,1.347439,5.186679,0.271457
+41.700000,6.672446,2.656879,2.081502,4.515743,1.511398,0.523927,4.665524,0.114988,2.961062,0.654616,0.000271,0.325384,0.040664,21.997864,1.562262,19.566735,16.748554,4.366618,1.761085,1.348062,5.186679,0.337101
+41.800000,6.671772,2.707436,1.935639,4.285789,1.591684,0.491615,4.931984,0.118552,3.035761,0.639570,0.000246,0.340430,0.040971,21.998351,1.548999,19.583557,16.748251,4.358188,1.761002,1.348300,5.186678,0.402678
+41.900000,6.671156,2.764425,1.930735,4.109933,1.593733,0.471968,5.246759,0.122491,3.132607,0.630533,0.000247,0.349467,0.041246,22.045189,1.538615,19.599293,16.748449,4.372976,1.760933,1.348008,5.186677,0.405533
+42.000000,6.671021,2.785015,2.038697,4.091262,1.534741,0.474575,5.394655,0.124213,3.183948,0.631877,0.000267,0.348123,0.041325,22.101746,1.536756,19.604000,16.748936,4.397713,1.760932,1.347474,5.186677,0.356562
+42.100000,6.671417,2.757034,2.191194,4.251406,1.444809,0.500421,5.257343,0.122397,3.153684,0.643542,0.000297,0.336458,0.041137,22.125545,1.544460,19.595078,16.749349,4.413604,1.761001,1.347086,5.186678,0.293997
+42.200000,6.672139,2.695601,2.274104,4.495643,1.393060,0.533029,4.892374,0.117732,3.048355,0.658296,0.000313,0.321704,0.040771,22.088344,1.558528,19.575977,16.749336,4.405763,1.761084,1.347189,5.186678,0.262836
+42.300000,6.672553,2.653227,2.175609,4.579509,1.455301,0.536349,4.643634,0.114606,2.961397,0.660176,0.000289,0.319824,0.040594,22.019932,1.565339,19.564160,16.748838,4.378807,1.761106,1.347771,5.186679,0.299091
+42.400000,6.672143,2.677922,1.991368,4.402938,1.562039,0.506981,4.777764,0.116531,2.990591,0.646766,0.000255,0.333234,0.040810,21.990496,1.555876,19.574343,16.748335,4.359059,1.761046,1.348258,5.186678,0.376594
+42.500000,6.671410,2.739401,1.915597,4.179876,1.601853,0.479105,5.103242,0.120723,3.087806,0.633761,0.000244,0.346239,0.041129,22.018556,1.542766,19.592655,16.748296,4.363441,1.760960,1.348204,5.186677,0.412550
+42.600000,6.671019,2.780861,1.975535,4.077662,1.569714,0.470241,5.353197,0.123760,3.167466,0.629838,0.000255,0.350162,0.041317,22.075546,1.536485,19.603339,16.748683,4.385542,1.760922,1.347742,5.186677,0.384752
+42.700000,6.671162,2.776617,2.116959,4.152834,1.489535,0.485310,5.362777,0.123757,3.179838,0.636749,0.000282,0.343251,0.041263,22.120584,1.539524,19.601152,16.749181,4.408140,1.760960,1.347233,5.186677,0.323506
+42.800000,6.671776,2.727283,2.251668,4.379335,1.407152,0.518447,5.083091,0.120172,3.105485,0.651658,0.000309,0.328342,0.040954,22.114032,1.551471,19.585839,16.749411,4.412924,1.761046,1.347064,5.186678,0.271180
+42.900000,6.672441,2.667192,2.247062,4.574211,1.410596,0.540184,4.722981,0.115571,2.992708,0.661700,0.000305,0.318300,0.040629,22.052437,1.564035,19.567477,16.749121,4.392913,1.761106,1.347455,5.186679,0.272343
+43.000000,6.672437,2.657473,2.076626,4.511229,1.514216,0.523168,4.668785,0.115035,2.961746,0.654269,0.000270,0.325731,0.040670,21.996976,1.562021,19.566989,16.748539,4.366077,1.761083,1.348076,5.186679,0.339159
+43.100000,6.671753,2.709028,1.933590,4.280026,1.592746,0.490893,4.940295,0.118659,3.038243,0.639231,0.000246,0.340769,0.040980,21.998947,1.548661,19.584029,16.748248,4.358271,1.761000,1.348300,5.186678,0.403665
+43.200000,6.671147,2.765520,1.932162,4.107176,1.592975,0.471720,5.253312,0.122570,3.134680,0.630423,0.000247,0.349577,0.041251,22.046554,1.538447,19.599575,16.748458,4.373524,1.760931,1.347998,5.186677,0.404864
+43.300000,6.671025,2.784956,2.042277,4.092987,1.532718,0.474935,5.395230,0.124217,3.184359,0.632040,0.000267,0.347960,0.041324,22.102861,1.536824,19.603958,16.748948,4.398298,1.760932,1.347462,5.186677,0.355006
+43.400000,6.671433,2.755788,2.194805,4.257243,1.442589,0.501285,5.250271,0.122306,3.151830,0.643930,0.000297,0.336070,0.041129,22.125354,1.544764,19.594692,16.749355,4.413747,1.761002,1.347082,5.186677,0.292607
+43.500000,6.672158,2.693975,2.274211,4.501084,1.393002,0.533653,4.882551,0.117606,3.045296,0.658583,0.000313,0.321417,0.040762,22.086627,1.558879,19.575472,16.749328,4.405238,1.761085,1.347200,5.186678,0.262787
+43.600000,6.672554,2.652916,2.170994,4.577921,1.458126,0.535896,4.641984,0.114589,2.960490,0.659980,0.000288,0.320020,0.040595,22.018315,1.565294,19.564132,16.748821,4.378070,1.761105,1.347789,5.186679,0.300880
+43.700000,6.672125,2.679309,1.987493,4.396730,1.564145,0.506118,4.785006,0.116628,2.992638,0.646362,0.000254,0.333638,0.040818,21.990431,1.555516,19.574802,16.748326,4.358832,1.761043,1.348265,5.186678,0.378363
+43.800000,6.671394,2.740914,1.915527,4.175265,1.601876,0.478593,5.111568,0.120827,3.090368,0.633526,0.000244,0.346474,0.041136,22.019704,1.542496,19.593068,16.748300,4.363832,1.760957,1.348198,5.186677,0.412598
+43.900000,6.671017,2.781401,1.978389,4.077167,1.568163,0.470308,5.357130,0.123805,3.168824,0.629874,0.000256,0.350126,0.041319,22.076947,1.536438,19.603461,16.748695,4.386193,1.760921,1.347729,5.186677,0.383449
+44.000000,6.671174,2.775878,2.121022,4.157077,1.487130,0.485997,5.359164,0.123709,3.179049,0.637059,0.000282,0.342941,0.041258,22.121126,1.539727,19.600917,16.749191,4.408561,1.760961,1.347223,5.186677,0.321848
+44.100000,6.671797,2.725637,2.253961,4.385948,1.405712,0.519336,5.073247,0.120046,3.102654,0.652059,0.000309,0.327941,0.040944,22.112937,1.551852,19.585325,16.749410,4.412712,1.761048,1.347068,5.186678,0.270328
+44.200000,6.672454,2.666039,2.244383,4.576489,1.412308,0.540269,4.716248,0.115486,2.990341,0.661750,0.000305,0.318250,0.040624,22.050482,1.564223,19.567152,16.749107,4.392180,1.761106,1.347472,5.186679,0.273310
+44.300000,6.672427,2.658167,2.071668,4.506372,1.517072,0.522370,4.672580,0.115090,2.962598,0.653904,0.000269,0.326096,0.040676,21.996117,1.561759,19.567273,16.748525,4.365552,1.761080,1.348090,5.186678,0.341261
+44.400000,6.671735,2.710670,1.931683,4.274180,1.593732,0.490169,4.948906,0.118770,3.040824,0.638893,0.000246,0.341107,0.040988,21.999602,1.548318,19.584512,16.748246,4.358392,1.760996,1.348300,5.186678,0.404586
+44.500000,6.671138,2.766595,1.933782,4.104553,1.592115,0.471495,5.259829,0.122649,3.136753,0.630324,0.000248,0.349676,0.041256,22.047950,1.538288,19.599849,16.748467,4.374106,1.760929,1.347987,5.186677,0.404104
+44.600000,6.671030,2.784834,2.045992,4.094989,1.530614,0.475332,5.395457,0.124216,3.184675,0.632225,0.000268,0.347775,0.041322,22.103935,1.536906,19.603897,16.748960,4.398888,1.760932,1.347450,5.186677,0.353395
+44.700000,6.671451,2.754474,2.198389,4.263301,1.440383,0.502173,5.242775,0.122210,3.149842,0.644329,0.000298,0.335671,0.041121,22.125053,1.545083,19.594283,16.749360,4.413862,1.761003,1.347079,5.186677,0.291228
+44.800000,6.672177,2.692364,2.274025,4.506305,1.393138,0.534233,4.872852,0.117482,3.042250,0.658850,0.000313,0.321150,0.040753,22.084825,1.559220,19.574973,16.749319,4.404683,1.761086,1.347212,5.186678,0.262837
+44.900000,6.672555,2.652702,2.166264,4.575953,1.461013,0.535394,4.640901,0.114580,2.959759,0.659762,0.000287,0.320238,0.040597,22.016740,1.565224,19.564138,16.748804,4.377347,1.761103,1.347807,5.186679,0.302723
+45.000000,6.672108,2.680731,1.983816,4.390529,1.566136,0.505265,4.792434,0.116727,2.994757,0.645963,0.000254,0.334037,0.040827,21.990427,1.555155,19.575267,16.748318,4.358644,1.761039,1.348272,5.186678,0.380049
+45.100000,6.671380,2.742380,1.915628,4.170855,1.601810,0.478109,5.119702,0.120928,3.092877,0.633304,0.000244,0.346696,0.041143,22.020859,1.542237,19.593467,16.748305,4.364244,1.760955,1.348191,5.186677,0.412562
+45.200000,6.671015,2.781880,1.981314,4.076887,1.566570,0.470402,5.360727,0.123847,3.170087,0.629920,0.000256,0.350080,0.041321,22.078307,1.536402,19.603567,16.748707,4.386842,1.760920,1.347716,5.186677,0.382117
+45.300000,6.671186,2.775087,2.125039,4.161485,1.484751,0.486701,5.355191,0.123657,3.178151,0.637376,0.000283,0.342624,0.041252,22.121580,1.539940,19.600668,16.749201,4.408954,1.760962,1.347215,5.186677,0.320210
+45.400000,6.671817,2.723980,2.256010,4.392476,1.404413,0.520202,5.063305,0.119919,3.099769,0.652452,0.000310,0.327548,0.040934,22.111728,1.552233,19.584806,16.749408,4.412457,1.761049,1.347073,5.186678,0.269577
+45.500000,6.672465,2.664989,2.241406,4.578255,1.414203,0.540279,4.710144,0.115409,2.988145,0.661765,0.000304,0.318235,0.040620,22.048534,1.564381,19.566864,16.749092,4.391439,1.761105,1.347489,5.186678,0.274391
+45.600000,6.672415,2.658975,2.066788,4.501198,1.519878,0.521541,4.677011,0.115153,2.963661,0.653524,0.000268,0.326476,0.040682,21.995371,1.561474,19.567593,16.748511,4.365070,1.761077,1.348103,5.186678,0.343335
+45.700000,6.671717,2.712303,1.930054,4.268471,1.594570,0.489472,4.957548,0.118881,3.043431,0.638566,0.000245,0.341434,0.040996,22.000335,1.547983,19.584988,16.748246,4.358559,1.760993,1.348298,5.186677,0.405376
+45.800000,6.671130,2.767606,1.935572,4.102170,1.591161,0.471305,5.266078,0.122724,3.138752,0.630243,0.000248,0.349757,0.041260,22.049358,1.538142,19.600105,16.748477,4.374707,1.760927,1.347975,5.186677,0.403268
+45.900000,6.671036,2.784636,2.049776,4.097257,1.528466,0.475764,5.395229,0.124210,3.184862,0.632423,0.000269,0.347577,0.041321,22.104969,1.537003,19.603816,16.748972,4.399469,1.760932,1.347437,5.186677,0.351758
+46.000000,6.671469,2.753127,2.201846,4.269392,1.438250,0.503058,5.235052,0.122111,3.147775,0.644727,0.000299,0.335273,0.041112,22.124690,1.545406,19.593866,16.749364,4.413952,1.761005,1.347076,5.186677,0.289904
+46.100000,6.672195,2.690822,2.273680,4.511195,1.393374,0.534765,4.863583,0.117363,3.039319,0.659098,0.000313,0.320902,0.040745,22.083079,1.559542,19.574500,16.749310,4.404137,1.761086,1.347223,5.186678,0.262946
+46.200000,6.672555,2.652533,2.161712,4.573948,1.463785,0.534901,4.640044,0.114573,2.959115,0.659546,0.000286,0.320454,0.040598,22.015275,1.565149,19.564154,16.748788,4.376666,1.761101,1.347824,5.186678,0.304504
+46.300000,6.672091,2.682109,1.980311,4.384550,1.568030,0.504447,4.799625,0.116822,2.996812,0.645580,0.000253,0.334420,0.040835,21.990459,1.554807,19.575716,16.748310,4.358473,1.761036,1.348277,5.186678,0.381660
+46.400000,6.671366,2.743793,1.915775,4.166631,1.601720,0.477648,5.127542,0.121026,3.095298,0.633093,0.000244,0.346907,0.041150,22.022007,1.541989,19.593849,16.748310,4.364652,1.760952,1.348183,5.186677,0.412506
+46.500000,6.671014,2.782320,1.984185,4.076713,1.565005,0.470507,5.364080,0.123885,3.171271,0.629974,0.000257,0.350026,0.041322,22.079630,1.536372,19.603662,16.748719,4.387471,1.760919,1.347703,5.186677,0.380811
+46.600000,6.671198,2.774299,2.128928,4.165822,1.482442,0.487391,5.351206,0.123605,3.177239,0.637686,0.000284,0.342314,0.041247,22.122012,1.540148,19.600422,16.749210,4.409328,1.760963,1.347206,5.186677,0.318631
+46.700000,6.671837,2.722380,2.257948,4.398762,1.403189,0.521034,5.053700,0.119796,3.096978,0.652828,0.000310,0.327172,0.040925,22.110571,1.552600,19.584305,16.749406,4.412209,1.761050,1.347077,5.186678,0.268863
+46.800000,6.672476,2.663974,2.238528,4.579968,1.416034,0.540289,4.704236,0.115335,2.986020,0.661782,0.000303,0.318218,0.040616,22.046668,1.564535,19.566585,16.749077,4.390725,1.761105,1.347505,5.186678,0.275438
+46.900000,6.672404,2.659740,2.062051,4.496251,1.522591,0.520748,4.681168,0.115211,2.964649,0.653159,0.000267,0.326841,0.040689,21.994629,1.561202,19.567896,16.748498,4.364593,1.761075,1.348116,5.186678,0.345358
+47.000000,6.671699,2.713901,1.928415,4.262881,1.595413,0.488788,4.965957,0.118988,3.045960,0.638249,0.000245,0.341751,0.041004,22.001043,1.547654,19.585456,16.748245,4.358713,1.760990,1.348296,5.186677,0.406172
+47.100000,6.671122,2.768589,1.937324,4.099882,1.590233,0.471120,5.272104,0.122797,3.140684,0.630161,0.000248,0.349839,0.041265,22.050733,1.538001,19.600353,16.748487,4.375287,1.760925,1.347963,5.186677,0.402444
+47.200000,6.671041,2.784444,2.053447,4.099458,1.526378,0.476184,5.395012,0.124204,3.185045,0.632612,0.000269,0.347388,0.041319,22.105968,1.537095,19.603738,16.748984,4.400028,1.760932,1.347425,5.186677,0.350176
+47.300000,6.671486,2.751794,2.205225,4.275425,1.436164,0.503934,5.227371,0.122013,3.145716,0.645121,0.000299,0.334879,0.041104,22.124305,1.545726,19.593453,16.749369,4.414026,1.761006,1.347073,5.186677,0.288612
+47.400000,6.672213,2.689275,2.273178,4.516032,1.393708,0.535281,4.854265,0.117244,3.036358,0.659338,0.000312,0.320662,0.040737,22.081264,1.559864,19.574024,16.749300,4.403559,1.761086,1.347235,5.186678,0.263115
+47.500000,6.672554,2.652455,2.156875,4.571479,1.466721,0.534341,4.639739,0.114574,2.958626,0.659300,0.000285,0.320700,0.040601,22.013812,1.565047,19.564205,16.748772,4.375968,1.761099,1.347841,5.186678,0.306404
+47.600000,6.672072,2.683600,1.976856,4.378251,1.569891,0.503597,4.807438,0.116926,2.999068,0.645182,0.000252,0.334818,0.040843,21.990595,1.554438,19.576198,16.748303,4.358338,1.761033,1.348282,5.186678,0.383253
+47.700000,6.671352,2.745230,1.916153,4.162422,1.601511,0.477198,5.135595,0.121126,3.097795,0.632888,0.000244,0.347112,0.041157,22.023260,1.541741,19.594236,16.748316,4.365109,1.760949,1.348174,5.186677,0.412336
+47.800000,6.671013,2.782709,1.987305,4.076784,1.563299,0.470649,5.367227,0.123921,3.172412,0.630043,0.000257,0.349957,0.041324,22.081008,1.536354,19.603743,16.748732,4.388131,1.760918,1.347689,5.186676,0.379397
+47.900000,6.671211,2.773418,2.132939,4.170523,1.480056,0.488129,5.346698,0.123547,3.176180,0.638024,0.000285,0.341976,0.041241,22.122397,1.540381,19.600144,16.749219,4.409697,1.760964,1.347197,5.186677,0.317006
+48.000000,6.671858,2.720710,2.259764,4.405210,1.402044,0.521877,5.043683,0.119668,3.094047,0.653210,0.000311,0.326790,0.040915,22.109319,1.552980,19.583784,16.749403,4.411924,1.761051,1.347082,5.186678,0.268193
+48.100000,6.672486,2.662997,2.235323,4.581359,1.418069,0.540242,4.698597,0.115265,2.983952,0.661772,0.000303,0.318228,0.040613,22.044776,1.564671,19.566325,16.749062,4.389983,1.761104,1.347522,5.186678,0.276609
+48.200000,6.672391,2.660625,2.057219,4.490881,1.525349,0.519904,4.685986,0.115279,2.965843,0.652771,0.000266,0.327229,0.040695,21.993986,1.560903,19.568237,16.748485,4.364139,1.761072,1.348128,5.186678,0.347433
+48.300000,6.671681,2.715548,1.926950,4.257216,1.596165,0.488103,4.974690,0.119100,3.048600,0.637929,0.000245,0.342071,0.041013,22.001875,1.547320,19.585934,16.748245,4.358915,1.760987,1.348294,5.186677,0.406885
+48.400000,6.671114,2.769554,1.939278,4.097712,1.589194,0.470958,5.278138,0.122870,3.142627,0.630093,0.000249,0.349907,0.041269,22.052199,1.537866,19.600595,16.748497,4.375907,1.760923,1.347951,5.186676,0.401528
+48.500000,6.671048,2.784181,2.057298,4.101970,1.524183,0.476648,5.394415,0.124194,3.185126,0.632827,0.000270,0.347173,0.041317,22.106994,1.537202,19.603640,16.748996,4.400602,1.760932,1.347413,5.186676,0.348520
+48.600000,6.671504,2.750388,2.208608,4.281696,1.434071,0.504838,5.219256,0.121910,3.143524,0.645527,0.000300,0.334473,0.041095,22.123883,1.546061,19.593018,16.749373,4.414084,1.761007,1.347071,5.186677,0.287321
+48.700000,6.672231,2.687725,2.272503,4.520772,1.394156,0.535774,4.844960,0.117125,3.033383,0.659567,0.000312,0.320433,0.040728,22.079449,1.560181,19.573552,16.749290,4.402966,1.761087,1.347248,5.186678,0.263342
+48.800000,6.672551,2.652432,2.151952,4.568780,1.469700,0.533752,4.639759,0.114580,2.958238,0.659040,0.000284,0.320960,0.040603,22.012423,1.564930,19.564275,16.748756,4.375282,1.761098,1.347858,5.186678,0.308348
+48.900000,6.672054,2.685120,1.973524,4.371957,1.571680,0.502753,4.815373,0.117031,3.001368,0.644787,0.000252,0.335213,0.040852,21.990823,1.554068,19.576684,16.748297,4.358231,1.761030,1.348286,5.186678,0.384797
+49.000000,6.671338,2.746632,1.916638,4.158354,1.601247,0.476767,5.143508,0.121224,3.100252,0.632692,0.000244,0.347308,0.041163,22.024566,1.541500,19.594613,16.748323,4.365580,1.760947,1.348165,5.186677,0.412115
+49.100000,6.671012,2.783060,1.990453,4.076990,1.561576,0.470809,5.370159,0.123954,3.173490,0.630120,0.000258,0.349880,0.041325,22.082404,1.536342,19.603814,16.748745,4.388789,1.760917,1.347675,5.186676,0.377971
+49.200000,6.671223,2.772510,2.136939,4.175307,1.477669,0.488879,5.341976,0.123485,3.175059,0.638357,0.000286,0.341643,0.041235,22.122798,1.540613,19.599864,16.749229,4.410053,1.760965,1.347189,5.186677,0.315392
+49.300000,6.671877,2.719035,2.261464,4.411618,1.400972,0.522709,5.033605,0.119540,3.091086,0.653587,0.000311,0.326413,0.040905,22.108073,1.553358,19.583264,16.749401,4.411621,1.761052,1.347087,5.186678,0.267564
+49.400000,6.672494,2.662066,2.231975,4.582516,1.420191,0.540160,4.693223,0.115198,2.981956,0.661747,0.000302,0.318253,0.040610,22.042938,1.564793,19.566081,16.749048,4.389238,1.761104,1.347539,5.186678,0.277835
+49.500000,6.672377,2.661578,2.052418,4.485329,1.528079,0.519045,4.691145,0.115351,2.967149,0.652375,0.000265,0.327625,0.040703,21.993454,1.560593,19.568596,16.748473,4.363707,1.761069,1.348139,5.186678,0.349504
+49.600000,6.671663,2.717191,1.925653,4.251647,1.596827,0.487436,4.983413,0.119211,3.051245,0.637618,0.000245,0.342382,0.041021,22.002799,1.546991,19.586408,16.748246,4.359142,1.760984,1.348290,5.186677,0.407521
+49.700000,6.671106,2.770473,1.941334,4.095717,1.588101,0.470820,5.283947,0.122939,3.144508,0.630035,0.000249,0.349965,0.041273,22.053713,1.537739,19.600825,16.748509,4.376535,1.760922,1.347937,5.186676,0.400565
+49.800000,6.671054,2.783871,2.061166,4.104637,1.521973,0.477132,5.393532,0.124180,3.185125,0.633047,0.000271,0.346953,0.041314,22.108030,1.537318,19.603530,16.749009,4.401164,1.760933,1.347400,5.186676,0.346861
+49.900000,6.671522,2.748961,2.211889,4.287986,1.432038,0.505738,5.210986,0.121804,3.141276,0.645932,0.000301,0.334068,0.041086,22.123457,1.546398,19.592578,16.749377,4.414119,1.761009,1.347068,5.186677,0.286073
+50.000000,8.156723,3.190142,2.243777,4.356720,1.412105,0.515392,5.141786,0.120899,3.122967,0.649844,0.000308,0.330156,0.041035,23.491140,1.552601,19.601480,16.760950,4.421766,1.764058,1.349403,5.186006,0.274118
+50.100000,8.157558,3.119871,2.260264,4.572163,1.402143,0.540788,4.763646,0.116072,3.006912,0.661485,0.000309,0.318515,0.040684,23.432436,1.566122,19.582103,16.760712,4.403701,1.764126,1.349743,5.186007,0.267593
+50.200000,8.157764,3.095483,2.097894,4.539637,1.501869,0.527451,4.662636,0.114920,2.961543,0.655780,0.000274,0.324220,0.040678,23.371528,1.566045,19.578981,16.760123,4.375634,1.764112,1.350384,5.186007,0.330237
+50.300000,8.157086,3.144516,1.939560,4.310412,1.589674,0.494487,4.916022,0.118332,3.031160,0.640458,0.000247,0.339542,0.040980,23.366751,1.552892,19.595344,16.759772,4.364859,1.764030,1.350676,5.186006,0.400766
+50.400000,8.156302,3.211449,1.922272,4.121384,1.598186,0.472890,5.242356,0.122428,3.130944,0.630494,0.000246,0.349506,0.041270,23.411560,1.541745,19.611994,16.759935,4.378231,1.763955,1.350417,5.186005,0.409542
+50.500000,8.156006,3.243004,2.023945,4.085858,1.543021,0.473280,5.415008,0.124457,3.189229,0.630849,0.000264,0.349151,0.041373,23.469969,1.539012,19.617926,16.760419,4.403257,1.763947,1.349880,5.186005,0.363033
+50.600000,8.156346,3.220121,2.178640,4.232668,1.452485,0.497589,5.304586,0.122975,3.167132,0.641843,0.000294,0.338157,0.041208,23.499144,1.545929,19.610167,16.760863,4.421084,1.764012,1.349454,5.186006,0.298875
+50.700000,8.157163,3.153882,2.276417,4.482408,1.391518,0.531664,4.943410,0.118367,3.064624,0.657222,0.000314,0.322778,0.040841,23.467089,1.560061,19.591192,16.760901,4.415622,1.764100,1.349502,5.186006,0.262065
+50.800000,8.157788,3.097869,2.194133,4.594082,1.443899,0.539092,4.659287,0.114779,2.968121,0.660941,0.000294,0.319059,0.040622,23.397125,1.568466,19.577400,16.760426,4.389006,1.764131,1.350068,5.186007,0.291968
+50.900000,8.157496,3.113211,2.004340,4.432827,1.554961,0.510879,4.761191,0.116291,2.986351,0.648133,0.000257,0.331867,0.040813,23.361271,1.560067,19.585893,16.759886,4.367002,1.764075,1.350603,5.186006,0.370698
+51.000000,8.156656,3.179991,1.912782,4.200930,1.603364,0.481312,5.087034,0.120509,3.082812,0.634324,0.000243,0.345676,0.041140,23.384951,1.546443,19.604625,16.759795,4.369045,1.763987,1.350604,5.186005,0.413854
+51.100000,8.156077,3.233496,1.961841,4.081175,1.577104,0.470042,5.358068,0.123815,3.168261,0.629289,0.000253,0.350711,0.041351,23.441678,1.539209,19.616575,16.760158,4.390417,1.763941,1.350159,5.186005,0.391054
+51.200000,8.156098,3.238492,2.100048,4.137684,1.499468,0.482734,5.398976,0.124198,3.189626,0.635159,0.000279,0.344841,0.041326,23.490870,1.541262,19.615801,16.760670,4.414277,1.763972,1.349628,5.186005,0.330484
+51.300000,8.156723,3.190126,2.243867,4.356827,1.412050,0.515409,5.141711,0.120898,3.122951,0.649853,0.000308,0.330147,0.041035,23.491150,1.552606,19.601468,16.760950,4.421771,1.764058,1.349403,5.186006,0.274083
+51.400000,8.157559,3.119815,2.260288,4.572348,1.402128,0.540810,4.763357,0.116068,3.006821,0.661495,0.000309,0.318505,0.040684,23.432388,1.566134,19.582085,16.760712,4.403684,1.764126,1.349743,5.186007,0.267583
+51.500000,8.157763,3.095489,2.097740,4.539518,1.501961,0.527430,4.662718,0.114921,2.961558,0.655770,0.000274,0.324230,0.040678,23.371498,1.566039,19.578987,16.760122,4.375615,1.764112,1.350385,5.186007,0.330299
+51.600000,8.157085,3.144563,1.939538,4.310282,1.589684,0.494472,4.916250,0.118335,3.031231,0.640450,0.000247,0.339550,0.040980,23.366775,1.552884,19.595356,16.759772,4.364864,1.764030,1.350676,5.186006,0.400778
+51.700000,8.156302,3.211462,1.922340,4.121379,1.598150,0.472892,5.242453,0.122429,3.130977,0.630495,0.000246,0.349505,0.041270,23.411593,1.541744,19.611997,16.759935,4.378245,1.763955,1.350417,5.186005,0.409509
+51.800000,8.156006,3.242989,2.024022,4.085932,1.542978,0.473291,5.414962,0.124457,3.189220,0.630854,0.000264,0.349146,0.041373,23.469989,1.539015,19.617923,16.760419,4.403268,1.763947,1.349880,5.186005,0.363000
+51.900000,8.156346,3.220083,2.178694,4.232809,1.452453,0.497608,5.304389,0.122972,3.167077,0.641851,0.000294,0.338149,0.041208,23.499130,1.545937,19.610157,16.760863,4.421081,1.764012,1.349454,5.186006,0.298853
+52.000000,8.157163,3.153850,2.276372,4.482480,1.391551,0.531669,4.943243,0.118365,3.064568,0.657224,0.000314,0.322776,0.040841,23.467053,1.560066,19.591185,16.760901,4.415607,1.764100,1.349502,5.186006,0.262077
+52.100000,8.157788,3.097873,2.193998,4.593978,1.443982,0.539072,4.659340,0.114779,2.968127,0.660931,0.000293,0.319069,0.040623,23.397101,1.568461,19.577405,16.760426,4.388990,1.764131,1.350069,5.186007,0.292020
+52.200000,8.157495,3.113267,2.004263,4.432625,1.555005,0.510853,4.761482,0.116295,2.986439,0.648121,0.000257,0.331879,0.040814,23.361302,1.560055,19.585910,16.759886,4.367007,1.764075,1.350603,5.186006,0.370732
+52.300000,8.156655,3.180032,1.912829,4.200837,1.603340,0.481303,5.087253,0.120511,3.082883,0.634320,0.000243,0.345680,0.041141,23.385009,1.546437,19.604635,16.759795,4.369065,1.763987,1.350603,5.186006,0.413831
+52.400000,8.156077,3.233503,1.961942,4.081201,1.577050,0.470049,5.358125,0.123816,3.168285,0.629293,0.000253,0.350707,0.041351,23.441732,1.539210,19.616576,16.760158,4.390439,1.763941,1.350159,5.186005,0.391007
+52.500000,8.156098,3.238462,2.100154,4.137820,1.499405,0.482755,5.398833,0.124196,3.189591,0.635169,0.000279,0.344831,0.041325,23.490895,1.541268,19.615793,16.760671,4.414288,1.763972,1.349628,5.186005,0.330440
+52.600000,8.156724,3.190076,2.243919,4.357004,1.412016,0.515432,5.141436,0.120895,3.122872,0.649863,0.000308,0.330137,0.041034,23.491136,1.552615,19.601455,16.760950,4.421765,1.764058,1.349403,5.186006,0.274064
+52.700000,8.157559,3.119783,2.260206,4.572387,1.402181,0.540809,4.763206,0.116066,3.006767,0.661495,0.000309,0.318505,0.040684,23.432359,1.566137,19.582079,16.760711,4.403667,1.764126,1.349743,5.186007,0.267613
+52.800000,8.157763,3.095508,2.097618,4.539383,1.502032,0.527408,4.662840,0.114923,2.961587,0.655760,0.000274,0.324240,0.040678,23.371504,1.566031,19.578995,16.760122,4.375605,1.764112,1.350385,5.186007,0.330351
+52.900000,8.157084,3.144609,1.939514,4.310149,1.589692,0.494457,4.916463,0.118337,3.031299,0.640440,0.000247,0.339560,0.040982,23.366819,1.552876,19.595368,16.759773,4.364871,1.764030,1.350676,5.186006,0.400794
+53.000000,8.156302,3.211489,1.922384,4.121321,1.598127,0.472888,5.242603,0.122431,3.131023,0.630494,0.000246,0.349506,0.041269,23.411652,1.541741,19.612003,16.759936,4.378262,1.763955,1.350416,5.186005,0.409489
+53.100000,8.156006,3.242979,2.024137,4.086013,1.542914,0.473306,5.414912,0.124457,3.189210,0.630861,0.000264,0.349139,0.041371,23.470046,1.539015,19.617923,16.760420,4.403285,1.763947,1.349879,5.186005,0.362948
+53.200000,8.156347,3.220037,2.178782,4.232987,1.452399,0.497633,5.304131,0.122969,3.167007,0.641862,0.000294,0.338138,0.041208,23.499141,1.545946,19.610145,16.760863,4.421082,1.764012,1.349454,5.186006,0.298819
+53.300000,8.157163,3.153807,2.276378,4.482604,1.391545,0.531684,4.943007,0.118362,3.064496,0.657230,0.000314,0.322770,0.040840,23.467045,1.560073,19.591175,16.760901,4.415596,1.764100,1.349502,5.186007,0.262077
+53.400000,8.157787,3.097856,2.193905,4.593968,1.444041,0.539065,4.659261,0.114778,2.968094,0.660928,0.000293,0.319072,0.040623,23.397093,1.568462,19.577402,16.760425,4.388974,1.764131,1.350069,5.186007,0.292053
+53.500000,8.157495,3.113299,2.004133,4.432451,1.555075,0.510827,4.761653,0.116297,2.986484,0.648110,0.000257,0.331890,0.040814,23.361323,1.560045,19.585921,16.759886,4.366998,1.764076,1.350603,5.186006,0.370792
+53.600000,8.156654,3.180092,1.912813,4.200674,1.603347,0.481285,5.087530,0.120515,3.082967,0.634312,0.000243,0.345688,0.041141,23.385076,1.546427,19.604650,16.759795,4.369077,1.763987,1.350603,5.186006,0.413840
+53.700000,8.156077,3.233528,1.962035,4.081181,1.577000,0.470051,5.358259,0.123817,3.168330,0.629294,0.000253,0.350706,0.041352,23.441809,1.539208,19.616580,16.760159,4.390461,1.763941,1.350158,5.186005,0.390965
+53.800000,8.156098,3.238441,2.100281,4.137935,1.499332,0.482774,5.398746,0.124195,3.189573,0.635178,0.000279,0.344822,0.041325,23.490950,1.541274,19.615786,16.760671,4.414305,1.763973,1.349627,5.186005,0.330387
+53.900000,8.156724,3.190034,2.244002,4.357165,1.411966,0.515455,5.141222,0.120892,3.122813,0.649874,0.000308,0.330126,0.041034,23.491159,1.552625,19.601443,16.760951,4.421770,1.764059,1.349403,5.186006,0.274032
+54.000000,8.157559,3.119727,2.260224,4.572569,1.402170,0.540830,4.762894,0.116062,3.006671,0.661505,0.000309,0.318495,0.040684,23.432344,1.566148,19.582064,16.760712,4.403655,1.764127,1.349744,5.186007,0.267605
+54.100000,8.157763,3.095479,2.097477,4.539381,1.502112,0.527400,4.662702,0.114921,2.961532,0.655757,0.000274,0.324243,0.040678,23.371470,1.566033,19.578990,16.760122,4.375579,1.764112,1.350386,5.186007,0.330411
+54.200000,8.157083,3.144657,1.939347,4.309930,1.589784,0.494425,4.916694,0.118340,3.031359,0.640428,0.000247,0.339572,0.040981,23.366833,1.552864,19.595384,16.759772,4.364859,1.764031,1.350676,5.186006,0.400869
+54.300000,8.156301,3.211552,1.922375,4.121163,1.598131,0.472869,5.242890,0.122435,3.131112,0.630485,0.000246,0.349515,0.041270,23.411712,1.541731,19.612017,16.759936,4.378273,1.763955,1.350416,5.186005,0.409494
+54.400000,8.156006,3.243007,2.024215,4.085978,1.542870,0.473305,5.415085,0.124458,3.189268,0.630860,0.000264,0.349140,0.041373,23.470107,1.539016,19.617924,16.760420,4.403305,1.763947,1.349879,5.186005,0.362914
+54.500000,8.156347,3.220028,2.178917,4.233082,1.452315,0.497651,5.304114,0.122969,3.167011,0.641870,0.000294,0.338130,0.041208,23.499193,1.545950,19.610140,16.760864,4.421101,1.764013,1.349453,5.186006,0.298767
+54.600000,8.157164,3.153749,2.276507,4.482856,1.391462,0.531721,4.942688,0.118358,3.064408,0.657247,0.000314,0.322753,0.040840,23.467041,1.560087,19.591157,16.760901,4.415597,1.764100,1.349502,5.186007,0.262031
+54.700000,8.157788,3.097787,2.193868,4.594155,1.444065,0.539084,4.658903,0.114773,2.967976,0.660937,0.000293,0.319063,0.040623,23.397032,1.568475,19.577383,16.760425,4.388950,1.764131,1.350070,5.186007,0.292067
+54.800000,8.157495,3.113287,2.003958,4.432384,1.555174,0.510811,4.761616,0.116297,2.986460,0.648102,0.000257,0.331898,0.040814,23.361274,1.560042,19.585922,16.759885,4.366969,1.764076,1.350604,5.186006,0.370868
+54.900000,8.156654,3.180139,1.912687,4.200494,1.603411,0.481261,5.087742,0.120518,3.083026,0.634300,0.000243,0.345700,0.041141,23.385070,1.546418,19.604663,16.759795,4.369065,1.763987,1.350603,5.186006,0.413902
+55.000000,8.156076,3.233583,1.962028,4.081033,1.576996,0.470033,5.358523,0.123820,3.168412,0.629281,0.000253,0.350719,0.041353,23.441846,1.539199,19.616593,16.760159,4.390469,1.763941,1.350158,5.186005,0.390975
+55.100000,8.156098,3.238458,2.100382,4.137965,1.499274,0.482783,5.398816,0.124196,3.189599,0.635185,0.000279,0.344815,0.041324,23.490983,1.541273,19.615790,16.760671,4.414319,1.763973,1.349627,5.186005,0.330343
+55.200000,8.156725,3.189985,2.244118,4.357388,1.411890,0.515488,5.140933,0.120888,3.122734,0.649888,0.000308,0.330112,0.041034,23.491128,1.552637,19.601427,16.760951,4.421764,1.764059,1.349403,5.186006,0.273991
+55.300000,8.157560,3.119682,2.260150,4.572652,1.402218,0.540836,4.762671,0.116059,3.006593,0.661507,0.000309,0.318493,0.040684,23.432270,1.566156,19.582051,16.760711,4.403628,1.764127,1.349744,5.186007,0.267632
+55.400000,8.157763,3.095502,2.097338,4.539233,1.502194,0.527376,4.662838,0.114923,2.961565,0.655746,0.000274,0.324254,0.040678,23.371440,1.566025,19.578999,16.760121,4.375563,1.764112,1.350386,5.186007,0.330467
+55.500000,8.157083,3.144695,1.939315,4.309812,1.589801,0.494411,4.916879,0.118343,3.031414,0.640422,0.000247,0.339578,0.040981,23.366837,1.552857,19.595394,16.759772,4.364859,1.764031,1.350676,5.186006,0.400883
+55.600000,8.156301,3.211578,1.922399,4.121103,1.598119,0.472864,5.243036,0.122436,3.131159,0.630482,0.000246,0.349518,0.041270,23.411725,1.541728,19.612023,16.759936,4.378281,1.763955,1.350416,5.186005,0.409482
+55.700000,8.156006,3.243008,2.024283,4.086022,1.542831,0.473313,5.415094,0.124459,3.189274,0.630871,0.000264,0.349129,0.041374,23.470109,1.539018,19.617924,16.760420,4.403315,1.763947,1.349879,5.186005,0.362885
+55.800000,8.156347,3.219990,2.178993,4.233245,1.452270,0.497674,5.303898,0.122966,3.166952,0.641880,0.000294,0.338120,0.041207,23.499161,1.545959,19.610129,16.760864,4.421097,1.764013,1.349454,5.186006,0.298737
+55.900000,8.157165,3.153708,2.276443,4.482939,1.391504,0.531726,4.942475,0.118355,3.064336,0.657250,0.000314,0.322750,0.040840,23.466967,1.560094,19.591146,16.760900,4.415574,1.764100,1.349503,5.186007,0.262053
+56.000000,8.157788,3.097791,2.193715,4.594039,1.444159,0.539062,4.658959,0.114774,2.967982,0.660927,0.000293,0.319073,0.040623,23.396983,1.568469,19.577389,16.760424,4.388928,1.764131,1.350070,5.186007,0.292126
+56.100000,8.157494,3.113344,2.003870,4.432178,1.555220,0.510785,4.761889,0.116300,2.986542,0.648090,0.000257,0.331910,0.040814,23.361275,1.560030,19.585939,16.759885,4.366967,1.764076,1.350604,5.186006,0.370910
+56.200000,8.156653,3.180184,1.912717,4.200383,1.603397,0.481249,5.087968,0.120520,3.083097,0.634295,0.000243,0.345705,0.041141,23.385099,1.546411,19.604673,16.759795,4.369080,1.763987,1.350603,5.186006,0.413887
+56.300000,8.156076,3.233594,1.962110,4.081042,1.576959,0.470039,5.358602,0.123821,3.168438,0.629288,0.000253,0.350712,0.041352,23.441870,1.539200,19.616594,16.760159,4.390487,1.763941,1.350158,5.186005,0.390930
+56.400000,8.156098,3.238436,2.100487,4.138075,1.499210,0.482801,5.398714,0.124194,3.189579,0.635189,0.000279,0.344811,0.041325,23.490987,1.541280,19.615782,16.760672,4.414330,1.763973,1.349627,5.186005,0.330302
+56.500000,8.156725,3.189939,2.244172,4.357554,1.411857,0.515510,5.140683,0.120885,3.122662,0.649898,0.000308,0.330102,0.041033,23.491090,1.552647,19.601414,16.760951,4.421758,1.764059,1.349403,5.186006,0.273970
+56.600000,8.157561,3.119647,2.260073,4.572702,1.402266,0.540836,4.762505,0.116057,3.006533,0.661508,0.000309,0.318492,0.040683,23.432210,1.566160,19.582043,16.760710,4.403609,1.764127,1.349745,5.186007,0.267661
+56.700000,8.157762,3.095528,2.097197,4.539069,1.502277,0.527351,4.662989,0.114925,2.961604,0.655734,0.000274,0.324266,0.040679,23.371416,1.566016,19.579010,16.760121,4.375551,1.764112,1.350387,5.186007,0.330526
+56.800000,8.157082,3.144751,1.939270,4.309628,1.589824,0.494389,4.917158,0.118346,3.031499,0.640411,0.000247,0.339589,0.040981,23.366860,1.552846,19.595409,16.759772,4.364867,1.764030,1.350676,5.186006,0.400906
+56.900000,8.156300,3.211613,1.922480,4.121047,1.598076,0.472861,5.243209,0.122438,3.131215,0.630481,0.000246,0.349519,0.041270,23.411773,1.541725,19.612030,16.759936,4.378305,1.763955,1.350416,5.186005,0.409443
+57.000000,8.156006,3.242999,2.024415,4.086101,1.542758,0.473328,5.415064,0.124458,3.189276,0.630871,0.000264,0.349129,0.041373,23.470147,1.539022,19.617920,16.760420,4.403334,1.763947,1.349878,5.186005,0.362826
+57.100000,8.156348,3.219948,2.179098,4.233417,1.452205,0.497699,5.303678,0.122963,3.166894,0.641891,0.000294,0.338109,0.041207,23.499155,1.545968,19.610118,16.760864,4.421103,1.764013,1.349454,5.186006,0.298696
+57.200000,8.157165,3.153649,2.276437,4.483110,1.391510,0.531745,4.942148,0.118351,3.064235,0.657258,0.000314,0.322742,0.040840,23.466908,1.560105,19.591129,16.760900,4.415556,1.764100,1.349503,5.186007,0.262053
+57.300000,8.157788,3.097792,2.193516,4.593896,1.444281,0.539035,4.659010,0.114775,2.967980,0.660915,0.000293,0.319085,0.040623,23.396936,1.568462,19.577393,16.760424,4.388906,1.764131,1.350071,5.186007,0.292203
+57.400000,8.157493,3.113412,2.003791,4.431943,1.555262,0.510756,4.762227,0.116305,2.986645,0.648076,0.000257,0.331924,0.040815,23.361306,1.560016,19.585959,16.759885,4.366974,1.764076,1.350604,5.186007,0.370947
+57.500000,8.156653,3.180227,1.912780,4.200295,1.603363,0.481242,5.088187,0.120523,3.083169,0.634292,0.000243,0.345708,0.041141,23.385155,1.546405,19.604683,16.759796,4.369102,1.763987,1.350603,5.186006,0.413856
+57.600000,8.156076,3.233595,1.962229,4.081091,1.576896,0.470049,5.358630,0.123822,3.168454,0.629293,0.000253,0.350707,0.041352,23.441917,1.539202,19.616593,16.760160,4.390510,1.763941,1.350158,5.186005,0.390875
+57.700000,8.156099,3.238398,2.100599,4.138237,1.499145,0.482824,5.398525,0.124192,3.189530,0.635200,0.000279,0.344800,0.041325,23.490998,1.541288,19.615771,16.760672,4.414339,1.763973,1.349627,5.186005,0.330256
+57.800000,8.156726,3.189885,2.244194,4.357718,1.411843,0.515530,5.140394,0.120881,3.122576,0.649907,0.000308,0.330093,0.041033,23.491057,1.552657,19.601400,16.760950,4.421748,1.764059,1.349403,5.186006,0.273962
+57.900000,8.157561,3.119627,2.259953,4.572680,1.402344,0.540826,4.762420,0.116056,3.006497,0.661503,0.000309,0.318497,0.040683,23.432175,1.566161,19.582041,16.760710,4.403590,1.764127,1.349745,5.186007,0.267703
+58.000000,8.157762,3.095566,2.097063,4.538866,1.502355,0.527320,4.663214,0.114928,2.961666,0.655720,0.000274,0.324280,0.040679,23.371431,1.566004,19.579025,16.760120,4.375546,1.764112,1.350387,5.186007,0.330582
+58.100000,8.157082,3.144808,1.939289,4.309483,1.589811,0.494373,4.917424,0.118350,3.031587,0.640399,0.000247,0.339601,0.040981,23.366925,1.552836,19.595424,16.759772,4.364884,1.764030,1.350676,5.186006,0.400900
+58.200000,8.156300,3.211635,1.922562,4.121026,1.598039,0.472861,5.243332,0.122441,3.131255,0.630487,0.000246,0.349513,0.041268,23.411840,1.541723,19.612035,16.759937,4.378329,1.763955,1.350415,5.186005,0.409399
+58.300000,8.156006,3.242985,2.024534,4.086194,1.542692,0.473344,5.414995,0.124457,3.189266,0.630874,0.000264,0.349126,0.041374,23.470201,1.539025,19.617916,16.760421,4.403352,1.763947,1.349878,5.186005,0.362774
+58.400000,8.156348,3.219896,2.179183,4.233616,1.452154,0.497726,5.303380,0.122959,3.166811,0.641904,0.000294,0.338096,0.041207,23.499157,1.545979,19.610104,16.760864,4.421102,1.764013,1.349453,5.186006,0.298663
+58.500000,8.157166,3.153609,2.276377,4.483185,1.391548,0.531749,4.941939,0.118348,3.064164,0.657261,0.000314,0.322739,0.040840,23.466884,1.560111,19.591120,16.760900,4.415540,1.764100,1.349504,5.186007,0.262075
+58.600000,8.157788,3.097803,2.193401,4.593794,1.444353,0.539015,4.659076,0.114776,2.967994,0.660906,0.000293,0.319094,0.040624,23.396947,1.568457,19.577400,16.760424,4.388895,1.764131,1.350071,5.186007,0.292246
+58.700000,8.157492,3.113461,2.003694,4.431737,1.555316,0.510728,4.762488,0.116308,2.986722,0.648063,0.000257,0.331937,0.040815,23.361354,1.560003,19.585975,16.759885,4.366976,1.764076,1.350604,5.186007,0.370990
+58.800000,8.156652,3.180288,1.912815,4.200148,1.603344,0.481227,5.088484,0.120527,3.083262,0.634285,0.000243,0.345715,0.041142,23.385247,1.546397,19.604698,16.759796,4.369126,1.763987,1.350602,5.186006,0.413840
+58.900000,8.156076,3.233605,1.962367,4.081127,1.576822,0.470059,5.358701,0.123822,3.168483,0.629298,0.000253,0.350702,0.041352,23.442007,1.539203,19.616594,16.760161,4.390538,1.763941,1.350157,5.186005,0.390811
+59.000000,8.156099,3.238356,2.100746,4.138426,1.499059,0.482853,5.398319,0.124189,3.189479,0.635213,0.000279,0.344787,0.041325,23.491048,1.541297,19.615760,16.760673,4.414354,1.763973,1.349626,5.186005,0.330195
+59.100000,8.156726,3.189820,2.244247,4.357934,1.411810,0.515558,5.140041,0.120877,3.122473,0.649920,0.000308,0.330080,0.041033,23.491055,1.552669,19.601383,16.760951,4.421740,1.764059,1.349403,5.186006,0.273942
+59.200000,8.157561,3.119584,2.259850,4.572744,1.402411,0.540826,4.762199,0.116053,3.006418,0.661504,0.000309,0.318496,0.040683,23.432151,1.566166,19.582031,16.760710,4.403567,1.764127,1.349746,5.186007,0.267738
+59.300000,8.157761,3.095581,2.096867,4.538697,1.502469,0.527291,4.663316,0.114930,2.961683,0.655707,0.000274,0.324293,0.040679,23.371432,1.565995,19.579033,16.760120,4.375525,1.764112,1.350387,5.186007,0.330664
+59.400000,8.157080,3.144894,1.939165,4.309180,1.589877,0.494335,4.917850,0.118355,3.031711,0.640386,0.000247,0.339614,0.040982,23.366994,1.552819,19.595448,16.759773,4.364890,1.764031,1.350675,5.186006,0.400958
+59.500000,8.156299,3.211702,1.922644,4.120884,1.597990,0.472849,5.243671,0.122444,3.131365,0.630476,0.000246,0.349524,0.041271,23.411954,1.541714,19.612049,16.759938,4.378358,1.763956,1.350414,5.186005,0.409366
+59.600000,8.156006,3.242983,2.024709,4.086282,1.542594,0.473362,5.415029,0.124457,3.189284,0.630887,0.000264,0.349113,0.041373,23.470296,1.539030,19.617912,16.760422,4.403384,1.763948,1.349877,5.186005,0.362696
+59.700000,8.156348,3.219847,2.179349,4.233831,1.452051,0.497760,5.303156,0.122956,3.166756,0.641919,0.000294,0.338081,0.041207,23.499212,1.545990,19.610089,16.760865,4.421119,1.764013,1.349453,5.186006,0.298600
+59.800000,8.157166,3.153532,2.276465,4.483460,1.391492,0.531786,4.941530,0.118343,3.064044,0.657278,0.000314,0.322722,0.040839,23.466887,1.560127,19.591098,16.760900,4.415535,1.764101,1.349503,5.186007,0.262042
+59.900000,8.157788,3.097758,2.193283,4.593852,1.444426,0.539015,4.658865,0.114773,2.967916,0.660907,0.000293,0.319093,0.040623,23.396925,1.568462,19.577390,16.760424,4.388872,1.764132,1.350071,5.186007,0.292291
+60.000000,9.645909,3.645198,2.085866,4.126192,1.507726,0.480728,5.422917,0.124491,3.195887,0.633963,0.000276,0.346037,0.041369,24.513290,1.542389,19.625710,16.768410,4.417965,1.766012,1.351254,5.185553,0.336408
+60.100000,9.646508,3.599885,2.235589,4.336896,1.417238,0.512646,5.187136,0.121462,3.136225,0.648317,0.000306,0.331683,0.041095,24.519229,1.553128,19.612318,16.768729,4.427639,1.766097,1.350984,5.185554,0.277172
+60.200000,9.647466,3.522460,2.269193,4.566618,1.396386,0.540730,4.798837,0.116509,3.018910,0.661126,0.000311,0.318874,0.040729,24.463675,1.567257,19.592360,16.768536,4.411409,1.766171,1.351278,5.185555,0.264421
+60.300000,9.647873,3.484478,2.115960,4.560392,1.491249,0.530748,4.659248,0.114848,2.961960,0.656974,0.000277,0.323026,0.040682,24.398878,1.568823,19.587053,16.767948,4.382639,1.766165,1.351929,5.185555,0.322791
+60.400000,9.647251,3.528228,1.946355,4.335562,1.586137,0.497544,4.894047,0.118037,3.024784,0.641581,0.000248,0.338419,0.040974,24.388366,1.556023,19.602618,16.767551,4.369456,1.766085,1.352274,5.185554,0.397508
+60.500000,9.646338,3.602623,1.915615,4.134400,1.601683,0.474062,5.228713,0.122255,3.126524,0.630714,0.000245,0.349286,0.041277,24.430411,1.544167,19.620070,16.767672,4.381107,1.766005,1.352055,5.185553,0.412703
+60.600000,9.645876,3.645375,2.009551,4.081741,1.551031,0.472162,5.425001,0.124580,3.191395,0.630036,0.000262,0.349964,0.041404,24.489995,1.540537,19.627243,16.768146,4.406101,1.765989,1.351522,5.185553,0.369418
+60.700000,9.646121,3.629867,2.164547,4.213163,1.461050,0.494604,5.343527,0.123455,3.177873,0.640212,0.000292,0.339788,0.041265,24.524239,1.546585,19.620752,16.768616,4.425676,1.766050,1.351063,5.185553,0.304404
+60.800000,9.646981,3.562095,2.275685,4.464321,1.391939,0.529555,4.992577,0.118982,3.079916,0.655961,0.000314,0.324039,0.040902,24.498042,1.560545,19.602212,16.768706,4.422771,1.766140,1.351054,5.185554,0.262376
+60.900000,9.647795,3.494006,2.211812,4.602813,1.432905,0.541158,4.676924,0.114981,2.975360,0.661534,0.000297,0.318466,0.040647,24.427751,1.570434,19.586638,16.768264,4.396983,1.766180,1.351593,5.185555,0.285282
+61.000000,9.647668,3.497329,2.019786,4.461030,1.546437,0.514727,4.742240,0.116022,2.981478,0.649620,0.000260,0.330380,0.040806,24.385628,1.563355,19.593139,16.767694,4.372960,1.766131,1.352170,5.185554,0.363777
+61.100000,9.646779,3.565674,1.912536,4.222820,1.603549,0.483715,5.063818,0.120209,3.075736,0.635127,0.000243,0.344873,0.041137,24.404362,1.549375,19.612041,16.767548,4.372502,1.766041,1.352228,5.185553,0.413914
+61.200000,9.646030,3.629998,1.949696,4.086372,1.583609,0.470108,5.353111,0.123754,3.166155,0.628999,0.000251,0.351001,0.041369,24.460087,1.541220,19.625187,16.767881,4.392828,1.765987,1.351809,5.185553,0.396695
+61.300000,9.645904,3.645503,2.083145,4.123828,1.509304,0.480329,5.424500,0.124513,3.196169,0.633781,0.000276,0.346219,0.041371,24.512722,1.542279,19.625829,16.768402,4.417625,1.766011,1.351262,5.185553,0.337551
+61.400000,9.646492,3.601086,2.233693,4.332499,1.418427,0.512035,5.193385,0.121541,3.137971,0.648041,0.000306,0.331959,0.041102,24.519736,1.552883,19.612645,16.768727,4.427702,1.766096,1.350984,5.185554,0.277880
+61.500000,9.647452,3.523627,2.270383,4.564311,1.395617,0.540543,4.804256,0.116578,3.020718,0.661036,0.000312,0.318964,0.040733,24.464920,1.567088,19.592627,16.768544,4.411863,1.766170,1.351269,5.185555,0.264000
+61.600000,9.647875,3.484394,2.119322,4.562978,1.489255,0.531223,4.657952,0.114826,2.961803,0.657190,0.000278,0.322810,0.040683,24.399589,1.568955,19.586928,16.767957,4.383048,1.766166,1.351919,5.185555,0.321423
+61.700000,9.647267,3.527034,1.948159,4.339668,1.585189,0.498074,4.888495,0.117965,3.023148,0.641829,0.000248,0.338171,0.040969,24.388045,1.556265,19.602290,16.767553,4.369459,1.766087,1.352274,5.185554,0.396652
+61.800000,9.646351,3.601516,1.914967,4.136735,1.602026,0.474295,5.223766,0.122195,3.124980,0.630818,0.000245,0.349182,0.041273,24.429469,1.544305,19.619846,16.767666,4.380758,1.766006,1.352063,5.185553,0.413007
+61.900000,9.645878,3.645099,2.007281,4.081142,1.552289,0.471994,5.423723,0.124567,3.190868,0.629956,0.000261,0.350044,0.041404,24.489099,1.540521,19.627229,16.768137,4.405675,1.765989,1.351532,5.185553,0.370430
+62.000000,9.646111,3.630620,2.161932,4.209588,1.462632,0.494058,5.347465,0.123505,3.178857,0.639967,0.000291,0.340033,0.041269,24.524120,1.546405,19.620975,16.768610,4.425499,1.766049,1.351068,5.185553,0.305436
+62.100000,9.646964,3.563449,2.275011,4.460223,1.392365,0.529049,4.999442,0.119070,3.081984,0.655729,0.000314,0.324271,0.040909,24.499029,1.560293,19.602566,16.768709,4.423050,1.766139,1.351049,5.185554,0.262625
+62.200000,9.647788,3.494689,2.214528,4.602913,1.431204,0.541338,4.679401,0.115011,2.976379,0.661607,0.000298,0.318393,0.040648,24.428914,1.570404,19.586736,16.768274,4.397491,1.766180,1.351582,5.185555,0.284268
+62.300000,9.647679,3.496551,2.022733,4.464990,1.544801,0.515307,4.738079,0.115965,2.980353,0.649891,0.000260,0.330109,0.040801,24.385815,1.563583,19.592862,16.767701,4.373187,1.766133,1.352164,5.185554,0.362466
+62.400000,9.646795,3.564393,1.913033,4.226249,1.603301,0.484113,5.058092,0.120137,3.073993,0.635311,0.000243,0.344689,0.041132,24.403657,1.549577,19.611743,16.767546,4.372301,1.766043,1.352232,5.185554,0.413666
+62.500000,9.646038,3.629263,1.948110,4.087305,1.584455,0.470147,5.349712,0.123714,3.165038,0.629013,0.000251,0.350987,0.041367,24.459082,1.541283,19.625064,16.767873,4.392400,1.765988,1.351819,5.185553,0.397435
+62.600000,9.645900,3.645751,2.080513,4.121648,1.510829,0.479954,5.425773,0.124530,3.196367,0.633607,0.000275,0.346393,0.041374,24.512136,1.542179,19.625935,16.768393,4.417284,1.766010,1.351270,5.185553,0.338659
+62.700000,9.646477,3.602239,2.231702,4.328153,1.419673,0.511424,5.199394,0.121617,3.139634,0.647766,0.000305,0.332234,0.041108,24.520177,1.552644,19.612960,16.768725,4.427741,1.766094,1.350985,5.185554,0.278625
+62.800000,9.647437,3.524831,2.271417,4.561775,1.394941,0.540326,4.809886,0.116649,3.022580,0.660931,0.000312,0.319069,0.040738,24.466163,1.566908,19.592907,16.768551,4.412308,1.766170,1.351260,5.185555,0.263642
+62.900000,9.647877,3.484347,2.122702,4.565475,1.487252,0.531691,4.656781,0.114809,2.961690,0.657399,0.000279,0.322601,0.040676,24.400336,1.569079,19.586815,16.767967,4.383466,1.766167,1.351909,5.185555,0.320046
+63.000000,9.647282,3.525860,1.949984,4.343736,1.584228,0.498600,4.883008,0.117893,3.021533,0.642076,0.000249,0.337924,0.040963,24.387742,1.556505,19.601965,16.767556,4.369469,1.766089,1.352273,5.185554,0.395788
+63.100000,9.646364,3.600414,1.914357,4.139082,1.602349,0.474531,5.218818,0.122134,3.123438,0.630924,0.000244,0.349076,0.041269,24.428539,1.544444,19.619621,16.767660,4.380414,1.766008,1.352070,5.185553,0.413293
+63.200000,9.645880,3.644818,2.005048,4.080589,1.553524,0.471833,5.422383,0.124552,3.190325,0.629880,0.000261,0.350120,0.041404,24.488205,1.540506,19.627215,16.768127,4.405249,1.765989,1.351541,5.185553,0.371428
+63.300000,9.646101,3.631348,2.159349,4.206107,1.464195,0.493525,5.351236,0.123554,3.179791,0.639727,0.000291,0.340273,0.041273,24.523978,1.546229,19.621193,16.768604,4.425314,1.766047,1.351073,5.185553,0.306456
+63.400000,9.646948,3.564776,2.274237,4.456139,1.392852,0.528537,5.006167,0.119156,3.083994,0.655496,0.000314,0.324504,0.040915,24.499954,1.560045,19.602912,16.768712,4.423306,1.766138,1.351045,5.185554,0.262911
+63.500000,9.647780,3.495414,2.217078,4.602775,1.429605,0.541482,4.682133,0.115044,2.977466,0.661665,0.000299,0.318335,0.040649,24.430068,1.570361,19.586849,16.768284,4.397987,1.766180,1.351571,5.185555,0.283317
+63.600000,9.647689,3.495845,2.025709,4.468794,1.543140,0.515873,4.734212,0.115912,2.979326,0.650153,0.000261,0.329847,0.040796,24.386048,1.563800,19.592601,16.767708,4.373430,1.766134,1.352158,5.185554,0.361150
+63.700000,9.646811,3.563125,1.913639,4.229703,1.602998,0.484518,5.052426,0.120065,3.072273,0.635499,0.000243,0.344501,0.041126,24.402991,1.549780,19.611444,16.767544,4.372120,1.766044,1.352236,5.185554,0.413363
+63.800000,9.646046,3.628505,1.946611,4.088333,1.585256,0.470200,5.346222,0.123673,3.163899,0.629034,0.000250,0.350966,0.041364,24.458091,1.541351,19.624934,16.767865,4.391982,1.765988,1.351827,5.185553,0.398133
+63.900000,9.645896,3.645959,2.077916,4.119599,1.512329,0.479598,5.426855,0.124546,3.196508,0.633449,0.000275,0.346551,0.041376,24.511524,1.542088,19.626030,16.768385,4.416939,1.766009,1.351278,5.185553,0.339754
+64.000000,9.646463,3.603357,2.229685,4.323891,1.420935,0.510822,5.205225,0.121692,3.141241,0.647495,0.000305,0.332505,0.041114,24.520581,1.552410,19.613268,16.768723,4.427767,1.766093,1.350986,5.185554,0.279379
+64.100000,9.647423,3.526034,2.272318,4.559150,1.394353,0.540087,4.815556,0.116722,3.024440,0.660817,0.000312,0.319183,0.040743,24.467379,1.566724,19.593191,16.768558,4.412738,1.766169,1.351251,5.185555,0.263329
+64.200000,9.647878,3.484373,2.125985,4.567698,1.485298,0.532124,4.656011,0.114795,2.961700,0.657593,0.000279,0.322407,0.040674,24.401126,1.569187,19.586723,16.767977,4.383892,1.766168,1.351899,5.185555,0.318717
+64.300000,9.647297,3.524730,1.951941,4.347786,1.583194,0.499131,4.877682,0.117823,3.019977,0.642325,0.000249,0.337675,0.040957,24.387509,1.556743,19.601646,16.767558,4.369507,1.766091,1.352271,5.185554,0.394865
+64.400000,9.646377,3.599288,1.913862,4.141538,1.602615,0.474783,5.213785,0.122072,3.121875,0.631038,0.000244,0.348962,0.041265,24.427647,1.544589,19.619389,16.767655,4.380088,1.766009,1.352077,5.185553,0.413523
+64.500000,9.645883,3.644490,2.002868,4.080169,1.554729,0.471690,5.420849,0.124536,3.189729,0.629812,0.000261,0.350188,0.041403,24.487313,1.540500,19.627188,16.768119,4.404825,1.765989,1.351550,5.185553,0.372403
+64.600000,9.646092,3.632042,2.156721,4.202686,1.465781,0.492998,5.354866,0.123600,3.180683,0.639491,0.000290,0.340509,0.041278,24.523815,1.546061,19.621400,16.768598,4.425119,1.766046,1.351078,5.185553,0.307497
+64.700000,9.646931,3.566106,2.273369,4.451980,1.393404,0.528010,5.012956,0.119243,3.086017,0.655258,0.000314,0.324742,0.040922,24.500885,1.559792,19.603263,16.768714,4.423555,1.766137,1.351041,5.185554,0.263227
+64.800000,9.647771,3.496183,2.219562,4.602457,1.428044,0.541603,4.685133,0.115081,2.978632,0.661711,0.000299,0.318289,0.040650,24.431275,1.570306,19.586977,16.768294,4.398492,1.766181,1.351560,5.185555,0.282393
+64.900000,9.647699,3.495174,2.028778,4.472577,1.541426,0.516441,4.730479,0.115861,2.978347,0.650417,0.000261,0.329583,0.040791,24.386354,1.564015,19.592345,16.767715,4.373696,1.766136,1.352151,5.185555,0.359796
+65.000000,9.646826,3.561838,1.914341,4.233253,1.602644,0.484938,5.046681,0.119992,3.070533,0.635694,0.000244,0.344306,0.041121,24.402373,1.549988,19.611140,16.767543,4.371954,1.766046,1.352239,5.185554,0.413015
+65.100000,9.646054,3.627711,1.945138,4.089463,1.586041,0.470265,5.342587,0.123630,3.162715,0.629065,0.000250,0.350935,0.041362,24.457114,1.541426,19.624795,16.767857,4.391566,1.765989,1.351836,5.185553,0.398821
+65.200000,9.645893,3.646138,2.075302,4.117609,1.513838,0.479247,5.427799,0.124559,3.196608,0.633290,0.000274,0.346710,0.041378,24.510920,1.542000,19.626120,16.768377,4.416588,1.766009,1.351286,5.185553,0.340860
+65.300000,9.646448,3.604477,2.227582,4.319563,1.422250,0.510207,5.211089,0.121766,3.142851,0.647219,0.000305,0.332781,0.041120,24.521001,1.552174,19.613579,16.768721,4.427785,1.766091,1.350986,5.185554,0.280167
+65.400000,9.647407,3.527276,2.273183,4.556393,1.393789,0.539831,4.821436,0.116797,3.026364,0.660696,0.000313,0.319304,0.040748,24.468662,1.566530,19.593488,16.768566,4.413178,1.766169,1.351242,5.185555,0.263028
+65.500000,9.647879,3.484398,2.129398,4.570044,1.483266,0.532579,4.655150,0.114780,2.961691,0.657796,0.000280,0.322204,0.040671,24.401968,1.569302,19.586626,16.767987,4.384332,1.766169,1.351888,5.185555,0.317336
+65.600000,9.647312,3.523551,1.953874,4.351929,1.582177,0.499671,4.872166,0.117751,3.018359,0.642578,0.000249,0.337422,0.040952,24.387274,1.556987,19.601317,16.767562,4.369535,1.766092,1.352270,5.185554,0.393950
+65.700000,9.646389,3.598167,1.913311,4.143963,1.602907,0.475030,5.208757,0.122011,3.120310,0.631149,0.000244,0.348851,0.041261,24.426767,1.544732,19.619160,16.767650,4.379753,1.766010,1.352083,5.185553,0.413782
+65.800000,9.645885,3.644177,2.000664,4.079714,1.555945,0.471541,5.419360,0.124519,3.189144,0.629742,0.000260,0.350258,0.041403,24.486445,1.540491,19.627165,16.768110,4.404398,1.765989,1.351560,5.185553,0.373391
+65.900000,9.646082,3.632747,2.154102,4.199249,1.467361,0.492468,5.358531,0.123647,3.181584,0.639253,0.000289,0.340747,0.041283,24.523684,1.545889,19.621611,16.768592,4.424924,1.766045,1.351083,5.185553,0.308537
+66.000000,9.646914,3.567441,2.272527,4.447829,1.393934,0.527486,5.019750,0.119329,3.088041,0.655019,0.000314,0.324981,0.040928,24.501845,1.559540,19.603614,16.768717,4.423807,1.766136,1.351036,5.185554,0.263539
+66.100000,9.647762,3.496939,2.222073,4.602211,1.426469,0.541730,4.688042,0.115116,2.979771,0.661763,0.000300,0.318237,0.040652,24.432490,1.570257,19.587099,16.768304,4.398996,1.766181,1.351548,5.185555,0.281459
+66.200000,9.647708,3.494489,2.031813,4.476380,1.539727,0.517011,4.726683,0.115809,2.977347,0.650681,0.000262,0.329319,0.040786,24.386655,1.564231,19.592087,16.767723,4.373952,1.766138,1.352144,5.185555,0.358459
+66.300000,9.646841,3.560557,1.915006,4.236780,1.602310,0.485354,5.040954,0.119920,3.068796,0.635887,0.000244,0.344113,0.041116,24.401755,1.550196,19.610836,16.767541,4.371780,1.766048,1.352242,5.185554,0.412684
+66.400000,9.646063,3.626926,1.943663,4.090559,1.586828,0.470326,5.338986,0.123587,3.161546,0.629085,0.000250,0.350915,0.041359,24.456162,1.541495,19.624662,16.767849,4.391148,1.765990,1.351845,5.185553,0.399509
+66.500000,9.645889,3.646327,2.072695,4.115601,1.515341,0.478895,5.428782,0.124573,3.196722,0.633130,0.000274,0.346870,0.041380,24.510334,1.541910,19.626212,16.768369,4.416237,1.766008,1.351294,5.185553,0.341964
+66.600000,9.646434,3.605589,2.225512,4.315291,1.423544,0.509602,5.216884,0.121840,3.144441,0.646947,0.000304,0.333053,0.041126,24.521422,1.551941,19.613885,16.768719,4.427802,1.766090,1.350987,5.185554,0.280944
+66.700000,9.647392,3.528501,2.274003,4.553657,1.393254,0.539574,4.827233,0.116871,3.028255,0.660575,0.000313,0.319425,0.040753,24.469916,1.566339,19.593780,16.768573,4.413604,1.766168,1.351233,5.185555,0.262743
+66.800000,9.647879,3.484455,2.132684,4.572195,1.481307,0.533005,4.654514,0.114769,2.961745,0.657986,0.000281,0.322014,0.040669,24.402817,1.569404,19.586543,16.767998,4.384766,1.766170,1.351878,5.185555,0.316009
+66.900000,9.647326,3.522421,1.955871,4.356006,1.581114,0.500208,4.866832,0.117681,3.016801,0.642830,0.000249,0.337170,0.040946,24.387086,1.557226,19.600996,16.767565,4.369578,1.766094,1.352268,5.185554,0.393014
+67.000000,9.646402,3.597038,1.912823,4.146430,1.603169,0.475282,5.203723,0.121948,3.118750,0.631260,0.000244,0.348740,0.041259,24.425910,1.544880,19.618924,16.767645,4.379428,1.766011,1.352090,5.185553,0.414008
+67.100000,9.645887,3.643852,1.998478,4.079298,1.557149,0.471399,5.417860,0.124503,3.188558,0.629674,0.000260,0.350326,0.041403,24.485571,1.540485,19.627135,16.768101,4.403972,1.765989,1.351569,5.185553,0.374372
+67.200000,9.646072,3.633443,2.151493,4.195840,1.468931,0.491944,5.362181,0.123694,3.182482,0.639017,0.000289,0.340983,0.041287,24.523544,1.545719,19.621820,16.768586,4.424730,1.766044,1.351089,5.185553,0.309576
+67.300000,9.646897,3.568770,2.271694,4.443701,1.394460,0.526966,5.026537,0.119416,3.090064,0.654781,0.000314,0.325219,0.040935,24.502801,1.559289,19.603964,16.768720,4.424060,1.766135,1.351032,5.185554,0.263846
+67.400000,9.647754,3.497682,2.224627,4.602030,1.424858,0.541872,4.690880,0.115150,2.980894,0.661818,0.000300,0.318182,0.040653,24.433700,1.570209,19.587218,16.768314,4.399499,1.766181,1.351537,5.185555,0.280515
+67.500000,9.647718,3.493774,2.034847,4.480271,1.538026,0.517591,4.722742,0.115755,2.976300,0.650950,0.000262,0.329050,0.040781,24.386919,1.564454,19.591820,16.767730,4.374198,1.766139,1.352138,5.185555,0.357127
+67.600000,9.646857,3.559266,1.915617,4.240311,1.602004,0.485768,5.035181,0.119847,3.067041,0.636079,0.000244,0.343921,0.041111,24.401099,1.550404,19.610531,16.767540,4.371594,1.766050,1.352245,5.185554,0.412379
+67.700000,9.646071,3.626152,1.942146,4.091633,1.587635,0.470384,5.335419,0.123544,3.160382,0.629107,0.000250,0.350893,0.041357,24.455175,1.541565,19.624529,16.767841,4.390722,1.765990,1.351854,5.185553,0.400219
+67.800000,9.645885,3.646525,2.070079,4.113581,1.516846,0.478542,5.429798,0.124588,3.196845,0.632969,0.000273,0.347031,0.041382,24.509725,1.541819,19.626305,16.768360,4.415882,1.766008,1.351302,5.185553,0.343074
+67.900000,9.646419,3.606707,2.223441,4.311008,1.424835,0.508995,5.222712,0.121914,3.146041,0.646674,0.000304,0.333326,0.041132,24.521823,1.551707,19.614192,16.768717,4.427817,1.766089,1.350988,5.185554,0.281723
+68.000000,9.647377,3.529735,2.274841,4.550906,1.392703,0.539317,4.833091,0.116945,3.030166,0.660453,0.000313,0.319547,0.040757,24.471163,1.566148,19.594073,16.768580,4.414035,1.766168,1.351224,5.185555,0.262456
+68.100000,9.647880,3.484501,2.136081,4.574481,1.479268,0.533454,4.653750,0.114755,2.961768,0.658187,0.000281,0.321813,0.040666,24.403643,1.569515,19.586451,16.768008,4.385203,1.766171,1.351867,5.185555,0.314651
+68.200000,9.647341,3.521252,1.957852,4.360182,1.580071,0.500753,4.861323,0.117609,3.015188,0.643086,0.000250,0.336914,0.040940,24.386836,1.557473,19.600666,16.767568,4.369609,1.766096,1.352266,5.185554,0.392076
+68.300000,9.646415,3.595894,1.912312,4.148940,1.603440,0.475541,5.198588,0.121886,3.117149,0.631380,0.000244,0.348620,0.041253,24.425000,1.545026,19.618690,16.767639,4.379092,1.766013,1.352097,5.185553,0.414247
+68.400000,9.645890,3.643499,1.996305,4.078952,1.558345,0.471265,5.416160,0.124484,3.187912,0.629611,0.000259,0.350389,0.041402,24.484668,1.540481,19.627107,16.768092,4.403539,1.765989,1.351578,5.185553,0.375349
+68.500000,9.646063,3.634119,2.148832,4.192450,1.470531,0.491419,5.365679,0.123739,3.183331,0.638782,0.000288,0.341218,0.041291,24.523361,1.545552,19.622024,16.768580,4.424520,1.766043,1.351094,5.185553,0.310637
+68.600000,9.646880,3.570116,2.270755,4.439454,1.395058,0.526424,5.033392,0.119503,3.092098,0.654536,0.000313,0.325464,0.040941,24.503739,1.559033,19.604319,16.768722,4.424303,1.766134,1.351028,5.185554,0.264186
+68.700000,9.647744,3.498481,2.227100,4.601638,1.423301,0.541983,4.693993,0.115189,2.982095,0.661861,0.000301,0.318139,0.040654,24.434931,1.570150,19.587353,16.768325,4.400007,1.766182,1.351525,5.185555,0.279599
+68.800000,9.647727,3.493110,2.037944,4.484073,1.536284,0.518166,4.718987,0.115703,2.975319,0.651217,0.000263,0.328783,0.040776,24.387227,1.564671,19.591563,16.767737,4.374463,1.766141,1.352131,5.185555,0.355772
+68.900000,9.646872,3.557979,1.916341,4.243898,1.601638,0.486193,5.029397,0.119774,3.065288,0.636276,0.000244,0.343724,0.041105,24.400475,1.550616,19.610223,16.767538,4.371425,1.766052,1.352248,5.185554,0.412021
+69.000000,9.646079,3.625345,1.940702,4.092815,1.588403,0.470456,5.331704,0.123500,3.159178,0.629136,0.000249,0.350864,0.041354,24.454191,1.541641,19.624387,16.767834,4.390300,1.765991,1.351863,5.185553,0.400895
+69.100000,9.645882,3.646684,2.067475,4.111657,1.518343,0.478200,5.430624,0.124600,3.196912,0.632814,0.000273,0.347186,0.041383,24.509092,1.541734,19.626390,16.768352,4.415520,1.766007,1.351311,5.185553,0.344182
+69.200000,9.646405,3.607808,2.221315,4.306734,1.426161,0.508386,5.228451,0.121987,3.147609,0.646401,0.000303,0.333599,0.041138,24.522196,1.551476,19.614496,16.768714,4.427819,1.766088,1.350989,5.185554,0.282524
+69.300000,9.647362,3.530976,2.275597,4.548086,1.392211,0.539046,4.838984,0.117020,3.032083,0.660325,0.000313,0.319675,0.040763,24.472398,1.565952,19.594370,16.768587,4.414456,1.766168,1.351215,5.185555,0.262191
+69.400000,9.647880,3.484570,2.139404,4.576649,1.477279,0.533887,4.653113,0.114744,2.961826,0.658380,0.000282,0.321620,0.040664,24.404472,1.569619,19.586367,16.768018,4.385637,1.766172,1.351857,5.185555,0.313317
+69.500000,9.647356,3.520111,1.959862,4.364314,1.579005,0.501297,4.855910,0.117539,3.013605,0.643340,0.000250,0.336660,0.040935,24.386606,1.557717,19.600340,16.767571,4.369645,1.766098,1.352265,5.185554,0.391132
+69.600000,9.646428,3.594754,1.911814,4.151437,1.603706,0.475798,5.193489,0.121823,3.115564,0.631496,0.000244,0.348504,0.041249,24.424098,1.545174,19.618455,16.767634,4.378758,1.766014,1.352104,5.185553,0.414480
+69.700000,9.645893,3.643159,1.994127,4.078582,1.559542,0.471128,5.414544,0.124466,3.187293,0.629546,0.000259,0.350454,0.041402,24.483758,1.540476,19.627078,16.768083,4.403105,1.765989,1.351588,5.185553,0.376331
+69.800000,9.646054,3.634787,2.146217,4.189141,1.472102,0.490907,5.369112,0.123784,3.184164,0.638551,0.000288,0.341449,0.041295,24.523154,1.545388,19.622225,16.768574,4.424305,1.766042,1.351100,5.185553,0.311681
+69.900000,9.646863,3.571425,2.269760,4.435292,1.395683,0.525890,5.040063,0.119588,3.094067,0.654294,0.000313,0.325706,0.040948,24.504589,1.558786,19.604662,16.768724,4.424519,1.766133,1.351024,5.185554,0.264557
+70.000000,11.637880,4.007391,1.917179,4.260979,1.601246,0.488107,5.014638,0.119579,3.060856,0.636884,0.000244,0.343116,0.041107,25.414780,1.553133,19.617280,16.774630,4.375059,1.767928,1.353731,5.185139,0.411575
+70.100000,11.636931,4.084287,1.932697,4.098607,1.592636,0.470769,5.328595,0.123459,3.157876,0.628988,0.000248,0.351012,0.041370,25.467474,1.543520,19.632260,16.774902,4.393063,1.767863,1.353366,5.185138,0.404667
+70.200000,11.636569,4.116617,2.055586,4.104160,1.525139,0.476783,5.448218,0.124814,3.201448,0.631901,0.000270,0.348099,0.041419,25.524425,1.542924,19.635241,16.775423,4.418785,1.767873,1.352807,5.185138,0.349275
+70.300000,11.637023,4.083087,2.212863,4.290419,1.431408,0.506040,5.265856,0.122448,3.158351,0.645080,0.000302,0.334920,0.041190,25.542103,1.552101,19.624201,16.775814,4.432802,1.767952,1.352451,5.185139,0.285729
+70.400000,11.638070,4.001322,2.280559,4.540210,1.388973,0.538469,4.873440,0.117449,3.043411,0.659770,0.000315,0.320230,0.040807,25.495725,1.566863,19.603875,16.775727,4.421185,1.768036,1.352635,5.185140,0.260468
+70.500000,11.638801,3.941158,2.154917,4.591779,1.467936,0.536470,4.655884,0.114755,2.964062,0.659261,0.000285,0.320739,0.040673,25.425340,1.571918,19.594084,16.775167,4.392157,1.768047,1.353275,5.185140,0.307147
+70.600000,11.638398,3.967790,1.967684,4.386826,1.574853,0.504120,4.838323,0.117298,3.008648,0.644381,0.000251,0.335619,0.040931,25.402386,1.560559,19.607070,16.774684,4.374184,1.767976,1.353726,5.185139,0.387463
+70.700000,11.637378,4.047418,1.907598,4.164868,1.605918,0.477113,5.180227,0.121653,3.111374,0.631811,0.000243,0.348189,0.041254,25.437026,1.547477,19.625742,16.774708,4.381647,1.767889,1.353604,5.185139,0.416484
+70.800000,11.636660,4.107549,1.982489,4.077833,1.565901,0.470533,5.419786,0.124530,3.188237,0.628988,0.000257,0.351012,0.041426,25.497116,1.542024,19.635397,16.775144,4.405715,1.767857,1.353096,5.185138,0.381610
+70.900000,11.636686,4.108671,2.133441,4.174451,1.479737,0.488568,5.399176,0.124152,3.192313,0.637234,0.000286,0.342766,0.041342,25.540331,1.546181,19.631637,16.775652,4.428176,1.767905,1.352585,5.185139,0.316822
+71.000000,11.637496,4.046428,2.266264,4.418106,1.397881,0.523714,5.083744,0.120132,3.107301,0.653037,0.000313,0.326963,0.041004,25.527047,1.559251,19.614665,16.775845,4.430581,1.767997,1.352462,5.185139,0.265855
+71.100000,11.638536,3.963934,2.242525,4.603919,1.413532,0.543216,4.719836,0.115501,2.991743,0.662097,0.000305,0.317903,0.040685,25.459558,1.571582,19.596316,16.775490,4.407693,1.768053,1.352920,5.185140,0.273943
+71.200000,11.638746,3.942880,2.056212,4.511240,1.525954,0.522091,4.703218,0.115472,2.971687,0.652753,0.000266,0.327247,0.040768,25.405991,1.567738,19.598199,16.774884,4.380531,1.768020,1.353557,5.185140,0.347834
+71.300000,11.637916,4.004646,1.919206,4.268546,1.600214,0.489024,5.002966,0.119430,3.057342,0.637311,0.000244,0.342689,0.041096,25.413530,1.553580,19.616644,16.774628,4.374805,1.767930,1.353736,5.185139,0.410580
+71.400000,11.636956,4.082222,1.930192,4.101627,1.593962,0.471004,5.320362,0.123360,3.155247,0.629088,0.000248,0.350912,0.041364,25.465358,1.543706,19.631930,16.774886,4.392244,1.767863,1.353384,5.185138,0.405846
+71.500000,11.636569,4.116540,2.050480,4.101006,1.528046,0.476189,5.448687,0.124824,3.201244,0.631629,0.000270,0.348371,0.041421,25.522849,1.542791,19.635358,16.775404,4.418009,1.767871,1.352825,5.185138,0.351474
+71.600000,11.636996,4.085183,2.208199,4.282078,1.434300,0.504827,5.276548,0.122584,3.161208,0.644535,0.000301,0.335465,0.041201,25.542442,1.551658,19.624773,16.775806,4.432700,1.767948,1.352456,5.185139,0.287501
+71.700000,11.638034,4.004199,2.281185,4.533534,1.388554,0.537752,4.886286,0.117613,3.047478,0.659438,0.000315,0.320562,0.040818,25.497995,1.566420,19.604527,16.775738,4.421967,1.768033,1.352620,5.185140,0.260261
+71.800000,11.638793,3.941956,2.161421,4.594898,1.463990,0.537201,4.656640,0.114758,2.964828,0.659583,0.000287,0.320417,0.040671,25.427164,1.572045,19.594031,16.775187,4.393109,1.768048,1.353253,5.185140,0.304589
+71.900000,11.638427,3.965675,1.972429,4.395147,1.572312,0.505249,4.828104,0.117163,3.005718,0.644910,0.000252,0.335090,0.040919,25.402104,1.561047,19.606434,16.774692,4.374398,1.767979,1.353720,5.185139,0.385259
+72.000000,11.637411,4.044759,1.907272,4.170568,1.606104,0.477731,5.169420,0.121520,3.108047,0.632093,0.000243,0.347907,0.041245,25.435239,1.547812,19.625222,16.774699,4.381067,1.767891,1.353616,5.185139,0.416624
+72.100000,11.636674,4.106345,1.978481,4.077996,1.568083,0.470379,5.415217,0.124478,3.186624,0.628911,0.000256,0.351089,0.041424,25.495106,1.542061,19.635273,16.775126,4.404841,1.767856,1.353115,5.185138,0.383436
+72.200000,11.636673,4.109688,2.128047,4.168400,1.482946,0.487605,5.404786,0.124225,3.193594,0.636801,0.000284,0.343199,0.041349,25.539571,1.545889,19.631983,16.775637,4.427662,1.767902,1.352598,5.185139,0.319006
+72.300000,11.637460,4.049195,2.263577,4.409337,1.399582,0.522552,5.097219,0.120304,3.111206,0.652512,0.000312,0.327488,0.041017,25.528511,1.558738,19.615364,16.775846,4.430937,1.767993,1.352457,5.185139,0.266840
+72.400000,11.638509,3.966130,2.246623,4.601642,1.410919,0.543222,4.727970,0.115603,2.994678,0.662085,0.000306,0.317915,0.040691,25.461991,1.571374,19.596697,16.775508,4.408693,1.768052,1.352898,5.185140,0.272458
+72.500000,11.638759,3.942064,2.062791,4.518222,1.522198,0.523203,4.697205,0.115387,2.970239,0.653265,0.000268,0.326735,0.040759,25.406812,1.568126,19.597763,16.774900,4.381179,1.768022,1.353541,5.185140,0.345010
+72.600000,11.637951,4.001927,1.921400,4.276175,1.599092,0.489954,4.991332,0.119280,3.053846,0.637743,0.000244,0.342257,0.041087,25.412379,1.554027,19.616006,16.774628,4.374582,1.767933,1.353739,5.185139,0.409508
+72.700000,11.636981,4.080117,1.927817,4.104818,1.595217,0.471263,5.311905,0.123259,3.152556,0.629200,0.000247,0.350800,0.041358,25.463310,1.543901,19.631592,16.774871,4.391441,1.767864,1.353401,5.185138,0.406965
+72.800000,11.636569,4.116399,2.045438,4.098054,1.530908,0.475621,5.448805,0.124830,3.200942,0.631370,0.000269,0.348630,0.041423,25.521285,1.542669,19.635460,16.775387,4.417225,1.767869,1.352842,5.185138,0.353654
+72.900000,11.636970,4.087230,2.203466,4.273811,1.437227,0.503620,5.286993,0.122717,3.163984,0.643995,0.000300,0.336005,0.041213,25.542767,1.551222,19.625335,16.775799,4.432575,1.767945,1.352461,5.185139,0.289306
+73.000000,11.637997,4.007090,2.281668,4.526712,1.388223,0.537010,4.899238,0.117779,3.051561,0.659095,0.000315,0.320905,0.040830,25.500296,1.565970,19.605187,16.775750,4.422735,1.768031,1.352604,5.185140,0.260109
+73.100000,11.638784,3.942800,2.167919,4.597918,1.460034,0.537924,4.657549,0.114764,2.965647,0.659900,0.000288,0.320100,0.040668,25.429051,1.572164,19.593988,16.775209,4.394064,1.768049,1.353230,5.185140,0.302047
+73.200000,11.638455,3.963571,1.977238,4.403528,1.569728,0.506389,4.817844,0.117027,3.002779,0.645445,0.000253,0.334555,0.040908,25.401862,1.561539,19.605795,16.774701,4.374614,1.767981,1.353713,5.185140,0.383035
+73.300000,11.637444,4.042084,1.906979,4.176350,1.606274,0.478358,5.158505,0.121385,3.104687,0.632378,0.000243,0.347622,0.041235,25.433473,1.548152,19.624695,16.774691,4.380483,1.767893,1.353627,5.185139,0.416746
+73.400000,11.636688,4.105112,1.974493,4.078265,1.570250,0.470238,5.410487,0.124424,3.184964,0.628841,0.000256,0.351159,0.041421,25.493094,1.542104,19.635140,16.775108,4.403955,1.767856,1.353134,5.185138,0.385256
+73.500000,11.636659,4.110665,2.122653,4.162465,1.486148,0.486657,5.410170,0.124295,3.194808,0.636372,0.000283,0.343628,0.041355,25.538786,1.545601,19.632323,16.775623,4.427126,1.767899,1.352611,5.185138,0.321199
+73.600000,11.637425,4.051953,2.260752,4.400508,1.401372,0.521376,5.110675,0.120475,3.115088,0.651981,0.000312,0.328019,0.041031,25.529940,1.558225,19.616062,16.775847,4.431266,1.767990,1.352452,5.185139,0.267876
+73.700000,11.638481,3.968407,2.250598,4.599060,1.408380,0.543186,4.736552,0.115711,2.997742,0.662054,0.000307,0.317946,0.040696,25.464481,1.571148,19.597101,16.775527,4.409698,1.768051,1.352876,5.185140,0.271022
+73.800000,11.638771,3.941297,2.069517,4.525215,1.518342,0.524328,4.691309,0.115304,2.968843,0.653781,0.000269,0.326219,0.040750,25.407696,1.568513,19.597331,16.774918,4.381849,1.768024,1.353524,5.185140,0.342141
+73.900000,11.637986,3.999180,1.923660,4.283941,1.597936,0.490902,4.979569,0.119131,3.050313,0.638188,0.000245,0.341812,0.041074,25.411224,1.554488,19.615350,16.774628,4.374359,1.767936,1.353743,5.185139,0.408403
+74.000000,11.637007,4.077977,1.925414,4.108081,1.596485,0.471529,5.303391,0.123156,3.149845,0.629314,0.000247,0.350686,0.041352,25.461213,1.544102,19.631240,16.774857,4.390622,1.767865,1.353418,5.185138,0.408101
+74.100000,11.636570,4.116225,2.040359,4.095162,1.533782,0.475060,5.448855,0.124835,3.200619,0.631112,0.000268,0.348888,0.041426,25.519673,1.542549,19.635558,16.775369,4.416426,1.767867,1.352860,5.185138,0.355859
+74.200000,11.636943,4.089251,2.198673,4.265601,1.440185,0.502419,5.297341,0.122848,3.166724,0.643454,0.000299,0.336546,0.041224,25.543023,1.550790,19.625891,16.775790,4.432429,1.767941,1.352466,5.185139,0.291142
+74.300000,11.637960,4.009998,2.281959,4.519719,1.388016,0.536236,4.912378,0.117947,3.055681,0.658738,0.000315,0.321262,0.040842,25.502543,1.565512,19.605855,16.775761,4.423485,1.768028,1.352590,5.185140,0.260024
+74.400000,11.638774,3.943736,2.174342,4.600649,1.456108,0.538614,4.658940,0.114775,2.966616,0.660200,0.000289,0.319800,0.040666,25.430969,1.572264,19.593972,16.775229,4.395031,1.768049,1.353208,5.185140,0.299550
+74.500000,11.638483,3.961528,1.982187,4.411889,1.567057,0.507535,4.807789,0.116893,2.999912,0.645982,0.000254,0.334018,0.040897,25.401663,1.562029,19.605163,16.774711,4.374859,1.767984,1.353706,5.185140,0.380755
+74.600000,11.637478,4.039389,1.906841,4.182284,1.606362,0.479009,5.147509,0.121248,3.101305,0.632677,0.000243,0.347323,0.041226,25.431715,1.548501,19.624158,16.774682,4.379921,1.767895,1.353639,5.185139,0.416797
+74.700000,11.636703,4.103816,1.970588,4.078714,1.572365,0.470123,5.405521,0.124366,3.183240,0.628780,0.000255,0.351220,0.041419,25.491055,1.542156,19.634995,16.775091,4.403073,1.767855,1.353153,5.185138,0.387046
+74.800000,11.636647,4.111579,2.117233,4.156678,1.489354,0.485727,5.415292,0.124362,3.195944,0.635955,0.000282,0.344045,0.041363,25.537921,1.545327,19.632644,16.775608,4.426574,1.767896,1.352624,5.185138,0.323413
+74.900000,11.637390,4.054673,2.257804,4.391701,1.403238,0.520195,5.123987,0.120645,3.118914,0.651448,0.000311,0.328552,0.041044,25.531288,1.557716,19.616752,16.775848,4.431571,1.767987,1.352448,5.185139,0.268958
+75.000000,11.638453,3.970707,2.254304,4.596211,1.406006,0.543104,4.745367,0.115821,3.000853,0.662001,0.000308,0.317999,0.040703,25.466913,1.570908,19.597520,16.775545,4.410679,1.768050,1.352855,5.185140,0.269690
+75.100000,11.638781,3.940702,2.076132,4.531706,1.514532,0.525395,4.686210,0.115231,2.967699,0.654270,0.000270,0.325730,0.040742,25.408661,1.568867,19.596944,16.774936,4.382544,1.768026,1.353507,5.185140,0.339336
+75.200000,11.638020,3.996537,1.926257,4.291733,1.596597,0.491869,4.968097,0.118984,3.046886,0.638639,0.000245,0.341361,0.041063,25.410197,1.554948,19.614704,16.774629,4.374203,1.767939,1.353745,5.185139,0.407145
+75.300000,11.637033,4.075770,1.923345,4.111683,1.597571,0.471847,5.294549,0.123049,3.147054,0.629448,0.000246,0.350552,0.041346,25.459185,1.544317,19.630871,16.774843,4.389847,1.767866,1.353434,5.185138,0.409083
+75.400000,11.636573,4.115909,2.035479,4.092709,1.536536,0.474559,5.448213,0.124831,3.200105,0.630873,0.000267,0.349127,0.041424,25.518039,1.542446,19.635630,16.775351,4.415625,1.767865,1.352878,5.185138,0.357984
+75.500000,11.636919,4.091129,2.193797,4.257673,1.443187,0.501246,5.307010,0.122971,3.169254,0.642929,0.000298,0.337071,0.041235,25.543166,1.550377,19.626420,16.775782,4.432238,1.767938,1.352473,5.185139,0.293015
+75.600000,11.637924,4.012900,2.281883,4.512450,1.388048,0.535406,4.925615,0.118116,3.059795,0.658357,0.000315,0.321643,0.040854,25.504739,1.565043,19.606533,16.775771,4.424195,1.768026,1.352576,5.185140,0.260069
+75.700000,11.638762,3.944820,2.180535,4.602822,1.452309,0.539230,4.661062,0.114797,2.967803,0.660467,0.000291,0.319533,0.040664,25.432977,1.572330,19.594001,16.775250,4.396007,1.768050,1.353185,5.185140,0.297156
+75.800000,11.638509,3.959625,1.987285,4.420043,1.564297,0.508666,4.798221,0.116765,2.997209,0.646513,0.000255,0.333487,0.040886,25.401611,1.562505,19.604554,16.774721,4.375153,1.767987,1.353698,5.185140,0.378418
+75.900000,11.637511,4.036719,1.906959,4.188323,1.606318,0.479681,5.136560,0.121112,3.097950,0.632985,0.000243,0.347015,0.041217,25.430083,1.548856,19.623617,16.774675,4.379406,1.767897,1.353649,5.185139,0.416723
+76.000000,11.636719,4.102443,1.966909,4.079476,1.574354,0.470052,5.400188,0.124305,3.181420,0.628741,0.000254,0.351259,0.041416,25.489069,1.542224,19.634829,16.775074,4.402211,1.767855,1.353172,5.185138,0.388737
+76.100000,11.636636,4.112361,2.111910,4.151267,1.492494,0.484845,5.419772,0.124421,3.196897,0.635557,0.000281,0.344443,0.041369,25.537024,1.545071,19.632939,16.775594,4.426003,1.767894,1.352638,5.185138,0.325596
+76.200000,11.637356,4.057307,2.254648,4.382950,1.405232,0.519009,5.136964,0.120810,3.122615,0.650914,0.000310,0.329086,0.041057,25.532563,1.557214,19.617428,16.775848,4.431831,1.767984,1.352445,5.185139,0.270119
+76.300000,11.638424,3.973076,2.257712,4.592951,1.403818,0.542955,4.754630,0.115938,3.004080,0.661920,0.000309,0.318080,0.040709,25.469393,1.570644,19.597966,16.775563,4.411646,1.768049,1.352834,5.185140,0.268470
+76.400000,11.638790,3.940183,2.082793,4.538084,1.510682,0.526455,4.681337,0.115161,2.966630,0.654755,0.000271,0.325245,0.040734,25.409707,1.569213,19.596571,16.774954,4.383253,1.768028,1.353489,5.185140,0.336525
+76.500000,11.638054,3.993935,1.928839,4.299400,1.595270,0.492819,4.956831,0.118840,3.043518,0.639085,0.000246,0.340915,0.041052,25.409245,1.555400,19.614068,16.774630,4.374058,1.767942,1.353746,5.185139,0.405891
+76.600000,11.637059,4.073599,1.921347,4.115269,1.598631,0.472164,5.285839,0.122944,3.144302,0.629592,0.000246,0.350408,0.041338,25.457237,1.544535,19.630502,16.774830,4.389093,1.767867,1.353450,5.185138,0.410022
+76.700000,11.636576,4.115567,2.030693,4.090413,1.539227,0.474082,5.447455,0.124826,3.199564,0.630660,0.000266,0.349340,0.041429,25.516419,1.542362,19.635681,16.775334,4.414832,1.767864,1.352896,5.185138,0.360080
+76.800000,11.636895,4.092949,2.188973,4.249939,1.446151,0.500100,5.316428,0.123091,3.171711,0.642414,0.000297,0.337586,0.041245,25.543292,1.549975,19.626931,16.775773,4.432037,1.767935,1.352479,5.185139,0.294876
+76.900000,11.637887,4.015736,2.281671,4.505258,1.388166,0.534577,4.938629,0.118282,3.063822,0.657976,0.000315,0.322024,0.040866,25.506870,1.564581,19.607198,16.775780,4.424871,1.768024,1.352563,5.185140,0.260164
+77.000000,11.638749,3.945948,2.186517,4.604727,1.448626,0.539806,4.663499,0.114823,2.969076,0.660715,0.000292,0.319285,0.040663,25.434993,1.572379,19.594049,16.775271,4.396969,1.768050,1.353162,5.185140,0.294857
+77.100000,11.638534,3.957792,1.992414,4.428088,1.561509,0.509790,4.788912,0.116641,2.994593,0.647038,0.000255,0.332962,0.040875,25.401613,1.562973,19.603960,16.774732,4.375458,1.767990,1.353689,5.185140,0.376076
+77.200000,11.637544,4.034066,1.907155,4.194377,1.606235,0.480357,5.125696,0.120977,3.094622,0.633295,0.000243,0.346705,0.041207,25.428499,1.549211,19.623076,16.774669,4.378907,1.767899,1.353658,5.185139,0.416610
+77.300000,11.636734,4.101052,1.963316,4.080336,1.576292,0.469997,5.394791,0.124242,3.179586,0.628709,0.000254,0.351291,0.041413,25.487111,1.542296,19.634658,16.775057,4.401359,1.767855,1.353190,5.185138,0.390392
+77.400000,11.636625,4.113091,2.106681,4.146054,1.495569,0.483994,5.423977,0.124477,3.197777,0.635168,0.000280,0.344832,0.041376,25.536119,1.544822,19.633224,16.775579,4.425427,1.767891,1.352652,5.185138,0.327750
+77.500000,11.637323,4.059871,2.251449,4.374363,1.407252,0.517840,5.149605,0.120970,3.126207,0.650386,0.000310,0.329614,0.041070,25.533773,1.556725,19.618087,16.775848,4.432064,1.767981,1.352442,5.185139,0.271298
+77.600000,11.638394,3.975446,2.260875,4.589494,1.401783,0.542770,4.764022,0.116057,3.007321,0.661823,0.000309,0.318177,0.040716,25.471835,1.570372,19.598421,16.775580,4.412587,1.768048,1.352813,5.185140,0.267342
+77.700000,11.638797,3.939778,2.089379,4.544145,1.506856,0.527480,4.676965,0.115097,2.965722,0.655222,0.000272,0.324778,0.040727,25.410817,1.569539,19.596227,16.774972,4.383975,1.768030,1.353471,5.185140,0.333764
+77.800000,11.638087,3.991377,1.931600,4.307120,1.593842,0.493785,4.945660,0.118696,3.040189,0.639536,0.000246,0.340464,0.041041,25.408357,1.555856,19.613432,16.774632,4.373942,1.767945,1.353747,5.185139,0.404558
+77.900000,11.637085,4.071388,1.919482,4.119013,1.599615,0.472505,5.276972,0.122837,3.141508,0.629742,0.000246,0.350258,0.041332,25.455316,1.544760,19.630124,16.774817,4.388352,1.767869,1.353465,5.185138,0.410903
+78.000000,11.636579,4.115159,2.025992,4.088307,1.541864,0.473631,5.446393,0.124817,3.198939,0.630452,0.000265,0.349548,0.041430,25.514800,1.542282,19.635724,16.775317,4.414036,1.767863,1.352913,5.185138,0.362144
+78.100000,11.636871,4.094708,2.184116,4.242337,1.449128,0.498969,5.325532,0.123207,3.174072,0.641906,0.000296,0.338094,0.041255,25.543372,1.549582,19.627428,16.775764,4.431816,1.767932,1.352486,5.185139,0.296756
+78.200000,11.637851,4.018575,2.281288,4.497930,1.388397,0.533721,4.951703,0.118449,3.067850,0.657583,0.000315,0.322417,0.040878,25.508984,1.564114,19.607867,16.775789,4.425531,1.768021,1.352550,5.185140,0.260315
+78.300000,11.638735,3.947165,2.192403,4.606332,1.444990,0.540345,4.666367,0.114854,2.970479,0.660946,0.000293,0.319054,0.040663,25.437073,1.572410,19.594122,16.775292,4.397941,1.768051,1.353139,5.185140,0.292607
+78.400000,11.638558,3.956009,1.997729,4.436202,1.558607,0.510933,4.779653,0.116517,2.992003,0.647572,0.000256,0.332428,0.040865,25.401677,1.563446,19.603363,16.774744,4.375790,1.767993,1.353680,5.185140,0.373664
+78.500000,11.637577,4.031359,1.907466,4.200634,1.606096,0.481060,5.114581,0.120838,3.091219,0.633619,0.000243,0.346381,0.041198,25.426919,1.549579,19.622518,16.774662,4.378414,1.767902,1.353668,5.185139,0.416439
+78.600000,11.636751,4.099597,1.959723,4.081336,1.578225,0.469958,5.389132,0.124176,3.177674,0.628683,0.000253,0.351317,0.041410,25.485122,1.542375,19.634476,16.775040,4.400493,1.767856,1.353208,5.185138,0.392052
+78.700000,11.636615,4.113783,2.101353,4.140895,1.498693,0.483144,5.428013,0.124530,3.198600,0.634789,0.000279,0.345211,0.041381,25.535149,1.544582,19.633497,16.775564,4.424825,1.767889,1.352666,5.185138,0.329954
+78.800000,11.637290,4.062449,2.248075,4.365635,1.409380,0.516645,5.162347,0.121132,3.129811,0.649848,0.000309,0.330152,0.041082,25.534944,1.556230,19.618750,16.775847,4.432274,1.767978,1.352440,5.185139,0.272544
+78.900000,11.638363,3.977909,2.263886,4.585684,1.399840,0.542535,4.773924,0.116182,3.010709,0.661703,0.000310,0.318297,0.040724,25.474321,1.570078,19.598904,16.775597,4.413533,1.768047,1.352793,5.185140,0.266274
+79.000000,11.638803,3.939480,2.096141,4.550089,1.502911,0.528506,4.672975,0.115038,2.964954,0.655689,0.000274,0.324311,0.040720,25.412035,1.569854,19.595903,16.774991,4.384738,1.768032,1.353452,5.185140,0.330947
+79.100000,11.638120,3.988773,1.934631,4.315160,1.592272,0.494797,4.934200,0.118548,3.036781,0.640010,0.000246,0.339990,0.041030,25.407500,1.556330,19.612774,16.774635,4.373851,1.767948,1.353747,5.185139,0.403096
+79.200000,11.637113,4.069057,1.917716,4.123064,1.600547,0.472884,5.267601,0.122724,3.138561,0.629908,0.000245,0.350092,0.041324,25.453372,1.544990,19.629734,16.774804,4.387605,1.767871,1.353480,5.185138,0.411736
+79.300000,11.636583,4.114665,2.021219,4.086374,1.544532,0.473198,5.444900,0.124803,3.198185,0.630251,0.000264,0.349749,0.041431,25.513101,1.542212,19.635754,16.775299,4.413203,1.767862,1.352931,5.185138,0.364248
+79.400000,11.636849,4.096430,2.179052,4.234720,1.452221,0.497827,5.334431,0.123321,3.176354,0.641394,0.000295,0.338606,0.041265,25.543352,1.549192,19.627921,16.775755,4.431545,1.767929,1.352494,5.185139,0.298726
+79.500000,11.637813,4.021492,2.280586,4.490186,1.388833,0.532796,4.965226,0.118621,3.071982,0.657162,0.000315,0.322838,0.040890,25.511086,1.563626,19.608562,16.775798,4.426165,1.768019,1.352538,5.185140,0.260581
+79.600000,11.638719,3.948516,2.198258,4.607580,1.441361,0.540845,4.669829,0.114893,2.972072,0.661158,0.000295,0.318842,0.040663,25.439242,1.572416,19.594230,16.775313,4.398933,1.768052,1.353116,5.185140,0.290381
+79.700000,11.638581,3.954295,2.003236,4.444294,1.555590,0.512085,4.770613,0.116395,2.989497,0.648109,0.000257,0.331891,0.040854,25.401832,1.563915,19.602776,16.774756,4.376157,1.767996,1.353669,5.185140,0.371174
+79.800000,11.637611,4.028631,1.907978,4.207078,1.605852,0.481793,5.103334,0.120698,3.087782,0.633958,0.000243,0.346042,0.041187,25.425385,1.549958,19.621948,16.774657,4.377945,1.767905,1.353676,5.185139,0.416169
+79.900000,11.636768,4.098057,1.956253,4.082604,1.580090,0.469954,5.383098,0.124105,3.175655,0.628674,0.000252,0.351326,0.041406,25.483121,1.542468,19.634273,16.775024,4.399626,1.767856,1.353226,5.185138,0.393657
+80.000000,13.132350,4.356328,1.908551,4.150472,1.605378,0.475556,5.216240,0.122093,3.122482,0.630952,0.000244,0.349048,0.041292,26.027590,1.547437,19.631700,16.778570,4.385896,1.768899,1.354355,5.184915,0.416071
+80.100000,13.131605,4.417082,1.993717,4.079142,1.559756,0.471162,5.438073,0.124738,3.194450,0.629145,0.000259,0.350855,0.041445,26.088277,1.542825,19.640229,16.779031,4.410770,1.768874,1.353827,5.184915,0.376527
+80.200000,13.131658,4.415041,2.148476,4.193170,1.470737,0.491469,5.388746,0.124007,3.190364,0.638393,0.000289,0.341607,0.041334,26.127938,1.547914,19.635134,16.779528,4.432194,1.768929,1.353334,5.184915,0.310787
+80.300000,13.132543,4.347095,2.273476,4.443974,1.393301,0.527097,5.051661,0.119717,3.098116,0.654420,0.000314,0.325580,0.040980,26.108467,1.561586,19.617190,16.779676,4.432156,1.769022,1.353262,5.184916,0.263223
+80.400000,13.133635,4.261782,2.230962,4.611439,1.420877,0.543321,4.702960,0.115288,2.985454,0.662037,0.000302,0.317963,0.040684,26.038424,1.573036,19.599774,16.779274,4.407505,1.769072,1.353766,5.184917,0.278162
+80.500000,13.133812,4.244524,2.038230,4.493904,1.536140,0.519261,4.724531,0.115761,2.977274,0.651293,0.000263,0.328707,0.040804,25.989242,1.567587,19.603876,16.778674,4.381306,1.769031,1.354387,5.184916,0.355630
+80.600000,13.132919,4.311442,1.912998,4.249611,1.603378,0.486684,5.039414,0.119889,3.068363,0.636066,0.000243,0.343934,0.041138,26.002089,1.553273,19.622858,16.778465,4.377929,1.768940,1.354512,5.184915,0.413624
+80.700000,13.131913,4.391589,1.936169,4.094468,1.590791,0.470446,5.348656,0.123696,3.164177,0.628701,0.000249,0.351299,0.041394,26.056409,1.544071,19.637352,16.778762,4.396946,1.768877,1.354124,5.184915,0.403041
+80.800000,13.131517,4.425108,2.063683,4.110186,1.520509,0.477841,5.454369,0.124877,3.203883,0.632238,0.000272,0.347762,0.041428,26.112668,1.544002,19.639597,16.779289,4.422680,1.768892,1.353562,5.184915,0.345808
+80.900000,13.131996,4.389259,2.220702,4.305387,1.426531,0.508186,5.254724,0.122298,3.155670,0.645897,0.000303,0.334103,0.041185,26.127285,1.553713,19.627775,16.779664,4.435635,1.768974,1.353226,5.184916,0.282768
+81.000000,13.133110,4.303141,2.279968,4.553054,1.389387,0.539882,4.857589,0.117241,3.038461,0.660273,0.000315,0.319727,0.040801,26.077643,1.568511,19.607266,16.779546,4.422543,1.769056,1.353444,5.184916,0.260646
+81.100000,13.133885,4.241056,2.144566,4.588950,1.474191,0.535547,4.658841,0.114800,2.964243,0.658707,0.000283,0.321293,0.040690,26.007815,1.572654,19.598603,16.778969,4.393163,1.769063,1.354096,5.184917,0.311243
+81.200000,13.133466,4.269722,1.959744,4.375489,1.579090,0.502518,4.858939,0.117564,3.014715,0.643475,0.000250,0.336525,0.040961,25.988130,1.560704,19.612538,16.778504,4.376312,1.768989,1.354524,5.184916,0.391167
+81.300000,13.132394,4.352798,1.907355,4.157153,1.606016,0.476248,5.202717,0.121927,3.118289,0.631265,0.000243,0.348735,0.041281,26.025205,1.547832,19.631071,16.778557,4.385033,1.768902,1.354373,5.184915,0.416629
+81.400000,13.131622,4.415647,1.988070,4.078367,1.562850,0.470829,5.433530,0.124687,3.192742,0.628985,0.000258,0.351015,0.041443,26.085832,1.542822,19.640139,16.779008,4.409628,1.768874,1.353852,5.184915,0.379080
+81.500000,13.131636,4.416637,2.141545,4.184558,1.474894,0.490130,5.397573,0.124120,3.192487,0.637791,0.000287,0.342209,0.041345,26.127323,1.547488,19.635652,16.779512,4.431619,1.768926,1.353348,5.184915,0.313561
+81.600000,13.132494,4.350893,2.270775,4.432965,1.395015,0.525677,5.069290,0.119941,3.103305,0.653776,0.000314,0.326224,0.040997,26.110696,1.560928,19.618100,16.779681,4.432728,1.769019,1.353252,5.184916,0.264210
+81.700000,13.133601,4.264539,2.236949,4.609831,1.417088,0.543521,4.711752,0.115396,2.988760,0.662108,0.000304,0.317892,0.040689,26.041528,1.572849,19.600163,16.779300,4.408793,1.769072,1.353737,5.184917,0.275964
+81.800000,13.133831,4.243247,2.046360,4.503390,1.531552,0.520719,4.715587,0.115637,2.974993,0.651967,0.000265,0.328033,0.040792,25.990101,1.568123,19.603251,16.778694,4.382035,1.769034,1.354368,5.184916,0.352089
+81.900000,13.132966,4.307814,1.915180,4.259005,1.602275,0.487807,5.024563,0.119700,3.063879,0.636588,0.000244,0.343412,0.041125,26.000508,1.553826,19.622057,16.778463,4.377545,1.768944,1.354519,5.184915,0.412546
+82.000000,13.131946,4.388879,1.932687,4.097857,1.592634,0.470683,5.338704,0.123578,3.160978,0.628799,0.000248,0.351201,0.041387,26.053823,1.544284,19.636966,16.778742,4.395881,1.768879,1.354147,5.184915,0.404679
+82.100000,13.131517,4.425049,2.057092,4.105696,1.524278,0.477023,5.455775,0.124899,3.203854,0.631864,0.000271,0.348136,0.041432,26.110881,1.543807,19.639783,16.779267,4.421723,1.768890,1.353584,5.184915,0.348631
+82.200000,13.131959,4.392093,2.214997,4.294575,1.430081,0.506629,5.268959,0.122479,3.159513,0.645198,0.000302,0.334802,0.041200,26.128014,1.553132,19.628532,16.779656,4.435577,1.768970,1.353231,5.184916,0.284922
+82.300000,13.133061,4.306939,2.281363,4.545145,1.388464,0.539077,4.873450,0.117444,3.043547,0.659895,0.000315,0.320105,0.040815,26.080729,1.567974,19.608069,16.779563,4.423591,1.769054,1.353423,5.184916,0.260173
+82.400000,13.133874,4.241995,2.153079,4.593797,1.469055,0.536586,4.658474,0.114786,2.964805,0.659166,0.000285,0.320834,0.040686,26.010090,1.572872,19.598458,16.778996,4.394338,1.769065,1.354069,5.184917,0.307867
+82.500000,13.133504,4.266856,1.965370,4.386164,1.576095,0.503943,4.845369,0.117385,3.010784,0.644143,0.000251,0.335857,0.040946,25.987679,1.561332,19.611708,16.778514,4.376497,1.768993,1.354518,5.184916,0.388535
+82.600000,13.132438,4.349288,1.906523,4.164041,1.606466,0.476977,5.189196,0.121760,3.114111,0.631595,0.000243,0.348405,0.041270,26.022929,1.548238,19.630434,16.778544,4.384234,1.768905,1.354389,5.184915,0.417011
+82.700000,13.131641,4.414082,1.982749,4.078103,1.565757,0.470570,5.428373,0.124629,3.190872,0.628858,0.000257,0.351142,0.041441,26.083388,1.542846,19.640015,16.778985,4.408508,1.768874,1.353877,5.184915,0.381494
+82.800000,13.131618,4.418035,2.134697,4.176463,1.478986,0.488856,5.405498,0.124223,3.194349,0.637218,0.000286,0.342782,0.041355,26.126574,1.547093,19.636128,16.779495,4.431007,1.768923,1.353364,5.184915,0.316318
+82.900000,13.132446,4.354599,2.267730,4.421906,1.396951,0.524232,5.086657,0.120162,3.108377,0.653122,0.000313,0.326878,0.041014,26.112784,1.560273,19.618998,16.779685,4.433243,1.769015,1.353244,5.184916,0.265319
+83.000000,13.133565,4.267428,2.242600,4.607593,1.413493,0.543631,4.721344,0.115516,2.992290,0.662137,0.000305,0.317863,0.040695,26.044690,1.572624,19.600600,16.779325,4.410083,1.769072,1.353709,5.184917,0.273907
+83.100000,13.133848,4.242139,2.054633,4.512624,1.526858,0.522160,4.707222,0.115521,2.972911,0.652633,0.000266,0.327367,0.040780,25.991095,1.568641,19.602656,16.778715,4.382815,1.769038,1.354349,5.184916,0.348510
+83.200000,13.133013,4.304219,1.917648,4.268561,1.601021,0.488960,5.009714,0.119512,3.059407,0.637126,0.000244,0.342874,0.041111,25.999020,1.554390,19.621248,16.778462,4.377209,1.768948,1.354525,5.184916,0.411331
+83.300000,13.131981,4.386080,1.929428,4.101591,1.594358,0.470966,5.328349,0.123454,3.157668,0.628920,0.000248,0.351080,0.041379,26.051257,1.544515,19.636555,16.778723,4.394835,1.768880,1.354169,5.184915,0.406214
+83.400000,13.131518,4.424846,2.050579,4.101581,1.527988,0.476253,5.456550,0.124914,3.203645,0.631512,0.000270,0.348488,0.041436,26.109025,1.543632,19.639940,16.779245,4.420744,1.768888,1.353606,5.184915,0.351434
+83.500000,13.131923,4.394825,2.209107,4.283862,1.433733,0.505077,5.282799,0.122655,3.163222,0.644501,0.000301,0.335499,0.041215,26.128630,1.552562,19.629271,16.779648,4.435472,1.768966,1.353236,5.184916,0.287160
+83.600000,13.133012,4.310783,2.282380,4.536820,1.387783,0.538198,4.889718,0.117651,3.048713,0.659490,0.000315,0.320510,0.040829,26.083797,1.567418,19.608893,16.779579,4.424616,1.769052,1.353402,5.184916,0.259837
+83.700000,13.133862,4.243092,2.161507,4.598205,1.463945,0.537571,4.658802,0.114782,2.965587,0.659602,0.000287,0.320398,0.040681,26.012469,1.573061,19.598354,16.779023,4.395538,1.769067,1.354040,5.184917,0.304549
+83.800000,13.133541,4.264093,1.971218,4.396819,1.572968,0.505377,4.832058,0.117210,3.006949,0.644816,0.000252,0.335184,0.040932,25.987335,1.561960,19.610887,16.778525,4.376727,1.768997,1.354510,5.184916,0.385814
+83.900000,13.132483,4.345753,1.905920,4.171152,1.606799,0.477740,5.175516,0.121591,3.109893,0.631943,0.000243,0.348057,0.041259,26.020711,1.548656,19.629781,16.778533,4.383466,1.768908,1.354405,5.184915,0.417282
+84.000000,13.131660,4.412426,1.977540,4.078111,1.568592,0.470347,5.422834,0.124566,3.188897,0.628748,0.000256,0.351252,0.041439,26.080933,1.542883,19.639873,16.778963,4.407388,1.768874,1.353901,5.184915,0.383869
+84.100000,13.131600,4.419324,2.127836,4.168623,1.483070,0.487615,5.412932,0.124319,3.196064,0.636660,0.000285,0.343340,0.041364,26.125746,1.546714,19.636582,16.779478,4.430365,1.768920,1.353380,5.184915,0.319095
+84.200000,13.132398,4.358256,2.264424,4.410772,1.399041,0.522763,5.103904,0.120382,3.113382,0.652459,0.000313,0.327541,0.041031,26.114781,1.559621,19.619890,16.779688,4.433714,1.769012,1.353237,5.184916,0.266535
+84.300000,13.133527,4.270408,2.247949,4.604907,1.410082,0.543671,4.731469,0.115642,2.995963,0.662136,0.000306,0.317864,0.040701,26.047863,1.572372,19.601069,16.779349,4.411359,1.769071,1.353681,5.184917,0.271969
+84.400000,13.133862,4.241169,2.062992,4.521651,1.522088,0.523591,4.699303,0.115409,2.970984,0.653291,0.000268,0.326709,0.040769,25.992171,1.569145,19.602085,16.778737,4.383622,1.769041,1.354328,5.184916,0.344920
+84.500000,13.133059,4.300644,1.920314,4.278244,1.599661,0.490137,4.994852,0.119322,3.054936,0.637674,0.000244,0.342326,0.041097,25.997578,1.554962,19.620431,16.778461,4.376900,1.768952,1.354530,5.184916,0.410025
+84.600000,13.132016,4.383225,1.926278,4.105513,1.596021,0.471275,5.317776,0.123327,3.154296,0.629052,0.000247,0.350948,0.041371,26.048687,1.544756,19.636130,16.778705,4.393795,1.768882,1.354191,5.184915,0.407701
+84.700000,13.131521,4.424564,2.044126,4.097716,1.531648,0.475517,5.456932,0.124924,3.203328,0.631175,0.000268,0.348825,0.041439,26.107109,1.543470,19.640081,16.779223,4.419748,1.768887,1.353629,5.184915,0.354226
+84.800000,13.131889,4.397452,2.203135,4.273396,1.437429,0.503550,5.296117,0.122824,3.166762,0.643816,0.000300,0.336184,0.041229,26.129102,1.552008,19.629985,16.779639,4.435315,1.768963,1.353243,5.184916,0.289437
+84.900000,13.132962,4.314620,2.282976,4.528196,1.387375,0.537259,4.906137,0.117861,3.053885,0.659056,0.000316,0.320944,0.040844,26.086746,1.566850,19.609728,16.779593,4.425583,1.769050,1.353383,5.184916,0.259649
+85.000000,13.133847,4.244374,2.169715,4.601998,1.458942,0.538485,4.660016,0.114789,2.966644,0.660001,0.000289,0.319999,0.040677,26.014903,1.573210,19.598303,16.779050,4.396744,1.769068,1.354012,5.184917,0.301343
+85.100000,13.133577,4.261472,1.977290,4.407364,1.569707,0.506811,4.819180,0.117039,3.003261,0.645489,0.000253,0.334511,0.040917,25.987088,1.562579,19.610083,16.778537,4.377003,1.769001,1.354502,5.184916,0.383003
+85.200000,13.132527,4.342215,1.905584,4.178453,1.606993,0.478534,5.161776,0.121421,3.105666,0.632305,0.000243,0.347695,0.041247,26.018543,1.549086,19.629117,16.778523,4.382735,1.768912,1.354419,5.184915,0.417423
+85.300000,13.131682,4.410663,1.972543,4.078490,1.571303,0.470177,5.416831,0.124497,3.186797,0.628661,0.000255,0.351339,0.041436,26.078450,1.542938,19.639705,16.778941,4.406274,1.768874,1.353925,5.184915,0.386155
+85.400000,13.131585,4.420460,2.121031,4.161191,1.487106,0.486425,5.419657,0.124407,3.197576,0.636124,0.000283,0.343876,0.041373,26.124789,1.546357,19.637004,16.779460,4.429687,1.768917,1.353397,5.184915,0.321864
+85.500000,13.132352,4.361821,2.260836,4.399655,1.401313,0.521280,5.120843,0.120597,3.118263,0.651790,0.000312,0.328210,0.041048,26.116622,1.558976,19.620768,16.779690,4.434126,1.769008,1.353232,5.184916,0.267851
+85.600000,13.133488,4.273490,2.252909,4.601635,1.406909,0.543621,4.742283,0.115778,2.999819,0.662095,0.000307,0.317905,0.040709,26.051036,1.572086,19.601579,16.779373,4.412618,1.769071,1.353653,5.184917,0.270182
+85.700000,13.133875,4.240378,2.071378,4.530299,1.517280,0.524985,4.692086,0.115307,2.969287,0.653932,0.000269,0.326068,0.040758,25.993348,1.569622,19.601554,16.778759,4.384465,1.769044,1.354307,5.184917,0.341342
+85.800000,13.133104,4.297171,1.923238,4.287909,1.598162,0.491321,4.980297,0.119136,3.050571,0.638228,0.000245,0.341772,0.041083,25.996249,1.555533,19.619621,16.778462,4.376646,1.768956,1.354534,5.184916,0.408600
+85.900000,13.132051,4.380329,1.923435,4.109737,1.597522,0.471631,5.306976,0.123197,3.150870,0.629206,0.000247,0.350794,0.041363,26.046171,1.545013,19.635686,16.778687,4.392795,1.768884,1.354212,5.184915,0.409043
+86.000000,13.131525,4.424131,2.037875,4.094316,1.535182,0.474846,5.456650,0.124926,3.202829,0.630866,0.000267,0.349134,0.041441,26.105143,1.543332,19.640188,16.779201,4.418748,1.768885,1.353651,5.184915,0.356943
+86.100000,13.131856,4.399922,2.197087,4.263249,1.441160,0.502058,5.308768,0.122986,3.170092,0.643155,0.000299,0.336845,0.041242,26.129431,1.551478,19.630667,16.779629,4.435113,1.768959,1.353250,5.184915,0.291754
+86.200000,13.132913,4.318429,2.283172,4.519315,1.387226,0.536264,4.922637,0.118071,3.059039,0.658598,0.000316,0.321402,0.040859,26.089603,1.566272,19.610568,16.779607,4.426504,1.769047,1.353366,5.184916,0.259602
+86.300000,13.133830,4.245828,2.177657,4.605156,1.454082,0.539314,4.662110,0.114809,2.967961,0.660362,0.000290,0.319638,0.040675,26.017413,1.573320,19.598303,16.779077,4.397960,1.769070,1.353984,5.184917,0.298262
+86.400000,13.133610,4.259003,1.983583,4.417775,1.566312,0.508245,4.806763,0.116874,2.999735,0.646160,0.000254,0.333840,0.040904,25.986972,1.563188,19.609300,16.778550,4.377333,1.769005,1.354493,5.184916,0.380106
+86.500000,13.132572,4.338678,1.905520,4.185940,1.607048,0.479359,5.147985,0.121250,3.101433,0.632682,0.000243,0.347318,0.041235,26.016461,1.549526,19.628442,16.778513,4.382050,1.768915,1.354433,5.184915,0.417433
+86.600000,13.131704,4.408805,1.967741,4.079197,1.573900,0.470052,5.410420,0.124423,3.184587,0.628595,0.000254,0.351405,0.041433,26.075978,1.543010,19.639514,16.778919,4.405175,1.768874,1.353949,5.184915,0.388359
+86.700000,13.131571,4.421459,2.114282,4.154121,1.491093,0.485283,5.425754,0.124487,3.198906,0.635609,0.000282,0.344391,0.041381,26.123753,1.546020,19.637396,16.779441,4.428983,1.768914,1.353414,5.184915,0.324625
+86.800000,13.132307,4.365289,2.257010,4.388605,1.403735,0.519791,5.137417,0.120808,3.123006,0.651118,0.000311,0.328882,0.041064,26.118341,1.558339,19.621629,16.779691,4.434485,1.769005,1.353227,5.184916,0.269256
+86.900000,13.133448,4.276654,2.257409,4.597775,1.404020,0.543477,4.753716,0.115922,3.003825,0.662011,0.000309,0.317989,0.040717,26.054203,1.571769,19.602125,16.779396,4.413851,1.769070,1.353627,5.184917,0.268571
+87.000000,13.133884,4.239818,2.079850,4.538520,1.512388,0.526345,4.685704,0.115216,2.967870,0.654554,0.000271,0.325446,0.040748,25.994684,1.570071,19.601068,16.778782,4.385359,1.769047,1.354285,5.184917,0.337762
+87.100000,13.133149,4.293718,1.926518,4.297831,1.596478,0.492549,4.965646,0.118948,3.046191,0.638802,0.000245,0.341198,0.041069,25.995012,1.556119,19.618797,16.778463,4.376442,1.768960,1.354537,5.184916,0.407004
+87.200000,13.132089,4.377327,1.920764,4.114275,1.598929,0.472028,5.295772,0.123062,3.147330,0.629379,0.000246,0.350621,0.041355,26.043666,1.545287,19.635219,16.778670,4.391806,1.768886,1.354233,5.184915,0.410307
+87.300000,13.131531,4.423579,2.031651,4.091199,1.538685,0.474210,5.455860,0.124922,3.202185,0.630572,0.000266,0.349428,0.041444,26.103117,1.543208,19.640274,16.779179,4.417725,1.768883,1.353674,5.184915,0.359664
+87.400000,13.131825,4.402309,2.190894,4.253190,1.444969,0.500571,5.321062,0.123142,3.173309,0.642479,0.000297,0.337521,0.041256,26.129673,1.550953,19.631337,16.779618,4.434865,1.768955,1.353259,5.184915,0.294138
+87.500000,13.132864,4.322277,2.282998,4.510059,1.387315,0.535203,4.939465,0.118286,3.064255,0.658111,0.000316,0.321889,0.040874,26.092426,1.565676,19.611428,16.779620,4.427393,1.769045,1.353348,5.184916,0.259687
+87.600000,13.133811,4.247482,2.185466,4.607712,1.449280,0.540073,4.665143,0.114840,2.969575,0.660690,0.000292,0.319310,0.040674,26.020062,1.573390,19.598358,16.779104,4.399208,1.769071,1.353955,5.184917,0.295255
+87.700000,13.133642,4.256654,1.990260,4.428280,1.562687,0.509710,4.794563,0.116711,2.996301,0.646846,0.000255,0.333154,0.040889,25.987001,1.563802,19.608520,16.778564,4.377728,1.769009,1.354482,5.184916,0.377053
+87.800000,13.132618,4.335050,1.905750,4.193820,1.606956,0.480238,5.133769,0.121074,3.097086,0.633079,0.000243,0.346921,0.041222,26.014428,1.549988,19.627738,16.778504,4.381392,1.768918,1.354446,5.184915,0.417294
+87.900000,13.131728,4.406792,1.963041,4.080298,1.576435,0.469977,5.403342,0.124341,3.182185,0.628552,0.000254,0.351448,0.041429,26.073470,1.543102,19.639296,16.778898,4.404061,1.768874,1.353973,5.184915,0.390524
+88.000000,13.131559,4.422339,2.107413,4.147250,1.495137,0.484160,5.431308,0.124560,3.200068,0.635103,0.000281,0.344897,0.041389,26.122614,1.545697,19.637768,16.779423,4.428230,1.768911,1.353432,5.184915,0.327451
+88.100000,13.132262,4.368779,2.252819,4.377234,1.406381,0.518245,5.154185,0.121021,3.127772,0.650422,0.000310,0.329578,0.041081,26.120009,1.557692,19.622501,16.779691,4.434803,1.769001,1.353224,5.184916,0.270800
+88.200000,13.133405,4.280009,2.261759,4.593333,1.401221,0.543257,4.766049,0.116078,3.008100,0.661895,0.000310,0.318105,0.040726,26.057510,1.571415,19.602722,16.779420,4.415112,1.769069,1.353599,5.184917,0.267021
+88.300000,13.133892,4.239359,2.088662,4.546812,1.507278,0.527735,4.679504,0.115126,2.966541,0.655189,0.000272,0.324811,0.040738,25.996156,1.570520,19.600589,16.778807,4.386305,1.769050,1.354262,5.184917,0.334060
+88.400000,13.133195,4.290193,1.930056,4.308126,1.594655,0.493830,4.950579,0.118755,3.041691,0.639402,0.000246,0.340598,0.041054,25.993800,1.556728,19.617944,16.778466,4.376255,1.768964,1.354539,5.184916,0.405290
+88.500000,13.132127,4.374201,1.918131,4.119117,1.600316,0.472460,5.284048,0.122920,3.143631,0.629568,0.000245,0.350432,0.041346,26.041108,1.545578,19.634725,16.778652,4.390795,1.768888,1.354254,5.184915,0.411554
+88.600000,13.131538,4.422934,2.025313,4.088230,1.542242,0.473588,5.454673,0.124913,3.201416,0.630286,0.000265,0.349714,0.041445,26.100993,1.543093,19.640344,16.779156,4.416657,1.768882,1.353698,5.184915,0.362446
+88.700000,13.131794,4.404690,2.184449,4.242999,1.448920,0.499058,5.333358,0.123298,3.176502,0.641800,0.000296,0.338200,0.041270,26.129827,1.550426,19.632008,16.779606,4.434574,1.768951,1.353268,5.184915,0.296632
+88.800000,13.132812,4.326239,2.282598,4.500367,1.387551,0.534077,4.956889,0.118509,3.069629,0.657595,0.000316,0.322405,0.040890,26.095283,1.565057,19.612318,16.779632,4.428279,1.769042,1.353332,5.184916,0.259852
+88.900000,13.133790,4.249244,2.193425,4.610163,1.444363,0.540834,4.668517,0.114876,2.971312,0.661017,0.000294,0.318983,0.040672,26.022790,1.573450,19.598430,16.779132,4.400486,1.769072,1.353925,5.184917,0.292212
+89.000000,13.133675,4.254268,1.997134,4.439054,1.558939,0.511219,4.782075,0.116544,2.992791,0.647551,0.000256,0.332449,0.040875,25.987010,1.564432,19.607721,16.778578,4.378126,1.769013,1.354471,5.184916,0.373927
+89.100000,13.132665,4.331346,1.906007,4.201941,1.606847,0.481145,5.119207,0.120892,3.092616,0.633503,0.000243,0.346497,0.041210,26.012299,1.550467,19.627010,16.778495,4.380714,1.768922,1.354460,5.184915,0.417146
+89.200000,13.131753,4.404718,1.958239,4.081487,1.579017,0.469909,5.396098,0.124257,3.179727,0.628510,0.000253,0.351490,0.041424,26.070829,1.543202,19.639062,16.778875,4.402908,1.768875,1.353998,5.184915,0.392745
+89.300000,13.131547,4.423184,2.100421,4.140381,1.499237,0.483035,5.436811,0.124633,3.201209,0.634594,0.000279,0.345406,0.041397,26.121356,1.545373,19.638138,16.779403,4.427444,1.768908,1.353452,5.184915,0.330343
+89.400000,13.132217,4.372255,2.248500,4.365835,1.409108,0.516690,5.170965,0.121234,3.132527,0.649721,0.000309,0.330279,0.041098,26.121573,1.557043,19.623373,16.779690,4.435094,1.768997,1.353221,5.184916,0.272393
+89.500000,13.133363,4.283383,2.265794,4.588606,1.398618,0.542985,4.778667,0.116237,3.012433,0.661753,0.000311,0.318247,0.040736,26.060708,1.571046,19.603332,16.779442,4.416340,1.769068,1.353574,5.184917,0.265588
+89.600000,13.133899,4.239042,2.097345,4.554681,1.502217,0.529079,4.673973,0.115045,2.965422,0.655800,0.000274,0.324200,0.040728,25.997623,1.570941,19.600148,16.778830,4.387259,1.769053,1.354239,5.184917,0.330438
+89.700000,13.133240,4.286805,1.933787,4.318298,1.592721,0.495106,4.935981,0.118567,3.037345,0.639999,0.000246,0.340001,0.041040,25.992643,1.557330,19.617107,16.778468,4.376115,1.768968,1.354540,5.184916,0.403493
+89.800000,13.132166,4.371062,1.915806,4.124211,1.601540,0.472932,5.272239,0.122777,3.139920,0.629777,0.000245,0.350223,0.041337,26.038563,1.545883,19.634216,16.778635,4.389828,1.768890,1.354275,5.184915,0.412654
+89.900000,13.131547,4.422146,2.019238,4.085752,1.545636,0.473035,5.452864,0.124896,3.200483,0.630028,0.000264,0.349972,0.041446,26.098791,1.543001,19.640385,16.779133,4.415596,1.768880,1.353722,5.184915,0.365126
+90.000000,14.629470,4.556082,2.264016,4.594370,1.399773,0.543517,4.772817,0.116159,3.010481,0.661888,0.000310,0.318112,0.040738,26.538540,1.572089,19.606360,16.782450,4.417565,1.769859,1.354216,5.184738,0.266212
+90.100000,14.630051,4.509522,2.091535,4.551859,1.505609,0.528448,4.679610,0.115121,2.966838,0.655396,0.000273,0.324604,0.040743,26.476280,1.571454,19.603866,16.781834,4.388511,1.769842,1.354883,5.184738,0.332856
+90.200000,14.629389,4.557954,1.930463,4.312906,1.594450,0.494373,4.948880,0.118729,3.041228,0.639534,0.000246,0.340466,0.041059,26.473006,1.557655,19.621175,16.781485,4.378034,1.769756,1.355169,5.184737,0.405088
+90.300000,14.628268,4.645070,1.916326,4.121401,1.601257,0.472640,5.284802,0.122927,3.143797,0.629534,0.000245,0.350466,0.041354,26.519999,1.546361,19.638134,16.781665,4.392340,1.769678,1.354890,5.184736,0.412417
+90.400000,14.627594,4.699055,2.022459,4.087401,1.543835,0.473361,5.460155,0.124977,3.202904,0.630065,0.000265,0.349935,0.041457,26.580301,1.543712,19.643983,16.782169,4.418285,1.769671,1.354333,5.184736,0.363706
+90.500000,14.627797,4.684320,2.182104,4.239750,1.450352,0.498557,5.343820,0.123424,3.179506,0.641462,0.000296,0.338538,0.041286,26.610176,1.550904,19.635855,16.782626,4.436581,1.769740,1.353895,5.184737,0.297545
+90.600000,14.628833,4.605027,2.283128,4.498254,1.387199,0.533868,4.967868,0.118644,3.073124,0.657381,0.000316,0.322619,0.040906,26.576607,1.565553,19.616180,16.782661,4.430734,1.769831,1.353948,5.184738,0.259674
+90.700000,14.629897,4.522660,2.197086,4.613497,1.442098,0.541430,4.672405,0.114920,2.972908,0.661162,0.000294,0.318838,0.040681,26.503776,1.574259,19.601903,16.782165,4.402990,1.769863,1.354539,5.184738,0.290817
+90.800000,14.629865,4.522384,1.999591,4.445314,1.557600,0.512023,4.779664,0.116507,2.992232,0.647806,0.000257,0.332194,0.040878,26.466717,1.565445,19.610869,16.781604,4.380173,1.769805,1.355094,5.184738,0.372811
+90.900000,14.628845,4.599737,1.905292,4.206349,1.607226,0.481602,5.117084,0.120862,3.091966,0.633592,0.000243,0.346408,0.041215,26.491166,1.551370,19.630254,16.781511,4.382303,1.769713,1.355094,5.184737,0.417483
+91.000000,14.627855,4.677906,1.955416,4.082432,1.580528,0.469894,5.398269,0.124281,3.180252,0.628381,0.000252,0.351619,0.041434,26.549674,1.543915,19.642559,16.781886,4.404364,1.769665,1.354636,5.184736,0.394057
+91.100000,14.627570,4.701447,2.096994,4.137650,1.501238,0.482553,5.445224,0.124734,3.203516,0.634262,0.000279,0.345738,0.041412,26.601042,1.545894,19.641911,16.782417,4.429157,1.769697,1.354084,5.184736,0.331769
+91.200000,14.628213,4.652400,2.246848,4.361556,1.410145,0.516101,5.183928,0.121393,3.136379,0.649341,0.000309,0.330659,0.041117,26.602637,1.557442,19.627341,16.782714,4.437351,1.769786,1.353842,5.184737,0.273007
+91.300000,14.629414,4.560313,2.268420,4.588382,1.396926,0.543127,4.788077,0.116352,3.015676,0.661692,0.000311,0.318308,0.040749,26.542390,1.571631,19.607106,16.782476,4.418996,1.769858,1.354185,5.184738,0.264655
+91.400000,14.630053,4.509476,2.101737,4.560775,1.499648,0.529993,4.673663,0.115033,2.965704,0.656098,0.000275,0.323902,0.040732,26.478196,1.571927,19.603380,16.781864,4.389666,1.769846,1.354854,5.184738,0.328616
+91.500000,14.629440,4.553984,1.935026,4.324901,1.592084,0.495884,4.931800,0.118509,3.036154,0.640242,0.000246,0.339758,0.041042,26.471815,1.558364,19.620192,16.781490,4.377908,1.769761,1.355169,5.184737,0.402890
+91.600000,14.628316,4.641160,1.913736,4.127516,1.602620,0.473216,5.270783,0.122757,3.139406,0.629782,0.000245,0.350218,0.041343,26.517147,1.546724,19.637529,16.781647,4.391226,1.769682,1.354912,5.184736,0.413645
+91.700000,14.627607,4.697883,2.015391,4.084694,1.547774,0.472740,5.457723,0.124954,3.201722,0.629781,0.000263,0.350219,0.041458,26.577782,1.543615,19.644014,16.782143,4.417037,1.769670,1.354360,5.184736,0.366836
+91.800000,14.627763,4.686771,2.174513,4.228510,1.454983,0.496866,5.356891,0.123591,3.182842,0.640702,0.000294,0.339298,0.041302,26.610145,1.550329,19.636580,16.782611,4.436159,1.769736,1.353907,5.184737,0.300504
+91.900000,14.628770,4.609702,2.281883,4.486562,1.387975,0.532461,4.988164,0.118903,3.079299,0.656739,0.000316,0.323261,0.040925,26.579755,1.564819,19.617221,16.782674,4.431663,1.769828,1.353930,5.184738,0.260143
+92.000000,14.629863,4.525280,2.205702,4.614967,1.436740,0.542128,4.678193,0.114986,2.975476,0.661456,0.000296,0.318544,0.040681,26.507133,1.574244,19.602097,16.782197,4.404490,1.769865,1.354504,5.184738,0.287559
+92.100000,14.629895,4.520073,2.008029,4.457414,1.552965,0.513756,4.766350,0.116327,2.988565,0.648615,0.000258,0.331385,0.040863,26.467080,1.566146,19.609997,16.781624,4.380762,1.769811,1.355078,5.184738,0.369007
+92.200000,14.628901,4.595324,1.906246,4.216183,1.606764,0.482725,5.100092,0.120650,3.086785,0.634110,0.000243,0.345890,0.041200,26.488956,1.551948,19.629388,16.781503,4.381626,1.769718,1.355106,5.184737,0.416990
+92.300000,14.627889,4.675065,1.950317,4.084589,1.583261,0.469924,5.388870,0.124172,3.177130,0.628387,0.000252,0.351613,0.041426,26.546701,1.544068,19.642238,16.781862,4.403066,1.769666,1.354662,5.184736,0.396422
+92.400000,14.627561,4.701987,2.089019,4.130527,1.505885,0.481356,5.450116,0.124800,3.204411,0.633719,0.000277,0.346281,0.041419,26.599458,1.545564,19.642276,16.782394,4.428187,1.769694,1.354106,5.184736,0.335096
+92.500000,14.628161,4.656267,2.241250,4.348438,1.413667,0.514277,5.202566,0.121630,3.141581,0.648520,0.000308,0.331480,0.041136,26.604207,1.556710,19.628315,16.782711,4.437560,1.769782,1.353841,5.184737,0.275083
+92.600000,14.629356,4.564658,2.272165,4.581563,1.394496,0.542599,4.804213,0.116557,3.021083,0.661434,0.000312,0.318566,0.040762,26.546192,1.571128,19.607904,16.782501,4.420379,1.769857,1.354155,5.184738,0.263339
+92.700000,14.630049,4.509776,2.111954,4.568930,1.493634,0.531464,4.669078,0.114963,2.965017,0.656763,0.000277,0.323237,0.040723,26.480315,1.572348,19.602971,16.781894,4.390884,1.769849,1.354824,5.184738,0.324413
+92.800000,14.629490,4.550146,1.940120,4.337078,1.589432,0.497440,4.914936,0.118291,3.031172,0.640971,0.000247,0.339029,0.041025,26.470793,1.559082,19.619208,16.781496,4.377869,1.769767,1.355167,5.184737,0.400449
+92.900000,14.628366,4.637137,1.911524,4.134115,1.603787,0.473859,5.256278,0.122580,3.134878,0.630068,0.000244,0.349932,0.041332,26.514340,1.547114,19.636890,16.781630,4.390153,1.769685,1.354934,5.184736,0.414689
+93.000000,14.627623,4.696504,2.008506,4.082515,1.551597,0.472187,5.454439,0.124919,3.200309,0.629511,0.000262,0.350489,0.041459,26.575207,1.543544,19.644007,16.782117,4.415773,1.769670,1.354387,5.184736,0.369898
+93.100000,14.627732,4.689031,2.166773,4.217587,1.459689,0.495208,5.369186,0.123748,3.185934,0.639959,0.000292,0.340041,0.041315,26.609944,1.549776,19.637270,16.782596,4.435674,1.769733,1.353920,5.184737,0.303539
+93.200000,14.628708,4.614358,2.280118,4.474497,1.389086,0.530978,5.008627,0.119163,3.085470,0.656065,0.000316,0.323935,0.040944,26.582798,1.564072,19.618273,16.782685,4.432532,1.769825,1.353914,5.184738,0.260796
+93.300000,14.629826,4.528118,2.213979,4.615628,1.431568,0.542718,4.685094,0.115068,2.978373,0.661700,0.000298,0.318300,0.040683,26.510597,1.574178,19.602357,16.782229,4.406002,1.769866,1.354469,5.184738,0.284454
+93.400000,14.629923,4.517983,2.016719,4.469280,1.548163,0.515482,4.753693,0.116156,2.985126,0.649419,0.000260,0.330581,0.040847,26.467616,1.566831,19.609157,16.781644,4.381416,1.769816,1.355060,5.184738,0.365119
+93.500000,14.628956,4.590943,1.907583,4.226261,1.606104,0.483891,5.083053,0.120436,3.081603,0.634649,0.000243,0.345351,0.041185,26.486866,1.552540,19.628508,16.781497,4.381009,1.769723,1.355117,5.184737,0.416314
+93.600000,14.627925,4.672095,1.945520,4.087210,1.585813,0.470018,5.378903,0.124054,3.173860,0.628412,0.000250,0.351588,0.041422,26.543751,1.544244,19.641885,16.781838,4.401786,1.769668,1.354689,5.184736,0.398668
+93.700000,14.627555,4.702326,2.081138,4.123911,1.510455,0.480223,5.454141,0.124855,3.205061,0.633204,0.000275,0.346796,0.041427,26.597769,1.545262,19.642601,16.782370,4.427180,1.769692,1.354129,5.184736,0.338408
+93.800000,14.628112,4.659995,2.235385,4.335433,1.417350,0.512452,5.220717,0.121860,3.146608,0.647699,0.000307,0.332301,0.041154,26.605630,1.555990,19.629268,16.782707,4.437705,1.769778,1.353841,5.184737,0.277266
+93.900000,14.629298,4.569067,2.275409,4.574171,1.392385,0.541974,4.820917,0.116770,3.026616,0.661135,0.000313,0.318865,0.040776,26.549975,1.570595,19.608735,16.782525,4.421727,1.769856,1.354126,5.184738,0.262207
+94.000000,14.630043,4.510313,2.122103,4.576503,1.487626,0.532874,4.665456,0.114905,2.964642,0.657398,0.000279,0.322602,0.040714,26.482582,1.572730,19.602618,16.781924,4.392138,1.769852,1.354792,5.184738,0.320272
+94.100000,14.629538,4.546440,1.945563,4.349303,1.586579,0.499019,4.898344,0.118075,3.026293,0.641711,0.000248,0.338289,0.041008,26.469919,1.559803,19.618228,16.781505,4.377893,1.769772,1.355163,5.184737,0.397859
+94.200000,14.628417,4.633054,1.909614,4.141070,1.604797,0.474555,5.241458,0.122399,3.130265,0.630381,0.000244,0.349619,0.041320,26.511592,1.547526,19.636223,16.781613,4.389115,1.769689,1.354954,5.184737,0.415590
+94.300000,14.627641,4.694961,2.001765,4.080809,1.555324,0.471698,5.450479,0.124877,3.198698,0.629286,0.000261,0.350714,0.041459,26.572567,1.543500,19.643964,16.782091,4.414496,1.769669,1.354414,5.184736,0.372912
+94.400000,14.627704,4.691116,2.158950,4.207017,1.464426,0.493590,5.380750,0.123896,3.188803,0.639232,0.000291,0.340768,0.041329,26.609593,1.549245,19.637928,16.782579,4.435130,1.769729,1.353934,5.184737,0.306625
+94.500000,14.628647,4.618970,2.277867,4.462149,1.390510,0.529434,5.029148,0.119425,3.091606,0.655363,0.000315,0.324637,0.040964,26.585721,1.563316,19.619329,16.782695,4.433336,1.769822,1.353899,5.184738,0.261624
+94.600000,14.629786,4.531183,2.221853,4.615392,1.426625,0.543186,4.693232,0.115166,2.981632,0.661889,0.000300,0.318111,0.040686,26.514174,1.574056,19.602688,16.782260,4.407524,1.769867,1.354434,5.184738,0.281523
+94.700000,14.629948,4.516132,2.025772,4.480980,1.543125,0.517215,4.741697,0.115992,2.981927,0.650225,0.000261,0.329775,0.040832,26.468358,1.567501,19.608348,16.781667,4.382149,1.769821,1.355040,5.184738,0.361104
+94.800000,14.629012,4.586538,1.909338,4.236712,1.605228,0.485113,5.065778,0.120218,3.076365,0.635213,0.000243,0.344787,0.041170,26.484883,1.553154,19.627603,16.781493,4.380448,1.769728,1.355127,5.184737,0.415434
+94.900000,14.627963,4.668966,1.940924,4.090300,1.588263,0.470174,5.368302,0.123928,3.170408,0.628472,0.000250,0.351528,0.041414,26.540792,1.544446,19.641497,16.781815,4.400512,1.769670,1.354715,5.184736,0.400814
+95.000000,14.627551,4.702479,2.073242,4.117700,1.515017,0.479142,5.457405,0.124902,3.205483,0.632717,0.000274,0.347283,0.041433,26.595967,1.544983,19.642891,16.782347,4.426132,1.769690,1.354153,5.184737,0.341742
+95.100000,14.628063,4.663621,2.229191,4.322423,1.421229,0.510611,5.238542,0.122087,3.151503,0.646872,0.000305,0.333128,0.041173,26.606918,1.555277,19.630208,16.782702,4.437784,1.769775,1.353842,5.184737,0.279580
+95.200000,14.629238,4.573593,2.278134,4.566061,1.390603,0.541233,4.838437,0.116993,3.032351,0.660784,0.000314,0.319216,0.040791,26.553782,1.570024,19.609613,16.782548,4.423052,1.769855,1.354097,5.184738,0.261264
+95.300000,14.630033,4.511101,2.132310,4.583573,1.481545,0.534240,4.662777,0.114860,2.964582,0.658010,0.000281,0.321990,0.040706,26.485033,1.573077,19.602319,16.781956,4.393445,1.769856,1.354760,5.184738,0.316146
+95.400000,14.629584,4.542821,1.951361,4.361662,1.583533,0.500629,4.881882,0.117860,3.021469,0.642467,0.000249,0.337533,0.040991,26.469184,1.560532,19.617246,16.781514,4.377978,1.769778,1.355158,5.184738,0.395107
+95.500000,14.628468,4.628905,1.907992,4.148372,1.605654,0.475300,5.226303,0.122213,3.125563,0.630714,0.000244,0.349286,0.041309,26.508910,1.547956,19.635533,16.781598,4.388110,1.769693,1.354974,5.184737,0.416354
+95.600000,14.627660,4.693263,1.995186,4.079544,1.558947,0.471267,5.445842,0.124826,3.196902,0.629079,0.000259,0.350921,0.041457,26.569902,1.543478,19.643889,16.782065,4.413208,1.769669,1.354441,5.184736,0.375868
+95.700000,14.627677,4.693033,2.151039,4.196779,1.469197,0.492010,5.391602,0.124036,3.191453,0.638524,0.000289,0.341476,0.041341,26.609108,1.548737,19.638552,16.782562,4.434530,1.769726,1.353949,5.184737,0.309765
+95.800000,14.628586,4.623542,2.275174,4.449557,1.392217,0.527834,5.049704,0.119687,3.097704,0.654637,0.000315,0.325363,0.040984,26.588540,1.562553,19.620388,16.782703,4.434079,1.769819,1.353885,5.184738,0.262610
+95.900000,14.629743,4.534428,2.229363,4.614420,1.421890,0.543552,4.702361,0.115278,2.985176,0.662031,0.000302,0.317969,0.040691,26.517838,1.573890,19.603077,16.782292,4.409049,1.769868,1.354399,5.184738,0.278747
+96.000000,14.629970,4.514488,2.035031,4.492433,1.537943,0.518937,4.730348,0.115836,2.978951,0.651023,0.000263,0.328977,0.040817,26.469263,1.568154,19.607571,16.781690,4.382939,1.769826,1.355019,5.184738,0.357027
+96.100000,14.629067,4.582166,1.911429,4.247389,1.604181,0.486374,5.048475,0.120000,3.071125,0.635801,0.000243,0.344199,0.041153,26.483005,1.553783,19.626685,16.781489,4.379939,1.769734,1.355136,5.184737,0.414391
+96.200000,14.628002,4.665725,1.936569,4.093788,1.590572,0.470385,5.357232,0.123797,3.166825,0.628558,0.000249,0.351442,0.041408,26.537851,1.544669,19.641081,16.781793,4.399254,1.769672,1.354741,5.184737,0.402860
+96.300000,14.627549,4.702457,2.065450,4.111944,1.519493,0.478119,5.459904,0.124938,3.205694,0.632248,0.000272,0.347752,0.041439,26.594087,1.544727,19.643150,16.782322,4.425054,1.769688,1.354177,5.184737,0.345057
+96.400000,14.628016,4.667104,2.222763,4.309586,1.425244,0.508778,5.255815,0.122306,3.156209,0.646049,0.000304,0.333951,0.041191,26.608047,1.554580,19.631121,16.782695,4.437794,1.769771,1.353845,5.184737,0.281994
+96.500000,14.629177,4.578169,2.280329,4.557396,1.389161,0.540394,4.856476,0.117223,3.038194,0.660390,0.000315,0.319610,0.040806,26.557547,1.569425,19.610520,16.782570,4.424332,1.769853,1.354070,5.184738,0.260511
+96.600000,14.630020,4.512143,2.142397,4.589963,1.475500,0.535532,4.661195,0.114829,2.964872,0.658585,0.000283,0.321415,0.040700,26.487638,1.573379,19.602083,16.781988,4.394787,1.769859,1.354728,5.184738,0.312104
+96.700000,14.629629,4.539350,1.957547,4.374074,1.580261,0.502265,4.865728,0.117649,3.016763,0.643235,0.000250,0.336765,0.040974,26.468608,1.561263,19.616270,16.781525,4.378130,1.769784,1.355151,5.184738,0.392193
+96.800000,14.628520,4.624691,1.906686,4.156040,1.606355,0.476097,5.210830,0.122024,3.120770,0.631077,0.000243,0.348923,0.041295,26.506295,1.548407,19.634818,16.781584,4.387143,1.769697,1.354993,5.184737,0.416960
+96.900000,14.627681,4.691402,1.988784,4.078744,1.562459,0.470899,5.440525,0.124768,3.194916,0.628901,0.000258,0.351099,0.041455,26.567200,1.543476,19.643784,16.782040,4.411913,1.769670,1.354469,5.184737,0.378758
+97.000000,14.627653,4.694769,2.143098,4.186927,1.473963,0.490475,5.401656,0.124165,3.193867,0.637830,0.000288,0.342170,0.041354,26.608498,1.548249,19.639146,16.782544,4.433877,1.769723,1.353965,5.184737,0.312940
+97.100000,14.628525,4.628041,2.272056,4.436805,1.394195,0.526190,5.070111,0.119947,3.103710,0.653893,0.000314,0.326107,0.041004,26.591232,1.561790,19.621443,16.782710,4.434755,1.769816,1.353873,5.184738,0.263750
+97.200000,14.629698,4.537844,2.236428,4.612655,1.417418,0.543803,4.712472,0.115403,2.988994,0.662121,0.000303,0.317879,0.040696,26.521569,1.573676,19.603525,16.782323,4.410563,1.769869,1.354364,5.184739,0.276155
+97.300000,14.629988,4.513083,2.044477,4.503561,1.532622,0.520640,4.719743,0.115689,2.976232,0.651812,0.000264,0.328188,0.040803,26.470343,1.568783,19.606833,16.781715,4.383786,1.769831,1.354996,5.184738,0.352902
+97.400000,14.629122,4.577844,1.913892,4.258273,1.602937,0.487674,5.031169,0.119781,3.065900,0.636405,0.000244,0.343595,0.041137,26.481253,1.554424,19.625755,16.781487,4.379486,1.769739,1.355143,5.184737,0.413172
+97.500000,14.628043,4.662382,1.932466,4.097659,1.592748,0.470649,5.345716,0.123660,3.163119,0.628669,0.000248,0.351331,0.041399,26.534946,1.544912,19.640637,16.781771,4.398015,1.769675,1.354766,5.184737,0.404787
+97.600000,14.627549,4.702266,2.057746,4.106635,1.523905,0.477155,5.461669,0.124966,3.205693,0.631813,0.000271,0.348187,0.041443,26.592126,1.544496,19.643372,16.782298,4.423948,1.769687,1.354201,5.184737,0.348350
+97.700000,14.627971,4.670439,2.216145,4.296956,1.429363,0.506962,5.272489,0.122517,3.160715,0.645233,0.000302,0.334767,0.041209,26.609030,1.553900,19.632007,16.782687,4.437741,1.769767,1.353849,5.184737,0.284493
+97.800000,14.629115,4.582774,2.282013,4.548239,1.388047,0.539466,4.874917,0.117458,3.044107,0.659957,0.000315,0.320043,0.040822,26.561258,1.568802,19.611452,16.782590,4.425565,1.769852,1.354045,5.184738,0.259940
+97.900000,14.630003,4.513417,2.152331,4.595699,1.469511,0.536750,4.660619,0.114811,2.965480,0.659125,0.000285,0.320875,0.040694,26.490377,1.573638,19.601906,16.782020,4.396154,1.769862,1.354694,5.184739,0.308159
+98.000000,14.629672,4.536026,1.964048,4.386478,1.576805,0.503917,4.849909,0.117441,3.012179,0.644010,0.000251,0.335990,0.040957,26.468176,1.561994,19.615304,16.781538,4.378341,1.769790,1.355143,5.184738,0.389147
+98.100000,14.628573,4.620445,1.905683,4.164007,1.606896,0.476939,5.195134,0.121831,3.115923,0.631458,0.000243,0.348542,0.041282,26.503750,1.548876,19.634080,16.781570,4.386212,1.769702,1.355011,5.184737,0.417422
+98.200000,14.627704,4.689406,1.982540,4.078340,1.565867,0.470584,5.434658,0.124701,3.192778,0.628750,0.000257,0.351250,0.041453,26.564466,1.543500,19.643645,16.782014,4.410613,1.769670,1.354496,5.184737,0.381594
+98.300000,14.627630,4.696346,2.135121,4.177435,1.478732,0.488985,5.411032,0.124286,3.196075,0.637163,0.000286,0.342837,0.041365,26.607754,1.547785,19.639706,16.782525,4.433177,1.769720,1.353982,5.184737,0.316147
+98.400000,14.628466,4.632471,2.268568,4.423938,1.396407,0.524511,5.090389,0.120205,3.109636,0.653133,0.000313,0.326867,0.041023,26.593795,1.561027,19.622491,16.782716,4.435369,1.769813,1.353863,5.184738,0.265025
+98.500000,14.629650,4.541405,2.243088,4.610197,1.413185,0.543953,4.723466,0.115539,2.993056,0.662165,0.000305,0.317835,0.040703,26.525344,1.573422,19.604024,16.782353,4.412069,1.769869,1.354330,5.184739,0.273728
+98.600000,14.630004,4.511887,2.054094,4.514413,1.527169,0.522329,4.709805,0.115551,2.973744,0.652591,0.000266,0.327409,0.040789,26.471564,1.569393,19.606130,16.781740,4.384683,1.769836,1.354973,5.184738,0.348738
+98.700000,14.629176,4.573557,1.916680,4.269371,1.601522,0.489009,5.013838,0.119561,3.060678,0.637027,0.000244,0.342973,0.041121,26.479587,1.555078,19.624813,16.781486,4.379081,1.769745,1.355149,5.184738,0.411798
+98.800000,14.628084,4.658934,1.928595,4.101920,1.594793,0.470967,5.333744,0.123516,3.159289,0.628803,0.000247,0.351197,0.041390,26.532040,1.545176,19.640165,16.781749,4.396790,1.769677,1.354792,5.184737,0.406612
+98.900000,14.627551,4.701906,2.050142,4.101776,1.528232,0.476252,5.462696,0.124985,3.205486,0.631401,0.000270,0.348599,0.041448,26.590064,1.544287,19.643564,16.782273,4.422810,1.769685,1.354226,5.184737,0.351626
+99.000000,14.627927,4.673630,2.209317,4.284522,1.433601,0.505160,5.288600,0.122722,3.165030,0.644423,0.000301,0.335577,0.041226,26.609836,1.553237,19.632867,16.782678,4.437619,1.769764,1.353854,5.184738,0.287083
+99.100000,14.629053,4.587416,2.283175,4.538565,1.387270,0.538444,4.893820,0.117699,3.050110,0.659483,0.000316,0.320517,0.040839,26.564896,1.568155,19.612411,16.782610,4.426749,1.769850,1.354020,5.184738,0.259556
+99.200000,14.629984,4.514934,2.162114,4.600748,1.463579,0.537890,4.661130,0.114808,2.966432,0.659627,0.000287,0.320373,0.040689,26.493240,1.573852,19.601792,16.782052,4.397552,1.769865,1.354661,5.184739,0.304308
+99.300000,14.629713,4.532855,1.970905,4.398895,1.573141,0.505590,4.834437,0.117237,3.007725,0.644794,0.000252,0.335206,0.040940,26.467877,1.562724,19.614349,16.781551,4.378616,1.769795,1.355134,5.184738,0.385955
+99.400000,14.628626,4.616153,1.905018,4.172323,1.607259,0.477833,5.179161,0.121633,3.111002,0.631864,0.000243,0.348136,0.041268,26.501258,1.549364,19.633319,16.781558,4.385322,1.769706,1.355029,5.184737,0.417724
+99.500000,14.627730,4.687249,1.976501,4.078421,1.569154,0.470335,5.428092,0.124627,3.190449,0.628624,0.000256,0.351376,0.041450,26.561687,1.543545,19.643476,16.781989,4.409307,1.769671,1.354524,5.184737,0.384346
+99.600000,14.627610,4.697735,2.127106,4.168345,1.483505,0.487543,5.419597,0.124398,3.198042,0.636517,0.000285,0.343483,0.041373,26.606855,1.547346,19.640230,16.782506,4.432421,1.769717,1.354000,5.184737,0.319390
+99.700000,14.628407,4.636831,2.264644,4.410896,1.398896,0.522787,5.110558,0.120461,3.115481,0.652354,0.000313,0.327646,0.041043,26.596206,1.560263,19.623534,16.782720,4.435913,1.769810,1.353854,5.184738,0.266461
+99.800000,14.629601,4.545143,2.249301,4.606932,1.409221,0.543984,4.735497,0.115689,2.997406,0.662157,0.000307,0.317843,0.040711,26.529172,1.573119,19.604583,16.782382,4.413568,1.769870,1.354297,5.184739,0.271478
+99.900000,14.630017,4.510935,2.063905,4.524918,1.521570,0.523998,4.700668,0.115423,2.971532,0.653359,0.000268,0.326641,0.040776,26.472950,1.569978,19.605468,16.781767,4.385642,1.769840,1.354948,5.184739,0.344526
+100.000000,16.124360,4.950561,2.031232,4.091012,1.538915,0.474165,5.468442,0.125067,3.205977,0.630342,0.000266,0.349658,0.041465,26.985360,1.544360,19.646880,16.784640,4.421544,1.770327,1.354801,5.184595,0.359853
+100.100000,16.124588,4.933204,2.192196,4.255000,1.444161,0.500843,5.331478,0.123261,3.176617,0.642394,0.000298,0.337606,0.041276,27.012118,1.552206,19.637806,16.785084,4.438840,1.770400,1.354381,5.184596,0.293643
+100.200000,16.125683,4.849747,2.285373,4.515001,1.385784,0.535911,4.944658,0.118343,3.066157,0.658218,0.000317,0.321782,0.040889,26.974286,1.567116,19.617644,16.785084,4.431222,1.770490,1.354473,5.184597,0.258843
+100.300000,16.126778,4.766082,2.186342,4.613705,1.448748,0.540793,4.666689,0.114853,2.970228,0.660805,0.000292,0.319195,0.040686,26.900899,1.574925,19.604412,16.784561,4.402637,1.770517,1.355089,5.184597,0.294910
+100.400000,16.126717,4.768894,1.988445,4.431613,1.563685,0.509992,4.798390,0.116755,2.997478,0.646759,0.000255,0.333241,0.040905,26.867456,1.565176,19.614759,16.784014,4.380888,1.770454,1.355623,5.184596,0.377871
+100.500000,16.125655,4.849577,1.903166,4.194700,1.608282,0.480232,5.141712,0.121167,3.099454,0.632861,0.000242,0.347139,0.041242,26.895191,1.551207,19.634206,16.783954,4.384613,1.770362,1.355586,5.184595,0.418552
+100.600000,16.124631,4.929388,1.960989,4.079861,1.577530,0.469838,5.414652,0.124473,3.185525,0.628273,0.000253,0.351727,0.041450,26.954864,1.544252,19.645877,16.784351,4.407538,1.770317,1.355108,5.184595,0.391481
+100.700000,16.124343,4.952093,2.106676,4.146690,1.495563,0.484054,5.444228,0.124710,3.203941,0.634847,0.000281,0.345153,0.041412,27.004725,1.546834,19.644379,16.784883,4.432030,1.770354,1.354560,5.184595,0.327761
+100.800000,16.125029,4.899544,2.254172,4.378755,1.405520,0.518494,5.164981,0.121148,3.131254,0.650323,0.000311,0.329677,0.041102,27.002427,1.558925,19.628997,16.785156,4.438802,1.770445,1.354347,5.184596,0.270309
+100.900000,16.126284,4.804090,2.264362,4.598559,1.399561,0.544011,4.770784,0.116129,3.009908,0.662019,0.000310,0.317981,0.040741,26.939234,1.572875,19.608916,16.784884,4.418945,1.770514,1.354725,5.184597,0.266077
+101.000000,16.126926,4.754068,2.089380,4.552807,1.506867,0.528437,4.680953,0.115138,2.967142,0.655298,0.000273,0.324702,0.040751,26.876844,1.572053,19.606645,16.784262,4.389718,1.770495,1.355397,5.184597,0.333753
+101.100000,16.126277,4.801965,1.928288,4.311613,1.595585,0.494139,4.954371,0.118798,3.042853,0.639324,0.000246,0.340676,0.041070,26.874132,1.558102,19.624187,16.783914,4.379413,1.770408,1.355680,5.184596,0.406127
+101.200000,16.125113,4.891738,1.915479,4.120124,1.601690,0.472464,5.291871,0.123011,3.145928,0.629350,0.000245,0.350650,0.041365,26.921712,1.546807,19.641178,16.784101,4.393997,1.770331,1.355395,5.184595,0.412831
+101.300000,16.124379,4.949235,2.022957,4.087331,1.543552,0.473374,5.466530,0.125051,3.204870,0.629977,0.000265,0.350023,0.041468,26.982325,1.544223,19.646947,16.784609,4.420135,1.770324,1.354833,5.184595,0.363491
+101.400000,16.124551,4.936180,2.183644,4.241717,1.449406,0.498862,5.347369,0.123463,3.180724,0.641505,0.000296,0.338495,0.041294,27.012056,1.551521,19.638674,16.785067,4.438437,1.770393,1.354395,5.184596,0.296950
+101.500000,16.125612,4.855267,2.284593,4.502062,1.386257,0.534392,4.967698,0.118637,3.073234,0.657523,0.000317,0.322477,0.040911,26.977805,1.566293,19.618821,16.785099,4.432364,1.770485,1.354453,5.184596,0.259150
+101.600000,16.126742,4.769023,2.196615,4.616413,1.442396,0.541726,4.671857,0.114910,2.972732,0.661204,0.000294,0.318796,0.040685,26.904375,1.574974,19.604548,16.784596,4.404334,1.770516,1.355051,5.184597,0.290990
+101.700000,16.126756,4.766085,1.997709,4.445633,1.558636,0.511969,4.782437,0.116541,2.993025,0.647683,0.000256,0.332317,0.040887,26.867435,1.565994,19.613729,16.784033,4.381475,1.770458,1.355607,5.184596,0.373656
+101.800000,16.125723,4.844415,1.903791,4.205550,1.607992,0.481455,5.122481,0.120927,3.093575,0.633428,0.000242,0.346572,0.041225,26.892323,1.551845,19.633241,16.783942,4.383773,1.770365,1.355604,5.184595,0.418217
+101.900000,16.124674,4.926104,1.954896,4.081783,1.580799,0.469799,5.404605,0.124355,3.182156,0.628241,0.000252,0.351759,0.041445,26.951255,1.544400,19.645549,16.784322,4.406041,1.770316,1.355141,5.184595,0.394305
+102.000000,16.124335,4.952801,2.097513,4.138023,1.500933,0.482618,5.450766,0.124798,3.205236,0.634201,0.000278,0.345799,0.041420,27.002830,1.546429,19.644836,16.784855,4.430966,1.770348,1.354587,5.184595,0.331555
+102.100000,16.124971,4.904158,2.248140,4.363669,1.409324,0.516416,5.186829,0.121425,3.137402,0.649388,0.000309,0.330612,0.041124,27.004202,1.558075,19.630135,16.785153,4.439124,1.770438,1.354345,5.184596,0.272536
+102.200000,16.126220,4.809153,2.269316,4.591590,1.396355,0.543546,4.788363,0.116352,3.015882,0.661786,0.000312,0.318214,0.040754,26.943387,1.572345,19.609776,16.784912,4.420568,1.770511,1.354691,5.184597,0.264329
+102.300000,16.126927,4.754280,2.101063,4.562845,1.500045,0.530185,4.674439,0.115041,2.965939,0.656092,0.000275,0.323908,0.040739,26.878849,1.572584,19.606104,16.784294,4.391050,1.770498,1.355365,5.184597,0.328892
+102.400000,16.126338,4.797443,1.933619,4.325329,1.592824,0.495872,4.934926,0.118547,3.037084,0.640137,0.000246,0.339863,0.041050,26.872590,1.558913,19.623065,16.783919,4.379288,1.770412,1.355681,5.184596,0.403557
+102.500000,16.125174,4.887062,1.912606,4.127202,1.603202,0.473135,5.275758,0.122816,3.140885,0.629647,0.000245,0.350353,0.041353,26.918242,1.547229,19.640479,16.784079,4.392734,1.770332,1.355422,5.184595,0.414192
+102.600000,16.124400,4.947663,2.014924,4.084334,1.548031,0.472676,5.463579,0.125022,3.203474,0.629651,0.000263,0.350349,0.041469,26.979226,1.544119,19.646974,16.784578,4.418706,1.770321,1.354866,5.184595,0.367045
+102.700000,16.124517,4.938891,2.174918,4.228889,1.454734,0.496929,5.362211,0.123652,3.184502,0.640638,0.000294,0.339362,0.041311,27.011781,1.550867,19.639497,16.785049,4.437944,1.770387,1.354410,5.184595,0.300348
+102.800000,16.125542,4.860757,2.283090,4.488575,1.387195,0.532764,4.991033,0.118935,3.080327,0.656781,0.000316,0.323219,0.040932,26.981202,1.565449,19.620018,16.785112,4.433423,1.770480,1.354434,5.184596,0.259715
+102.900000,16.126701,4.772288,2.206460,4.617980,1.436271,0.542511,4.678651,0.114989,2.975722,0.661535,0.000297,0.318465,0.040686,26.908041,1.574950,19.604778,16.784631,4.406058,1.770516,1.355012,5.184597,0.287270
+103.000000,16.126792,4.763591,2.007407,4.459410,1.553312,0.513948,4.767342,0.116338,2.988876,0.648606,0.000258,0.331394,0.040869,26.867692,1.566794,19.612737,16.784054,4.382164,1.770462,1.355589,5.184596,0.369282
+103.100000,16.125791,4.839264,1.904971,4.216829,1.607421,0.482746,5.103042,0.120684,3.087658,0.634019,0.000242,0.345981,0.041208,26.889638,1.552509,19.632248,16.783933,4.383014,1.770369,1.355619,5.184595,0.417608
+103.200000,16.124720,4.922619,1.949142,4.084340,1.583878,0.469846,5.393732,0.124228,3.178556,0.628250,0.000251,0.351750,0.041438,26.947677,1.544580,19.645176,16.784293,4.404563,1.770316,1.355173,5.184595,0.396980
+103.300000,16.124330,4.953239,2.088406,4.129957,1.506238,0.481258,5.456207,0.124871,3.206215,0.633583,0.000277,0.346417,0.041430,27.000816,1.546058,19.645245,16.784828,4.429852,1.770344,1.354613,5.184595,0.335356
+103.400000,16.124913,4.908600,2.241701,4.348647,1.413379,0.514325,5.208135,0.121696,3.143343,0.648448,0.000308,0.331552,0.041146,27.005816,1.557237,19.631250,16.785148,4.439362,1.770432,1.354344,5.184596,0.274920
+103.500000,16.126153,4.814327,2.273563,4.583736,1.393597,0.542934,4.806875,0.116587,3.022079,0.661489,0.000313,0.318511,0.040769,26.947564,1.571768,19.610691,16.784939,4.422150,1.770508,1.354658,5.184597,0.262840
+103.600000,16.126922,4.754849,2.112747,4.572113,1.493170,0.531860,4.669283,0.114962,2.965182,0.656849,0.000277,0.323151,0.040728,26.881118,1.573063,19.605640,16.784328,4.392449,1.770500,1.355332,5.184597,0.324083
+103.700000,16.126397,4.793074,1.939461,4.339235,1.589785,0.497649,4.915701,0.118297,3.031407,0.640975,0.000247,0.339025,0.041032,26.871260,1.559740,19.621935,16.783926,4.379251,1.770417,1.355679,5.184596,0.400754
+103.800000,16.125236,4.882287,1.910086,4.134754,1.604532,0.473873,5.259204,0.122614,3.135724,0.629977,0.000244,0.350023,0.041339,26.914858,1.547684,19.639738,16.784058,4.391510,1.770335,1.355447,5.184595,0.415383
+103.900000,16.124424,4.945872,2.007102,4.081939,1.552372,0.472059,5.459713,0.124981,3.201822,0.629362,0.000262,0.350638,0.041469,26.976101,1.544042,19.646963,16.784547,4.417264,1.770318,1.354898,5.184595,0.370526
+104.000000,16.124485,4.941396,2.166065,4.216433,1.460113,0.495037,5.376202,0.123831,3.188014,0.639789,0.000292,0.340211,0.041327,27.011363,1.550239,19.640282,16.785030,4.437383,1.770381,1.354426,5.184595,0.303822
+104.100000,16.125470,4.866223,2.281012,4.474676,1.388506,0.531053,5.014566,0.119235,3.087415,0.656003,0.000316,0.323997,0.040955,26.984517,1.564590,19.621226,16.785123,4.434416,1.770475,1.354416,5.184596,0.260482
+104.200000,16.126657,4.775807,2.216019,4.618716,1.430295,0.543191,4.686670,0.115084,2.979086,0.661817,0.000299,0.318183,0.040689,26.911879,1.574872,19.605081,16.784667,4.407805,1.770516,1.354972,5.184597,0.283687
+104.300000,16.126825,4.761263,2.017479,4.473234,1.547746,0.515955,4.752534,0.116137,2.984845,0.649542,0.000260,0.330458,0.040851,26.868113,1.567594,19.611755,16.784077,4.382911,1.770466,1.355570,5.184596,0.364775
+104.400000,16.125859,4.834073,1.906420,4.228440,1.606710,0.484084,5.083307,0.120437,3.081651,0.634638,0.000243,0.345362,0.041191,26.887012,1.553193,19.631230,16.783924,4.382281,1.770373,1.355633,5.184595,0.416870
+104.500000,16.124767,4.919008,1.943508,4.087264,1.586881,0.469940,5.382328,0.124094,3.174804,0.628279,0.000250,0.351721,0.041430,26.944074,1.544780,19.644775,16.784264,4.403072,1.770316,1.355205,5.184595,0.399611
+104.600000,16.124327,4.953529,2.079284,4.122232,1.511526,0.479942,5.461002,0.124937,3.207006,0.632986,0.000275,0.347014,0.041439,26.998692,1.545706,19.645626,16.784800,4.428689,1.770339,1.354640,5.184595,0.339191
+104.700000,16.124857,4.912969,2.234969,4.333597,1.417606,0.512217,5.229216,0.121963,3.149184,0.647500,0.000307,0.332500,0.041167,27.007299,1.556404,19.632353,16.785143,4.439536,1.770426,1.354345,5.184596,0.277425
+104.800000,16.126084,4.819619,2.277443,4.575311,1.391071,0.542234,4.826110,0.116832,3.028461,0.661153,0.000314,0.318847,0.040785,26.951766,1.571160,19.611645,16.784966,4.423717,1.770505,1.354626,5.184596,0.261487
+104.900000,16.126915,4.755567,2.124627,4.581282,1.486130,0.533547,4.664495,0.114887,2.964569,0.657609,0.000279,0.322391,0.040717,26.883465,1.573533,19.605196,16.784362,4.393876,1.770502,1.355297,5.184597,0.319243
+105.000000,16.126456,4.788670,1.945556,4.353476,1.586597,0.499477,4.896096,0.118043,3.025620,0.641828,0.000248,0.338172,0.041011,26.869918,1.560579,19.620788,16.783933,4.379219,1.770422,1.355677,5.184596,0.397847
+105.100000,16.125300,4.877402,1.907642,4.142605,1.605817,0.474646,5.242129,0.122406,3.130394,0.630322,0.000244,0.349678,0.041326,26.911402,1.548144,19.638986,16.784037,4.390263,1.770337,1.355473,5.184595,0.416541
+105.200000,16.124449,4.943992,1.999158,4.079686,1.556757,0.471456,5.455502,0.124937,3.200066,0.629077,0.000260,0.350923,0.041469,26.972818,1.543978,19.646929,16.784515,4.415765,1.770316,1.354931,5.184595,0.374085
+105.300000,16.124455,4.943818,2.157053,4.204109,1.465566,0.493157,5.389834,0.124005,3.191410,0.638945,0.000291,0.341055,0.041343,27.010755,1.549619,19.641052,16.785010,4.436755,1.770375,1.354444,5.184595,0.307381
+105.400000,16.125400,4.871682,2.278564,4.460547,1.390053,0.529294,5.038226,0.119536,3.094497,0.655203,0.000316,0.324797,0.040977,26.987668,1.563724,19.622439,16.785133,4.435347,1.770469,1.354400,5.184596,0.261382
+105.500000,16.126611,4.779486,2.225209,4.618771,1.424520,0.543776,4.695599,0.115191,2.982709,0.662055,0.000301,0.317945,0.040692,26.915684,1.574754,19.605434,16.784702,4.409534,1.770515,1.354933,5.184597,0.280271
+105.600000,16.126855,4.759193,2.027754,4.486747,1.542026,0.517949,4.738515,0.115946,2.981084,0.650470,0.000261,0.329530,0.040833,26.868612,1.568372,19.610810,16.784100,4.383708,1.770469,1.355549,5.184596,0.360221
+105.700000,16.125928,4.828935,1.908331,4.240384,1.605757,0.485478,5.063499,0.120187,3.075637,0.635284,0.000243,0.344716,0.041173,26.884413,1.553898,19.630191,16.783917,4.381605,1.770376,1.355646,5.184595,0.415912
+105.800000,16.124817,4.915223,1.938206,4.090785,1.589697,0.470116,5.370201,0.123950,3.170853,0.628345,0.000249,0.351655,0.041422,26.940375,1.545011,19.644331,16.784236,4.401589,1.770316,1.355237,5.184595,0.402097
+105.900000,16.124329,4.953552,2.070244,4.115139,1.516738,0.478707,5.464720,0.124989,3.207488,0.632424,0.000273,0.347576,0.041446,26.996325,1.545387,19.645959,16.784771,4.427470,1.770335,1.354669,5.184595,0.343018
+106.000000,16.124805,4.917123,2.227858,4.318740,1.422058,0.510112,5.249571,0.122221,3.154767,0.646554,0.000305,0.333446,0.041188,27.008453,1.555592,19.633423,16.785134,4.439606,1.770419,1.354349,5.184595,0.280085
+106.100000,16.126016,4.824976,2.280494,4.566015,1.389076,0.541379,4.846159,0.117087,3.035015,0.660748,0.000315,0.319252,0.040802,26.955800,1.570507,19.612646,16.784990,4.425210,1.770501,1.354595,5.184596,0.260430
+106.200000,16.126903,4.756715,2.136212,4.589210,1.479215,0.535090,4.661635,0.114838,2.964560,0.658300,0.000282,0.321700,0.040708,26.885970,1.573922,19.604864,16.784396,4.395356,1.770503,1.355263,5.184596,0.314573
+106.300000,16.126511,4.784636,1.952257,4.367521,1.583068,0.501313,4.877508,0.117801,3.020184,0.642689,0.000249,0.337311,0.040992,26.868826,1.561409,19.619673,16.783943,4.379325,1.770426,1.355673,5.184596,0.394675
+106.400000,16.125365,4.872490,1.905936,4.151079,1.606721,0.475518,5.224740,0.122193,3.125005,0.630714,0.000243,0.349286,0.041312,26.908066,1.548644,19.638188,16.784018,4.389125,1.770339,1.355497,5.184595,0.417342
+106.500000,16.124479,4.941777,1.991750,4.078479,1.560828,0.470997,5.449888,0.124875,3.197928,0.628858,0.000259,0.351142,0.041467,26.969449,1.543965,19.646827,16.784484,4.414286,1.770314,1.354964,5.184594,0.377422
+106.600000,16.124431,4.945822,2.148021,4.192642,1.471005,0.491379,5.401801,0.124159,3.194310,0.638146,0.000289,0.341854,0.041357,27.009834,1.549051,19.641748,16.784988,4.436039,1.770369,1.354463,5.184595,0.310974
+106.700000,16.125332,4.876947,2.275266,4.446113,1.392147,0.527447,5.061576,0.119833,3.101398,0.654366,0.000315,0.325634,0.041000,26.990512,1.562855,19.623643,16.785140,4.436153,1.770463,1.354387,5.184596,0.262588
+106.800000,16.126560,4.783500,2.233534,4.617237,1.419259,0.544132,4.706534,0.115325,2.986896,0.662189,0.000303,0.317811,0.040698,26.919597,1.574540,19.605907,16.784736,4.411262,1.770514,1.354895,5.184596,0.277207
+106.900000,16.126879,4.757592,2.038393,4.499602,1.536059,0.519896,4.726000,0.115773,2.977837,0.651372,0.000263,0.328628,0.040817,26.869443,1.569104,19.609946,16.784126,4.384634,1.770473,1.355526,5.184596,0.355548
+107.000000,16.125995,4.823917,1.910911,4.252604,1.604460,0.486929,5.043857,0.119939,3.069701,0.635958,0.000243,0.344042,0.041155,26.882065,1.554618,19.629142,16.783912,4.381056,1.770380,1.355657,5.184595,0.414629
+107.100000,16.124868,4.911282,1.933422,4.094974,1.592233,0.470388,5.357356,0.123798,3.166714,0.628456,0.000248,0.351544,0.041413,26.936770,1.545276,19.643841,16.784209,4.400170,1.770316,1.355267,5.184594,0.404346
+107.200000,16.124334,4.953263,2.061445,4.108856,1.521785,0.477579,5.467127,0.125026,3.207601,0.631910,0.000272,0.348090,0.041452,26.993857,1.545113,19.646229,16.784741,4.426227,1.770330,1.354698,5.184594,0.346770
+107.300000,16.124755,4.921004,2.220428,4.304227,1.426693,0.508033,5.268918,0.122467,3.160015,0.645621,0.000304,0.334379,0.041209,27.009379,1.554809,19.634446,16.785125,4.439583,1.770413,1.354354,5.184595,0.282879
+107.400000,16.125946,4.830384,2.282715,4.555850,1.387611,0.540372,4.866965,0.117352,3.041720,0.660277,0.000315,0.319723,0.040820,26.959788,1.569810,19.613695,16.785012,4.426645,1.770497,1.354567,5.184596,0.259675
+107.500000,16.126885,4.758261,2.147652,4.596121,1.472340,0.536522,4.660424,0.114810,2.965081,0.658936,0.000284,0.321064,0.040701,26.888751,1.574242,19.604627,16.784431,4.396905,1.770505,1.355226,5.184596,0.310008
+107.600000,16.126564,4.780789,1.959524,4.381722,1.579220,0.503194,4.859199,0.117561,3.014864,0.643572,0.000250,0.336428,0.040972,26.867974,1.562247,19.618559,16.783954,4.379533,1.770430,1.355666,5.184596,0.391257
+107.700000,16.125431,4.867487,1.904613,4.160014,1.607432,0.476454,5.206899,0.121974,3.119491,0.631138,0.000243,0.348862,0.041297,26.904840,1.549170,19.637356,16.784000,4.388037,1.770342,1.355520,5.184595,0.417956
+107.800000,16.124511,4.939364,1.984524,4.077805,1.564780,0.470608,5.443457,0.124803,3.195562,0.628670,0.000258,0.351330,0.041465,26.966065,1.543979,19.646686,16.784453,4.412798,1.770312,1.354997,5.184594,0.380696
+107.900000,16.124408,4.947618,2.138903,4.181591,1.476469,0.489650,5.412882,0.124302,3.196941,0.637369,0.000287,0.342631,0.041371,27.008775,1.548510,19.642404,16.784965,4.435259,1.770363,1.354483,5.184595,0.314628
+108.000000,16.125265,4.882147,2.271438,4.431417,1.394578,0.525537,5.084892,0.120130,3.108230,0.653502,0.000314,0.326498,0.041022,26.993238,1.561981,19.624846,16.785146,4.436884,1.770457,1.354376,5.184596,0.263984
+108.100000,16.126506,4.787747,2.241345,4.614701,1.414302,0.544346,4.718786,0.115477,2.991458,0.662259,0.000305,0.317741,0.040705,26.923639,1.574265,19.606458,16.784769,4.412991,1.770512,1.354857,5.184596,0.274354
+108.200000,16.126898,4.756312,2.049364,4.512102,1.529859,0.521831,4.714440,0.115613,2.974923,0.652267,0.000265,0.327733,0.040801,26.870547,1.569808,19.609129,16.784153,4.385650,1.770476,1.355501,5.184596,0.350776
+108.300000,16.126061,4.818918,1.914027,4.265247,1.602883,0.488447,5.023996,0.119688,3.063719,0.636661,0.000244,0.343339,0.041135,26.879890,1.555360,19.628070,16.783909,4.380581,1.770384,1.355665,5.184595,0.413091
+108.400000,16.124922,4.907167,1.928857,4.099674,1.594645,0.470726,5.343870,0.123636,3.162397,0.628598,0.000248,0.351402,0.041404,26.933166,1.545580,19.643298,16.784183,4.398756,1.770317,1.355297,5.184594,0.406498
+108.500000,16.124341,4.952772,2.052656,4.103058,1.526800,0.476511,5.468690,0.125052,3.207474,0.631422,0.000270,0.348578,0.041457,26.991269,1.544862,19.646463,16.784711,4.424931,1.770327,1.354728,5.184594,0.350544
+108.600000,16.124707,4.924762,2.212652,4.289758,1.431527,0.505943,5.287872,0.122707,3.165109,0.644682,0.000302,0.335318,0.041229,27.010140,1.554035,19.635452,16.785114,4.439479,1.770407,1.354361,5.184595,0.285821
+108.700000,16.125874,4.835943,2.284400,4.544890,1.386494,0.539239,4.888762,0.117630,3.048675,0.659750,0.000316,0.320250,0.040839,26.963823,1.569070,19.614796,16.785034,4.428060,1.770493,1.354539,5.184596,0.259106
+108.800000,16.126863,4.760080,2.159234,4.602559,1.465335,0.537920,4.660215,0.114796,2.965944,0.659554,0.000286,0.320446,0.040695,26.891744,1.574528,19.604446,16.784467,4.398518,1.770506,1.355188,5.184596,0.305432
+108.900000,16.126616,4.776983,1.967276,4.396319,1.575091,0.505144,4.840696,0.117317,3.009509,0.644487,0.000251,0.335513,0.040953,26.867227,1.563108,19.617423,16.783968,4.379796,1.770435,1.355657,5.184596,0.387633
+109.000000,16.125498,4.862327,1.903518,4.169469,1.608024,0.477458,5.188384,0.121746,3.113774,0.631593,0.000243,0.348407,0.041282,26.901586,1.549727,19.636482,16.783983,4.386950,1.770345,1.355542,5.184595,0.418459
+109.100000,16.124545,4.936756,1.977284,4.077529,1.568722,0.470267,5.436294,0.124722,3.192979,0.628501,0.000256,0.351499,0.041462,26.962559,1.544014,19.646512,16.784422,4.411264,1.770311,1.355030,5.184594,0.383994
+109.200000,16.124388,4.949283,2.129554,4.170666,1.482042,0.487928,5.423493,0.124439,3.199419,0.636594,0.000285,0.343406,0.041384,27.007552,1.547978,19.643043,16.784941,4.434408,1.770358,1.354505,5.184595,0.318404
+109.300000,16.125197,4.887396,2.267169,4.416275,1.397285,0.523552,5.108616,0.120431,3.115136,0.652605,0.000313,0.327395,0.041045,26.995896,1.561088,19.626070,16.785150,4.437570,1.770451,1.354365,5.184595,0.265547
+109.400000,16.126448,4.792219,2.248986,4.611514,1.409430,0.544478,4.732086,0.115642,2.996334,0.662292,0.000307,0.317708,0.040713,26.927801,1.573949,19.607064,16.784802,4.414749,1.770511,1.354819,5.184596,0.271584
+109.500000,16.126917,4.755135,2.060766,4.524853,1.523370,0.523827,4.702860,0.115451,2.972042,0.653187,0.000267,0.326813,0.040785,26.871711,1.570526,19.608305,16.784181,4.386710,1.770480,1.355474,5.184596,0.345864
+109.600000,16.126129,4.813809,1.917377,4.278416,1.601185,0.490034,5.003510,0.119427,3.057541,0.637405,0.000244,0.342595,0.041117,26.877615,1.556142,19.626947,16.783906,4.380100,1.770389,1.355674,5.184595,0.411439
+109.700000,16.124978,4.902856,1.924405,4.104860,1.596993,0.471124,5.329517,0.123465,3.157810,0.628766,0.000247,0.351234,0.041394,26.929445,1.545889,19.642744,16.784155,4.397308,1.770318,1.355328,5.184594,0.408603
+109.800000,16.124351,4.952084,2.043778,4.097600,1.531839,0.475483,5.469447,0.125069,3.207106,0.630951,0.000268,0.349049,0.041461,26.988489,1.544631,19.646669,16.784680,4.423568,1.770323,1.354759,5.184594,0.354383
+109.900000,16.124661,4.928377,2.204535,4.275384,1.436557,0.503849,5.306256,0.122940,3.170004,0.643743,0.000300,0.336257,0.041249,27.010655,1.553273,19.636437,16.785100,4.439279,1.770400,1.354370,5.184595,0.288908
+110.000000,17.623000,5.080046,1.902460,4.178674,1.608594,0.478432,5.174879,0.121577,3.109613,0.631956,0.000242,0.348044,0.041275,27.238510,1.550692,19.638070,16.785980,4.387333,1.770884,1.355975,5.184477,0.418946
+110.100000,17.621794,5.159622,1.970757,4.078122,1.572259,0.470054,5.432901,0.124684,3.191597,0.628315,0.000255,0.351685,0.041466,27.299267,1.544524,19.648805,16.786572,4.411252,1.770863,1.355486,5.183374,0.386984
+110.200000,17.621368,5.178770,2.121169,4.161800,1.487016,0.486493,5.435856,0.124593,3.202522,0.635873,0.000283,0.344127,0.041403,27.346288,1.547998,19.646203,16.787262,4.435003,1.770925,1.354964,5.182277,0.321815
+110.300000,17.621954,5.120713,2.263205,4.403495,1.399800,0.521853,5.132705,0.120734,3.122198,0.651763,0.000313,0.328237,0.041073,27.338096,1.560795,19.629916,16.787660,4.439531,1.771035,1.354810,5.181186,0.266996
+110.400000,17.623081,5.022677,2.255700,4.609194,1.405136,0.544649,4.747097,0.115828,3.001704,0.662270,0.000308,0.317730,0.040728,27.271435,1.574164,19.610552,16.787501,4.417689,1.771116,1.355252,5.180100,0.269164
+110.500000,17.623506,4.977046,2.071204,4.537219,1.517388,0.525739,4.695112,0.115337,2.970360,0.653992,0.000269,0.326008,0.040777,27.212684,1.571698,19.610659,16.787038,4.389045,1.771106,1.355932,5.179020,0.341408
+110.600000,17.622620,5.030585,1.920490,4.291475,1.599600,0.491599,4.987212,0.119216,3.052680,0.638062,0.000244,0.341938,0.041106,27.215421,1.557404,19.629168,16.786895,4.381022,1.771033,1.356179,5.177944,0.409910
+110.700000,17.621258,5.122165,1.920159,4.110515,1.599225,0.471581,5.318973,0.123336,3.154421,0.628893,0.000246,0.351107,0.041391,27.265893,1.546734,19.645642,16.787283,4.397325,1.770976,1.355869,5.176874,0.410617
+110.800000,17.620365,5.177947,2.035456,4.093369,1.536537,0.474621,5.472938,0.125115,3.207629,0.630487,0.000267,0.349513,0.041473,27.325843,1.544976,19.650449,16.787964,4.423667,1.770994,1.355316,5.175810,0.358007
+110.900000,17.620423,5.160255,2.196946,4.262782,1.441239,0.501989,5.326158,0.123188,3.175429,0.642844,0.000299,0.337156,0.041274,27.351113,1.553140,19.641102,16.788560,4.440467,1.771085,1.354920,5.174752,0.291816
+111.000000,17.621386,5.074512,2.286226,4.523167,1.385250,0.536892,4.934503,0.118210,3.063116,0.658602,0.000317,0.321398,0.040884,27.311296,1.568174,19.620888,16.788702,4.432001,1.771191,1.355046,5.173700,0.258524
+111.100000,17.622354,4.988865,2.181116,4.613763,1.451969,0.540479,4.665300,0.114837,2.969394,0.660615,0.000291,0.319385,0.040693,27.237778,1.575551,19.608346,16.788324,4.403052,1.771231,1.355688,5.172653,0.296916
+111.200000,17.622137,4.991769,1.983403,4.425561,1.566421,0.509093,4.808080,0.116881,3.000262,0.646277,0.000254,0.333723,0.040921,27.206083,1.565398,19.619481,16.787942,4.381831,1.771183,1.356227,5.171610,0.380176
+111.300000,17.620890,5.073993,1.902331,4.189833,1.608694,0.479660,5.153767,0.121314,3.103149,0.632540,0.000242,0.347460,0.041258,27.235336,1.551505,19.639096,16.788054,4.386285,1.771106,1.356190,5.170572,0.418975
+111.400000,17.619665,5.155833,1.963665,4.079242,1.576087,0.469879,5.422718,0.124565,3.188140,0.628244,0.000254,0.351756,0.041461,27.295551,1.544795,19.650633,16.788618,4.409592,1.771079,1.355719,5.169540,0.390248
+111.500000,17.619191,5.179487,2.111230,4.151489,1.492884,0.484823,5.444047,0.124701,3.204258,0.635144,0.000281,0.344856,0.041415,27.344704,1.547672,19.648896,16.789305,4.433920,1.771134,1.355190,5.168514,0.325886
+111.600000,17.619731,5.125664,2.257508,4.387254,1.403404,0.519660,5.156374,0.121034,3.128954,0.650801,0.000311,0.329199,0.041098,27.340570,1.560033,19.633289,16.789721,4.440001,1.771242,1.355007,5.167494,0.269088
+111.700000,17.620867,5.027734,2.262245,4.603382,1.400927,0.544417,4.763438,0.116033,3.007450,0.662167,0.000310,0.317833,0.040740,27.276083,1.573865,19.613464,16.789586,4.419450,1.771325,1.355419,5.166479,0.266828
+111.800000,17.621377,4.976523,2.083675,4.549242,1.510186,0.527733,4.685161,0.115195,2.968110,0.654933,0.000272,0.325067,0.040763,27.214648,1.572535,19.612038,16.789115,4.390307,1.771319,1.356109,5.165468,0.336140
+111.900000,17.620564,5.025134,1.925383,4.305987,1.597088,0.493398,4.965148,0.118933,3.046097,0.638933,0.000245,0.341067,0.041086,27.213643,1.558442,19.630047,16.788933,4.380676,1.771246,1.356394,5.164462,0.407529
+112.000000,17.619210,5.116806,1.916441,4.117330,1.601175,0.472190,5.301682,0.123126,3.149003,0.629184,0.000245,0.350816,0.041381,27.262262,1.547322,19.647029,16.789285,4.395823,1.771184,1.356113,5.163461,0.412385
+112.100000,17.618282,5.176124,2.026544,4.089184,1.541543,0.473743,5.470499,0.125092,3.206336,0.630111,0.000265,0.349889,0.041475,27.322864,1.544995,19.652624,16.789950,4.422085,1.771194,1.355565,5.162466,0.361913
+112.200000,17.618288,5.163166,2.187883,4.248397,1.446808,0.499852,5.342762,0.123399,3.179722,0.641917,0.000297,0.338083,0.041294,27.351377,1.552580,19.644115,16.790554,4.439979,1.771280,1.355152,5.161477,0.295310
+112.300000,17.619223,5.080265,2.285740,4.509509,1.385529,0.535309,4.958336,0.118513,3.070484,0.657910,0.000317,0.322090,0.040907,27.315396,1.567489,19.624199,16.790722,4.433171,1.771386,1.355243,5.160493,0.258731
+112.400000,17.620239,4.991748,2.192498,4.617416,1.444951,0.541583,4.669054,0.114874,2.971548,0.661123,0.000294,0.318877,0.040691,27.241673,1.575844,19.610473,16.790357,4.404764,1.771430,1.355870,5.159514,0.292551
+112.500000,17.620116,4.988310,1.993098,4.440867,1.561157,0.511228,4.789438,0.116632,2.994997,0.647309,0.000256,0.332691,0.040901,27.206117,1.566491,19.620373,16.789947,4.382279,1.771383,1.356438,5.158538,0.375746
+112.600000,17.618910,5.068017,1.902630,4.201222,1.608575,0.480930,5.132376,0.121047,3.096614,0.633155,0.000242,0.346845,0.041240,27.232389,1.552370,19.640106,16.790018,4.385204,1.771305,1.356438,5.157568,0.418795
+112.700000,17.617668,5.151940,1.956914,4.080890,1.579715,0.469781,5.411638,0.124435,3.184439,0.628217,0.000253,0.351783,0.041456,27.291926,1.545125,19.652338,16.790555,4.407845,1.771271,1.355985,5.156602,0.393371
+112.800000,17.617147,5.179987,2.101425,4.141816,1.498641,0.483239,5.450920,0.124792,3.205621,0.634461,0.000280,0.345539,0.041426,27.343041,1.547413,19.651437,16.791238,4.432685,1.771319,1.355450,5.155643,0.329934
+112.900000,17.617640,5.130448,2.251466,4.371167,1.407224,0.517466,5.179198,0.121323,3.135418,0.649846,0.000310,0.330154,0.041122,27.342899,1.559318,19.636529,16.791674,4.440281,1.771424,1.355238,5.154689,0.271310
+113.000000,17.618780,5.032856,2.268175,4.596920,1.397100,0.544074,4.780183,0.116243,3.013264,0.662021,0.000311,0.317979,0.040753,27.280728,1.573562,19.616310,16.791564,4.421054,1.771509,1.355619,5.153740,0.264725
+113.100000,17.619372,4.976272,2.096091,4.560741,1.502958,0.529679,4.675911,0.115061,2.966095,0.655856,0.000274,0.324144,0.040749,27.216759,1.573366,19.613365,16.791086,4.391490,1.771506,1.356315,5.152795,0.330951
+113.200000,17.618635,5.019841,1.930532,4.320537,1.594432,0.495215,4.943154,0.118649,3.039541,0.639819,0.000246,0.340181,0.041065,27.211987,1.559513,19.630824,16.790866,4.380273,1.771433,1.356638,5.151853,0.405037
+113.300000,17.617290,5.111446,1.912935,4.124402,1.603020,0.472836,5.284060,0.122913,3.143487,0.629507,0.000245,0.350493,0.041366,27.258682,1.547953,19.648295,16.791182,4.394246,1.771366,1.356386,5.150917,0.414045
+113.400000,17.616327,5.174192,2.017812,4.085437,1.546421,0.472927,5.467330,0.125060,3.204846,0.629767,0.000264,0.350233,0.041477,27.319840,1.545060,19.654669,16.791831,4.420395,1.771369,1.355845,5.149986,0.365767
+113.500000,17.616282,5.165895,2.178823,4.234508,1.452350,0.497777,5.358340,0.123597,3.183711,0.641020,0.000295,0.338980,0.041312,27.351469,1.552075,19.646987,16.792442,4.439336,1.771450,1.355414,5.149061,0.298827
+113.600000,17.617187,5.085889,2.284736,4.495778,1.386146,0.533687,4.981712,0.118810,3.077654,0.657204,0.000317,0.322796,0.040930,27.319273,1.566835,19.627394,16.792636,4.434153,1.771555,1.355471,5.148141,0.259118
+113.700000,17.618246,4.994861,2.203169,4.619931,1.438325,0.542523,4.674062,0.114928,2.974050,0.661561,0.000296,0.318439,0.040690,27.245580,1.576094,19.612583,16.792286,4.406356,1.771602,1.356081,5.147225,0.288505
+113.800000,17.618214,4.985298,2.003018,4.455574,1.555730,0.513315,4.772026,0.116398,2.990141,0.648322,0.000257,0.331678,0.040882,27.206380,1.567569,19.621233,16.791852,4.382729,1.771558,1.356674,5.146313,0.371252
+113.900000,17.617053,5.062203,1.903561,4.212893,1.608131,0.482255,5.111065,0.120781,3.090127,0.633802,0.000242,0.346198,0.041223,27.229638,1.553274,19.641005,16.791883,4.384147,1.771477,1.356710,5.145405,0.418308
+114.000000,17.615797,5.147886,1.950711,4.083299,1.583036,0.469793,5.399634,0.124293,3.180496,0.628244,0.000252,0.351756,0.041449,27.288339,1.545516,19.653896,16.792393,4.406067,1.771437,1.356275,5.144502,0.396253
+114.100000,17.615231,5.180141,2.091877,4.133103,1.504216,0.481782,5.456152,0.124862,3.206523,0.633838,0.000278,0.346162,0.041436,27.341193,1.547226,19.653813,16.793070,4.431323,1.771478,1.355736,5.143605,0.333907
+114.200000,17.615675,5.134903,2.244967,4.355464,1.411321,0.515292,5.200736,0.121596,3.141444,0.648905,0.000309,0.331095,0.041145,27.344882,1.558659,19.639618,16.793523,4.440351,1.771579,1.355496,5.142712,0.273712
+114.300000,17.616814,5.038092,2.273009,4.589211,1.393968,0.543516,4.798044,0.116469,3.019326,0.661786,0.000313,0.318214,0.040768,27.285296,1.573214,19.619136,16.793439,4.422506,1.771666,1.355845,5.141825,0.263024
+114.400000,17.617481,4.976570,2.108305,4.570885,1.495793,0.531476,4.668767,0.114955,2.964751,0.656710,0.000276,0.323290,0.040737,27.219181,1.574130,19.614723,16.792960,4.392684,1.771667,1.356544,5.140941,0.325903
+114.500000,17.616821,5.014929,1.936362,4.334970,1.591405,0.497048,4.921976,0.118375,3.033272,0.640717,0.000247,0.339283,0.041045,27.210692,1.560595,19.631535,16.792703,4.379955,1.771594,1.356902,5.140060,0.402233
+114.600000,17.615490,5.106073,1.910159,4.132069,1.604481,0.473577,5.265996,0.122692,3.137874,0.629874,0.000244,0.350126,0.041353,27.255334,1.548634,19.649432,16.792984,4.392715,1.771523,1.356680,5.139185,0.415360
+114.700000,17.614495,5.171960,2.009596,4.082690,1.550987,0.472252,5.462701,0.125010,3.202961,0.629488,0.000262,0.350512,0.041478,27.316826,1.545194,19.656555,16.793616,4.418658,1.771519,1.356146,5.138314,0.369417
+114.800000,17.614400,5.168218,2.169741,4.221487,1.457882,0.495806,5.372138,0.123773,3.187168,0.640174,0.000293,0.339826,0.041330,27.351335,1.551641,19.649690,16.794233,4.438537,1.771594,1.355698,5.137448,0.302377
+114.900000,17.615271,5.091343,2.282886,4.481693,1.387308,0.531968,5.004793,0.119104,3.084645,0.656461,0.000316,0.323539,0.040952,27.322962,1.566192,19.630493,16.794452,4.434954,1.771698,1.355722,5.136588,0.259806
+115.000000,17.616367,4.998280,2.213081,4.621071,1.432143,0.543267,4.680700,0.115003,2.977013,0.661914,0.000298,0.318086,0.040692,27.249657,1.576280,19.614705,16.794118,4.407878,1.771748,1.356311,5.135731,0.284776
+115.100000,17.616423,4.982712,2.013170,4.469674,1.550135,0.515353,4.755817,0.116178,2.985685,0.649314,0.000259,0.330686,0.040864,27.206981,1.568625,19.622068,16.793663,4.383215,1.771706,1.356927,5.134878,0.366695
+115.200000,17.615309,5.056564,1.904990,4.224669,1.607431,0.483610,5.089994,0.120516,3.083730,0.634468,0.000242,0.345532,0.041205,27.227179,1.554202,19.641814,16.793656,4.383135,1.771623,1.356999,5.134029,0.417578
+115.300000,17.614041,5.143763,1.944994,4.086245,1.586086,0.469885,5.387053,0.124144,3.176408,0.628312,0.000251,0.351688,0.041442,27.284926,1.545949,19.655331,16.794139,4.404290,1.771577,1.356583,5.133184,0.398920
+115.400000,17.613432,5.180030,2.082646,4.125233,1.509577,0.480442,5.460037,0.124916,3.207053,0.633270,0.000276,0.346730,0.041445,27.339320,1.547099,19.656037,16.794810,4.429884,1.771612,1.356039,5.132345,0.337776
+115.500000,17.613829,5.139070,2.238230,4.340233,1.415557,0.513161,5.221065,0.121853,3.147078,0.647987,0.000307,0.332013,0.041167,27.346692,1.558051,19.642564,16.795279,4.440269,1.771709,1.355773,5.131510,0.276213
+115.600000,17.614962,5.043303,2.277072,4.580884,1.391322,0.542838,4.816209,0.116699,3.025411,0.661501,0.000314,0.318499,0.040784,27.289817,1.572851,19.621900,16.795221,4.423819,1.771797,1.356089,5.130680,0.261606
+115.700000,17.615700,4.977158,2.120217,4.580189,1.488756,0.533175,4.662739,0.114863,2.963754,0.657518,0.000279,0.322482,0.040726,27.221787,1.574854,19.616067,16.794742,4.393831,1.771801,1.356788,5.129853,0.321027
+115.800000,17.615116,5.010292,1.942422,4.349148,1.588242,0.498867,4.901439,0.118108,3.027210,0.641613,0.000248,0.338387,0.041025,27.209638,1.561678,19.632186,16.794451,4.379645,1.771729,1.357180,5.129030,0.399337
+115.900000,17.613801,5.100789,1.907755,4.139926,1.605747,0.474353,5.247946,0.122470,3.132271,0.630270,0.000244,0.349730,0.041342,27.252182,1.549340,19.650472,16.794697,4.391194,1.771653,1.356986,5.128210,0.416498
+116.000000,17.612777,5.169615,2.001781,4.080552,1.555309,0.471666,5.457314,0.124950,3.200883,0.629252,0.000261,0.350748,0.041478,27.313888,1.545372,19.658313,16.795312,4.416886,1.771643,1.356460,5.127396,0.372910
+116.100000,17.612632,5.170278,2.160810,4.209219,1.463294,0.493935,5.384620,0.123932,3.190245,0.639374,0.000291,0.340626,0.041346,27.351083,1.551264,19.652244,16.795935,4.437628,1.771713,1.355998,5.126586,0.305896
+116.200000,17.613469,5.096628,2.280553,4.467612,1.388783,0.530220,5.027350,0.119390,3.091421,0.655709,0.000316,0.324291,0.040975,27.326494,1.565571,19.633483,16.796177,4.435606,1.771815,1.355988,5.125781,0.260664
+116.300000,17.614595,5.001852,2.222571,4.621499,1.426185,0.543914,4.688149,0.115090,2.980210,0.662221,0.000300,0.317779,0.040695,27.253822,1.576431,19.616800,16.795862,4.409326,1.771868,1.356556,5.124980,0.281245
+116.400000,17.614739,4.980334,2.023477,4.483590,1.544415,0.517390,4.740046,0.115963,2.981383,0.650305,0.000261,0.329695,0.040845,27.207722,1.569680,19.622841,16.795388,4.383680,1.771829,1.357192,5.124182,0.362108
+116.500000,17.613674,5.050988,1.906661,4.236619,1.606606,0.484995,5.068850,0.120249,3.077312,0.635152,0.000243,0.344848,0.041187,27.224812,1.555153,19.642524,16.795342,4.382099,1.771743,1.357299,5.123388,0.416733
+116.600000,17.612396,5.139578,1.939464,4.089520,1.589026,0.470024,5.374050,0.123989,3.172204,0.628402,0.000250,0.351598,0.041435,27.281535,1.546410,19.656659,16.795798,4.402464,1.771692,1.356902,5.122597,0.401510
+116.700000,17.611744,5.179781,2.073524,4.117814,1.514847,0.479163,5.463167,0.124961,3.207374,0.632730,0.000274,0.347270,0.041453,27.337369,1.547006,19.658146,16.796463,4.428357,1.771720,1.356355,5.121812,0.341629
+116.800000,17.612093,5.143082,2.231306,4.325278,1.419898,0.511055,5.240669,0.122101,3.152472,0.647081,0.000306,0.332919,0.041188,27.348325,1.557475,19.645392,16.796948,4.440058,1.771814,1.356063,5.121031,0.278797
+116.900000,17.613216,5.048545,2.280519,4.571984,1.389071,0.542055,4.834808,0.116934,3.031566,0.661171,0.000315,0.318829,0.040800,27.294255,1.572470,19.624609,16.796916,4.425017,1.771902,1.356347,5.120255,0.260410
+117.000000,17.614020,4.978084,2.131991,4.588666,1.481742,0.534787,4.658015,0.114788,2.963177,0.658286,0.000281,0.321714,0.040716,27.224563,1.575535,19.617403,16.796439,4.394967,1.771910,1.357043,5.119481,0.316267
+117.100000,17.613515,5.005859,1.948970,4.363461,1.584805,0.500723,4.881157,0.117843,3.021249,0.642527,0.000249,0.337473,0.041006,27.208749,1.562778,19.632755,16.796117,4.379363,1.771838,1.357467,5.118711,0.396226
+117.200000,17.612219,5.095436,1.905752,4.148264,1.606806,0.475198,5.229399,0.122243,3.126543,0.630682,0.000243,0.349318,0.041326,27.249092,1.550080,19.651394,16.796327,4.389662,1.771759,1.357302,5.117945,0.417442
+117.300000,17.611166,5.167072,1.994146,4.078969,1.559510,0.471154,5.451051,0.124879,3.198558,0.629049,0.000259,0.350951,0.041477,27.310873,1.545585,19.659952,16.796925,4.415048,1.771742,1.356785,5.117183,0.376343
+117.400000,17.610973,5.172105,2.151791,4.197427,1.468736,0.492117,5.396087,0.124079,3.193016,0.638600,0.000290,0.341400,0.041361,27.350632,1.550924,19.654677,16.797551,4.436599,1.771806,1.356308,5.116425,0.309474
+117.500000,17.611772,5.101778,2.277605,4.453365,1.390654,0.528415,5.049582,0.119673,3.098032,0.654932,0.000315,0.325068,0.040997,27.329797,1.564959,19.636381,16.797817,4.436106,1.771907,1.356266,5.115673,0.261741
+117.600000,17.612924,5.005683,2.231134,4.620499,1.420783,0.544345,4.697247,0.115199,2.983852,0.662433,0.000302,0.317567,0.040700,27.258025,1.576508,19.618913,16.797521,4.410692,1.771962,1.356811,5.114923,0.278084
+117.700000,17.613151,4.978499,2.033939,4.496562,1.538566,0.519338,4.726083,0.115772,2.977673,0.651255,0.000263,0.328745,0.040828,27.208799,1.570681,19.623631,16.797032,4.384211,1.771926,1.357463,5.114177,0.357495
+117.800000,17.612139,5.045669,1.909046,4.248686,1.605410,0.486423,5.048193,0.119988,3.071071,0.635861,0.000243,0.344139,0.041169,27.222770,1.556117,19.643162,16.796950,4.381167,1.771839,1.357604,5.113433,0.415544
+117.900000,17.610854,5.135286,1.934646,4.093539,1.591580,0.470276,5.360310,0.123825,3.167815,0.628547,0.000249,0.351453,0.041426,27.278334,1.546912,19.657866,16.797379,4.400691,1.771782,1.357227,5.112694,0.403774
+118.000000,17.610162,5.179179,2.064824,4.111463,1.519847,0.478031,5.464624,0.124985,3.207233,0.632258,0.000273,0.347742,0.041459,27.335347,1.546976,19.660098,16.798036,4.426773,1.771804,1.356677,5.111959,0.345329
+118.100000,17.610462,5.146741,2.224088,4.310852,1.424406,0.508995,5.258882,0.122332,3.157416,0.646200,0.000304,0.333800,0.041209,27.349711,1.556945,19.648079,16.798535,4.439699,1.771893,1.356363,5.111229,0.281506
+118.200000,17.611571,5.053812,2.283099,4.562235,1.387375,0.541119,4.854032,0.117178,3.037835,0.660776,0.000315,0.319224,0.040818,27.298662,1.572051,19.627284,16.798529,4.426105,1.771982,1.356612,5.110503,0.259526
+118.300000,17.612436,4.979371,2.143546,4.596190,1.474819,0.536290,4.654695,0.114732,2.963044,0.659001,0.000283,0.320999,0.040708,27.227593,1.576158,19.618749,16.798057,4.396108,1.771994,1.357303,5.109779,0.311635
+118.400000,17.612011,5.001675,1.955843,4.377611,1.581178,0.502580,4.861431,0.117584,3.015477,0.643444,0.000250,0.336556,0.040987,27.208115,1.563876,19.633267,16.797705,4.379124,1.771923,1.357758,5.109059,0.392979
+118.500000,17.610735,5.090145,1.904133,4.156833,1.607665,0.476083,5.210803,0.122014,3.120806,0.631126,0.000243,0.348874,0.041312,27.246197,1.550840,19.652224,16.797881,4.388162,1.771840,1.357622,5.108342,0.418202
+118.600000,17.609656,5.164401,1.986869,4.077962,1.563497,0.470725,5.444049,0.124800,3.196039,0.628886,0.000258,0.351114,0.041476,27.307932,1.545832,19.661474,16.798460,4.413195,1.771817,1.357114,5.107629,0.379635
+118.700000,17.609414,5.173697,2.142873,4.186260,1.474090,0.490383,5.406435,0.124211,3.195465,0.637863,0.000288,0.342137,0.041375,27.350092,1.550624,19.656980,16.799090,4.435486,1.771875,1.356624,5.106920,0.313038
+118.800000,17.610175,5.106800,2.274277,4.439101,1.392768,0.526586,5.071434,0.119950,3.104486,0.654147,0.000315,0.325853,0.041020,27.333009,1.564357,19.639188,16.799379,4.436501,1.771974,1.356550,5.106216,0.262955
+118.900000,17.611349,5.009618,2.239331,4.618959,1.415588,0.544696,4.706940,0.115317,2.987654,0.662609,0.000304,0.317391,0.040705,27.262305,1.576556,19.620989,16.799104,4.412005,1.772032,1.357070,5.105515,0.275081
+119.000000,17.611658,4.976817,2.044488,4.509389,1.532625,0.521284,4.712426,0.115583,2.974073,0.652201,0.000264,0.327799,0.040812,27.209984,1.571676,19.624363,16.798601,4.384725,1.771998,1.357737,5.104817,0.352887
+119.100000,17.610699,5.040414,1.911562,4.260847,1.604146,0.487863,5.027541,0.119725,3.064831,0.636572,0.000243,0.343428,0.041152,27.220793,1.557095,19.643711,16.798482,4.380213,1.771910,1.357912,5.104121,0.414292
+119.200000,17.609408,5.130990,1.929867,4.097687,1.594106,0.470545,5.346520,0.123659,3.163412,0.628698,0.000248,0.351302,0.041418,27.275115,1.547431,19.658974,16.798883,4.398875,1.771848,1.357555,5.103430,0.406027
+119.300000,17.608677,5.178498,2.056199,4.105387,1.524778,0.476937,5.465755,0.125005,3.207007,0.631800,0.000271,0.348200,0.041465,27.333273,1.546960,19.661957,16.799533,4.425138,1.771864,1.357004,5.102742,0.349023
+119.400000,17.608929,5.150243,2.216842,4.296824,1.428922,0.506984,5.276426,0.122554,3.162155,0.645339,0.000303,0.334661,0.041229,27.350950,1.556441,19.650658,16.800045,4.439253,1.771949,1.356666,5.102059,0.284236
+119.500000,17.610023,5.058937,2.285150,4.552400,1.386021,0.540138,4.872991,0.117419,3.043960,0.660361,0.000316,0.319639,0.040835,27.302853,1.571638,19.629873,16.800065,4.427065,1.772038,1.356883,5.101380,0.258829
+119.600000,17.610945,4.980846,2.154526,4.602796,1.468191,0.537668,4.652500,0.114691,2.963234,0.659658,0.000285,0.320342,0.040701,27.230615,1.576728,19.620090,16.799599,4.397184,1.772053,1.357566,5.100703,0.307284
+119.700000,17.610596,4.997849,1.962865,4.391275,1.577449,0.504393,4.842800,0.117339,3.010054,0.644339,0.000251,0.335661,0.040968,27.207647,1.564945,19.633757,16.799219,4.378919,1.771983,1.358050,5.100029,0.389686
+119.800000,17.609343,5.084999,1.902949,4.165517,1.608301,0.476997,5.192515,0.121788,3.115177,0.631583,0.000243,0.348417,0.041298,27.243455,1.551607,19.652980,16.799362,4.386716,1.771897,1.357942,5.099358,0.418750
+119.900000,17.608240,5.161643,1.980060,4.077524,1.567210,0.470383,5.436521,0.124713,3.193395,0.628761,0.000257,0.351239,0.041474,27.305032,1.546107,19.662889,16.799922,4.411357,1.771868,1.357444,5.098691,0.382731
+120.000000,17.587500,5.009080,2.245170,4.617750,1.411870,0.544935,4.688840,0.115055,2.982780,0.663732,0.000306,0.316268,0.040708,27.326600,1.582410,19.654900,16.831400,4.395930,1.765630,1.663898,4.968440,0.272960
+120.100000,17.588079,4.960898,2.181463,4.588769,1.451274,0.537497,4.527497,0.112253,2.937955,0.676412,0.000298,0.303588,0.041684,27.333069,1.807736,19.708564,16.831532,4.357221,1.765584,1.657201,4.968024,0.297263
+120.200000,17.587917,4.959946,2.159617,4.531902,1.464560,0.529865,4.432163,0.110970,2.906325,0.678471,0.000293,0.301529,0.041602,27.373813,1.817789,19.728728,16.832783,4.316211,1.765406,1.653628,4.967616,0.305823
+120.300000,17.587497,4.976431,2.142142,4.481782,1.475076,0.523287,4.372775,0.110200,2.885565,0.679162,0.000288,0.300838,0.041508,27.408350,1.816866,19.732037,16.834259,4.278307,1.765104,1.650317,4.967216,0.312782
+120.400000,17.587040,4.996764,2.131125,4.441702,1.481639,0.518213,4.336633,0.109733,2.872841,0.679496,0.000286,0.300504,0.041441,27.437667,1.814923,19.732426,16.835726,4.244693,1.764688,1.647096,4.966822,0.317236
+120.500000,17.586643,5.014439,2.127252,4.415460,1.483927,0.515085,4.308908,0.109372,2.863366,0.679962,0.000284,0.300038,0.041384,27.462125,1.813021,19.732181,16.837147,4.215295,1.764176,1.643946,4.966434,0.318821
+120.600000,17.586341,5.026706,2.126418,4.401967,1.484422,0.513545,4.281402,0.109009,2.854092,0.680607,0.000284,0.299393,0.041330,27.481051,1.811417,19.731466,16.838507,4.189353,1.763578,1.640872,4.966053,0.319160
+120.700000,17.586122,5.034322,2.123221,4.393951,1.486333,0.512485,4.257162,0.108692,2.845652,0.681065,0.000283,0.298935,0.041284,27.494886,1.809796,19.730721,16.839801,4.166272,1.762907,1.637879,4.965678,0.320446
+120.800000,17.585943,5.040244,2.116156,4.383596,1.490524,0.510952,4.244561,0.108534,2.840808,0.680987,0.000281,0.299013,0.041258,27.505957,1.807666,19.730643,16.841040,4.146133,1.762172,1.634950,4.965309,0.323320
+120.900000,17.585767,5.046794,2.109025,4.369541,1.494721,0.509005,4.246188,0.108569,2.840769,0.680460,0.000280,0.299540,0.041251,27.516947,1.804934,19.731459,16.842250,4.129379,1.761384,1.632060,4.964947,0.326254
+121.000000,17.585598,5.053622,2.106632,4.357371,1.496109,0.507523,4.254355,0.108688,2.843296,0.679955,0.000279,0.300045,0.041250,27.528712,1.802059,19.732622,16.843449,4.116047,1.760554,1.629188,4.964590,0.327259
+121.100000,17.585460,5.058503,2.109516,4.352971,1.494401,0.507189,4.257955,0.108741,2.844654,0.679854,0.000280,0.300146,0.041240,27.539868,1.799589,19.733349,16.844638,4.105391,1.759692,1.626340,4.964239,0.326083
+121.200000,17.585373,5.060006,2.113276,4.355960,1.492192,0.507727,4.252926,0.108677,2.843132,0.680081,0.000281,0.299919,0.041220,27.548556,1.797625,19.733390,16.845798,4.096329,1.758805,1.623537,4.963894,0.324532
+121.300000,17.585321,5.059274,2.112862,4.359537,1.492453,0.508106,4.245911,0.108589,2.840602,0.680181,0.000280,0.299819,0.041201,27.554613,1.795726,19.733260,16.846917,4.088244,1.757899,1.620788,4.963555,0.324684
+121.400000,17.585264,5.059122,2.107711,4.357036,1.495497,0.507553,4.247175,0.108618,2.840517,0.679793,0.000279,0.300207,0.041197,27.559991,1.793365,19.733712,16.848002,4.081348,1.756975,1.618083,4.963221,0.326793
+121.500000,17.585179,5.061315,2.102415,4.348736,1.498597,0.506346,4.259504,0.108796,2.844182,0.679043,0.000278,0.300957,0.041206,27.566899,1.790489,19.734931,16.849077,4.076221,1.756039,1.615397,4.962893,0.328988
+121.600000,17.585079,5.064826,2.101881,4.341419,1.498891,0.505502,4.275009,0.109012,2.849278,0.678416,0.000278,0.301584,0.041216,27.575614,1.787588,19.736325,16.850154,4.072977,1.755098,1.612716,4.962570,0.329228
+121.700000,17.584997,5.066995,2.106251,4.341226,1.496318,0.505712,4.283085,0.109124,2.852219,0.678263,0.000279,0.301737,0.041213,27.584297,1.785183,19.737138,16.851229,4.070946,1.754156,1.610053,4.962253,0.327431
+121.800000,17.584954,5.066307,2.110792,4.347411,1.493655,0.506645,4.280930,0.109098,2.851705,0.678452,0.000280,0.301548,0.041198,27.590907,1.783310,19.737205,16.852280,4.069180,1.753215,1.607427,4.961941,0.325553
+121.900000,17.584934,5.063986,2.110555,4.352891,1.493813,0.507245,4.276438,0.109044,2.850033,0.678492,0.000280,0.301508,0.041184,27.595313,1.781482,19.737117,16.853294,4.067263,1.752276,1.604852,4.961635,0.325632
+122.000000,17.584901,5.062851,2.105441,4.351286,1.496830,0.506794,4.280312,0.109107,2.850821,0.678033,0.000279,0.301967,0.041184,27.599518,1.779173,19.737637,16.854281,4.065620,1.751339,1.602314,4.961333,0.327729
+122.100000,17.584831,5.064461,2.100444,4.343588,1.499750,0.505671,4.294885,0.109314,2.855242,0.677236,0.000278,0.302764,0.041196,27.605631,1.776370,19.738900,16.855260,4.064983,1.750405,1.599790,4.961037,0.329806
+122.200000,17.584743,5.067506,2.100467,4.337106,1.499718,0.504949,4.311664,0.109546,2.860782,0.676606,0.000278,0.303394,0.041208,27.613724,1.773588,19.740272,16.856247,4.065543,1.749478,1.597268,4.960746,0.329815
+122.300000,17.584674,5.069166,2.105348,4.337971,1.496847,0.505303,4.319987,0.109660,2.863829,0.676480,0.000279,0.303520,0.041206,27.621786,1.771338,19.741008,16.857232,4.066680,1.748562,1.594761,4.960460,0.327805
+122.400000,17.584642,5.067965,2.110076,4.345045,1.494077,0.506345,4.317604,0.109631,2.863255,0.676692,0.000280,0.303308,0.041191,27.627748,1.769620,19.740988,16.858194,4.067516,1.747657,1.592291,4.960179,0.325847
+122.500000,17.584632,5.065270,2.109695,4.350897,1.494320,0.506978,4.313107,0.109577,2.861578,0.676731,0.000280,0.303269,0.041178,27.631569,1.767921,19.740844,16.859121,4.067741,1.746761,1.589870,4.959903,0.325985
+122.600000,17.584604,5.063987,2.104360,4.349188,1.497465,0.506504,4.317471,0.109647,2.862513,0.676251,0.000278,0.303749,0.041179,27.635342,1.765718,19.741339,16.860021,4.067897,1.745872,1.587484,4.959631,0.328175
+122.700000,17.584538,5.065608,2.099335,4.341287,1.500399,0.505357,4.332715,0.109862,2.867138,0.675438,0.000278,0.304562,0.041193,27.641172,1.763023,19.742578,16.860916,4.068796,1.744991,1.585109,4.959365,0.330266
+122.800000,17.584453,5.068671,2.099574,4.334859,1.500239,0.504652,4.349835,0.110097,2.872785,0.674817,0.000278,0.305183,0.041205,27.649033,1.760372,19.743898,16.861820,4.070660,1.744123,1.582734,4.959103,0.330187
+122.900000,17.584387,5.070245,2.104749,4.336090,1.497198,0.505063,4.357926,0.110207,2.875766,0.674720,0.000279,0.305280,0.041202,27.656821,1.758271,19.744552,16.862724,4.072870,1.743267,1.580372,4.958845,0.328053
+123.000000,17.584362,5.068864,2.109637,4.343615,1.494335,0.506163,4.354931,0.110169,2.875007,0.674965,0.000280,0.305035,0.041188,27.662437,1.756706,19.744440,16.863605,4.074562,1.742426,1.578047,4.958593,0.326028
+123.100000,17.584356,5.065997,2.109184,4.349704,1.494621,0.506819,4.349895,0.110108,2.873156,0.675021,0.000279,0.304979,0.041174,27.665886,1.755147,19.744218,16.864450,4.075461,1.741595,1.575771,4.958345,0.326195
+123.200000,17.584332,5.064649,2.103633,4.347891,1.497892,0.506322,4.354138,0.110176,2.874033,0.674539,0.000278,0.305461,0.041176,27.669334,1.753066,19.744659,16.865269,4.076167,1.740773,1.573527,4.958101,0.328475
+123.300000,17.584268,5.066330,2.098446,4.339697,1.500919,0.505134,4.369643,0.110394,2.878716,0.673717,0.000277,0.306283,0.041190,27.674923,1.750485,19.745857,16.866086,4.077540,1.739960,1.571293,4.957862,0.330635
+123.400000,17.584184,5.069498,2.098717,4.333066,1.500740,0.504408,4.387050,0.110632,2.884439,0.673096,0.000277,0.306904,0.041202,27.682607,1.747951,19.747132,16.866912,4.079822,1.739160,1.569056,4.957627,0.330543
+123.500000,17.584120,5.071116,2.104102,4.334376,1.497577,0.504838,4.395078,0.110740,2.887406,0.673019,0.000279,0.306981,0.041200,27.690221,1.745980,19.747724,16.867739,4.082387,1.738375,1.566832,4.957397,0.328322
+123.600000,17.584098,5.069664,2.109224,4.342231,1.494577,0.505987,4.391551,0.110695,2.886496,0.673297,0.000279,0.306703,0.041185,27.695605,1.744556,19.747533,16.868544,4.084351,1.737603,1.564644,4.957171,0.326198
+123.700000,17.584097,5.066652,2.108842,4.348662,1.494823,0.506685,4.385768,0.110624,2.884416,0.673383,0.000279,0.306617,0.041171,27.698749,1.743140,19.747225,16.869313,4.085437,1.736842,1.562503,4.956949,0.326335
+123.800000,17.584076,5.065193,2.103126,4.346924,1.498190,0.506188,4.389517,0.110684,2.885115,0.672913,0.000278,0.307087,0.041172,27.701867,1.741191,19.747592,16.870057,4.086265,1.736090,1.560395,4.956731,0.328684
+123.900000,17.584014,5.066889,2.097671,4.338467,1.501373,0.504957,4.405059,0.110902,2.889773,0.672083,0.000277,0.307917,0.041187,27.707178,1.738723,19.748741,16.870798,4.087740,1.735348,1.558294,4.956518,0.330956
+124.000000,17.583931,5.070183,2.097808,4.331458,1.501272,0.504182,4.422856,0.111144,2.895595,0.671452,0.000277,0.308548,0.041200,27.714681,1.736292,19.749984,16.871551,4.090134,1.734618,1.556190,4.956308,0.330920
+124.100000,17.583868,5.071928,2.103334,4.332614,1.498026,0.504602,4.431120,0.111255,2.898643,0.671381,0.000278,0.308619,0.041198,27.722177,1.734429,19.750538,16.872306,4.092821,1.733902,1.554095,4.956102,0.328640
+124.200000,17.583848,5.070481,2.108784,4.340723,1.494835,0.505797,4.427238,0.111204,2.897651,0.671690,0.000279,0.308310,0.041183,27.727414,1.733131,19.750284,16.873039,4.094880,1.733199,1.552036,4.955901,0.326381
+124.300000,17.583852,5.067325,2.108638,4.347647,1.494943,0.506562,4.420562,0.111121,2.895305,0.671819,0.000279,0.308181,0.041168,27.730301,1.731860,19.749884,16.873737,4.096002,1.732507,1.550023,4.955703,0.326420
+124.400000,17.583836,5.065685,2.102826,4.346207,1.498367,0.506093,4.423467,0.111170,2.895718,0.671374,0.000278,0.308626,0.041169,27.733067,1.730053,19.750159,16.874410,4.096808,1.731824,1.548043,4.955509,0.328807
+124.500000,17.583777,5.067325,2.097005,4.337553,1.501763,0.504821,4.438828,0.111385,2.900272,0.670538,0.000277,0.309462,0.041183,27.738047,1.727700,19.751249,16.875080,4.098245,1.731149,1.546070,4.955319,0.331232
+124.600000,17.583694,5.070751,2.096838,4.330007,1.501839,0.503970,4.457133,0.111633,2.906219,0.669884,0.000277,0.310116,0.041197,27.745348,1.725355,19.752473,16.875763,4.100639,1.730486,1.544091,4.955133,0.331323
+124.700000,17.583630,5.072702,2.102422,4.330771,1.498560,0.504349,4.465968,0.111751,2.909454,0.669805,0.000278,0.310195,0.041196,27.752775,1.723576,19.753017,16.876450,4.103372,1.729837,1.542119,4.954950,0.329018
+124.800000,17.583611,5.071338,2.108288,4.339042,1.495126,0.505583,4.461963,0.111698,2.908462,0.670143,0.000279,0.309857,0.041181,27.757947,1.722390,19.752717,16.877117,4.105486,1.729201,1.540181,4.954772,0.326587
+124.900000,17.583619,5.068042,2.108555,4.346607,1.494991,0.506442,4.454284,0.111601,2.905831,0.670325,0.000279,0.309675,0.041166,27.760627,1.721266,19.752222,16.877749,4.106610,1.728575,1.538289,4.954596,0.326455
+125.000000,17.583608,5.066144,2.102742,4.345713,1.498417,0.506034,4.455989,0.111634,2.905848,0.669921,0.000278,0.310079,0.041165,27.763019,1.719611,19.752385,16.878354,4.107342,1.727957,1.536430,4.954425,0.328841
+125.100000,17.583553,5.067648,2.096469,4.336965,1.502078,0.504728,4.470910,0.111842,2.910208,0.669083,0.000277,0.310917,0.041180,27.767607,1.717374,19.753405,16.878957,4.108678,1.727347,1.534578,4.954257,0.331453
+125.200000,17.583471,5.071198,2.095816,4.328739,1.502437,0.503776,4.489807,0.112098,2.916295,0.668394,0.000277,0.311606,0.041194,27.774677,1.715102,19.754621,16.879573,4.111016,1.726747,1.532718,4.954092,0.331747
+125.300000,17.583406,5.073429,2.101353,4.328857,1.499185,0.504080,4.499565,0.112227,2.919823,0.668291,0.000278,0.311709,0.041195,27.782071,1.713383,19.755180,16.880196,4.113772,1.726161,1.530862,4.953931,0.329461
+125.400000,17.583387,5.072237,2.107703,4.337160,1.495468,0.505343,4.495727,0.112176,2.918933,0.668651,0.000279,0.311349,0.041180,27.787263,1.712293,19.754855,16.880801,4.115944,1.725588,1.529038,4.953773,0.326830
+125.500000,17.583398,5.068818,2.108570,4.345493,1.494980,0.506319,4.486991,0.112065,2.916014,0.668898,0.000279,0.311102,0.041164,27.789795,1.711315,19.754263,16.881371,4.117073,1.725024,1.527259,4.953618,0.326450
+125.600000,17.583393,5.066591,2.102882,4.345412,1.498335,0.506009,4.487135,0.112076,2.915529,0.668552,0.000278,0.311448,0.041162,27.791802,1.709823,19.754296,16.881913,4.117716,1.724468,1.525515,4.953467,0.328782
+125.700000,17.583343,5.067864,2.096098,4.336720,1.502297,0.504682,4.501295,0.112274,2.919587,0.667718,0.000277,0.312282,0.041176,27.795934,1.707708,19.755232,16.882452,4.118911,1.723919,1.523778,4.953319,0.331605
+125.800000,17.583262,5.071514,2.094770,4.327701,1.503049,0.503606,4.520809,0.112537,2.925809,0.666984,0.000277,0.313016,0.041192,27.802728,1.705497,19.756446,16.883005,4.121157,1.723379,1.522032,4.953174,0.332181
+125.900000,17.583194,5.074093,2.100117,4.326903,1.499909,0.503798,4.531841,0.112683,2.929732,0.666839,0.000278,0.313161,0.041194,27.810117,1.703816,19.757047,16.883567,4.123924,1.722853,1.520286,4.953033,0.329974
+126.000000,17.583173,5.073173,2.106988,4.335056,1.495885,0.505071,4.528532,0.112638,2.929063,0.667212,0.000279,0.312788,0.041180,27.815411,1.702801,19.756722,16.884115,4.126168,1.722338,1.518569,4.952894,0.327127
+126.100000,17.583187,5.069670,2.108647,4.344241,1.494933,0.506184,4.518762,0.112513,2.925881,0.667532,0.000279,0.312468,0.041162,27.817869,1.701966,19.756036,16.884628,4.127326,1.721834,1.516896,4.952759,0.326420
+126.200000,17.583190,5.067048,2.103251,4.345257,1.498120,0.506011,4.516994,0.112499,2.924796,0.667261,0.000278,0.312739,0.041158,27.819493,1.700648,19.755920,16.885111,4.127878,1.721335,1.515260,4.952627,0.328629
+126.300000,17.583146,5.067984,2.095933,4.336831,1.502396,0.504686,4.529998,0.112681,2.928422,0.666441,0.000277,0.313559,0.041171,27.823106,1.698665,19.756751,16.885590,4.128904,1.720844,1.513633,4.952498,0.331671
+126.400000,17.583066,5.071684,2.093739,4.326956,1.503653,0.503470,4.550066,0.112952,2.934743,0.665655,0.000276,0.314345,0.041189,27.829563,1.696508,19.757966,16.886083,4.131020,1.720361,1.511995,4.952371,0.332608
+126.500000,17.582995,5.074669,2.098713,4.324961,1.500730,0.503508,4.562704,0.113118,2.939155,0.665449,0.000277,0.314551,0.041193,27.836955,1.694842,19.758632,16.886588,4.133785,1.719889,1.510354,4.952248,0.330557
+126.600000,17.582971,5.074134,2.106097,4.332717,1.496406,0.504763,4.560360,0.113085,2.938848,0.665822,0.000279,0.314178,0.041180,27.842434,1.693879,19.758335,16.887082,4.136120,1.719431,1.508736,4.952127,0.327497
+126.700000,17.582987,5.070611,2.108733,4.342778,1.494880,0.506026,4.549691,0.112947,2.935463,0.666219,0.000279,0.313781,0.041161,27.844908,1.693179,19.757565,16.887542,4.137336,1.718981,1.507163,4.952010,0.326388
+126.800000,17.582997,5.067548,2.103842,4.345179,1.497773,0.506035,4.545694,0.112903,2.933694,0.666043,0.000278,0.313957,0.041155,27.846170,1.692046,19.757284,16.887971,4.137809,1.718538,1.505629,4.951895,0.328385
+126.900000,17.582962,5.068027,2.096022,4.337298,1.502347,0.504744,4.557069,0.113064,2.936740,0.665253,0.000277,0.314747,0.041167,27.849203,1.690208,19.757987,16.888392,4.138643,1.718100,1.504105,4.951783,0.331631
+127.000000,17.582883,5.071700,2.092779,4.326575,1.504216,0.503379,4.577511,0.113339,2.943088,0.664411,0.000276,0.315589,0.041185,27.855246,1.688103,19.759196,16.888828,4.140593,1.717670,1.502570,4.951674,0.333005
+127.100000,17.582808,5.075127,2.097151,4.323107,1.501643,0.503220,4.592039,0.113530,2.948061,0.664124,0.000277,0.315876,0.041192,27.862626,1.686432,19.759948,16.889279,4.143333,1.717251,1.501028,4.951567,0.331206
+127.200000,17.582779,5.075097,2.104981,4.330150,1.497059,0.504418,4.591168,0.113516,2.948274,0.664477,0.000279,0.315523,0.041181,27.868363,1.685494,19.759712,16.889723,4.145774,1.716844,1.499505,4.951463,0.327961
+127.300000,17.582796,5.071651,2.108760,4.341024,1.494860,0.505832,4.579869,0.113369,2.944787,0.664952,0.000279,0.315048,0.041161,27.870960,1.684916,19.758876,16.890135,4.147085,1.716446,1.498025,4.951362,0.326380
+127.400000,17.582814,5.068126,2.104633,4.345082,1.497308,0.506066,4.573396,0.113292,2.942277,0.664892,0.000278,0.315108,0.041152,27.871907,1.683977,19.758417,16.890514,4.147502,1.716054,1.496586,4.951263,0.328059
+127.500000,17.582788,5.068022,2.096412,4.338105,1.502122,0.504855,4.582598,0.113424,2.944577,0.664152,0.000277,0.315848,0.041162,27.874309,1.682303,19.758962,16.890881,4.148129,1.715666,1.495161,4.951167,0.331466
+127.600000,17.582713,5.071555,2.091963,4.326631,1.504696,0.503343,4.603090,0.113700,2.950836,0.663255,0.000276,0.316745,0.041181,27.879843,1.680254,19.760152,16.891262,4.149870,1.715286,1.493724,4.951073,0.333342
+127.700000,17.582634,5.075434,2.095461,4.321439,1.502631,0.502946,4.619710,0.113918,2.956413,0.662867,0.000277,0.317133,0.041191,27.887169,1.678559,19.761006,16.891662,4.152556,1.714915,1.492276,4.950982,0.331907
+127.800000,17.582598,5.076032,2.103594,4.327384,1.497869,0.504037,4.620877,0.113930,2.957313,0.663178,0.000278,0.316822,0.041182,27.893223,1.677617,19.760865,16.892059,4.155111,1.714557,1.490842,4.950894,0.328536
+127.900000,17.582613,5.072794,2.108646,4.338902,1.494923,0.505590,4.609376,0.113780,2.953874,0.663724,0.000279,0.316276,0.041162,27.896064,1.677142,19.759990,16.892427,4.156558,1.714208,1.489448,4.950807,0.326431
+128.000000,17.582639,5.068819,2.105581,4.344849,1.496750,0.506091,4.600293,0.113668,2.950607,0.663796,0.000278,0.316204,0.041150,27.896774,1.676402,19.759346,16.892760,4.156953,1.713864,1.488098,4.950724,0.327669
+128.100000,17.582624,5.068008,2.097143,4.339200,1.501698,0.505016,4.606731,0.113763,2.951987,0.663133,0.000277,0.316867,0.041157,27.898510,1.674911,19.759702,16.893077,4.157368,1.713524,1.486766,4.950642,0.331159
+128.200000,17.582554,5.071255,2.091375,4.327190,1.505042,0.503375,4.626785,0.114034,2.957991,0.662190,0.000276,0.317810,0.041176,27.903428,1.672931,19.760849,16.893406,4.158858,1.713190,1.485423,4.950563,0.333582
+128.300000,17.582471,5.075552,2.093698,4.320080,1.503662,0.502703,4.645564,0.114281,2.964169,0.661685,0.000276,0.318315,0.041190,27.910626,1.671200,19.761814,16.893757,4.161448,1.712865,1.484065,4.950486,0.332640
+128.400000,17.582427,5.076896,2.101908,4.324488,1.498855,0.503625,4.649355,0.114327,2.965926,0.661925,0.000278,0.318075,0.041184,27.917032,1.670224,19.761806,16.894110,4.164114,1.712551,1.482714,4.950411,0.329237
+128.500000,17.582439,5.074029,2.108295,4.336355,1.495124,0.505288,4.638250,0.114180,2.962731,0.662526,0.000279,0.317474,0.041163,27.920244,1.669824,19.760926,16.894438,4.165736,1.712247,1.481401,4.950339,0.326581
+128.600000,17.582471,5.069665,2.106613,4.344339,1.496141,0.506089,4.626591,0.114034,2.958748,0.662746,0.000279,0.317254,0.041148,27.920830,1.669281,19.760101,16.894729,4.166158,1.711948,1.480133,4.950269,0.327246
+128.700000,17.582468,5.068037,2.098237,4.340494,1.501061,0.505218,4.629671,0.114085,2.959042,0.662190,0.000277,0.317810,0.041152,27.921895,1.667998,19.760236,16.895000,4.166369,1.711653,1.478889,4.950201,0.330702
+128.800000,17.582407,5.070818,2.091113,4.328296,1.505201,0.503486,4.648627,0.114342,2.964576,0.661218,0.000276,0.318782,0.041171,27.926084,1.666107,19.761303,16.895280,4.167568,1.711362,1.477635,4.950135,0.333686
+128.900000,17.582321,5.075452,2.091941,4.319166,1.504690,0.502511,4.669454,0.114616,2.971293,0.660583,0.000276,0.319417,0.041187,27.933042,1.664334,19.762378,16.895583,4.170009,1.711079,1.476363,4.950071,0.333369
+129.000000,17.582267,5.077635,2.099913,4.321567,1.500022,0.503195,4.676426,0.114703,2.974057,0.660720,0.000278,0.319280,0.041185,27.939801,1.663291,19.762538,16.895895,4.172768,1.710807,1.475092,4.950009,0.330065
+129.100000,17.582273,5.075333,2.107608,4.333349,1.495522,0.504916,4.666480,0.114570,2.971348,0.661354,0.000279,0.318646,0.041166,27.943512,1.662933,19.761699,16.896186,4.174602,1.710545,1.473854,4.949950,0.326869
+129.200000,17.582310,5.070694,2.107627,4.343398,1.495540,0.506039,4.652496,0.114392,2.966759,0.661729,0.000279,0.318271,0.041147,27.944123,1.662579,19.760709,16.896440,4.175109,1.710289,1.472662,4.949892,0.326832
+129.300000,17.582320,5.068171,2.099688,4.341855,1.500214,0.505447,4.651678,0.114392,2.965827,0.661314,0.000277,0.318686,0.041147,27.944550,1.661526,19.760591,16.896668,4.175142,1.710035,1.471499,4.949836,0.330098
+129.400000,17.582269,5.070278,2.091273,4.329964,1.505113,0.503680,4.668710,0.114624,2.970632,0.660340,0.000276,0.319660,0.041165,27.947900,1.659752,19.761535,16.896902,4.176017,1.709785,1.470331,4.949782,0.333614
+129.500000,17.582182,5.075109,2.090300,4.318843,1.505650,0.502390,4.691245,0.114921,2.977754,0.659571,0.000276,0.320429,0.041184,27.954474,1.657940,19.762705,16.897159,4.178246,1.709541,1.469142,4.949731,0.334050
+129.600000,17.582118,5.078189,2.097630,4.318770,1.501356,0.502764,4.701867,0.115056,2.981641,0.659571,0.000277,0.320429,0.041187,27.961545,1.656803,19.763064,16.897432,4.181063,1.709308,1.467946,4.949681,0.331014
+129.700000,17.582115,5.076661,2.106492,4.329898,1.496173,0.504472,4.693983,0.114949,2.979695,0.660203,0.000279,0.319797,0.041169,27.965869,1.656445,19.762320,16.897690,4.183136,1.709085,1.466778,4.949633,0.327335
+129.800000,17.582154,5.071926,2.108493,4.341874,1.495026,0.505915,4.678191,0.114746,2.974690,0.660732,0.000279,0.319268,0.041148,27.966685,1.656259,19.761194,16.897910,4.183796,1.708868,1.465656,4.949587,0.326481
+129.900000,17.582178,5.068477,2.101457,4.343104,1.499178,0.505680,4.673064,0.114689,2.972441,0.660492,0.000278,0.319508,0.041143,27.966555,1.655456,19.760800,16.898100,4.183697,1.708653,1.464568,4.949542,0.329365
+130.000000,17.582140,5.069691,2.091944,4.332153,1.504729,0.503960,4.687215,0.114884,2.976226,0.659553,0.000276,0.320447,0.041159,27.968972,1.653836,19.761567,16.898290,4.184225,1.708441,1.463481,4.949500,0.333328
+130.100000,17.582054,5.074516,2.088910,4.319246,1.506464,0.502363,4.710851,0.115197,2.983538,0.658654,0.000275,0.321346,0.041180,27.974989,1.652000,19.762802,16.898504,4.186174,1.708234,1.462372,4.949459,0.334625
+130.200000,17.581980,5.078493,2.095122,4.316288,1.502821,0.502357,4.725419,0.115383,2.988604,0.658486,0.000277,0.321514,0.041187,27.982279,1.650744,19.763381,16.898738,4.188995,1.708036,1.461249,4.949420,0.332057
+130.300000,17.581965,5.077950,2.104872,4.326074,1.497118,0.503960,4.720587,0.115315,2.987711,0.659074,0.000279,0.320926,0.041173,27.987302,1.650339,19.762791,16.898965,4.191319,1.707849,1.460146,4.949383,0.328010
+130.400000,17.582004,5.073359,2.109056,4.339637,1.494688,0.505696,4.703795,0.115097,2.982567,0.659742,0.000279,0.320258,0.041149,27.988526,1.650290,19.761577,16.899156,4.192203,1.707669,1.459088,4.949347,0.326256
+130.500000,17.582040,5.069023,2.103454,4.344019,1.498006,0.505888,4.694176,0.114980,2.978990,0.659709,0.000278,0.320291,0.041139,27.987978,1.649749,19.760896,16.899312,4.192038,1.707491,1.458070,4.949313,0.328540
+130.600000,17.582018,5.069131,2.093191,4.334766,1.504007,0.504316,4.704416,0.115125,2.981455,0.658852,0.000276,0.321148,0.041152,27.989406,1.648326,19.761427,16.899461,4.192218,1.707314,1.457059,4.949281,0.332801
+130.700000,17.581937,5.073684,2.087927,4.320483,1.507043,0.502451,4.728254,0.115441,2.988655,0.657841,0.000275,0.322159,0.041175,27.994669,1.646492,19.762679,16.899633,4.193814,1.707141,1.456026,4.949250,0.335030
+130.800000,17.581853,5.078486,2.092497,4.314344,1.504355,0.502003,4.746816,0.115680,2.994871,0.657477,0.000276,0.322523,0.041187,28.002029,1.645103,19.763488,16.899830,4.196566,1.706976,1.454974,4.949221,0.333149
+130.900000,17.581824,5.079120,2.102709,4.322017,1.498382,0.503394,4.746032,0.115664,2.995313,0.657970,0.000278,0.322030,0.041177,28.007790,1.644603,19.763111,16.900027,4.199131,1.706822,1.453932,4.949193,0.328909
+131.000000,17.581858,5.074968,2.109147,4.336599,1.494626,0.505362,4.729343,0.115446,2.990389,0.658749,0.000279,0.321251,0.041153,28.009639,1.644645,19.761871,16.900193,4.200310,1.706676,1.452932,4.949167,0.326227
+131.100000,17.581906,5.069870,2.105537,4.344351,1.496781,0.506035,4.715368,0.115271,2.985577,0.658945,0.000278,0.321055,0.041137,28.008870,1.644366,19.760910,16.900321,4.200167,1.706531,1.451978,4.949143,0.327683
+131.200000,17.581902,5.068693,2.095038,4.337624,1.502935,0.504732,4.720690,0.115352,2.986442,0.658225,0.000276,0.321775,0.041145,28.009303,1.643185,19.761147,16.900433,4.200019,1.706388,1.451038,4.949120,0.332027
+131.300000,17.581830,5.072654,2.087516,4.322614,1.507291,0.502668,4.743540,0.115657,2.993148,0.657135,0.000275,0.322865,0.041169,28.013615,1.641396,19.762351,16.900563,4.201198,1.706246,1.450080,4.949098,0.335194
+131.400000,17.581738,5.078118,2.089912,4.313176,1.505864,0.501740,4.765803,0.115945,3.000378,0.656558,0.000276,0.323442,0.041186,28.020837,1.639870,19.763380,16.900723,4.203787,1.706113,1.449096,4.949078,0.334224
+131.500000,17.581693,5.080073,2.100013,4.317944,1.499958,0.502798,4.769967,0.115992,3.002392,0.656903,0.000278,0.323097,0.041181,28.027314,1.639227,19.763272,16.900893,4.206557,1.705989,1.448112,4.949060,0.330030
+131.600000,17.581718,5.076694,2.108606,4.332743,1.494936,0.504903,4.754741,0.115791,2.998113,0.657747,0.000279,0.322253,0.041157,28.029990,1.639304,19.762084,16.901037,4.208088,1.705873,1.447166,4.949043,0.326458
+131.700000,17.581774,5.071059,2.107511,4.343840,1.495615,0.506084,4.736956,0.115566,2.992287,0.658182,0.000279,0.321818,0.041137,28.029260,1.639272,19.760873,16.901139,4.208072,1.705761,1.446268,4.949027,0.326874
+131.800000,17.581790,5.068485,2.097449,4.340472,1.501529,0.505176,4.736501,0.115572,2.991334,0.657656,0.000277,0.322344,0.041139,28.028764,1.638373,19.760764,16.901219,4.207650,1.705648,1.445395,4.949013,0.331021
+131.900000,17.581731,5.071501,2.087830,4.325618,1.507117,0.503019,4.756927,0.115846,2.997100,0.656536,0.000275,0.323464,0.041161,28.031942,1.636684,19.761840,16.901310,4.208362,1.705536,1.444507,4.948999,0.335053
+132.000000,17.581635,5.077363,2.087570,4.313018,1.507232,0.501601,4.782191,0.116175,3.005084,0.655743,0.000275,0.324257,0.041183,28.038766,1.635036,19.763056,16.901434,4.210681,1.705431,1.443590,4.948988,0.335198
+132.100000,17.581573,5.080703,2.096858,4.314141,1.501801,0.502209,4.791977,0.116295,3.008826,0.655885,0.000277,0.324115,0.041184,28.045858,1.634209,19.763261,16.901575,4.213589,1.705335,1.442664,4.948977,0.331341
+132.200000,17.581585,5.078446,2.107295,4.328148,1.495698,0.504321,4.779757,0.116131,3.005654,0.656734,0.000279,0.323266,0.041163,28.049530,1.634253,19.762214,16.901699,4.215510,1.705247,1.441766,4.948968,0.327007
+132.300000,17.581644,5.072602,2.109139,4.342255,1.494649,0.505994,4.759170,0.115867,2.999174,0.657399,0.000279,0.322601,0.041138,28.049142,1.634433,19.760807,16.901782,4.215736,1.705164,1.440919,4.948960,0.326212
+132.400000,17.581679,5.068618,2.100316,4.342979,1.499853,0.505607,4.752379,0.115790,2.996293,0.657123,0.000277,0.322877,0.041134,28.047873,1.633850,19.760317,16.901833,4.215127,1.705081,1.440105,4.948954,0.329831
+132.500000,17.581639,5.070331,2.088995,4.329382,1.506449,0.503499,4.768777,0.116014,3.000638,0.656039,0.000275,0.323961,0.041153,28.049776,1.632326,19.761173,16.901889,4.215347,1.704997,1.439286,4.948948,0.334556
+132.600000,17.581544,5.076227,2.085709,4.314061,1.508322,0.501622,4.795895,0.116368,3.008982,0.655045,0.000275,0.324955,0.041178,28.055905,1.630588,19.762518,16.901976,4.217282,1.704917,1.438434,4.948944,0.335969
+132.700000,17.581465,5.080910,2.093394,4.310950,1.503823,0.501673,4.811618,0.116565,3.014488,0.654936,0.000276,0.325064,0.041186,28.063425,1.629547,19.763063,16.902089,4.220229,1.704846,1.437564,4.948941,0.332783
+132.800000,17.581458,5.080103,2.105134,4.323006,1.496959,0.503633,4.803997,0.116460,3.012883,0.655717,0.000279,0.324283,0.041169,28.068198,1.629486,19.762249,16.902195,4.222546,1.704785,1.436712,4.948939,0.327907
+132.900000,17.581516,5.074472,2.110157,4.339430,1.494041,0.505733,4.782097,0.116176,3.006243,0.656581,0.000279,0.323419,0.041142,28.068481,1.629822,19.760729,16.902262,4.223128,1.704728,1.435909,4.948939,0.325803
+133.000000,17.581569,5.069193,2.103441,4.344758,1.498020,0.505971,4.768872,0.116015,3.001477,0.656600,0.000278,0.323400,0.041130,28.066688,1.629572,19.759847,16.902290,4.222452,1.704672,1.435149,4.948939,0.328539
+133.100000,17.581551,5.069286,2.091070,4.333665,1.505250,0.504085,4.779622,0.116167,3.003937,0.655632,0.000276,0.324368,0.041145,28.067251,1.628284,19.760388,16.902312,4.222192,1.704614,1.434393,4.948941,0.333681
+133.200000,17.581463,5.074759,2.084583,4.316422,1.508986,0.501828,4.806985,0.116526,3.012116,0.654473,0.000274,0.325527,0.041172,28.072372,1.626511,19.761776,16.902364,4.223637,1.704559,1.433606,4.948943,0.336431
+133.300000,17.581369,5.080610,2.089848,4.308742,1.505892,0.501243,4.828472,0.116799,3.019268,0.654078,0.000276,0.325922,0.041187,28.080042,1.625243,19.762661,16.902448,4.226493,1.704511,1.432791,4.948947,0.334260
+133.400000,17.581341,5.081516,2.102122,4.317631,1.498719,0.502875,4.826924,0.116771,3.019631,0.654710,0.000278,0.325290,0.041175,28.085930,1.625006,19.762169,16.902536,4.229171,1.704473,1.431983,4.948952,0.329159
+133.500000,17.581390,5.076587,2.110305,4.335311,1.493941,0.505281,4.805624,0.116493,3.013436,0.655716,0.000279,0.324284,0.041147,28.087205,1.625423,19.760642,16.902590,4.230210,1.704441,1.431220,4.948958,0.325753
+133.600000,17.581457,5.070283,2.106541,4.345408,1.496195,0.506208,4.786477,0.116252,3.007022,0.656057,0.000279,0.323943,0.041128,28.085234,1.625499,19.759391,16.902601,4.229616,1.704410,1.430506,4.948965,0.327264
+133.700000,17.581465,5.068526,2.094028,4.338105,1.503532,0.504734,4.790128,0.116313,3.007208,0.655291,0.000276,0.324709,0.041136,28.084493,1.624518,19.759530,16.902594,4.228932,1.704377,1.429808,4.948972,0.332440
+133.800000,17.581390,5.073061,2.084433,4.320101,1.509085,0.502230,4.815736,0.116653,3.014593,0.654031,0.000274,0.325969,0.041164,28.088309,1.622782,19.760851,16.902611,4.229798,1.704344,1.429084,4.948981,0.336482
+133.900000,17.581286,5.079753,2.086516,4.307873,1.507835,0.500975,4.842214,0.116992,3.023088,0.653334,0.000275,0.326666,0.041185,28.095773,1.621298,19.762043,16.902665,4.232411,1.704317,1.428325,4.948991,0.335649
+134.000000,17.581234,5.082525,2.098356,4.312445,1.500919,0.502099,4.847898,0.117056,3.025707,0.653736,0.000277,0.326264,0.041181,28.102674,1.620820,19.761946,16.902734,4.235371,1.704299,1.427560,4.949002,0.330725
+134.100000,17.581268,5.078816,2.109371,4.329994,1.494480,0.504638,4.829407,0.116812,3.020627,0.654803,0.000279,0.325197,0.041155,28.105216,1.621228,19.760536,16.902778,4.236937,1.704290,1.426832,4.949014,0.326150
+134.200000,17.581344,5.071915,2.109262,4.344563,1.494586,0.506259,4.805551,0.116508,3.013011,0.655466,0.000279,0.324534,0.041129,28.103486,1.621593,19.758979,16.902776,4.236592,1.704282,1.426158,4.949026,0.326152
+134.300000,17.581379,5.068221,2.097725,4.342222,1.501376,0.505387,4.801065,0.116463,3.010684,0.654987,0.000277,0.325013,0.041129,28.101607,1.620978,19.758649,16.902746,4.235592,1.704272,1.425512,4.949040,0.330899
+134.400000,17.581324,5.071286,2.085456,4.324954,1.508504,0.502824,4.822637,0.116753,3.016584,0.653713,0.000275,0.326287,0.041154,28.103880,1.619372,19.759773,16.902729,4.235826,1.704260,1.424849,4.949054,0.336040
+134.500000,17.581216,5.078340,2.083744,4.308642,1.509454,0.500918,4.852676,0.117141,3.025924,0.652725,0.000274,0.327275,0.041181,28.110719,1.617708,19.761204,16.902752,4.238033,1.704252,1.424146,4.949070,0.336802
+134.600000,17.581140,5.082977,2.094048,4.307951,1.503434,0.501374,4.866246,0.117307,3.030917,0.652823,0.000276,0.327177,0.041186,28.118406,1.616942,19.761551,16.902801,4.241146,1.704253,1.423424,4.949086,0.332518
+134.700000,17.581152,5.080982,2.107220,4.323745,1.495733,0.503827,4.852872,0.117127,3.027624,0.653851,0.000279,0.326149,0.041163,28.122402,1.617240,19.760389,16.902836,4.243263,1.704263,1.422728,4.949103,0.327047
+134.800000,17.581230,5.074054,2.111216,4.341958,1.493423,0.506072,4.826242,0.116784,3.019458,0.654802,0.000280,0.325198,0.041133,28.121378,1.617828,19.758630,16.902827,4.243336,1.704277,1.422087,4.949121,0.325361
+134.900000,17.581289,5.068524,2.101891,4.345456,1.498937,0.505968,4.813222,0.116628,3.014595,0.654684,0.000278,0.325316,0.041123,28.118666,1.617615,19.757798,16.902778,4.242178,1.704288,1.421487,4.949140,0.329172
+135.000000,17.581261,5.069632,2.087754,4.330657,1.507180,0.503578,4.828414,0.116837,3.018327,0.653503,0.000275,0.326497,0.041143,28.119254,1.616241,19.758589,16.902731,4.241778,1.704297,1.420881,4.949160,0.335065
+135.100000,17.581157,5.076435,2.081900,4.311233,1.510535,0.501113,4.859921,0.117248,3.027824,0.652267,0.000274,0.327733,0.041174,28.125025,1.614465,19.760150,16.902721,4.243420,1.704307,1.420235,4.949180,0.337565
+135.200000,17.581060,5.082747,2.089515,4.304687,1.506077,0.500775,4.881333,0.117516,3.035089,0.652005,0.000276,0.327995,0.041188,28.133140,1.613386,19.760952,16.902748,4.246514,1.704325,1.419558,4.949201,0.334408
+135.300000,17.581045,5.082870,2.103842,4.317009,1.497707,0.502897,4.875231,0.117427,3.034179,0.652881,0.000278,0.327119,0.041172,28.138646,1.613474,19.760165,16.902775,4.249152,1.704352,1.418893,4.949223,0.328451
+135.400000,17.581114,5.076589,2.112021,4.337495,1.492935,0.505618,4.848397,0.117079,3.026282,0.654050,0.000280,0.325950,0.041140,28.138788,1.614189,19.758343,16.902761,4.249791,1.704385,1.418279,4.949246,0.325045
+135.500000,17.581194,5.069547,2.106128,4.347218,1.496446,0.506389,4.827320,0.116816,3.019137,0.654339,0.000278,0.325661,0.041121,28.135690,1.614381,19.757026,16.902700,4.248677,1.704416,1.417716,4.949269,0.327426
+135.600000,17.581198,5.068332,2.091310,4.336711,1.505121,0.504438,4.833988,0.116917,3.020113,0.653372,0.000276,0.326628,0.041133,28.134597,1.613342,19.757353,16.902627,4.247704,1.704443,1.417163,4.949293,0.333569
+135.700000,17.581107,5.074174,2.081332,4.315666,1.510879,0.501578,4.864290,0.117315,3.028923,0.651966,0.000274,0.328034,0.041165,28.138871,1.611549,19.758900,16.902585,4.248649,1.704470,1.416574,4.949318,0.337789
+135.800000,17.580995,5.081758,2.085175,4.303168,1.508606,0.500382,4.892665,0.117675,3.038104,0.651316,0.000275,0.328684,0.041187,28.146942,1.610163,19.760126,16.902586,4.251517,1.704503,1.415944,4.949343,0.336219
+135.900000,17.580949,5.084252,2.099371,4.310388,1.500320,0.501924,4.895551,0.117701,3.040011,0.651927,0.000277,0.328073,0.041180,28.153853,1.609952,19.759820,16.902602,4.254577,1.704546,1.415310,4.949370,0.330310
+136.000000,17.581001,5.079336,2.111361,4.331298,1.493308,0.504891,4.871525,0.117386,3.033300,0.653207,0.000280,0.326793,0.041149,28.155559,1.610674,19.758101,16.902587,4.255891,1.704595,1.414719,4.949397,0.325331
+136.100000,17.581094,5.071333,2.109933,4.346976,1.494198,0.506565,4.843876,0.117036,3.024432,0.653913,0.000279,0.326087,0.041121,28.152634,1.611233,19.756371,16.902521,4.255049,1.704645,1.414186,4.949424,0.325869
+136.200000,17.581131,5.067630,2.095928,4.342437,1.502433,0.505318,4.840440,0.117006,3.022269,0.653280,0.000276,0.326720,0.041124,28.150043,1.610617,19.756132,16.902426,4.253638,1.704691,1.413679,4.949453,0.331639
+136.300000,17.581064,5.071775,2.082322,4.321743,1.510321,0.502306,4.866459,0.117353,3.029455,0.651816,0.000274,0.328184,0.041153,28.152471,1.608930,19.757493,16.902353,4.253801,1.704733,1.413145,4.949481,0.337357
+136.400000,17.580943,5.080009,2.081516,4.303815,1.510738,0.500267,4.899990,0.117783,3.039920,0.650786,0.000274,0.329214,0.041183,28.159939,1.607280,19.759059,16.902327,4.256221,1.704780,1.412564,4.949511,0.337746
+136.500000,17.580867,5.084907,2.094109,4.304601,1.503391,0.501004,4.912852,0.117936,3.044839,0.651030,0.000276,0.328970,0.041186,28.167971,1.606702,19.759305,16.902329,4.259538,1.704835,1.411963,4.949541,0.332500
+136.600000,17.580893,5.082038,2.109054,4.323755,1.494652,0.503926,4.894773,0.117695,3.040228,0.652288,0.000279,0.327712,0.041159,28.171510,1.607299,19.757864,16.902314,4.261569,1.704900,1.411392,4.949572,0.326294
+136.700000,17.580989,5.073830,2.112749,4.344351,1.492524,0.506422,4.863077,0.117289,3.030491,0.653370,0.000280,0.326630,0.041126,28.169382,1.608142,19.755852,16.902247,4.261229,1.704966,1.410882,4.949603,0.324727
+136.800000,17.581058,5.067740,2.101227,4.347045,1.499334,0.506110,4.848867,0.117119,3.025114,0.653175,0.000277,0.326825,0.041117,28.165676,1.608006,19.754996,16.902139,4.259586,1.705029,1.410414,4.949635,0.329439
+136.900000,17.581023,5.069516,2.085016,4.329010,1.508775,0.503254,4.867432,0.117373,3.029748,0.651796,0.000274,0.328204,0.041141,28.166045,1.606562,19.755985,16.902036,4.258955,1.705086,1.409933,4.949667,0.336209
+137.000000,17.580905,5.077594,2.079047,4.306874,1.512182,0.500482,4.903401,0.117838,3.040605,0.650437,0.000273,0.329563,0.041176,28.172318,1.604733,19.757754,16.901980,4.260713,1.705145,1.409404,4.949700,0.338770
+137.100000,17.580800,5.084665,2.088510,4.300396,1.506654,0.500246,4.926247,0.118122,3.048426,0.650238,0.000275,0.329762,0.041190,28.181007,1.603753,19.758573,16.901965,4.264059,1.705212,1.408838,4.949734,0.334836
+137.200000,17.580793,5.084393,2.105101,4.315510,1.496962,0.502797,4.917002,0.117991,3.046710,0.651325,0.000279,0.328675,0.041171,28.186467,1.604093,19.757578,16.901948,4.266770,1.705289,1.408287,4.949768,0.327937
+137.300000,17.580881,5.076875,2.114049,4.339230,1.491740,0.505920,4.884652,0.117572,3.037183,0.652692,0.000280,0.327308,0.041134,28.185747,1.605097,19.755466,16.901886,4.267133,1.705371,1.407793,4.949803,0.324211
+137.400000,17.580976,5.068815,2.106645,4.349719,1.496149,0.506696,4.860234,0.117269,3.028908,0.653000,0.000278,0.327000,0.041113,28.181505,1.605450,19.754005,16.901770,4.265525,1.705449,1.407355,4.949838,0.327206
+137.500000,17.580980,5.067722,2.089370,4.336763,1.506257,0.504343,4.868476,0.117392,3.030199,0.651865,0.000275,0.328135,0.041128,28.179801,1.604386,19.754449,16.901644,4.264176,1.705522,1.406922,4.949873,0.334373
+137.600000,17.580877,5.074709,2.078238,4.312347,1.512669,0.501051,4.903395,0.117848,3.040349,0.650277,0.000273,0.329723,0.041165,28.184314,1.602503,19.756235,16.901556,4.265093,1.705592,1.406446,4.949909,0.339094
+137.700000,17.580751,5.083432,2.083152,4.298461,1.509772,0.499755,4.935085,0.118248,3.050612,0.649597,0.000274,0.330403,0.041190,28.193047,1.601127,19.757589,16.901520,4.268200,1.705669,1.405920,4.949946,0.337075
+137.800000,17.580705,5.086089,2.099712,4.307404,1.500112,0.501610,4.936914,0.118258,3.052360,0.650366,0.000278,0.329634,0.041181,28.200291,1.601096,19.757178,16.901499,4.271462,1.705757,1.405390,4.949983,0.330176
+137.900000,17.580773,5.080203,2.113420,4.331814,1.492092,0.505059,4.907867,0.117878,3.044242,0.651879,0.000280,0.328121,0.041145,28.201500,1.602107,19.755179,16.901442,4.272669,1.705851,1.404908,4.950021,0.324488
+138.000000,17.580885,5.070898,2.111488,4.349748,1.493287,0.506958,4.875194,0.117465,3.033799,0.652703,0.000279,0.327297,0.041114,28.197449,1.602902,19.753207,16.901328,4.271393,1.705944,1.404491,4.950059,0.325225
+138.100000,17.580930,5.066718,2.095108,4.344080,1.502921,0.505458,4.871028,0.117428,3.031241,0.651970,0.000276,0.328030,0.041117,28.193904,1.602336,19.752970,16.901184,4.269502,1.706030,1.404099,4.950097,0.331972
+138.200000,17.580855,5.071651,2.079447,4.319941,1.511989,0.501958,4.900894,0.117824,3.039467,0.650299,0.000273,0.329701,0.041152,28.196199,1.600554,19.754550,16.901065,4.269469,1.706113,1.403675,4.950136,0.338564
+138.300000,17.580718,5.081218,2.078687,4.299332,1.512371,0.499624,4.939069,0.118311,3.051355,0.649148,0.000273,0.330852,0.041186,28.204253,1.598839,19.756332,16.901002,4.272046,1.706199,1.403194,4.950175,0.338942
+138.400000,17.580634,5.086840,2.093317,4.300405,1.503844,0.500496,4.953195,0.118478,3.056803,0.649468,0.000276,0.330532,0.041189,28.212908,1.598352,19.756594,16.900973,4.275643,1.706294,1.402689,4.950215,0.332838
+138.500000,17.580669,5.083464,2.110646,4.322670,1.493709,0.503890,4.931511,0.118189,3.051269,0.650953,0.000280,0.329047,0.041158,28.216386,1.599200,19.754935,16.900924,4.277746,1.706399,1.402216,4.950255,0.325645
+138.600000,17.580785,5.073904,2.115010,4.346655,1.491192,0.506801,4.893919,0.117708,3.039778,0.652238,0.000280,0.327762,0.041120,28.213331,1.600330,19.752622,16.900816,4.277100,1.706505,1.401811,4.950296,0.323798
+138.700000,17.580870,5.066785,2.101696,4.349894,1.499067,0.506454,4.876529,0.117500,3.033289,0.652042,0.000277,0.327958,0.041109,28.208446,1.600335,19.751635,16.900662,4.274938,1.706605,1.401452,4.950337,0.329236
+138.800000,17.580833,5.068800,2.082847,4.329026,1.510039,0.503145,4.897250,0.117783,3.038397,0.650471,0.000274,0.329529,0.041137,28.208253,1.598834,19.752771,16.900515,4.273941,1.706699,1.401078,4.950378,0.337114
+138.900000,17.580700,5.078163,2.075780,4.303297,1.514068,0.499918,4.938370,0.118313,3.050757,0.648918,0.000273,0.331082,0.041177,28.214869,1.596888,19.754805,16.900423,4.275715,1.706793,1.400645,4.950420,0.340151
+139.000000,17.580582,5.086431,2.086542,4.295499,1.507790,0.499599,4.964691,0.118638,3.059731,0.648695,0.000275,0.331305,0.041194,28.224328,1.595903,19.755764,16.900379,4.279350,1.706895,1.400170,4.950462,0.335668
+139.100000,17.580575,5.086251,2.105771,4.312699,1.496561,0.502519,4.954010,0.118487,3.057776,0.649963,0.000279,0.330037,0.041172,28.230164,1.596425,19.754654,16.900335,4.282291,1.707008,1.399707,4.950504,0.327668
+139.200000,17.580680,5.077595,2.116524,4.340345,1.490276,0.506178,4.915950,0.117995,3.046642,0.651585,0.000281,0.328415,0.041130,28.228885,1.597729,19.752235,16.900239,4.282528,1.707126,1.399308,4.950547,0.323200
+139.300000,17.580796,5.068108,2.108358,4.353128,1.495148,0.507168,4.886209,0.117625,3.036670,0.652005,0.000279,0.327995,0.041105,28.223412,1.598315,19.750523,16.900083,4.280439,1.707239,1.398971,4.950590,0.326493
+139.400000,17.580807,5.066589,2.088344,4.338626,1.506863,0.504498,4.894172,0.117746,3.037670,0.650741,0.000275,0.329259,0.041122,28.220733,1.597269,19.750993,16.899914,4.278588,1.707344,1.398642,4.950633,0.334793
+139.500000,17.580692,5.074547,2.075029,4.310298,1.514524,0.500660,4.933729,0.118262,3.049090,0.648917,0.000273,0.331083,0.041164,28.225204,1.595253,19.753041,16.899790,4.279338,1.707446,1.398260,4.950677,0.340447
+139.600000,17.580549,5.084761,2.080168,4.293559,1.511495,0.499057,4.970616,0.118726,3.060962,0.648109,0.000274,0.331891,0.041194,28.234674,1.593785,19.754640,16.899726,4.282665,1.707554,1.397820,4.950721,0.338337
+139.700000,17.580495,5.088153,2.099138,4.303064,1.500439,0.501096,4.973604,0.118748,3.063245,0.648973,0.000277,0.331027,0.041185,28.242656,1.593840,19.754245,16.899682,4.286265,1.707673,1.397370,4.950765,0.330423
+139.800000,17.580573,5.081595,2.115527,4.331184,1.490842,0.505102,4.940156,0.118311,3.053992,0.650750,0.000280,0.329250,0.041144,28.243782,1.595121,19.751994,16.899600,4.287549,1.707800,1.396973,4.950810,0.323631
+139.900000,17.580708,5.070714,2.114151,4.352885,1.491719,0.507451,4.900806,0.117813,3.041538,0.651791,0.000280,0.328209,0.041107,28.238662,1.596219,19.749686,16.899452,4.285917,1.707925,1.396648,4.950855,0.324129
+140.000000,17.580769,5.065442,2.095510,4.347482,1.502696,0.505859,4.893549,0.117739,3.037851,0.651032,0.000276,0.328968,0.041109,28.233830,1.595774,19.749327,16.899268,4.283451,1.708041,1.396355,4.950900,0.331794
+140.100000,17.580690,5.070783,2.076860,4.319864,1.513492,0.501818,4.926456,0.118176,3.046794,0.649127,0.000273,0.330873,0.041148,28.235606,1.593890,19.751104,16.899113,4.283053,1.708151,1.396024,4.950946,0.339648
+140.200000,17.580535,5.081880,2.075049,4.295210,1.514470,0.498981,4.970715,0.118739,3.060477,0.647759,0.000273,0.332241,0.041188,28.244173,1.592017,19.753200,16.899022,4.285709,1.708265,1.395626,4.950992,0.340482
+140.300000,17.580435,5.088819,2.091375,4.295042,1.504967,0.499798,4.988605,0.118951,3.067204,0.648065,0.000276,0.331935,0.041194,28.253781,1.591510,19.753618,16.898972,4.289677,1.708388,1.395195,4.951038,0.333658
+140.400000,17.580472,5.085419,2.111824,4.320038,1.493005,0.503660,4.964797,0.118633,3.061266,0.649772,0.000280,0.330228,0.041161,28.257684,1.592558,19.751813,16.898904,4.292048,1.708522,1.394798,4.951084,0.325171
+140.500000,17.580609,5.074439,2.118105,4.348650,1.489361,0.507191,4.920338,0.118065,3.047818,0.651350,0.000281,0.328650,0.041115,28.253927,1.594021,19.749139,16.898770,4.291237,1.708657,1.394476,4.951131,0.322534
+140.600000,17.580716,5.065698,2.103575,4.354194,1.497974,0.507033,4.897193,0.117785,3.039452,0.651254,0.000278,0.328746,0.041100,28.247624,1.594257,19.747882,16.898581,4.288514,1.708784,1.394209,4.951178,0.328450
+140.700000,17.580686,5.067385,2.081418,4.331076,1.510878,0.503300,4.918398,0.118076,3.044459,0.649504,0.000274,0.330496,0.041130,28.246421,1.592728,19.749092,16.898398,4.286979,1.708903,1.393926,4.951225,0.337704
+140.800000,17.580537,5.078013,2.072015,4.300707,1.516242,0.499440,4.965388,0.118681,3.058459,0.647673,0.000272,0.332327,0.041177,28.253151,1.590596,19.751454,16.898277,4.288633,1.709021,1.393575,4.951272,0.341743
+140.900000,17.580398,5.088008,2.083341,4.289859,1.509640,0.498807,4.997652,0.119079,3.069300,0.647318,0.000274,0.332682,0.041199,28.263582,1.589490,19.752695,16.898214,4.292587,1.709148,1.393170,4.951319,0.337019
+141.000000,17.580383,5.088544,2.105583,4.308164,1.496660,0.502004,4.987759,0.118936,3.067822,0.648720,0.000279,0.331280,0.041177,28.270293,1.590109,19.751584,16.898155,4.295940,1.709286,1.392775,4.951367,0.327757
+141.100000,17.580502,5.078927,2.119393,4.340455,1.488573,0.506345,4.943969,0.118370,3.055175,0.650662,0.000281,0.329338,0.041129,28.268835,1.591726,19.748847,16.898041,4.296244,1.709429,1.392449,4.951415,0.322034
+141.200000,17.580645,5.067544,2.111482,4.357422,1.493314,0.507815,4.906523,0.117902,3.042840,0.651312,0.000279,0.328688,0.041097,28.262051,1.592638,19.746749,16.897857,4.293708,1.709567,1.392195,4.951463,0.325204
+141.300000,17.580672,5.064903,2.088489,4.342611,1.506791,0.504950,4.911772,0.117991,3.042766,0.649974,0.000275,0.330026,0.041113,28.257948,1.591678,19.747127,16.897653,4.291204,1.709695,1.391954,4.951512,0.334720
+141.400000,17.580550,5.073560,2.071768,4.309846,1.516411,0.500445,4.955744,0.118566,3.055300,0.647857,0.000272,0.332143,0.041161,28.262001,1.589494,19.749449,16.897498,4.291605,1.709818,1.391654,4.951560,0.341821
+141.500000,17.580384,5.085645,2.076045,4.288530,1.513874,0.498288,4.999929,0.119121,3.069356,0.646807,0.000273,0.333193,0.041197,28.272244,1.587822,19.751424,16.897413,4.295110,1.709947,1.391284,4.951609,0.340081
+141.600000,17.580313,5.090467,2.097348,4.297089,1.501474,0.500337,5.006810,0.119189,3.073012,0.647685,0.000277,0.332315,0.041191,28.281407,1.587855,19.751189,16.897358,4.299190,1.710088,1.390896,4.951657,0.331178
+141.700000,17.580395,5.083658,2.117481,4.328951,1.489677,0.504958,4.970017,0.118707,3.063034,0.649748,0.000281,0.330252,0.041146,28.282956,1.589379,19.748729,16.897265,4.300775,1.710237,1.390561,4.951707,0.322842
+141.800000,17.580556,5.070949,2.118009,4.356138,1.489440,0.508022,4.922241,0.118102,3.048132,0.651125,0.000281,0.328875,0.041101,28.276883,1.590857,19.745982,16.897096,4.298898,1.710385,1.390310,4.951756,0.322551
+141.900000,17.580643,5.063852,2.097418,4.352814,1.501592,0.506554,4.908954,0.117953,3.042416,0.650436,0.000277,0.329564,0.041099,28.270388,1.590631,19.745347,16.896881,4.295758,1.710522,1.390100,4.951805,0.330990
+142.000000,17.580566,5.069076,2.074760,4.321898,1.514715,0.501939,4.943596,0.118415,3.051597,0.648282,0.000272,0.331718,0.041141,28.271155,1.588652,19.747274,16.896694,4.294790,1.710651,1.389851,4.951855,0.340525
+142.100000,17.580391,5.081852,2.070548,4.291711,1.517064,0.498365,4.995335,0.119074,3.067414,0.646587,0.000272,0.333413,0.041189,28.280078,1.586528,19.749783,16.896580,4.297405,1.710782,1.389523,4.951904,0.342388
+142.200000,17.580266,5.090784,2.088000,4.288412,1.506922,0.498885,5.019922,0.119369,3.076284,0.646767,0.000275,0.333233,0.041201,28.290961,1.585877,19.750517,16.896520,4.301824,1.710923,1.389151,4.951954,0.335079
+142.300000,17.580296,5.088001,2.112267,4.315399,1.492731,0.503166,4.996095,0.119047,3.070644,0.648671,0.000280,0.331329,0.041166,28.295861,1.587055,19.748666,16.896446,4.304691,1.711076,1.388808,4.952004,0.325002
+142.400000,17.580453,5.075633,2.121959,4.349874,1.487073,0.507536,4.944050,0.118381,3.055135,0.650637,0.000282,0.329363,0.041113,28.291732,1.588895,19.745578,16.896299,4.303903,1.711232,1.388549,4.952055,0.320968
+142.500000,17.580592,5.064616,2.107122,4.359910,1.495899,0.507860,4.912118,0.117990,3.044015,0.650774,0.000278,0.329226,0.041090,28.283788,1.589479,19.743885,16.896085,4.300602,1.711379,1.388358,4.952105,0.326979
+142.600000,17.580577,5.065230,2.081055,4.335553,1.511102,0.503781,4.931414,0.118260,3.048127,0.648880,0.000273,0.331120,0.041120,28.281028,1.587979,19.745058,16.895870,4.298327,1.711514,1.388155,4.952155,0.337842
+142.700000,17.580415,5.076979,2.067847,4.299546,1.518646,0.499101,4.984649,0.118947,3.063783,0.646686,0.000271,0.333314,0.041174,28.287517,1.585599,19.747797,16.895723,4.299671,1.711647,1.387877,4.952206,0.343507
+142.800000,17.580247,5.089256,2.078686,4.283594,1.512329,0.497873,5.025592,0.119454,3.077261,0.646067,0.000274,0.333933,0.041205,28.299064,1.584243,19.749480,16.895648,4.303939,1.711788,1.387529,4.952256,0.338985
+142.900000,17.580213,5.091295,2.104132,4.301531,1.497498,0.501188,5.019431,0.119354,3.077178,0.647530,0.000278,0.332470,0.041185,28.307205,1.584853,19.748513,16.895586,4.307902,1.711943,1.387182,4.952307,0.328370
+143.000000,17.580342,5.081067,2.122397,4.338941,1.486782,0.506339,4.970496,0.118721,3.063309,0.649844,0.000282,0.330156,0.041130,28.306090,1.586782,19.745473,16.895467,4.308517,1.712104,1.386909,4.952358,0.320821
+143.100000,17.580517,5.067342,2.116172,4.362299,1.490549,0.508611,4.922787,0.118122,3.047928,0.650871,0.000280,0.329129,0.041089,28.297995,1.588128,19.742842,16.895265,4.305614,1.712260,1.386722,4.952409,0.323279
+143.200000,17.580572,5.062709,2.090215,4.349007,1.505802,0.505753,4.922055,0.118138,3.045758,0.649550,0.000275,0.330450,0.041101,28.291954,1.587358,19.742960,16.895032,4.302301,1.712403,1.386558,4.952460,0.333983
+143.300000,17.580448,5.071594,2.068721,4.311560,1.518177,0.500482,4.969552,0.118760,3.059035,0.647095,0.000271,0.332905,0.041154,28.295065,1.584991,19.745539,16.894849,4.302115,1.712539,1.386332,4.952511,0.343102
+143.400000,17.580254,5.085878,2.070688,4.283734,1.516961,0.497484,5.023131,0.119435,3.075823,0.645669,0.000272,0.334331,0.041201,28.306001,1.582999,19.748024,16.894749,4.305699,1.712680,1.386020,4.952562,0.342351
+143.500000,17.580155,5.092954,2.093932,4.289309,1.503456,0.499292,5.037293,0.119593,3.081864,0.646444,0.000277,0.333556,0.041201,28.316793,1.582876,19.748126,16.894691,4.310390,1.712834,1.385677,4.952614,0.332612
+143.600000,17.580233,5.086537,2.118857,4.324465,1.488847,0.504531,4.999083,0.119090,3.071835,0.648793,0.000281,0.331207,0.041152,28.319404,1.584590,19.745542,16.894599,4.312543,1.712998,1.385386,4.952665,0.322296
+143.700000,17.580421,5.071872,2.123018,4.358926,1.486468,0.508605,4.941383,0.118357,3.054160,0.650635,0.000282,0.329365,0.041097,28.312642,1.586526,19.742259,16.894421,4.310602,1.713161,1.385191,4.952717,0.320514
+143.800000,17.580544,5.062108,2.101222,4.360117,1.499378,0.507570,4.918417,0.118086,3.045331,0.650158,0.000277,0.329842,0.041087,28.304110,1.586654,19.741152,16.894182,4.306717,1.713313,1.385052,4.952768,0.329400
+143.900000,17.580481,5.066446,2.073567,4.326600,1.515421,0.502402,4.952573,0.118546,3.053983,0.647764,0.000272,0.332236,0.041131,28.303241,1.584622,19.743134,16.893965,4.304928,1.713454,1.384878,4.952820,0.341012
+144.000000,17.580284,5.080905,2.065279,4.289396,1.520097,0.497844,5.012829,0.119315,3.072144,0.645628,0.000271,0.334372,0.041189,28.312207,1.582160,19.746142,16.893832,4.307316,1.713594,1.384611,4.952871,0.344624
+144.100000,17.580125,5.092561,2.082888,4.280639,1.509879,0.497758,5.047434,0.119735,3.084108,0.645539,0.000274,0.334461,0.041210,28.324626,1.581221,19.747377,16.893767,4.312223,1.713745,1.384284,4.952923,0.337233
+144.200000,17.580137,5.091245,2.111465,4.308265,1.493186,0.502327,5.026623,0.119448,3.079733,0.647579,0.000280,0.332421,0.041176,28.331177,1.582430,19.745625,16.893697,4.315830,1.713911,1.383978,4.952975,0.325349
+144.300000,17.580310,5.077737,2.126286,4.349574,1.484493,0.507738,4.966978,0.118682,3.062297,0.650022,0.000282,0.329978,0.041113,28.327184,1.584674,19.742102,16.893550,4.315325,1.714080,1.383763,4.953027,0.319221
+144.400000,17.580489,5.063795,2.112569,4.366739,1.492698,0.508913,4.922913,0.118137,3.047492,0.650558,0.000279,0.329442,0.041080,28.317464,1.585742,19.739785,16.893320,4.311485,1.714240,1.383634,4.953079,0.324733
+144.500000,17.580502,5.062369,2.082252,4.342841,1.510429,0.504654,4.936909,0.118343,3.049623,0.648597,0.000274,0.331403,0.041107,28.312515,1.584372,19.740752,16.893077,4.308256,1.714386,1.383505,4.953131,0.337320
+144.600000,17.580331,5.074866,2.063575,4.300474,1.521110,0.498991,4.996046,0.119109,3.066716,0.645961,0.000270,0.334039,0.041169,28.318237,1.581704,19.743884,16.892905,4.309036,1.714527,1.383292,4.953183,0.345315
+144.700000,17.580127,5.089934,2.072460,4.277120,1.515918,0.496838,5.048415,0.119761,3.083576,0.644928,0.000272,0.335072,0.041211,28.330916,1.579961,19.746175,16.892821,4.313547,1.714675,1.382991,4.953235,0.341622
+144.800000,17.580063,5.094415,2.100938,4.292598,1.499353,0.500024,5.049703,0.119752,3.086012,0.646337,0.000278,0.333663,0.041197,28.341052,1.580427,19.745540,16.892765,4.318301,1.714839,1.382678,4.953287,0.329708
+144.900000,17.580193,5.084185,2.125050,4.335042,1.485189,0.506048,4.997226,0.119070,3.071526,0.649050,0.000282,0.330950,0.041136,28.340963,1.582633,19.742259,16.892653,4.319530,1.715011,1.382439,4.953339,0.319760
+145.000000,17.580405,5.067807,2.122409,4.367123,1.486854,0.509488,4.936927,0.118310,3.052530,0.650615,0.000281,0.329385,0.041082,28.331724,1.584526,19.738955,16.892444,4.316419,1.715179,1.382303,4.953391,0.320736
+145.100000,17.580500,5.060175,2.093986,4.357908,1.503620,0.506943,4.926095,0.118199,3.047011,0.649453,0.000276,0.330547,0.041087,28.323226,1.584091,19.738596,16.892187,4.312164,1.715332,1.382207,4.953443,0.332393
+145.200000,17.580384,5.068540,2.066359,4.316093,1.519552,0.500869,4.975199,0.118848,3.060338,0.646641,0.000271,0.333359,0.041144,28.324708,1.581565,19.741359,16.891976,4.311103,1.715475,1.382049,4.953495,0.344089
+145.300000,17.580159,5.085189,2.064192,4.279824,1.520695,0.496725,5.039876,0.119665,3.080263,0.644698,0.000271,0.335302,0.041202,28.336081,1.579140,19.744475,16.891861,4.314586,1.715621,1.381789,4.953547,0.345113
+145.400000,17.580020,5.095415,2.088515,4.279841,1.506597,0.497958,5.065209,0.119962,3.089816,0.645217,0.000276,0.334783,0.041212,28.348882,1.578707,19.745122,16.891807,4.319974,1.715781,1.381480,4.953599,0.334887
+145.500000,17.580083,5.090293,2.119045,4.317093,1.488715,0.503718,5.028658,0.119476,3.080741,0.647805,0.000281,0.332195,0.041163,28.353314,1.580517,19.742555,16.891727,4.322992,1.715954,1.381215,4.953652,0.322240
+145.600000,17.580297,5.073792,2.128891,4.360362,1.482968,0.509086,4.960316,0.118604,3.060239,0.650239,0.000283,0.329761,0.041096,28.346343,1.582968,19.738676,16.891552,4.321255,1.716128,1.381058,4.953704,0.318142
+145.700000,17.580467,5.060495,2.107270,4.369127,1.495839,0.508896,4.923505,0.118158,3.047105,0.650161,0.000278,0.329839,0.041073,28.335490,1.583619,19.736866,16.891296,4.316612,1.716289,1.380980,4.953756,0.326891
+145.800000,17.580430,5.062891,2.073885,4.334527,1.515260,0.503301,4.953708,0.118573,3.054092,0.647586,0.000272,0.332414,0.041117,28.332229,1.581628,19.738738,16.891050,4.313729,1.716435,1.380874,4.953808,0.340855
+145.900000,17.580216,5.078775,2.059555,4.289098,1.523386,0.497526,5.022712,0.119457,3.074538,0.644900,0.000270,0.335100,0.041185,28.340710,1.578760,19.742297,16.890896,4.315615,1.716579,1.380666,4.953860,0.347059
+146.000000,17.580013,5.093856,2.075820,4.272163,1.513960,0.496455,5.070821,0.120047,3.090560,0.644367,0.000273,0.335633,0.041219,28.354782,1.577375,19.744232,16.890830,4.320974,1.716734,1.380374,4.953912,0.340220
+146.100000,17.579992,5.095084,2.108773,4.298242,1.494751,0.501066,5.057165,0.119847,3.088718,0.646430,0.000279,0.333570,0.041190,28.363693,1.578473,19.742780,16.890774,4.325565,1.716905,1.380090,4.953965,0.326476
+146.200000,17.580174,5.081008,2.130536,4.346736,1.481946,0.507653,4.991141,0.118996,3.069881,0.649408,0.000283,0.330592,0.041118,28.360575,1.581107,19.738862,16.890639,4.325683,1.717083,1.379903,4.954017,0.317519
+146.300000,17.580400,5.063615,2.120040,4.374012,1.488284,0.510129,4.931623,0.118253,3.050529,0.650545,0.000281,0.329455,0.041069,28.349134,1.582813,19.735726,16.890402,4.321436,1.717252,1.379822,4.954069,0.321676
+146.400000,17.580456,5.058945,2.085667,4.353258,1.508470,0.505991,4.935664,0.118336,3.049232,0.648655,0.000274,0.331345,0.041090,28.341306,1.581732,19.736247,16.890133,4.317052,1.717404,1.379759,4.954121,0.335863
+146.500000,17.580286,5.071468,2.059734,4.304408,1.523328,0.499238,4.999142,0.119164,3.067157,0.645530,0.000270,0.334470,0.041160,28.345509,1.578776,19.739727,16.889934,4.316933,1.717547,1.379609,4.954173,0.346937
+146.600000,17.580042,5.089683,2.064663,4.271190,1.520400,0.495788,5.065417,0.119993,3.088029,0.643909,0.000271,0.336091,0.041216,28.359125,1.576506,19.742787,16.889842,4.321521,1.717697,1.379351,4.954225,0.344938
+146.700000,17.579933,5.097696,2.095433,4.281338,1.502555,0.498482,5.078721,0.120133,3.094321,0.645100,0.000277,0.334900,0.041211,28.371782,1.576656,19.742719,16.889798,4.327207,1.717863,1.379058,4.954277,0.332012
+146.800000,17.580051,5.088424,2.126601,4.327825,1.484244,0.505326,5.025799,0.119440,3.080263,0.648185,0.000283,0.331815,0.041148,28.373596,1.579052,19.739334,16.889704,4.329404,1.718042,1.378836,4.954329,0.319155
+146.900000,17.580299,5.069355,2.129983,4.370851,1.482344,0.510319,4.951306,0.118496,3.057358,0.650460,0.000283,0.329540,0.041078,28.363650,1.581590,19.735247,16.889500,4.326360,1.718217,1.378735,4.954381,0.317674
+147.000000,17.580450,5.057605,2.100362,4.369206,1.499910,0.508538,4.925315,0.118195,3.047005,0.649662,0.000277,0.330338,0.041069,28.352231,1.581690,19.734133,16.889223,4.321090,1.718377,1.378699,4.954433,0.329727
+147.100000,17.580357,5.064320,2.065405,4.324256,1.520127,0.501729,4.972605,0.118827,3.059228,0.646527,0.000270,0.333473,0.041129,28.351209,1.579084,19.736927,16.888983,4.318814,1.718522,1.378608,4.954485,0.344468
+147.200000,17.580103,5.083224,2.056843,4.277782,1.524908,0.496134,5.049299,0.119801,3.082430,0.643925,0.000269,0.336075,0.041201,28.362508,1.576130,19.740768,16.888851,4.321913,1.718667,1.378398,4.954537,0.348249
+147.300000,17.579912,5.097511,2.080751,4.269112,1.511090,0.496366,5.090054,0.120291,3.096688,0.643993,0.000274,0.336007,0.041225,28.377557,1.575206,19.742192,16.888804,4.328001,1.718827,1.378113,4.954589,0.338159
+147.400000,17.579943,5.094888,2.117244,4.306245,1.489755,0.502411,5.059658,0.119878,3.089964,0.646712,0.000281,0.333288,0.041179,28.384665,1.576965,19.739856,16.888745,4.332191,1.719003,1.377860,4.954640,0.323001
+147.500000,17.580175,5.077053,2.135041,4.359219,1.479280,0.509297,4.981337,0.118875,3.067030,0.649835,0.000284,0.330165,0.041099,28.378255,1.579949,19.735388,16.888585,4.331031,1.719184,1.377724,4.954692,0.315678
+147.600000,17.580404,5.059448,2.115819,4.379192,1.490807,0.510479,4.926297,0.118196,3.048403,0.650393,0.000280,0.329607,0.041059,28.364988,1.581315,19.732623,16.888321,4.325725,1.719351,1.377693,4.954744,0.323374
+147.700000,17.580411,5.058530,2.076500,4.346163,1.513780,0.504730,4.947550,0.118502,3.052140,0.647764,0.000272,0.332236,0.041097,28.358484,1.579528,19.734130,16.888046,4.321474,1.719500,1.377654,4.954796,0.339720
+147.800000,17.580187,5.075192,2.053947,4.291869,1.526606,0.497558,5.024259,0.119492,3.074407,0.644444,0.000269,0.335556,0.041177,28.365693,1.576226,19.738231,16.887867,4.322489,1.719643,1.377503,4.954847,0.349446
+147.900000,17.579933,5.094259,2.066760,4.263815,1.519171,0.495072,5.089119,0.120295,3.095344,0.643271,0.000271,0.336729,0.041227,28.381308,1.574230,19.741067,16.887799,4.328154,1.719795,1.377243,4.954898,0.344069
+148.000000,17.579864,5.099295,2.103512,4.285249,1.497818,0.499340,5.087787,0.120246,3.097561,0.645182,0.000278,0.334818,0.041207,28.393254,1.575029,19.740173,16.887763,4.333928,1.719967,1.376969,4.954950,0.328669
+148.100000,17.580041,5.085635,2.133856,4.340241,1.479939,0.507109,5.018346,0.119346,3.078365,0.648694,0.000284,0.331306,0.041130,28.391990,1.577982,19.735986,16.887652,4.335080,1.720149,1.376791,4.955002,0.316205
+148.200000,17.580316,5.064555,2.129361,4.380587,1.482744,0.511373,4.940758,0.118369,3.053887,0.650648,0.000283,0.329352,0.041061,28.379184,1.580467,19.731866,16.887419,4.330694,1.720324,1.376744,4.955053,0.317896
+148.300000,17.580435,5.055278,2.091984,4.366785,1.504819,0.507828,4.928997,0.118255,3.047408,0.649048,0.000275,0.330952,0.041070,28.367827,1.579899,19.731622,16.887127,4.325011,1.720479,1.376742,4.955104,0.333197
+148.400000,17.580280,5.066667,2.057126,4.312308,1.524847,0.499988,4.993588,0.119106,3.065043,0.645435,0.000269,0.334565,0.041144,28.369531,1.576715,19.735316,16.886898,4.323593,1.720621,1.376656,4.955155,0.348027
+148.500000,17.579995,5.088088,2.055583,4.266919,1.525598,0.494864,5.075420,0.120136,3.090278,0.643053,0.000269,0.336947,0.041217,28.383604,1.573793,19.739280,16.886794,4.327969,1.720767,1.376439,4.955206,0.348819
+148.600000,17.579825,5.100761,2.087169,4.268181,1.507351,0.496590,5.105809,0.120488,3.101863,0.643807,0.000275,0.336193,0.041228,28.399158,1.573422,19.740049,16.886764,4.334639,1.720931,1.376160,4.955257,0.335480
+148.700000,17.579915,5.093779,2.126097,4.316498,1.484514,0.504033,5.057285,0.119846,3.089763,0.647165,0.000283,0.332835,0.041165,28.403894,1.575859,19.736786,16.886698,4.338185,1.721111,1.375940,4.955308,0.319389
+148.800000,17.580194,5.072418,2.138287,4.372042,1.477368,0.510910,4.968528,0.118716,3.063169,0.650294,0.000285,0.329706,0.041079,28.394032,1.579092,19.731882,16.886512,4.335612,1.721291,1.375856,4.955360,0.314345
+148.900000,17.580415,5.055485,2.109771,4.382299,1.494399,0.510501,4.921797,0.118150,3.046419,0.650135,0.000279,0.329865,0.041051,28.379423,1.579968,19.729695,16.886223,4.329371,1.721455,1.375870,4.955410,0.325830
+149.000000,17.580364,5.059003,2.066814,4.336790,1.519351,0.503195,4.961947,0.118700,3.055817,0.646789,0.000271,0.333211,0.041108,28.374865,1.577446,19.732255,16.885950,4.325523,1.721599,1.375846,4.955461,0.343835
+149.100000,17.580089,5.079587,2.049244,4.278952,1.529254,0.495892,5.050107,0.119827,3.081962,0.643409,0.000268,0.336591,0.041195,28.385244,1.573905,19.736847,16.885797,4.327824,1.721740,1.375687,4.955512,0.351503
+149.200000,17.579835,5.098734,2.070419,4.258005,1.517044,0.494608,5.110517,0.120565,3.102063,0.642791,0.000272,0.337209,0.041237,28.402520,1.572291,19.739299,16.885754,4.334488,1.721895,1.375423,4.955562,0.342537
+149.300000,17.579814,5.100130,2.112484,4.291525,1.492537,0.500514,5.092372,0.120300,3.099509,0.645449,0.000280,0.334551,0.041200,28.413192,1.573788,19.737492,16.885723,4.340132,1.722070,1.375169,4.955613,0.324978
+149.400000,17.580051,5.082000,2.140455,4.353895,1.476013,0.509001,5.006910,0.119201,3.075206,0.649293,0.000285,0.330707,0.041109,28.408469,1.577245,19.732551,16.885592,4.340036,1.722253,1.375037,4.955663,0.313532
+149.500000,17.580344,5.059618,2.126886,4.388971,1.484245,0.512174,4.929777,0.118238,3.050154,0.650765,0.000282,0.329235,0.041046,28.393066,1.579525,19.728594,16.885330,4.334333,1.722425,1.375040,4.955714,0.318869
+149.600000,17.580419,5.053716,2.082498,4.361784,1.510340,0.506778,4.935218,0.118349,3.048546,0.648317,0.000273,0.331683,0.041073,28.382460,1.578199,19.729367,16.885028,4.328495,1.722575,1.375064,4.955764,0.337162
+149.700000,17.580202,5.069872,2.049574,4.299296,1.529124,0.498170,5.016242,0.119404,3.071439,0.644347,0.000268,0.335653,0.041162,28.387250,1.574515,19.733878,16.884818,4.328159,1.722713,1.374975,4.955814,0.351302
+149.800000,17.579894,5.093087,2.055944,4.257208,1.525364,0.493802,5.100119,0.120450,3.097799,0.642316,0.000269,0.337684,0.041232,28.403873,1.571752,19.737788,16.884742,4.333796,1.722859,1.374747,4.955864,0.348692
+149.900000,17.579757,5.103362,2.094772,4.269602,1.502909,0.497140,5.117481,0.120633,3.105883,0.643809,0.000277,0.336191,0.041228,28.419373,1.572004,19.737787,16.884728,4.340843,1.723025,1.374476,4.955914,0.332318
+150.000000,17.579908,5.091750,2.134732,4.328510,1.479381,0.505846,5.050476,0.119758,3.088201,0.647743,0.000284,0.332257,0.041148,28.421252,1.575095,19.733604,16.884652,4.343513,1.723208,1.374291,4.955964,0.315888
+150.100000,17.580228,5.067388,2.139822,4.384207,1.476478,0.512356,4.954227,0.118538,3.058725,0.650717,0.000285,0.329283,0.041059,28.408006,1.578444,19.728430,16.884437,4.339476,1.723386,1.374259,4.956014,0.313700
+150.200000,17.580427,5.052109,2.102134,4.382741,1.498906,0.510143,4.919579,0.118134,3.045049,0.649742,0.000277,0.330258,0.041047,28.392720,1.578696,19.727016,16.884129,4.332519,1.723544,1.374309,4.956064,0.328960
+150.300000,17.580313,5.060450,2.057382,4.325662,1.524739,0.501486,4.978832,0.118927,3.060306,0.645769,0.000269,0.334231,0.041122,28.390639,1.575477,19.730609,16.883865,4.329348,1.723682,1.374290,4.956113,0.347879
+150.400000,17.579995,5.084415,2.046100,4.266549,1.531008,0.494361,5.075691,0.120156,3.089542,0.642473,0.000267,0.337527,0.041213,28.404129,1.571827,19.735520,16.883740,4.332995,1.723821,1.374119,4.956163,0.352893
+150.500000,17.579751,5.102784,2.075617,4.254391,1.514028,0.494467,5.128557,0.120790,3.107863,0.642495,0.000273,0.337505,0.041245,28.422573,1.570690,19.737438,16.883722,4.340500,1.723977,1.373852,4.956212,0.340356
+150.600000,17.579786,5.100012,2.121816,4.300092,1.487020,0.501969,5.092192,0.120295,3.100042,0.645879,0.000282,0.334121,0.041189,28.431381,1.572897,19.734677,16.883692,4.345757,1.724155,1.373621,4.956261,0.321164
+150.700000,17.580080,5.077665,2.145779,4.367920,1.472842,0.510866,4.992593,0.119020,3.071071,0.649918,0.000286,0.330082,0.041088,28.423039,1.576761,19.729096,16.883538,4.344280,1.724337,1.373535,4.956311,0.311379
+150.800000,17.580379,5.054881,2.122524,4.395237,1.486865,0.512636,4.919861,0.118120,3.046625,0.650763,0.000281,0.329237,0.041034,28.405538,1.578683,19.725512,16.883249,4.337387,1.724504,1.373584,4.956360,0.320611
+150.900000,17.580400,5.053035,2.072450,4.354460,1.516148,0.505448,4.944187,0.118477,3.050526,0.647491,0.000272,0.332509,0.041081,28.396311,1.576566,19.727371,16.882943,4.331666,1.724647,1.373626,4.956409,0.341402
+151.000000,17.580124,5.073772,2.043021,4.285777,1.532813,0.496349,5.039959,0.119712,3.078239,0.643292,0.000267,0.336708,0.041180,28.404353,1.572486,19.732577,16.882758,4.332558,1.724780,1.373526,4.956458,0.354166
+151.100000,17.579802,5.098084,2.057820,4.248824,1.524266,0.492962,5.123099,0.120740,3.104894,0.641717,0.000270,0.338283,0.041246,28.423247,1.569985,19.736281,16.882712,4.339402,1.724926,1.373287,4.956506,0.347915
+151.200000,17.579706,5.105298,2.103386,4.273274,1.497859,0.497998,5.125196,0.120726,3.108777,0.643984,0.000279,0.336016,0.041225,28.438171,1.570913,19.735417,16.882711,4.346627,1.725095,1.373025,4.956555,0.328755
+151.300000,17.579921,5.088878,2.143032,4.342026,1.474428,0.507816,5.039704,0.119619,3.085409,0.648426,0.000286,0.331574,0.041129,28.436783,1.574628,19.730335,16.882621,4.348219,1.725277,1.372877,4.956604,0.312540
+151.400000,17.580274,5.062056,2.139741,4.395585,1.476559,0.513624,4.938899,0.118348,3.053846,0.651095,0.000285,0.328905,0.041040,28.420289,1.577965,19.725055,16.882377,4.342698,1.725452,1.372895,4.956652,0.313701
+151.500000,17.580441,5.049256,2.093212,4.380940,1.504141,0.509470,4.919303,0.118143,3.044213,0.649238,0.000275,0.330762,0.041046,28.404902,1.577491,19.724568,16.882053,4.335225,1.725602,1.372976,4.956701,0.332647
+151.600000,17.580260,5.062712,2.048146,4.313080,1.529978,0.499633,4.997733,0.119178,3.065449,0.644715,0.000267,0.335285,0.041138,28.405702,1.573612,19.729167,16.881804,4.332945,1.725734,1.372955,4.956749,0.351876
+151.700000,17.579904,5.089606,2.044222,4.254553,1.532041,0.492937,5.101045,0.120479,3.097133,0.641619,0.000267,0.338381,0.041231,28.422257,1.569958,19.734255,16.881711,4.337993,1.725870,1.372767,4.956797,0.353738
+151.800000,17.579681,5.106488,2.082109,4.252606,1.510254,0.494597,5.143782,0.120978,3.112899,0.642354,0.000275,0.337646,0.041250,28.441467,1.569377,19.735519,16.881716,4.346211,1.726028,1.372497,4.956845,0.337637
+151.900000,17.579778,5.099113,2.131554,4.310681,1.481236,0.503680,5.087907,0.120236,3.099362,0.646457,0.000284,0.333543,0.041176,28.447910,1.572314,19.731759,16.881684,4.350870,1.726207,1.372291,4.956893,0.317211
+152.000000,17.580125,5.072715,2.150040,4.382351,1.470308,0.512720,4.975673,0.118806,3.066056,0.650571,0.000287,0.329429,0.041066,28.435772,1.576503,19.725629,16.881504,4.347883,1.726387,1.372252,4.956941,0.309652
+152.100000,17.580420,5.050291,2.116488,4.399703,1.490468,0.512806,4.910762,0.118014,3.043236,0.650660,0.000280,0.329340,0.041024,28.416574,1.577929,19.722605,16.881190,4.339900,1.726546,1.372343,4.956989,0.323044
+152.200000,17.580379,5.053145,2.061860,4.345045,1.522226,0.503866,4.955624,0.118635,3.053256,0.646579,0.000270,0.333421,0.041092,28.409287,1.574990,19.725621,16.880887,4.334536,1.726681,1.372394,4.957036,0.345915
+152.300000,17.580046,5.078326,2.037390,4.271798,1.535964,0.494525,5.064717,0.120032,3.085424,0.642266,0.000266,0.337734,0.041200,28.420760,1.570604,19.731413,16.880730,4.336803,1.726810,1.372279,4.957083,0.356646
+152.400000,17.579720,5.103047,2.061141,4.241778,1.522340,0.492342,5.144389,0.121006,3.111570,0.641248,0.000270,0.338752,0.041258,28.441651,1.568465,19.734765,16.880715,4.344800,1.726955,1.372027,4.957130,0.346519
+152.500000,17.579673,5.106555,2.112922,4.279160,1.492243,0.499157,5.129043,0.120769,3.110570,0.644325,0.000280,0.335675,0.041219,28.455478,1.570121,19.732950,16.880724,4.352004,1.727125,1.371776,4.957178,0.324835
+152.600000,17.579954,5.085183,2.150875,4.356921,1.469732,0.509920,5.025198,0.119433,3.081444,0.649200,0.000288,0.330800,0.041107,28.450426,1.574428,19.726993,16.880617,4.352321,1.727307,1.371668,4.957225,0.309393
+152.700000,17.580333,5.056486,2.137938,4.405957,1.477672,0.514684,4.922960,0.118151,3.048650,0.651409,0.000284,0.328591,0.041022,28.430856,1.577616,19.721779,16.880343,4.345310,1.727476,1.371734,4.957272,0.314391
+152.800000,17.580456,5.047030,2.083029,4.376712,1.510075,0.508469,4.921439,0.118183,3.044057,0.648609,0.000273,0.331391,0.041048,28.415979,1.576314,19.722374,16.880008,4.337539,1.727618,1.371839,4.957319,0.336897
+152.900000,17.580205,5.065816,2.039300,4.299186,1.534962,0.497659,5.018714,0.119454,3.071275,0.643632,0.000266,0.336368,0.041156,28.420048,1.571832,19.727929,16.879779,4.336370,1.727743,1.371808,4.957365,0.355737
+153.000000,17.579819,5.095102,2.043710,4.243160,1.532299,0.491646,5.126028,0.120795,3.104698,0.640855,0.000267,0.339145,0.041248,28.439573,1.568284,19.733046,16.879720,4.342852,1.727876,1.371601,4.957411,0.353992
+153.100000,17.579626,5.109764,2.089901,4.252825,1.505712,0.495019,5.155980,0.121127,3.117111,0.642374,0.000276,0.337626,0.041252,28.459099,1.568335,19.733533,16.879747,4.351633,1.728034,1.371329,4.957458,0.334386
+153.200000,17.579789,5.097352,2.141547,4.323325,1.475271,0.505642,5.079409,0.120124,3.097424,0.647175,0.000286,0.332825,0.041159,28.462655,1.572015,19.728737,16.879708,4.355470,1.728214,1.371151,4.957504,0.313182
+153.300000,17.580188,5.067163,2.152987,4.396937,1.468564,0.514520,4.956477,0.118564,3.060238,0.651229,0.000288,0.328771,0.041042,28.446594,1.576433,19.722170,16.879500,4.350856,1.728390,1.371161,4.957551,0.308450
+153.400000,17.580467,5.045975,2.108711,4.402035,1.495082,0.512647,4.903128,0.117928,3.040187,0.650434,0.000278,0.329566,0.041017,28.426201,1.577217,19.719907,16.879163,4.341920,1.728541,1.371289,4.957597,0.326208
+153.500000,17.580357,5.054123,2.050936,4.333596,1.528447,0.502051,4.969749,0.118828,3.056820,0.645583,0.000268,0.334417,0.041105,28.421414,1.573447,19.724122,16.878869,4.337170,1.728667,1.371342,4.957643,0.350617
+153.600000,17.579969,5.083484,2.032836,4.257598,1.538495,0.492731,5.090351,0.120361,3.092949,0.641281,0.000265,0.338719,0.041220,28.436428,1.568859,19.730371,16.878744,4.340936,1.728791,1.371206,4.957688,0.358670
+153.700000,17.579648,5.107889,2.065920,4.236246,1.519576,0.491963,5.163781,0.121247,3.117764,0.640916,0.000271,0.339084,0.041268,28.459000,1.567178,19.733229,16.878760,4.350008,1.728935,1.370940,4.957734,0.344503
+153.800000,17.579659,5.107070,2.123295,4.287328,1.486104,0.500623,5.128902,0.120761,3.111222,0.644830,0.000283,0.335170,0.041210,28.471184,1.569609,19.730380,16.878776,4.356979,1.729107,1.370703,4.957779,0.320602
+153.900000,17.580008,5.080675,2.158062,4.373014,1.465417,0.512128,5.007197,0.119202,3.076356,0.650048,0.000289,0.329952,0.041084,28.462101,1.574462,19.723590,16.878647,4.355829,1.729287,1.370638,4.957825,0.306521
+154.000000,17.580403,5.050785,2.134303,4.414989,1.479879,0.515492,4.907015,0.117954,3.043315,0.651636,0.000283,0.328364,0.041006,28.439713,1.577353,19.718633,16.878343,4.347353,1.729449,1.370750,4.957871,0.315819
+154.100000,17.580470,5.045520,2.071781,4.370067,1.516580,0.507151,4.926266,0.118259,3.044686,0.647859,0.000271,0.332141,0.041054,28.425978,1.575141,19.720445,16.878002,4.339526,1.729581,1.370872,4.957916,0.341639
+154.200000,17.580149,5.069729,2.031041,4.284237,1.539584,0.495604,5.041614,0.119753,3.077741,0.642536,0.000264,0.337464,0.041176,28.433636,1.570130,19.726879,16.877799,4.339669,1.729698,1.370825,4.957960,0.359375
+154.300000,17.579741,5.100798,2.044619,4.232623,1.531752,0.490519,5.150334,0.121100,3.112145,0.640192,0.000267,0.339808,0.041265,28.455975,1.566795,19.731874,16.877776,4.347589,1.729829,1.370597,4.958005,0.353629
+154.400000,17.579588,5.112519,2.098913,4.255175,1.500439,0.495747,5.164921,0.121233,3.120425,0.642556,0.000278,0.337444,0.041251,28.475335,1.567550,19.731472,16.877822,4.356765,1.729988,1.370324,4.958050,0.330648
+154.500000,17.579823,5.094714,2.151588,4.337901,1.469248,0.507831,5.066806,0.119960,3.094244,0.648020,0.000288,0.331980,0.041138,28.475491,1.571975,19.725616,16.877774,4.359553,1.730166,1.370177,4.958095,0.309164
+154.600000,17.580267,5.061112,2.154413,4.411275,1.467739,0.516207,4.935636,0.118301,3.053789,0.651861,0.000288,0.328139,0.041019,28.455476,1.576508,19.718751,16.877534,4.353227,1.730338,1.370237,4.958139,0.307849
+154.700000,17.580518,5.042073,2.099289,4.402031,1.500635,0.512143,4.897513,0.117868,3.037660,0.650074,0.000276,0.329926,0.041013,28.434454,1.576512,19.717446,16.877177,4.343512,1.730479,1.370397,4.958184,0.330076
+154.800000,17.580332,5.055993,2.039948,4.320328,1.534657,0.500040,4.986544,0.119053,3.061224,0.644519,0.000266,0.335481,0.041122,28.432677,1.571928,19.722866,16.876897,4.339627,1.730596,1.370444,4.958228,0.355396
+154.900000,17.579896,5.089148,2.029496,4.243496,1.540335,0.491007,5.116522,0.120693,3.100715,0.640352,0.000264,0.339648,0.041241,28.451266,1.567248,19.729429,16.876808,4.344986,1.730714,1.370283,4.958271,0.360169
+155.000000,17.579590,5.112492,2.072127,4.232440,1.515985,0.491849,5.180937,0.121457,3.123377,0.640727,0.000273,0.339273,0.041277,28.475145,1.566113,19.731659,16.876854,4.355025,1.730858,1.370004,4.958315,0.341888
+155.100000,17.579666,5.106781,2.134325,4.297770,1.479539,0.502388,5.124688,0.120702,3.110692,0.645490,0.000285,0.334510,0.041197,28.485131,1.569358,19.727706,16.876873,4.361540,1.731030,1.369784,4.958359,0.316136
+155.200000,17.580081,5.075404,2.164328,4.389976,1.461649,0.514386,4.986133,0.118933,3.070252,0.650941,0.000290,0.329059,0.041058,28.471717,1.574695,19.720147,16.876719,4.358750,1.731207,1.369764,4.958403,0.304023
+155.300000,17.580482,5.045105,2.128770,4.422293,1.483213,0.516002,4.891792,0.117768,3.038063,0.651751,0.000282,0.328249,0.040991,28.446880,1.577132,19.715655,16.876386,4.348878,1.731360,1.369921,4.958447,0.318016
+155.400000,17.580484,5.044820,2.059722,4.361056,1.523499,0.505540,4.934027,0.118371,3.046194,0.646994,0.000269,0.333006,0.041064,28.434917,1.573954,19.718787,16.876043,4.341253,1.731482,1.370052,4.958490,0.346778
+155.500000,17.580094,5.074397,2.023597,4.268559,1.543723,0.493512,5.066173,0.120070,3.084775,0.641444,0.000263,0.338556,0.041198,28.446402,1.568507,19.725996,16.875871,4.342886,1.731592,1.369983,4.958533,0.362681
+155.600000,17.579672,5.106574,2.046990,4.223215,1.530377,0.489588,5.173593,0.121389,3.119364,0.639640,0.000268,0.340360,0.041281,28.471334,1.565488,19.730720,16.875885,4.352214,1.731720,1.369732,4.958576,0.352634
+155.700000,17.579567,5.114656,2.109032,4.259763,1.494490,0.496787,5.170367,0.121294,3.122765,0.642900,0.000280,0.337100,0.041248,28.490012,1.567009,19.729326,16.875947,4.361595,1.731880,1.369461,4.958619,0.326478
+155.800000,17.579878,5.091196,2.161430,4.354223,1.463317,0.510214,5.050276,0.119746,3.089850,0.648974,0.000290,0.331026,0.041115,28.486286,1.572170,19.722406,16.875884,4.363113,1.732057,1.369348,4.958662,0.305253
+155.900000,17.580362,5.054682,2.154121,4.424937,1.467953,0.517720,4.913826,0.118026,3.046899,0.652438,0.000287,0.327562,0.040997,28.462388,1.576684,19.715404,16.875612,4.355026,1.732222,1.369458,4.958705,0.307926
+156.000000,17.580572,5.038727,2.088372,4.399534,1.507025,0.511290,4.894425,0.117841,3.035831,0.649572,0.000274,0.330428,0.041013,28.441363,1.575782,19.715244,16.875238,4.344742,1.732353,1.369645,4.958747,0.334604
+156.100000,17.580306,5.058751,2.029184,4.305529,1.540692,0.497881,5.005860,0.119309,3.066440,0.643404,0.000264,0.336596,0.041141,28.443039,1.570432,19.721837,16.874978,4.341963,1.732460,1.369679,4.958789,0.360125
+156.200000,17.579828,5.095207,2.027463,4.229787,1.541439,0.489389,5.142872,0.121026,3.108613,0.639492,0.000264,0.340508,0.041262,28.465156,1.565770,19.728566,16.874928,4.348970,1.732574,1.369491,4.958831,0.361099
+156.300000,17.579547,5.116751,2.079690,4.230509,1.511597,0.492014,5.195581,0.121634,3.128322,0.640684,0.000274,0.339316,0.041283,28.489933,1.565263,19.730042,16.875002,4.359847,1.732717,1.369200,4.958873,0.338713
+156.400000,17.579694,5.105652,2.145826,4.310420,1.472655,0.504435,5.116400,0.120590,3.108967,0.646298,0.000287,0.333702,0.041181,28.497167,1.569351,19.724928,16.875020,4.365677,1.732889,1.369000,4.958916,0.311519
+156.500000,17.580174,5.069443,2.169437,4.407455,1.458577,0.516639,4.962501,0.118631,3.063257,0.651855,0.000291,0.328145,0.041031,28.479198,1.575092,19.716687,16.874837,4.361099,1.733062,1.369027,4.958958,0.301986
+156.600000,17.580570,5.039591,2.121355,4.427571,1.487652,0.516184,4.877921,0.117600,3.033094,0.651737,0.000281,0.328263,0.040980,28.452366,1.576916,19.712874,16.874475,4.349941,1.733205,1.369225,4.959000,0.320993
+156.700000,17.580497,5.044981,2.047142,4.349863,1.530657,0.503673,4.944755,0.118521,3.048614,0.646025,0.000267,0.333975,0.041077,28.442775,1.572745,19.717397,16.874137,4.342781,1.733316,1.369359,4.959041,0.352201
+156.800000,17.580040,5.079727,2.017132,4.252488,1.547291,0.491427,5.092027,0.120402,3.092270,0.640374,0.000262,0.339626,0.041221,28.458239,1.566965,19.725255,16.874000,4.346046,1.733419,1.369263,4.959082,0.365577
+156.900000,17.579614,5.112312,2.050784,4.215131,1.528191,0.488873,5.195476,0.121659,3.126253,0.639205,0.000269,0.340795,0.041295,28.485488,1.564357,19.729565,16.874050,4.356724,1.733545,1.368989,4.959123,0.351025
+157.000000,17.579566,5.116117,2.120100,4.266590,1.487947,0.498136,5.172216,0.121310,3.124092,0.643400,0.000282,0.336600,0.041241,28.502961,1.566699,19.727091,16.874126,4.366111,1.733705,1.368722,4.959164,0.321953
+157.100000,17.579954,5.086835,2.170840,4.372027,1.457622,0.512747,5.030144,0.119486,3.084318,0.650014,0.000292,0.329986,0.041090,28.494920,1.572571,19.719119,16.874044,4.366152,1.733880,1.368648,4.959206,0.301539
+157.200000,17.580470,5.048005,2.152002,4.437533,1.469271,0.519010,4.891728,0.117748,3.039768,0.652935,0.000287,0.327065,0.040975,28.467311,1.576924,19.712163,16.873737,4.356294,1.734037,1.368807,4.959247,0.308727
+157.300000,17.580628,5.036039,2.076199,4.394562,1.514092,0.510105,4.894136,0.117851,3.034807,0.648934,0.000272,0.331066,0.041016,28.446923,1.575011,19.713311,16.873351,4.345671,1.734156,1.369014,4.959287,0.339709
+157.400000,17.580280,5.062349,2.018880,4.289531,1.546423,0.495620,5.027419,0.119591,3.072391,0.642258,0.000262,0.337742,0.041162,28.452409,1.568962,19.721011,16.873116,4.344214,1.734254,1.369030,4.959327,0.364697
+157.500000,17.579767,5.101536,2.026776,4.216755,1.541786,0.487910,5.168997,0.121353,3.116520,0.638714,0.000264,0.341286,0.041282,28.477938,1.564427,19.727756,16.873107,4.352893,1.734363,1.368812,4.959367,0.361437
+157.600000,17.579520,5.120568,2.088491,4.230551,1.506473,0.492465,5.207472,0.121776,3.132521,0.640788,0.000276,0.339212,0.041286,28.503173,1.564617,19.728367,16.873207,4.364456,1.734507,1.368510,4.959408,0.335036
+157.700000,17.579745,5.103675,2.157569,4.325118,1.465585,0.506736,5.104169,0.120428,3.106066,0.647236,0.000289,0.332764,0.041161,28.507129,1.569565,19.722053,16.873220,4.369379,1.734678,1.368334,4.959448,0.306846
+157.800000,17.580286,5.062901,2.173178,4.425033,1.456335,0.518827,4.936931,0.118305,3.055546,0.652758,0.000292,0.327242,0.041004,28.484478,1.575616,19.713239,16.873005,4.362897,1.734845,1.368411,4.959488,0.300487
+157.900000,17.580665,5.034393,2.112164,4.430598,1.493119,0.516022,4.865977,0.117458,3.028600,0.651582,0.000279,0.328418,0.040971,28.456181,1.576673,19.710317,16.872615,4.350601,1.734978,1.368647,4.959528,0.324717
+158.000000,17.580510,5.046029,2.034342,4.336732,1.537874,0.501593,4.958382,0.118707,3.051939,0.644973,0.000264,0.335027,0.041092,28.449503,1.571512,19.716260,16.872287,4.344165,1.735077,1.368775,4.959568,0.357783
+158.100000,17.579990,5.085613,2.011790,4.236369,1.550220,0.489393,5.118768,0.120742,3.100104,0.639343,0.000261,0.340657,0.041244,28.469009,1.565509,19.724626,16.872189,4.349168,1.735173,1.368648,4.959607,0.367990
+158.200000,17.579570,5.117886,2.055953,4.208576,1.525219,0.488396,5.215619,0.121906,3.132700,0.638895,0.000270,0.341105,0.041307,28.498251,1.563400,19.728393,16.872275,4.361109,1.735298,1.368352,4.959646,0.348828
+158.300000,17.579586,5.116842,2.131931,4.275630,1.480912,0.499783,5.170380,0.121278,3.124367,0.644049,0.000284,0.335951,0.041231,28.513989,1.566604,19.724763,16.872360,4.370294,1.735458,1.368093,4.959686,0.317157
+158.400000,17.580053,5.081686,2.179553,4.390980,1.452328,0.515378,5.006826,0.119185,3.077749,0.651115,0.000293,0.328885,0.041062,28.501269,1.573148,19.715777,16.872255,4.368672,1.735630,1.368060,4.959725,0.298119
+158.500000,17.580591,5.041241,2.147988,4.448650,1.471732,0.520027,4.870088,0.117477,3.032625,0.653325,0.000286,0.326675,0.040955,28.470238,1.577185,19.709064,16.871913,4.357079,1.735778,1.368268,4.959764,0.310280
+158.600000,17.580685,5.034097,2.063066,4.387217,1.521654,0.508619,4.896809,0.117900,3.034660,0.648170,0.000269,0.331830,0.041022,28.451120,1.574187,19.711648,16.871519,4.346366,1.735885,1.368489,4.959803,0.345280
+158.700000,17.580256,5.066704,2.009241,4.272689,1.551745,0.493305,5.050846,0.119896,3.078967,0.641101,0.000260,0.338899,0.041184,28.460671,1.567527,19.720361,16.871314,4.346411,1.735973,1.368480,4.959841,0.369015
+158.800000,17.579717,5.108022,2.027410,4.204590,1.541395,0.486590,5.194577,0.121671,3.124335,0.638024,0.000264,0.341976,0.041301,28.489445,1.563216,19.726982,16.871346,4.356752,1.736079,1.368231,4.959879,0.361195
+158.900000,17.579512,5.123884,2.098401,4.232587,1.500676,0.493202,5.216485,0.121880,3.135933,0.641034,0.000278,0.338966,0.041287,28.514688,1.564164,19.726630,16.871470,4.368842,1.736223,1.367921,4.959918,0.330923
+159.000000,17.579818,5.100869,2.169369,4.341692,1.458438,0.509262,5.088179,0.120219,3.102029,0.648290,0.000292,0.331710,0.041139,28.514871,1.569981,19.719086,16.871474,4.372644,1.736393,1.367773,4.959956,0.302193
+159.100000,17.580417,5.055868,2.175412,4.442402,1.455013,0.520906,4.909919,0.117960,3.047252,0.653630,0.000292,0.326370,0.040976,28.487481,1.576236,19.709826,16.871223,4.364170,1.736554,1.367901,4.959995,0.299576
+159.200000,17.580766,5.029607,2.101349,4.431317,1.499506,0.515520,4.856273,0.117346,3.024698,0.651286,0.000276,0.328714,0.040966,28.458287,1.576385,19.707998,16.870808,4.350908,1.736675,1.368170,4.960033,0.329145
+159.300000,17.580524,5.047907,2.021548,4.322015,1.545025,0.499351,4.974557,0.118925,3.056077,0.643856,0.000262,0.336144,0.041110,28.454973,1.570263,19.715351,16.870496,4.345430,1.736762,1.368287,4.960070,0.363426
+159.400000,17.579948,5.091947,2.007519,4.220366,1.552546,0.487422,5.146114,0.121088,3.108182,0.638357,0.000261,0.341643,0.041267,28.478530,1.564140,19.724093,16.870439,4.352248,1.736852,1.368126,4.960108,0.369934
+159.500000,17.579541,5.123260,2.062354,4.203497,1.521534,0.488144,5.234021,0.122130,3.138699,0.638702,0.000271,0.341298,0.041318,28.509450,1.562601,19.727204,16.870560,4.365360,1.736975,1.367808,4.960145,0.346112
+159.600000,17.579628,5.116863,2.144406,4.286743,1.473446,0.501707,5.165047,0.121202,3.123639,0.644835,0.000287,0.335165,0.041218,28.522954,1.566708,19.722352,16.870652,4.374148,1.737135,1.367560,4.960183,0.312148
+159.700000,17.580174,5.075830,2.187482,4.410847,1.447497,0.518072,4.980731,0.118849,3.070253,0.652260,0.000295,0.327740,0.041032,28.505240,1.573879,19.712392,16.870519,4.370697,1.737304,1.367572,4.960220,0.295022
+159.800000,17.580725,5.034479,2.142192,4.458199,1.475256,0.520767,4.849245,0.117217,3.025586,0.653606,0.000285,0.326394,0.040937,28.471116,1.577450,19.706119,16.870141,4.357427,1.737442,1.367827,4.960258,0.312552
+159.900000,17.580746,5.032893,2.049211,4.377753,1.529559,0.506876,4.902285,0.117984,3.035362,0.647297,0.000267,0.332703,0.041032,28.453844,1.573312,19.710239,16.869744,4.346860,1.737537,1.368055,4.960294,0.351230
+160.000000,17.580236,5.071720,2.000397,4.255346,1.556589,0.490979,5.075727,0.120217,3.086044,0.639951,0.000259,0.340049,0.041208,28.467645,1.566136,19.719856,16.869573,4.348562,1.737616,1.368016,4.960331,0.373013
+160.100000,17.579679,5.114535,2.029289,4.193488,1.540306,0.485445,5.219242,0.121976,3.131942,0.637429,0.000265,0.342571,0.041319,28.499446,1.562138,19.726223,16.869647,4.360529,1.737718,1.367736,4.960367,0.360405
+160.200000,17.579524,5.126649,2.109210,4.236542,1.494319,0.494206,5.222592,0.121948,3.138536,0.641413,0.000280,0.338587,0.041285,28.524261,1.563891,19.724830,16.869791,4.372982,1.737862,1.367422,4.960404,0.326471
+160.300000,17.579915,5.097303,2.180964,4.359772,1.451375,0.511957,5.068900,0.119968,3.096972,0.649433,0.000294,0.330567,0.041114,28.520243,1.570572,19.716049,16.869782,4.375472,1.738030,1.367304,4.960440,0.297660
+160.400000,17.580564,5.048560,2.176061,4.459008,1.454659,0.522807,4.882465,0.117611,3.038676,0.654437,0.000292,0.325563,0.040949,28.488216,1.576908,19.706493,16.869494,4.364977,1.738184,1.367484,4.960477,0.299280
+160.500000,17.580872,5.025378,2.089290,4.429757,1.506573,0.514707,4.849173,0.117268,3.021534,0.650858,0.000274,0.329142,0.040963,28.458710,1.576035,19.705925,16.869058,4.350951,1.738293,1.367781,4.960513,0.334137
+160.600000,17.580540,5.050562,2.009178,4.306200,1.551877,0.497021,4.992876,0.119169,3.060923,0.642708,0.000260,0.337292,0.041130,28.459102,1.569016,19.714636,16.868765,4.346636,1.738369,1.367880,4.960548,0.368945
+160.700000,17.579915,5.098519,2.004482,4.205040,1.554184,0.485585,5.173253,0.121429,3.116263,0.637446,0.000260,0.342554,0.041290,28.486587,1.562878,19.723606,16.868751,4.355287,1.738453,1.367684,4.960584,0.371334
+160.800000,17.579530,5.128235,2.069797,4.200127,1.517238,0.488137,5.250097,0.122323,3.144063,0.638631,0.000273,0.341369,0.041326,28.518803,1.561964,19.725971,16.868904,4.369435,1.738575,1.367347,4.960619,0.342966
+160.900000,17.579693,5.116149,2.157106,4.299631,1.465795,0.503855,5.156372,0.121084,3.121924,0.645734,0.000290,0.334266,0.041202,28.529626,1.566987,19.719865,16.868999,4.377635,1.738735,1.367113,4.960655,0.307098
+161.000000,17.580316,5.069443,2.194270,4.430942,1.443351,0.520731,4.952814,0.118490,3.062090,0.653404,0.000296,0.326596,0.041002,28.506768,1.574716,19.709011,16.868836,4.372246,1.738899,1.367171,4.960691,0.292378
+161.100000,17.580869,5.027965,2.134705,4.465721,1.479779,0.521188,4.830161,0.116981,3.018962,0.653754,0.000283,0.326246,0.040922,28.470008,1.577675,19.703373,16.868424,4.357418,1.739026,1.367471,4.960726,0.315516
+161.200000,17.580809,5.032503,2.035128,4.366476,1.537517,0.504936,4.910535,0.118103,3.036941,0.646341,0.000264,0.333659,0.041044,28.455100,1.572391,19.709072,16.868028,4.347239,1.739109,1.367700,4.960761,0.357354
+161.300000,17.580223,5.077237,1.992598,4.238023,1.560833,0.488709,5.101406,0.120546,3.093429,0.638839,0.000258,0.341161,0.041232,28.473190,1.564809,19.719454,16.867894,4.350692,1.739179,1.367629,4.960796,0.376570
+161.400000,17.579657,5.120898,2.032343,4.183719,1.538557,0.484504,5.242446,0.122261,3.139171,0.636939,0.000266,0.343061,0.041336,28.507728,1.561197,19.725451,16.868008,4.364205,1.739278,1.367318,4.960830,0.359100
+161.500000,17.579558,5.128788,2.120659,4.242355,1.487546,0.495460,5.225663,0.121977,3.140277,0.641915,0.000282,0.338085,0.041280,28.531678,1.563786,19.722963,16.868171,4.376846,1.739422,1.367000,4.960865,0.321794
+161.600000,17.580034,5.093053,2.192056,4.378961,1.444582,0.514759,5.046804,0.119681,3.091012,0.650636,0.000296,0.329364,0.041087,28.523126,1.571308,19.712964,16.868144,4.377861,1.739589,1.366917,4.960900,0.293362
+161.700000,17.580727,5.041107,2.175040,4.474498,1.455327,0.524486,4.855166,0.117263,3.029997,0.655157,0.000291,0.324843,0.040923,28.486644,1.577601,19.703269,16.867817,4.365353,1.739734,1.367148,4.960935,0.299633
+161.800000,17.580984,5.021796,2.076214,4.425949,1.514173,0.513602,4.844877,0.117227,3.019193,0.650304,0.000271,0.329696,0.040964,28.457418,1.575615,19.704105,16.867363,4.350781,1.739831,1.367468,4.960969,0.339613
+161.900000,17.580562,5.053929,1.997426,4.289615,1.558329,0.494646,5.012988,0.119434,3.066377,0.641548,0.000258,0.338452,0.041152,28.461768,1.567781,19.714087,16.867096,4.347805,1.739896,1.367545,4.961002,0.374245
+162.000000,17.579895,5.105224,2.002635,4.190541,1.555162,0.483894,5.199909,0.121762,3.124258,0.636613,0.000260,0.343387,0.041312,28.493012,1.561723,19.723150,16.867124,4.358278,1.739974,1.367313,4.961036,0.372202
+162.100000,17.579540,5.132770,2.078157,4.198439,1.512395,0.488366,5.263793,0.122485,3.148771,0.638678,0.000274,0.341322,0.041333,28.526146,1.561479,19.724691,16.867308,4.373322,1.740095,1.366958,4.961070,0.339448
+162.200000,17.579782,5.114730,2.169886,4.314128,1.458047,0.506200,5.144550,0.120926,3.119267,0.646731,0.000292,0.333269,0.041184,28.533872,1.567424,19.717311,16.867401,4.380754,1.740255,1.366741,4.961104,0.302068
+162.300000,17.580477,5.062623,2.199813,4.450959,1.439965,0.523313,4.923577,0.118114,3.053401,0.654525,0.000297,0.325475,0.040971,28.505792,1.575632,19.705657,16.867206,4.373346,1.740414,1.366848,4.961138,0.290222
+162.400000,17.581022,5.021802,2.125696,4.471136,1.485186,0.521291,4.813177,0.116773,3.012878,0.653768,0.000281,0.326232,0.040910,28.466898,1.577843,19.700841,16.866760,4.357106,1.740530,1.367188,4.961171,0.319119
+162.500000,17.580876,5.032890,2.021087,4.353726,1.545377,0.502850,4.921258,0.118253,3.039317,0.645324,0.000262,0.334676,0.041059,28.454793,1.571434,19.708122,16.866371,4.347538,1.740600,1.367413,4.961204,0.363537
+162.600000,17.580220,5.083130,1.985881,4.220997,1.564462,0.486525,5.127463,0.120877,3.100992,0.637776,0.000257,0.342224,0.041256,28.477138,1.563555,19.719128,16.866277,4.352802,1.740662,1.367306,4.961237,0.379657
+162.700000,17.579652,5.127026,2.036440,4.175333,1.536219,0.483766,5.263996,0.122524,3.145957,0.636551,0.000266,0.343449,0.041351,28.514106,1.560389,19.724658,16.866430,4.367761,1.740759,1.366967,4.961270,0.357340
+162.800000,17.579614,5.130303,2.132563,4.249867,1.480461,0.496938,5.225825,0.121969,3.141181,0.642526,0.000285,0.337474,0.041273,28.536785,1.563833,19.721034,16.866607,4.380422,1.740903,1.366649,4.961303,0.316976
+162.900000,17.580176,5.088212,2.202472,4.398912,1.438172,0.517619,5.022396,0.119365,3.084285,0.651875,0.000298,0.328125,0.041058,28.523440,1.572162,19.709851,16.866559,4.379828,1.741067,1.366602,4.961336,0.289357
+163.000000,17.580904,5.033668,2.172404,4.488560,1.456981,0.525908,4.828686,0.116927,3.021428,0.655775,0.000291,0.324225,0.040898,28.482785,1.578283,19.700183,16.866194,4.365356,1.741203,1.366884,4.961369,0.300615
+163.100000,17.581102,5.018907,2.062493,4.420142,1.522077,0.512255,4.843331,0.117221,3.017690,0.649644,0.000269,0.330356,0.040968,28.454391,1.575127,19.702526,16.865726,4.350460,1.741287,1.367221,4.961401,0.345430
+163.200000,17.580591,5.057878,1.986497,4.272703,1.564278,0.492283,5.034332,0.119713,3.072272,0.640401,0.000256,0.339599,0.041174,28.462834,1.566576,19.713667,16.865487,4.348955,1.741342,1.367271,4.961433,0.379225
+163.300000,17.579889,5.111914,2.001896,4.177078,1.555531,0.482369,5.225640,0.122081,3.132028,0.635866,0.000260,0.344134,0.041333,28.497613,1.560679,19.722700,16.865558,4.361202,1.741415,1.367004,4.961464,0.372573
+163.400000,17.579570,5.136810,2.087209,4.198350,1.507129,0.488813,5.275053,0.122617,3.152793,0.638831,0.000276,0.341169,0.041337,28.531297,1.561134,19.723363,16.865770,4.376997,1.741536,1.366633,4.961496,0.335663
+163.500000,17.579893,5.112676,2.182494,4.329876,1.450352,0.508690,5.130013,0.120734,3.115780,0.647801,0.000295,0.332199,0.041163,28.535586,1.567996,19.714709,16.865858,4.383507,1.741695,1.366436,4.961529,0.297154
+163.600000,17.580657,5.055533,2.204027,4.470463,1.437394,0.525760,4.893776,0.117731,3.044410,0.655598,0.000298,0.324402,0.040940,28.502318,1.576593,19.702362,16.865628,4.374041,1.741848,1.366592,4.961561,0.288578
+163.700000,17.581183,5.016109,2.115465,4.474457,1.491282,0.521099,4.798589,0.116596,3.007458,0.653656,0.000279,0.326344,0.040900,28.461816,1.577942,19.698532,16.865152,4.356562,1.741952,1.366970,4.961592,0.323252
+163.800000,17.580948,5.033982,2.007416,4.339962,1.552954,0.500686,4.933987,0.118428,3.042365,0.644275,0.000259,0.335725,0.041075,28.452838,1.570461,19.707354,16.864774,4.347792,1.742010,1.367184,4.961623,0.369630
+163.900000,17.580229,5.089235,1.980263,4.204595,1.567478,0.484463,5.153349,0.121205,3.108560,0.636779,0.000256,0.343221,0.041280,28.479316,1.562386,19.718845,16.864720,4.354881,1.742064,1.367041,4.961654,0.382259
+164.000000,17.579667,5.132815,2.041390,4.168361,1.533397,0.483226,5.283659,0.122762,3.152221,0.636263,0.000267,0.343737,0.041365,28.518394,1.559708,19.723833,16.864910,4.371171,1.742159,1.366675,4.961685,0.355213
+164.100000,17.579694,5.131216,2.144659,4.258816,1.473216,0.498597,5.223320,0.121928,3.141303,0.643226,0.000287,0.336774,0.041263,28.539450,1.564012,19.719057,16.865098,4.383697,1.742303,1.366360,4.961717,0.312126
+164.200000,17.580338,5.082921,2.212030,4.419167,1.432262,0.520471,4.996369,0.119028,3.076983,0.653121,0.000300,0.326879,0.041028,28.521159,1.573103,19.706742,16.865027,4.381400,1.742464,1.366351,4.961748,0.285708
+164.300000,17.581094,5.026405,2.168301,4.500959,1.459525,0.527059,4.803626,0.116609,3.013170,0.656279,0.000290,0.323721,0.040876,28.476693,1.578930,19.697261,16.864623,4.365054,1.742591,1.366682,4.961779,0.302173
+164.400000,17.581224,5.016718,2.048520,4.412690,1.530053,0.510727,4.844311,0.117247,3.016985,0.648906,0.000266,0.331094,0.040975,28.449609,1.574582,19.701167,16.864146,4.350045,1.742662,1.367030,4.961809,0.351427
+164.500000,17.580629,5.062257,1.976535,4.255894,1.569657,0.489983,5.056310,0.119998,3.078427,0.639291,0.000255,0.340709,0.041196,28.462166,1.565420,19.713338,16.863938,4.350093,1.742706,1.367051,4.961839,0.383808
+164.600000,17.579901,5.118447,2.002137,4.164802,1.555361,0.481019,5.250060,0.122383,3.139447,0.635209,0.000260,0.344791,0.041353,28.500210,1.559748,19.722237,16.864051,4.364035,1.742775,1.366749,4.961869,0.372502
+164.700000,17.579622,5.140327,2.096703,4.199705,1.501578,0.489449,5.283921,0.122718,3.156129,0.639076,0.000278,0.340924,0.041338,28.534108,1.560915,19.721992,16.864287,4.380438,1.742896,1.366366,4.961900,0.331719
+164.800000,17.580027,5.110088,2.194693,4.346464,1.442861,0.511262,5.113310,0.120515,3.111605,0.648917,0.000297,0.331083,0.041141,28.534709,1.568672,19.712083,16.864369,4.385902,1.743054,1.366191,4.961930,0.292446
+164.900000,17.580853,5.048348,2.206909,4.489062,1.435648,0.528028,4.864155,0.117349,3.035345,0.656600,0.000298,0.323400,0.040910,28.496397,1.577567,19.699160,16.864102,4.374388,1.743200,1.366396,4.961961,0.287443
+165.000000,17.581353,5.010970,2.104365,4.475819,1.497853,0.520648,4.786520,0.116452,3.002774,0.653431,0.000277,0.326569,0.040894,28.454801,1.577969,19.696445,16.863599,4.355853,1.743293,1.366806,4.961990,0.327783
+165.100000,17.581028,5.035670,1.994393,4.325656,1.560104,0.498506,4.948173,0.118620,3.045928,0.643223,0.000257,0.336777,0.041092,28.449155,1.569492,19.706730,16.863235,4.348030,1.743338,1.367006,4.962020,0.375502
+165.200000,17.580253,5.095389,1.975707,4.189090,1.569908,0.482548,5.178551,0.121522,3.115974,0.635858,0.000255,0.344142,0.041302,28.479569,1.561311,19.718576,16.863221,4.356914,1.743386,1.366827,4.962049,0.384385
+165.300000,17.579702,5.138188,2.046977,4.162766,1.530207,0.482871,5.301292,0.122975,3.157909,0.636066,0.000269,0.343934,0.041376,28.520438,1.559147,19.722972,16.863446,4.374408,1.743479,1.366435,4.962078,0.352816
+165.400000,17.579796,5.131580,2.156688,4.268877,1.465964,0.500387,5.218499,0.121858,3.140730,0.643992,0.000290,0.336008,0.041252,28.539584,1.564302,19.717047,16.863643,4.386666,1.743622,1.366125,4.962107,0.307348
+165.500000,17.580520,5.077338,2.220600,4.439264,1.426944,0.523255,4.969473,0.118680,3.069323,0.654345,0.000302,0.325655,0.040998,28.516311,1.574097,19.703671,16.863547,4.382614,1.743780,1.366156,4.962137,0.282456
+165.600000,17.581295,5.019464,2.162962,4.511571,1.462815,0.527936,4.780458,0.116316,3.005395,0.656669,0.000288,0.323331,0.040857,28.468453,1.579521,19.694524,16.863106,4.364517,1.743897,1.366533,4.962166,0.304223
+165.700000,17.581354,5.015193,2.034678,4.404022,1.537880,0.509086,4.847447,0.117301,3.016990,0.648118,0.000264,0.331882,0.040983,28.443057,1.573996,19.700000,16.862624,4.349583,1.743956,1.366887,4.962195,0.357441
+165.800000,17.580679,5.066899,1.967622,4.239580,1.574434,0.487793,5.078319,0.120281,3.084657,0.638238,0.000253,0.341762,0.041218,28.459643,1.564330,19.713060,16.862448,4.351217,1.743991,1.366877,4.962223,0.387944
+165.900000,17.579932,5.124700,2.003193,4.153803,1.554744,0.479847,5.272848,0.122663,3.146411,0.634641,0.000260,0.345359,0.041371,28.500657,1.558930,19.721748,16.862601,4.366751,1.744056,1.366543,4.962251,0.372063
+166.000000,17.579697,5.143318,2.106379,4.202286,1.495893,0.490237,5.290545,0.122792,3.158808,0.639397,0.000280,0.340603,0.041339,28.534471,1.560806,19.720587,16.862859,4.383625,1.744176,1.366149,4.962280,0.327728
+166.100000,17.580181,5.107091,2.206271,4.363443,1.435710,0.513855,5.095072,0.120277,3.106917,0.650048,0.000300,0.329952,0.041118,28.531238,1.569424,19.709464,16.862931,4.387957,1.744332,1.365998,4.962309,0.288019
+166.200000,17.581063,5.041241,2.208527,4.506425,1.434685,0.530080,4.835414,0.116980,3.026429,0.657515,0.000298,0.322485,0.040882,28.488126,1.578525,19.696083,16.862628,4.374448,1.744472,1.366251,4.962338,0.286788
+166.300000,17.581529,5.006439,2.092792,4.475465,1.504652,0.519990,4.776933,0.116340,2.998848,0.653116,0.000274,0.326884,0.040890,28.445915,1.577928,19.694570,16.862101,4.355046,1.744553,1.366689,4.962366,0.332557
+166.400000,17.581118,5.037819,1.982243,4.311280,1.566715,0.496370,4.963219,0.118821,3.049828,0.642196,0.000255,0.337804,0.041110,28.443678,1.568549,19.706209,16.861755,4.348272,1.744587,1.366871,4.962393,0.381042
+166.500000,17.580293,5.101433,1.972128,4.174700,1.571805,0.480801,5.202599,0.121823,3.123083,0.635022,0.000255,0.344978,0.041324,28.477770,1.560337,19.718296,16.861781,4.358882,1.744628,1.366656,4.962420,0.386068
+166.600000,17.579759,5.143089,2.052965,4.158453,1.526780,0.482679,5.316835,0.123161,3.162989,0.635949,0.000270,0.344051,0.041386,28.520126,1.558694,19.722074,16.862038,4.377445,1.744720,1.366242,4.962448,0.350255
+166.700000,17.579919,5.131471,2.168397,4.279673,1.458862,0.502253,5.211813,0.121766,3.139578,0.644797,0.000292,0.335203,0.041240,28.537159,1.564676,19.715026,16.862240,4.389328,1.744863,1.365939,4.962476,0.302741
+166.800000,17.580718,5.071633,2.228106,4.458760,1.422272,0.525913,4.942471,0.118330,3.061531,0.655520,0.000304,0.324480,0.040969,28.508983,1.575110,19.700672,16.862119,4.383517,1.745016,1.366009,4.962504,0.279622
+166.900000,17.581505,5.012967,2.156707,4.520411,1.466645,0.528563,4.759485,0.116052,2.998231,0.656952,0.000287,0.323048,0.040840,28.458179,1.580048,19.691981,16.861642,4.363821,1.745124,1.366429,4.962532,0.306648
+167.000000,17.581490,5.014236,2.021320,4.394660,1.545365,0.507407,4.852159,0.117374,3.017543,0.647315,0.000261,0.332685,0.040993,28.434718,1.573395,19.698983,16.861158,4.349111,1.745170,1.366785,4.962558,0.363315
+167.100000,17.580743,5.071627,1.959714,4.224058,1.578643,0.485740,5.099807,0.120557,3.090782,0.637261,0.000252,0.342739,0.041238,28.455148,1.563320,19.712803,16.861015,4.352312,1.745196,1.366744,4.962585,0.391643
+167.200000,17.579983,5.130587,2.004849,4.144055,1.553799,0.478840,5.293835,0.122920,3.152856,0.634155,0.000261,0.345845,0.041387,28.498848,1.558216,19.721228,16.861206,4.369321,1.745258,1.366378,4.962611,0.371352
+167.300000,17.579792,5.145838,2.115981,4.205771,1.490221,0.491128,5.295265,0.122842,3.160913,0.639769,0.000282,0.340231,0.041337,28.532348,1.560784,19.719164,16.861484,4.386551,1.745378,1.365976,4.962638,0.323797
+167.400000,17.580354,5.103862,2.217112,4.380324,1.428975,0.516404,5.076102,0.120029,3.101947,0.651167,0.000302,0.328833,0.041095,28.525263,1.570218,19.706885,16.861544,4.389715,1.745532,1.365850,4.962666,0.283913
+167.500000,17.581284,5.034376,2.209224,4.522486,1.434290,0.531931,4.808025,0.116627,3.017844,0.658347,0.000298,0.321653,0.040856,28.477672,1.579450,19.693150,16.861206,4.374311,1.745665,1.366148,4.962693,0.286485
+167.600000,17.581714,5.002376,2.081295,4.474222,1.511359,0.519245,4.768896,0.116248,2.995427,0.652764,0.000272,0.327236,0.040887,28.435132,1.577859,19.692848,16.860658,4.354179,1.745734,1.366611,4.962719,0.337346
+167.700000,17.581220,5.040114,1.970847,4.297357,1.572863,0.494330,4.978065,0.119019,3.053725,0.641217,0.000253,0.338783,0.041127,28.436188,1.567661,19.705735,16.860331,4.348458,1.745758,1.366774,4.962745,0.386290
+167.800000,17.580351,5.107265,1.969021,4.161204,1.573444,0.479174,5.225396,0.122107,3.129829,0.634248,0.000254,0.345752,0.041344,28.473731,1.559449,19.718009,16.860394,4.360712,1.745793,1.366525,4.962770,0.387535
+167.900000,17.579834,5.147675,2.058919,4.154768,1.523363,0.482558,5.331071,0.123330,3.167671,0.635870,0.000271,0.344130,0.041394,28.517415,1.558312,19.721180,16.860681,4.380263,1.745883,1.366090,4.962796,0.347718
+168.000000,17.580059,5.131185,2.179703,4.290540,1.451961,0.504114,5.204440,0.121665,3.138196,0.645605,0.000295,0.334395,0.041227,28.532301,1.565092,19.713047,16.860889,4.391742,1.746025,1.365794,4.962823,0.298335
+168.100000,17.580931,5.066026,2.235045,4.477635,1.417935,0.528472,4.915934,0.117986,3.053823,0.656658,0.000305,0.323342,0.040940,28.499363,1.576131,19.697764,16.860741,4.384218,1.746175,1.365902,4.962849,0.277020
+168.200000,17.581725,5.006761,2.150282,4.528520,1.470562,0.529101,4.739584,0.115801,2.991381,0.657199,0.000285,0.322801,0.040824,28.445829,1.580564,19.689556,16.860232,4.363013,1.746273,1.366363,4.962875,0.309155
+168.300000,17.581640,5.013423,2.008463,4.385535,1.552509,0.505791,4.856832,0.117446,3.018136,0.646543,0.000259,0.333457,0.041002,28.424267,1.572833,19.698026,16.859747,4.348551,1.746307,1.366720,4.962900,0.369027
+168.400000,17.580824,5.076189,1.952240,4.209348,1.582599,0.483798,5.120135,0.120817,3.096580,0.636326,0.000251,0.343674,0.041260,28.448349,1.562386,19.712547,16.859635,4.353256,1.746325,1.366648,4.962925,0.395162
+168.500000,17.580053,5.136213,2.006374,4.134784,1.552926,0.477881,5.313750,0.123163,3.158959,0.633696,0.000261,0.346304,0.041403,28.494573,1.557566,19.720715,16.859862,4.371666,1.746382,1.366253,4.962950,0.370699
+168.600000,17.579905,5.148233,2.125172,4.209198,1.484764,0.491997,5.299575,0.122887,3.162873,0.640134,0.000284,0.339866,0.041336,28.527772,1.560792,19.717795,16.860158,4.389241,1.746502,1.365843,4.962976,0.320064
+168.700000,17.580541,5.100696,2.227532,4.396804,1.422467,0.518892,5.057350,0.119784,3.097012,0.652262,0.000304,0.327738,0.041072,28.516911,1.571026,19.704385,16.860207,4.391268,1.746655,1.365740,4.963001,0.280001
+168.800000,17.581519,5.027725,2.209561,4.537857,1.434122,0.533682,4.781492,0.116284,3.009475,0.659139,0.000298,0.320861,0.040830,28.464970,1.580372,19.690319,16.859835,4.374023,1.746780,1.366083,4.963027,0.286318
+168.900000,17.581910,4.998617,2.069979,4.472529,1.517913,0.518469,4.761772,0.116167,2.992319,0.652400,0.000270,0.327600,0.040886,28.422247,1.577787,19.691235,16.859268,4.353237,1.746838,1.366568,4.963051,0.342108
+169.000000,17.581337,5.042455,1.960215,4.284157,1.578556,0.492413,4.992315,0.119208,3.057493,0.640298,0.000251,0.339702,0.041144,28.426487,1.566841,19.705281,16.858959,4.348569,1.746851,1.366712,4.963075,0.391229
+169.100000,17.580430,5.112758,1.966303,4.148791,1.574873,0.477685,5.246557,0.122371,3.136090,0.633541,0.000254,0.346459,0.041362,28.467224,1.558653,19.717693,16.859059,4.362369,1.746880,1.366431,4.963099,0.388824
+169.200000,17.579931,5.151888,2.064605,4.151618,1.520088,0.482485,5.343964,0.123483,3.171928,0.635816,0.000272,0.344184,0.041402,28.512095,1.557990,19.720291,16.859374,4.382827,1.746968,1.365976,4.963124,0.345307
+169.300000,17.580217,5.130763,2.190354,4.301157,1.445423,0.505919,5.196753,0.121560,3.136679,0.646391,0.000297,0.333609,0.041214,28.524878,1.565528,19.711129,16.859585,4.393897,1.747111,1.365687,4.963149,0.294223
+169.400000,17.581156,5.060594,2.241209,4.495527,1.414075,0.530877,4.890350,0.117653,3.046333,0.657732,0.000306,0.322268,0.040913,28.487360,1.577134,19.694969,16.859413,4.384721,1.747256,1.365832,4.963174,0.274716
+169.500000,17.581955,5.001060,2.143499,4.535208,1.474680,0.529460,4.721834,0.115577,2.985178,0.657369,0.000284,0.322631,0.040810,28.431433,1.581019,19.687309,16.858872,4.362137,1.747344,1.366329,4.963198,0.311821
+169.600000,17.581800,5.013081,1.996513,4.376292,1.559088,0.504218,4.862529,0.117530,3.019130,0.645791,0.000257,0.334209,0.041012,28.411917,1.572278,19.697176,16.858389,4.348035,1.747367,1.366685,4.963221,0.374399
+169.700000,17.580924,5.080598,1.945936,4.196025,1.585915,0.482064,5.139078,0.121058,3.102015,0.635499,0.000250,0.344501,0.041278,28.439361,1.561558,19.712255,16.858308,4.354175,1.747377,1.366583,4.963245,0.398149
+169.800000,17.580146,5.141237,2.008322,4.127028,1.551823,0.477109,5.331205,0.123375,3.164339,0.633326,0.000262,0.346674,0.041416,28.487766,1.557027,19.720138,16.858568,4.373829,1.747431,1.366162,4.963268,0.369855
+169.900000,17.580040,5.150092,2.133833,4.213230,1.479595,0.492911,5.302084,0.122910,3.164257,0.640524,0.000286,0.339476,0.041333,28.520490,1.560865,19.716413,16.858880,4.391636,1.747550,1.365745,4.963292,0.316572
+170.000000,17.580744,5.097461,2.236754,4.412389,1.416686,0.521214,5.038904,0.119544,3.092074,0.653288,0.000306,0.326712,0.041050,28.506023,1.571822,19.701979,16.858918,4.392548,1.747701,1.365665,4.963316,0.276559
+170.100000,17.581761,5.021609,2.208881,4.551130,1.434583,0.535134,4.757671,0.115977,3.001862,0.659801,0.000298,0.320199,0.040808,28.450224,1.581199,19.687700,16.858514,4.373628,1.747820,1.366049,4.963340,0.286536
+170.200000,17.582111,4.995644,2.059161,4.469574,1.524130,0.517589,4.757279,0.116119,2.990097,0.651989,0.000268,0.328011,0.040886,28.407728,1.577650,19.689822,16.857931,4.352388,1.747866,1.366550,4.963363,0.346709
+170.300000,17.581467,5.045012,1.951127,4.271884,1.583380,0.490673,5.006317,0.119393,3.061286,0.639464,0.000250,0.340536,0.041159,28.415003,1.566090,19.704849,16.857643,4.348786,1.747870,1.366674,4.963386,0.395493
+170.400000,17.580530,5.117748,1.964632,4.138209,1.575741,0.476444,5.265308,0.122603,3.141674,0.632953,0.000254,0.347047,0.041378,28.458507,1.557984,19.717297,16.857776,4.363966,1.747894,1.366364,4.963408,0.389627
+170.500000,17.580051,5.155359,2.070281,4.149869,1.516812,0.482569,5.354099,0.123602,3.175356,0.635837,0.000273,0.344163,0.041407,28.504216,1.557773,19.719334,16.858115,4.385149,1.747981,1.365893,4.963431,0.342908
+170.600000,17.580394,5.129941,2.199914,4.311634,1.439526,0.507653,5.188040,0.121443,3.134769,0.647150,0.000299,0.332850,0.041201,28.514860,1.565994,19.709240,16.858328,4.395738,1.748122,1.365612,4.963455,0.290560
+170.700000,17.581391,5.055505,2.245922,4.511358,1.411122,0.532962,4.866952,0.117349,3.039395,0.658665,0.000307,0.321335,0.040888,28.473240,1.578049,19.692363,16.858132,4.385043,1.748263,1.365791,4.963478,0.272957
+170.800000,17.582187,4.996203,2.136613,4.539920,1.478836,0.529596,4.707414,0.115397,2.980025,0.657439,0.000282,0.322561,0.040800,28.415510,1.581367,19.685305,16.857565,4.361329,1.748342,1.366320,4.963501,0.314550
+170.900000,17.581967,5.013173,1.985949,4.367370,1.564858,0.502753,4.868875,0.117620,3.020433,0.645092,0.000255,0.334908,0.041022,28.398019,1.571752,19.696399,16.857087,4.347658,1.748354,1.366670,4.963523,0.379193
+171.000000,17.581040,5.084709,1.940812,4.184266,1.588597,0.480554,5.156229,0.121275,3.106967,0.634781,0.000249,0.345219,0.041294,28.428435,1.560839,19.711909,16.857036,4.355096,1.748357,1.366542,4.963544,0.400592
+171.100000,17.580260,5.145636,2.010518,4.120670,1.550584,0.476503,5.346189,0.123556,3.168985,0.633037,0.000262,0.346963,0.041427,28.478662,1.556589,19.719500,16.857324,4.375816,1.748409,1.366097,4.963566,0.368897
+171.200000,17.580193,5.151493,2.141807,4.217596,1.474817,0.493830,5.303100,0.122916,3.165146,0.640920,0.000287,0.339080,0.041330,28.510780,1.560986,19.715037,16.857649,4.393754,1.748527,1.365676,4.963589,0.313376
+171.300000,17.580958,5.094305,2.244692,4.426690,1.411680,0.523320,5.021367,0.119315,3.087307,0.654223,0.000308,0.325777,0.041029,28.492936,1.572580,19.699692,16.857675,4.393595,1.748675,1.365618,4.963612,0.273628
+171.400000,17.582007,5.016177,2.207493,4.562250,1.435478,0.536300,4.736940,0.115710,2.995156,0.660337,0.000298,0.319663,0.040788,28.433851,1.581917,19.685310,16.857243,4.373208,1.748787,1.366038,4.963634,0.287029
+171.500000,17.582316,4.993288,2.049313,4.466174,1.529754,0.516716,4.754408,0.116092,2.988470,0.651581,0.000266,0.328419,0.040888,28.391799,1.577490,19.688544,16.856650,4.351666,1.748824,1.366552,4.963656,0.350933
+171.600000,17.581609,5.047479,1.943328,4.260898,1.587495,0.489135,5.019152,0.119561,3.064804,0.638724,0.000249,0.341276,0.041173,28.401787,1.565430,19.704390,16.856381,4.349047,1.748818,1.366656,4.963677,0.399176
+171.700000,17.580648,5.122198,1.963447,4.129063,1.576351,0.475382,5.281792,0.122806,3.146593,0.632452,0.000253,0.347548,0.041393,28.447685,1.557415,19.716841,16.856544,4.365437,1.748838,1.366320,4.963698,0.390203
+171.800000,17.580189,5.158351,2.075529,4.148708,1.513772,0.482699,5.362560,0.123701,3.178254,0.635882,0.000274,0.344118,0.041412,28.494048,1.557613,19.718368,16.856905,4.387226,1.748923,1.365836,4.963719,0.340698
+171.900000,17.580583,5.129038,2.208453,4.321402,1.434234,0.509253,5.179446,0.121329,3.132822,0.647854,0.000301,0.332146,0.041189,28.502673,1.566447,19.707433,16.857119,4.397340,1.749063,1.365563,4.963741,0.287313
+172.000000,17.581631,5.050862,2.249747,4.525437,1.408725,0.534795,4.845763,0.117074,3.033062,0.659490,0.000308,0.320510,0.040866,28.457369,1.578885,19.689940,16.856901,4.385268,1.749199,1.365773,4.963763,0.271528
+172.100000,17.582422,4.991975,2.130024,4.543516,1.482796,0.529626,4.695185,0.115244,2.975593,0.657462,0.000281,0.322538,0.040791,28.398172,1.581655,19.683473,16.856312,4.360586,1.749270,1.366329,4.963784,0.317180
+172.200000,17.582142,5.013454,1.976605,4.359145,1.569925,0.501428,4.875063,0.117708,3.021775,0.644460,0.000254,0.335540,0.041031,28.382589,1.571276,19.695655,16.855840,4.347356,1.749273,1.366673,4.963805,0.383470
+172.300000,17.581172,5.088435,1.936501,4.173944,1.590843,0.479238,5.171474,0.121467,3.111378,0.634156,0.000248,0.345844,0.041309,28.415621,1.560219,19.711510,16.855815,4.355957,1.749269,1.366520,4.963825,0.402656
+172.400000,17.580391,5.149489,2.012655,4.115309,1.549380,0.476005,5.359147,0.123712,3.173014,0.632800,0.000263,0.347200,0.041437,28.467408,1.556227,19.718826,16.856129,4.377603,1.749318,1.366055,4.963846,0.367965
+172.500000,17.580361,5.152615,2.148976,4.221824,1.470504,0.494694,5.303411,0.122913,3.165769,0.641294,0.000289,0.338706,0.041326,28.498913,1.561123,19.713701,16.856466,4.395625,1.749434,1.365631,4.963867,0.310519
+172.600000,17.581179,5.091391,2.251622,4.439573,1.407301,0.525208,5.005310,0.119106,3.082913,0.655062,0.000309,0.324938,0.041011,28.478027,1.573279,19.697551,16.856482,4.394494,1.749580,1.365592,4.963888,0.271076
+172.700000,17.582254,5.011356,2.205949,4.571876,1.436465,0.537288,4.718678,0.115474,2.989210,0.660795,0.000297,0.319205,0.040771,28.416081,1.582555,19.683111,16.856026,4.372816,1.749686,1.366045,4.963909,0.287586
+172.800000,17.582525,4.991326,2.040461,4.462816,1.534778,0.515905,4.752337,0.116073,2.987178,0.651202,0.000264,0.328798,0.040890,28.374522,1.577336,19.687354,16.855424,4.351043,1.749713,1.366568,4.963929,0.354761
+172.900000,17.581764,5.049759,1.936579,4.251191,1.591036,0.487786,5.030629,0.119710,3.067954,0.638083,0.000248,0.341917,0.041186,28.386924,1.564853,19.703902,16.855174,4.349317,1.749700,1.366655,4.963949,0.402385
+173.000000,17.580783,5.126120,1.962544,4.121164,1.576812,0.474470,5.296165,0.122983,3.150885,0.632023,0.000253,0.347977,0.041405,28.434904,1.556934,19.716332,16.855363,4.366766,1.749715,1.366296,4.963968,0.390644
+173.100000,17.580342,5.160903,2.080240,4.147932,1.511038,0.482847,5.369636,0.123783,3.180700,0.635938,0.000275,0.344062,0.041415,28.481802,1.557493,19.717406,16.855742,4.389072,1.749799,1.365799,4.963989,0.338722
+173.200000,17.580782,5.128141,2.215965,4.330251,1.429561,0.510695,5.171390,0.121222,3.130961,0.648488,0.000302,0.331512,0.041177,28.488591,1.566871,19.705726,16.855958,4.398742,1.749937,1.365535,4.964009,0.284473
+173.300000,17.581873,5.046721,2.252850,4.537764,1.406775,0.536387,4.826958,0.116829,3.027408,0.660207,0.000308,0.319793,0.040846,28.440024,1.579634,19.687703,16.855721,4.385444,1.750069,1.365772,4.964030,0.270376
+173.400000,17.582657,4.988410,2.123984,4.546147,1.486414,0.529581,4.685149,0.115120,2.971904,0.657451,0.000280,0.322549,0.040785,28.379702,1.581885,19.681810,16.855114,4.359961,1.750131,1.366350,4.964050,0.319602
+173.500000,17.582325,5.013852,1.968611,4.351828,1.574232,0.500268,4.880827,0.117787,3.023089,0.643889,0.000252,0.336111,0.041042,28.365859,1.570856,19.694925,16.854648,4.347158,1.750126,1.366687,4.964069,0.387156
+173.600000,17.581318,5.091705,1.932952,4.165142,1.592684,0.478122,5.184646,0.121633,3.115197,0.633635,0.000248,0.346365,0.041325,28.401104,1.559702,19.711043,16.854647,4.356767,1.750117,1.366513,4.964088,0.404364
+173.700000,17.580538,5.152778,2.014636,4.110895,1.548264,0.475605,5.370097,0.123844,3.176427,0.632610,0.000263,0.347390,0.041445,28.454206,1.555934,19.718114,16.854984,4.379193,1.750163,1.366031,4.964107,0.367100
+173.800000,17.580539,5.153507,2.155234,4.225700,1.466725,0.495472,5.303320,0.122907,3.166206,0.641632,0.000290,0.338368,0.041322,28.485140,1.561262,19.712418,16.855331,4.397271,1.750278,1.365604,4.964127,0.308041
+173.900000,17.581404,5.088796,2.257568,4.450873,1.403535,0.526859,4.991078,0.118921,3.079001,0.655797,0.000311,0.324203,0.040994,28.461593,1.573904,19.695572,16.855338,4.395284,1.750421,1.365583,4.964147,0.268897
+174.000000,17.582501,5.007158,2.204412,4.580121,1.437448,0.538121,4.702847,0.115270,2.984031,0.661183,0.000297,0.318817,0.040757,28.397189,1.583114,19.681096,16.854860,4.372488,1.750520,1.366062,4.964167,0.288140
+174.100000,17.582737,4.989675,2.032711,4.459772,1.539151,0.515188,4.750696,0.116059,2.986107,0.650868,0.000263,0.329132,0.040891,28.356099,1.577201,19.686228,16.854252,4.350532,1.750540,1.366594,4.964185,0.358139
+174.200000,17.581929,5.051776,1.930787,4.242819,1.594060,0.486626,5.040565,0.119840,3.070691,0.637529,0.000247,0.342471,0.041197,28.370597,1.564364,19.703372,16.854018,4.349588,1.750520,1.366664,4.964203,0.405153
+174.300000,17.580931,5.129515,1.961812,4.114421,1.577185,0.473693,5.308498,0.123135,3.154566,0.631659,0.000253,0.348341,0.041415,28.420365,1.556531,19.715778,16.854232,4.367952,1.750531,1.366286,4.964222,0.391003
+174.400000,17.580506,5.163093,2.084342,4.147352,1.508651,0.482988,5.375614,0.123853,3.182774,0.635993,0.000276,0.344007,0.041418,28.467714,1.557402,19.716459,16.854627,4.390698,1.750612,1.365779,4.964241,0.337007
+174.500000,17.580986,5.127334,2.222471,4.338010,1.425498,0.511958,5.164221,0.121127,3.129292,0.649046,0.000304,0.330954,0.041167,28.472895,1.567253,19.704133,16.854844,4.399978,1.750749,1.365521,4.964260,0.282031
+174.600000,17.582115,5.043124,2.255453,4.548435,1.405138,0.537759,4.810614,0.116616,3.022474,0.660830,0.000309,0.319170,0.040830,28.421507,1.580295,19.685653,16.854591,4.385617,1.750877,1.365782,4.964279,0.269410
+174.700000,17.582891,4.985320,2.118662,4.548373,1.489590,0.529533,4.676461,0.115012,2.968703,0.657438,0.000279,0.322562,0.040779,28.360219,1.582090,19.680265,16.853968,4.359442,1.750932,1.366379,4.964298,0.321748
+174.800000,17.582514,5.014216,1.961661,4.345530,1.577959,0.499272,4.885788,0.117857,3.024199,0.643431,0.000251,0.336569,0.041046,28.347859,1.570502,19.694185,16.853510,4.347014,1.750919,1.366710,4.964316,0.390379
+174.900000,17.581477,5.094530,1.929926,4.157605,1.594253,0.477169,5.195908,0.121775,3.118461,0.633176,0.000247,0.346824,0.041332,28.385063,1.559258,19.710536,16.853529,4.357494,1.750904,1.366517,4.964333,0.405820
+175.000000,17.580697,5.155594,2.016328,4.107129,1.547309,0.475264,5.379433,0.123957,3.179335,0.632449,0.000263,0.347551,0.041452,28.439282,1.555689,19.717391,16.853886,4.380595,1.750947,1.366021,4.964351,0.366364
+175.100000,17.580725,5.154244,2.160614,4.229128,1.463467,0.496153,5.303052,0.122899,3.166527,0.641929,0.000291,0.338071,0.041319,28.469711,1.561392,19.711198,16.854242,4.398713,1.751061,1.365591,4.964370,0.305920
+175.200000,17.581630,5.086527,2.262580,4.460635,1.400344,0.528282,4.978636,0.118758,3.075560,0.656432,0.000312,0.323568,0.040980,28.443832,1.574455,19.693749,16.854242,4.395974,1.751202,1.365585,4.964389,0.267077
+175.300000,17.582744,5.003601,2.202825,4.586879,1.438455,0.538784,4.689571,0.115098,2.979656,0.661495,0.000296,0.318505,0.040745,28.377376,1.583585,19.679271,16.853747,4.372228,1.751295,1.366088,4.964407,0.288720
+175.400000,17.582951,4.988390,2.026088,4.456939,1.542871,0.514553,4.749703,0.116053,2.985326,0.650571,0.000262,0.329429,0.040893,28.336784,1.577075,19.685174,16.853134,4.350158,1.751307,1.366626,4.964424,0.361040
+175.500000,17.582103,5.053540,1.926056,4.235777,1.596521,0.485659,5.048998,0.119950,3.073027,0.637054,0.000246,0.342946,0.041205,28.353087,1.563946,19.702812,16.852916,4.349891,1.751280,1.366682,4.964441,0.407424
+175.600000,17.581092,5.132367,1.961297,4.108859,1.577445,0.473056,5.318745,0.123261,3.157628,0.631361,0.000253,0.348639,0.041424,28.404319,1.556202,19.715176,16.853150,4.369015,1.751288,1.366286,4.964459,0.391258
+175.700000,17.580681,5.164894,2.087839,4.146990,1.506612,0.483124,5.380427,0.123909,3.184457,0.636048,0.000277,0.343952,0.041420,28.452024,1.557338,19.715523,16.853560,4.392120,1.751367,1.365770,4.964476,0.335549
+175.800000,17.581193,5.126625,2.227946,4.344610,1.422068,0.513031,5.158025,0.121045,3.127840,0.649520,0.000305,0.330480,0.041159,28.455853,1.567583,19.702657,16.853778,4.401068,1.751502,1.365518,4.964494,0.279985
+175.900000,17.582353,5.040076,2.257613,4.557461,1.403777,0.538921,4.796720,0.116435,3.018274,0.661357,0.000309,0.318643,0.040815,28.402089,1.580860,19.683794,16.853513,4.385810,1.751626,1.365799,4.964513,0.268609
+176.000000,17.583124,4.982713,2.114151,4.550268,1.492274,0.529495,4.669072,0.114920,2.965980,0.657429,0.000278,0.322571,0.040774,28.339993,1.582268,19.678834,16.852877,4.359052,1.751675,1.366412,4.964530,0.323575
+176.100000,17.582709,5.014512,1.955822,4.340291,1.581075,0.498444,4.889823,0.117914,3.025103,0.643035,0.000250,0.336965,0.041052,28.328883,1.570212,19.693433,16.852424,4.346936,1.751655,1.366738,4.964546,0.393102
+176.200000,17.581645,5.096893,1.927334,4.151319,1.595594,0.476371,5.205258,0.121893,3.121165,0.632799,0.000247,0.347201,0.041341,28.367703,1.558896,19.709974,16.852462,4.358145,1.751635,1.366529,4.964563,0.407072
+176.300000,17.580866,5.157973,2.017683,4.103931,1.546543,0.474971,5.387287,0.124051,3.181775,0.632311,0.000264,0.347689,0.041458,28.422884,1.555487,19.716657,16.852836,4.381815,1.751675,1.366020,4.964579,0.365774
+176.400000,17.580916,5.154901,2.165099,4.231929,1.460742,0.496716,5.302939,0.122894,3.166830,0.642175,0.000292,0.337825,0.041317,28.452915,1.561501,19.710052,16.853201,4.399977,1.751788,1.365588,4.964597,0.304159
+176.500000,17.581855,5.084661,2.266828,4.468818,1.397638,0.529478,4.968263,0.118623,3.072696,0.656966,0.000313,0.323034,0.040968,28.425098,1.574921,19.692093,16.853195,4.396617,1.751926,1.365594,4.964615,0.265534
+176.600000,17.582983,5.000612,2.201613,4.592709,1.439224,0.539365,4.678275,0.114952,2.975940,0.661768,0.000296,0.318232,0.040735,28.356902,1.583992,19.677604,16.852686,4.372073,1.752014,1.366117,4.964632,0.289163
+176.700000,17.583165,4.987261,2.020574,4.454741,1.545956,0.514046,4.748596,0.116044,2.984591,0.650333,0.000261,0.329667,0.040895,28.316686,1.576984,19.684150,16.852070,4.349888,1.752019,1.366660,4.964648,0.363470
+176.800000,17.582284,5.054958,1.921971,4.230014,1.598638,0.484860,5.055831,0.120038,3.074903,0.636684,0.000245,0.343316,0.041213,28.334412,1.563629,19.702180,16.851865,4.350167,1.751987,1.366704,4.964664,0.409391
+176.900000,17.581262,5.134732,1.960707,4.104159,1.577747,0.472511,5.327318,0.123366,3.160177,0.631105,0.000253,0.348895,0.041431,28.386921,1.555930,19.714543,16.852116,4.369931,1.751991,1.366294,4.964680,0.391546
+177.000000,17.580861,5.166448,2.090636,4.146528,1.504977,0.483213,5.384682,0.123958,3.185927,0.636082,0.000277,0.343918,0.041423,28.434974,1.557277,19.714626,16.852539,4.393354,1.752068,1.365771,4.964696,0.334387
+177.100000,17.581401,5.126073,2.232496,4.350084,1.419210,0.513924,5.152947,0.120978,3.126654,0.649914,0.000306,0.330086,0.041152,28.437670,1.567861,19.701300,16.852759,4.402029,1.752201,1.365523,4.964713,0.278295
+177.200000,17.582587,5.037563,2.259365,4.564936,1.402675,0.539879,4.785230,0.116285,3.014792,0.661792,0.000310,0.318208,0.040803,28.381923,1.581333,19.682116,16.852483,4.386024,1.752321,1.365820,4.964730,0.267960
+177.300000,17.583352,4.980589,2.110361,4.551723,1.494523,0.529449,4.663135,0.114846,2.963779,0.657415,0.000277,0.322585,0.040770,28.319194,1.582411,19.677524,16.851838,4.358793,1.752364,1.366447,4.964746,0.325116
+177.400000,17.582905,5.014789,1.951061,4.335979,1.583607,0.497765,4.893214,0.117961,3.025874,0.642708,0.000249,0.337292,0.041057,28.309137,1.569975,19.692677,16.851391,4.346945,1.752338,1.366768,4.964762,0.395332
+177.500000,17.581821,5.098832,1.925251,4.146214,1.596669,0.475724,5.212889,0.121989,3.123375,0.632489,0.000247,0.347511,0.041347,28.349285,1.558604,19.709369,16.851444,4.358751,1.752314,1.366546,4.964777,0.408080
+177.600000,17.581042,5.159909,2.018793,4.101353,1.545916,0.474736,5.393670,0.124127,3.183759,0.632201,0.000264,0.347799,0.041463,28.405240,1.555330,19.715906,16.851833,4.382883,1.752352,1.366026,4.964792,0.365291
+177.700000,17.581110,5.155436,2.168764,4.234236,1.458511,0.497180,5.302826,0.122889,3.167071,0.642377,0.000293,0.337623,0.041315,28.434956,1.561593,19.708971,16.852206,4.401083,1.752462,1.365592,4.964809,0.302725
+177.800000,17.582076,5.083131,2.270314,4.475554,1.395412,0.530463,4.959722,0.118511,3.070337,0.657407,0.000313,0.322593,0.040958,28.405557,1.575308,19.690593,16.852196,4.397214,1.752598,1.365608,4.964825,0.264274
+177.900000,17.583217,4.998151,2.200587,4.597506,1.439875,0.539841,4.668965,0.114831,2.972873,0.661993,0.000296,0.318007,0.040726,28.335931,1.584332,19.676093,16.851676,4.372012,1.752682,1.366147,4.964841,0.289538
+178.000000,17.583378,4.986322,2.016010,4.452952,1.548502,0.513630,4.747626,0.116035,2.983965,0.650139,0.000260,0.329861,0.040896,28.296016,1.576913,19.683168,16.851057,4.349728,1.752681,1.366694,4.964857,0.365488
+178.100000,17.582470,5.056136,1.918620,4.225263,1.600369,0.484203,5.061433,0.120111,3.076443,0.636370,0.000245,0.343630,0.041219,28.314954,1.563360,19.701535,16.850863,4.350461,1.752644,1.366728,4.964871,0.411010
+178.200000,17.581437,5.136691,1.960226,4.100301,1.577993,0.472064,5.334344,0.123452,3.162265,0.630896,0.000253,0.349104,0.041438,28.368505,1.555708,19.713888,16.851130,4.370753,1.752644,1.366307,4.964886,0.391781
+178.300000,17.581045,5.167735,2.092929,4.146124,1.503634,0.483284,5.388196,0.123999,3.187137,0.636110,0.000278,0.343890,0.041424,28.416857,1.557229,19.713754,16.851564,4.394439,1.752719,1.365777,4.964901,0.333437
+178.400000,17.581607,5.125659,2.236283,4.354532,1.416827,0.514656,5.148898,0.120924,3.125723,0.650238,0.000307,0.329762,0.041146,28.418671,1.568087,19.700057,16.851787,4.402907,1.752850,1.365532,4.964917,0.276890
+178.500000,17.582816,5.035484,2.260974,4.571285,1.401663,0.540702,4.775575,0.116158,3.011876,0.662165,0.000310,0.317835,0.040793,28.361272,1.581736,19.680590,16.851503,4.386284,1.752967,1.365843,4.964933,0.267362
+178.600000,17.583577,4.978740,2.107308,4.553247,1.496333,0.529452,4.657732,0.114779,2.961807,0.657423,0.000276,0.322577,0.040766,28.297933,1.582552,19.676284,16.850850,4.358629,1.753005,1.366480,4.964948,0.326359
+178.700000,17.583104,5.014913,1.947015,4.332593,1.585751,0.497223,4.895591,0.117994,3.026372,0.642450,0.000249,0.337550,0.041061,28.288693,1.569792,19.691905,16.850407,4.346975,1.752974,1.366798,4.964963,0.397234
+178.800000,17.582001,5.100405,1.923301,4.141930,1.597675,0.475175,5.219120,0.122067,3.125158,0.632232,0.000246,0.347768,0.041354,28.329942,1.558364,19.708739,16.850474,4.359272,1.752945,1.366565,4.964977,0.409025
+178.900000,17.581221,5.161575,2.019520,4.098960,1.545501,0.474504,5.399236,0.124195,3.185470,0.632090,0.000264,0.347910,0.041467,28.386625,1.555180,19.715183,16.850876,4.383810,1.752980,1.366036,4.964991,0.364978
+179.000000,17.581303,5.155993,2.171755,4.235907,1.456687,0.497534,5.303149,0.122890,3.167394,0.642531,0.000293,0.337469,0.041314,28.416149,1.561656,19.707972,16.851256,4.402071,1.753089,1.365599,4.965007,0.301558
+179.100000,17.582292,5.081926,2.273385,4.481213,1.393448,0.531302,4.952697,0.118419,3.068413,0.657781,0.000314,0.322219,0.040950,28.385438,1.575633,19.689225,16.851245,4.397793,1.753222,1.365623,4.965022,0.263167
+179.200000,17.583445,4.996058,2.199900,4.601797,1.440314,0.540282,4.660865,0.114726,2.970217,0.662201,0.000295,0.317799,0.040719,28.314545,1.584634,19.674691,16.850715,4.372020,1.753302,1.366175,4.965037,0.289786
+179.300000,17.583590,4.985439,2.012264,4.451773,1.550583,0.513322,4.746332,0.116022,2.983297,0.649993,0.000259,0.330007,0.040897,28.274826,1.576873,19.682204,16.850095,4.349628,1.753296,1.366726,4.965051,0.367153
+179.400000,17.582659,5.057012,1.915630,4.221435,1.601912,0.483662,5.065776,0.120167,3.077614,0.636124,0.000244,0.343876,0.041226,28.294687,1.563160,19.700848,16.849910,4.350707,1.753254,1.366753,4.965065,0.412458
+179.500000,17.581617,5.138325,1.959545,4.096903,1.578348,0.471660,5.340321,0.123526,3.164025,0.630706,0.000253,0.349294,0.041443,28.349164,1.555515,19.713231,16.850189,4.371446,1.753250,1.366322,4.965079,0.392107
+179.600000,17.581230,5.168928,2.094653,4.145447,1.502622,0.483297,5.391634,0.124039,3.188287,0.636110,0.000278,0.343890,0.041426,28.397855,1.557170,19.712936,16.850634,4.395388,1.753324,1.365786,4.965093,0.332725
+179.700000,17.581810,5.125438,2.239468,4.358061,1.414818,0.515248,5.145942,0.120884,3.125077,0.650498,0.000307,0.329502,0.041142,28.398982,1.568264,19.698922,16.850860,4.403710,1.753453,1.365542,4.965108,0.275713
+179.800000,17.583038,5.033799,2.262516,4.576698,1.400684,0.541414,4.767551,0.116053,3.009466,0.662488,0.000310,0.317512,0.040784,28.340187,1.582077,19.679197,16.850571,4.386577,1.753567,1.365864,4.965123,0.266800
+179.900000,17.583798,4.977145,2.104930,4.554809,1.497738,0.529497,4.652910,0.114718,2.960071,0.657448,0.000276,0.322552,0.040763,28.276284,1.582688,19.675111,16.849911,4.358551,1.753600,1.366512,4.965137,0.327332
+180.000000,17.583304,5.014917,1.943649,4.330008,1.587531,0.496797,4.897187,0.118018,3.026668,0.642244,0.000248,0.337756,0.041063,28.267676,1.569654,19.691125,16.849472,4.347032,1.753564,1.366828,4.965150,0.398820
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/ModredExample/HynneProject/experiments/firstexp/experiment.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/ModredExample/HynneProject/experiments/firstexp/experiment.exp
new file mode 100644
index 0000000000000000000000000000000000000000..28db43df66ada11093f7bf76f07274a268772018
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/ModredExample/HynneProject/experiments/firstexp/experiment.exp
@@ -0,0 +1,284 @@
+********** EXPERIMENT NAME
+Reference experiment
+
+********** EXPERIMENT NOTES
+Reference experiment for Hynne model that is used to generate in-silico 
+measurement data that the reduced model should be able to reproduce.
+
+Pretty complicated experiment definition ... :)
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+Glcx(0) = 1.244479e+000
+Glc(0) = 4.080968e-001
+ATP(0) = 2.102544e+000
+G6P(0) = 4.148672e+000
+ADP(0) = 1.498510e+000
+F6P(0) = 4.845546e-001
+FBP(0) = 4.454132e+000
+GAP(0) = 1.127139e-001
+DHAP(0) = 2.887661e+000
+NADplus(0) = 6.527018e-001
+BPG(0) = 2.672910e-004
+NADH(0) = 3.272982e-001
+PEP(0) = 3.950288e-002
+Pyr(0) = 6.602917e+000
+ACA(0) = 1.448285e+000
+EtOH(0) = 1.905934e+001
+EtOHx(0) = 1.629870e+001
+Glyc(0) = 4.103154e+000
+Glycx(0) = 1.647506e+000
+ACAx(0) = 1.259385e+000
+CNxminus(0) = 5.211879e+000
+AMP(0) = 3.289457e-001
+
+********** EXPERIMENT PARAMETER CHANGES
+k0 = {0,0.048,110,4.790000e-002}
+CNxminus0 = {0,5.6,110,5.370000e+000}
+Glcx0 = {0,18.0,10,18.5,20,20.0,30,22.0,40,24.0,50,25.5,60,27.0,70,29.0,80,30.5,90,32.0,100,33.5,110,35.0}
+
+********** EXPERIMENT STATE CHANGES
+% Glcx0 represents the glucose concentration in the inflow to the extracellular
+% environment. Here we change it at discrete time steps.
+time = 10, Glcx = 1.553067e+000, Glc = 5.730636e-001,ATP = 2.100013e+000,G6P = 4.200046e+000, ADP = 1.499993e+000, F6P = 4.900058e-001, FBP = 4.639941e+000, GAP = 1.149991e-001, DHAP = 2.949984e+000, NADplus = 6.500026e-001,BPG = 2.700022e-004,NADH = 3.299974e-001,PEP = 3.999995e-002,Pyr = 8.699937e+000,ACA = 1.481537e+000,EtOH = 1.923791e+001,EtOHx = 1.645141e+001,Glyc = 4.195995e+000,Glycx = 1.684783e+000,ACAx = 1.288364e+000,CNxminus = 5.203581e+000,AMP = 3.299941e-001
+time = 120, Glcx = 1.758750e+001
+time = 120, Glc = 5.009080e+000
+time = 120, ATP = 2.245170e+000
+time = 120, G6P = 4.617750e+000
+time = 120, ADP = 1.411870e+000
+time = 120, F6P = 5.449350e-001
+time = 120, FBP = 4.688840e+000
+time = 120, GAP = 1.150550e-001
+time = 120, DHAP = 2.982780e+000
+time = 120, NADplus = 6.637320e-001
+time = 120, BPG = 3.055760e-004
+time = 120, NADH = 3.162680e-001
+time = 120, PEP = 4.070840e-002
+time = 120, Pyr = 2.732660e+001
+time = 120, ACA = 1.582410e+000
+time = 120, EtOH = 1.965490e+001
+time = 120, EtOHx = 1.683140e+001
+time = 120, Glyc = 4.395930e+000
+time = 120, Glycx = 1.765630e+000
+time = 120, ACAx = 1.663898e+000
+time = 120, CNxminus = 4.968440e+000
+time = 120, AMP = 2.729600e-001
+time = 20, Glcx = 2.802425e+000
+time = 20, Glc = 1.232681e+000
+time = 20, ATP = 2.075232e+000
+time = 20, G6P = 4.104630e+000
+time = 20, ADP = 1.513974e+000
+time = 20, F6P = 4.779194e-001
+time = 20, FBP = 5.185798e+000
+time = 20, GAP = 1.217449e-001
+time = 20, DHAP = 3.121903e+000
+time = 20, NADplus = 6.371490e-001
+time = 20, BPG = 2.711660e-004
+time = 20, NADH = 3.428510e-001
+time = 20, PEP = 4.091509e-002
+time = 20, Pyr = 1.455773e+001
+time = 20, ACA = 1.515910e+000
+time = 20, EtOH = 1.948145e+001
+time = 20, EtOHx = 1.664728e+001
+time = 20, Glyc = 4.332919e+000
+time = 20, Glycx = 1.734484e+000
+time = 20, ACAx = 1.326834e+000
+time = 20, CNxminus = 5.192535e+000
+time = 20, AMP = 3.407943e-001
+time = 30, Glcx = 4.707406e+000
+time = 30, Glc = 2.067248e+000
+time = 30, ATP = 2.100316e+000
+time = 30, G6P = 4.132511e+000
+time = 30, ADP = 1.499337e+000
+time = 30, F6P = 4.822114e-001
+time = 30, FBP = 5.320994e+000
+time = 30, GAP = 1.232962e-001
+time = 30, DHAP = 3.165687e+000
+time = 30, NADplus = 6.363827e-001
+time = 30, BPG = 2.776353e-004
+time = 30, NADH = 3.436173e-001
+time = 30, PEP = 4.117599e-002
+time = 30, Pyr = 1.936477e+001
+time = 30, ACA = 1.532642e+000
+time = 30, EtOH = 1.956867e+001
+time = 30, EtOHx = 1.672114e+001
+time = 30, Glyc = 4.386919e+000
+time = 30, Glycx = 1.753622e+000
+time = 30, ACAx = 1.341603e+000
+time = 30, CNxminus = 5.188295e+000
+time = 30, AMP = 3.303475e-001
+time = 40, Glcx = 6.671025e+000
+time = 40, Glc = 2.779759e+000
+time = 40, ATP = 1.970142e+000
+time = 40, G6P = 4.078857e+000
+time = 40, ADP = 1.572638e+000
+time = 40, F6P = 4.701445e-001
+time = 40, FBP = 5.345308e+000
+time = 40, GAP = 1.236676e-001
+time = 40, DHAP = 3.164761e+000
+time = 40, NADplus = 6.297851e-001
+time = 40, BPG = 2.541788e-004
+time = 40, NADH = 3.502149e-001
+time = 40, PEP = 4.131294e-002
+time = 40, Pyr = 2.207275e+001
+time = 40, ACA = 1.536590e+000
+time = 40, EtOH = 1.960308e+001
+time = 40, EtOHx = 1.674866e+001
+time = 40, Glyc = 4.384283e+000
+time = 40, Glycx = 1.760923e+000
+time = 40, ACAx = 1.347767e+000
+time = 40, CNxminus = 5.186677e+000
+time = 40, AMP = 3.872205e-001
+time = 50, Glcx = 8.156723e+000
+time = 50, Glc = 3.190142e+000
+time = 50, ATP = 2.243777e+000
+time = 50, G6P = 4.356720e+000
+time = 50, ADP = 1.412105e+000
+time = 50, F6P = 5.153919e-001
+time = 50, FBP = 5.141786e+000
+time = 50, GAP = 1.208989e-001
+time = 50, DHAP = 3.122967e+000
+time = 50, NADplus = 6.498441e-001
+time = 50, BPG = 3.077847e-004
+time = 50, NADH = 3.301559e-001
+time = 50, PEP = 4.103520e-002
+time = 50, Pyr = 2.349114e+001
+time = 50, ACA = 1.552601e+000
+time = 50, EtOH = 1.960148e+001
+time = 50, EtOHx = 1.676095e+001
+time = 50, Glyc = 4.421766e+000
+time = 50, Glycx = 1.764058e+000
+time = 50, ACAx = 1.349403e+000
+time = 50, CNxminus = 5.186006e+000
+time = 50, AMP = 2.741177e-001
+time = 60, Glcx = 9.645909e+000
+time = 60, Glc = 3.645198e+000
+time = 60, ATP = 2.085866e+000
+time = 60, G6P = 4.126192e+000
+time = 60, ADP = 1.507726e+000
+time = 60, F6P = 4.807281e-001
+time = 60, FBP = 5.422917e+000
+time = 60, GAP = 1.244911e-001
+time = 60, DHAP = 3.195887e+000
+time = 60, NADplus = 6.339630e-001
+time = 60, BPG = 2.760613e-004
+time = 60, NADH = 3.460370e-001
+time = 60, PEP = 4.136867e-002
+time = 60, Pyr = 2.451329e+001
+time = 60, ACA = 1.542389e+000
+time = 60, EtOH = 1.962571e+001
+time = 60, EtOHx = 1.676841e+001
+time = 60, Glyc = 4.417965e+000
+time = 60, Glycx = 1.766012e+000
+time = 60, ACAx = 1.351254e+000
+time = 60, CNxminus = 5.185553e+000
+time = 60, AMP = 3.364078e-001
+time = 70, Glcx = 1.163788e+001
+time = 70, Glc = 4.007391e+000
+time = 70, ATP = 1.917179e+000
+time = 70, G6P = 4.260979e+000
+time = 70, ADP = 1.601246e+000
+time = 70, F6P = 4.881074e-001
+time = 70, FBP = 5.014638e+000
+time = 70, GAP = 1.195787e-001
+time = 70, DHAP = 3.060856e+000
+time = 70, NADplus = 6.368836e-001
+time = 70, BPG = 2.439078e-004
+time = 70, NADH = 3.431164e-001
+time = 70, PEP = 4.110717e-002
+time = 70, Pyr = 2.541478e+001
+time = 70, ACA = 1.553133e+000
+time = 70, EtOH = 1.961728e+001
+time = 70, EtOHx = 1.677463e+001
+time = 70, Glyc = 4.375059e+000
+time = 70, Glycx = 1.767928e+000
+time = 70, ACAx = 1.353731e+000
+time = 70, CNxminus = 5.185139e+000
+time = 70, AMP = 4.115748e-001
+time = 80, Glcx = 1.313235e+001
+time = 80, Glc = 4.356328e+000
+time = 80, ATP = 1.908551e+000
+time = 80, G6P = 4.150472e+000
+time = 80, ADP = 1.605378e+000
+time = 80, F6P = 4.755556e-001
+time = 80, FBP = 5.216240e+000
+time = 80, GAP = 1.220930e-001
+time = 80, DHAP = 3.122482e+000
+time = 80, NADplus = 6.309519e-001
+time = 80, BPG = 2.435722e-004
+time = 80, NADH = 3.490481e-001
+time = 80, PEP = 4.129238e-002
+time = 80, Pyr = 2.602759e+001
+time = 80, ACA = 1.547437e+000
+time = 80, EtOH = 1.963170e+001
+time = 80, EtOHx = 1.677857e+001
+time = 80, Glyc = 4.385896e+000
+time = 80, Glycx = 1.768899e+000
+time = 80, ACAx = 1.354355e+000
+time = 80, CNxminus = 5.184915e+000
+time = 80, AMP = 4.160714e-001
+time = 90, Glcx = 1.462947e+001
+time = 90, Glc = 4.556082e+000
+time = 90, ATP = 2.264016e+000
+time = 90, G6P = 4.594370e+000
+time = 90, ADP = 1.399773e+000
+time = 90, F6P = 5.435173e-001
+time = 90, FBP = 4.772817e+000
+time = 90, GAP = 1.161592e-001
+time = 90, DHAP = 3.010481e+000
+time = 90, NADplus = 6.618877e-001
+time = 90, BPG = 3.102375e-004
+time = 90, NADH = 3.181123e-001
+time = 90, PEP = 4.073758e-002
+time = 90, Pyr = 2.653854e+001
+time = 90, ACA = 1.572089e+000
+time = 90, EtOH = 1.960636e+001
+time = 90, EtOHx = 1.678245e+001
+time = 90, Glyc = 4.417565e+000
+time = 90, Glycx = 1.769859e+000
+time = 90, ACAx = 1.354216e+000
+time = 90, CNxminus = 5.184738e+000
+time = 90, AMP = 2.662117e-001
+time = 100, Glcx = 1.612436e+001
+time = 100, Glc = 4.950561e+000
+time = 100, ATP = 2.031232e+000
+time = 100, G6P = 4.091012e+000
+time = 100, ADP = 1.538915e+000
+time = 100, F6P = 4.741648e-001
+time = 100, FBP = 5.468442e+000
+time = 100, GAP = 1.250671e-001
+time = 100, DHAP = 3.205977e+000
+time = 100, NADplus = 6.303416e-001
+time = 100, BPG = 2.664400e-004
+time = 100, NADH = 3.496584e-001
+time = 100, PEP = 4.146546e-002
+time = 100, Pyr = 2.698536e+001
+time = 100, ACA = 1.544360e+000
+time = 100, EtOH = 1.964688e+001
+time = 100, EtOHx = 1.678464e+001
+time = 100, Glyc = 4.421544e+000
+time = 100, Glycx = 1.770327e+000
+time = 100, ACAx = 1.354801e+000
+time = 100, CNxminus = 5.184595e+000
+time = 100, AMP = 3.598532e-001
+time = 110, Glcx = 1.762300e+001
+time = 110, Glc = 5.080046e+000
+time = 110, ATP = 1.902460e+000
+time = 110, G6P = 4.178674e+000
+time = 110, ADP = 1.608594e+000
+time = 110, F6P = 4.784323e-001
+time = 110, FBP = 5.174879e+000
+time = 110, GAP = 1.215767e-001
+time = 110, DHAP = 3.109613e+000
+time = 110, NADplus = 6.319559e-001
+time = 110, BPG = 2.424658e-004
+time = 110, NADH = 3.480441e-001
+time = 110, PEP = 4.127520e-002
+time = 110, Pyr = 2.723851e+001
+time = 110, ACA = 1.550692e+000
+time = 110, EtOH = 1.963807e+001
+time = 110, EtOHx = 1.678598e+001
+time = 110, Glyc = 4.387333e+000
+time = 110, Glycx = 1.770884e+000
+time = 110, ACAx = 1.355975e+000
+time = 110, CNxminus = 5.184477e+000
+time = 110, AMP = 4.189462e-001
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/ModredExample/HynneProject/models/hynneModel.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/ModredExample/HynneProject/models/hynneModel.txt
new file mode 100644
index 0000000000000000000000000000000000000000..4536ca23a36c99aecbab3e3f106d98468b0ac51b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/ModredExample/HynneProject/models/hynneModel.txt
@@ -0,0 +1,174 @@
+********** MODEL NAME
+HynneGlycolysisModel
+
+********** MODEL NOTES
+Full-scale model of glycolysis in Saccharomyces cerevisiae                                                                             
+F. Hynne, S. Dano, and PG, Sorensen                                                                                                    
+Biophysical Chemistry 94 (2001) 121-163                                                                                                
+                                                                                                                                       
+Time units: minutes                                                                                                                    
+Species units: mM                                                                                                                      
+                                                                                                                                       
+Initialconditions do not give a steady-state, but a state-that allows                                                                  
+to see the oscillations when simulating.
+
+********** MODEL STATES
+d/dt(Glcx) = inGlc-0.0169491525423729*GlcTrans    
+d/dt(Glc) = GlcTrans-HK                                                                                                                      
+d/dt(ATP) = -HK-PFK+lpPEP+PK-storage-consum-AK                                                                                         
+d/dt(G6P) = HK-PGI-storage                                                                                                             
+d/dt(ADP) = HK+PFK-lpPEP-PK+storage+consum+2*AK                                                                                        
+d/dt(F6P) = PGI-PFK                                                                                                                    
+d/dt(FBP) = PFK-ALD                                                                                                                    
+d/dt(GAP) = ALD+TIM-GAPDH                                                                                                              
+d/dt(DHAP) = ALD-TIM-lpGlyc                                                                                                            
+d/dt(NADplus) = -GAPDH+ADH+lpGlyc                                                                                                      
+d/dt(BPG) = GAPDH-lpPEP                                                                                                                
+d/dt(NADH) = GAPDH-ADH-lpGlyc                                                                                                          
+d/dt(PEP) = lpPEP-PK                                                                                                                   
+d/dt(Pyr) = PK-PDC                                                                                                                     
+d/dt(ACA) = PDC-ADH-difACA                                                                                                             
+d/dt(EtOH) = ADH-difEtOH                                                                                                               
+d/dt(EtOHx) = 0.0169491525423729*difEtOH-outEtOH                                                                                       
+d/dt(Glyc) = lpGlyc-difGlyc                                                                                                            
+d/dt(Glycx) = 0.0169491525423729*difGlyc-outGlyc                                                                                       
+d/dt(ACAx) = 0.0169491525423729*difACA-outACA-lacto                                                                                    
+d/dt(CNxminus) = -lacto+inCN                                                                                                           
+d/dt(AMP) = -AK                                                                                                                        
+                     
+Glcx(0) = 1.553067e+000
+Glc(0) = 5.730636e-001
+ATP(0) = 2.100013e+000
+G6P(0) = 4.200046e+000
+ADP(0) = 1.499993e+000
+F6P(0) = 4.900058e-001
+FBP(0) = 4.639941e+000
+GAP(0) = 1.149991e-001
+DHAP(0) = 2.949984e+000
+NADplus(0) = 6.500026e-001
+BPG(0) = 2.700022e-004
+NADH(0) = 3.299974e-001
+PEP(0) = 3.999995e-002
+Pyr(0) = 8.699937e+000
+ACA(0) = 1.481537e+000
+EtOH(0) = 1.923791e+001
+EtOHx(0) = 1.645141e+001
+Glyc(0) = 4.195995e+000
+Glycx(0) = 1.684783e+000
+ACAx(0) = 1.288364e+000
+CNxminus(0) = 5.203581e+000
+AMP(0) = 3.299941e-001
+
+********** MODEL PARAMETERS
+V2m = 1014.96                                                                                                                          
+V3m = 51.7547                                                                                                                          
+V4m = 496.04199999999997                                                                                                               
+V5m = 45.432699999999997                                                                                                               
+V6f = 2207.8200000000002                                                                                                               
+V6r = 11039.1                                                                                                                          
+V7m = 116.36499999999999                                                                                                               
+V8m = 833.85799999999995                                                                                                               
+k9f = 443866                                                                                                                           
+k9r = 1528.6199999999999                                                                                                               
+V10m = 343.096                                                                                                                         
+V11m = 53.132800000000003                                                                                                              
+V12m = 89.802300000000002                                                                                                              
+k13 = 16.719999999999999                                                                                                               
+V15m = 81.479699999999994                                                                                                              
+k16 = 1.8999999999999999                                                                                                               
+k18 = 24.699999999999999                                                                                                               
+k20 = 0.0028382799999999999                                                                                                            
+k22 = 2.2593200000000002                                                                                                               
+k23 = 3.2075999999999998                                                                                                               
+k24f = 432.89999999999998                                                                                                              
+k24r = 133.333                                                                                                                         
+K2Glc = 1.7                                                                                                                            
+K2IG6P = 1.2                                                                                                                           
+K2IIG6P = 7.2000000000000002                                                                                                           
+P2 = 1                                                                                                                                 
+K3ATP = 0.10000000000000001                                                                                                            
+K3Glc = 0                                                                                                                              
+K3DGlc = 0.37                                                                                                                          
+K4G6P = 0.80000000000000004                                                                                                            
+K4F6P = 0.14999999999999999                                                                                                            
+K4eq = 0.13                                                                                                                            
+K5 = 0.021000000000000001                                                                                                              
+kappa5 = 0.14999999999999999                                                                                                           
+K6eq = 0.081000000000000003                                                                                                            
+K6FBP = 0.29999999999999999                                                                                                            
+K6GAP = 4                                                                                                                              
+K6DHAP = 2                                                                                                                             
+K6IGAP = 10                                                                                                                            
+K7DHAP = 1.23                                                                                                                          
+K7GAP = 1.27                                                                                                                           
+K7eq = 0.055                                                                                                                           
+K8GAP = 0.59999999999999998                                                                                                            
+K8BPG = 0.01                                                                                                                           
+K8NAD = 0.10000000000000001                                                                                                            
+K8NADH = 0.059999999999999998                                                                                                          
+K8eq = 0.0054999999999999997                                                                                                           
+K10ADP = 0.17000000000000001                                                                                                           
+K10PEP = 0.20000000000000001                                                                                                           
+K11 = 0.29999999999999999                                                                                                              
+K12ACA = 0.70999999999999996                                                                                                           
+K12NADH = 0.10000000000000001                                                                                                          
+K15NADH = 0.13                                                                                                                         
+K15DHAP = 25                                                                                                                           
+K15INADH = 0.034000000000000002                                                                                                        
+K15INAD = 0.13
+Glcx0 = 1.850000e+001
+CNxminus0 = 5.600000e+000
+k0 = 4.800000e-002
+
+********** MODEL VARIABLES                                                                                                        
+GlcTransF = V2m*(Glcx/K2Glc)/(1+Glcx/K2Glc+(P2*Glcx/K2Glc+1)/(P2*Glc/K2Glc+1)*(1+(Glc/K2Glc)+(G6P/K2IG6P)+(Glc*G6P/(K2Glc*K2IIG6P))))  
+GlcTransR = V2m*(Glc/K2Glc)/(1+Glc/K2Glc+(P2*Glc/K2Glc+1)/(P2*Glcx/K2Glc+1)*(1+Glcx/K2Glc)+G6P/K2IG6P+Glc*G6P/(K2Glc*K2IIG6P))         
+HKF = V3m*ATP*Glc/(K3DGlc*K3ATP+K3Glc*ATP+K3ATP*Glc+Glc*ATP)                                                                           
+PGIF = V4m*G6P/(K4G6P+G6P+(K4G6P/K4F6P)*F6P)                                                                                           
+PGIR = V4m*(F6P/K4eq)/(K4G6P+G6P+(K4G6P/K4F6P)*F6P)                                                                                    
+PFKF = V5m*(F6P*F6P)/(K5*(1+kappa5*((ATP*ATP)/(AMP*AMP)))+(F6P*F6P))                                                                   
+ALDden = K6FBP+FBP+(GAP*K6DHAP*V6f)/(K6eq*V6r)+(DHAP*K6GAP*V6f)/(K6eq*V6r)+(FBP*GAP)/K6IGAP+(GAP*DHAP*V6f)/(K6eq*V6r)                  
+ALDF = (V6f*FBP)/ALDden                                                                                                                
+ALDR = V6f*(GAP*DHAP)/K6eq/ALDden                                                                                                      
+TIMden = K7DHAP+DHAP+(K7DHAP/K7GAP)*GAP                                                                                                
+TIMF = V7m*DHAP/TIMden                                                                                                                 
+TIMR = V7m*GAP/K7eq/TIMden                                                                                                             
+GAPDHden = K8GAP*K8NAD*(1+(GAP/K8GAP)+(BPG/K8BPG))*(1+(NADplus/K8NAD)+(NADH/K8NADH))                                                   
+GAPDHF = V8m*GAP*NADplus/GAPDHden                                                                                                      
+GAPDHR = V8m*BPG*NADH/K8eq/GAPDHden                                                                                                    
+lpGlycF = V15m*DHAP/(K15DHAP*(1+(K15INADH/NADH)*(1+(NADplus/K15INAD)))+DHAP*(1+(K15NADH/NADH)*(1+NADplus/K15INAD)))
+
+********** MODEL REACTIONS
+inGlc = k0*(Glcx0-Glcx)                                                                                                                
+GlcTrans = GlcTransF-GlcTransR                                                                                                         
+HK = HKF                                                                                                                               
+PGI = PGIF-PGIR                                                                                                                        
+PFK = PFKF                                                                                                                             
+ALD = ALDF-ALDR                                                                                                                        
+TIM = TIMF-TIMR                                                                                                                        
+GAPDH = GAPDHF-GAPDHR                                                                                                                  
+lpPEP = k9f*BPG*ADP-k9r*PEP*ATP                                                                                                        
+PK = (V10m*ADP*PEP)/((K10PEP+PEP)*(K10ADP+ADP))                                                                                        
+PDC = V11m*Pyr/(K11+Pyr)                                                                                                               
+ADH = V12m*ACA*NADH/((K12NADH+NADH)*(K12ACA+ACA))                                                                                      
+difEtOH = k13*(EtOH-EtOHx)                                                                                                             
+outEtOH = k0*EtOHx                                                                                                                     
+lpGlyc = lpGlycF                                                                                                                       
+difGlyc = k16*(Glyc-Glycx)                                                                                                             
+outGlyc = k0*Glycx                                                                                                                     
+difACA = k18*(ACA-ACAx)                                                                                                                
+outACA = k0*ACAx                                                                                                                       
+lacto = k20*ACAx*CNxminus                                                                                                              
+inCN = k0*(CNxminus0-CNxminus)                                                                                                         
+storage = k22*ATP*G6P                                                                                                                  
+consum = k23*ATP                                                                                                                       
+AK = k24f*AMP*ATP-k24r*ADP*ADP
+
+********** MODEL FUNCTIONS
+
+
+********** MODEL EVENTS
+
+
+********** MODEL MATLAB FUNCTIONS
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/ModredExample/reduceExample.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/ModredExample/reduceExample.m
new file mode 100644
index 0000000000000000000000000000000000000000..6bcba7241dd167ea8ed17bcaa41552d86c5fbd13
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/ModredExample/reduceExample.m
@@ -0,0 +1,71 @@
+% Model reduction example script
+
+academicWarningSBPD
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+%% First we apply the model reduction functionality to a project.
+project = SBPDproject('HynneProject');
+% The project contains 1 model and 1 experiment. The measurement data for
+% the experiment have been generated in silico and their only purpose is
+% to provide the timevector that is used for the reduction algorithm. 
+
+%% Apply the reduction of the kinetic rate expressions
+project = SBPDreducerateexpressions(project)
+% You will see a warning message. Press a key! Then just follow the script
+% ... The output argument of the function is an SBPDproject equal to the 
+% one given as input argument but with the reduced model added.
+
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% For the reduction of rate expressions a project is not needed. Instead
+% you can do as follows:
+
+%% Load a model (here we get it out of the project ...)
+model = SBPDgetmodel(project,1);
+
+%% Define the experiment to consider
+experiments = SBPDgetexperiment(project,1);
+% Several experiments can be defined by grouping them into a cell-array
+
+%% Define the time-vector of interest
+timevectors = [0:0.1:190];
+% If several experiments are defined then for each a timevector needs to be
+% defined within a cell-array.
+
+%% Perform the reduction
+modelred = SBredallreac(model,experiments,timevectors)
+
+%% Write the result
+SBcreateTEXTfile(modelred,'hynneModel_reduced');
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Instead of the guided reduction of the full model also single reactions 
+% in the model can be reduced. It goes as follows:
+
+%% Load a model (again, here we get it out of the project ...)
+model = SBPDgetmodel(project,1);
+
+%% Define the experiment to consider
+experiments = {SBPDgetexperiment(project,1)};
+% Several experiments can be defined by grouping them into a cell-array
+
+%% Define the time-vector of interest
+time = {[0:0.1:190]};
+% If several experiments are defined then for each a timevector needs to be
+% defined within a cell-array.
+
+%% Prepare the model for the reduction and perform the experiments
+output = SBprepredreac(model, time, experiments);
+
+%% Define the reaction to reduce
+reaction = 'HK';                    
+
+%% Perform the reduction
+modelred = SBredreac(output,reaction);
+
+%% Show the reduced model
+SBedit(modelred)
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_accumulation_ThDP_10uM/PHO3DaccumulationThDP10uM.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_accumulation_ThDP_10uM/PHO3DaccumulationThDP10uM.exp
new file mode 100644
index 0000000000000000000000000000000000000000..727fa65bfa7257ca15e49e29db76dedcc45ba27a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_accumulation_ThDP_10uM/PHO3DaccumulationThDP10uM.exp
@@ -0,0 +1,16 @@
+********** EXPERIMENT NAME
+PHO3D accumulation ThDP 10uM
+
+********** EXPERIMENT NOTES
+
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+Thex(0) = 0.01
+ThMPex(0) = 0.1
+ThDPex(0) = 10
+
+k_PHO3 = 0
+
+********** EXPERIMENT PARAMETER CHANGES
+
+********** EXPERIMENT STATE CHANGES
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_accumulation_ThDP_10uM/notes.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_accumulation_ThDP_10uM/notes.txt
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_accumulation_ThDP_10uM/pho3DThiamineaccumulationThDP10uM.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_accumulation_ThDP_10uM/pho3DThiamineaccumulationThDP10uM.csv
new file mode 100644
index 0000000000000000000000000000000000000000..e3d411c6ba241928a001e23a305c9a1409a0ac03
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_accumulation_ThDP_10uM/pho3DThiamineaccumulationThDP10uM.csv
@@ -0,0 +1,19 @@
+% Measurement file generated: 12-Jul-2007
+
+[Name]
+pho3DThiamineaccumulationThDP10uM
+
+[Notes]
+Intracellular th in pho3D. o/n incubation w/o thiamine followed by 10uM thdp
+
+[Components]
+time,ThDP,ThMP,Th
+
+[Componentnotes]
+
+[Values]
+0.000000,43.879749,0.000000,11.979591
+5.000000,405.162363,10.340414,172.845727
+12.000000,687.904739,13.498601,160.859575
+22.000000,681.208892,12.412984,107.275324
+32.000000,696.025338,12.699371,76.716342
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_accumulation_ThMP_10uM/PHO3DaccumulationThMP10uM.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_accumulation_ThMP_10uM/PHO3DaccumulationThMP10uM.exp
new file mode 100644
index 0000000000000000000000000000000000000000..36d5b47c9663b8479bfcde029528213ddad88b4a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_accumulation_ThMP_10uM/PHO3DaccumulationThMP10uM.exp
@@ -0,0 +1,16 @@
+********** EXPERIMENT NAME
+PHO3D accumulation ThMP 10uM
+
+********** EXPERIMENT NOTES
+
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+Thex(0) = 2
+ThMPex(0) = 10
+ThDPex(0) = 0 % uM
+
+k_PHO3 = 0
+
+********** EXPERIMENT PARAMETER CHANGES
+
+********** EXPERIMENT STATE CHANGES
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_accumulation_ThMP_10uM/notes.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_accumulation_ThMP_10uM/notes.txt
new file mode 100644
index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_accumulation_ThMP_10uM/notes.txt
@@ -0,0 +1 @@
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_accumulation_ThMP_10uM/pho3DThiamineaccumulationThMP10uM.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_accumulation_ThMP_10uM/pho3DThiamineaccumulationThMP10uM.csv
new file mode 100644
index 0000000000000000000000000000000000000000..777ede249861b5e78cc9a7e28e96c93ccb6ae88f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_accumulation_ThMP_10uM/pho3DThiamineaccumulationThMP10uM.csv
@@ -0,0 +1,19 @@
+% Measurement file generated: 12-Jul-2007
+
+[Name]
+pho3DThiamineaccumulationThMP10uM
+
+[Notes]
+Intracellular th in pho3D. o/n incubation w/o thiamine followed by 10uM thmp
+
+[Components]
+time,ThDP,ThMP,Th
+
+[Componentnotes]
+
+[Values]
+0.000000,43.879749,0.000000,11.979591
+5.000000,307.472663,465.097901,677.971047
+12.000000,481.739307,1572.723811,1100.077396
+22.000000,609.202433,2535.371145,1637.835117
+32.000000,774.056594,2873.651619,2205.814961
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_balancing_ThDP_10uM/PHO3DbalancingThDP10uM.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_balancing_ThDP_10uM/PHO3DbalancingThDP10uM.exp
new file mode 100644
index 0000000000000000000000000000000000000000..3d5f0c488c5060fb91c303838591cfa3c7d10d21
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_balancing_ThDP_10uM/PHO3DbalancingThDP10uM.exp
@@ -0,0 +1,16 @@
+********** EXPERIMENT NAME
+PHO3D balancing ThDP 10uM
+
+********** EXPERIMENT NOTES
+
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+Thex(0) = 0 % uM
+ThMPex(0) = 0
+ThDPex(0) = 0 % uM
+
+k_PHO3 = 0
+
+********** EXPERIMENT PARAMETER CHANGES
+
+********** EXPERIMENT STATE CHANGES
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_balancing_ThDP_10uM/THDPrebalancinginpho3D10uMthdp.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_balancing_ThDP_10uM/THDPrebalancinginpho3D10uMthdp.csv
new file mode 100644
index 0000000000000000000000000000000000000000..02905a955904bac5385f9896cfa7d3e3743600b6
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_balancing_ThDP_10uM/THDPrebalancinginpho3D10uMthdp.csv
@@ -0,0 +1,19 @@
+% Measurement file generated: 12-Jul-2007
+
+[Name]
+THDPrebalancinginpho3D10uMthdp
+
+[Notes]
+pho3D incubated with 10uM THDP o/n then into media w/o thiamine for 24h. Samples are taken after cells move
+
+[Components]
+time,ThDP,ThMP,Th
+
+[Componentnotes]
+
+[Values]
+0.000000,329.794334,14.710084,30.225127
+10.000000,298.669070,12.673648,28.478123
+20.000000,274.699102,12.267113,27.471333
+50.000000,263.408289,10.714373,35.745092
+110.000000,161.249123,5.440406,33.016437
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_balancing_ThDP_10uM/notes.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_balancing_ThDP_10uM/notes.txt
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_balancing_ThMP_10uM/PHO3DbalancingThMP10uM.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_balancing_ThMP_10uM/PHO3DbalancingThMP10uM.exp
new file mode 100644
index 0000000000000000000000000000000000000000..87b6afc2834a7d7cd322a30282bb2730f5fe2ffa
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_balancing_ThMP_10uM/PHO3DbalancingThMP10uM.exp
@@ -0,0 +1,16 @@
+********** EXPERIMENT NAME
+PHO3D balancing ThMP 10uM
+
+********** EXPERIMENT NOTES
+
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+Thex(0) = 0 % uM
+ThMPex(0) = 0
+ThDPex(0) = 0 % uM
+
+k_PHO3 = 0
+
+********** EXPERIMENT PARAMETER CHANGES
+
+********** EXPERIMENT STATE CHANGES
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_balancing_ThMP_10uM/THMPrebalancinginpho3D10uMthmp.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_balancing_ThMP_10uM/THMPrebalancinginpho3D10uMthmp.csv
new file mode 100644
index 0000000000000000000000000000000000000000..0315539fa1f030995faf1c4a5f1c07f893bb64a1
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_balancing_ThMP_10uM/THMPrebalancinginpho3D10uMthmp.csv
@@ -0,0 +1,19 @@
+% Measurement file generated: 12-Jul-2007
+
+[Name]
+THMPrebalancinginpho3D10uMthmp
+
+[Notes]
+pho3D incubated with 10uM THMP o/n then into media w/o thiamine for 24h. Samples are taken after cells move
+
+[Components]
+time,ThDP,ThMP,Th
+
+[Componentnotes]
+
+[Values]
+0.000000,560.379299,1416.858218,1654.070851
+10.000000,527.747447,928.542711,1335.276914
+20.000000,592.055101,681.707783,1663.176936
+50.000000,629.540830,80.438664,1993.777187
+110.000000,543.242399,39.055697,1411.832440
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_balancing_ThMP_10uM/notes.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/PHO3D_balancing_ThMP_10uM/notes.txt
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_100um/Accumulation_100um_thiamine.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_100um/Accumulation_100um_thiamine.exp
new file mode 100644
index 0000000000000000000000000000000000000000..07eb35a33caef7dd9cec2447a52db85950c4991d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_100um/Accumulation_100um_thiamine.exp
@@ -0,0 +1,18 @@
+********** EXPERIMENT NAME
+Accumulation_100um_thiamine
+
+********** EXPERIMENT NOTES
+
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+Thex(0) = 100 % uM
+ThMPex(0) = 0
+ThDPex(0) = 0
+
+
+********** EXPERIMENT PARAMETER CHANGES
+
+
+********** EXPERIMENT STATE CHANGES
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_100um/WTThiamineaccumulation100uM.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_100um/WTThiamineaccumulation100uM.csv
new file mode 100644
index 0000000000000000000000000000000000000000..6195b6a51103c7be1682d5cdf2d3d0df53bee8e3
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_100um/WTThiamineaccumulation100uM.csv
@@ -0,0 +1,26 @@
+% Measurement file generated: 12-Jul-2007
+
+[Name]
+WTThiamineaccumulation100uM
+
+[Notes]
+Experiment description - WT incubated w/o th o/n then 100uM th samples taken after. All measurements in uM.
+
+[Components]
+time,ThDP,ThMP,Th
+
+[Componentnotes]
+
+[Values]
+0.000000,16.083770,2.526010,6.088757
+1.000000,131.186042,23.351411,854.300502
+4.000000,181.553296,32.797588,1789.065655
+6.000000,331.636547,79.796050,2481.843898
+9.000000,238.505207,47.413173,3152.000000
+12.000000,356.716766,85.146282,4997.547810
+15.000000,291.627983,86.893768,4986.379899
+22.000000,282.153046,81.615433,5355.248240
+30.000000,520.236272,162.307687,6741.466202
+45.000000,805.310548,191.058751,8745.201082
+60.000000,662.628626,160.646542,10449.892780
+120.000000,707.523562,197.967896,12900.000000
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_100um/notes.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_100um/notes.txt
new file mode 100644
index 0000000000000000000000000000000000000000..7a16db31e57f303942076be9bdcf97ed096a2f09
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_100um/notes.txt
@@ -0,0 +1,5 @@
+WT accumulation of thiamine in yeast.
+Cells cultured o/n w/o thiamine in the medium.
+Then adding 100um thiamine to the medium and 
+taking samples thereafter.
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_10um/Accumulation_10um_thiamine.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_10um/Accumulation_10um_thiamine.exp
new file mode 100644
index 0000000000000000000000000000000000000000..c57819f4bf3c27052e59d4d053584154af7c4ffb
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_10um/Accumulation_10um_thiamine.exp
@@ -0,0 +1,15 @@
+********** EXPERIMENT NAME
+Accumulation_10um_thiamine
+
+********** EXPERIMENT NOTES
+
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+Thex(0) = 10 % uM
+ThMPex(0) = 0
+ThDPex(0) = 0
+
+
+********** EXPERIMENT PARAMETER CHANGES
+
+********** EXPERIMENT STATE CHANGES
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_10um/WTThiamineaccumulation10uM.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_10um/WTThiamineaccumulation10uM.csv
new file mode 100644
index 0000000000000000000000000000000000000000..4abc2e17fc75f19e1bc227ce0eaeeebe5dad5e5f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_10um/WTThiamineaccumulation10uM.csv
@@ -0,0 +1,26 @@
+% Measurement file generated: 12-Jul-2007
+
+[Name]
+WTThiamineaccumulation10uM
+
+[Notes]
+Experiment description - WT incubated w/o th o/n then 10uM th samples taken after. All measurements in uM
+
+[Components]
+time,ThDP,ThMP,Th
+
+[Componentnotes]
+
+[Values]
+0.000000,13.592683,2.641193,8.280421
+2.000000,127.235268,37.127671,2438.661422
+5.000000,142.995016,46.294758,2487.097080
+8.000000,225.560677,75.498541,4027.705929
+11.000000,222.476230,72.750897,3835.892491
+14.000000,227.568551,89.256841,3645.581454
+17.000000,232.812114,61.440215,3162.779496
+24.000000,275.782654,90.445931,2671.761302
+30.000000,269.206644,88.007137,3072.569988
+60.000000,422.379817,112.031979,2822.186043
+120.000000,258.856452,71.664568,1842.216941
+180.000000,269.254443,46.418704,1980.587893
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_10um/notes.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_10um/notes.txt
new file mode 100644
index 0000000000000000000000000000000000000000..9be6f2871ee04f1583e4dc0f1d65968102bf3f68
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_10um/notes.txt
@@ -0,0 +1,5 @@
+WT accumulation of thiamine in yeast.
+Cells cultured o/n w/o thiamine in the medium.
+Then adding 10um thiamine to the medium and 
+taking samples thereafter.
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_1um/Accumulation_1um_thiamine.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_1um/Accumulation_1um_thiamine.exp
new file mode 100644
index 0000000000000000000000000000000000000000..fb6a30a7ba00f0ecb3b7e9b83b10070dc7402494
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_1um/Accumulation_1um_thiamine.exp
@@ -0,0 +1,15 @@
+********** EXPERIMENT NAME
+Accumulation_1um_thiamine
+
+********** EXPERIMENT NOTES
+
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+Thex(0) = 1 % uM
+ThMPex(0) = 0
+ThDPex(0) = 0
+
+
+********** EXPERIMENT PARAMETER CHANGES
+
+********** EXPERIMENT STATE CHANGES
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_1um/WTThiamineaccumulation1uM.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_1um/WTThiamineaccumulation1uM.csv
new file mode 100644
index 0000000000000000000000000000000000000000..9a675e0ff00886d5da434370b50bf4f0d8e3be52
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_1um/WTThiamineaccumulation1uM.csv
@@ -0,0 +1,23 @@
+% Measurement file generated: 12-Jul-2007
+
+[Name]
+WTThiamineaccumulation1uM
+
+[Notes]
+Experiment description - WT incubated w/o th o/n then 1uM th samples taken after. All measurements in uM.
+
+[Components]
+time,ThDP,ThMP,Th
+
+[Componentnotes]
+
+[Values]
+0.000000,16.083770,2.526010,6.088757
+1.000000,80.802699,12.466020,208.407574
+4.000000,133.436180,17.225538,253.729176
+6.000000,114.272790,13.627292,177.542885
+9.000000,149.110914,17.113859,192.139930
+12.000000,175.268236,23.111233,218.222955
+30.000000,193.364047,20.398068,181.079348
+60.000000,168.035102,10.918975,126.204019
+120.000000,157.413456,14.546469,153.197238
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_1um/notes.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_1um/notes.txt
new file mode 100644
index 0000000000000000000000000000000000000000..b2532baf1b76ae5206ed874595bcb1195091d4f5
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_1um/notes.txt
@@ -0,0 +1,5 @@
+WT accumulation of thiamine in yeast.
+Cells cultured o/n w/o thiamine in the medium.
+Then adding 1um thiamine to the medium and 
+taking samples thereafter.
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_2um/Accumulation_2um_thiamine.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_2um/Accumulation_2um_thiamine.exp
new file mode 100644
index 0000000000000000000000000000000000000000..61aeb85161cb8e6d292bcfbce9f380dc4df61b2a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_2um/Accumulation_2um_thiamine.exp
@@ -0,0 +1,14 @@
+********** EXPERIMENT NAME
+Accumulation_2um_thiamine
+
+********** EXPERIMENT NOTES
+
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+Thex(0) = 2 % uM
+ThMPex(0) = 0
+ThDPex(0) = 0
+
+********** EXPERIMENT PARAMETER CHANGES
+
+********** EXPERIMENT STATE CHANGES
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_2um/WTThiamineaccumulation2uM.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_2um/WTThiamineaccumulation2uM.csv
new file mode 100644
index 0000000000000000000000000000000000000000..29a8468793660609b3eec4a42c8a5bdb7a84f1f2
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_2um/WTThiamineaccumulation2uM.csv
@@ -0,0 +1,26 @@
+% Measurement file generated: 12-Jul-2007
+
+[Name]
+WTThiamineaccumulation2uM
+
+[Notes]
+Experiment description - WT incubated w/o th o/n then 2uM th samples taken after. All measurements in uM.
+
+[Components]
+time,ThDP,ThMP,Th
+
+[Componentnotes]
+
+[Values]
+0.000000,15.137686,3.089039,10.216738
+2.000000,87.645519,24.689845,683.046057
+5.000000,182.011740,29.745260,453.667293
+8.000000,141.571151,28.115616,587.819206
+11.000000,154.023297,25.092005,528.757030
+14.000000,149.883317,26.142246,479.836700
+17.000000,170.101431,29.154329,480.782900
+24.000000,168.825718,28.183505,410.939491
+30.000000,202.047177,31.952293,457.743133
+60.000000,164.981917,43.109321,389.071206
+120.000000,117.619487,32.356405,331.898394
+180.000000,128.793476,19.333544,304.282683
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_2um/notes.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_2um/notes.txt
new file mode 100644
index 0000000000000000000000000000000000000000..c2544ae220e0aaa17fdf0c116a0b2f965ddc49ae
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/experiments/WT_accumulation_Th_2um/notes.txt
@@ -0,0 +1,5 @@
+WT accumulation of thiamine in yeast.
+Cells cultured o/n w/o thiamine in the medium.
+Then adding 2um thiamine to the medium and 
+taking samples thereafter.
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/models/anothermodel.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/models/anothermodel.txt
new file mode 100644
index 0000000000000000000000000000000000000000..dc65a0765c963f6991ce0fe3b01ca311a3a22684
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/models/anothermodel.txt
@@ -0,0 +1,98 @@
+********** MODEL NAME
+anothermodel
+
+********** MODEL NOTES
+All parameters estimated + manual tuning of the transport parameters.
+An ok fit requires 3uM of free thiamine in the PHO3D experiments!
+
+All concentrations in uM
+Time units in minutes
+
+Initial conditions chosen to reflect a cell that is in thiamine limitation 
+levels of Th(M/D P) that reflect the basal levels.
+
+********** MODEL STATES
+d/dt(ThDPex) = (-v_PHO3-v_Thi7ThDP-v_Thi71ThDP)/EC 
+d/dt(ThMPex) = (-v_PHO3m+v_PHO3-v_Thi7ThMP-v_Thi71ThMP)/EC 
+d/dt(Thex) = (+v_PHO3m-v_Thi7Th-v_Thi71Th)/EC 
+d/dt(ThDP) = (+v_Thi80-v_Y+v_Thi7ThDP+v_Thi71ThDP-v_ThDPdeg)/CY-ThDP*ddtCY/CY 
+d/dt(ThMP) = (-v_X+v_ThMPsyn+v_Y+v_Thi7ThMP+v_Thi71ThMP-v_ThMPdeg)/CY-ThMP*ddtCY/CY 
+d/dt(Th) = (-v_Thi80+v_X+v_Thi7Th+v_Thi71Th-v_Thdeg)/CY-Th*ddtCY/CY 
+d/dt(Thi7) = (v_Thi7syn-v_Thi7deg)/CY-Thi7*ddtCY/CY 
+d/dt(Thi71) = (v_Thi71syn-v_Thi71deg)/CY-Thi71*ddtCY/CY 
+
+ThDPex(0) = 0
+ThMPex(0) = 0
+Thex(0) = 0
+ThDP(0) = 20
+ThMP(0) = 2
+Th(0) = 5
+Thi7(0) = 1
+Thi71(0) = 1
+
+
+********** MODEL PARAMETERS
+EC = 400
+k_Thi7d = 181.19316941644144 
+Km_Thi7d = 8.4759599999999882 
+k_Thi7m = 67.840499999999992 
+Km_Thi7m = 0.1905460000000001 
+k_Thi7 = 121.8072198948425 
+Km_Thi7 = 0.79999999999999993 
+h_Thi7 = 1.9999999999999982 
+V_synThi7 = 3.421489999999999 
+Ki_synThi7 = 319.62599999999975 
+ni_synThi7 = 1 
+kdeg_Thi7 = 0.99896399999999996 
+V_Thi80 = 349.96510429759684 
+Km_Thi80 = 1.0174699999999999 
+h_Thi80 = 2.0200289939437224 
+V_X = 39.650558346089845  %At upper bound (value adjusted to be inside bounds)
+Km_X = 57.366209715329795 
+V_Y = 10.807899999999993 
+Km_Y = 108.2369999999999  %At lower bound (value adjusted to be inside bounds)
+V_synThMP = 10.1244 
+Ki_synThMP = 507905.99999999884 
+ni_synThMP = 1.9999999999999982 
+Vdeg_Th = 0.099515117644716086 
+Kmdeg_Th = 149.97697372758481 
+doublingtime = 150 
+ThDPLevelsynThMP = 200 
+k_PHO3 = 20 
+
+
+********** MODEL VARIABLES
+CY = 2^(time/doublingtime)  %doubling time 120min a./(1+exp(b-c*time)) % logistic equation for total cytosol volume ... growth over 8 hours
+ddtCY = 2^(time/doublingtime)/doublingtime*log(2)  %a*c*exp(b-c*time)/(1+exp(b-c*time))^2 % time-derivative of CY
+
+
+********** MODEL REACTIONS
+v_PHO3 = kin_mass_action_irr(k_PHO3,ThDPex)*EC
+v_PHO3m = kin_mass_action_irr(k_PHO3,ThMPex)*EC
+v_Thi80 = kin_hill_cooperativity_irr(V_Thi80,Th,h_Thi80,Km_Thi80) 
+v_X = kin_michaelis_menten_irr(V_X,ThMP,Km_X)*CY
+v_Y = kin_michaelis_menten_irr(V_Y,ThDP,Km_Y)*CY
+v_Thi7deg = kin_degradation(kdeg_Thi7,Thi7)*CY
+v_Thi71deg = 0
+v_Thi7ThDP = kin_hill_cooperativity_irr(k_Thi7d*Thi7,ThDPex,h_Thi7,Km_Thi7d)*CY
+v_Thi7ThMP = kin_hill_cooperativity_irr(k_Thi7m*Thi7,ThMPex,h_Thi7,Km_Thi7m)*CY
+v_Thi7Th = kin_hill_cooperativity_irr(k_Thi7*Thi7,Thex,h_Thi7,Km_Thi7)*CY
+v_Thi71ThDP = 0
+v_Thi71ThMP = 0
+v_Thi71Th = 0
+v_ThMPsyn = V_synThMP*max((1/(1+power(ThDP/Ki_synThMP,ni_synThMP))-1/(1+power(ThDPLevelsynThMP/Ki_synThMP,ni_synThMP))),0)*CY
+v_Thi7syn = V_synThi7*1/(1+power(ThDP/Ki_synThi7,ni_synThi7))*CY
+v_Thi71syn = 0
+v_Thdeg = kin_michaelis_menten_irr(Vdeg_Th,Th,Kmdeg_Th)*CY
+v_ThMPdeg = kin_michaelis_menten_irr(Vdeg_Th,ThMP,Kmdeg_Th)*CY
+v_ThDPdeg = kin_michaelis_menten_irr(Vdeg_Th,ThDP,Kmdeg_Th)*CY
+
+
+********** MODEL FUNCTIONS
+
+
+********** MODEL EVENTS
+
+
+********** MODEL MATLAB FUNCTIONS
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/models/onemodel.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/models/onemodel.txt
new file mode 100644
index 0000000000000000000000000000000000000000..22d94e8c7c1d11f54f243d2266dd454f01f13f0f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/models/onemodel.txt
@@ -0,0 +1,100 @@
+********** MODEL NAME
+one model
+
+********** MODEL NOTES
+All parameters estimated + manual tuning of the transport parameters.
+An ok fit requires 3uM of free thiamine in the PHO3D experiments!
+
+All concentrations in uM
+Time units in minutes
+
+Initial conditions chosen to reflect a cell that is in thiamine limitation 
+levels of Th(M/D P) that reflect the basal levels.
+
+********** MODEL STATES
+d/dt(ThDPex) = (-v_PHO3-v_Thi7ThDP-v_Thi71ThDP)/EC 
+d/dt(ThMPex) = (-v_PHO3m+v_PHO3-v_Thi7ThMP-v_Thi71ThMP)/EC 
+d/dt(Thex) = (+v_PHO3m-v_Thi7Th-v_Thi71Th)/EC 
+d/dt(ThDP) = (+v_Thi80-v_Y+v_Thi7ThDP+v_Thi71ThDP-v_ThDPdeg)/CY-ThDP*ddtCY/CY 
+d/dt(ThMP) = (-v_X+v_ThMPsyn+v_Y+v_Thi7ThMP+v_Thi71ThMP-v_ThMPdeg)/CY-ThMP*ddtCY/CY 
+d/dt(Th) = (-v_Thi80+v_X+v_Thi7Th+v_Thi71Th-v_Thdeg)/CY-Th*ddtCY/CY 
+d/dt(Thi7) = (v_Thi7syn-v_Thi7deg)/CY-Thi7*ddtCY/CY 
+d/dt(Thi71) = (v_Thi71syn-v_Thi71deg)/CY-Thi71*ddtCY/CY 
+
+ThDPex(0) = 0
+ThMPex(0) = 0
+Thex(0) = 0
+ThDP(0) = 20
+ThMP(0) = 2
+Th(0) = 5
+Thi7(0) = 1
+Thi71(0) = 1
+
+********** MODEL PARAMETERS
+EC = 400
+k_Thi7d = 181.19316941644144 
+Km_Thi7d = 8.4759599999999882 
+k_Thi7m = 67.840499999999992 
+Km_Thi7m = 0.1905460000000001 
+k_Thi7 = 121.8072198948425 
+Km_Thi7 = 0.79999999999999993 
+h_Thi7 = 1.9999999999999982 
+V_synThi7 = 3.421489999999999 
+Ki_synThi7 = 319.62599999999975 
+ni_synThi7 = 1 
+kdeg_Thi7 = 0.99896399999999996 
+V_Thi80 = 349.96510429759684 
+Km_Thi80 = 1.0174699999999999 
+Ki_Thi80 = 0.52660262894267929 
+h_Thi80 = 2.0200289939437224 
+hi_Thi80 = 1 
+n_Thi80 = 0.27186231643343423 
+L_Thi80 = 27.830774743062886 
+V_X = 39.650558346089845  %At upper bound (value adjusted to be inside bounds)
+Km_X = 57.366209715329795 
+V_Y = 10.807899999999993 
+Km_Y = 108.2369999999999  %At lower bound (value adjusted to be inside bounds)
+V_synThMP = 10.1244 
+Ki_synThMP = 507905.99999999884 
+ni_synThMP = 1.9999999999999982 
+Vdeg_Th = 0.099515117644716086 
+Kmdeg_Th = 149.97697372758481 
+doublingtime = 150 
+ThDPLevelsynThMP = 200 
+k_PHO3 = 20 
+
+
+********** MODEL VARIABLES
+CY = 2^(time/doublingtime)  %doubling time 120min a./(1+exp(b-c*time)) % logistic equation for total cytosol volume ... growth over 8 hours
+ddtCY = 2^(time/doublingtime)/doublingtime*log(2)  %a*c*exp(b-c*time)/(1+exp(b-c*time))^2 % time-derivative of CY
+
+********** MODEL REACTIONS
+v_PHO3 = kin_mass_action_irr(k_PHO3,ThDPex)*EC
+v_PHO3m = kin_mass_action_irr(k_PHO3,ThMPex)*EC
+v_Thi80 = kin_allosteric_inihib_mwc_irr(V_Thi80,Th,Km_Thi80,n_Thi80,L_Thi80,ThDP,Ki_Thi80) %V_Thi80*power(Th,h_Thi80)/(power(Km_Thi80,h_Thi80)+power(Th,h_Thi80)*power((1+ThDP/Ki_Thi80),hi_Thi80)) %kin_uncomp_inihib_hill_irr
+v_X = kin_michaelis_menten_irr(V_X,ThMP,Km_X)*CY
+v_Y = kin_michaelis_menten_irr(V_Y,ThDP,Km_Y)*CY
+v_Thi7deg = kin_degradation(kdeg_Thi7,Thi7)*CY
+v_Thi71deg = 0
+v_Thi7ThDP = kin_hill_cooperativity_irr(k_Thi7d*Thi7,ThDPex,h_Thi7,Km_Thi7d)*CY
+v_Thi7ThMP = kin_hill_cooperativity_irr(k_Thi7m*Thi7,ThMPex,h_Thi7,Km_Thi7m)*CY
+v_Thi7Th = kin_hill_cooperativity_irr(k_Thi7*Thi7,Thex,h_Thi7,Km_Thi7)*CY
+v_Thi71ThDP = 0
+v_Thi71ThMP = 0
+v_Thi71Th = 0
+v_ThMPsyn = V_synThMP*max((1/(1+power(ThDP/Ki_synThMP,ni_synThMP))-1/(1+power(ThDPLevelsynThMP/Ki_synThMP,ni_synThMP))),0)*CY
+v_Thi7syn = V_synThi7*1/(1+power(ThDP/Ki_synThi7,ni_synThi7))*CY
+v_Thi71syn = 0
+v_Thdeg = kin_michaelis_menten_irr(Vdeg_Th,Th,Kmdeg_Th)*CY
+v_ThMPdeg = kin_michaelis_menten_irr(Vdeg_Th,ThMP,Kmdeg_Th)*CY
+v_ThDPdeg = kin_michaelis_menten_irr(Vdeg_Th,ThDP,Kmdeg_Th)*CY
+
+
+********** MODEL FUNCTIONS
+
+
+********** MODEL EVENTS
+
+
+********** MODEL MATLAB FUNCTIONS
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/notes.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/notes.txt
new file mode 100644
index 0000000000000000000000000000000000000000..8eafbe991cf0d2c335de6381d52cc09f6c0f6761
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/Example_Project/notes.txt
@@ -0,0 +1,3 @@
+Thiamine transport modeling project.
+Uptake of thiamine into the cell, switch to de-novo synthesis of ThMP
+in case of thiamine limitation in medium. Etc. 
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/loadProjectExample.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/loadProjectExample.m
new file mode 100644
index 0000000000000000000000000000000000000000..2cd27a5292e98d95decea6a0c4a30ce899976e54
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/loadProjectExample.m
@@ -0,0 +1,13 @@
+% Just a script for quick loading of the example project
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+olddir = pwd;
+cd(fileparts(which('installSBPD')));
+cd _ACADEMIC/_EXAMPLES/Projects
+project = SBPDproject('Example_Project');
+cd(olddir)
+disp('The project is saved in the ''project'' variable.');
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/runEstimation.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/runEstimation.m
new file mode 100644
index 0000000000000000000000000000000000000000..3b21d9f7ed89becb29b7b1a450254fd3ec441194
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/runEstimation.m
@@ -0,0 +1,87 @@
+% Parameter estimation example script
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+%% Load the project and set the model
+sbp = SBPDproject('Example_Project');
+sbpopt = sbp;
+
+% Show model information
+SBPDinfo(sbp)
+
+% Estimate parameters for second model in the project
+modelindex = 2
+
+%% Define GLOBAL parameters to estimate and lower and upper bound 
+% (commented parameters are not optimized)
+% Parameter         Lower bound         Upper bound
+paramdata = {
+% 'k_Thi7d'         20                  100
+% 'Km_Thi7d'        0.1                 8
+% 'k_Thi7m'         20                  100
+% 'Km_Thi7m'        0.09                2
+'k_Thi7'          100                 150
+'Km_Thi7'         0.1                 2
+% 'h_Thi7'          0.9                 3
+
+% 'V_synThi7'       2                   5
+% 'Ki_synThi7'      250                 400 
+% 'ni_synThi7'      0.99                3
+% 'kdeg_Thi7'       1e-4                2
+
+'V_Thi80'           100                 350
+'Km_Thi80'          1                   1000
+'Ki_Thi80'          0.001               100
+'n_Thi80'           0                   3
+'L_Thi80'           0                   30
+
+'V_X'               20                  70
+'Km_X'              10                  150
+
+'V_Y'               0.1                 12
+'Km_Y'              50                  300
+
+% 'V_synThMP'       1e-4                20
+% 'Ki_synThMP'      100                 1e6
+% 'ni_synThMP'      1                   3
+
+%  'Vdeg_Th'        1e-4                0.5
+%  'Kmdeg_Th'       1e-4                1e5
+};
+
+% Define LOCAL parameters to estimate and lower and upper bound 
+%               Parameter       Lower bound     Upper bound
+paramdatalocal = {
+                'EC'            100             2000
+};
+
+% Define initial conditions to be estimated
+%               Statename       Lower bound     Upper bound
+icdata = {
+};
+
+%% Define estimation structure
+estimation = []; clc;
+
+estimation.experiments.indices = [1:8];  % optimize all 8 experiments
+%estimation.optimization.method = 'pswarmSB';
+estimation.optimization.method = 'simplexSB';
+estimation.timescalingFlag = 2;
+estimation.scalingFlag = 2;
+estimation.displayFlag = 2;
+
+estimation.modelindex = modelindex;  
+
+estimation.parameters = paramdata;
+estimation.parameterslocal = paramdatalocal;
+estimation.initialconditions = icdata;
+
+output = SBPDparameterestimation(sbpopt,estimation)
+sbpopt = output.projectopt;
+
+%% Compare the optimized project with the measurement data
+SBPDcomparemeasurements(sbpopt,modelindex);
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/runExample.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/runExample.m
new file mode 100644
index 0000000000000000000000000000000000000000..5807965e8fbe9c5ba16f4db23cc230474c47f7a4
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/Projects/runExample.m
@@ -0,0 +1,80 @@
+% Project Example Script
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+%% Load the project from the folder structure
+project = SBPDproject('Example_Project')
+
+%% Get the internal data structure
+structure = SBPDstruct(project)
+
+%% Export the project to a different folder
+SBPDexportproject(project,'exported project')
+
+%% Saving the project as a binary MAT file (extension .sbp)
+SBPDsaveproject(project,'project file')
+% Note that the space in the filename disappears
+
+%% Loading MAT saved project
+project = SBPDproject('projectfile.sbp')
+
+%% Checking if SBPDproject
+test1 = isSBPDproject(project)
+test2 = isSBPDproject(523523)
+
+%% Information about an SBPDproject
+SBPDinfo(project)
+
+%% Display all the measurements that are present in the project
+SBPDplotmeasurements(project)
+
+%% Get models from project
+allmodels = SBPDgetmodel(project)
+firstmodel = SBPDgetmodel(project,1)
+allmodels_reversed = SBPDgetmodel(project,[2 1])
+% Note that the location of a model in the folder does not necessarily 
+% determine the modelindex. The index of the model is easiest determined
+% using the SBPDinfo function.
+
+%% Get experiments from project
+allexperiments = SBPDgetexperiment(project)
+firstexperiment = SBPDgetexperiment(project,1)
+someexperiments = SBPDgetexperiment(project,[3 4 5 7 8])
+
+%% Get all measurements (its just one) for experiment 5
+measurements_exp5 = SBPDgetmeasurement(project,5)
+
+%% Compare all models to measurements
+SBPDcomparemeasurements(project)
+
+%% Compare only second model to measurements
+plotdata = SBPDcomparemeasurements(project,2)
+SBPDplot(plotdata)
+
+%% Add first model as third (last) model to the project
+project_new = SBPDupdatemodel(project,firstmodel)
+
+%% Perform insilico experiment and plot result
+model = SBPDgetmodel(project,2)
+experiment = SBPDgetexperiment(project,6)
+SBPDinsilicoexp(model,experiment,[0:5:120]) 
+
+%% Perform insilico experiment on the project and export results as CSV file
+% Second model, 7th experiment
+SBPDinsilicoexpproj(project,2,7,[0:5:120]) 
+
+%% Perform insilico experiment and export as CSV measurement file
+SBPDinsilicoexp(model,experiment,[0:5:120],{'Th','ThMP','ThDP'},1) 
+edit onemodel_Accumulation_10um_thiamine.csv
+
+%% Manual tuning of model 2 in project
+projecttuned = SBPDmanualtuning(project,2)
+
+%% Identifiability of parameters
+options = [];
+options.modelindex = 1;
+parameters = SBparameters(SBPDgetmodel(project,options.modelindex));
+SBPDidentifiability(project,parameters,options)
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex1Isomerizationofalpha-pinene/experiments/default_initial_conditions/default_initial_conditions.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex1Isomerizationofalpha-pinene/experiments/default_initial_conditions/default_initial_conditions.exp
new file mode 100644
index 0000000000000000000000000000000000000000..ff3d9cb75a48e01f814ada2611048fba9932506b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex1Isomerizationofalpha-pinene/experiments/default_initial_conditions/default_initial_conditions.exp
@@ -0,0 +1,25 @@
+********** EXPERIMENT NAME
+
+Default_experiment_on_alpha_pinene_model
+
+********** EXPERIMENT NOTES
+
+In-silico experimental settings corresponding to the
+measurements reported by Fuguitt and Hawkins [1].  
+
+[1] Fuguitt R, Hawkins JE: Rate of Thermal Isomerization of ?-
+    Pinene in the Liquid Phase. JACS 1947, 69:461.
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+
+y1(0) = 100  % alpha-pinene
+
+% All the other species are initially not present
+y2(0) = 0    % dipentene
+y3(0) = 0    % allo-ocimen
+y4(0) = 0    % pyrone
+y5(0) = 0    % dimer
+
+********** EXPERIMENT PARAMETER CHANGES
+
+********** EXPERIMENT STATE CHANGES
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex1Isomerizationofalpha-pinene/experiments/default_initial_conditions/measurements.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex1Isomerizationofalpha-pinene/experiments/default_initial_conditions/measurements.csv
new file mode 100644
index 0000000000000000000000000000000000000000..a6b99f6b25d8f637b0604dc022c738246bdab289
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex1Isomerizationofalpha-pinene/experiments/default_initial_conditions/measurements.csv
@@ -0,0 +1,32 @@
+[Name]
+Isomerization_of_alpha_pinene_measurements
+
+[Notes]
+In-silico generated measurements mimicking the experimental data
+reported by Fuguitt and Hawkins [1].  
+
+[1] Fuguitt R, Hawkins JE: Rate of Thermal Isomerization of 
+    alpha-Pinene in the Liquid Phase. JACS 1947, 69:461.
+
+[Components]
+time,y1,y2,y3,y4,y5
+
+[Componentnotes]
+y1: alpha-pinene
+y2: dipentene
+y3: allo-ocimen
+y4: pyrone
+y5: dimer
+
+[Values]
+0,100.0,0.0,0.0,0.0,0.0
+1230,88.35,7.3,2.3,0.4,1.75
+3060,76.4,15.6,4.5,0.7,2.8
+4920,65.1,23.1,5.3,1.1,5.8
+7800,50.4,32.9,6.0,1.5,9.3
+10680,37.5,42.7,6.0,1.9,12.0
+15030,25.9,49.1,5.9,2.2,17.0
+22620,14.0,57.4,5.1,2.6,21.0
+36420,4.5,63.1,3.8,2.9,25.7
+
+     
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex1Isomerizationofalpha-pinene/models/model_a_pinene.txtbc b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex1Isomerizationofalpha-pinene/models/model_a_pinene.txtbc
new file mode 100644
index 0000000000000000000000000000000000000000..7655e5db78ebaf475bca03aef53629a10e640cf3
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex1Isomerizationofalpha-pinene/models/model_a_pinene.txtbc
@@ -0,0 +1,69 @@
+********** MODEL NAME
+
+Isomerization_of_alpha_pinene
+
+********** MODEL NOTES
+
+The model represents a homogeneous chemical reaction describing 
+the thermal isomerization of alpha-pinene (y1) to dipentene (y2) and 
+alloocimen (y3) which in turn yields alpha- and beta-pyronene (y4) and 
+a dimer (y5).  
+
+This process was studied by Fuguitt and Hawkins [1], who reported 
+the concentrations of the reactant and the four products at eight 
+time intervals.
+
+This model is based on the model by Hunter and MacGregor [2],
+which assumed first-order kinetics.
+
+[1] Fuguitt R, Hawkins JE: Rate of Thermal Isomerization of alpha-
+    Pinene in the Liquid Phase. JACS 1947, 69:461.
+    
+[2] Hunter WG, McGregor JF: The Estimation of Common Parameters
+    from Several Responses: Some Actual Examples. In Unpublished 
+    Report The Department of Statistics. University of Winsconsin, 1967.
+
+********** MODEL STATE INFORMATION
+
+y1(0) = 100  % alpha-pinene
+
+% All the other species are initially not present
+y2(0) = 0    % dipentene
+y3(0) = 0    % allo-ocimen
+y4(0) = 0    % pyrone
+y5(0) = 0    % dimer
+
+********** MODEL PARAMETERS
+
+p1 = 0.5
+p2 = 0.5
+p3 = 0.5 
+p4 = 0.5 
+p5 = 0.5
+
+********** MODEL VARIABLES
+
+
+********** MODEL REACTIONS
+
+y1 => y2 : R1       % conversion of alpha-pinene to dipentene
+    vf = p1*y1
+    
+y1 => y3 : R2       % conversion of alpha-pinene to allo-ocimen
+    vf = p2*y1
+    
+y3 => y4 : R3       % conversion of allo-ocimen to pyrone
+    vf = p3*y3
+    
+y3 <=> y5 : R45   % reversible dimerization (neglected stoichiometric coefficient)
+    vf = p4*y3
+    vr = p5*y5
+
+********** MODEL FUNCTIONS
+
+
+********** MODEL EVENTS
+
+
+********** MODEL MATLAB FUNCTIONS
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex1Isomerizationofalpha-pinene/notes.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex1Isomerizationofalpha-pinene/notes.txt
new file mode 100644
index 0000000000000000000000000000000000000000..59e5b154b137de173e7ec729e3d3b535788fba6a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex1Isomerizationofalpha-pinene/notes.txt
@@ -0,0 +1,25 @@
+>>> Ex1 - Parameter Identification Benchmark Project <<<
+
+This benchmark example has been taken from the following publication:
+Rodriguez-Fernandez, M., J. A. Egea and J. R. Banga (2006) Novel 
+Metaheuristic for Parameter Estimation in Nonlinear Dynamic Biological 
+Systems. BMC Bioinformatics 7:483. 
+
+The contained model represents a homogeneous chemical reaction 
+describing the thermal isomerization of alpha-pinene to dipentene 
+and alloocimen which in turn yields alpha- and beta-pyronene and 
+a dimer.  
+
+This process was studied by Fuguitt and Hawkins [1], who reported 
+the concentrations of the reactant and the four products at eight 
+time intervals.
+
+The model in this project is based on the model by Hunter and 
+MacGregor [2], which assumed first-order kinetics.
+
+[1] Fuguitt R, Hawkins JE: Rate of Thermal Isomerization of alpha-
+    Pinene in the Liquid Phase. JACS 1947, 69:461.
+    
+[2] Hunter WG, McGregor JF: The Estimation of Common Parameters
+    from Several Responses: Some Actual Examples. In Unpublished 
+    Report The Department of Statistics. University of Winsconsin, 1967.
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp1_I_0/inhibitor_0.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp1_I_0/inhibitor_0.exp
new file mode 100644
index 0000000000000000000000000000000000000000..a83020581c59d44c9f6a4d50d928b84c43b818ff
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp1_I_0/inhibitor_0.exp
@@ -0,0 +1,18 @@
+********** EXPERIMENT NAME
+
+Inhibitor_Concentration_0nM
+
+********** EXPERIMENT NOTES
+
+In-silico experimental settings corresponding to the measurements:
+
+HIV proteinase (assay concentration 4nM) was added to a solution 
+of an irreversible inhibitor and a fluorogenic substrate (25 uM). 
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+
+I(0) = 0 % (uM) Inhibitor concentration
+
+********** EXPERIMENT PARAMETER CHANGES
+
+********** EXPERIMENT STATE CHANGES
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp1_I_0/measurement_0.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp1_I_0/measurement_0.csv
new file mode 100644
index 0000000000000000000000000000000000000000..8d20bedf280bed97d2771a6fedc8c66f401ec4c1
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp1_I_0/measurement_0.csv
@@ -0,0 +1,322 @@
+[Name]
+Inhibition_of_HIV_proteinase_0nM
+
+[Notes]
+The data stems from an experiment where HIV proteinase (assay 
+concentration 4nM) was added to a solution of an irreversible 
+inhibitor and a fluorogenic substrate (25 uM). The fluorescence 
+changes were monitored for 1h. 
+
+Kuzmic P: Program DYNAFIT for the analysis of enzyme
+kinetic data: application to HIV proteinase. Analytical 
+Biochemistry 1996, 237:260-273.
+
+[Components]
+time,fc
+
+[Componentnotes]
+fc: fluorecent changes
+
+[Values]
+0,0
+12,0.003662
+24,0.013122
+36,0.017089
+48,0.026855
+60,0.036316
+72,0.044860
+84,0.051574
+96,0.061950
+108,0.070495
+120,0.078125
+132,0.081482
+144,0.094299
+156,0.099792
+168,0.111389
+180,0.119323
+192,0.127258
+204,0.131836
+216,0.139465
+228,0.148620
+240,0.158691
+252,0.166015
+264,0.169067
+276,0.180053
+288,0.189819
+300,0.195007
+312,0.205078
+324,0.212402
+336,0.213623
+348,0.223388
+360,0.230102
+372,0.241088
+384,0.245056
+396,0.254516
+408,0.260009
+420,0.268554
+432,0.271911
+444,0.278625
+456,0.288086
+468,0.290222
+480,0.300293
+492,0.303955
+504,0.315551
+516,0.318298
+528,0.328369
+540,0.336914
+552,0.339660
+564,0.343933
+576,0.354919
+588,0.354614
+600,0.366516
+612,0.370483
+624,0.376587
+636,0.382385
+648,0.390625
+660,0.395507
+672,0.401001
+684,0.406494
+696,0.411377
+708,0.416259
+720,0.420837
+732,0.425720
+744,0.422058
+756,0.437011
+768,0.440063
+780,0.445251
+792,0.449218
+804,0.461425
+816,0.458374
+828,0.460510
+840,0.470581
+852,0.474243
+864,0.477295
+876,0.483703
+888,0.488891
+900,0.492248
+912,0.495910
+924,0.498657
+936,0.496826
+948,0.508117
+960,0.505676
+972,0.510864
+984,0.519104
+996,0.518493
+1008,0.521545
+1020,0.524597
+1032,0.527038
+1044,0.529480
+1056,0.534362
+1068,0.535888
+1080,0.543823
+1092,0.539245
+1104,0.546875
+1116,0.545349
+1128,0.546875
+1140,0.548401
+1152,0.552368
+1164,0.552673
+1176,0.559082
+1188,0.561523
+1200,0.556335
+1212,0.563964
+1224,0.563049
+1236,0.564270
+1248,0.560608
+1260,0.561218
+1272,0.569458
+1284,0.567321
+1296,0.567016
+1308,0.568542
+1320,0.574951
+1332,0.573120
+1344,0.575561
+1356,0.573730
+1368,0.576171
+1380,0.574035
+1392,0.572204
+1404,0.575561
+1416,0.581054
+1428,0.580444
+1440,0.577697
+1452,0.575866
+1464,0.580749
+1476,0.578003
+1488,0.584106
+1500,0.581970
+1512,0.577392
+1524,0.576171
+1536,0.579528
+1548,0.583191
+1560,0.581359
+1572,0.585327
+1584,0.586242
+1596,0.580749
+1608,0.581359
+1620,0.584106
+1632,0.587158
+1644,0.574646
+1656,0.587768
+1668,0.584106
+1680,0.591125
+1692,0.582580
+1704,0.585327
+1716,0.587768
+1728,0.585937
+1740,0.584716
+1752,0.581970
+1764,0.586853
+1776,0.585937
+1788,0.581970
+1800,0.592956
+1812,0.586853
+1824,0.588989
+1836,0.587463
+1848,0.585327
+1860,0.588073
+1872,0.588684
+1884,0.596313
+1896,0.589904
+1908,0.584716
+1920,0.584716
+1932,0.585632
+1944,0.594482
+1956,0.587768
+1968,0.587463
+1980,0.585632
+1992,0.586853
+2004,0.585327
+2016,0.585327
+2028,0.585327
+2040,0.587463
+2052,0.584106
+2064,0.589294
+2076,0.588684
+2088,0.586242
+2100,0.584716
+2112,0.584716
+2124,0.582885
+2136,0.589599
+2148,0.586547
+2160,0.590210
+2172,0.586547
+2184,0.584716
+2196,0.588379
+2208,0.585022
+2220,0.592346
+2232,0.584716
+2244,0.589599
+2256,0.580749
+2268,0.588073
+2280,0.585632
+2292,0.594482
+2304,0.587768
+2316,0.588989
+2328,0.585937
+2340,0.581054
+2352,0.586242
+2364,0.584106
+2376,0.588379
+2388,0.587158
+2400,0.586853
+2412,0.586853
+2424,0.584106
+2436,0.586547
+2448,0.591125
+2460,0.593261
+2472,0.581665
+2484,0.585327
+2496,0.592041
+2508,0.588073
+2520,0.587158
+2532,0.587768
+2544,0.584106
+2556,0.583191
+2568,0.581970
+2580,0.583191
+2592,0.585022
+2604,0.591735
+2616,0.591430
+2628,0.589599
+2640,0.584716
+2652,0.587768
+2664,0.585327
+2676,0.586547
+2688,0.584716
+2700,0.587158
+2712,0.587768
+2724,0.585632
+2736,0.588073
+2748,0.590210
+2760,0.582580
+2772,0.586242
+2784,0.584106
+2796,0.585022
+2808,0.585632
+2820,0.583801
+2832,0.580749
+2844,0.582275
+2856,0.588684
+2868,0.585632
+2880,0.588989
+2892,0.588073
+2904,0.585022
+2916,0.592346
+2928,0.583191
+2940,0.580749
+2952,0.581359
+2964,0.585632
+2976,0.591125
+2988,0.587158
+3000,0.590210
+3012,0.590515
+3024,0.585937
+3036,0.585937
+3048,0.586853
+3060,0.582885
+3072,0.585327
+3084,0.588073
+3096,0.586242
+3108,0.583496
+3120,0.589294
+3132,0.583496
+3144,0.583191
+3156,0.586853
+3168,0.581970
+3180,0.585022
+3192,0.584106
+3204,0.581665
+3216,0.585937
+3228,0.581054
+3240,0.583496
+3252,0.582275
+3264,0.589904
+3276,0.578613
+3288,0.584106
+3300,0.584411
+3312,0.589599
+3324,0.585632
+3336,0.579834
+3348,0.586547
+3360,0.583191
+3372,0.584106
+3384,0.580139
+3396,0.581665
+3408,0.584716
+3420,0.583191
+3432,0.585632
+3444,0.581054
+3456,0.580749
+3468,0.581359
+3480,0.579528
+3492,0.587158
+3504,0.587768
+3516,0.584411
+3528,0.580444
+3540,0.584411
+3552,0.582580
+3564,0.584411
+3576,0.580444
+3588,0.583496
+3600,0.587768
+     
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp2_I_15/inhibitor_15.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp2_I_15/inhibitor_15.exp
new file mode 100644
index 0000000000000000000000000000000000000000..e33687036ee037b371b512135434c3f1a38b1c03
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp2_I_15/inhibitor_15.exp
@@ -0,0 +1,18 @@
+********** EXPERIMENT NAME
+
+Inhibitor_Concentration_1.5nM
+
+********** EXPERIMENT NOTES
+
+In-silico experimental settings corresponding to the measurements:
+
+HIV proteinase (assay concentration 4nM) was added to a solution 
+of an irreversible inhibitor and a fluorogenic substrate (25 uM). 
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+
+I(0) = 1.5*1e-3 % (uM) 1.5nM Inhibitor concentration
+
+********** EXPERIMENT PARAMETER CHANGES
+
+********** EXPERIMENT STATE CHANGES
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp2_I_15/measurement_15.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp2_I_15/measurement_15.csv
new file mode 100644
index 0000000000000000000000000000000000000000..7f2f8565b692a9af5acaf6be1dd9e3ad068fc149
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp2_I_15/measurement_15.csv
@@ -0,0 +1,321 @@
+[Name]
+Inhibition_of_HIV_proteinase_1.5nM
+
+[Notes]
+The data stems from an experiment where HIV proteinase (assay 
+concentration 4nM) was added to a solution of an irreversible 
+inhibitor and a fluorogenic substrate (25 uM). The fluorescence 
+changes were monitored for 1h. 
+
+Kuzmic P: Program DYNAFIT for the analysis of enzyme
+kinetic data: application to HIV proteinase. Analytical 
+Biochemistry 1996, 237:260-273.
+
+[Components]
+time,fc
+
+[Componentnotes]
+fc: fluorecent changes
+
+[Values]
+0,0
+12,0.002136
+24,0.013733
+36,0.016479
+48,0.020752
+60,0.030823
+72,0.035095
+84,0.041199
+96,0.043335
+108,0.052795
+120,0.060119
+132,0.068054
+144,0.070801
+156,0.079346
+168,0.084839
+180,0.091858
+192,0.101013
+204,0.102234
+216,0.106201
+228,0.112610
+240,0.123291
+252,0.126037
+264,0.135498
+276,0.140991
+288,0.143432
+300,0.153198
+312,0.156860
+324,0.162048
+336,0.169678
+348,0.169983
+360,0.178223
+372,0.183411
+384,0.188904
+396,0.195312
+408,0.198669
+420,0.207825
+432,0.208740
+444,0.213623
+456,0.228577
+468,0.223999
+480,0.230102
+492,0.232849
+504,0.236206
+516,0.248413
+528,0.249634
+540,0.253601
+552,0.260315
+564,0.260925
+576,0.270080
+588,0.271301
+600,0.273132
+612,0.279541
+624,0.286865
+636,0.288696
+648,0.295105
+660,0.297241
+672,0.301208
+684,0.306702
+696,0.316772
+708,0.318298
+720,0.320740
+732,0.322265
+744,0.329895
+756,0.334778
+768,0.338440
+780,0.335693
+792,0.341492
+804,0.346069
+816,0.350342
+828,0.359497
+840,0.369873
+852,0.363159
+864,0.369568
+876,0.375671
+888,0.378723
+900,0.383911
+912,0.387573
+924,0.390625
+936,0.393066
+948,0.399170
+960,0.414429
+972,0.402222
+984,0.410156
+996,0.411682
+1008,0.415039
+1020,0.427551
+1032,0.424499
+1044,0.433655
+1056,0.433349
+1068,0.429687
+1080,0.434570
+1092,0.434875
+1104,0.436096
+1116,0.438843
+1128,0.449524
+1140,0.437927
+1152,0.450439
+1164,0.469055
+1176,0.462952
+1188,0.459289
+1200,0.450134
+1212,0.454712
+1224,0.463257
+1236,0.463562
+1248,0.471496
+1260,0.468140
+1272,0.476684
+1284,0.475464
+1296,0.477905
+1308,0.478515
+1320,0.481262
+1332,0.489502
+1344,0.490112
+1356,0.495300
+1368,0.497436
+1380,0.497436
+1392,0.498962
+1404,0.492859
+1416,0.492859
+1428,0.495300
+1440,0.500183
+1452,0.496826
+1464,0.511169
+1476,0.514831
+1488,0.507812
+1500,0.517578
+1512,0.509033
+1524,0.510254
+1536,0.522156
+1548,0.520019
+1560,0.521545
+1572,0.518799
+1584,0.525207
+1596,0.519104
+1608,0.526428
+1620,0.522461
+1632,0.530395
+1644,0.529480
+1656,0.531616
+1668,0.532532
+1680,0.544128
+1692,0.530395
+1704,0.534057
+1716,0.534057
+1728,0.532837
+1740,0.536804
+1752,0.540466
+1764,0.540771
+1776,0.536804
+1788,0.543823
+1800,0.543213
+1812,0.538025
+1824,0.547790
+1836,0.538940
+1848,0.545654
+1860,0.548096
+1872,0.547485
+1884,0.548401
+1896,0.548096
+1908,0.536804
+1920,0.545654
+1932,0.550537
+1944,0.543213
+1956,0.545959
+1968,0.547180
+1980,0.541382
+1992,0.549316
+2004,0.546265
+2016,0.541077
+2028,0.549011
+2040,0.562439
+2052,0.549927
+2064,0.552673
+2076,0.561828
+2088,0.561828
+2100,0.553284
+2112,0.548096
+2124,0.553894
+2136,0.553589
+2148,0.550842
+2160,0.554199
+2172,0.557861
+2184,0.555420
+2196,0.563965
+2208,0.555115
+2220,0.551758
+2232,0.554199
+2244,0.563049
+2256,0.556946
+2268,0.552063
+2280,0.555115
+2292,0.559387
+2304,0.568848
+2316,0.552673
+2328,0.553894
+2340,0.571594
+2352,0.563965
+2364,0.563965
+2376,0.560303
+2388,0.557861
+2400,0.559692
+2412,0.552978
+2424,0.565185
+2436,0.556946
+2448,0.566406
+2460,0.572815
+2472,0.567932
+2484,0.562744
+2496,0.554199
+2508,0.554504
+2520,0.565185
+2532,0.561523
+2544,0.571899
+2556,0.565491
+2568,0.560608
+2580,0.563965
+2592,0.557556
+2604,0.559997
+2616,0.556946
+2628,0.560913
+2640,0.554199
+2652,0.551758
+2664,0.562439
+2676,0.563049
+2688,0.563049
+2700,0.550537
+2712,0.555420
+2724,0.558777
+2736,0.567932
+2748,0.559387
+2760,0.556946
+2772,0.563049
+2784,0.564880
+2796,0.555725
+2808,0.558472
+2820,0.554809
+2832,0.554504
+2844,0.563354
+2856,0.561523
+2868,0.561523
+2880,0.559082
+2892,0.559387
+2904,0.548401
+2916,0.547485
+2928,0.567627
+2940,0.549927
+2952,0.562439
+2964,0.558472
+2976,0.548706
+2988,0.558472
+3000,0.553589
+3012,0.558166
+3024,0.551147
+3036,0.559997
+3048,0.558777
+3060,0.556946
+3072,0.556640
+3084,0.567627
+3096,0.557556
+3108,0.564575
+3120,0.551758
+3132,0.553589
+3144,0.564270
+3156,0.558472
+3168,0.555420
+3180,0.550537
+3192,0.568237
+3204,0.554809
+3216,0.546875
+3228,0.566711
+3240,0.550842
+3252,0.550232
+3264,0.555420
+3276,0.552673
+3288,0.569153
+3300,0.550537
+3312,0.556335
+3324,0.558166
+3336,0.553894
+3348,0.561523
+3360,0.552063
+3372,0.554199
+3384,0.555725
+3396,0.548096
+3408,0.548096
+3420,0.545349
+3432,0.549927
+3444,0.560608
+3456,0.553894
+3468,0.556335
+3480,0.540466
+3492,0.546570
+3504,0.552368
+3516,0.543518
+3528,0.544739
+3540,0.557861
+3552,0.552673
+3564,0.565185
+3576,0.549316
+3588,0.551452
+3600,0.545044
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp3_I_3/inhibitor_3.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp3_I_3/inhibitor_3.exp
new file mode 100644
index 0000000000000000000000000000000000000000..4cb024015be49155941523975ca421925cbeb5ea
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp3_I_3/inhibitor_3.exp
@@ -0,0 +1,18 @@
+********** EXPERIMENT NAME
+
+Inhibitor_Concentration_3nM
+
+********** EXPERIMENT NOTES
+
+In-silico experimental settings corresponding to the measurements:
+
+HIV proteinase (assay concentration 4nM) was added to a solution 
+of an irreversible inhibitor and a fluorogenic substrate (25 uM).
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+
+I(0) = 3*1e-3 % (uM) 3nM Inhibitor concentration
+
+********** EXPERIMENT PARAMETER CHANGES
+
+********** EXPERIMENT STATE CHANGES
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp3_I_3/measurement_3.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp3_I_3/measurement_3.csv
new file mode 100644
index 0000000000000000000000000000000000000000..9015d359e05b8ba7ed407b06467de52293f157df
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp3_I_3/measurement_3.csv
@@ -0,0 +1,321 @@
+[Name]
+Inhibition_of_HIV_proteinase_3nM
+
+[Notes]
+The data stems from an experiment where HIV proteinase (assay 
+concentration 4nM) was added to a solution of an irreversible 
+inhibitor and a fluorogenic substrate (25 uM). The fluorescence 
+changes were monitored for 1h. 
+
+Kuzmic P: Program DYNAFIT for the analysis of enzyme
+kinetic data: application to HIV proteinase. Analytical 
+Biochemistry 1996, 237:260-273.
+
+[Components]
+time,fc
+
+[Componentnotes]
+fc: fluorecent changes
+
+[Values]
+0,0
+12,0.002747
+24,0.010071
+36,0.014954
+48,0.019531
+60,0.025940
+72,0.035705
+84,0.037842
+96,0.045776
+108,0.047607
+120,0.052490
+132,0.061950
+144,0.065918
+156,0.072326
+168,0.078430
+180,0.079040
+192,0.085144
+204,0.093994
+216,0.097656
+228,0.104065
+240,0.106506
+252,0.109253
+264,0.119018
+276,0.122070
+288,0.122986
+300,0.134887
+312,0.136108
+324,0.141906
+336,0.146484
+348,0.150451
+360,0.156250
+372,0.158996
+384,0.168152
+396,0.167541
+408,0.175781
+420,0.181579
+432,0.184631
+444,0.191650
+456,0.191040
+468,0.200805
+480,0.202026
+492,0.209655
+504,0.207519
+516,0.210876
+528,0.216980
+540,0.224609
+552,0.226135
+564,0.230102
+576,0.234375
+588,0.238647
+600,0.250549
+612,0.252380
+624,0.253906
+636,0.253296
+648,0.260620
+660,0.268554
+672,0.271301
+684,0.274353
+696,0.279236
+708,0.277404
+720,0.289306
+732,0.288696
+744,0.292663
+756,0.296936
+768,0.301208
+780,0.303344
+792,0.306701
+804,0.317993
+816,0.315857
+828,0.320129
+840,0.325317
+852,0.328064
+864,0.332031
+876,0.334778
+888,0.340576
+900,0.344848
+912,0.347290
+924,0.346374
+936,0.352478
+948,0.355224
+960,0.364990
+972,0.363464
+984,0.369873
+996,0.370788
+1008,0.376892
+1020,0.379944
+1032,0.382690
+1044,0.383606
+1056,0.385742
+1068,0.395202
+1080,0.398559
+1092,0.400390
+1104,0.406189
+1116,0.406799
+1128,0.411071
+1140,0.414734
+1152,0.411071
+1164,0.423279
+1176,0.418396
+1188,0.422668
+1200,0.428772
+1212,0.432434
+1224,0.434570
+1236,0.433960
+1248,0.437927
+1260,0.440368
+1272,0.444336
+1284,0.449218
+1296,0.446167
+1308,0.452575
+1320,0.455322
+1332,0.459900
+1344,0.458374
+1356,0.466308
+1368,0.468445
+1380,0.466003
+1392,0.475464
+1404,0.479126
+1416,0.479431
+1428,0.480041
+1440,0.487671
+1452,0.495605
+1464,0.495300
+1476,0.489807
+1488,0.494384
+1500,0.505066
+1512,0.498047
+1524,0.502624
+1536,0.506286
+1548,0.503235
+1560,0.501404
+1572,0.513305
+1584,0.509033
+1596,0.518799
+1608,0.516662
+1620,0.519104
+1632,0.526733
+1644,0.521545
+1656,0.521240
+1668,0.530090
+1680,0.535278
+1692,0.533752
+1704,0.538635
+1716,0.541992
+1728,0.540161
+1740,0.541992
+1752,0.543518
+1764,0.546264
+1776,0.544128
+1788,0.553283
+1800,0.546875
+1812,0.550232
+1824,0.557556
+1836,0.559692
+1848,0.566101
+1860,0.575256
+1872,0.560302
+1884,0.564880
+1896,0.566406
+1908,0.564270
+1920,0.567016
+1932,0.570678
+1944,0.572815
+1956,0.566101
+1968,0.564575
+1980,0.572815
+1992,0.573730
+2004,0.573730
+2016,0.580749
+2028,0.577392
+2040,0.582885
+2052,0.585327
+2064,0.589904
+2076,0.587158
+2088,0.594177
+2100,0.587463
+2112,0.591125
+2124,0.592041
+2136,0.594482
+2148,0.589294
+2160,0.591736
+2172,0.592346
+2184,0.597534
+2196,0.594787
+2208,0.601196
+2220,0.600280
+2232,0.607300
+2244,0.600586
+2256,0.600586
+2268,0.615539
+2280,0.598755
+2292,0.604248
+2304,0.603027
+2316,0.607605
+2328,0.605163
+2340,0.606689
+2352,0.605163
+2364,0.613403
+2376,0.599975
+2388,0.607300
+2400,0.606994
+2412,0.606384
+2424,0.617981
+2436,0.616455
+2448,0.618286
+2460,0.615539
+2472,0.611877
+2484,0.619812
+2496,0.611877
+2508,0.612182
+2520,0.621948
+2532,0.629883
+2544,0.619812
+2556,0.615539
+2568,0.614929
+2580,0.623779
+2592,0.620727
+2604,0.626220
+2616,0.621032
+2628,0.623779
+2640,0.617065
+2652,0.622253
+2664,0.623779
+2676,0.619507
+2688,0.626526
+2700,0.621948
+2712,0.621643
+2724,0.620422
+2736,0.640258
+2748,0.628051
+2760,0.626220
+2772,0.633850
+2784,0.629577
+2796,0.622558
+2808,0.629577
+2820,0.630188
+2832,0.631408
+2844,0.623779
+2856,0.628662
+2868,0.635376
+2880,0.626220
+2892,0.626831
+2904,0.627136
+2916,0.631714
+2928,0.626831
+2940,0.625610
+2952,0.630188
+2964,0.628662
+2976,0.626526
+2988,0.632934
+3000,0.629883
+3012,0.628662
+3024,0.626526
+3036,0.632629
+3048,0.634765
+3060,0.632324
+3072,0.633545
+3084,0.631103
+3096,0.632629
+3108,0.632934
+3120,0.626831
+3132,0.627746
+3144,0.629883
+3156,0.624389
+3168,0.628662
+3180,0.632629
+3192,0.628967
+3204,0.624695
+3216,0.627746
+3228,0.630188
+3240,0.629272
+3252,0.623779
+3264,0.630798
+3276,0.636596
+3288,0.629577
+3300,0.631408
+3312,0.631408
+3324,0.631714
+3336,0.629577
+3348,0.628967
+3360,0.623169
+3372,0.637207
+3384,0.635681
+3396,0.627136
+3408,0.631103
+3420,0.626526
+3432,0.648193
+3444,0.631408
+3456,0.633239
+3468,0.631103
+3480,0.632629
+3492,0.624084
+3504,0.638427
+3516,0.628967
+3528,0.630188
+3540,0.628357
+3552,0.629883
+3564,0.628051
+3576,0.629577
+3588,0.624389
+3600,0.632629
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp4_I_4/inhibitor_4.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp4_I_4/inhibitor_4.exp
new file mode 100644
index 0000000000000000000000000000000000000000..807117dcdf2cda0957c575f4445739363d7f2f79
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp4_I_4/inhibitor_4.exp
@@ -0,0 +1,18 @@
+********** EXPERIMENT NAME
+
+Inhibitor_Concentration_4nM
+
+********** EXPERIMENT NOTES
+
+In-silico experimental settings corresponding to the measurements:
+
+HIV proteinase (assay concentration 4nM) was added to a solution 
+of an irreversible inhibitor and a fluorogenic substrate (25 uM).
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+
+I(0) = 4*1e-3 % (uM) 4nM Inhibitor concentration
+
+********** EXPERIMENT PARAMETER CHANGES
+
+********** EXPERIMENT STATE CHANGES
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp4_I_4/measurement_4_1.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp4_I_4/measurement_4_1.csv
new file mode 100644
index 0000000000000000000000000000000000000000..fb1d17ddf8f96a189e50b870984209c1c8107f2d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp4_I_4/measurement_4_1.csv
@@ -0,0 +1,321 @@
+[Name]
+Inhibition_of_HIV_proteinase_4nM_first
+
+[Notes]
+The data stems from an experiment where HIV proteinase (assay 
+concentration 4nM) was added to a solution of an irreversible 
+inhibitor and a fluorogenic substrate (25 uM). The fluorescence 
+changes were monitored for 1h. 
+
+Kuzmic P: Program DYNAFIT for the analysis of enzyme
+kinetic data: application to HIV proteinase. Analytical 
+Biochemistry 1996, 237:260-273.
+
+[Components]
+time,fc
+
+[Componentnotes]
+fc: fluorecent changes
+
+[Values]
+0,0
+12,0.002441
+24,0.006409
+36,0.009766
+48,0.012817
+60,0.015564
+72,0.019836
+84,0.022888
+96,0.025330
+108,0.025635
+120,0.028687
+132,0.034790
+144,0.032349
+156,0.036926
+168,0.036316
+180,0.042725
+192,0.043030
+204,0.043640
+216,0.042419
+228,0.048523
+240,0.048523
+252,0.049744
+264,0.053406
+276,0.053711
+288,0.054321
+300,0.056152
+312,0.056763
+324,0.061035
+336,0.061035
+348,0.062561
+360,0.062256
+372,0.062561
+384,0.065613
+396,0.067444
+408,0.069885
+420,0.070496
+432,0.069275
+444,0.073547
+456,0.071106
+468,0.072021
+480,0.074158
+492,0.075073
+504,0.073547
+516,0.075073
+528,0.075683
+540,0.078735
+552,0.078125
+564,0.078125
+576,0.079651
+588,0.082092
+600,0.082703
+612,0.084228
+624,0.084228
+636,0.086670
+648,0.084534
+660,0.087891
+672,0.087585
+684,0.087585
+696,0.089722
+708,0.087585
+720,0.092773
+732,0.092163
+744,0.091247
+756,0.092773
+768,0.094604
+780,0.093079
+792,0.094604
+804,0.096741
+816,0.094910
+828,0.094910
+840,0.092163
+852,0.097656
+864,0.098877
+876,0.096435
+888,0.097656
+900,0.099182
+912,0.097656
+924,0.101318
+936,0.101013
+948,0.102844
+960,0.100708
+972,0.104675
+984,0.105286
+996,0.105286
+1008,0.105896
+1020,0.105896
+1032,0.103760
+1044,0.107727
+1056,0.104065
+1068,0.108032
+1080,0.109558
+1092,0.109253
+1104,0.106506
+1116,0.108642
+1128,0.111389
+1140,0.112305
+1152,0.113830
+1164,0.112305
+1176,0.115356
+1188,0.115051
+1200,0.113220
+1212,0.115967
+1224,0.123291
+1236,0.119018
+1248,0.117798
+1260,0.118713
+1272,0.117798
+1284,0.118713
+1296,0.117493
+1308,0.123596
+1320,0.122681
+1332,0.123596
+1344,0.122986
+1356,0.124512
+1368,0.122375
+1380,0.128174
+1392,0.128174
+1404,0.126953
+1416,0.125732
+1428,0.131225
+1440,0.126953
+1452,0.129394
+1464,0.129089
+1476,0.129700
+1488,0.129700
+1500,0.128174
+1512,0.127258
+1524,0.131531
+1536,0.130615
+1548,0.133972
+1560,0.134277
+1572,0.130920
+1584,0.131836
+1596,0.133972
+1608,0.136413
+1620,0.134888
+1632,0.133667
+1644,0.134277
+1656,0.137329
+1668,0.133362
+1680,0.139465
+1692,0.135498
+1704,0.136719
+1716,0.134582
+1728,0.137024
+1740,0.136108
+1752,0.140076
+1764,0.143433
+1776,0.138855
+1788,0.137939
+1800,0.140076
+1812,0.140686
+1824,0.142212
+1836,0.144043
+1848,0.143738
+1860,0.140686
+1872,0.139770
+1884,0.140991
+1896,0.138550
+1908,0.142517
+1920,0.144043
+1932,0.141601
+1944,0.144043
+1956,0.140686
+1968,0.144348
+1980,0.144653
+1992,0.145569
+2004,0.146179
+2016,0.147400
+2028,0.145264
+2040,0.146484
+2052,0.147400
+2064,0.146484
+2076,0.147705
+2088,0.145569
+2100,0.147705
+2112,0.148926
+2124,0.148621
+2136,0.147400
+2148,0.151977
+2160,0.148315
+2172,0.150452
+2184,0.150146
+2196,0.151672
+2208,0.153503
+2220,0.154114
+2232,0.155334
+2244,0.150757
+2256,0.149536
+2268,0.153503
+2280,0.151672
+2292,0.158081
+2304,0.155640
+2316,0.152588
+2328,0.156555
+2340,0.157471
+2352,0.156250
+2364,0.152283
+2376,0.159607
+2388,0.156555
+2400,0.157165
+2412,0.159302
+2424,0.158996
+2436,0.159607
+2448,0.160828
+2460,0.157471
+2472,0.159607
+2484,0.162353
+2496,0.158081
+2508,0.160522
+2520,0.161133
+2532,0.158996
+2544,0.164490
+2556,0.163574
+2568,0.160828
+2580,0.163879
+2592,0.164184
+2604,0.161133
+2616,0.167541
+2628,0.167847
+2640,0.163574
+2652,0.163574
+2664,0.166016
+2676,0.166321
+2688,0.163269
+2700,0.165100
+2712,0.168457
+2724,0.165100
+2736,0.164184
+2748,0.168152
+2760,0.166016
+2772,0.169372
+2784,0.170288
+2796,0.172729
+2808,0.165100
+2820,0.168152
+2832,0.172424
+2844,0.168457
+2856,0.169678
+2868,0.170898
+2880,0.175171
+2892,0.176392
+2904,0.171509
+2916,0.173950
+2928,0.173340
+2940,0.174560
+2952,0.170288
+2964,0.173645
+2976,0.176697
+2988,0.174255
+3000,0.178833
+3012,0.174255
+3024,0.174866
+3036,0.171814
+3048,0.175171
+3060,0.177002
+3072,0.175171
+3084,0.177307
+3096,0.177612
+3108,0.178223
+3120,0.175781
+3132,0.181274
+3144,0.180969
+3156,0.178528
+3168,0.182190
+3180,0.182495
+3192,0.180054
+3204,0.179443
+3216,0.180664
+3228,0.178833
+3240,0.179748
+3252,0.180664
+3264,0.180359
+3276,0.180054
+3288,0.180664
+3300,0.183411
+3312,0.183716
+3324,0.183105
+3336,0.183716
+3348,0.186767
+3360,0.183716
+3372,0.183716
+3384,0.185242
+3396,0.185852
+3408,0.187378
+3420,0.185852
+3432,0.186767
+3444,0.185547
+3456,0.188293
+3468,0.184631
+3480,0.186767
+3492,0.187683
+3504,0.183105
+3516,0.187988
+3528,0.189514
+3540,0.187378
+3552,0.189209
+3564,0.187378
+3576,0.187378
+3588,0.189819
+3600,0.193176
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp5_I_4/inhibitor_4.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp5_I_4/inhibitor_4.exp
new file mode 100644
index 0000000000000000000000000000000000000000..807117dcdf2cda0957c575f4445739363d7f2f79
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp5_I_4/inhibitor_4.exp
@@ -0,0 +1,18 @@
+********** EXPERIMENT NAME
+
+Inhibitor_Concentration_4nM
+
+********** EXPERIMENT NOTES
+
+In-silico experimental settings corresponding to the measurements:
+
+HIV proteinase (assay concentration 4nM) was added to a solution 
+of an irreversible inhibitor and a fluorogenic substrate (25 uM).
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+
+I(0) = 4*1e-3 % (uM) 4nM Inhibitor concentration
+
+********** EXPERIMENT PARAMETER CHANGES
+
+********** EXPERIMENT STATE CHANGES
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp5_I_4/measurement_4_2.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp5_I_4/measurement_4_2.csv
new file mode 100644
index 0000000000000000000000000000000000000000..3f9df9d9d5c9ba82458af6d4d115f00f3e7df4ea
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/experiments/exp5_I_4/measurement_4_2.csv
@@ -0,0 +1,321 @@
+[Name]
+Inhibition_of_HIV_proteinase_4nM_second
+
+[Notes]
+The data stems from an experiment where HIV proteinase (assay 
+concentration 4nM) was added to a solution of an irreversible 
+inhibitor and a fluorogenic substrate (25 uM). The fluorescence 
+changes were monitored for 1h. 
+
+Kuzmic P: Program DYNAFIT for the analysis of enzyme
+kinetic data: application to HIV proteinase. Analytical 
+Biochemistry 1996, 237:260-273.
+
+[Components]
+time,fc
+
+[Componentnotes]
+fc: fluorecent changes
+
+[Values]
+0,0
+12,0.004883
+24,0.009155
+36,0.017090
+48,0.017700
+60,0.021973
+72,0.025024
+84,0.025330
+96,0.030212
+108,0.031433
+120,0.033264
+132,0.035400
+144,0.039673
+156,0.038757
+168,0.042114
+180,0.042114
+192,0.045471
+204,0.047607
+216,0.050049
+228,0.051575
+240,0.051575
+252,0.052795
+264,0.052795
+276,0.057373
+288,0.055237
+300,0.057678
+312,0.062256
+324,0.061035
+336,0.060730
+348,0.061340
+360,0.060730
+372,0.063477
+384,0.061035
+396,0.064087
+408,0.067139
+420,0.068665
+432,0.066223
+444,0.068970
+456,0.069275
+468,0.069580
+480,0.068359
+492,0.069885
+504,0.070801
+516,0.070191
+528,0.070496
+540,0.069580
+552,0.074158
+564,0.075378
+576,0.076599
+588,0.074463
+600,0.076599
+612,0.075073
+624,0.076904
+636,0.076599
+648,0.077820
+660,0.075684
+672,0.080261
+684,0.080261
+696,0.079346
+708,0.079651
+720,0.080566
+732,0.083008
+744,0.082703
+756,0.081787
+768,0.081482
+780,0.081482
+792,0.081787
+804,0.086365
+816,0.084229
+828,0.086975
+840,0.082092
+852,0.084534
+864,0.083618
+876,0.083313
+888,0.086365
+900,0.089417
+912,0.086670
+924,0.085144
+936,0.085449
+948,0.086670
+960,0.087586
+972,0.086060
+984,0.086670
+996,0.085449
+1008,0.088196
+1020,0.086975
+1032,0.086670
+1044,0.090027
+1056,0.089722
+1068,0.090942
+1080,0.090942
+1092,0.089722
+1104,0.092163
+1116,0.093689
+1128,0.087280
+1140,0.087586
+1152,0.090027
+1164,0.090942
+1176,0.091248
+1188,0.094910
+1200,0.090942
+1212,0.091248
+1224,0.089111
+1236,0.092468
+1248,0.091858
+1260,0.093384
+1272,0.094605
+1284,0.093994
+1296,0.095215
+1308,0.095825
+1320,0.095825
+1332,0.096436
+1344,0.093994
+1356,0.092774
+1368,0.095520
+1380,0.096130
+1392,0.093994
+1404,0.094299
+1416,0.094910
+1428,0.096130
+1440,0.097961
+1452,0.095215
+1464,0.095520
+1476,0.092774
+1488,0.095520
+1500,0.096436
+1512,0.099182
+1524,0.100098
+1536,0.097046
+1548,0.098267
+1560,0.098572
+1572,0.098267
+1584,0.096130
+1596,0.099182
+1608,0.100403
+1620,0.099793
+1632,0.101013
+1644,0.097656
+1656,0.101318
+1668,0.096436
+1680,0.102234
+1692,0.098572
+1704,0.100403
+1716,0.098267
+1728,0.101624
+1740,0.103149
+1752,0.099793
+1764,0.103149
+1776,0.103760
+1788,0.102234
+1800,0.101318
+1812,0.102844
+1824,0.100403
+1836,0.102539
+1848,0.102539
+1860,0.101318
+1872,0.103760
+1884,0.102844
+1896,0.101929
+1908,0.102844
+1920,0.105591
+1932,0.105591
+1944,0.103760
+1956,0.103149
+1968,0.100403
+1980,0.104675
+1992,0.107727
+2004,0.101624
+2016,0.106506
+2028,0.103760
+2040,0.108948
+2052,0.103760
+2064,0.109558
+2076,0.103455
+2088,0.104981
+2100,0.104065
+2112,0.104675
+2124,0.105896
+2136,0.107422
+2148,0.104675
+2160,0.107117
+2172,0.108032
+2184,0.108948
+2196,0.105896
+2208,0.103455
+2220,0.106201
+2232,0.105286
+2244,0.105591
+2256,0.105591
+2268,0.104065
+2280,0.109558
+2292,0.108337
+2304,0.108032
+2316,0.107117
+2328,0.107117
+2340,0.105896
+2352,0.107727
+2364,0.108032
+2376,0.108948
+2388,0.108643
+2400,0.110169
+2412,0.108032
+2424,0.109558
+2436,0.108337
+2448,0.109558
+2460,0.108643
+2472,0.104675
+2484,0.112000
+2496,0.112915
+2508,0.108337
+2520,0.109558
+2532,0.110779
+2544,0.110779
+2556,0.110474
+2568,0.112305
+2580,0.111389
+2592,0.112305
+2604,0.109558
+2616,0.110169
+2628,0.107117
+2640,0.112305
+2652,0.108948
+2664,0.112610
+2676,0.111694
+2688,0.111389
+2700,0.109253
+2712,0.112610
+2724,0.110474
+2736,0.110779
+2748,0.112915
+2760,0.112915
+2772,0.113831
+2784,0.111084
+2796,0.110169
+2808,0.112000
+2820,0.112000
+2832,0.111389
+2844,0.111389
+2856,0.112915
+2868,0.112915
+2880,0.112000
+2892,0.111694
+2904,0.114746
+2916,0.113831
+2928,0.108643
+2940,0.111694
+2952,0.114136
+2964,0.111694
+2976,0.113525
+2988,0.113220
+3000,0.112305
+3012,0.112915
+3024,0.115662
+3036,0.115662
+3048,0.115967
+3060,0.113220
+3072,0.111389
+3084,0.110169
+3096,0.115051
+3108,0.115357
+3120,0.114746
+3132,0.112915
+3144,0.111389
+3156,0.112915
+3168,0.117493
+3180,0.117798
+3192,0.112305
+3204,0.113525
+3216,0.112610
+3228,0.113831
+3240,0.118408
+3252,0.116272
+3264,0.115967
+3276,0.114746
+3288,0.114746
+3300,0.116577
+3312,0.116882
+3324,0.112305
+3336,0.110779
+3348,0.116272
+3360,0.117188
+3372,0.114746
+3384,0.117493
+3396,0.118408
+3408,0.116577
+3420,0.116882
+3432,0.115662
+3444,0.116882
+3456,0.116272
+3468,0.115051
+3480,0.114441
+3492,0.116577
+3504,0.112610
+3516,0.115662
+3528,0.115662
+3540,0.118713
+3552,0.114441
+3564,0.115967
+3576,0.115967
+3588,0.117798
+3600,0.115051
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/models/model_HIV_proteinase.txtbc b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/models/model_HIV_proteinase.txtbc
new file mode 100644
index 0000000000000000000000000000000000000000..5e37aa7d1bc59fc576803735e725059ea36d8981
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/models/model_HIV_proteinase.txtbc
@@ -0,0 +1,83 @@
+********** MODEL NAME
+
+Inhibition_of_HIV_proteinase
+
+********** MODEL NOTES
+
+The model represents an in-silico system in which HIV proteinase (assay 
+concentration 4nM) is added to a solution of an irreversible inhibitor and 
+a fluorogenic substrate (25 uM). 
+
+Kuzmic P: Program DYNAFIT for the analysis of enzyme
+kinetic data: application to HIV proteinase. Analytical 
+Biochemistry 1996, 237:260-273.
+
+Mendes, P. & Kell, D.B. (1998) Non-linear optimization 
+of biochemical pathways: applications to metabolic engineering 
+and parameter estimation. Bioinformatics  14, 869-883
+
+Rodriguez-Fernandez, M., J. A. Egea and J. R. Banga (2006) Novel 
+Metaheuristic for Parameter Estimation in Nonlinear Dynamic 
+Biological Systems. BMC Bioinformatics 7:483. 
+
+********** MODEL STATE INFORMATION
+
+S(0) = 25       	% (uM) Substrate
+E(0) = 0.004    	% (uM) HIV proteinase
+I(0) = 0.004        % (uM) Irreversible inhibitor
+
+********** MODEL PARAMETERS
+
+% Kinetic parameters
+k11 = 0.1           % (1/uM/s)  
+k12 = 0.001         % (1/uM)    
+k21 = 100           % (1/uM/s)  
+k22 = 473           % (1/s)     
+k3 = 6.235          % (1/s)     
+k41 = 100           % (1/uM/s)  
+k42 = 8772          % (1/s)     
+k51 = 100           % (1/uM/s)  
+k52 = 0.09726       % (1/s)     
+k6 = 0.01417        % (1/s)
+
+% Output signal (fluorescent change) parameters      
+fc_slope = 0.024    % (1/uM) slope 
+fc_offset = 0       % () offset        
+
+********** MODEL VARIABLES
+
+% Model for the fluorescent change signal
+fc = fc_slope*P + fc_offset   
+
+********** MODEL REACTIONS
+
+M + M <=> E : R1
+    vf = k11*M*M
+    vr = k12*E
+    
+S+E <=> ES : R2
+    vf = k21*S*E
+    vr = k22*ES
+    
+ES => E + P : R3
+    vf = k3*ES
+    
+E+P <=> EP : R4
+    vf = k41*E*P
+    vr = k42*EP
+
+E+I <=> EI : R5
+    vf = k51*E*I
+    vr = k52*EI
+    
+EI => EJ : R6
+    vf = k6*EI
+    
+********** MODEL FUNCTIONS
+
+
+********** MODEL EVENTS
+
+
+********** MODEL MATLAB FUNCTIONS
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/notes.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/notes.txt
new file mode 100644
index 0000000000000000000000000000000000000000..1764afbeb80fd0be29895b502aad5e2cfe05f4b0
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex2InhibitionofHIVproteinase/notes.txt
@@ -0,0 +1,22 @@
+>>> Ex2 - Parameter Identification Benchmark Project <<<
+
+This benchmark example has been taken from the following publication:
+Rodriguez-Fernandez, M., J. A. Egea and J. R. Banga (2006) Novel 
+Metaheuristic for Parameter Estimation in Nonlinear Dynamic Biological 
+Systems. BMC Bioinformatics 7:483. 
+
+The contained model represents a system in which HIV proteinase (assay 
+concentration 4nM) is added to a solution of an irreversible inhibitor and 
+a fluorogenic substrate (25 uM). 
+
+Further references, studying this example:
+
+Kuzmic P: Program DYNAFIT for the analysis of enzyme
+kinetic data: application to HIV proteinase. Analytical 
+Biochemistry 1996, 237:260-273.
+
+Mendes, P. & Kell, D.B. (1998) Non-linear optimization 
+of biochemical pathways: applications to metabolic engineering 
+and parameter estimation. Bioinformatics  14, 869-883
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_01/Experiment_01.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_01/Experiment_01.exp
new file mode 100644
index 0000000000000000000000000000000000000000..0403d28b784b317b302e4f441a039a34f7634c5f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_01/Experiment_01.exp
@@ -0,0 +1,23 @@
+********** EXPERIMENT NAME
+
+Experiment_01
+
+********** EXPERIMENT NOTES
+
+Experiment #1 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The settings are:
+	S = 0.1
+	P = 0.05
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+S = 0.1 % Substrate S
+P = 0.05 % Product P
+
+********** EXPERIMENT PARAMETER CHANGES
+
+********** EXPERIMENT STATE CHANGES
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_01/Measurement_01.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_01/Measurement_01.csv
new file mode 100644
index 0000000000000000000000000000000000000000..cf215c318d1dc70829e8c9ec42cfbd1292b16fa0
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_01/Measurement_01.csv
@@ -0,0 +1,43 @@
+% Measurement file generated: 06-Apr-2008
+
+[Name]
+Measurement_01
+
+[Notes]
+Measurement #1 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The experimental settings have been:
+	S = 0.1
+	P = 0.05
+
+[Components]
+time,G1,G2,G3,E1,E2,E3,M1,M2
+
+[Componentnotes]
+
+[Values]
+0.000000,0.666700,0.572500,0.417600,0.400000,0.364100,0.294600,1.419000,0.934600
+6.000000,0.011532,0.257040,0.211503,0.254445,0.336287,0.274294,0.498326,0.446073
+12.000000,0.009905,0.071803,0.055377,0.144162,0.236796,0.193874,0.250161,0.215859
+18.000000,0.009901,0.031488,0.022898,0.083542,0.149363,0.121029,0.170901,0.144788
+24.000000,0.009901,0.020418,0.014657,0.050272,0.092726,0.074229,0.140563,0.118716
+30.000000,0.009901,0.016239,0.011648,0.032013,0.058795,0.046436,0.126639,0.107023
+36.000000,0.009901,0.014253,0.010249,0.021993,0.038954,0.030307,0.119224,0.100924
+42.000000,0.009901,0.013143,0.009484,0.016493,0.027430,0.021009,0.114763,0.097334
+48.000000,0.009901,0.012437,0.009004,0.013475,0.020726,0.015645,0.111773,0.094983
+54.000000,0.009901,0.011936,0.008675,0.011819,0.016791,0.012529,0.109583,0.093281
+60.000000,0.009901,0.011552,0.008423,0.010910,0.014442,0.010692,0.107836,0.091959
+66.000000,0.009901,0.011242,0.008212,0.010411,0.013001,0.009584,0.106391,0.090832
+72.000000,0.009901,0.010972,0.008036,0.010137,0.012083,0.008892,0.105147,0.089827
+78.000000,0.009901,0.010736,0.007877,0.009987,0.011473,0.008435,0.103995,0.088958
+84.000000,0.009901,0.010525,0.007730,0.009904,0.011037,0.008119,0.102978,0.088123
+90.000000,0.009901,0.010336,0.007593,0.009859,0.010710,0.007883,0.102045,0.087342
+96.000000,0.009901,0.010161,0.007466,0.009834,0.010451,0.007694,0.101184,0.086604
+102.000000,0.009901,0.010002,0.007345,0.009820,0.010235,0.007536,0.100386,0.085907
+108.000000,0.009901,0.009855,0.007233,0.009813,0.010049,0.007398,0.099644,0.085244
+114.000000,0.009901,0.009718,0.007126,0.009809,0.009885,0.007274,0.098953,0.084616
+120.000000,0.009901,0.009592,0.007026,0.009806,0.009736,0.007160,0.098309,0.084018
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_02/Experiment_02.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_02/Experiment_02.exp
new file mode 100644
index 0000000000000000000000000000000000000000..d7656278b059de8cbf0e49f6d1a8400bcd017482
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_02/Experiment_02.exp
@@ -0,0 +1,23 @@
+********** EXPERIMENT NAME
+
+Experiment_02
+
+********** EXPERIMENT NOTES
+
+Experiment #2 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The settings are:
+	S = 0.46416
+	P = 0.05
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+S = 0.46416 % Substrate S
+P = 0.05 % Product P
+
+********** EXPERIMENT PARAMETER CHANGES
+
+********** EXPERIMENT STATE CHANGES
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_02/Measurement_02.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_02/Measurement_02.csv
new file mode 100644
index 0000000000000000000000000000000000000000..4fbfeafb036c89966f85db337d077572bbe73ba8
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_02/Measurement_02.csv
@@ -0,0 +1,43 @@
+% Measurement file generated: 06-Apr-2008
+
+[Name]
+Measurement_02
+
+[Notes]
+Measurement #2 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The experimental settings have been:
+	S = 0.46416
+	P = 0.05
+
+[Components]
+time,G1,G2,G3,E1,E2,E3,M1,M2
+
+[Componentnotes]
+
+[Values]
+0.000000,0.666700,0.572500,0.417600,0.400000,0.364100,0.294600,1.419000,0.934600
+6.000000,0.178390,0.384535,0.247707,0.305520,0.351878,0.278270,0.714883,0.516172
+12.000000,0.177182,0.196206,0.104975,0.235635,0.287500,0.213315,0.465415,0.319480
+18.000000,0.177177,0.131127,0.063142,0.197228,0.218020,0.149567,0.378806,0.251898
+24.000000,0.177177,0.111720,0.051085,0.176149,0.167431,0.105734,0.351951,0.229619
+30.000000,0.177177,0.107501,0.047998,0.164581,0.136129,0.079093,0.346895,0.224166
+36.000000,0.177177,0.108446,0.048213,0.158233,0.118614,0.064053,0.349431,0.225517
+42.000000,0.177177,0.110855,0.049712,0.154748,0.109710,0.056220,0.353912,0.229453
+48.000000,0.177177,0.113288,0.051558,0.152836,0.105733,0.052635,0.358157,0.233894
+54.000000,0.177177,0.115252,0.053257,0.151787,0.104350,0.051399,0.361476,0.237793
+60.000000,0.177177,0.116654,0.054584,0.151211,0.104191,0.051333,0.363795,0.240734
+66.000000,0.177177,0.117568,0.055498,0.150895,0.104510,0.051742,0.365277,0.242696
+72.000000,0.177177,0.118107,0.056054,0.150721,0.104938,0.052254,0.366134,0.243860
+78.000000,0.177177,0.118390,0.056349,0.150626,0.105313,0.052699,0.366570,0.244459
+84.000000,0.177177,0.118510,0.056480,0.150574,0.105586,0.053023,0.366746,0.244710
+90.000000,0.177177,0.118543,0.056514,0.150545,0.105760,0.053230,0.366783,0.244767
+96.000000,0.177177,0.118529,0.056509,0.150529,0.105857,0.053348,0.366754,0.244740
+102.000000,0.177177,0.118505,0.056482,0.150521,0.105903,0.053405,0.366708,0.244679
+108.000000,0.177177,0.118477,0.056457,0.150516,0.105918,0.053425,0.366662,0.244620
+114.000000,0.177177,0.118456,0.056435,0.150513,0.105918,0.053427,0.366626,0.244574
+120.000000,0.177177,0.118441,0.056421,0.150512,0.105911,0.053420,0.366601,0.244542
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_03/Experiment_03.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_03/Experiment_03.exp
new file mode 100644
index 0000000000000000000000000000000000000000..730feee2c0a423af0bea03f0c0b43b6b474bff7b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_03/Experiment_03.exp
@@ -0,0 +1,23 @@
+********** EXPERIMENT NAME
+
+Experiment_03
+
+********** EXPERIMENT NOTES
+
+Experiment #3 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The settings are:
+	S = 2.1544
+	P = 0.05
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+S = 2.1544 % Substrate S
+P = 0.05 % Product P
+
+********** EXPERIMENT PARAMETER CHANGES
+
+********** EXPERIMENT STATE CHANGES
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_03/Measurement_03.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_03/Measurement_03.csv
new file mode 100644
index 0000000000000000000000000000000000000000..bd564ec6dfd775cd7fad0767d12843f16a0b1980
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_03/Measurement_03.csv
@@ -0,0 +1,43 @@
+% Measurement file generated: 06-Apr-2008
+
+[Name]
+Measurement_03
+
+[Notes]
+Measurement #3 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The experimental settings have been:
+	S = 2.1544
+	P = 0.05
+
+[Components]
+time,G1,G2,G3,E1,E2,E3,M1,M2
+
+[Componentnotes]
+
+[Values]
+0.000000,0.666700,0.572500,0.417600,0.400000,0.364100,0.294600,1.419000,0.934600
+6.000000,0.820667,0.657523,0.330559,0.420004,0.377932,0.286608,1.376433,0.679252
+12.000000,0.821051,0.633988,0.286953,0.433922,0.384122,0.261474,1.310850,0.631403
+18.000000,0.821051,0.624611,0.285943,0.441567,0.384796,0.243550,1.291253,0.634655
+24.000000,0.821052,0.625046,0.293541,0.445763,0.384613,0.235081,1.295025,0.647000
+30.000000,0.821052,0.628152,0.300501,0.448066,0.384907,0.232482,1.303936,0.657270
+36.000000,0.821051,0.630827,0.304846,0.449329,0.385577,0.232536,1.311000,0.663384
+42.000000,0.821051,0.632415,0.306952,0.450023,0.386298,0.233373,1.315010,0.666211
+48.000000,0.821051,0.633137,0.307701,0.450404,0.386876,0.234173,1.316740,0.667140
+54.000000,0.821051,0.633360,0.307819,0.450613,0.387265,0.234707,1.317217,0.667227
+60.000000,0.821051,0.633365,0.307724,0.450727,0.387493,0.234993,1.317174,0.667055
+66.000000,0.821051,0.633307,0.307605,0.450790,0.387611,0.235120,1.317000,0.666873
+72.000000,0.821051,0.633251,0.307520,0.450825,0.387667,0.235163,1.316848,0.666752
+78.000000,0.821051,0.633215,0.307475,0.450844,0.387689,0.235169,1.316755,0.666690
+84.000000,0.821051,0.633197,0.307457,0.450854,0.387697,0.235165,1.316710,0.666666
+90.000000,0.821051,0.633190,0.307452,0.450860,0.387699,0.235160,1.316694,0.666661
+96.000000,0.821051,0.633188,0.307453,0.450863,0.387700,0.235157,1.316690,0.666662
+102.000000,0.821051,0.633188,0.307454,0.450865,0.387700,0.235156,1.316692,0.666665
+108.000000,0.821051,0.633189,0.307456,0.450865,0.387700,0.235155,1.316695,0.666668
+114.000000,0.821051,0.633190,0.307457,0.450866,0.387701,0.235156,1.316697,0.666669
+120.000000,0.821051,0.633191,0.307458,0.450866,0.387701,0.235156,1.316698,0.666670
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_04/Experiment_04.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_04/Experiment_04.exp
new file mode 100644
index 0000000000000000000000000000000000000000..8dc0c0c2321ec44a934c86707846745c9adf98e9
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_04/Experiment_04.exp
@@ -0,0 +1,23 @@
+********** EXPERIMENT NAME
+
+Experiment_04
+
+********** EXPERIMENT NOTES
+
+Experiment #4 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The settings are:
+	S = 10
+	P = 0.05
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+S = 10 % Substrate S
+P = 0.05 % Product P
+
+********** EXPERIMENT PARAMETER CHANGES
+
+********** EXPERIMENT STATE CHANGES
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_04/Measurement_04.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_04/Measurement_04.csv
new file mode 100644
index 0000000000000000000000000000000000000000..f5f12fad3fcbd43fc153c90543f478e166a69d5e
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_04/Measurement_04.csv
@@ -0,0 +1,43 @@
+% Measurement file generated: 06-Apr-2008
+
+[Name]
+Measurement_04
+
+[Notes]
+Measurement #4 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The experimental settings have been:
+	S = 10
+	P = 0.05
+
+[Components]
+time,G1,G2,G3,E1,E2,E3,M1,M2
+
+[Componentnotes]
+
+[Values]
+0.000000,0.666700,0.572500,0.417600,0.400000,0.364100,0.294600,1.419000,0.934600
+6.000000,0.986860,0.827599,0.407033,0.438362,0.392682,0.293751,2.338060,0.840028
+12.000000,0.987651,0.884729,0.480790,0.464759,0.424598,0.299938,2.879655,0.990446
+18.000000,0.987654,0.908640,0.549896,0.479258,0.446652,0.319169,3.249283,1.127164
+24.000000,0.987654,0.920922,0.589345,0.487215,0.460832,0.339634,3.500299,1.211629
+30.000000,0.987654,0.927668,0.608837,0.491582,0.469709,0.355808,3.663478,1.255753
+36.000000,0.987654,0.931447,0.617781,0.493979,0.475184,0.366973,3.764567,1.276517
+42.000000,0.987654,0.933563,0.621643,0.495294,0.478527,0.374107,3.824475,1.285543
+48.000000,0.987654,0.934731,0.623214,0.496016,0.480548,0.378442,3.858593,1.289189
+54.000000,0.987654,0.935363,0.623800,0.496412,0.481760,0.380986,3.877317,1.290522
+60.000000,0.987654,0.935695,0.623984,0.496630,0.482479,0.382439,3.887219,1.290919
+66.000000,0.987654,0.935864,0.624014,0.496749,0.482902,0.383251,3.892243,1.290960
+72.000000,0.987654,0.935946,0.623991,0.496815,0.483149,0.383696,3.894658,1.290886
+78.000000,0.987654,0.935983,0.623955,0.496851,0.483290,0.383935,3.895733,1.290789
+84.000000,0.987654,0.935998,0.623924,0.496870,0.483371,0.384060,3.896150,1.290703
+90.000000,0.987654,0.936003,0.623898,0.496881,0.483416,0.384124,3.896262,1.290634
+96.000000,0.987654,0.936003,0.623879,0.496887,0.483441,0.384155,3.896247,1.290584
+102.000000,0.987654,0.936001,0.623865,0.496890,0.483455,0.384170,3.896190,1.290548
+108.000000,0.987654,0.935999,0.623856,0.496892,0.483462,0.384176,3.896127,1.290524
+114.000000,0.987654,0.935998,0.623850,0.496893,0.483466,0.384178,3.896073,1.290508
+120.000000,0.987654,0.935997,0.623846,0.496894,0.483468,0.384178,3.896031,1.290497
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_05/Experiment_05.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_05/Experiment_05.exp
new file mode 100644
index 0000000000000000000000000000000000000000..394ac5806eccb17e0565189b3e96bb985712c809
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_05/Experiment_05.exp
@@ -0,0 +1,23 @@
+********** EXPERIMENT NAME
+
+Experiment_05
+
+********** EXPERIMENT NOTES
+
+Experiment #5 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The settings are:
+	S = 0.1
+	P = 0.13572
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+S = 0.1 % Substrate S
+P = 0.13572 % Product P
+
+********** EXPERIMENT PARAMETER CHANGES
+
+********** EXPERIMENT STATE CHANGES
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_05/Measurement_05.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_05/Measurement_05.csv
new file mode 100644
index 0000000000000000000000000000000000000000..ccbb161fab6e36edf1fb369658e13900a63ce5e7
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_05/Measurement_05.csv
@@ -0,0 +1,43 @@
+% Measurement file generated: 06-Apr-2008
+
+[Name]
+Measurement_05
+
+[Notes]
+Measurement #5 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The experimental settings have been:
+	S = 0.1
+	P = 0.13572
+
+[Components]
+time,G1,G2,G3,E1,E2,E3,M1,M2
+
+[Componentnotes]
+
+[Values]
+0.000000,0.666700,0.572500,0.417600,0.400000,0.364100,0.294600,1.419000,0.934600
+6.000000,0.011530,0.266381,0.244383,0.254445,0.336722,0.278916,0.518992,0.504103
+12.000000,0.009903,0.088652,0.085014,0.144161,0.242397,0.208347,0.286119,0.279308
+18.000000,0.009899,0.045805,0.044121,0.083540,0.158763,0.139064,0.210138,0.206441
+24.000000,0.009899,0.032734,0.032193,0.050271,0.103452,0.092229,0.180246,0.179009
+30.000000,0.009899,0.027461,0.027442,0.032012,0.069703,0.063450,0.166208,0.166337
+36.000000,0.009899,0.024824,0.025071,0.021991,0.049637,0.046265,0.158508,0.159434
+42.000000,0.009899,0.023267,0.023676,0.016492,0.037777,0.036074,0.153666,0.155134
+48.000000,0.009899,0.022214,0.022746,0.013474,0.030730,0.030001,0.150238,0.152144
+54.000000,0.009899,0.021420,0.022059,0.011817,0.026475,0.026330,0.147561,0.149873
+60.000000,0.009899,0.020773,0.021518,0.010908,0.023834,0.024056,0.145324,0.148030
+66.000000,0.009899,0.020217,0.021063,0.010409,0.022128,0.022596,0.143357,0.146471
+72.000000,0.009899,0.019724,0.020673,0.010135,0.020965,0.021614,0.141592,0.145092
+78.000000,0.009899,0.019277,0.020326,0.009985,0.020125,0.020916,0.139962,0.143868
+84.000000,0.009899,0.018872,0.020010,0.009903,0.019479,0.020391,0.138468,0.142740
+90.000000,0.009899,0.018490,0.019732,0.009857,0.018956,0.019974,0.137055,0.141729
+96.000000,0.009899,0.018146,0.019467,0.009832,0.018511,0.019629,0.135741,0.140790
+102.000000,0.009899,0.017813,0.019238,0.009819,0.018120,0.019333,0.134520,0.139910
+108.000000,0.009899,0.017522,0.019007,0.009811,0.017772,0.019069,0.133378,0.139090
+114.000000,0.009899,0.017242,0.018803,0.009807,0.017455,0.018832,0.132301,0.138334
+120.000000,0.009899,0.016981,0.018613,0.009805,0.017164,0.018617,0.131288,0.137629
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_06/Experiment_06.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_06/Experiment_06.exp
new file mode 100644
index 0000000000000000000000000000000000000000..61f077c77571151dfd1147b9e71274fa4b509a8d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_06/Experiment_06.exp
@@ -0,0 +1,23 @@
+********** EXPERIMENT NAME
+
+Experiment_06
+
+********** EXPERIMENT NOTES
+
+Experiment #6 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The settings are:
+	S = 0.46416
+	P = 0.13572
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+S = 0.46416 % Substrate S
+P = 0.13572 % Product P
+
+********** EXPERIMENT PARAMETER CHANGES
+
+********** EXPERIMENT STATE CHANGES
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_06/Measurement_06.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_06/Measurement_06.csv
new file mode 100644
index 0000000000000000000000000000000000000000..28ba3158a77ba6aa5f9f52f0e9dfab74dbd6c0c4
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_06/Measurement_06.csv
@@ -0,0 +1,43 @@
+% Measurement file generated: 06-Apr-2008
+
+[Name]
+Measurement_06
+
+[Notes]
+Measurement #6 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The experimental settings have been:
+	S = 0.46416
+	P = 0.13572
+
+[Components]
+time,G1,G2,G3,E1,E2,E3,M1,M2
+
+[Componentnotes]
+
+[Values]
+0.000000,0.666700,0.572500,0.417600,0.400000,0.364100,0.294600,1.419000,0.934600
+6.000000,0.177893,0.391908,0.280601,0.305388,0.351944,0.282670,0.735657,0.574373
+12.000000,0.176679,0.217614,0.141367,0.235399,0.292250,0.227930,0.501464,0.383466
+18.000000,0.176679,0.152525,0.092842,0.196936,0.227944,0.169868,0.414766,0.311711
+24.000000,0.176679,0.129835,0.076340,0.175827,0.179834,0.127566,0.383198,0.284459
+30.000000,0.176679,0.122471,0.070400,0.164242,0.148846,0.100538,0.373023,0.274216
+36.000000,0.176679,0.120878,0.068536,0.157884,0.130504,0.084365,0.371227,0.271169
+42.000000,0.176679,0.121386,0.068410,0.154395,0.120347,0.075177,0.372446,0.271292
+48.000000,0.176679,0.122486,0.068998,0.152480,0.115099,0.070262,0.374424,0.272686
+54.000000,0.176679,0.123577,0.069794,0.151429,0.112620,0.067854,0.376279,0.274390
+60.000000,0.176679,0.124457,0.070547,0.150852,0.111611,0.066842,0.377739,0.275935
+66.000000,0.176679,0.125094,0.071151,0.150536,0.111324,0.066552,0.378778,0.277144
+72.000000,0.176679,0.125522,0.071585,0.150362,0.111351,0.066593,0.379466,0.277997
+78.000000,0.176679,0.125791,0.071869,0.150266,0.111485,0.066754,0.379892,0.278549
+84.000000,0.176679,0.125948,0.072043,0.150214,0.111632,0.066928,0.380139,0.278877
+90.000000,0.176679,0.126032,0.072140,0.150185,0.111752,0.067075,0.380269,0.279056
+96.000000,0.176679,0.126071,0.072188,0.150170,0.111839,0.067181,0.380327,0.279144
+102.000000,0.176679,0.126087,0.072206,0.150161,0.111896,0.067252,0.380346,0.279180
+108.000000,0.176679,0.126091,0.072210,0.150156,0.111930,0.067295,0.380352,0.279182
+114.000000,0.176679,0.126087,0.072210,0.150154,0.111948,0.067319,0.380345,0.279179
+120.000000,0.176679,0.126082,0.072206,0.150152,0.111957,0.067330,0.380336,0.279171
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_07/Experiment_07.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_07/Experiment_07.exp
new file mode 100644
index 0000000000000000000000000000000000000000..4caa07a5936a57c0fffafe601b8a3b90a4457389
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_07/Experiment_07.exp
@@ -0,0 +1,23 @@
+********** EXPERIMENT NAME
+
+Experiment_07
+
+********** EXPERIMENT NOTES
+
+Experiment #7 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The settings are:
+	S = 2.1544
+	P = 0.13572
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+S = 2.1544 % Substrate S
+P = 0.13572 % Product P
+
+********** EXPERIMENT PARAMETER CHANGES
+
+********** EXPERIMENT STATE CHANGES
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_07/Measurement_07.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_07/Measurement_07.csv
new file mode 100644
index 0000000000000000000000000000000000000000..2487888149ebbb519783e7bdb62f4e38be2c428c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_07/Measurement_07.csv
@@ -0,0 +1,43 @@
+% Measurement file generated: 06-Apr-2008
+
+[Name]
+Measurement_07
+
+[Notes]
+Measurement #7 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The experimental settings have been:
+	S = 2.1544
+	P = 0.13572
+
+[Components]
+time,G1,G2,G3,E1,E2,E3,M1,M2
+
+[Componentnotes]
+
+[Values]
+0.000000,0.666700,0.572500,0.417600,0.400000,0.364100,0.294600,1.419000,0.934600
+6.000000,0.810099,0.655830,0.361619,0.418732,0.377264,0.290465,1.397192,0.738181
+12.000000,0.810457,0.640260,0.328049,0.431774,0.384267,0.273544,1.350510,0.698838
+18.000000,0.810458,0.633350,0.325404,0.438939,0.386241,0.260917,1.334378,0.698343
+24.000000,0.810458,0.632964,0.329626,0.442871,0.386837,0.254519,1.335168,0.705711
+30.000000,0.810457,0.634648,0.334062,0.445029,0.387337,0.252179,1.340522,0.712587
+36.000000,0.810458,0.636325,0.337102,0.446213,0.387909,0.251836,1.345319,0.717093
+42.000000,0.810458,0.637433,0.338773,0.446863,0.388456,0.252217,1.348354,0.719487
+48.000000,0.810458,0.638015,0.339526,0.447220,0.388891,0.252710,1.349890,0.720523
+54.000000,0.810458,0.638259,0.339784,0.447415,0.389194,0.253094,1.350503,0.720850
+60.000000,0.810458,0.638328,0.339821,0.447523,0.389383,0.253336,1.350654,0.720875
+66.000000,0.810458,0.638324,0.339785,0.447582,0.389491,0.253465,1.350623,0.720809
+72.000000,0.810458,0.638301,0.339741,0.447614,0.389547,0.253525,1.350553,0.720739
+78.000000,0.810458,0.638280,0.339708,0.447632,0.389574,0.253549,1.350492,0.720690
+84.000000,0.810458,0.638266,0.339689,0.447641,0.389587,0.253556,1.350452,0.720663
+90.000000,0.810458,0.638258,0.339680,0.447647,0.389591,0.253556,1.350431,0.720650
+96.000000,0.810458,0.638255,0.339678,0.447650,0.389593,0.253554,1.350423,0.720647
+102.000000,0.810458,0.638254,0.339677,0.447651,0.389593,0.253553,1.350422,0.720647
+108.000000,0.810458,0.638254,0.339678,0.447652,0.389594,0.253552,1.350422,0.720648
+114.000000,0.810458,0.638254,0.339678,0.447653,0.389594,0.253552,1.350422,0.720649
+120.000000,0.810458,0.638255,0.339679,0.447653,0.389594,0.253552,1.350423,0.720649
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_08/Experiment_08.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_08/Experiment_08.exp
new file mode 100644
index 0000000000000000000000000000000000000000..a0f39290a3b32668e9bbb2355e1b35f4592e516a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_08/Experiment_08.exp
@@ -0,0 +1,23 @@
+********** EXPERIMENT NAME
+
+Experiment_08
+
+********** EXPERIMENT NOTES
+
+Experiment #8 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The settings are:
+	S = 10
+	P = 0.13572
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+S = 10 % Substrate S
+P = 0.13572 % Product P
+
+********** EXPERIMENT PARAMETER CHANGES
+
+********** EXPERIMENT STATE CHANGES
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_08/Measurement_08.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_08/Measurement_08.csv
new file mode 100644
index 0000000000000000000000000000000000000000..53777e0e7e3f95cde99b7c99397ba949e943c088
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_08/Measurement_08.csv
@@ -0,0 +1,43 @@
+% Measurement file generated: 06-Apr-2008
+
+[Name]
+Measurement_08
+
+[Notes]
+Measurement #8 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The experimental settings have been:
+	S = 10
+	P = 0.13572
+
+[Components]
+time,G1,G2,G3,E1,E2,E3,M1,M2
+
+[Componentnotes]
+
+[Values]
+0.000000,0.666700,0.572500,0.417600,0.400000,0.364100,0.294600,1.419000,0.934600
+6.000000,0.971612,0.818720,0.434772,0.436796,0.391612,0.297090,2.358501,0.900122
+12.000000,0.972363,0.875275,0.512760,0.462140,0.422812,0.308482,2.925179,1.064377
+18.000000,0.972366,0.898532,0.577689,0.476061,0.444437,0.329541,3.310957,1.205460
+24.000000,0.972366,0.910351,0.614745,0.483701,0.458334,0.350035,3.572897,1.294543
+30.000000,0.972365,0.916864,0.633912,0.487894,0.467026,0.365865,3.745140,1.344029
+36.000000,0.972366,0.920577,0.643476,0.490195,0.472390,0.376817,3.854480,1.369737
+42.000000,0.972365,0.922719,0.648174,0.491458,0.475674,0.383934,3.921733,1.382634
+48.000000,0.972365,0.923954,0.650468,0.492151,0.477672,0.388377,3.961997,1.389001
+54.000000,0.972365,0.924662,0.651588,0.492532,0.478880,0.391077,3.985557,1.392126
+60.000000,0.972365,0.925063,0.652134,0.492741,0.479608,0.392686,3.999064,1.393654
+66.000000,0.972365,0.925288,0.652398,0.492855,0.480043,0.393632,4.006662,1.394392
+72.000000,0.972365,0.925412,0.652523,0.492918,0.480302,0.394180,4.010852,1.394738
+78.000000,0.972365,0.925479,0.652578,0.492952,0.480455,0.394494,4.013115,1.394892
+84.000000,0.972365,0.925514,0.652602,0.492971,0.480545,0.394673,4.014308,1.394954
+90.000000,0.972365,0.925533,0.652609,0.492982,0.480597,0.394773,4.014917,1.394972
+96.000000,0.972365,0.925542,0.652610,0.492988,0.480628,0.394829,4.015214,1.394971
+102.000000,0.972365,0.925546,0.652608,0.492991,0.480645,0.394859,4.015349,1.394963
+108.000000,0.972365,0.925548,0.652605,0.492992,0.480655,0.394875,4.015402,1.394954
+114.000000,0.972365,0.925548,0.652602,0.492993,0.480660,0.394884,4.015417,1.394945
+120.000000,0.972365,0.925548,0.652600,0.492994,0.480663,0.394888,4.015416,1.394938
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_09/Experiment_09.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_09/Experiment_09.exp
new file mode 100644
index 0000000000000000000000000000000000000000..7b3a72f1984db8dabc68d8dd25e4a5b8382100f3
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_09/Experiment_09.exp
@@ -0,0 +1,23 @@
+********** EXPERIMENT NAME
+
+Experiment_09
+
+********** EXPERIMENT NOTES
+
+Experiment #9 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The settings are:
+	S = 0.1
+	P = 0.3684
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+S = 0.1 % Substrate S
+P = 0.3684 % Product P
+
+********** EXPERIMENT PARAMETER CHANGES
+
+********** EXPERIMENT STATE CHANGES
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_09/Measurement_09.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_09/Measurement_09.csv
new file mode 100644
index 0000000000000000000000000000000000000000..38bf0a2075242b435e3984132327e1ae0a12ac14
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_09/Measurement_09.csv
@@ -0,0 +1,43 @@
+% Measurement file generated: 06-Apr-2008
+
+[Name]
+Measurement_09
+
+[Notes]
+Measurement #9 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The experimental settings have been:
+	S = 0.1
+	P = 0.3684
+
+[Components]
+time,G1,G2,G3,E1,E2,E3,M1,M2
+
+[Componentnotes]
+
+[Values]
+0.000000,0.666700,0.572500,0.417600,0.400000,0.364100,0.294600,1.419000,0.934600
+6.000000,0.011513,0.279626,0.311529,0.254441,0.334761,0.286044,0.564401,0.641702
+12.000000,0.009892,0.129909,0.172552,0.144154,0.252414,0.239784,0.369452,0.439710
+18.000000,0.009888,0.089352,0.122493,0.083531,0.180894,0.187100,0.308287,0.369133
+24.000000,0.009888,0.076281,0.105787,0.050261,0.133093,0.148093,0.286460,0.343725
+30.000000,0.009888,0.071880,0.099501,0.032001,0.103917,0.122982,0.278963,0.333721
+36.000000,0.009888,0.070781,0.097029,0.021980,0.086984,0.107745,0.277359,0.329756
+42.000000,0.009888,0.071094,0.096166,0.016481,0.077601,0.098828,0.278349,0.328438
+48.000000,0.009888,0.072031,0.096041,0.013462,0.072726,0.093779,0.280477,0.328360
+54.000000,0.009888,0.073224,0.096272,0.011806,0.070481,0.091043,0.283044,0.328878
+60.000000,0.009888,0.074488,0.096671,0.010897,0.069736,0.089667,0.285698,0.329677
+66.000000,0.009888,0.075729,0.097142,0.010398,0.069818,0.089078,0.288265,0.330593
+72.000000,0.009888,0.076901,0.097636,0.010124,0.070334,0.088937,0.290666,0.331537
+78.000000,0.009888,0.077985,0.098123,0.009974,0.071053,0.089044,0.292868,0.332460
+84.000000,0.009888,0.078974,0.098588,0.009891,0.071849,0.089281,0.294865,0.333338
+90.000000,0.009888,0.079870,0.099025,0.009846,0.072649,0.089579,0.296663,0.334158
+96.000000,0.009888,0.080677,0.099428,0.009821,0.073416,0.089899,0.298276,0.334913
+102.000000,0.009888,0.081401,0.099798,0.009807,0.074130,0.090218,0.299720,0.335604
+108.000000,0.009888,0.082050,0.100134,0.009800,0.074785,0.090524,0.301009,0.336231
+114.000000,0.009888,0.082631,0.100439,0.009795,0.075380,0.090810,0.302159,0.336798
+120.000000,0.009888,0.083150,0.100714,0.009793,0.075917,0.091075,0.303183,0.337309
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_10/Experiment_10.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_10/Experiment_10.exp
new file mode 100644
index 0000000000000000000000000000000000000000..9ffcdf49a2ffc39bd446b614a49468c846610bc8
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_10/Experiment_10.exp
@@ -0,0 +1,23 @@
+********** EXPERIMENT NAME
+
+Experiment_10
+
+********** EXPERIMENT NOTES
+
+Experiment #10 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The settings are:
+	S = 0.46416
+	P = 0.3684
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+S = 0.46416 % Substrate S
+P = 0.3684 % Product P
+
+********** EXPERIMENT PARAMETER CHANGES
+
+********** EXPERIMENT STATE CHANGES
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_10/Measurement_10.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_10/Measurement_10.csv
new file mode 100644
index 0000000000000000000000000000000000000000..e20a30475cb9dc330cffc3374ab95c31a040d8d3
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_10/Measurement_10.csv
@@ -0,0 +1,43 @@
+% Measurement file generated: 06-Apr-2008
+
+[Name]
+Measurement_10
+
+[Notes]
+Measurement #10 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The experimental settings have been:
+	S = 0.46416
+	P = 0.3684
+
+[Components]
+time,G1,G2,G3,E1,E2,E3,M1,M2
+
+[Componentnotes]
+
+[Values]
+0.000000,0.666700,0.572500,0.417600,0.400000,0.364100,0.294600,1.419000,0.934600
+6.000000,0.174321,0.394054,0.343946,0.304432,0.348536,0.289096,0.781967,0.712243
+12.000000,0.173096,0.260897,0.235472,0.233704,0.298126,0.256974,0.586035,0.545900
+18.000000,0.173092,0.204922,0.183400,0.194833,0.246827,0.217194,0.506922,0.472141
+24.000000,0.173092,0.179914,0.160635,0.173500,0.207361,0.184557,0.470887,0.439000
+30.000000,0.173092,0.167996,0.149764,0.161793,0.180235,0.161511,0.453340,0.422631
+36.000000,0.173092,0.162009,0.144100,0.155367,0.162610,0.146245,0.444392,0.413906
+42.000000,0.173092,0.158895,0.140977,0.151841,0.151520,0.136444,0.439694,0.409029
+48.000000,0.173092,0.157240,0.139202,0.149906,0.144683,0.130263,0.437184,0.406238
+54.000000,0.173092,0.156351,0.138183,0.148844,0.140529,0.126411,0.435832,0.404631
+60.000000,0.173092,0.155870,0.137598,0.148262,0.138032,0.124031,0.435100,0.403708
+66.000000,0.173092,0.155610,0.137264,0.147941,0.136544,0.122574,0.434706,0.403183
+72.000000,0.173092,0.155472,0.137077,0.147766,0.135664,0.121688,0.434496,0.402890
+78.000000,0.173092,0.155399,0.136974,0.147669,0.135148,0.121154,0.434385,0.402729
+84.000000,0.173092,0.155362,0.136918,0.147616,0.134847,0.120835,0.434329,0.402642
+90.000000,0.173092,0.155342,0.136890,0.147587,0.134673,0.120646,0.434300,0.402598
+96.000000,0.173092,0.155335,0.136874,0.147571,0.134574,0.120535,0.434289,0.402573
+102.000000,0.173092,0.155329,0.136869,0.147562,0.134517,0.120471,0.434280,0.402566
+108.000000,0.173092,0.155331,0.136863,0.147558,0.134485,0.120434,0.434284,0.402556
+114.000000,0.173092,0.155329,0.136863,0.147555,0.134468,0.120412,0.434281,0.402557
+120.000000,0.173092,0.155329,0.136863,0.147553,0.134458,0.120401,0.434281,0.402557
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_11/Experiment_11.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_11/Experiment_11.exp
new file mode 100644
index 0000000000000000000000000000000000000000..f889c5d925a00182d525d8196db435d2df67bd71
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_11/Experiment_11.exp
@@ -0,0 +1,23 @@
+********** EXPERIMENT NAME
+
+Experiment_11
+
+********** EXPERIMENT NOTES
+
+Experiment #11 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The settings are:
+	S = 2.1544
+	P = 0.3684
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+S = 2.1544 % Substrate S
+P = 0.3684 % Product P
+
+********** EXPERIMENT PARAMETER CHANGES
+
+********** EXPERIMENT STATE CHANGES
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_11/Measurement_11.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_11/Measurement_11.csv
new file mode 100644
index 0000000000000000000000000000000000000000..518486b825d0970b2ed3de1e8fdd55078030eb12
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_11/Measurement_11.csv
@@ -0,0 +1,43 @@
+% Measurement file generated: 06-Apr-2008
+
+[Name]
+Measurement_11
+
+[Notes]
+Measurement #11 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The experimental settings have been:
+	S = 2.1544
+	P = 0.3684
+
+[Components]
+time,G1,G2,G3,E1,E2,E3,M1,M2
+
+[Componentnotes]
+
+[Values]
+0.000000,0.666700,0.572500,0.417600,0.400000,0.364100,0.294600,1.419000,0.934600
+6.000000,0.739922,0.618436,0.412804,0.409922,0.370938,0.295311,1.442801,0.876657
+12.000000,0.740100,0.618355,0.406136,0.416866,0.376006,0.292836,1.440739,0.867688
+18.000000,0.740100,0.618004,0.406109,0.420681,0.378708,0.290980,1.439771,0.868492
+24.000000,0.740100,0.618183,0.407187,0.422774,0.380185,0.290137,1.440696,0.870702
+30.000000,0.740100,0.618532,0.408157,0.423923,0.381047,0.289914,1.442082,0.872538
+36.000000,0.740100,0.618840,0.408816,0.424553,0.381578,0.289974,1.443232,0.873752
+42.000000,0.740100,0.619050,0.409208,0.424899,0.381913,0.290122,1.443993,0.874459
+48.000000,0.740100,0.619173,0.409419,0.425089,0.382124,0.290268,1.444430,0.874833
+54.000000,0.740100,0.619237,0.409521,0.425193,0.382256,0.290382,1.444651,0.875011
+60.000000,0.740100,0.619267,0.409565,0.425251,0.382335,0.290459,1.444750,0.875085
+66.000000,0.740100,0.619278,0.409581,0.425282,0.382382,0.290508,1.444786,0.875110
+72.000000,0.740100,0.619281,0.409584,0.425299,0.382408,0.290537,1.444793,0.875113
+78.000000,0.740100,0.619280,0.409582,0.425308,0.382423,0.290552,1.444788,0.875109
+84.000000,0.740100,0.619278,0.409580,0.425314,0.382431,0.290560,1.444782,0.875104
+90.000000,0.740100,0.619277,0.409578,0.425317,0.382435,0.290564,1.444777,0.875101
+96.000000,0.740100,0.619276,0.409577,0.425318,0.382437,0.290566,1.444775,0.875099
+102.000000,0.740100,0.619275,0.409576,0.425319,0.382438,0.290567,1.444773,0.875098
+108.000000,0.740100,0.619275,0.409575,0.425319,0.382439,0.290567,1.444771,0.875096
+114.000000,0.740100,0.619275,0.409575,0.425319,0.382439,0.290567,1.444770,0.875095
+120.000000,0.740100,0.619274,0.409575,0.425319,0.382439,0.290567,1.444769,0.875095
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_12/Experiment_12.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_12/Experiment_12.exp
new file mode 100644
index 0000000000000000000000000000000000000000..57001c0271842517a47d9c6b5b6c25d07dbb0d62
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_12/Experiment_12.exp
@@ -0,0 +1,23 @@
+********** EXPERIMENT NAME
+
+Experiment_12
+
+********** EXPERIMENT NOTES
+
+Experiment #12 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The settings are:
+	S = 10
+	P = 0.3684
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+S = 10 % Substrate S
+P = 0.3684 % Product P
+
+********** EXPERIMENT PARAMETER CHANGES
+
+********** EXPERIMENT STATE CHANGES
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_12/Measurement_12.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_12/Measurement_12.csv
new file mode 100644
index 0000000000000000000000000000000000000000..cd24ab632c1a6e6e33a043598e9d3316ed0a2688
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_12/Measurement_12.csv
@@ -0,0 +1,43 @@
+% Measurement file generated: 06-Apr-2008
+
+[Name]
+Measurement_12
+
+[Notes]
+Measurement #12 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The experimental settings have been:
+	S = 10
+	P = 0.3684
+
+[Components]
+time,G1,G2,G3,E1,E2,E3,M1,M2
+
+[Componentnotes]
+
+[Values]
+0.000000,0.666700,0.572500,0.417600,0.400000,0.364100,0.294600,1.419000,0.934600
+6.000000,0.872300,0.749926,0.471797,0.426030,0.383516,0.300508,2.397059,1.039383
+12.000000,0.872814,0.797930,0.549360,0.444075,0.408245,0.318392,3.011186,1.241535
+18.000000,0.872815,0.817107,0.601043,0.453987,0.425913,0.340349,3.432651,1.399731
+24.000000,0.872814,0.826757,0.630365,0.459427,0.437422,0.359210,3.723875,1.504725
+30.000000,0.872815,0.832169,0.646789,0.462412,0.444696,0.373239,3.923085,1.570310
+36.000000,0.872815,0.835389,0.656167,0.464051,0.449239,0.382969,4.057724,1.610486
+42.000000,0.872815,0.837372,0.661668,0.464950,0.452065,0.389472,4.147818,1.635149
+48.000000,0.872814,0.838620,0.664987,0.465444,0.453823,0.393727,4.207680,1.650476
+54.000000,0.872815,0.839417,0.667042,0.465715,0.454919,0.396481,4.247281,1.660151
+60.000000,0.872815,0.839931,0.668343,0.465863,0.455604,0.398253,4.273420,1.666355
+66.000000,0.872815,0.840265,0.669179,0.465945,0.456035,0.399393,4.290660,1.670383
+72.000000,0.872815,0.840483,0.669724,0.465990,0.456307,0.400125,4.302033,1.673022
+78.000000,0.872815,0.840626,0.670082,0.466014,0.456479,0.400598,4.309544,1.674766
+84.000000,0.872815,0.840720,0.670320,0.466028,0.456589,0.400904,4.314513,1.675923
+90.000000,0.872815,0.840782,0.670478,0.466035,0.456659,0.401103,4.317804,1.676693
+96.000000,0.872815,0.840823,0.670583,0.466039,0.456705,0.401233,4.319987,1.677206
+102.000000,0.872815,0.840851,0.670653,0.466042,0.456734,0.401318,4.321437,1.677548
+108.000000,0.872815,0.840869,0.670700,0.466043,0.456753,0.401373,4.322399,1.677776
+114.000000,0.872815,0.840881,0.670731,0.466043,0.456765,0.401410,4.323039,1.677929
+120.000000,0.872815,0.840888,0.670751,0.466044,0.456773,0.401434,4.323467,1.678030
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_13/Experiment_13.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_13/Experiment_13.exp
new file mode 100644
index 0000000000000000000000000000000000000000..5351eaaf668d172c1706a1f6c3c7462f0126eff4
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_13/Experiment_13.exp
@@ -0,0 +1,23 @@
+********** EXPERIMENT NAME
+
+Experiment_13
+
+********** EXPERIMENT NOTES
+
+Experiment #13 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The settings are:
+	S = 0.1
+	P = 1
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+S = 0.1 % Substrate S
+P = 1 % Product P
+
+********** EXPERIMENT PARAMETER CHANGES
+
+********** EXPERIMENT STATE CHANGES
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_13/Measurement_13.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_13/Measurement_13.csv
new file mode 100644
index 0000000000000000000000000000000000000000..e236a092d5d5aaea794faff20cbb1349c0fc05d4
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_13/Measurement_13.csv
@@ -0,0 +1,43 @@
+% Measurement file generated: 06-Apr-2008
+
+[Name]
+Measurement_13
+
+[Notes]
+Measurement #13 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The experimental settings have been:
+	S = 0.1
+	P = 1
+
+[Components]
+time,G1,G2,G3,E1,E2,E3,M1,M2
+
+[Componentnotes]
+
+[Values]
+0.000000,0.666700,0.572500,0.417600,0.400000,0.364100,0.294600,1.419000,0.934600
+6.000000,0.011431,0.247333,0.319423,0.254411,0.314339,0.275728,0.639262,0.916168
+12.000000,0.009809,0.178294,0.284507,0.144101,0.247839,0.255196,0.516297,0.798345
+18.000000,0.009804,0.168698,0.269291,0.083465,0.201823,0.237237,0.505280,0.760636
+24.000000,0.009804,0.176341,0.267783,0.050187,0.177005,0.225495,0.526480,0.760383
+30.000000,0.009804,0.190527,0.271580,0.031924,0.167197,0.219574,0.561028,0.773595
+36.000000,0.009804,0.206908,0.276989,0.021901,0.166785,0.217680,0.600915,0.791062
+42.000000,0.009804,0.223138,0.282645,0.016400,0.171646,0.218191,0.641541,0.809408
+48.000000,0.009804,0.237952,0.288071,0.013381,0.178992,0.219994,0.680090,0.827355
+54.000000,0.009804,0.250813,0.293082,0.011724,0.187074,0.222399,0.715026,0.844316
+60.000000,0.009804,0.261642,0.297595,0.010815,0.194893,0.224998,0.745734,0.859935
+66.000000,0.009804,0.270602,0.301576,0.010316,0.201958,0.227556,0.772183,0.873994
+72.000000,0.009804,0.277947,0.305023,0.010042,0.208085,0.229941,0.794662,0.886401
+78.000000,0.009804,0.283942,0.307966,0.009892,0.213266,0.232089,0.813596,0.897169
+84.000000,0.009804,0.288827,0.310450,0.009809,0.217578,0.233976,0.829450,0.906395
+90.000000,0.009804,0.292807,0.312529,0.009764,0.221132,0.235605,0.842668,0.914218
+96.000000,0.009804,0.296050,0.314261,0.009739,0.224044,0.236992,0.853654,0.920803
+102.000000,0.009804,0.298696,0.315696,0.009725,0.226423,0.238162,0.862764,0.926315
+108.000000,0.009804,0.300857,0.316883,0.009718,0.228362,0.239142,0.870305,0.930907
+114.000000,0.009804,0.302623,0.317863,0.009714,0.229943,0.239958,0.876539,0.934722
+120.000000,0.009804,0.304068,0.318670,0.009711,0.231232,0.240635,0.881687,0.937885
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_14/Experiment_14.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_14/Experiment_14.exp
new file mode 100644
index 0000000000000000000000000000000000000000..483dd4c332e8a73c90342e28d3944b455ed85e6f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_14/Experiment_14.exp
@@ -0,0 +1,23 @@
+********** EXPERIMENT NAME
+
+Experiment_14
+
+********** EXPERIMENT NOTES
+
+Experiment #14 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The settings are:
+	S = 0.46416
+	P = 1
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+S = 0.46416 % Substrate S
+P = 1 % Product P
+
+********** EXPERIMENT PARAMETER CHANGES
+
+********** EXPERIMENT STATE CHANGES
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_14/Measurement_14.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_14/Measurement_14.csv
new file mode 100644
index 0000000000000000000000000000000000000000..36df812c94f29a2b47d3a477e43b96eb965723a4
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_14/Measurement_14.csv
@@ -0,0 +1,43 @@
+% Measurement file generated: 06-Apr-2008
+
+[Name]
+Measurement_14
+
+[Notes]
+Measurement #14 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The experimental settings have been:
+	S = 0.46416
+	P = 1
+
+[Components]
+time,G1,G2,G3,E1,E2,E3,M1,M2
+
+[Componentnotes]
+
+[Values]
+0.000000,0.666700,0.572500,0.417600,0.400000,0.364100,0.294600,1.419000,0.934600
+6.000000,0.151851,0.311774,0.332681,0.298299,0.322650,0.277048,0.861946,0.986624
+12.000000,0.150571,0.266085,0.315020,0.222812,0.276421,0.262213,0.741655,0.912017
+18.000000,0.150567,0.249965,0.302602,0.181326,0.243667,0.250025,0.702311,0.870213
+24.000000,0.150567,0.243108,0.296573,0.158558,0.222733,0.241042,0.685804,0.851470
+30.000000,0.150567,0.239944,0.293925,0.146063,0.209909,0.235049,0.678253,0.843518
+36.000000,0.150567,0.238457,0.292837,0.139205,0.202244,0.231305,0.674733,0.840327
+42.000000,0.150567,0.237773,0.292437,0.135441,0.197744,0.229071,0.673129,0.839193
+48.000000,0.150567,0.237477,0.292326,0.133376,0.195142,0.227786,0.672450,0.838915
+54.000000,0.150567,0.237368,0.292330,0.132242,0.193661,0.227070,0.672211,0.838964
+60.000000,0.150567,0.237345,0.292370,0.131620,0.192831,0.226685,0.672174,0.839113
+66.000000,0.150567,0.237358,0.292417,0.131279,0.192375,0.226486,0.672219,0.839273
+72.000000,0.150567,0.237384,0.292458,0.131091,0.192132,0.226388,0.672292,0.839410
+78.000000,0.150567,0.237412,0.292490,0.130988,0.192006,0.226344,0.672367,0.839517
+84.000000,0.150567,0.237438,0.292514,0.130932,0.191945,0.226328,0.672435,0.839597
+90.000000,0.150567,0.237458,0.292533,0.130901,0.191919,0.226325,0.672487,0.839658
+96.000000,0.150567,0.237474,0.292546,0.130884,0.191909,0.226327,0.672530,0.839700
+102.000000,0.150567,0.237487,0.292555,0.130875,0.191908,0.226331,0.672563,0.839731
+108.000000,0.150567,0.237497,0.292562,0.130870,0.191911,0.226336,0.672588,0.839752
+114.000000,0.150567,0.237504,0.292566,0.130867,0.191915,0.226339,0.672607,0.839767
+120.000000,0.150567,0.237509,0.292570,0.130865,0.191919,0.226343,0.672620,0.839778
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_15/Experiment_15.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_15/Experiment_15.exp
new file mode 100644
index 0000000000000000000000000000000000000000..399346193694f16d9c9acbb97bc2f6801964aefd
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_15/Experiment_15.exp
@@ -0,0 +1,23 @@
+********** EXPERIMENT NAME
+
+Experiment_15
+
+********** EXPERIMENT NOTES
+
+Experiment #15 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The settings are:
+	S = 2.1544
+	P = 1
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+S = 2.1544 % Substrate S
+P = 1 % Product P
+
+********** EXPERIMENT PARAMETER CHANGES
+
+********** EXPERIMENT STATE CHANGES
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_15/Measurement_15.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_15/Measurement_15.csv
new file mode 100644
index 0000000000000000000000000000000000000000..a38cedb544ad93a55a0f5e25df13e6628f184a0d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_15/Measurement_15.csv
@@ -0,0 +1,43 @@
+% Measurement file generated: 06-Apr-2008
+
+[Name]
+Measurement_15
+
+[Notes]
+Measurement #15 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The experimental settings have been:
+	S = 2.1544
+	P = 1
+
+[Components]
+time,G1,G2,G3,E1,E2,E3,M1,M2
+
+[Componentnotes]
+
+[Values]
+0.000000,0.666700,0.572500,0.417600,0.400000,0.364100,0.294600,1.419000,0.934600
+6.000000,0.451908,0.409620,0.358093,0.365649,0.334838,0.279650,1.517841,1.146978
+12.000000,0.451376,0.416983,0.374682,0.341007,0.315835,0.274946,1.595976,1.234046
+18.000000,0.451375,0.421419,0.381989,0.327467,0.306701,0.274927,1.644302,1.278123
+24.000000,0.451376,0.423924,0.385695,0.320037,0.302421,0.276120,1.673224,1.302180
+30.000000,0.451376,0.425356,0.387704,0.315959,0.300488,0.277404,1.690349,1.315734
+36.000000,0.451376,0.426181,0.388829,0.313722,0.299665,0.278456,1.700410,1.323481
+42.000000,0.451375,0.426656,0.389468,0.312493,0.299350,0.279228,1.706278,1.327943
+48.000000,0.451375,0.426930,0.389835,0.311819,0.299256,0.279763,1.709679,1.330515
+54.000000,0.451375,0.427088,0.390045,0.311449,0.299249,0.280120,1.711635,1.331995
+60.000000,0.451375,0.427177,0.390166,0.311246,0.299271,0.280353,1.712754,1.332843
+66.000000,0.451375,0.427228,0.390235,0.311134,0.299298,0.280502,1.713388,1.333327
+72.000000,0.451376,0.427257,0.390274,0.311073,0.299322,0.280595,1.713746,1.333601
+78.000000,0.451375,0.427273,0.390295,0.311040,0.299339,0.280653,1.713946,1.333755
+84.000000,0.451375,0.427282,0.390308,0.311021,0.299351,0.280689,1.714056,1.333840
+90.000000,0.451375,0.427287,0.390314,0.311011,0.299359,0.280710,1.714117,1.333888
+96.000000,0.451375,0.427289,0.390318,0.311005,0.299364,0.280723,1.714149,1.333913
+102.000000,0.451375,0.427291,0.390320,0.311003,0.299368,0.280731,1.714166,1.333926
+108.000000,0.451375,0.427291,0.390321,0.311001,0.299370,0.280735,1.714174,1.333933
+114.000000,0.451375,0.427292,0.390321,0.311000,0.299371,0.280738,1.714180,1.333937
+120.000000,0.451375,0.427292,0.390322,0.310999,0.299372,0.280740,1.714184,1.333939
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_16/Experiment_16.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_16/Experiment_16.exp
new file mode 100644
index 0000000000000000000000000000000000000000..eef13fd759907d94483cba220149fd14cc0a355b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_16/Experiment_16.exp
@@ -0,0 +1,23 @@
+********** EXPERIMENT NAME
+
+Experiment_16
+
+********** EXPERIMENT NOTES
+
+Experiment #16 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The settings are:
+	S = 10
+	P = 1
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+S = 10 % Substrate S
+P = 1 % Product P
+
+********** EXPERIMENT PARAMETER CHANGES
+
+********** EXPERIMENT STATE CHANGES
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_16/Measurement_16.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_16/Measurement_16.csv
new file mode 100644
index 0000000000000000000000000000000000000000..923dc4b316eef7dc1b790400605d5ae3aa3fbe22
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/Experiment_16/Measurement_16.csv
@@ -0,0 +1,43 @@
+% Measurement file generated: 06-Apr-2008
+
+[Name]
+Measurement_16
+
+[Notes]
+Measurement #16 for the benchmark system proposed in:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+
+The experimental settings have been:
+	S = 10
+	P = 1
+
+[Components]
+time,G1,G2,G3,E1,E2,E3,M1,M2
+
+[Componentnotes]
+
+[Values]
+0.000000,0.666700,0.572500,0.417600,0.400000,0.364100,0.294600,1.419000,0.934600
+6.000000,0.497940,0.456389,0.377794,0.373771,0.341235,0.281770,2.430556,1.302539
+12.000000,0.497516,0.473203,0.413302,0.355038,0.330916,0.283420,3.070185,1.588050
+18.000000,0.497511,0.479863,0.430660,0.344746,0.327379,0.289830,3.521866,1.793626
+24.000000,0.497512,0.483306,0.440268,0.339097,0.326395,0.296131,3.856522,1.942371
+30.000000,0.497513,0.485362,0.446137,0.335997,0.326388,0.301188,4.111016,2.051691
+36.000000,0.497512,0.486698,0.449986,0.334295,0.326716,0.304971,4.307672,2.133504
+42.000000,0.497513,0.487619,0.452648,0.333362,0.327120,0.307723,4.461280,2.195802
+48.000000,0.497512,0.488276,0.454562,0.332850,0.327497,0.309709,4.582209,2.243953
+54.000000,0.497512,0.488761,0.455980,0.332569,0.327818,0.311145,4.677988,2.281625
+60.000000,0.497512,0.489126,0.457053,0.332414,0.328078,0.312193,4.754196,2.311372
+66.000000,0.497512,0.489404,0.457879,0.332329,0.328285,0.312965,4.815066,2.335024
+72.000000,0.497512,0.489619,0.458521,0.332283,0.328448,0.313542,4.863828,2.353928
+78.000000,0.497512,0.489787,0.459026,0.332257,0.328576,0.313979,4.902988,2.369090
+84.000000,0.497512,0.489920,0.459425,0.332243,0.328676,0.314312,4.934496,2.381285
+90.000000,0.497512,0.490024,0.459742,0.332236,0.328754,0.314570,4.959891,2.391114
+96.000000,0.497512,0.490108,0.459997,0.332231,0.328816,0.314771,4.980387,2.399047
+102.000000,0.497512,0.490174,0.460200,0.332229,0.328865,0.314929,4.996940,2.405456
+108.000000,0.497512,0.490228,0.460363,0.332228,0.328904,0.315054,5.010322,2.410638
+114.000000,0.497512,0.490270,0.460495,0.332227,0.328935,0.315153,5.021148,2.414831
+120.000000,0.497512,0.490305,0.460601,0.332226,0.328960,0.315232,5.029910,2.418224
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/generateDataExperiments.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/generateDataExperiments.m
new file mode 100644
index 0000000000000000000000000000000000000000..7233e57fc1c21b0aef54328731ff7db7200ec03d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/experiments/generateDataExperiments.m
@@ -0,0 +1,65 @@
+% This script does generate the experiment descriptions and measurements
+P = [0.05 0.13572 0.36840 1.0];
+S = [0.1 0.46416 2.1544 10];
+expbasename = 'Experiment_';
+measbasename = 'Measurement_';
+
+% Get all combinations of P and S
+allCombinations = [];
+for k=1:length(P),
+    for k2=1:length(S),
+        allCombinations = [allCombinations; [P(k) S(k2)]];
+    end
+end
+
+% Load the model (for later use)
+cd ../models
+model = SBmodel('model_3_step_nominal.txt');
+cd ../experiments
+
+% Process each of the 16 experiments
+figure(1); clf;
+for k=1:size(allCombinations,1),
+    if k<10,
+        num2strk = ['0' num2str(k)];
+    else
+        num2strk = num2str(k);
+    end
+    % Create experiment folder
+    foldername = [expbasename num2strk];
+    mkdir(foldername);
+    % Change into this folder
+    cd(foldername);
+    % Create an experiment structure
+    exp = struct(SBexperiment);
+    exp.name = [char(10) expbasename num2strk];
+    exp.notes = sprintf('\nExperiment #%d for the benchmark system proposed in:\n\nMoles C, Mendes P, Banga J: Parameter estimation in biochemical\npathways: a comparison of global optimization methods.\nGenome Research 2003, 13:2467-2474.\n\nThe settings are:\n\tS = %g\n\tP = %g',k,allCombinations(k,2),allCombinations(k,1));
+    exp.paramicsettings(1).name = 'S';
+    exp.paramicsettings(1).formula = num2str(allCombinations(k,2));
+    exp.paramicsettings(1).icflag = 0;
+    exp.paramicsettings(1).notes = 'Substrate S';
+    exp.paramicsettings(2).name = 'P';
+    exp.paramicsettings(2).formula = num2str(allCombinations(k,1));
+    exp.paramicsettings(2).icflag = 0;
+    exp.paramicsettings(2).notes = 'Product P';
+    % Convert to Experiment
+    exp = SBexperiment(exp);
+    % Export the experiment
+    SBcreateEXPfile(exp,[expbasename num2strk]);
+    % Run the experiment for t=[0:6:120]
+    meas = SBPDinsilicoexp(model,exp,[0:6:120],SBstates(model));
+    % Update some information in the SBmeasurement object
+    meas = struct(meas);
+    meas.name = [measbasename num2strk];
+    meas.notes = sprintf('Measurement #%d for the benchmark system proposed in:\n\nMoles C, Mendes P, Banga J: Parameter estimation in biochemical\npathways: a comparison of global optimization methods.\nGenome Research 2003, 13:2467-2474.\n\nThe experimental settings have been:\n\tS = %g\n\tP = %g',k,allCombinations(k,2),allCombinations(k,1));
+    % Plot M2 to check with paper plots
+    figure(1); 
+    M2 = meas.data(8).values;
+    time = meas.time;
+    plot(time,M2,'-o'); hold on;
+    % Convert to SBmeasurement and export it
+    meas = SBmeasurement(meas);
+    SBexportCSVmeasurement(meas,[measbasename num2strk]);
+    % Change back
+    cd ..
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/models/model_3_step.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/models/model_3_step.txt
new file mode 100644
index 0000000000000000000000000000000000000000..014a8d365956cc2f4dbc25284518e88c9bf761ea
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/models/model_3_step.txt
@@ -0,0 +1,117 @@
+********** MODEL NAME
+
+Three_step_biochemical_pathway
+
+********** MODEL NOTES
+
+This model represents a biochemical pathway with three enzymatic steps, 
+including the enzymes and mRNAs explicitly. The model was created by 
+Moles and coworkers [1] as a benchmark for parameter estimation.
+
+[1] Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+    pathways: a comparison of global optimization methods.
+    Genome Research 2003, 13:2467-2474.
+    
+This model contains parameters that differ from the nominal settings.    
+
+********** MODEL STATES
+
+% mRNA synthesis and degradation
+d/dt(G1) = vG1syn - vG1deg
+d/dt(G2) = vG2syn - vG2deg
+d/dt(G3) = vG3syn - vG3deg
+
+% Protein synthesis and degradation
+d/dt(E1) = vE1syn - vE1deg
+d/dt(E2) = vE2syn - vE2deg
+d/dt(E3) = vE3syn - vE3deg
+
+% Metabolic reactions
+d/dt(M1) = vSM1 - vM1M2
+d/dt(M2) = vM1M2 - vM2P
+
+% Initial conditions
+G1(0) = 0.6667  
+G2(0) = 0.5725 
+G3(0) = 0.4176 
+E1(0) = 0.4000 
+E2(0) = 0.3641
+E3(0) = 0.2946 
+M1(0) = 1.4190 
+M2(0) = 0.9346
+                       
+********** MODEL PARAMETERS
+
+P = 0.05
+S = 0.1
+
+V1      = 500
+Ki1     = 500
+ni1     = 5
+Ka1     = 500
+na1     = 5
+k1      = 500
+V2      = 500
+Ki2     = 500
+ni2     = 5
+Ka2     = 500
+na2     = 5
+k2      = 500
+V3      = 500
+Ki3     = 500
+ni3     = 5
+Ka3     = 500
+na3     = 5
+k3      = 500
+V4      = 5
+K4      = 500
+k4      = 5
+V5      = 5
+K5      = 500
+k5      = 5
+V6      = 5
+K6      = 500
+k6      = 5
+kcat1   = 500
+Km1     = 500
+Km2     = 500
+kcat2   = 500
+Km3     = 500
+Km4     = 500
+kcat3   = 500
+Km5     = 500
+Km6     = 500
+
+********** MODEL VARIABLES
+
+vG1syn = V1 / (1 + (P/Ki1)^ni1 + (Ka1/S)^na1 )
+vG2syn = V2 / (1 + (P/Ki2)^ni2 + (Ka2/M1)^na2 )
+vG3syn = V3 / (1 + (P/Ki3)^ni3 + (Ka3/M2)^na3 )
+
+vG1deg = k1 * G1
+vG2deg = k2 * G2
+vG3deg = k3 * G3
+
+vE1syn = V4 * G1 / ( K4+G1 )
+vE2syn = V5 * G2 / ( K5+G2 ) 
+vE3syn = V6 * G3 / ( K6+G3 )
+
+vE1deg = k4 * E1
+vE2deg = k5 * E2
+vE3deg = k6 * E3
+
+vSM1   = kcat1*E1*(1/Km1)*(S-M1) / ( 1+S/Km1+M1/Km2 ) 
+vM1M2  = kcat2*E2*(1/Km3)*(M1-M2) / ( 1+M1/Km3+M2/Km4 ) 
+vM2P   = kcat3*E3*(1/Km5)*(M2-P) / ( 1+M2/Km5+P/Km6 )
+
+********** MODEL REACTIONS
+
+
+********** MODEL FUNCTIONS
+
+
+********** MODEL EVENTS
+
+
+********** MODEL MATLAB FUNCTIONS
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/models/model_3_step_nominal.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/models/model_3_step_nominal.txt
new file mode 100644
index 0000000000000000000000000000000000000000..63d8718128f8347bbf8df1ed79cbf41ff842ea19
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/models/model_3_step_nominal.txt
@@ -0,0 +1,118 @@
+********** MODEL NAME
+
+Three_step_biochemical_pathway_nominal_parameters
+
+********** MODEL NOTES
+
+This model represents a biochemical pathway with three enzymatic steps, 
+including the enzymes and mRNAs explicitly. The model was created by 
+Moles and coworkers [1] as a benchmark for parameter estimation.
+
+[1] Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+    pathways: a comparison of global optimization methods.
+    Genome Research 2003, 13:2467-2474.
+    
+This model contains the nominal parameters with which the measurement
+data has been generated.
+
+********** MODEL STATES
+
+% mRNA synthesis and degradation
+d/dt(G1) = vG1syn - vG1deg
+d/dt(G2) = vG2syn - vG2deg
+d/dt(G3) = vG3syn - vG3deg
+
+% Protein synthesis and degradation
+d/dt(E1) = vE1syn - vE1deg
+d/dt(E2) = vE2syn - vE2deg
+d/dt(E3) = vE3syn - vE3deg
+
+% Matabolic reactions
+d/dt(M1) = vSM1 - vM1M2
+d/dt(M2) = vM1M2 - vM2P
+
+% Initial conditions
+G1(0) = 0.6667  
+G2(0) = 0.5725 
+G3(0) = 0.4176 
+E1(0) = 0.4000 
+E2(0) = 0.3641
+E3(0) = 0.2946 
+M1(0) = 1.4190 
+M2(0) = 0.9346
+                       
+********** MODEL PARAMETERS
+
+P = 0.05
+S = 0.1
+
+V1      = 1
+Ki1     = 1
+ni1     = 2
+Ka1     = 1
+na1     = 2
+k1      = 1
+V2      = 1
+Ki2     = 1
+ni2     = 2
+Ka2     = 1
+na2     = 2
+k2      = 1
+V3      = 1
+Ki3     = 1
+ni3     = 2
+Ka3     = 1
+na3     = 2
+k3      = 1
+V4      = 0.1
+K4      = 1
+k4      = 0.1
+V5      = 0.1
+K5      = 1
+k5      = 0.1
+V6      = 0.1
+K6      = 1
+k6      = 0.1
+kcat1   = 1
+Km1     = 1
+Km2     = 1
+kcat2   = 1
+Km3     = 1
+Km4     = 1
+kcat3   = 1
+Km5     = 1
+Km6     = 1
+
+********** MODEL VARIABLES
+
+vG1syn = V1 / (1 + (P/Ki1)^ni1 + (Ka1/S)^na1 )
+vG2syn = V2 / (1 + (P/Ki2)^ni2 + (Ka2/M1)^na2 )
+vG3syn = V3 / (1 + (P/Ki3)^ni3 + (Ka3/M2)^na3 )
+
+vG1deg = k1 * G1
+vG2deg = k2 * G2
+vG3deg = k3 * G3
+
+vE1syn = V4 * G1 / ( K4+G1 )
+vE2syn = V5 * G2 / ( K5+G2 ) 
+vE3syn = V6 * G3 / ( K6+G3 )
+
+vE1deg = k4 * E1
+vE2deg = k5 * E2
+vE3deg = k6 * E3
+
+vSM1   = kcat1*E1*(1/Km1)*(S-M1) / ( 1+S/Km1+M1/Km2 ) 
+vM1M2  = kcat2*E2*(1/Km3)*(M1-M2) / ( 1+M1/Km3+M2/Km4 ) 
+vM2P   = kcat3*E3*(1/Km5)*(M2-P) / ( 1+M2/Km5+P/Km6 )
+
+********** MODEL REACTIONS
+
+
+********** MODEL FUNCTIONS
+
+
+********** MODEL EVENTS
+
+
+********** MODEL MATLAB FUNCTIONS
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/notes.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/notes.txt
new file mode 100644
index 0000000000000000000000000000000000000000..3d720f0914889c18db88f605c203ef2184f68ac5
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/ex3Three-stepbiochemicalpathway/notes.txt
@@ -0,0 +1,18 @@
+>>> Ex3 - Parameter Identification Benchmark Project <<<
+
+This benchmark example has been taken from the following publications:
+
+Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+pathways: a comparison of global optimization methods.
+Genome Research 2003, 13:2467-2474.
+    
+Rodriguez-Fernandez, M., J. A. Egea and J. R. Banga (2006) Novel 
+Metaheuristic for Parameter Estimation in Nonlinear Dynamic Biological 
+Systems. BMC Bioinformatics 7:483. 
+
+This case study, considered as a challenging benchmark problem by Moles and 
+coworkers, involves a biochemical pathway with three enzymatic steps, 
+including the enzymes and mRNAs explicitly. 
+The identification problem consists of the estimation of 36 kinetic 
+parameters of the nonlinear biochemical dynamic model (8 nonlinear ODEs) 
+which describes the variation of the metabolite concentration with time.
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/run_ex1.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/run_ex1.m
new file mode 100644
index 0000000000000000000000000000000000000000..d5700d30bedc642a21fee5ac8858c31f504cbf0c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/run_ex1.m
@@ -0,0 +1,108 @@
+% >>> Ex1 - Isomerization of alpha-pinene <<<
+% 
+% This benchmark example has been taken from the following publication:
+% Rodriguez-Fernandez, M., J. A. Egea and J. R. Banga (2006) Novel 
+% Metaheuristic for Parameter Estimation in Nonlinear Dynamic Biological 
+% Systems. BMC Bioinformatics 7:483. 
+% 
+% The contained model represents a homogeneous chemical reaction 
+% describing the thermal isomerization of alpha-pinene to dipentene 
+% and alloocimen which in turn yields alpha- and beta-pyronene and 
+% a dimer.  
+% 
+% This process was studied by Fuguitt and Hawkins [1], who reported 
+% the concentrations of the reactant and the four products at eight 
+% time intervals.
+% 
+% The model in this project is based on the model by Hunter and 
+% MacGregor [2], which assumed first-order kinetics.
+% 
+% [1] Fuguitt R, Hawkins JE: Rate of Thermal Isomerization of alpha-
+%     Pinene in the Liquid Phase. JACS 1947, 69:461.
+%     
+% [2] Hunter WG, McGregor JF: The Estimation of Common Parameters
+%     from Several Responses: Some Actual Examples. In Unpublished 
+%     Report The Department of Statistics. University of Winsconsin, 1967.
+clc; clear all
+
+%% LOAD THE PROJECT
+sbp = SBPDproject('ex1Isomerizationofalpha-pinene');
+
+%% DISPLAY INFORMATION ABOUT THE PROJECT
+SBPDinfo(sbp);
+
+%% JUST A BOOKKEEPING THING
+sbpopt = sbp;
+
+%% COMPARE MEASUREMENTS WITH MODEL
+SBPDcomparemeasurements(sbp)
+
+%% SELECT PARAMETERS AND BOUNDS
+% global parameters
+% name        lower bound        upper bound
+paramdata = {
+'p1'          0                 1
+'p2'          0                 1
+'p3'          0                 1
+'p4'          0                 1
+'p5'          0                 1
+};
+
+% local (experiment dependend) parameters
+paramdatalocal = {
+% name        lower bound        upper bound
+};
+
+% initial conditions (always experiment dependend)
+icdata = {
+% name        lower bound        upper bound
+};
+
+%% DEFINE THE ESTIMATION INFORMATION (STRUCTURE)
+estimation = []; 
+
+% user defined
+% estimation.optimization.method = 'SSmSB';         % Use SSm via the interface function
+estimation.optimization.method = 'simannealingSB';   
+% estimation.optimization.method = 'simplexSB';   
+estimation.optimization.options.maxfunevals = 2000;  
+% SSmSB options
+estimation.optimization.options.log_var = [1:size(paramdata,1)];
+estimation.optimization.options.local.solver = 'n2fb';
+% simannealingSB options
+estimation.optimization.options.tempstart = 100;
+estimation.optimization.options.tempend = 0.1;
+estimation.optimization.options.tempfactor = 0.2;
+estimation.optimization.options.maxitertemp = 2000;
+
+% always needed
+estimation.parameters = paramdata;
+estimation.parameterslocal = paramdatalocal;
+estimation.initialconditions = icdata;
+
+% run estimation
+output = SBPDparameterestimation(sbpopt,estimation)
+% get optimized project
+sbpopt = output.projectopt;
+
+%% COMPARE OPTIMIZED PROJECT WITH MEASUREMENTS
+SBPDcomparemeasurements(sbpopt);
+
+%% ANALYSIS OF RESIDUALS
+SBPDanalyzeresiduals(sbpopt,estimation)
+
+%% RUN A-POSTERIORI IDENTIFIABILITY ANALYSIS
+SBPDidentifiability(sbpopt,{'p1','p2','p3','p4','p5'})
+
+%% RUN SOME FIT ANALYSIS 
+% (after completion click in lower figure to remove outliers, corresponding
+%  to local minima. Finish with "Enter")
+output = SBPDparameterfitanalysis(sbpopt,estimation)
+
+%% FITANALYSIS EVALUATION
+SBPDfaboxplot(output)
+SBPDfahist(output)
+SBPDfacorr(output)
+SBPDfaclustering(output)
+SBPDfadetcorr(output)
+SBPDfasigncorr(output)
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/run_ex2.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/run_ex2.m
new file mode 100644
index 0000000000000000000000000000000000000000..6a7393e1adb4f0e3155936a6ed7866ee7c4a9def
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/run_ex2.m
@@ -0,0 +1,105 @@
+% >>> Ex2 - Irreversible inhibition of HIV proteinase <<<
+% 
+% This benchmark example has been taken from the following publication:
+% Rodriguez-Fernandez, M., J. A. Egea and J. R. Banga (2006) Novel 
+% Metaheuristic for Parameter Estimation in Nonlinear Dynamic Biological 
+% Systems. BMC Bioinformatics 7:483. 
+% 
+% The contained model represents a system in which HIV proteinase (assay 
+% concentration 4nM) is added to a solution of an irreversible inhibitor and 
+% a fluorogenic substrate (25 uM). 
+% 
+% Further references, studying this example:
+% 
+% Kuzmic P: Program DYNAFIT for the analysis of enzyme
+% kinetic data: application to HIV proteinase. Analytical 
+% Biochemistry 1996, 237:260-273.
+% 
+% Mendes, P. & Kell, D.B. (1998) Non-linear optimization 
+% of biochemical pathways: applications to metabolic engineering 
+% and parameter estimation. Bioinformatics  14, 869-883
+
+clc; clear all
+%% LOAD THE PROJECT
+sbp = SBPDproject('ex2InhibitionofHIV proteinase');
+
+%% DISPLAY INFORMATION ABOUT THE PROJECT
+SBPDinfo(sbp);
+
+%% JUST A BOOKKEEPING THING
+sbpopt = sbp;
+
+%% COMPARE MEASUREMENTS WITH MODEL
+SBPDcomparemeasurements(sbp)
+
+%% SELECT PARAMETERS AND BOUNDS
+% global parameters
+% name        lower bound        upper bound
+paramdata = {
+'k22'         0                  1000
+'k3'          0                  100
+'k42'         0                  20000
+'k52'         0                  100
+'k6'          0                  10
+};
+
+% local (experiment dependend) parameters
+paramdatalocal = {
+% name        lower bound        upper bound
+'fc_offset'   0                  1
+};
+
+% initial conditions (always experiment dependend)
+icdata = {
+% name        lower bound        upper bound
+'S'           25*0.5             25*1.5
+'E'           0.004*0.5          0.004*1.5  
+};
+
+%% DEFINE THE ESTIMATION INFORMATION (STRUCTURE)
+estimation = []; 
+
+% user defined
+% estimation.optimization.method = 'SSmSB';           % Use SSm via the interface function
+estimation.optimization.method = 'simannealingSB';   
+% estimation.optimization.method = 'simplexSB';   
+estimation.optimization.options.maxfunevals = 30000;  
+% SSmSB options
+estimation.optimization.options.local.solver = 'dn2fb';
+% simannealingSB options
+estimation.optimization.options.tempstart = 100;
+estimation.optimization.options.tempend = 0.01;
+estimation.optimization.options.tempfactor = 0.2;
+estimation.optimization.options.maxitertemp = 2000;
+
+% always needed
+estimation.parameters = paramdata;
+estimation.parameterslocal = paramdatalocal;
+estimation.initialconditions = icdata;
+
+% run estimation
+output = SBPDparameterestimation(sbpopt,estimation)
+% get optimized project
+sbpopt = output.projectopt;
+
+%% COMPARE OPTIMIZED PROJECT WITH MEASUREMENTS
+SBPDcomparemeasurements(sbpopt);
+
+%% ANALYSIS OF RESIDUALS
+SBPDanalyzeresiduals(sbpopt,estimation)
+
+%% RUN A-POSTERIORI IDENTIFIABILITY ANALYSIS
+SBPDidentifiability(sbpopt,{'k22','k3','k42','k52','k6'})
+
+%% RUN SOME FIT ANALYSIS 
+% (after completion click in lower figure to remove outliers, corresponding
+%  to local minima. Finish with "Enter")
+output = SBPDparameterfitanalysis(sbpopt,estimation)
+
+%% FITANALYSIS EVALUATION
+SBPDfaboxplot(output)
+SBPDfahist(output)
+SBPDfacorr(output)
+SBPDfaclustering(output)
+SBPDfadetcorr(output)
+SBPDfasigncorr(output)
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/run_ex3.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/run_ex3.m
new file mode 100644
index 0000000000000000000000000000000000000000..b61d0ec726d333c74c7b6bfeca13534ee3de55e4
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/benchmarkproblems/run_ex3.m
@@ -0,0 +1,135 @@
+% >>> Ex3 - Three-step biochemical pathway <<<
+% 
+% This benchmark example has been taken from the following publication:
+% 
+% Moles C, Mendes P, Banga J: Parameter estimation in biochemical
+% pathways: a comparison of global optimization methods.
+% Genome Research 2003, 13:2467-2474.
+%     
+% This case study, considered as a challenging benchmark problem by Moles and 
+% coworkers, involves a biochemical pathway with three enzymatic steps, 
+% including the enzymes and mRNAs explicitly. 
+% The identification problem consists of the estimation of 36 kinetic 
+% parameters of the nonlinear biochemical dynamic model (8 nonlinear ODEs) 
+% which describes the variation of the metabolite concentration with time.
+
+clc; clear all
+
+%% LOAD THE PROJECT
+sbp = SBPDproject('ex3Three-stepbiochemicalpathway');
+
+%% DISPLAY INFORMATION ABOUT THE PROJECT
+SBPDinfo(sbp);
+
+%% SELECT THE MODEL TO CONSIDER (THIS PROJECT CONTAINS 2 MODELS)
+modelindex = 1; % Have a look at the output from SBPDinfo. We do not want to estimate the nominal model.
+
+%% JUST A BOOKKEEPING THING
+sbpopt = sbp;
+
+%% COMPARE MEASUREMENTS WITH MODEL
+SBPDcomparemeasurements(sbp,modelindex)
+
+%% SELECT PARAMETERS AND BOUNDS
+% global parameters
+% name        lower bound        upper bound
+paramdata = {
+'V1'            1e-12           1e3
+'Ki1'           1e-12           1e3
+'ni1'           0.1             10
+'Ka1'           1e-12           1e3
+'na1'           0.1             10
+'k1'            1e-12           1e3
+'V2'            1e-12           1e3
+'Ki2'           1e-12           1e3
+'ni2'           0.1             10
+'Ka2'           1e-12           1e3
+'na2'           0.1             10
+'k2'            1e-12           1e3
+'V3'            1e-12           1e3
+'Ki3'           1e-12           1e3
+'ni3'           0.1             10
+'Ka3'           1e-12           1e3
+'na3'           0.1             10
+'k3'            1e-12           1e3
+'V4'            1e-12           1e3
+'K4'            1e-12           1e3
+'k4'            1e-12           1e3
+'V5'            1e-12           1e3
+'K5'            1e-12           1e3
+'k5'            1e-12           1e3
+'V6'            1e-12           1e3
+'K6'            1e-12           1e3
+'k6'            1e-12           1e3
+'kcat1'         1e-12           1e3
+'Km1'           1e-12           1e3
+'Km2'           1e-12           1e3
+'kcat2'         1e-12           1e3
+'Km3'           1e-12           1e3
+'Km4'           1e-12           1e3
+'kcat3'         1e-12           1e3
+'Km5'           1e-12           1e3
+'Km6'           1e-12           1e3
+};
+
+% local (experiment dependend) parameters
+paramdatalocal = {
+% name        lower bound        upper bound
+};
+
+% initial conditions (always experiment dependend)
+icdata = {
+% name        lower bound        upper bound
+};
+
+%% DEFINE THE ESTIMATION INFORMATION (STRUCTURE)
+estimation = []; 
+
+% user defined
+estimation.modelindex = 1;                          % We need to specify the model apply the estimation to
+% estimation.optimization.method = 'SSmSB';         % Use SSm via the interface function
+estimation.optimization.method = 'simannealingSB';   
+%estimation.optimization.method = 'simplexSB';   
+estimation.optimization.options.maxfunevals = 100000;  
+% SSmSB options
+estimation.optimization.options.local.solver = 'n2fb';
+estimation.optimization.options.combination=2;
+estimation.optimization.options.diverse_criteria = 2;
+estimation.optimization.options.tolx = 1e-2;
+% simannealingSB options
+estimation.optimization.options.tempstart = 100;
+estimation.optimization.options.tempend = 0.1;
+estimation.optimization.options.tempfactor = 0.2;
+estimation.optimization.options.maxitertemp = 2000;
+
+% always needed
+estimation.parameters = paramdata;
+estimation.parameterslocal = paramdatalocal;
+estimation.initialconditions = icdata;
+
+% run estimation
+output = SBPDparameterestimation(sbpopt,estimation)
+% get optimized project
+sbpopt = output.projectopt;
+
+%% COMPARE OPTIMIZED PROJECT WITH MEASUREMENTS
+SBPDcomparemeasurements(sbpopt,modelindex);
+
+%% RUN A-POSTERIORI IDENTIFIABILITY ANALYSIS
+options = [];
+options.modelindex = 1;
+SBPDidentifiability(sbpopt,{paramdata{:,1}},options)
+
+%% RUN SOME FIT ANALYSIS 
+% (after completion click in lower figure to remove outliers, corresponding
+%  to local minima. Finish with "Enter")
+estimation.optimization.method = 'simplexSB';   
+output = SBPDparameterfitanalysis(sbpopt,estimation,20)
+
+%% FITANALYSIS EVALUATION
+SBPDfaboxplot(output)
+SBPDfahist(output)
+SBPDfacorr(output)
+SBPDfaclustering(output)
+SBPDfadetcorr(output)
+SBPDfasigncorr(output)
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/eventExample.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/eventExample.txt
new file mode 100644
index 0000000000000000000000000000000000000000..dc0d76ff604caea03d5828170d7dc16cae7a91ae
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/_EXAMPLES/eventExample.txt
@@ -0,0 +1,31 @@
+********** MODEL NAME
+Event Example
+
+********** MODEL NOTES
+Event example taken from the SBML validation suite: events_one_event_two_assignments
+
+********** MODEL STATES
+d/dt(S1) = -k1*R %species
+d/dt(S2) = +k2*R %species
+
+S1(0) = 1
+S2(0) = 0
+
+********** MODEL PARAMETERS
+k1 = 1
+k2 = 1
+
+********** MODEL VARIABLES
+
+
+********** MODEL REACTIONS
+R = S1 %reaction kinetics
+
+********** MODEL FUNCTIONS
+
+
+********** MODEL EVENTS
+Event_1 = lt(S1, 0.1),S1,1,S2,0
+
+********** MODEL MATLAB FUNCTIONS
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/auxiliary/getdatatextstructSBPD.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/auxiliary/getdatatextstructSBPD.m
new file mode 100644
index 0000000000000000000000000000000000000000..0ff7d0117f5b80f53d54b3a603b22eb34d259853
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/auxiliary/getdatatextstructSBPD.m
@@ -0,0 +1,45 @@
+function text = getdatatextstructSBPD(root,roottext,text)
+% getdatatextstructSBPD: converts a structure to a flat file
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+% converting given root level of a structure into text
+fn = fieldnames(root);
+for k=1:length(fn),
+    fv = getfield(root,fn{k});
+    if isstruct(fv),
+        text = getdatatextstructSBPD(fv,[roottext '.' fn{k}],text);
+    else
+        if isnumeric(fv),
+            if length(fv) == 1,
+                help = num2str(fv);
+                text = sprintf('%s\n%s.%s = %s;',text,roottext,fn{k},help);
+            else
+                help = sprintf('%g, ',fv);
+                text = sprintf('%s\n%s.%s = [%s];',text,roottext,fn{k},help(1:end-2));
+            end
+        end
+        if ischar(fv),
+            text = sprintf('%s\n%s.%s = ''%s'';',text,roottext,fn{k},fv);
+        end
+        if iscell(fv),
+            help = '';
+            for k2 = 1:length(fv),
+                if ischar(fv{k2}),
+                    help2 = ['''' fv{k2} ''''];
+                elseif isnumeric(fv{k2}),
+                    help2 = num2str(fv{k2});
+                else
+                    help2 = '';
+                end
+                help = sprintf('%s%s, ',help,help2);
+            end
+            text = sprintf('%s\n%s.%s = {%s};',text,roottext,fn{k},help(1:end-2));
+        end
+    end
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/auxiliary/helpparamictextSBPD.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/auxiliary/helpparamictextSBPD.m
new file mode 100644
index 0000000000000000000000000000000000000000..c9c08947475b821cca045a6892ec36aa3d21c870
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/auxiliary/helpparamictextSBPD.m
@@ -0,0 +1,85 @@
+function [ictext,paramtext,paramlocaltext,maxlength] = helpparamictextSBPD(pgn,pglb,pgub,pln,pllb,plub,icn,iclb,icub)
+% helpparamictextSBPD: help function to construct the text that is
+% necessary to define parameters and initialconditions and associated high
+% and low bounds
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+% and lowbounds for the estimation
+ictext = '';
+paramtext = '';
+paramlocaltext = '';
+% get the formatting nice
+maxlength = 0;
+maxlength2 = 0;
+for k=1:length(icn),
+    l = length(icn{k});
+    if l>maxlength,
+        maxlength = l;
+    end
+    l = length(sprintf('%g',iclb(k)));
+    if l>maxlength2,
+        maxlength2 = l;
+    end    
+end
+for k=1:length(pgn),
+    l = length(pgn{k});
+    if l>maxlength,
+        maxlength = l;
+    end
+    l = length(sprintf('%g',pglb(k)));
+    if l>maxlength2,
+        maxlength2 = l;
+    end    
+end
+for k=1:length(pln),
+    l = length(pln{k});
+    if l>maxlength,
+        maxlength = l;
+    end
+    l = length(sprintf('%g',pllb(k)));
+    if l>maxlength2,
+        maxlength2 = l;
+    end    
+end
+maxlength2 = max(maxlength2,length('Lower bounds'));
+% states
+ictext = '';
+for k=1:length(icn),
+    l = length(icn{k});
+    add = maxlength - l;
+    addText = char(32*ones(1,add));
+    l = length(sprintf('%g',iclb(k)));
+    add2 = maxlength2 - l;
+    addText2 = char(32*ones(1,add2));
+    text = sprintf('''%s''%s  %g%s  %g',icn{k},addText,iclb(k),addText2,icub(k));
+    ictext = sprintf('%s%s\n',ictext,text);
+end
+% parameters global
+paramtext = '';
+for k=1:length(pgn),
+    l = length(pgn{k});
+    add = maxlength - l;
+    addText = char(32*ones(1,add));
+    l = length(sprintf('%g',pglb(k)));
+    add2 = maxlength2 - l;
+    addText2 = char(32*ones(1,add2));    
+    text = sprintf('''%s''%s  %g%s  %g',pgn{k},addText,pglb(k),addText2,pgub(k));
+    paramtext = sprintf('%s%s\n',paramtext,text);
+end
+% parameters local
+paramlocaltext = '';
+for k=1:length(pln),
+    l = length(pln{k});
+    add = maxlength - l;
+    addText = char(32*ones(1,add));
+    l = length(sprintf('%g',pllb(k)));
+    add2 = maxlength2 - l;
+    addText2 = char(32*ones(1,add2));    
+    text = sprintf('''%s''%s  %g%s  %g',pln{k},addText,pllb(k),addText2,plub(k));
+    paramlocaltext = sprintf('%s%s\n',paramlocaltext,text);
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classes/@SBPDproject/SBPDexportproject.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classes/@SBPDproject/SBPDexportproject.m
new file mode 100644
index 0000000000000000000000000000000000000000..c123ae4464555cd5e6f911157e3f1ffe0fe74eaa
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classes/@SBPDproject/SBPDexportproject.m
@@ -0,0 +1,155 @@
+function [] = SBPDexportproject(project,varargin)
+% SBPDexportproject: exports a given project to a projectfolder
+%
+% USAGE:
+% ======
+% [] = SBPDexportproject(project)        
+% [] = SBPDexportproject(project,foldername)        
+%
+% project:  SBPDproject object
+% foldername: foldername
+%
+% DEFAULT VALUES:
+% ===============
+% foldername: foldername derived from project name
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+oldfolder = pwd();
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 1,
+    foldername = regexprep(project.name,'\W','');
+elseif nargin == 2,
+    foldername = regexprep(varargin{1},'\W','');
+else
+    error('Wrong number of input arguments.');
+end
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK FOLDERNAME
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% check if foldername already exists
+% if exist(foldername),
+%     error('Folder ''%s'' already exists. Please specify a different name.',foldername);
+% end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CREATE FOLDERS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+mkdir(foldername);
+cd(foldername);
+mkdir('models');
+mkdir('experiments');
+mkdir('estimations');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CREATE NOTES.TXT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen('notes.txt','w');
+notes = fwrite(fid,project.notes)';
+fclose(fid);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXPORT THE MODELS (only .txt FORMAT)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+cd('models');
+modelnames = {};
+for k=1:length(project.models),
+    if isempty(project.modeltypes),
+        modeltype = 0;
+    else
+        modeltype = project.modeltypes(k);
+    end
+    modelstruct = SBstruct(project.models{k});
+    nrequalnames = length(strmatchSB(modelstruct.name,modelnames,'exact'));
+    if nrequalnames > 0,
+        if modeltype == 0,
+            SBcreateTEXTfile(project.models{k},sprintf('%s_%d',modelstruct.name,nrequalnames+1));
+        else
+            SBcreateTEXTBCfile(project.models{k},sprintf('%s_%d',modelstruct.name,nrequalnames+1));
+        end
+    else
+        if modeltype == 0,
+            SBcreateTEXTfile(project.models{k},modelstruct.name);
+        else
+            SBcreateTEXTBCfile(project.models{k},modelstruct.name);
+        end
+    end
+    modelnames{end+1} = modelstruct.name;
+end
+cd('..');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXPORT THE EXPERIMENTS AND MEASUREMENTS (only .txt FORMAT)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+cd('experiments');
+experimentnames = {};
+for k=1:length(project.experiments),
+    % check for multiple equal experiment names
+    nrequalnames = length(strmatchSB(project.experiments(k).name,experimentnames,'exact'));
+    if nrequalnames > 0,
+        expfoldername = sprintf('%s_%d',project.experiments(k).name,nrequalnames+1);
+    else
+        expfoldername = project.experiments(k).name;
+    end
+    experimentnames{end+1} = project.experiments(k).name;
+    % create folder for current experiment
+    if isempty(expfoldername),
+        expfoldername = ['Experiment ' num2str(k)];
+    end
+    
+    mkdir(expfoldername);
+    cd(expfoldername);
+    % create notes.txt file
+    fid = fopen('notes.txt','w');
+    notes = fwrite(fid,project.experiments(k).notes);
+    fclose(fid);    
+    % export experiment
+    SBcreateEXPfile(project.experiments(k).experiment);
+    % create measurement files (only .csv files)
+    measurementnames = {};
+    for k2=1:length(project.experiments(k).measurements),
+        measstruct = SBstruct(project.experiments(k).measurements{k2});
+        nrequalnames = length(strmatchSB(measstruct.name,measurementnames,'exact'));
+        if nrequalnames > 0,
+            measname = sprintf('%s_%d',measstruct.name,nrequalnames+1);
+        else
+            measname = measstruct.name;
+        end
+        measurementnames{end+1} = measstruct.name;
+        % export measurement
+        SBexportCSVmeasurement(project.experiments(k).measurements{k2},measname);
+    end
+    cd('..');
+end
+cd('..');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXPORT THE ESTIMATIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+cd('estimations');
+for k=1:length(project.estimations),
+    % convert estimation to text
+    text = sprintf('%% Estimation Settings\n\nestimation = [];');
+    text = getdatatextstructSBPD(project.estimations{k},'estimation',text);
+    % filename
+    ext = num2str(k);
+    ext = char([48*ones(1,3-length(ext)) double(ext)]);
+    filename = sprintf('Estimation_%s.est',ext);
+    % write to file
+    fid = fopen(filename,'w');
+    fwrite(fid,text);
+    fclose(fid);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% BACK TO STARTING FOLDER
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+cd(oldfolder);
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classes/@SBPDproject/SBPDproject.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classes/@SBPDproject/SBPDproject.m
new file mode 100644
index 0000000000000000000000000000000000000000..448b5f79a173926aea7edbd622b6809eee72f410
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classes/@SBPDproject/SBPDproject.m
@@ -0,0 +1,96 @@
+function [project] = SBPDproject(varargin)
+% SBPDproject: creates a project object containing models, experiments,
+% measurements, and information needed for parameterestimation
+%
+% USAGE:
+% ======
+% [project] = SBPDproject()               creates an empty SBPDproject 
+% [project] = SBPDproject(structure)      creates an SBPDproject from a MATLAB
+%                                         structure in the internal project format
+% [project] = SBPDproject(projectin)      construction from a given SBPDproject (projectin)
+% [project] = SBPDproject('file.sbp')     loading a binary SBPDproject
+%                                         stored in a MATLAB MAT file with .sbp as extension
+% [project] = SBPDproject('foldername')   converting a SBPD folder structure to an SBPDproject.
+%
+% Output Arguments:
+% =================
+% project: SBPDproject object 
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK THE TYPE OF THE INPUT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin==0,
+    inputType = 'empty';
+elseif nargin == 1,
+    input = varargin{1};
+    if isSBPDproject(input),
+        inputType = 'SBPDproject';
+    elseif isstruct(input),
+        inputType = 'structure';
+    elseif ischar(input),
+        if ~isempty(strfind(input,'.sbp')),
+            inputType = 'SBPfile';
+        else 
+            inputType = 'projectfolder';
+        end
+    else 
+        error('Input argument of unknown type');
+    end
+else
+    error('Wrong number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONSTRUCT THE SBPROJECT OBJECT 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp('empty',inputType),
+    % experiments substructure
+    experimentsStruct = struct('name',{},'notes',{},'experiment',{},'measurements',{});
+    % Create structure
+    structure = struct('name','unnamed project','notes','','models','','modeltypes','','experiments',experimentsStruct,'estimations','');
+    % construct the project object
+    project = class(structure,'SBPDproject');
+elseif strcmp('SBPDproject',inputType),
+    % copy the project object
+    project = input;
+elseif strcmp('structure',inputType),
+    % check if the given structure is a SBPDproject structure (only check the
+    % top-level fields)
+    checkFields = {'name','notes','models','experiments','estimations'};
+    for k = 1:length(checkFields),
+        if ~isfield(input,checkFields{k}),
+            errorMsg = sprintf('Given structure is not a valid internal SBPDproject structure.');
+            error(errorMsg);
+        end
+    end
+    % construct the project object
+    project = class(input,'SBPDproject');
+elseif strcmp('SBPfile',inputType),
+    % check if a file with given filename exists
+    [path,name,ext] = fileparts(input);
+    filename = fullfile(path, [name '.sbp']); 
+    if ~exist(filename),
+        errorMsg = sprintf('SBPDproject file, "%s", does not exist.', filename);
+        error(errorMsg);
+    end
+    % If file exists then import it
+    load(filename,'-MAT');
+    eval(sprintf('project = %s;',name));
+elseif strcmp('projectfolder',inputType),
+%     % Import a project folder to an SBPDproject
+%     % first check if the input variable corresponds to a folder in the
+%     % current directory
+%     if exist([pwd '/' input]) ~= 7,
+%         error('Projectfolder ''%s'' does not exist in the current directory.',input);
+%     end
+    project = importprojectfolderSBPD(input);
+else
+    error('Wrong input arguments.');
+end
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classes/@SBPDproject/SBPDsaveproject.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classes/@SBPDproject/SBPDsaveproject.m
new file mode 100644
index 0000000000000000000000000000000000000000..59c3e4c6eede8ed33bf1d17941680f5a72ba5421
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classes/@SBPDproject/SBPDsaveproject.m
@@ -0,0 +1,39 @@
+function [] = SBPDsaveproject(project,varargin)
+% SBPDsaveproject: save a SBPDproject object as a binary MATLAB MAT file
+% with .sbp as extension. The name of the project object variable is the same 
+% as the name of the file.
+%
+% USAGE:
+% ======
+% [] = SBPDsaveproject(project)        
+% [] = SBPDsaveproject(project,filename)        
+%
+% project:  SBPDproject object
+% filename: filename (.sbp is optional)
+%
+% DEFAULT VALUES:
+% ===============
+% filename: filename derived from project name
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 1,
+    filename = regexprep(project.name,'\W','');
+elseif nargin == 2,
+    filename = regexprep(regexprep(varargin{1},'.sbp',''),'\W','');
+else
+    error('Wrong number of input arguments.');
+end
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SAVE THE PROJECT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+eval(sprintf('%s = project;',filename));
+eval(sprintf('save %s.sbp %s -MAT',filename,filename));
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classes/@SBPDproject/SBPDstruct.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classes/@SBPDproject/SBPDstruct.m
new file mode 100644
index 0000000000000000000000000000000000000000..d0bc56f15076279265a55dfbee7f14943d9ed4e5
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classes/@SBPDproject/SBPDstruct.m
@@ -0,0 +1,25 @@
+function [structure] = SBPDstruct(project)
+% SBPDstruct: This function returns the internal data structure
+% of an SBPDproject
+%
+% USAGE:
+% ======
+% [structure] = SBPDstruct(SBPDproject) 
+%
+% SBPDproject: SBPDproject 
+%
+% Output Arguments:
+% =================
+% structure: internal data structure of the SBproject
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% VERY SIMPLE FUNCTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+structure = struct(project);
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classes/@SBPDproject/display.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classes/@SBPDproject/display.m
new file mode 100644
index 0000000000000000000000000000000000000000..f6d5a63383baec8957b17f4e5a0959f7bd47bea6
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classes/@SBPDproject/display.m
@@ -0,0 +1,28 @@
+function [] = display(project)
+% display: Displays information about SBPDproject. This function is 
+% called by MATLAB whenever an object is the result of a statement that
+% is not terminated by a semicolon. 
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% COLLECT INFORMATION ABOUT THE PROJECT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+numberModels = length(project.models);
+numberExperiments = length(project.experiments);
+numberMeasurements = length([project.experiments(1:end).measurements]);
+numberEstimations = length(project.estimations);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DISPLAY INFORMATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+text = sprintf('\tSBPDproject\n\t===========\n');
+text = sprintf('%s\tName: %s\n',text,project.name);
+text = sprintf('%s\tNumber Models:\t\t\t%d\n',text,numberModels);
+text = sprintf('%s\tNumber Experiments:\t\t%d\n',text,numberExperiments);
+text = sprintf('%s\tNumber Measurements:\t%d\n',text,numberMeasurements);
+text = sprintf('%s\tNumber Estimations:\t\t%d\n',text,numberEstimations);
+disp(text);
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classes/@SBPDproject/private/importprojectfolderSBPD.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classes/@SBPDproject/private/importprojectfolderSBPD.m
new file mode 100644
index 0000000000000000000000000000000000000000..cb2eae919e9b4afcc67d79ead3e437aa0ed29d66
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classes/@SBPDproject/private/importprojectfolderSBPD.m
@@ -0,0 +1,184 @@
+function [project] = importprojectfolderSBPD(folder)
+% importprojectfolderSBPD: imports a project folder to a SBPD project
+% object.
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+global useSBPDguiFlag
+if useSBPDguiFlag ~= 1,
+    useSBPDguiFlag = 0;
+end
+
+oldfolder = pwd(); % save starting folder
+cd(folder); % change into the project folder
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INITIALIZE EMPTY SBPDPROJECT OBJECT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+project = SBPDproject();
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ASSIGN NAME
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+project.name = folder;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% READ NOTES.TXT AND ASSIGN THEM
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try
+    notes = fileread([pwd,'/','notes.txt']);     
+catch
+    notes = '';
+end
+project.notes = notes;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHANGE INTO THE MODELS FOLDER AND LOAD MODELS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if exist([pwd,'/','models']) ~= 7,
+    cd(oldfolder);
+    error('No ''models'' folder is defined.');
+end
+cd('models');
+models = {};
+modeltypes = [];
+files = dir();
+% get files in model folder
+for k=1:length(files),
+    if ~files(k).isdir,
+        filename = files(k).name;
+        % check correct extensions (.txt, .txtbc, .xml)
+        [a,b,EXT] = fileparts(filename);
+        if strcmp(EXT,'.txt') || strcmp(EXT,'.txtbc') || strcmp(EXT,'.xml'),
+            try
+                % import models
+                models{end+1} = SBmodel(filename);
+                if strcmp(EXT,'.txt'),
+                    modeltypes(end+1) = 0;  % txt
+                else
+                    modeltypes(end+1) = 1;  % txtbc or SBML
+                end
+            catch
+                disp(sprintf('Warning: Error during model import: %s',lasterr));
+            end
+        end
+    end
+end
+if length(models) == 0,
+    disp(sprintf('Warning: No models defined in the project.'));
+end
+% add models to project
+project.models = models;
+project.modeltypes = modeltypes;
+% exit the models folder
+cd('..');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHANGE INTO THE EXPERIMENTS FOLDER AND LOAD EXPERIMENTS AND MEASUREMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if exist([pwd,'/','experiments']) ~= 7,
+    cd(oldfolder);
+    error('No ''experiments'' folder is defined.');
+end
+cd('experiments');
+files = dir();
+nrexperiments = 0;
+% get files in experiments folder and search for experiment folders
+if useSBPDguiFlag,
+    h = waitbar(0,'Importing project. Please wait...');
+end
+for k=1:length(files),
+    if useSBPDguiFlag,
+        waitbar(k/length(files),h)
+    end
+    if files(k).isdir,
+        % . and .. not useful
+        if ~strcmp(files(k).name(1),'.') && ~strcmp(files(k).name,'..'),        
+%        if ~strcmp(files(k).name,'.') && ~strcmp(files(k).name,'..'),
+            % change into the current folder
+            cd(files(k).name);
+            % load notes.txt file for the current experiment
+            try
+                notes = fileread([pwd,'/','notes.txt']);
+            catch
+                notes = '';
+            end
+            % load experiment file for the current experiment (required
+            % to be there and error if more than one present)
+            expfiles = dir('*.exp');
+            if length(expfiles) > 1,
+                cd(oldfolder);
+                error('Experiment folder ''%s'' contains more than one experiment description.',files(k).name);
+            end
+            if length(expfiles) == 0,
+                cd(oldfolder);
+                error('Experiment folder ''%s'' contains no experiment description.',files(k).name);
+            end
+            experiment = SBexperiment(expfiles(1).name);
+            % add experiment to project structure
+            nrexperiments = nrexperiments + 1;
+            project.experiments(nrexperiments).name = files(k).name;
+            project.experiments(nrexperiments).notes = notes;
+            project.experiments(nrexperiments).experiment = experiment;
+            % now check for measurements (they are not required to be there)
+            measurements = {};
+            allfiles = dir();
+            for k=1:length(allfiles),
+                if ~allfiles(k).isdir,
+                    filename = allfiles(k).name;
+                    % check correct extensions (.xls, .csv) (.xls only when not unix)
+                    [a,b,EXT] = fileparts(filename);
+                    if strcmp(EXT,'.csv') || (strcmp(EXT,'.xls') && ~isunix),
+                        try
+                            % import measurements
+                            meas = SBmeasurement(filename);
+                            if iscell(meas),
+                                measurements = {measurements{:} meas{:}};
+                            else
+                                measurements{end+1} = meas;
+                            end
+                        catch
+                            disp(sprintf('Warning: Error during measurement import: %s',lasterr));
+                        end
+                    end
+                end
+            end
+            project.experiments(nrexperiments).measurements = measurements;
+            % change out of the current folder
+            cd('..');
+        end
+    end
+end
+if useSBPDguiFlag,
+    close(h);
+end
+cd('..');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHANGE INTO THE ESTIMATIONS FOLDER AND LOAD ESTIMATIONS (OPTIONAL)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+estimations = {};
+if exist([pwd,'/','estimations']) == 7,
+    cd('estimations');
+    files = dir('*.est');
+    for k=1:length(files),
+        content = fileread(files(k).name);
+        try
+            eval(content)
+            estimations{end+1} = estimation;
+        catch
+            disp(sprintf('Syntax error in estimation ''%s''. Neglected from import.',files(k).name));
+        end
+    end
+end
+project.estimations = estimations;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% RETURN TO STARTING FOLDER
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+cd(oldfolder);
+            
+            
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDcomparemeasurements.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDcomparemeasurements.m
new file mode 100644
index 0000000000000000000000000000000000000000..d2db4f2512615e622cae733ad024ba8889406fbc
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDcomparemeasurements.m
@@ -0,0 +1,220 @@
+function [varargout] = SBPDcomparemeasurements(project,varargin)
+% SBPDcomparemeasurements: Simulates the experiments in the project for the
+% models in the project and compares the simulated results to the
+% measurements. 
+%
+% USAGE:
+% ======
+% [] = SBPDcomparemeasurements(project)        
+% [plotdata] = SBPDcomparemeasurements(project,modelindices)        
+% [plotdata] = SBPDcomparemeasurements(project,modelindices,experimentindices)        
+% [plotdata] = SBPDcomparemeasurements(project,modelindices,experimentindices,OPTIONS)        
+%
+% project:  SBPDproject object
+% modelindices: indices of the models in the project to use for comparison
+%   (scalar or vector)
+% experimentindices: vector with indices of the experiments to do the
+%   comparison for
+% OPTIONS: structure with integrator options.
+%        OPTIONS.abstol: abs tolerance
+%        OPTIONS.reltol: rel tolerance
+%        OPTIONS.minstep: min step-size of integrator
+%        OPTIONS.maxstep: max step-size of integrator
+%        OPTIONS.maxnumsteps: maximum number of steps to be
+%          taken by the solver in its attempt to reach the next
+%          output time 
+%   
+% DEFAULT VALUES:
+% ===============
+% modelindices: comparison carried out for all models in the project if
+%               modelindices is not given
+% experimentindices: all experiments in the project
+% OPTIONS.abstol: 1e-6
+% OPTIONS.reltol: 1e-6
+% OPTIONS.minstep: 0
+% OPTIONS.maxstep: inf
+% OPTIONS.maxnumsteps: 500
+%
+% Output Arguments:
+% =================
+% If no output argument is given, the function plots the data using
+% SBPDplot. Otherwise a datastructure (plotdata) is given back that can be
+% used as input argument for SBPDplot.
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input argument
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBPDproject(project),
+    error('Input argument is not an SBPDproject.');
+end
+projectstruct = SBPDstruct(project);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handling variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 1,
+    modelindex = [1:length(projectstruct.models)];
+    experimentindices = [1:length(projectstruct.experiments)];
+    OPTIONS = [];
+elseif nargin == 2,
+    modelindex = varargin{1};
+    experimentindices = [1:length(projectstruct.experiments)];
+    OPTIONS = [];
+elseif nargin == 3,
+    modelindex = varargin{1};
+    experimentindices = varargin{2};
+    OPTIONS = [];
+elseif nargin == 4,
+    modelindex = varargin{1};
+    experimentindices = varargin{2};
+    OPTIONS = varargin{3};
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK WHICH EXPERIMENTS DO NOT HAVE MEASUREMENT DATA ASSIGNED TO
+% THESE ARE SKIPPED FROM THE CONSIDERATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+text = '';
+useexperimentindices = [];
+
+for e=1:length(experimentindices),
+    if isempty(projectstruct.experiments(experimentindices(e)).measurements),
+        text = sprintf('%sExperiment %d has no measurements assigned to ... not considered here.\n',text,experimentindices(e));
+    else
+        useexperimentindices = [useexperimentindices experimentindices(e)];
+    end
+end
+if ~isempty(text),
+    disp(text);
+end
+if isempty(useexperimentindices),
+    error('No measurements in the selected experiments. No comparison possible.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET ALL MEASUREMENT INFORMATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+infostruct = [];
+for k=1:length(projectstruct.models(modelindex)),
+    model = projectstruct.models{modelindex(k)};
+    experiments = projectstruct.experiments(useexperimentindices);
+    displayFlag = 0;
+    expmeasinfo = getexpmeasinfoSBPD(model,modelindex(k),experiments,useexperimentindices,displayFlag);
+    infostruct(k).modelstruct = SBstruct(projectstruct.models{modelindex(k)});
+    infostruct(k).modelindex = modelindex(k);
+    infostruct(k).expinfostruct = expmeasinfo;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ADD SIMULATION DATA TO THE STRUCTURE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
+plotdata = [];
+plotdata.project = projectstruct.name;
+plotdata.notes = projectstruct.notes;
+plotdata.model = [];
+% run through all models
+for m=1:length(projectstruct.models(modelindex)),
+    % model data
+    modelstruct = infostruct(m).modelstruct;
+    plotdata.model(m).name = modelstruct.name;      
+    plotdata.model(m).notes = modelstruct.notes;
+    for e=1:length(infostruct(m).expinfostruct),
+        % experiment data
+        plotdata.model(m).experiment(e).name = infostruct(m).expinfostruct(e).experimentname;
+        timevector = infostruct(m).expinfostruct(e).timevector;
+        timestart = timevector(1);
+        timeend = timevector(end);
+        timevectorsim = [timestart:(timeend-timestart)/1000:timeend];
+        plotdata.model(m).experiment(e).timevector = timevectorsim;
+        expstatenames = infostruct(m).expinfostruct(e).statenames;          
+        expvariablenames = infostruct(m).expinfostruct(e).variablenames; 
+        plotdata.model(m).experiment(e).componentnames = {expstatenames{:} expvariablenames{:}};  
+        % simulate to get the state and variable values
+        mexmodel = infostruct(m).expinfostruct(e).model;
+        ic = infostruct(m).expinfostruct(e).initialconditions;
+        try 
+            simdata = feval(mexmodel,timevectorsim,ic,[],OPTIONS);
+            % collect all states and variables that are measured
+            stateindices = infostruct(m).expinfostruct(e).stateindices;
+            statevalues = simdata.statevalues(:,stateindices);
+            variableindices = infostruct(m).expinfostruct(e).variableindices;
+            variablevalues = simdata.variablevalues(:,variableindices);
+        catch
+            disp(lasterr)
+            statevalues = NaN(length(timevectorsim),length(expstatenames));
+            variablevalues = NaN(length(timevectorsim),length(expvariablenames));
+        end
+        % add simulated state trajectories
+        plotdata.model(m).experiment(e).componentvalues = [statevalues variablevalues];
+        for meas=1:length(infostruct(m).expinfostruct(e).measurement),
+            % measurement data
+            plotdata.model(m).experiment(e).measurement(meas).name = infostruct(m).expinfostruct(e).measurement(meas).name;
+            timevectormeas = timevector(infostruct(m).expinfostruct(e).measurement(meas).timevectorindices);
+            plotdata.model(m).experiment(e).measurement(meas).timevector = timevectormeas;
+            % reorder the measurements
+            measstatenames = infostruct(m).expinfostruct(e).measurement(meas).statenames;
+            measvariablenames = infostruct(m).expinfostruct(e).measurement(meas).variablenames;
+            % states 
+            for k=1:length(expstatenames),
+                index = strmatchSB(expstatenames{k},measstatenames,'exact');
+                if ~isempty(index),
+                    plotdata.model(m).experiment(e).measurement(meas).componentnames{k} = measstatenames{index};
+                    plotdata.model(m).experiment(e).measurement(meas).componentvalues(:,k) = infostruct(m).expinfostruct(e).measurement(meas).statereferences(:,index);
+                    plotdata.model(m).experiment(e).measurement(meas).maxvalues(:,k) = infostruct(m).expinfostruct(e).measurement(meas).statemaxvalues(:,index);
+                    plotdata.model(m).experiment(e).measurement(meas).minvalues(:,k) = infostruct(m).expinfostruct(e).measurement(meas).stateminvalues(:,index);
+                else
+                    plotdata.model(m).experiment(e).measurement(meas).componentnames{k} = 'not available';
+                    plotdata.model(m).experiment(e).measurement(meas).componentvalues(:,k) = NaN(length(timevectormeas),1);
+                    plotdata.model(m).experiment(e).measurement(meas).maxvalues(:,k) = NaN(length(timevectormeas),1);
+                    plotdata.model(m).experiment(e).measurement(meas).minvalues(:,k) = NaN(length(timevectormeas),1);
+                end                    
+            end
+            offset = length(expstatenames);
+            % variables
+            for k=1:length(expvariablenames),
+                index = strmatchSB(expvariablenames{k},measvariablenames,'exact');
+                if ~isempty(index),
+                    plotdata.model(m).experiment(e).measurement(meas).componentnames{offset+k} = measvariablenames{index};
+                    plotdata.model(m).experiment(e).measurement(meas).componentvalues(:,offset+k) = infostruct(m).expinfostruct(e).measurement(meas).variablereferences(:,index);
+                    plotdata.model(m).experiment(e).measurement(meas).maxvalues(:,offset+k) = infostruct(m).expinfostruct(e).measurement(meas).variablemaxvalues(:,index);
+                    plotdata.model(m).experiment(e).measurement(meas).minvalues(:,offset+k) = infostruct(m).expinfostruct(e).measurement(meas).variableminvalues(:,index);
+                else
+                    plotdata.model(m).experiment(e).measurement(meas).componentnames{offset+k} = 'not available';
+                    plotdata.model(m).experiment(e).measurement(meas).componentvalues(:,offset+k) = NaN(length(timevectormeas),1);
+                    plotdata.model(m).experiment(e).measurement(meas).maxvalues(:,offset+k) = NaN(length(timevectormeas),1);
+                    plotdata.model(m).experiment(e).measurement(meas).minvalues(:,offset+k) = NaN(length(timevectormeas),1);
+                end                    
+            end
+        end
+    end
+end        
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OUTPUT ARGUMENT OR PLOTTING
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargout == 0,
+    SBPDplot(plotdata);
+else
+    varargout{1} = plotdata;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DELETE MEX MODELS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+global compiledExpModelsSBPDgui % if not empty then models are precompiled and should not be deleted
+if isempty(compiledExpModelsSBPDgui),
+    clear mex
+    for m=1:length(infostruct),
+        for e=1:length(infostruct(m).expinfostruct),
+            delete(infostruct(m).expinfostruct(e).mexfullpath);
+        end
+    end
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDexportestimation.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDexportestimation.m
new file mode 100644
index 0000000000000000000000000000000000000000..1e62477dbc362c4dff03c1012a4cba4f6f65e78f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDexportestimation.m
@@ -0,0 +1,47 @@
+function SBPDexportestimation(project,estimationindex,filename)
+% SBPDexportestimation: Exports the selected estimation settings in an
+% SBPDproject into a flat text file.
+%
+% USAGE:
+% ======
+% SBPDexportestimation(project,estimationindex,filename)
+%
+% project: SBPDproject
+% estimationindex: the index of the estimation to export
+% filename: name of the file to write the estimation to (*.est)
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% BASIC CHECK OF THE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBPDproject(project),
+    error('Input argument ''project'' is not an SBPDproject.');
+end
+if ~ischar(filename),
+    error('Input argument ''filename'' is not a string.');
+end
+projectstruct = SBPDstruct(project);
+[dummy,filename] = fileparts(filename);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% BASIC CHECK OF THE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if estimationindex > length(projectstruct.estimations) || estimationindex < 1,
+    error('Estimation index out of bounds.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DO THE EXPORT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% convert estimation to text
+text = sprintf('%% Estimation Settings\n\nestimation = [];');
+text = getdatatextstructSBPD(projectstruct.estimations{estimationindex},'estimation',text);
+% write to file
+fid = fopen([filename '.est'],'w');
+fwrite(fid,text);
+fclose(fid);
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDgetexperiment.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDgetexperiment.m
new file mode 100644
index 0000000000000000000000000000000000000000..b317a056c050bf1290003314f3643a4a6f9fa5cb
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDgetexperiment.m
@@ -0,0 +1,59 @@
+function [experiments] = SBPDgetexperiment(project,varargin)
+% SBPDgetexperiment: get experiment(s) from the given project
+%
+% USAGE:
+% ======
+% [experiments] = SBPDgetexperiment(project)        
+% [experiments] = SBPDgetexperiment(project,experimentindices)        
+%
+% project:  SBPDproject object
+% experimentindices: index/indices of the experiment in project to return
+%                    (scalar index or vector of indices)
+%
+% Output Arguments:
+% =================
+% experiments: if no experimentindices are specified, all the experiments are
+%         returned. If more than one experiment is present in the project a
+%         cell-array of experiments is returned. If an experimentindices 
+%         (scalar index of vector of indices) argument is specified the
+%         corresponding experiment(s) will be returned. 
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input argument
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBPDproject(project),
+    error('Input argument is not an SBPDproject.');
+end
+project = SBPDstruct(project);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 1,
+    if length(project.experiments) == 1,
+        experiments = project.experiments(1).experiment;
+    else
+        experiments = {project.experiments.experiment};
+    end
+elseif nargin == 2,
+    if ~isnumeric(varargin{1}),
+        error('Wrong input argument ''experimentindices''.');
+    end
+    if ~isempty(find(varargin{1}>length(project.experiments))) || ~isempty(find(varargin{1} < 1)),
+        error('''experimentindices'' input argument is out of bounds.');
+    end
+    if length(varargin{1}) == 1,
+        experiments = project.experiments(varargin{1}).experiment;
+    else 
+        experiments = {project.experiments(varargin{1}).experiment};
+    end
+else
+    error('Incorrect number of input arguments.');
+end
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDgetmeasurement.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDgetmeasurement.m
new file mode 100644
index 0000000000000000000000000000000000000000..5480c0878c0cd7772b76eac67eb4e543052b8465
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDgetmeasurement.m
@@ -0,0 +1,70 @@
+function [measurements] = SBPDgetmeasurement(project,varargin)
+% SBPDgetmeasurement: get measurement(s) from the given project and
+% experiment.
+%
+% USAGE:
+% ======
+% [measurements] = SBPDgetmeasurement(project,experimentindex)        
+% [measurements] = SBPDgetmeasurement(project,experimentindex,measurementindices)        
+%
+% project:  SBPDproject object
+% experimentindex:    index of the experiment in the project for which to return
+%                     the measurements
+% measurementindices: index/indices of the measurement(s) in the specified
+%                     experiment return (scalar or vector of indices)
+%
+% Output Arguments:
+% =================
+% measurements: if no measurementindices are specified, all the measurements
+%         are returned. If more than one measurement is present in the
+%         projects experiment a cell-array of measurements is returned. If a
+%         measurementindices argument is specified the corresponding
+%         measurement(s) will be returned. 
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input argument
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBPDproject(project),
+    error('Input argument is not an SBPDproject.');
+end
+project = SBPDstruct(project);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin ~= 2 && nargin ~= 3,
+    error('Incorrect number of input arguments.');
+end
+if ~isnumeric(varargin{1}) || length(varargin{1}) ~= 1,
+    error('Incorrect ''experimentindex'' input argument.');
+end
+if varargin{1} > length(project.experiments) || varargin{1} < 1,
+    error('''experimentindex'' input argument is out of bounds.');
+end
+
+if nargin == 2,
+    measurements = project.experiments(varargin{1}).measurements;
+    if length(measurements) == 1,
+        measurements = measurements{1};
+    end
+elseif nargin == 3,
+    if ~isnumeric(varargin{2}),
+        error('Wrong input argument ''measurementindices''.');
+    end
+    if ~isempty(find(varargin{2}>length(project.experiments(varargin{1}).measurements))) || ~isempty(find(varargin{2} < 1)),
+        error('''measurementindices'' input argument is out of bounds.');
+    end
+    if length(varargin{2}) == 1,
+        measurements = project.experiments(varargin{1}).measurements{varargin{2}};
+    else 
+        measurements = {project.experiments(varargin{1}).measurements{varargin{2}}};
+    end
+else
+end
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDgetmodel.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDgetmodel.m
new file mode 100644
index 0000000000000000000000000000000000000000..2ca9da2d582c4e197aa4063236884f1023feca66
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDgetmodel.m
@@ -0,0 +1,61 @@
+function [models] = SBPDgetmodel(project,varargin)
+% SBPDgetmodel: get model(s) from the given project
+%
+% USAGE:
+% ======
+% [models] = SBPDgetmodel(project)        
+% [models] = SBPDgetmodel(project,modelindices)        
+%
+% project:  SBPDproject object
+% modelindices: indices of the model in project to return (scalar
+%               or vector of indices)
+%
+% Output Arguments:
+% =================
+% models: if no modelindices are specified, all the models are returned. If
+%         more than one model is present in the project a cell-array of
+%         models is returned. If a modelindices argument is specified the
+%         corresponding model(s) will be returned.
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input argument
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBPDproject(project),
+    error('Input argument is not an SBPDproject.');
+end
+project = SBPDstruct(project);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 1,
+    if length(project.models) == 1,
+        models = project.models{1};
+    else
+        models = project.models;
+    end
+elseif nargin == 2,
+    if ~isnumeric(varargin{1}),
+        error('Wrong input argument ''modelindices''.');
+    end
+    if ~isempty(find(varargin{1}>length(project.models))) || ~isempty(find(varargin{1} < 1)),
+        error('''modelindices'' input argument is out of bounds.');
+    end
+    if length(varargin{1}) == 1,
+        models = project.models{varargin{1}};
+    else 
+        models = {project.models{varargin{1}}};
+    end
+else
+    error('Incorrect number of input arguments.');
+end
+
+
+
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDinfo.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDinfo.m
new file mode 100644
index 0000000000000000000000000000000000000000..13dc08af9e44bc6adb3eb55a0f262aa2d7b6d604
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDinfo.m
@@ -0,0 +1,61 @@
+function [] = SBPDinfo(project)
+% SBPDinfo: quick dump of contents of an SBPDproject. Mainly used to check
+% if everything is correct and to determine the model, experiment, and
+% measurement indices.
+%
+% USAGE:
+% ======
+% [] = SBPDinfo(project)        
+%
+% project:  SBPDproject object
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input argument
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBPDproject(project),
+    error('Input argument is not an SBPDproject.');
+end
+project = SBPDstruct(project);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Collect information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+name = project.name;
+notes = project.notes;
+models = project.models;
+experiments = project.experiments;
+estimations = project.estimations;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Display information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+disp(' ');
+disp('===PROJECT INFO===============================================');
+disp(sprintf('Project name: %s',name));
+disp('---NOTES------------------------------------------------------');
+notes = double(notes); notes(find(notes==13)) = []; notes = char(notes);
+disp(sprintf('Project notes: %s',notes));
+disp('---MODELS-----------------------------------------------------');
+for k=1:length(models),
+    ms = SBstruct(models{k});
+    disp(sprintf('Model %d: %s',k,ms.name));
+end
+disp('---EXPERIMENTS------------------------------------------------');
+for k=1:length(experiments),
+    es = SBstruct(experiments(k).experiment);
+    disp(sprintf('Experiment %d: %s',k,es.name));
+    for k2=1:length(experiments(k).measurements),
+        ms = SBstruct(experiments(k).measurements{k2});
+        disp(sprintf('\tMeasurement %d: %s',k2,ms.name));
+    end
+end
+disp('---ESTIMATIONS------------------------------------------------');
+disp(sprintf('%d estimations present',length(estimations)));
+disp('==============================================================');
+disp(' ');
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDplotmeasurements.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDplotmeasurements.m
new file mode 100644
index 0000000000000000000000000000000000000000..ae57c131629e91d8a275b2bc77c05af93b6eed4a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDplotmeasurements.m
@@ -0,0 +1,72 @@
+function [] = SBPDplotmeasurements(project,varargin)
+% SBPDplotmeasurements: Plots all measurements in the given SBPDproject
+% using SBplot. Very useful to get a quick overview over measurement
+% results. The function opens a simple GUI where you in the upper left
+% corner can select the experiment and measurement to display. If error
+% bound information is available in the measurement data this is displayed.
+%
+% USAGE:
+% ======
+% [] = SBPDplotmeasurements(project)        
+% [] = SBPDplotmeasurements(project,experimentindices)        
+%
+% project:  SBPDproject object
+% experimentindices: vector with indices of the experiments for which to
+%   plot the measurement data. Per default the measurement data of all
+%   experiments is plotted.
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input argument
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBPDproject(project),
+    error('Input argument is not an SBPDproject.');
+end
+project = SBPDstruct(project);
+experiments = project.experiments;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+experimentindices = [1:length(experiments)];
+if nargin == 2,
+    experimentindices = varargin{1};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get all measurements from all experiments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+datastructures = {};
+for k=1:length(experimentindices),
+    es = SBstruct(experiments(experimentindices(k)).experiment);
+    for k2=1:length(experiments(experimentindices(k)).measurements),
+        % get SBplot datastructure for measurement
+        ds = SBvisualizemeasurement(experiments(experimentindices(k)).measurements{k2});
+        % update name of measurement in plotstructure
+        ds.name = sprintf('E%d: %s, M%d: %s',experimentindices(k),experiments(experimentindices(k)).name,k2,ds.name);
+        datastructures{end+1} = ds;
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Error if empty
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(datastructures),
+    error('The project does not contain any measurements.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Display using SBplot
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% construct call for SBplot
+plotcall = 'SBplot(';
+for k=1:length(datastructures),
+    plotcall = sprintf('%sdatastructures{%d},',plotcall,k);
+end
+plotcall = [plotcall(1:end-1) ');'];
+eval(plotcall);
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDupdateexperiment.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDupdateexperiment.m
new file mode 100644
index 0000000000000000000000000000000000000000..e4ab68178fa05e32e08e21c5d224c56510f079ef
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDupdateexperiment.m
@@ -0,0 +1,60 @@
+function [project] = SBPDupdateexperiment(project,experiment,varargin)
+% SBPDupdateexperiment: update or add a experiment in a project.  
+%
+% USAGE:
+% ======
+% [project] = SBPDupdateexperiment(project,experiment)
+% [project] = SBPDupdateexperiment(project,experiment,experimentindex)        
+%
+% project:         SBPDproject object
+% experiment:      SBexperiment which to update or add
+% experimentindex: index of the experiment to be updated. If omitted the experiment is
+%                  added to the project as last experiment.
+%
+% Output Arguments:
+% =================
+% project: updated project
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input argument
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBPDproject(project),
+    error('First input argument is not an SBPDproject.');
+end
+if ~isSBexperiment(experiment),
+    error('Second input argument is not an SBexperiment.');
+end
+projectstruct = SBPDstruct(project);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 2,
+    experimentindex = length(projectstruct.experiments)+1;
+elseif nargin == 3,
+    experimentindex = varargin{1};
+    if experimentindex < 1 || experimentindex > length(projectstruct.experiments),
+        error('''experimentindex'' out of bounds.');
+    end
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Adding/Updating the project
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+projectstruct.experiments(experimentindex).experiment = experiment;
+if isempty(projectstruct.experiments(experimentindex).name),
+    % use experiments name as name for the experiment in the project
+    % (otherwise empty if added experiments)
+    x = struct(experiment);
+    projectstruct.experiments(experimentindex).name = x.name;
+end
+project = SBPDproject(projectstruct);
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDupdatemeasurement.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDupdatemeasurement.m
new file mode 100644
index 0000000000000000000000000000000000000000..653bd13b1f0cddc53365301dee63c97ca64f6ec1
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDupdatemeasurement.m
@@ -0,0 +1,58 @@
+function [project] = SBPDupdatemeasurement(project,experimentindex,measurement,varargin)
+% SBPDupdatemeasurement: update or add a measurement in an experiment of a project.  
+%
+% USAGE:
+% ======
+% [project] = SBPDupdatemeasurement(project,experimentindex,measurement)
+% [project] = SBPDupdatemeasurement(project,experimentindex,measurement,measurementindex)
+%
+% project:          SBPDproject object
+% experimentindex:  index of the experiment to add the measurement to
+% measurement:      SBmeasurement which to update or add
+% measurementindex: index of the measurement to be updated. If omitted the measurment is
+%                   added to the experiment as last measurement.
+%
+% Output Arguments:
+% =================
+% project: updated project
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input argument
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBPDproject(project),
+    error('First input argument is not an SBPDproject.');
+end
+if ~isnumeric(experimentindex),
+    error('Second input argument is not an experiment index.');
+end
+if ~isSBmeasurement(measurement),
+    error('Third input argument is not an SBmeasurement.');
+end
+projectstruct = SBPDstruct(project);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 3,
+    measurementindex = length(projectstruct.experiments(experimentindex).measurements)+1;
+elseif nargin == 4,
+    measurementindex = varargin{1};
+    if measurementindex < 1 || measurementindex > length(projectstruct.experiments(experimentindex).measurements),
+        error('''measurementindex'' out of bounds.');
+    end
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Adding/Updating the project
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+projectstruct.experiments(experimentindex).measurements{measurementindex} = measurement;
+project = SBPDproject(projectstruct);
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDupdatemodel.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDupdatemodel.m
new file mode 100644
index 0000000000000000000000000000000000000000..85c7fb4f794549c6cc7377f23e0f07cc12295682
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/SBPDupdatemodel.m
@@ -0,0 +1,54 @@
+function [project] = SBPDupdatemodel(project,model,varargin)
+% SBPDupdatemodel: update or add a model in a project.  
+%
+% USAGE:
+% ======
+% [project] = SBPDupdatemodel(project,model)        
+% [project] = SBPDupdatemodel(project,model,modelindex)        
+%
+% project:  SBPDproject object
+% model:    SBmodel which to update or add
+% modelindex: index of the model to be updates. If omitted the model is
+%           added to the project as last model.
+%
+% Output Arguments:
+% =================
+% project: updated project
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input argument
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBPDproject(project),
+    error('First input argument is not an SBPDproject.');
+end
+if ~isSBmodel(model),
+    error('Second input argument is not an SBmodel.');
+end
+projectstruct = SBPDstruct(project);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 2,
+    modelindex = length(projectstruct.models)+1;
+elseif nargin == 3,
+    modelindex = varargin{1};
+    if modelindex < 1 || modelindex > length(projectstruct.models),
+        error('''modelindex'' out of bounds.');
+    end
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Adding/Updating the project
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+projectstruct.models{modelindex} = model;
+project = SBPDproject(projectstruct);
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/auxiliary/getexpmeasinfoSBPD.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/auxiliary/getexpmeasinfoSBPD.m
new file mode 100644
index 0000000000000000000000000000000000000000..82249b54bdbd19070d4547f6bf45d1d6a3843c9c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/auxiliary/getexpmeasinfoSBPD.m
@@ -0,0 +1,492 @@
+function [modexpmeasinfostruct] = getexpmeasinfoSBPD(model,modelindex,experiments,experimentindices,varargin)
+% getexpmeasinfoSBPD: creates a datastructure containing all information 
+% about experiments and measurements. This structure is, e.g., used in the
+% SBPDparameterestimation function. It generates temporary MEX models and
+% adds their names to the output structure. 
+%
+% USAGE:
+% ======
+% [output] = getexpmeasinfoSBPD(model,modelindex,experiments)        
+% [output] = getexpmeasinfoSBPD(model,modelindex,experiments,displayFlag,scalingFlag,timescalingFlag,initialconditionsFlag,weight)        
+%
+% model:        SBmodel 
+% modelindex:   index of the model in the project (only used if run from SBPDgui)
+% experiments:  'experiments' structure as in the SBPDproject structure
+%               (name and notes fields can be skipped)
+% experimentindices: index of the experiments in the project to be considered (only used if run from SBPDgui)
+% displayFlag:  0-2: silent, 3: display information about the different
+%               steps
+% scalingFlag:  Allows to choose which type of scaling is to be used (main
+%               use: for parameter estimation. Possible settings for this flag are
+%               explained in the help text of the SBPDparameterestimation function.
+% timescalingFlag:  0=no time scaling, 1...N=time scaling. For equidistantly
+%               sampled data this flag has no significance. For
+%               nonequidistantly sampled data the time scaling allows to
+%               give ranges of measurement data with scarce sampling more
+%               weight. With increasing N the time weighting is made
+%               smaller. N=1 results in maximum time weighting.
+% initialconditionsFlag: 0=use initial conditions stored in the model or
+%               experiments. 1=determine initialconditions from the
+%               measurement data (mean values of first time points). Note
+%               that the function takes into account if not there are
+%               differences in the components that have been measured.
+%               States for which no measurements exist are initialized
+%               using the values from the model or experiment.
+% weight:       cell array with vectors containing weights
+%               for the different measurements in the different experiments
+%
+% DEFAULT VALUES:
+% ===============
+% displayFlag: 0=silent
+% scalingFlag: scaling using mean values of the measured data
+% initialconditionsFlag: 1=initial conditions based on measurements
+% weight: {}
+%
+% Output Arguments:
+% =================
+% modexpmeasinfostruct: structure with following content
+%       .SBmodel                         SBmodel (model merged with experiment)
+%       .model                           compiled mex model (merged with experiment)
+%       .mexfullpath                     full path to mex model (useful for deleting if after use) 
+%       .experimentname                  name of the experiment
+%
+%       .measurement.name                name of the measurement
+%       .measurement.statenames          names of measured states  
+%       .measurement.stateindices        indices of measured states in model
+%       .measurement.statereferences     measurements of states
+%       .measurement.statemaxvalues      max errorbounds for measurement
+%       .measurement.stateminvalues      min errorbounds for measurement
+%       .measurement.statescaling        scaling for measured states
+%       .measurement.variablenames       names of measured variables  
+%       .measurement.variableindices     indices of measured variables in model
+%       .measurement.variablereferences  measurements of variables
+%       .measurement.variablemaxvalues   max errorbounds for measurement
+%       .measurement.variableminvalues   min errorbounds for measurement
+%       .measurement.variablescaling     scaling for measured variables
+%       .measurement.timescaling         vector for scaling over time
+%       .measurement.timevectorindices   indices in timevector to which the measurements belong
+%       .measurement.weight              weight to address different importances of measurements for the costfunction
+%
+%       .statenames                      names of all states that are measured in at least one measurement
+%       .stateindices                    indices of all states that are measured 
+%       .initialconditions               initial conditions for experiment simulation
+%       .variablenames                   names of all variables that are measured in at least one measurement
+%       .variableindices                 indices of all variables that are measured 
+%
+%       .timevector                      global timevector for experiment simulation
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GLOBAL VARIABLES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+global scalingFlag timescalingFlag displayFlag initialconditionsFlag
+
+global compiledExpModelsSBPDgui % if not empty then models are precompiled
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE NON-NUMERIC INITIAL CONDITIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% just by replacing them
+% + warning ... as user feedback
+if ~hasonlynumericICsSB(model),
+    model = SBconvertNonNum2NumIC(model);
+    disp('Warning: The model contains non-numeric initial conditions. For this analysis these are replaced');
+    disp('by numeric initial conditions, determined from the non-numeric ones.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+displayFlag = 0;
+scalingFlag = 0;
+timescalingFlag = 0;
+initialconditionsFlag = 1;
+weight = {};
+if nargin < 2 || nargin > 9,
+    error('Incorrect number of input arguments.');
+elseif nargin == 5,
+    displayFlag = varargin{1};
+elseif nargin == 6,
+    displayFlag = varargin{1};
+    scalingFlag = varargin{2};
+elseif nargin == 7,
+    displayFlag = varargin{1};
+    scalingFlag = varargin{2};
+    timescalingFlag = varargin{3};
+elseif nargin == 8,
+    displayFlag = varargin{1};
+    scalingFlag = varargin{2};
+    timescalingFlag = varargin{3};
+    initialconditionsFlag = varargin{4};
+elseif nargin == 9,
+    displayFlag = varargin{1};
+    scalingFlag = varargin{2};
+    timescalingFlag = varargin{3};
+    initialconditionsFlag = varargin{4};
+    weight = varargin{5};
+end    
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% MERGING MODELS AND EXPERIMENTS + MEX FILE GENERATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(compiledExpModelsSBPDgui),
+    % not precompiled ...
+    [modelexperiments,mexmodelexperiments,mexmodelfullpaths] = mergemodelwithexperiments(model,experiments);
+else
+    % precompiled by SBPDgui
+    [modelexperiments,mexmodelexperiments,mexmodelfullpaths] = getmodelwithexperiments(compiledExpModelsSBPDgui,modelindex,experimentindices);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESSING ALL INTO A STRUCTURE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modexpmeasinfostruct = getexpmeasinfostruct(modelexperiments,mexmodelexperiments,mexmodelfullpaths,experiments,weight);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% MERGING MODELS AND EXPERIMENTS + MEX FILE GENERATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [modelexperiments,mexmodelexperiments,mexmodelfullpaths] = mergemodelwithexperiments(model,experiments)
+global useSBPDguiFlag
+if useSBPDguiFlag ~= 1,
+    useSBPDguiFlag = 0;
+end
+modelexperiments = {};
+mexmodelexperiments = {};
+mexmodelfullpaths = {};
+if useSBPDguiFlag,
+    h = waitbar(0,'Compiling Models. Please wait...');
+end
+for k=1:length(experiments),
+    if useSBPDguiFlag,
+        waitbar(k/length(experiments),h)
+    end    
+    % merging
+    modelexperiments{k} = SBmergemodexp(model,experiments(k).experiment);
+    % compiling
+    [MEXmodel, MEXmodelfullpath] = makeTempMEXmodelSBPD(modelexperiments{k});
+    mexmodelexperiments{k} = MEXmodel;
+    mexmodelfullpaths{k} = MEXmodelfullpath;
+end
+if useSBPDguiFlag,
+    close(h);
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PRECOMPILED FROM SBPDgui ... get the info
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [modelexperiments,mexmodelexperiments,mexmodelfullpaths] = getmodelwithexperiments(compiledExpModelsSBPDgui,modelindex,experimentindices)
+modelexperiments = {};
+mexmodelexperiments = {};
+mexmodelfullpaths = {};
+for k=1:length(experimentindices),
+    modelexperiments{k} = compiledExpModelsSBPDgui(modelindex).experiment(experimentindices(k)).modexp;
+    mexmodelexperiments{k} = compiledExpModelsSBPDgui(modelindex).experiment(experimentindices(k)).MEXmodel;
+    mexmodelfullpaths{k} = compiledExpModelsSBPDgui(modelindex).experiment(experimentindices(k)).MEXmodelfullpath;
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESSING ALL INTO A STRUCTURE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [modexpmeasinfostruct] = getexpmeasinfostruct(modelexperiments,mexmodelexperiments,mexmodelfullpaths,experiments,weight)
+global displayFlag
+if displayFlag == 3,
+    disp('Building data structure with experiment and measurement information ...');
+    infomergmodexp()
+end
+% initialize structure
+modexpmeasinfostruct = [];      
+% fill stucture with data
+for k=1:length(experiments),
+    % MEXmodel
+    modexpmeasinfostruct(k).SBmodel = modelexperiments{k}; % SBmodel running the experiment
+    modexpmeasinfostruct(k).model = mexmodelexperiments{k}; % mex model running the experiment
+    modexpmeasinfostruct(k).mexfullpath = mexmodelfullpaths{k}; % mex model running the experiment
+    expstruct = SBstruct(experiments(k).experiment);
+    modexpmeasinfostruct(k).experimentname = expstruct.name;
+    % get all the states and variables in the current model+experiment
+    allmodelstates = SBstates(modelexperiments{k});
+    allmodelvariables = SBvariables(modelexperiments{k});
+    % 1) Getting the overall timevector to simulate for experiment
+    %    It is given by all measured timepoints in all measurements for that experiment
+    % 2) Check if the measured components are present in the
+    %    model (at the moment only states are allowed to be measured)
+    % 3) Get the stateindices and statereferences
+    % 4) Get the scaling for each measurment
+    % 5) Get the timevector for each measurement
+    % 6) Get the timescaling for each measurement
+    % 7) Get the indices of all states that have unknown initial conditions (not measured and not set in the experiment)
+    timevector = [];
+    allmeasstates = {};
+    allmeasvariables = {};
+    for k2=1:length(experiments(k).measurements),
+        % get the structure of the current measurement
+        measstruct = SBstruct(experiments(k).measurements{k2});
+        % name of measurement 
+        modexpmeasinfostruct(k).measurement(k2).name = measstruct.name;
+        % add measurement timepoints to timevector
+        timevectormeasurement = measstruct.time;
+        timevector = unique([timevector(:)' timevectormeasurement(:)']);
+        % process states in measurements
+        [statenames,stateindices,statereferences,statemaxvalues,stateminvalues] = processStateMeasurements(modelexperiments{k},measstruct);
+        % process variables in measurements
+        [variablenames,variableindices,variablereferences,variablemaxvalues,variableminvalues] = processVariableMeasurements(modelexperiments{k},measstruct);
+        % save statenames and variablenames appearing in all measurements
+        allmeasstates = unique({allmeasstates{:} statenames{:}});
+        allmeasvariables = unique({allmeasvariables{:} variablenames{:}});
+        % add state info to the structure
+        modexpmeasinfostruct(k).measurement(k2).statenames = statenames;
+        modexpmeasinfostruct(k).measurement(k2).stateindices = stateindices; 
+        modexpmeasinfostruct(k).measurement(k2).statereferences = statereferences;
+        modexpmeasinfostruct(k).measurement(k2).statemaxvalues = statemaxvalues;
+        modexpmeasinfostruct(k).measurement(k2).stateminvalues = stateminvalues;
+        modexpmeasinfostruct(k).measurement(k2).statescaling = getScaling(statereferences,statemaxvalues,stateminvalues);
+        % add variable info to the structure
+        modexpmeasinfostruct(k).measurement(k2).variablenames = variablenames;
+        modexpmeasinfostruct(k).measurement(k2).variableindices = variableindices; 
+        modexpmeasinfostruct(k).measurement(k2).variablereferences = variablereferences;
+        modexpmeasinfostruct(k).measurement(k2).variablemaxvalues = variablemaxvalues;
+        modexpmeasinfostruct(k).measurement(k2).variableminvalues = variableminvalues;
+        modexpmeasinfostruct(k).measurement(k2).variablescaling = getScaling(variablereferences,variablemaxvalues,variableminvalues);
+        if isempty(weight),
+            % set to 1 if weight not defined
+            modexpmeasinfostruct(k).measurement(k2).weight = 1;
+        else
+            % set the defined value
+            modexpmeasinfostruct(k).measurement(k2).weight = weight{k}(k2);
+        end
+    end
+    % add the sorted simulation timevector to the structure
+    modexpmeasinfostruct(k).timevector = sort(timevector);
+    % now we can determine the timevectorindices for each measurement and the timescaling
+    for k2=1:length(experiments(k).measurements),
+        % get the structure of the current measurement
+        measstruct = SBstruct(experiments(k).measurements{k2});
+        timevectormeasurement = measstruct.time;
+        [timevectormeas,timevectorindices] = intersect(modexpmeasinfostruct(k).timevector,timevectormeasurement);
+        modexpmeasinfostruct(k).measurement(k2).timevectorindices = timevectorindices;
+        timescaling = gettimescaling(timevectormeas);
+        modexpmeasinfostruct(k).measurement(k2).timescaling = timescaling;
+    end
+    % add names of all measured states to the structure
+    modexpmeasinfostruct(k).statenames = allmeasstates;
+    % determine the stateindices of the measured components in all the
+    % measurements of this experiment        
+    allstateindices = [];
+    for k2=1:length(allmeasstates),
+        index = strmatchSB(allmeasstates{k2},allmodelstates,'exact');
+        allstateindices = [allstateindices index];
+    end
+    modexpmeasinfostruct(k).stateindices = allstateindices;
+    % determine the initial conditions (take care of the fact that in
+    % different measurements different states might be measured)
+    % also take care of the initialconditionsFlag
+    modexpmeasinfostruct(k).initialconditions = processInitialconditions(modelexperiments{k},modexpmeasinfostruct(k));
+    % add names of all measured variables to the structure
+    modexpmeasinfostruct(k).variablenames = allmeasvariables;
+    % determine the variableindices of the measured components in all the
+    % measurements of this experiment        
+    allvariableindices = [];
+    for k2=1:length(allmeasvariables),
+        index = strmatchSB(allmeasvariables{k2},allmodelvariables,'exact');
+        allvariableindices = [allvariableindices index];
+    end
+    modexpmeasinfostruct(k).variableindices = allvariableindices;
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INFO MERGED MODEL EXP
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [] = infomergmodexp()
+global scalingFlag timescalingFlag initialconditionsFlag
+% intialconditions
+if initialconditionsFlag == 0,
+    disp(sprintf('\t ... nominal initialconditions from model and experiment'));
+elseif initialconditionsFlag == 1,
+    disp(sprintf('\t ... initialconditions taken from the measurements if present'));
+end
+% scaling
+if scalingFlag == 0,
+    disp(sprintf('\t ... no scaling of data'));
+elseif scalingFlag == 1,
+    disp(sprintf('\t ... scaling of data by max(abs(measurement))'));
+elseif scalingFlag == 2,
+    disp(sprintf('\t ... scaling of data by mean(measurement)'));
+elseif scalingFlag == 3,
+    disp(sprintf('\t ... scaling of data by the difference between max and min values'));
+end
+% timescaling
+if timescalingFlag == 0,
+    disp(sprintf('\t ... no time scaling'));
+elseif timescalingFlag == 1,
+    disp(sprintf('\t ... time scaling on'));
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE THE SCALING OF EACH MEASUREMENT IN EACH EXPERIMENT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [scaling] = getScaling(references,maxref,minref)
+global scalingFlag 
+if scalingFlag == 0,
+    % no scaling
+    scaling = ones(size(references));
+elseif scalingFlag == 1,
+    % scale by maxabs value of references
+    scaling = max(abs(references));
+    % expand to matrix with same column entries
+    scaling = scaling(ones(1,size(references,1)),:);
+elseif scalingFlag == 2,
+    % scale by mean value of references 
+    % take care of possible NaN (missing data) values
+    scaling = [];
+    for k=1:size(references,2),
+        data = references(:,k);
+        data(find(isnan(data))) = [];
+        if ~isempty(data),
+            scaling(k) = mean(data);
+        else
+            scaling(k) = 1;
+        end
+    end
+    % expand to matrix with same column entries
+    scaling = scaling(ones(1,size(references,1)),:);
+elseif scalingFlag == 3,
+    % scaling by the difference between max and min values
+    scaling = maxref-minref;
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE THE TIMESCALING OF EACH MEASUREMENT IN EACH EXPERIMENT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [timescaling] = gettimescaling(timevectormeas)
+global timescalingFlag
+if timescalingFlag == 0,
+    % no timescaling
+    timescaling = ones(length(timevectormeas),1);
+else
+    % augment timevector with two elements
+    timevectormeas = timevectormeas(:);
+    timehelp = [timevectormeas(1)-timevectormeas(2); timevectormeas; timevectormeas(end)+timevectormeas(end-1)];
+    % get the raw scaling
+    timescaleraw = (timehelp(3:end)-timehelp(1:end-2))/2;
+    timescaleraw = timescaleraw/min(timescaleraw);
+    timescaling = timescaleraw.^(1/timescalingFlag);
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE THE INITIAL CONDITIONS FOR EACH EXPERIMENT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [initialconditions] = processInitialconditions(modelexperiment,experiment)
+global initialconditionsFlag
+initialconditions = SBinitialconditions(modelexperiment);
+if initialconditionsFlag == 0,
+    % if flag==0 then just use the initialconditions defined by model and
+    % experiment description
+    return
+end
+% construct intialconditions from measured data at the first time point
+% do not use data if NaN!
+datapresent = zeros(1,length(SBstates(modelexperiment)));
+suminitialconditions = zeros(1,length(SBstates(modelexperiment)));
+for k=1:length(experiment.measurement),
+    stateindices = experiment.measurement(k).stateindices;
+    if ~isempty(stateindices),
+        measuredics = experiment.measurement(k).statereferences(1,:);
+        suminitialconditions(stateindices) = suminitialconditions(stateindices) + measuredics;
+        datapresent(stateindices) = datapresent(stateindices)+1;
+    end
+end
+% add ones to avoid division by zero
+divisionvector = datapresent;
+divisionvector(find(divisionvector==0)) = 1;
+definedinitialconditions = suminitialconditions./divisionvector;
+% handle NaN initial conditions (if measured but first time point
+% undefined) by just exchanging for the model/experiment definition.
+nanindices = find(isnan(definedinitialconditions));
+definedinitialconditions(nanindices) = initialconditions(nanindices);
+% insert the determined initial conditions into the initialconditions vector
+initialconditions(find(datapresent~=0)) = definedinitialconditions(find(datapresent~=0));
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECKING AND PROCESSING THE MEASUREMENTS (STATES)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [statenames,stateindices,statereferences,statemaxvalues,stateminvalues] = processStateMeasurements(modelexperiment, measstruct);
+global scalingFlag
+% get all states in the model with experiment    
+allmodelstates = SBstates(modelexperiment);
+measuredcomponentnames = {measstruct.data.name};
+% initialize
+statenames = {};
+stateindices = [];
+statereferences = [];
+statemaxvalues = [];
+stateminvalues = [];
+% get all the states from the measured components
+for k=1:length(measuredcomponentnames),
+    index = strmatchSB(measuredcomponentnames{k},allmodelstates,'exact');
+    if ~isempty(index),
+        % measured component is a state ... so get the data
+        statenames{end+1} = measuredcomponentnames{k};
+        stateindices = [stateindices index];
+        statereferences(:,end+1) = measstruct.data(k).values;
+        statemaxvalues(:,end+1) = measstruct.data(k).maxvalues;
+        stateminvalues(:,end+1) = measstruct.data(k).minvalues;
+        % check if NaN appears in min or max values ... if yes then the
+        % min/max scaling can not be used.
+        if sum(isnan(measstruct.data(k).maxvalues)) > 0 && scalingFlag == 3,
+            warning('Max values are not defined for all measurements. Min/max scaling (scalingFlag=3) might not be the right choice!');
+        end
+        if sum(isnan(measstruct.data(k).minvalues)) < 0 && scalingFlag == 3,
+            warning('Min values are not defined for all measurements. Min/max scaling (scalingFlag=3) might not be the right choice!');
+        end        
+    end
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECKING AND PROCESSING THE MEASUREMENTS (VARIABLES)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [variablenames,variableindices,variablereferences,variablemaxvalues,variableminvalues] = processVariableMeasurements(modelexperiment, measstruct);
+global scalingFlag
+% get all states in the model with experiment    
+allmodelvariables = SBvariables(modelexperiment);
+measuredcomponentnames = {measstruct.data.name};
+% initialize
+variablenames = {};
+variableindices = [];
+variablereferences = [];
+variablemaxvalues = [];
+variableminvalues = [];
+% get all the variables from the measured components
+for k=1:length(measuredcomponentnames),
+    index = strmatchSB(measuredcomponentnames{k},allmodelvariables,'exact');
+    if ~isempty(index),
+        % measured component is a variable ... so get the data
+        variablenames{end+1} = measuredcomponentnames{k};
+        variableindices = [variableindices index];
+        variablereferences(:,end+1) = measstruct.data(k).values;
+        variablemaxvalues(:,end+1) = measstruct.data(k).maxvalues;
+        variableminvalues(:,end+1) = measstruct.data(k).minvalues;
+        % check if NaN appears in min or max values ... if yes then the
+        % min/max scaling can not be used.
+        if sum(isnan(measstruct.data(k).maxvalues)) > 0 && scalingFlag == 3,
+            warning('Max values are not defined for all measurements. Min/max scaling (scalingFlag=3) might not be the right choice!');
+        end
+        if sum(isnan(measstruct.data(k).minvalues)) < 0 && scalingFlag == 3,
+            warning('Min values are not defined for all measurements. Min/max scaling (scalingFlag=3) might not be the right choice!');
+        end        
+    end
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/isSBPDproject.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/isSBPDproject.m
new file mode 100644
index 0000000000000000000000000000000000000000..4d681388d8bbfb549688a9c8791faadaf2f64d0c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/classeshandling/projecthandling/isSBPDproject.m
@@ -0,0 +1,10 @@
+function [output] = isSBPDproject(model)
+% isSBPDproject: check if input argument is an isSBPDproject.
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+output = strcmp(class(model),'SBPDproject');
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/SBPDgui.fig b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/SBPDgui.fig
new file mode 100644
index 0000000000000000000000000000000000000000..231337769e87a0de6a06cb8e2b20be3d76a62340
Binary files /dev/null and b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/SBPDgui.fig differ
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/SBPDgui.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/SBPDgui.m
new file mode 100644
index 0000000000000000000000000000000000000000..0c7d6f5b08f25029013f0bdcd9b9db4734010c35
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/SBPDgui.m
@@ -0,0 +1,2396 @@
+function varargout = SBPDgui(varargin)
+% SBPDgui: Graphical user-interface for running parameter estimation tasks.
+% More information you find in the "Help" menu of this GUI.
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% Begin initialization code - DO NOT EDIT
+gui_Singleton = 1;
+gui_State = struct('gui_Name',       mfilename, ...
+                   'gui_Singleton',  gui_Singleton, ...
+                   'gui_OpeningFcn', @SBPDgui_OpeningFcn, ...
+                   'gui_OutputFcn',  @SBPDgui_OutputFcn, ...
+                   'gui_LayoutFcn',  [] , ...
+                   'gui_Callback',   []);
+if nargin && ischar(varargin{1})
+    gui_State.gui_Callback = str2func(varargin{1});
+end
+if nargout
+    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
+else
+    gui_mainfcn(gui_State, varargin{:});
+end
+% End initialization code - DO NOT EDIT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OPENING FUNCTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function SBPDgui_OpeningFcn(hObject, eventdata, handles, varargin)
+academicWarningSBPD
+
+% display wait bars in different functions
+global useSBPDguiFlag
+useSBPDguiFlag = 1;
+
+handles.output = hObject;
+
+% start with an empty SBPDproject
+handles.UserData.project = SBPDproject();
+handles.UserData.empty = 1;
+
+% clear everything related to a project (results in empty project)
+handles = clearProject(hObject, eventdata, handles);
+
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OUTPUT FUNCTION (NOT USED but needs to be present)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function varargout = SBPDgui_OutputFcn(hObject, eventdata, handles) 
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXIT FUNCTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function Exit_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 0,
+    check = checkProjectOverwrite(handles);
+    if ~check,
+        return
+    end
+end
+% clear everything
+handles = clearProject(hObject, eventdata, handles);
+% reset waitbar display
+clear global useSBPDguiFlag
+% close the GUI
+closereq
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PRINT MENU CALLBACKS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function PrintMenu_Callback(hObject, eventdata, handles)
+print -depsc2 -r300
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HELP MENU CALLBACKS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function DocumentationMenu_Callback(hObject, eventdata, handles)
+old = pwd;
+cd([fileparts(which('SBPDgui')) '/documentation']);
+open('documentation.html');
+cd(old);
+return
+
+function AboutMenu_Callback(hObject, eventdata, handles)
+old = pwd;
+cd([fileparts(which('SBPDgui')) '/documentation']);
+open('about.html');
+cd(old);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ESTIMATION SETTINGS CALLBACK
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function handles = ApplyEstimationSettings_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    return
+end
+% get the estimation settings
+estindex = get(handles.listofestimations,'Value');
+% get number of estimations available
+nrest = length(get(handles.listofestimations,'String'));
+if estindex > nrest,
+    estindex = 1;
+end
+ps = struct(handles.UserData.project);
+% check if estimation settings present in the project
+if isempty(ps.estimations),
+    return
+end
+estimation = ps.estimations{estindex};
+% Apply the estimation settings
+handles.UserData.INTEGRATOROPTIONS = estimation.integrator.options;
+handles = applyEstimationSettings(handles,estimation);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% LEFT BUTTON CALLBACKS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Plot measurements
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function PlotMeasurements_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+project = handles.UserData.project;
+e = get(handles.listofexperiments,'Value');
+if isempty(e),
+    errordlg('No measurements in project.');
+    return
+end
+try
+    SBPDplotmeasurements(project,e);
+catch
+    errordlg(lasterr);
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Simulate single experiment
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function SimulateExperiment_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+clear mex % more robust like that!
+% get project structure
+ps = struct(handles.UserData.project);
+% check if models present
+if isempty(ps.models),
+    errordlg('No models present in project.');
+    return
+end
+% get index of selected model and the model
+m = get(handles.listofmodels,'Value');
+model = ps.models{m};
+% check selected experiment
+e = get(handles.listofexperiments,'Value');
+if length(e) ~= 1,
+    errordlg('You need to select a single experiment.');
+    return
+end
+% get experiment
+experiment = ps.experiments(e).experiment;
+% get simulation time
+time = str2num(get(handles.simEndTime,'String'));
+if isempty(time),
+    errordlg('Simulation end time (Te) needs to be a numeric value.');
+    return
+end
+if time <= 0,
+    errordlg('Simulation end time needs to be larger than zero.');
+    return
+end
+% do the simulation
+try
+    modexp = SBmergemodexp(model,experiment);
+    SBPDsimulate(modexp,time,[],{},[],handles.UserData.INTEGRATOROPTIONS);
+catch
+    errordlg(lasterr);
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Compare measurements
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function CompareMeasurements_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+clear mex % more robust like that!
+% get project structure
+project = handles.UserData.project;
+ps = struct(project);
+% check if models present
+if isempty(ps.models),
+    errordlg('No models present in project.');
+    return
+end
+% get index of selected model and the model
+m = get(handles.listofmodels,'Value');
+% check if experiments present
+e = get(handles.listofexperiments,'Value');
+if isempty(e),
+    errordlg('No experiments in project.');
+    return
+end
+try
+    SBPDcomparemeasurements(project,m,e,handles.UserData.INTEGRATOROPTIONS);
+catch
+    errordlg(lasterr);
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Manual tuning
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function ManualTuning_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+clear mex % more robust like that!
+% get estimation structure
+estimation = getEstimationStructure(handles);
+if isempty(estimation),
+    return
+end
+% Run manual tuning 
+try
+    handles.UserData.project = SBPDmanualtuning(handles.UserData.project,estimation);
+catch
+    errordlg(lasterr);
+end
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Identifiability analysis
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function Identifiability_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+clear mex % more robust like that!
+% get project structure
+project = handles.UserData.project;
+ps = struct(project);
+% check if models present
+if isempty(ps.models),
+    errordlg('No models present in project.');
+    return
+end
+% get index of selected model and the model
+m = get(handles.listofmodels,'Value');
+% get selected experiments
+e = get(handles.listofexperiments,'Value');
+if isempty(e),
+    errordlg('You need to select at least one experiment.');
+    return
+end
+% get estimation structure
+estimation = getEstimationStructure(handles);
+if isempty(estimation),
+    return
+end
+% get the options
+OPTIONS = [];
+OPTIONS.modelindex = m;
+OPTIONS.experimentindices = e;
+OPTIONS.integratoroptions = handles.UserData.INTEGRATOROPTIONS;
+% Run identifiability analysis 
+try
+    SBPDidentifiability(handles.UserData.project,estimation.parameters.names,OPTIONS);
+catch
+    errordlg(lasterr);
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% MIDDLE BUTTON CALLBACKS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INITIALIZING GLOBAL/LOCAL/IC FIELDS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function InitializeParamSettings_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+% get project structure
+project = handles.UserData.project;
+ps = struct(project);
+% check if models present
+if isempty(ps.models),
+    errordlg('No models present in project.');
+    return
+end
+% get index of selected model 
+m = get(handles.listofmodels,'Value');
+% get the factors for low and high bounds
+low = str2num(get(handles.lowbounds,'String'));
+high = str2num(get(handles.highbounds,'String'));
+% do checks
+if isempty(low),
+    errordlg('The lowbounds factor needs to be numeric and positive.');
+end
+if isempty(high),
+    errordlg('The highbounds factor needs to be numeric and positive.');
+end
+if low < 0 || high < 0 || low > high,
+    errordlg('The bounds factors need to be positive and ''low'' < ''high''.');
+end
+OPTIONS.lowbounds = low;
+OPTIONS.highbounds = high;
+try
+    output = getparamictextSBPD(project,m,OPTIONS);
+catch
+    errordlg(lasterr);
+end
+% set the information in the gui
+set(handles.globalparaminfo,'String',output.parametersText);
+set(handles.localparaminfo,'String','');
+set(handles.icinfo,'String',output.initialConditionsText);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% WRITE OUT GLOBAL/LOCAL/IC DATA
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function WriteOutParamSettings_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+% get project structure
+project = handles.UserData.project;
+ps = struct(project);
+% check if models present
+if isempty(ps.models),
+    errordlg('No models present in project.');
+    return
+end
+% get index of selected model 
+m = get(handles.listofmodels,'Value');
+% get the factors for low and high bounds
+low = str2num(get(handles.lowbounds,'String'));
+high = str2num(get(handles.highbounds,'String'));
+% do checks
+if isempty(low),
+    errordlg('The lowbounds factor needs to be numeric and positive.');
+end
+if isempty(high),
+    errordlg('The highbounds factor needs to be numeric and positive.');
+end
+if low < 0 || high < 0 || low > high,
+    errordlg('The bounds factors need to be positive and ''low'' < ''high''.');
+end
+OPTIONS.lowbounds = low;
+OPTIONS.highbounds = high;
+try
+    output = getparamictextSBPD(project,m,OPTIONS);
+catch
+    errordlg(lasterr);
+end
+% write out
+clc;
+disp('*****************************************************************');
+disp('* PARAMETER SETTINGS (COPY AND PASTE IN THE GUI AS YOU NEED IT) *');
+disp('*****************************************************************');
+disp(' Parameter name / lower bound / upper bound');
+disp(output.parametersText);
+disp(' ');
+disp('*****************************************************************');
+disp('* STATE IC SETTINGS (COPY AND PASTE IN THE GUI AS YOU NEED IT)  *');
+disp('*****************************************************************');
+disp(' State name / lower bound / upper bound');
+disp(output.initialConditionsText);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% RIGHT BUTTON CALLBACKS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OPTIMIZER OPTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function OptimizerOptions_Callback(hObject, eventdata, handles)
+% get the number of the selected optimizer
+optindex = get(handles.optimizerlist,'Value');
+% get the options
+optimizeroptions = handles.UserData.optimizeroptions{optindex};
+% call the options gui
+handles.UserData.optimizeroptions{optindex} = editoptionsGUI({optimizeroptions},'Optimizer Options');
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OPTIMIZER OPTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function IntegratorOptionsMenu_Callback(hObject, eventdata, handles)
+% get the integrator options
+options = handles.UserData.INTEGRATOROPTIONS;
+% make text out of it
+text = getdatatextstructSBPD(options,'OPTIONS',sprintf('%% CVODE Integrator Settings\n'));
+text = editoptionsGUI({text},'Integrator Options');
+OPTIONS = [];
+eval(text);
+handles.UserData.INTEGRATOROPTIONS = OPTIONS;
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run Estimation
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function RunEstimation_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+clear mex % more robust like that!
+% check if start or stop button
+text = get(handles.runestimation,'String');
+if strcmp(text,'Stop Estimation');
+    warning off;
+    global stopOptimization;
+    stopOptimization = 1;
+    warning on;
+    return
+end
+% get estimation structure
+estimation = getEstimationStructure(handles);
+if isempty(estimation),
+    return
+end
+% Run estimation
+try
+    handles = disableAllButtons(handles);
+    set(handles.runfitanalysis,'Enable','off');
+    set(handles.runestimation,'String','Stop Estimation');
+    set(handles.runestimation,'BackgroundColor',[1 0 0]);
+    output = SBPDparameterestimation(handles.UserData.project,estimation,1);
+    % get optimized project
+    handles.UserData.project = output.projectopt;
+catch
+    errordlg(lasterr);
+    disp('Please check that the parameters you selected are really parameters in the model.');
+    disp('Take into consideration that sometimes parameters in the model are changed to variables');
+    disp('by experimental settings. Then these parameters are not allowed to be estimated.');
+end
+set(handles.runestimation,'String','Run Estimation');
+set(handles.runestimation,'BackgroundColor',[0.027 0.729 0.396]);
+handles = enableAllButtons(handles);
+set(handles.runfitanalysis,'Enable','on');
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Residual Analysis
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function ResidualAnalysis_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+clear mex % more robust like that!
+% get estimation structure
+estimation = getEstimationStructure(handles);
+if isempty(estimation),
+    return
+end
+% Run residual analysis
+try
+    SBPDanalyzeresiduals(handles.UserData.project,estimation);
+catch
+    errordlg(lasterr);
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run Fit Analysis
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function RunFitAnalysis_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+clear mex % more robust like that!
+% check if start or stop button
+text = get(handles.runfitanalysis,'String');
+if strcmp(text,'Stop Fitanalysis');
+    warning off;
+    global stopOptimization;
+    stopOptimization = 1;
+    warning on;
+    return
+end
+% get estimation structure
+estimation = getEstimationStructure(handles);
+if isempty(estimation),
+    return
+end
+% get nrestimations
+nrestimations = str2num(get(handles.nrestimations,'String'));
+if isempty(nrestimations),
+    errordlg('#Estmations needs to be a numeric value.');
+    return
+end
+% get perttype
+perttype = str2num(get(handles.perttype,'String'));
+if isempty(perttype),
+    errordlg('Perttype needs to be a numeric value.');
+    return
+end
+% Run fitanalysis
+try
+    handles = disableAllButtons(handles);
+    set(handles.runestimation,'Enable','off');
+    set(handles.runfitanalysis,'String','Stop Fitanalysis');
+    set(handles.runfitanalysis,'BackgroundColor',[1 0 0]);
+    handles.UserData.estdata = SBPDparameterfitanalysis(handles.UserData.project,estimation,nrestimations,perttype,1);
+catch
+    errordlg(lasterr);
+end
+set(handles.runfitanalysis,'String','Run Fitanalysis');
+set(handles.runfitanalysis,'BackgroundColor',[0.027 0.729 0.396]);
+handles = enableAllButtons(handles);
+set(handles.runestimation,'Enable','on');
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Box Plot
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function BoxPlot_Callback(hObject, eventdata, handles)
+estdata = handles.UserData.estdata;
+if isempty(estdata),
+    errordlg('You need to first run the fit analysis.');
+    return
+end
+if estdata.nrestimations < 10,
+    errordlg('At least 10 estimation runs are required.');
+    return
+end
+SBPDfaboxplot(estdata);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Correlation
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function Correlation_Callback(hObject, eventdata, handles)
+estdata = handles.UserData.estdata;
+if isempty(estdata),
+    errordlg('You need to first run the fit analysis.');
+    return
+end
+if estdata.nrestimations < 10,
+    errordlg('At least 10 estimation runs are required.');
+    return
+end
+SBPDfacorr(estdata);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Pairwise Correlation
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function PairwiseCorrelation_Callback(hObject, eventdata, handles)
+estdata = handles.UserData.estdata;
+if isempty(estdata),
+    errordlg('You need to first run the fit analysis.');
+    return
+end
+if estdata.nrestimations < 10,
+    errordlg('At least 10 estimation runs are required.');
+    return
+end
+SBPDfadetcorr(estdata);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Histogram
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function Histogram_Callback(hObject, eventdata, handles)
+estdata = handles.UserData.estdata;
+if isempty(estdata),
+    errordlg('You need to first run the fit analysis.');
+    return
+end
+if estdata.nrestimations < 10,
+    errordlg('At least 10 estimation runs are required.');
+    return
+end
+SBPDfahist(estdata);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Clustering
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function Clustering_Callback(hObject, eventdata, handles)
+estdata = handles.UserData.estdata;
+if isempty(estdata),
+    errordlg('You need to first run the fit analysis.');
+    return
+end
+if estdata.nrestimations < 10,
+    errordlg('At least 10 estimation runs are required.');
+    return
+end
+SBPDfaclustering(estdata);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Significant Correlation
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function SignificantCorrelation_Callback(hObject, eventdata, handles)
+estdata = handles.UserData.estdata;
+if isempty(estdata),
+    errordlg('You need to first run the fit analysis.');
+    return
+end
+if estdata.nrestimations < 10,
+    errordlg('At least 10 estimation runs are required.');
+    return
+end
+SBPDfasigncorr(estdata);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Save Estimation Settings
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function handles = SaveEstimationSettings_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+% get the text
+text = get(handles.estimationsettingnotes,'String');
+% check if empty
+if isempty(strtrim(text)),
+    errordlg('Please enter at least a name for the estimation data.');
+    return
+end
+% get name and notes
+name = text(1,:);
+notes = text(2:end,:);
+name = strtrim(sprintf('%s',char([double(name)])'));
+notes = strtrim(sprintf('%s',char([double(notes) 10*ones(size(notes,1),1)])'));
+% get estimation structure
+estimation = getEstimationStructure(handles);
+if isempty(estimation),
+    return
+end
+% add name and notes
+estimation.name = name;
+estimation.notes = notes;
+% add estimation structure to the project
+ps = struct(handles.UserData.project);
+ps.estimations{end+1} = estimation;
+handles.UserData.project = SBPDproject(ps);
+% Update project information
+handles.UserData.donotchangeexperimentsFlag = 1;
+handles = UpdateProjectInformation(hObject, eventdata, handles);
+handles.UserData.donotchangeexperimentsFlag = 0;
+% set right value in estimation thing field
+nrest = length(get(handles.listofestimations,'String'));
+set(handles.listofestimations,'Value',nrest);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Update Estimation Settings
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function UpdateEstimationSettings_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+% get current estimation index
+estnames = get(handles.listofestimations,'String');
+if ~isempty(estnames),
+    estindex = get(handles.listofestimations,'Value');
+else 
+    estindex = 1;
+end
+% get the text
+text = get(handles.estimationsettingnotes,'String');
+% check if empty
+if isempty(strtrim(text)),
+    errordlg('Please enter at least a name for the estimation data.');
+    return
+end
+% get name and notes
+name = text(1,:);
+notes = text(2:end,:);
+name = strtrim(sprintf('%s',char([double(name)])'));
+notes = strtrim(sprintf('%s',char([double(notes) 10*ones(size(notes,1),1)])'));
+% get estimation structure
+estimation = getEstimationStructure(handles);
+if isempty(estimation),
+    return
+end
+% add name and notes
+estimation.name = name;
+estimation.notes = notes;
+% add estimation structure to the project
+ps = struct(handles.UserData.project);
+ps.estimations{estindex} = estimation;
+handles.UserData.project = SBPDproject(ps);
+% Update project information
+handles.UserData.donotchangeexperimentsFlag = 1;
+handles = UpdateProjectInformation(hObject, eventdata, handles);
+handles.UserData.donotchangeexperimentsFlag = 0;
+% set right value in estimation thing field
+set(handles.listofestimations,'Value',estindex);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Reset Project
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function ResetProject_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+% add estimations to the original project
+psO = struct(handles.UserData.projectOrig);
+ps = struct(handles.UserData.project);
+psO.estimations = ps.estimations;
+% save the old handles (for removing the old MEX models)
+handlesold = handles;
+handles.UserData.projectOrig = SBPDproject(psO);
+% reset it
+handles.UserData.project = handles.UserData.projectOrig;
+% set estimation index to 1
+set(handles.listofestimations,'Value',1);
+% update GUI
+handles = UpdateProjectInformation(hObject, eventdata, handles);
+% apply estimation settings
+handles.donotchangeParameters = 1;
+handles = ApplyEstimationSettings_Callback(hObject, eventdata, handles);
+handles.donotchangeParameters = 0;
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLING FILE MENU FUNCTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% LOAD PROJECT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function LoadProjectMenu_Callback(hObject, eventdata, handles)
+warning off;
+if handles.UserData.empty == 0,
+    check = checkProjectOverwrite(handles);
+    if ~check,
+        return
+    end
+end
+% clear the old project
+handles = clearProject(hObject, eventdata, handles);
+% get project file
+[filename, pathname] = uigetfile({'*.sbp', 'SBPDproject file (*.sbp)'},'Pick a project file to load');
+if filename == 0,
+    return
+end
+% load project
+try
+    project = SBPDproject([pathname filename]);
+    % add project to handles
+    handles.UserData.project = project;
+    % check and remove incorrect estimation settings
+    handles = checkEstimations(handles);    
+    % set original project
+    handles.UserData.projectOrig = project;
+    handles.UserData.empty = 0;
+catch
+    errordlg(lasterr);
+    return
+end
+% set default experiment weights
+handles.UserData.allExperimentWeights = ones(1,length(SBPDgetexperiment(project)));
+% update GUI
+handles = UpdateProjectInformation(hObject, eventdata, handles);
+% set estimation index to 1
+set(handles.listofestimations,'Value',1);
+% apply estimation settings
+handles = ApplyEstimationSettings_Callback(hObject, eventdata, handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% IMPORT PROJECT MENU 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function ImportProjectMenu_Callback(hObject, eventdata, handles)
+warning off;
+if handles.UserData.empty == 0,
+    check = checkProjectOverwrite(handles);
+    if ~check,
+        return
+    end
+end
+% clear the old project
+handles = clearProject(hObject, eventdata, handles);
+% get project folder name
+dirname = uigetdir('Pick an SBPDproject folder');
+if dirname == 0,
+    return
+end
+% load project
+try
+    project = SBPDproject(dirname);
+    % add project to handles
+    handles.UserData.project = project;
+    % check and remove incorrect estimation settings
+    handles = checkEstimations(handles);    
+    % set original project
+    handles.UserData.projectOrig = project;
+    handles.UserData.empty = 0;
+catch
+    disp(lasterr);
+    errordlg('An error occured. Please check output on console.');
+    return
+end
+% set default experiment weights
+handles.UserData.allExperimentWeights = ones(1,length(SBPDgetexperiment(project)));
+% update GUI
+handles = UpdateProjectInformation(hObject, eventdata, handles);
+% set estimation index to 1
+set(handles.listofestimations,'Value',1);
+% apply estimation settings
+handles = ApplyEstimationSettings_Callback(hObject, eventdata, handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function handles = checkEstimations(handles)
+% we want to check all estimation settings ... estimations with
+% modelindices that do not correspond to a model are deleted. 
+% models. 
+ps = struct(handles.UserData.project);
+nrmodels = length(ps.models);
+nrexperiments = length(ps.experiments);
+keepindices = [];
+for k=1:length(ps.estimations),
+    try
+        mi = ps.estimations{k}.modelindex;
+    catch
+        mi = 1;
+        ps.estimations{k}.modelindex = mi;
+    end
+    if ~(mi < 0 || mi > nrmodels),
+        keepindices(end+1) = k;
+    end
+end
+ps.estimations = ps.estimations(keepindices);
+% We also check experiment indices and if not fitting then we
+% delete them also
+keepindices = [];
+for k=1:length(ps.estimations),
+    try
+        ei = ps.estimations{k}.experiments.indices;
+        if length(ps.estimations{k}.experiments.weight) ~= length(ei),
+            ps.estimations{k}.experiments.weight = ones(1,length(ei));
+        end
+    catch
+        ei = [1:nrexperiments];
+        ps.estimations{k}.experiments.indices = ei;
+        ps.estimations{k}.experiments.weight = ones(1,length(ei));
+    end
+    if isempty([find(ei<0) find(ei>nrexperiments)]),
+        keepindices(end+1) = k;
+    end
+end
+ps.estimations = ps.estimations(keepindices);
+handles.UserData.project = SBPDproject(ps);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function handles = removeEstimations(handles,modelindex,experimentindex)
+ps = struct(handles.UserData.project);
+if ~isempty(modelindex),
+    keepindices = [];
+    % cycle trough the estimations and check in which estimations the
+    % modelindex appears => these are deleted.
+    for est=1:length(ps.estimations),
+        if ps.estimations{est}.modelindex < modelindex,
+            keepindices(end+1) = est;
+        elseif ps.estimations{est}.modelindex > modelindex,
+            keepindices(end+1) = est;
+            % also reduce the modelindices here by one (since one model
+            % deleted from the project)
+            ps.estimations{est}.modelindex = ps.estimations{est}.modelindex - 1;
+        else
+            % do nothing
+        end
+    end
+    % remove the estimations
+    ps.estimations = ps.estimations(keepindices);
+elseif ~isempty(experimentindex),
+    % cycle trough all estimations and check the experiment indices
+    % remove the given one, reduce the larger ones by one, check if
+    % experiments.indices is empty ... then remove the whole estimation
+    % setting
+    keepindices = [];
+    for est=1:length(ps.estimations),
+        ei = ps.estimations{est}.experiments.indices;
+        % find experimentindex in ei
+        ind = find(ei==experimentindex);
+        % remove entry from the vector
+        ei(ind) = [];
+        % remove the corresponding weights
+        ps.estimations{est}.experiments.weight(ind) = [];
+        % find elements in ei larger than experimentindex
+        larger = ei > experimentindex;
+        % decrease these elements by one
+        ei = ei - larger;
+        % check if ei is empty 
+        if ~isempty(ei),
+            keepindices(end+1) = est;
+        end
+        % update the structure
+        ps.estimations{est}.experiments.indices = ei;
+    end
+    % remove the estimations for which no experiments left in settings
+    ps.estimations = ps.estimations(keepindices);
+end
+% update the model and return
+handles.UserData.project = SBPDproject(ps);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SAVE PROJECT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function SaveProjectMenu_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+[filename, pathname] = uiputfile({'*.sbp', 'SBPDproject file (*.sbp)'}, 'Select a project file to write');
+if filename == 0,
+    return
+end
+% remove extension
+[dummy,projectfilename] = fileparts(filename);
+% save the project
+old = pwd;
+cd(pathname);
+SBPDsaveproject(handles.UserData.project,projectfilename);
+cd(old);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXPORT PROJECT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function ExportProjectMenu_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+foldername = uigetdir('Select a folder to export the SBPDproject folder to');
+if foldername == 0,
+    return
+end
+projectname = inputdlg('Please enter a name for the project','Project name',1);
+if isempty(projectname),
+    return
+end
+projectname = projectname{1};
+% check if folder exists
+old = pwd;
+cd(foldername);
+if exist(projectname) == 7,
+    answer = questdlg(sprintf('The project folder exists.\nDo you want to overwrite it?'), 'Question', 'YES', 'NO','NO');
+    if strcmp(answer,'NO'),
+        return;
+    end
+end
+SBPDexportproject(handles.UserData.project,projectname);
+cd(old);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SHOW AND EDIT PROJECT NOTES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function ShowEditProjectNotesMenu_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+% get the project notes
+ps = struct(handles.UserData.project);
+notes = {ps.notes};
+name = ps.name;
+ps.notes = notepadGUI(notes,sprintf('Notes for SBPDproject: %s',name));
+% update project
+handles.UserData.project = SBPDproject(ps);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CLEAR PROJECT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function ClearProjectMenu_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+check = checkProjectOverwrite(handles);
+if ~check,
+    return
+end
+handles = clearProject(hObject, eventdata, handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLING MODEL MENU FUNCTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add Model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function AddModelMenu_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+ps = struct(handles.UserData.project);
+% get model file
+[filename, pathname] = uigetfile({'*.txt;*.txtbc;*.xml', 'Model Files (*.txt,*.txtbc,*.xml)'},'Pick a model file to import');
+if filename == 0,
+    return
+end
+% load model
+try
+    model = SBmodel([pathname filename]);
+catch
+    errordlg(lasterr);
+    return
+end
+% append the model to the project
+ps.models{end+1} = model;
+% update project
+handles.UserData.project = SBPDproject(ps);
+% update GUI
+handles = UpdateProjectInformation(hObject, eventdata, handles);
+% set model index to the added one
+set(handles.listofmodels,'Value',length(ps.models));
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Edit Model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function EditModelMenu_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+ps = struct(handles.UserData.project);
+% check if models do exist (at least one must be present)
+if length(ps.models) < 1,
+    errordlg('No model to edit.');
+    return
+end
+% get the model
+m = get(handles.listofmodels,'Value');
+model = ps.models{m};
+modelold = model;
+% edit the model
+answer = questdlg('Select the format to edit the model in.', 'Question', 'TEXT Format', 'TEXTBC Format', 'TEXT Format');
+switch answer,
+    case 'TEXT Format',
+        model = SBedit(model);
+    case 'TEXTBC Format',
+        model = SBeditBC(model);
+    case '',
+        return
+end
+% add the model to project again
+ps.models{m} = model;
+% update project
+handles.UserData.project = SBPDproject(ps);
+% update GUI
+handles = UpdateProjectInformation(hObject, eventdata, handles);
+% set model index to the edited one
+set(handles.listofmodels,'Value',m);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Update Model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function UpdateModelMenu_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+ps = struct(handles.UserData.project);
+% check if models do exist (at least one must be present)
+if length(ps.models) < 1,
+    errordlg('No model to update.');
+    return
+end
+% get model file
+[filename, pathname] = uigetfile({'*.txt;*.txtbc;*.xml', 'Model Files (*.txt,*.txtbc,*.xml)'},'Pick a modelfile to import');
+if filename == 0,
+    return
+end
+% load model
+try
+    model = SBmodel([pathname filename]);
+catch
+    errordlg(lasterr);
+    return
+end
+% add the model to project again
+m = get(handles.listofmodels,'Value');
+modelold = ps.models{m};
+ps.models{m} = model;
+% update project
+handles.UserData.project = SBPDproject(ps);
+% update GUI
+handles = UpdateProjectInformation(hObject, eventdata, handles);
+% set model index to the edited one
+set(handles.listofmodels,'Value',m);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Delete Model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function DeleteModelMenu_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+ps = struct(handles.UserData.project);
+% check if models do exist (at least one must be present)
+if length(ps.models) <= 1,
+    errordlg('At least one model needs to be present in the project.');
+    return
+end
+% check if deletion desired
+output = checkYESNO('Delete the selected model?');
+if output == 0,
+    return
+end
+% get modelindex 
+mi = get(handles.listofmodels,'Value');
+% delete the model from the project
+keepindices = setdiff([1:length(ps.models)],mi);
+ps.models = ps.models(keepindices);
+% update project
+handles.UserData.project = SBPDproject(ps);
+% Finally also check the estimation settings and remove the estimations
+% that contain this model
+handles = removeEstimations(handles,mi,[]);
+% update GUI
+handles = UpdateProjectInformation(hObject, eventdata, handles);
+% set model index
+set(handles.listofmodels,'Value',1);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Export Model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function ExportModelMenu_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+ps = struct(handles.UserData.project);
+% check if models do exist (at least one must be present)
+if length(ps.models) < 1,
+    errordlg('No model in project that could be exported.');
+    return
+end
+% get the model
+model = ps.models{get(handles.listofmodels,'Value')};
+% get the type of export
+output = checkMODELTYPE('Select the format for the model export:');
+if output == 0,
+    return
+end
+switch output,
+    case '*.txt',
+        % get file name
+        [filename, pathname] = uiputfile({'*.txt','SBmodel TEXT description (*.txt)'},'Select a filename for the model');
+        if filename == 0,
+            return
+        end
+        % do the export
+        old = pwd;
+        cd(pathname);
+        [dummy,filename] = fileparts(filename);
+        SBcreateTEXTfile(model,filename);
+        cd(old);
+    case '*.txtbc',
+        % get file name
+        [filename, pathname] = uiputfile({'*.txtbc','SBmodel TEXTBC description (*.txtbc)'}, 'Select a filename for the model');
+        if filename == 0,
+            return
+        end
+        % do the export
+        old = pwd;
+        cd(pathname);
+        [dummy,filename] = fileparts(filename);
+        SBcreateTEXTBCfile(model,filename);
+        cd(old);
+    case '*.xml',
+        SBexportSBML(model);
+end
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% View Model 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function ViewModelMenu_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+ps = struct(handles.UserData.project);
+% get the model
+m = get(handles.listofmodels,'Value');
+model = ps.models{m};
+% view the model
+answer = questdlg('Select the format to view the model in.', 'Question', 'TEXT Format', 'TEXTBC Format', 'TEXT Format');
+switch answer,
+    case 'TEXT Format',
+        SBedit(model);
+    case 'TEXTBC Format',
+        SBeditBC(model);
+    case '',
+        return
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% View Model with Experiment
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function ViewModelExperiment_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+ps = struct(handles.UserData.project);
+% get the model
+m = get(handles.listofmodels,'Value');
+model = ps.models{m};
+% get the experiment
+e = get(handles.listofexperiments,'Value');
+if length(e) > 1,
+    errordlg('Please select a single experiment.');
+    return
+end
+experiment = ps.experiments(e).experiment;
+% combine model with experiment
+modexp = SBmergemodexp(model,experiment);
+% view the model
+answer = questdlg('Select the format to view the model with experiment changes in.', 'Question', 'TEXT Format', 'TEXTBC Format', 'TEXT Format');
+switch answer,
+    case 'TEXT Format',
+        SBedit(modexp);
+    case 'TEXTBC Format',
+        SBeditBC(modexp);
+    case '',
+        return
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Export Model with Experiment
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function ExportModelExperiment_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+ps = struct(handles.UserData.project);
+% get the model
+model = ps.models{get(handles.listofmodels,'Value')};
+% get the experiment
+e = get(handles.listofexperiments,'Value');
+if length(e) > 1,
+    errordlg('Please select a single experiment.');
+    return
+end
+experiment = ps.experiments(e).experiment;
+% combine model with experiment
+modexp = SBmergemodexp(model,experiment);
+% get the type of export
+output = checkMODELTYPE('Select the format for the model (with experiment changes) export:');
+if output == 0,
+    return
+end
+switch output,
+    case '*.txt',
+        % get file name
+        [filename, pathname] = uiputfile({'*.txt','SBmodel TEXT description (*.txt)'},'Select a filename for the model');
+        if filename == 0,
+            return
+        end
+        % do the export
+        old = pwd;
+        cd(pathname);
+        [dummy,filename] = fileparts(filename);
+        SBcreateTEXTfile(modexp,filename);
+        cd(old);
+    case '*.txtbc',
+        % get file name
+        [filename, pathname] = uiputfile({'*.txtbc','SBmodel TEXTBC description (*.txtbc)'}, 'Select a filename for the model');
+        if filename == 0,
+            return
+        end
+        % do the export
+        old = pwd;
+        cd(pathname);
+        [dummy,filename] = fileparts(filename);
+        SBcreateTEXTBCfile(modexp,filename);
+        cd(old);
+    case '*.xml',
+        SBexportSBML(modexp);
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLING EXPERIMENT MENU FUNCTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Edit Experiment
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function EditExperimentMenu_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+ps = struct(handles.UserData.project);
+% check if experiments do exist (at least one must be present)
+if length(ps.experiments) < 1,
+    errordlg('No experiment to edit.');
+    return
+end
+% check if only one experiment selected
+e = get(handles.listofexperiments,'Value');
+if length(e) > 1,
+    errordlg('Please select a single experiment for update.');
+    return
+end
+% get the experiment
+experiment = ps.experiments(e).experiment;
+% convert to text
+expTextStructure = convertExpToTextSB(experiment);
+exptext = setPartsToCompleteTextExpSB(expTextStructure);
+% edit the exptext using notepadGUI
+[exptext,flag] = notepadGUI({exptext},'Edit Experiment Description');
+if flag==0,
+    return
+end
+% convert exptext to SBexperiment
+[SBstructure,errorMsg] = convertTextToExpSB(exptext);
+if ~isempty(errorMsg),
+    errordlg(errorMsg);
+    return
+end
+experiment = SBexperiment(SBstructure);
+% add the model to project again
+experimentold = ps.experiments(e).experiment;
+ps.experiments(e).experiment = experiment;
+% update project
+handles.UserData.project = SBPDproject(ps);
+% update GUI
+handles = UpdateProjectInformation(hObject, eventdata, handles);
+% set experiment index to the edited one
+set(handles.listofexperiments,'Value',e);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% View Experiment
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function ViewExperimentMenu_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+ps = struct(handles.UserData.project);
+% check if only one experiment selected
+e = get(handles.listofexperiments,'Value');
+if length(e) > 1,
+    errordlg('Please select a single experiment for viewing.');
+    return
+end
+% get the experiment
+experiment = ps.experiments(e).experiment;
+% convert to text
+expTextStructure = convertExpToTextSB(experiment);
+exptext = setPartsToCompleteTextExpSB(expTextStructure);
+% edit the exptext using notepadGUI
+notepadGUI({exptext},'View Experiment Description',0);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Update Experiment
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function UpdateExperimentMenu_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+ps = struct(handles.UserData.project);
+% check if experiments do exist (at least one must be present)
+if length(ps.experiments) < 1,
+    errordlg('No experiment to update.');
+    return
+end
+% check if only one experiment selected
+e = get(handles.listofexperiments,'Value');
+if length(e) > 1,
+    errordlg('Please select a single experiment for update.');
+    return
+end
+% get experiment file
+[filename, pathname] = uigetfile({'*.exp', 'SBexperiment description (*.exp))'},'Pick an experiment file to import');
+if filename == 0,
+    return
+end
+% load experiment
+try
+    experiment = SBexperiment([pathname filename]);
+catch
+    errordlg(lasterr);
+    return
+end
+% add the experiment to project again
+experimentold = ps.experiments(e).experiment;
+ps.experiments(e).experiment = experiment;
+% update project
+handles.UserData.project = SBPDproject(ps);
+% update GUI
+handles = UpdateProjectInformation(hObject, eventdata, handles);
+% set model index to the edited one
+set(handles.listofexperiments,'Value',e);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Delete Experiment
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function DeleteExperimentMenu_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+ps = struct(handles.UserData.project);
+% check if experiments do exist (at least one must be present)
+if length(ps.experiments) <= 1,
+    errordlg('At least one experiment needs to be present in the project.');
+    return
+end
+% check if only one experiment selected
+e = get(handles.listofexperiments,'Value');
+if length(e) > 1,
+    errordlg('Please select a single experiment for deletion.');
+    return
+end
+% check if deletion desired
+output = checkYESNO('Delete the selected experiment?');
+if output == 0,
+    return
+end
+% delete the experiment from the project
+keepindices = setdiff([1:length(ps.experiments)],e);
+ps.experiments = ps.experiments(keepindices);
+% remove the saved experiment weight
+handles.UserData.allExperimentWeights(e) = [];
+% update project
+handles.UserData.project = SBPDproject(ps);
+% Finally also check the estimation settings and remove and change the
+% experiment indices from the estimations
+handles = removeEstimations(handles,[],e);
+% update GUI
+handles = UpdateProjectInformation(hObject, eventdata, handles);
+% set experiment index
+set(handles.listofexperiments,'Value',1);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Export Experiment
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function ExportExperimentMenu_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+ps = struct(handles.UserData.project);
+% check if experiments do exist (at least one must be present)
+if length(ps.experiments) < 1,
+    errordlg('No experiment in project that could be exported.');
+    return
+end
+% get experiment index
+e = get(handles.listofexperiments,'Value');
+% check that only one experiment
+if length(e) ~= 1,
+    errordlg('Please select only on experiment.');
+    return
+end
+% get the experiment
+experiment = ps.experiments(e).experiment;
+% get file name
+[filename, pathname] = uiputfile({'*.exp', 'SBexperiment description (*.exp))'}, 'Select a filename for the experiment');
+if filename == 0,
+    return
+end
+% do the export
+old = pwd;
+cd(pathname);
+[dummy,filename] = fileparts(filename);
+SBcreateEXPfile(experiment,filename);
+cd(old);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLING ESTIMATION MENU FUNCTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% VIEW ESTIMATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function ViewEstimationSettings_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+% get estimation index 
+est = get(handles.listofestimations,'Value');
+% get the estimation
+ps = struct(handles.UserData.project);
+estimation = ps.estimations{est};
+% convert estimation to text
+text = sprintf('%% Estimation Settings\n\nestimation = [];');
+text = getdatatextstructSBPD(estimation,'estimation',text);
+notepadGUI({text},'View Estimation Settings (MATLAB structure)',0);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Delete Estimation
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function DeleteEstimationMenu_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+ps = struct(handles.UserData.project);
+% check if estimations do exist 
+if isempty(ps.estimations),
+    errordlg('No estimation present in project.');
+    return
+end
+% check if deletion desired
+output = checkYESNO('Delete the selected estimation setting?');
+if output == 0,
+    return
+end
+% get estimation index 
+est = get(handles.listofestimations,'Value');
+% delete the estimation from the project
+keepindices = setdiff([1:length(ps.estimations)],est);
+ps.estimations = ps.estimations(keepindices);
+% update project
+handles.UserData.project = SBPDproject(ps);
+% update GUI
+handles = UpdateProjectInformation(hObject, eventdata, handles);
+% set estimation index
+set(handles.listofestimations,'Value',1);
+% apply estimation settings
+handles = ApplyEstimationSettings_Callback(hObject, eventdata, handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Delete All Estimations
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function DeleteAllEstimationsMenu_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+ps = struct(handles.UserData.project);
+% check if estimations do exist 
+if isempty(ps.estimations),
+    errordlg('No estimation present in project.');
+    return
+end
+% check if deletion desired
+output = checkYESNO('Delete ALL estimation setting?');
+if output == 0,
+    return
+end
+% remove all of them
+ps.estimations = {};
+% update project
+handles.UserData.project = SBPDproject(ps);
+% update GUI
+handles = UpdateProjectInformation(hObject, eventdata, handles);
+% set estimation index
+set(handles.listofestimations,'Value',1);
+% apply estimation settings
+handles = ApplyEstimationSettings_Callback(hObject, eventdata, handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXPORT ESTIMATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function ExportEstimationMenu_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+[filename, pathname] = uiputfile({'*.est', 'Estimation structure description (*.est))'}, 'Select estimation file to write');
+if filename == 0,
+    return
+end
+% remove extension
+[dummy,filename] = fileparts(filename);
+% get estimation index 
+est = get(handles.listofestimations,'Value');
+% save the estimation
+old = pwd;
+cd(pathname);
+SBPDexportestimation(handles.UserData.project,est,filename)
+cd(old);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLING OTHER MENU FUNCTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create Run Estimation Script
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function CreateRunEstimationScript_Callback(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    errordlg('No project loaded.');
+    return
+end
+ps = struct(handles.UserData.project);
+% check if model is present in project
+if isempty(ps.models),
+    errordlg('No models present in project.');
+    return
+end
+% check if experiments are present in project
+if isempty(ps.experiments),
+    errordlg('No experiments present in project.');
+    return
+end
+% select filename (.m)
+[filename, pathname] = uiputfile({'*.m', 'MATLAB m-file script (*.m)'}, 'Select file to write the script to');
+if filename == 0,
+    return
+end
+% remove extension
+[dummy,filename] = fileparts(filename);
+% get model index 
+m = get(handles.listofmodels,'Value');
+% construct the OPTIONS structure
+lowbounds = str2num(get(handles.lowbounds,'String')); 
+highbounds = str2num(get(handles.highbounds,'String'));
+if isempty(lowbounds),
+    lowbounds = 0.1;
+end
+if isempty(highbounds),
+    highbounds = 10;
+end
+OPTIONS = [];
+OPTIONS.lowbounds = lowbounds;
+OPTIONS.highbounds = highbounds;
+% create the file
+old = pwd;
+cd(pathname);
+createrunestimationscriptSBPD(handles.UserData.project,m,filename,OPTIONS)
+cd(old);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% AUXILIARY FUNCTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [output] = checkMODELTYPE(question)
+answer = questdlg(question, 'Question', 'TEXT (*.txt)', 'TEXTBC (*.txtbc)','SBML L2V1 (*.xml)','TEXT (*.txt)');
+switch answer,
+    case '',
+        output = 0;
+    case 'TEXT (*.txt)',
+        output = '*.txt';
+    case 'TEXTBC (*.txtbc)',
+        output = '*.txtbc';
+    case 'SBML L2V1 (*.xml)',
+        output = '*.xml';
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [output] = checkYESNO(question)
+output = 1;
+answer = questdlg(question, 'Question', 'YES', 'NO','NO');
+if strcmp(answer,'NO'),
+    output = 0;
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [output] = checkProjectOverwrite(handles)
+output = checkYESNO('Discard current project?');
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function handles = UpdateExperimentWeights(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    return
+end
+% get number of experiments in project
+experiments = SBPDgetexperiment(handles.UserData.project);
+nrexperiments = length(experiments);
+% check previous settings of the weights
+allWeights = handles.UserData.allExperimentWeights;
+if isempty(allWeights),
+    % set all to one if not defined otherwise
+    allWeights = ones(1,length(experiments));
+end
+if length(allWeights) < nrexperiments,
+    allWeights = [allWeights ones(1,nrexperiments-length(allWeights))];
+end
+if length(allWeights) > nrexperiments,
+    allWeights = allWeights(1:nrexperiments);
+end
+% get weights for the selected experiments
+indices = get(handles.listofexperiments,'Value');
+weights = allWeights(indices);
+% set weights in display
+text = sprintf('%g, ',weights);
+text = text(1:end-2);
+% add them to GUI
+set(handles.experimentweights,'String',text);
+% save allWeights if changed
+handles.UserData.allExperimentWeights = allWeights;
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function SetExperimentWeights(hObject, eventdata, handles)
+% get number of experiments in project
+experiments = SBPDgetexperiment(handles.UserData.project);
+nrexperiments = length(experiments);
+% get and check all weights
+allWeights = handles.UserData.allExperimentWeights;
+if isempty(allWeights),
+    % set all to one if not defined otherwise
+    allWeights = ones(1,length(experiments));
+end
+if length(allWeights) < nrexperiments,
+    warndlg(sprintf('Number of experiments exceeds number of weigths.\nThe weights are postpadded by ones.'));
+    allWeights = [allWeights ones(1,nrexperiments-allWeights)];
+end
+if length(allWeights) > nrexperiments,
+    warndlg(sprintf('Number of weights exceeds number of experiments.\nThe weights in excess are discarded.'));
+    allWeights = allWeights(1:nrexperiments);
+end
+% get indices and nr of currently selected experiments
+selectedindices = get(handles.listofexperiments,'Value');
+nrselectedexperiments = length(selectedindices);
+% now get the current weight settings and do some checks (need to fit to
+% currently nr of currently selected experiments
+try
+    setValues = eval(['[' get(handles.experimentweights,'String'), ']']);
+catch
+    warndlg('Incorrect weight setting.');
+end
+if length(setValues) > nrselectedexperiments,
+    warndlg(sprintf('Number of weights exceeds number of selected experiments.\nPlease correct that.'));
+    return
+end
+if length(setValues) < nrselectedexperiments,
+    warndlg(sprintf('Number of selected experiments exceeds number of weights.\nPlease correct that.'));
+    return
+end
+% Update all weights with the entered values
+allWeights(selectedindices) = setValues;
+handles.UserData.allExperimentWeights = allWeights;
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function handles = UpdateProjectInformation(hObject, eventdata, handles)
+if handles.UserData.empty == 1,
+    return
+end
+project = handles.UserData.project;
+ps = struct(project);
+% get model names
+models = ps.models;
+modelnames = {};
+for k=1:length(models),
+    ms = struct(models{k});
+    modelnames{end+1} = ms.name;
+end
+% get experiment names
+experimentnames = {};
+for k=1:length(ps.experiments),
+    es = struct(ps.experiments(k).experiment);
+    experimentnames{end+1} = es.name;
+end
+% get estimation names
+estimationnames = {};
+estimationnotes = {};
+for k=1:length(ps.estimations),
+    est = ps.estimations{k};
+    try
+        estimationnames{k} = sprintf('%d: %s',k,est.name);
+    catch
+        estimationnames{k} = sprintf('Estimation #%d',k);
+    end
+    try
+        estimationnotes{k} = est.notes;
+    catch
+        estimationnotes{k} = sprintf('No notes');
+    end
+end
+% set the info
+if handles.UserData.donotchangeexperimentsFlag ~= 1,
+    set(handles.listofmodels,'String',modelnames);
+    set(handles.listofexperiments,'String',experimentnames);
+    % select all experiments by default
+    set(handles.listofexperiments,'Value',[1:length(experimentnames)]);
+end
+% handle list of estimations
+if isempty(estimationnames),
+    InitializeParamSettings_Callback(hObject, eventdata, handles);
+    % make a default estimation setting
+    set(handles.estimationsettingnotes,'String',sprintf('default\nDefault estimation setting.'));
+    handles = SaveEstimationSettings_Callback(hObject, eventdata, handles);
+else 
+    set(handles.listofestimations,'String',estimationnames);
+    if get(handles.listofestimations,'Value') > length(estimationnames),
+        set(handles.listofestimations,'Value',1);
+    end
+end
+% update experiment weights
+handles = UpdateExperimentWeights(hObject, eventdata, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function estimation = getEstimationStructure(handles)
+estimation = [];
+% check if model and experiments in project
+project = handles.UserData.project;
+ps = struct(project);
+% check if models present
+if isempty(ps.models),
+    errordlg('No models present in project.');
+    return
+end
+% check if experiments in project
+if isempty(ps.experiments),
+    errordlg('No experiments present in project.');
+    return
+end
+% get estimation structure content
+% model, experiment, measurement related
+estimation.modelindex = get(handles.listofmodels,'Value');
+estimation.experiments.indices = get(handles.listofexperiments,'Value');
+estimation.experiments.measurementindices = {};
+estimation.experiments.weight = handles.UserData.allExperimentWeights(estimation.experiments.indices);
+estimation.experiments.measuremenweight = {};
+% parameter and initial condition related
+result = getParamInfo(handles);
+if isempty(result),
+    estimation = [];
+    return
+end
+estimation.parameters.names = result.paramnames;
+estimation.parameters.lowbounds = result.paramlow;
+estimation.parameters.highbounds = result.paramhigh;
+estimation.parameterslocal.names = result.paramlocalnames;
+estimation.parameterslocal.lowbounds = result.paramlocallow;
+estimation.parameterslocal.highbounds = result.paramlocalhigh;
+estimation.initialconditions.names = result.icnames;
+estimation.initialconditions.lowbounds = result.iclow;
+estimation.initialconditions.highbounds = result.ichigh;
+% options related
+estimation.optimization.method = handles.UserData.optimizernames{get(handles.optimizerlist,'Value')};
+OPTIONS = [];
+eval(handles.UserData.optimizeroptions{get(handles.optimizerlist,'Value')});
+estimation.optimization.options = OPTIONS;
+% integrator options
+estimation.integrator.options = handles.UserData.INTEGRATOROPTIONS;
+% flags
+estimation.initialconditionsFlag = get(handles.initialConditionsFlag,'Value')-1;
+estimation.displayFlag = get(handles.displayFlag,'Value')-1;
+estimation.scalingFlag = get(handles.scalingFlag,'Value')-1;
+estimation.timescalingFlag = get(handles.timeScalingFlag,'Value')-1;
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [result] = getParamInfo(handles)
+result = [];
+% get the three texts
+help = get(handles.globalparaminfo,'String');
+globalparaminfo = sprintf('%s',char([double(help) 10*ones(size(help,1),1)])');
+help = get(handles.localparaminfo,'String');
+localparaminfo = sprintf('%s',char([double(help) 10*ones(size(help,1),1)])');
+help = get(handles.icinfo,'String');
+icinfo = sprintf('%s',char([double(help) 10*ones(size(help,1),1)])');
+paramglobaltext = ['{' globalparaminfo '};'];
+paramlocaltext = ['{' localparaminfo '};'];
+ictext = ['{' icinfo '};'];
+% evaluate the texts
+try
+    paramglobal = eval(paramglobaltext);    
+catch
+    errordlg('Please check the definition of the global parameter settings.');
+    return
+end
+try
+    paramlocal = eval(paramlocaltext);
+catch
+    errordlg('Please check the definition of the local parameter settings.');
+    return
+end
+try
+    ic = eval(ictext);
+catch
+    errordlg('Please check the definition of the initial condition settings.');
+    return
+end
+% assign output variables
+if ~isempty(paramglobal),
+    try
+        result.paramnames = paramglobal(:,1);
+        result.paramlow = cell2mat(paramglobal(:,2));
+        result.paramhigh = cell2mat(paramglobal(:,3));
+    catch
+        errordlg('Please check the definition of the global parameter settings.');
+        result = [];
+        return
+    end
+else
+    errordlg('You need to define at least one global parameter to consider.');
+    result = [];
+    return
+end
+if ~isempty(paramlocal),
+    try
+        result.paramlocalnames = paramlocal(:,1);
+        result.paramlocallow = cell2mat(paramlocal(:,2));
+        result.paramlocalhigh = cell2mat(paramlocal(:,3));
+    catch
+        errordlg('Please check the definition of the local parameter settings.');
+        result = [];
+        return
+    end
+else
+    result.paramlocalnames = {};
+    result.paramlocallow = [];
+    result.paramlocalhigh = [];
+end
+if ~isempty(ic),
+    try
+        result.icnames = ic(:,1);
+        result.iclow = cell2mat(ic(:,2));
+        result.ichigh = cell2mat(ic(:,3));
+    catch
+        errordlg('Please check the definition of the initial condition settings.');
+        result = [];
+        return
+    end
+else
+    result.icnames = {};
+    result.iclow = [];
+    result.ichigh = [];
+end
+% check low < high
+if sum(result.paramlow > result.paramhigh) ~= 0,
+    errordlg('At least on high bound < low bound in global parameters.');
+    result = [];
+    return
+end
+if sum(result.paramlocallow > result.paramlocalhigh) ~= 0,
+    errordlg('At least on high bound < low bound in local parameters.');
+    result = [];
+    return
+end
+if sum(result.iclow > result.ichigh) ~= 0,
+    errordlg('At least on high bound < low bound in initial conditions.');
+    result = [];
+    return
+end
+% check that params really model parameters
+project = handles.UserData.project;
+ps = struct(project);
+m = get(handles.listofmodels,'Value');
+model = ps.models{m};
+try
+    dummy = SBparameters(model,result.paramnames);
+    dummy = SBparameters(model,result.paramlocalnames);
+    % check that ics really model states
+    dummy = SBinitialconditions(model,result.icnames);
+catch
+    errordlg(lasterr);
+    result = [];
+    return
+end
+% check that no double definition of local and global params
+intersection = intersect(result.paramnames,result.paramlocalnames);
+text = '';
+for k=1:length(intersection),
+    text = sprintf('%s%s,',text,intersection{k});
+end
+text = text(1:end-1);
+if ~isempty(intersection),
+	errordlg(sprintf('The following parameters are defined both as local and global:\n%s',text));
+    result = [];
+    return
+end
+% check elements appearing more than once
+if length(unique(result.paramnames)) ~= length(result.paramnames),
+    errordlg('Some global parameters appear more than once.');
+    result = [];
+    return
+end
+if length(unique(result.paramlocalnames)) ~= length(result.paramlocalnames),
+    errordlg('Some local parameters appear more than once.');
+    result = [];
+    return
+end
+if length(unique(result.icnames)) ~= length(result.icnames),
+    errordlg('Some initial conditions appear more than once.');
+    result = [];
+    return
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function handles = initializeEstimationOptions(handles)
+handles = setOptimizers(handles);
+handles = prepareOptimizerOptions(handles);
+% set flags
+% initial conditions flag
+String = {'0: use nominal model/experiment settings', '1: use averages from first time-point in measurements'};
+set(handles.initialConditionsFlag,'String',String);
+set(handles.initialConditionsFlag,'Value',2);
+% Scaling flag
+String = {'0: no scaling', '1: max values', '2: mean values', '3: (max-min) error bound sacaling'};
+set(handles.scalingFlag,'String',String);
+set(handles.scalingFlag,'Value',2);
+% Timescaling flag
+String = {'0: no timescaling', '1: strong timescaling', '2: less timescaling', '3: even less', '4: etc. ...', '5','6','7','8'};
+set(handles.timeScalingFlag,'String',String);
+set(handles.timeScalingFlag,'Value',1);
+% Display flag
+String = {'0: no messages', '1: final message', '2: iteration and final'};
+set(handles.displayFlag,'String',String);
+set(handles.displayFlag,'Value',3);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function handles = setOptimizers(handles)
+% find the available optimizers in the SBTOOLBOX2 (non academic)
+optimizersPath = [fileparts(which('installSB')) '/tools/optimization'];
+old = pwd;
+cd(optimizersPath);
+all = dir('*.m');
+cd(old);
+optimizerfunctions = {all.name};
+% find the available optimizers in the SBTOOLBOX2 (academic)
+optimizersPath = [fileparts(which('installSB')) '/_ACADEMIC/tools/optimization'];
+old = pwd;
+cd(optimizersPath);
+all = dir('*.m');
+cd(old);
+optimizerfunctionsACADEMIC = {all.name};
+% merge
+optimizerfunctions = [optimizerfunctions optimizerfunctionsACADEMIC];
+% swap first with simplexSB
+indexsimplex = strmatchSB('simplexSB',optimizerfunctions);
+help = optimizerfunctions{1};
+optimizerfunctions{1} = 'simplexSB.m';
+optimizerfunctions{indexsimplex} = help;
+% remove .m from the names
+for k=1:length(optimizerfunctions),
+    optimizerfunctions{k} = strrep(optimizerfunctions{k},'.m','');
+end
+optimizernames = {};
+optimizerdescription = {};
+% get description if existing
+for k=1:length(optimizerfunctions),
+    try
+        help = feval(optimizerfunctions{k});
+        isok = 1;
+    catch
+        isok = 0;
+    end
+    if isok,
+        try 
+            optimizernames{end+1} = optimizerfunctions{k};
+            optimizerdescription{end+1} = sprintf('%s: %s',optimizerfunctions{k},help.description);
+        catch
+            optimizernames{end+1} = optimizerfunctions{k};
+            optimizerdescription{end+1} = optimizerfunctions{k};
+        end
+    end
+end
+% set them into the pulldownmenu
+set(handles.optimizerlist,'String',optimizerdescription);
+% save the names of the optimizers to use them afterwards
+handles.UserData.optimizernames = optimizernames;
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function handles = prepareOptimizerOptions(handles)
+% get optimizernames
+optimizernames = handles.UserData.optimizernames;
+% build optimizer-specific options text
+optimizeroptions = {};
+for k=1:length(optimizernames),
+    text = '';
+    % get optimizer decriptions and default options
+    optinfo = feval(optimizernames{k});
+    % add name of optimizer
+    try 
+        text = sprintf('%s%% Optimizer: %s\n',text,optinfo.name); 
+    catch
+        text = sprintf('%s%% Optimizer: %s\n',text,optimizernames{k});         
+    end
+    % add description
+    try text = sprintf('%s%% %s\n\n',text,optinfo.description); catch, end
+    % add default settings
+    try
+        optnames = optinfo.defaultOptions.names;
+        optvalues = optinfo.defaultOptions.values;
+        optdescription = optinfo.defaultOptions.description;
+        for k2=1:length(optnames),
+            text = sprintf('%s%% %s:\nOPTIONS.%s = %s;\n',text,optdescription{k2},optnames{k2},optvalues{k2});
+        end
+    catch
+    end
+    % save the stuff
+    optimizeroptions{k} = text;
+end
+handles.UserData.optimizeroptions = optimizeroptions;
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function handles = disableAllButtons(handles)
+% disable all but the run estimation and run fit analysis button
+set(handles.plotmeasurements,'Enable','off');
+set(handles.simulatesingleexperiment,'Enable','off');
+set(handles.comparemeasurement,'Enable','off');
+set(handles.manualtuning,'Enable','off');
+set(handles.identifiabilityanalysis,'Enable','off');
+set(handles.optimizerOptions,'Enable','off');
+set(handles.InitializeParamSettings,'Enable','off');
+set(handles.writeout,'Enable','off');
+set(handles.residualanalysis,'Enable','off');
+set(handles.boxplot,'Enable','off');
+set(handles.clustering,'Enable','off');
+set(handles.correlation,'Enable','off');
+set(handles.histogram,'Enable','off');
+set(handles.pairwisecorrelation,'Enable','off');
+set(handles.significantcorrelation,'Enable','off');
+set(handles.updateestimationsettings,'Enable','off');
+set(handles.saveestimationsettings,'Enable','off');
+set(handles.resetproject,'Enable','off');
+set(handles.FileMenu,'Enable','off');
+set(handles.ModelMenu,'Enable','off');
+set(handles.ExperimentMenu,'Enable','off');
+set(handles.EstimationMenu,'Enable','off');
+set(handles.OtherMenu,'Enable','off');
+set(handles.HelpMenu,'Enable','off');
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function handles = enableAllButtons(handles)
+% disable all but the run estimation and run fit analysis button
+set(handles.plotmeasurements,'Enable','on');
+set(handles.simulatesingleexperiment,'Enable','on');
+set(handles.comparemeasurement,'Enable','on');
+set(handles.manualtuning,'Enable','on');
+set(handles.identifiabilityanalysis,'Enable','on');
+set(handles.optimizerOptions,'Enable','on');
+set(handles.InitializeParamSettings,'Enable','on');
+set(handles.writeout,'Enable','on');
+set(handles.residualanalysis,'Enable','on');
+set(handles.boxplot,'Enable','on');
+set(handles.clustering,'Enable','on');
+set(handles.correlation,'Enable','on');
+set(handles.histogram,'Enable','on');
+set(handles.pairwisecorrelation,'Enable','on');
+set(handles.significantcorrelation,'Enable','on');
+set(handles.updateestimationsettings,'Enable','on');
+set(handles.saveestimationsettings,'Enable','on');
+set(handles.resetproject,'Enable','on');
+set(handles.FileMenu,'Enable','on');
+set(handles.ModelMenu,'Enable','on');
+set(handles.ExperimentMenu,'Enable','on');
+set(handles.EstimationMenu,'Enable','on');
+set(handles.OtherMenu,'Enable','on');
+set(handles.HelpMenu,'Enable','on');
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function handles = applyEstimationSettings(handles,estimation)
+% name and notes
+try name = estimation.name; catch, name = 'untitled estimation'; end
+try notes = estimation.notes; catch, notes = 'no estimation notes'; end
+allnotestext = sprintf('%s\n%s',name,notes);
+set(handles.estimationsettingnotes,'String',allnotestext);
+% model index
+set(handles.listofmodels,'Value',estimation.modelindex);
+% experiment indices
+set(handles.listofexperiments,'Value',estimation.experiments.indices);
+% experiment weights
+text = sprintf('%g,',estimation.experiments.weight);
+set(handles.experimentweights,'String',text(1:end-1));
+if handles.donotchangeParameters == 0,
+    % global/local parameters + ics
+    pgn = estimation.parameters.names;
+    pglb = estimation.parameters.lowbounds;
+    pgub = estimation.parameters.highbounds;
+    pln = estimation.parameterslocal.names;
+    pllb = estimation.parameterslocal.lowbounds;
+    plub = estimation.parameterslocal.highbounds;
+    icn = estimation.initialconditions.names;
+    iclb = estimation.initialconditions.lowbounds;
+    icub = estimation.initialconditions.highbounds;
+    [ictext,paramtext,paramlocaltext] = helpparamictextSBPD(pgn,pglb,pgub,pln,pllb,plub,icn,iclb,icub);
+    set(handles.globalparaminfo,'String',paramtext);
+    set(handles.localparaminfo,'String',paramlocaltext);
+    set(handles.icinfo,'String',ictext);
+end
+% optimization method
+optindex = strmatchSB(estimation.optimization.method,handles.UserData.optimizernames,'exact');
+set(handles.optimizerlist,'Value',optindex);
+% optimization options
+optoptionstext = getoptimizeroptionstext(estimation.optimization.options,estimation.optimization.method);
+handles.UserData.optimizeroptions{optindex} = optoptionstext;
+% flags
+set(handles.initialConditionsFlag,'Value',estimation.initialconditionsFlag+1);
+set(handles.displayFlag,'Value',estimation.displayFlag+1);
+set(handles.scalingFlag,'Value',estimation.scalingFlag+1);
+set(handles.timeScalingFlag,'Value',estimation.timescalingFlag+1);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function text = getoptimizeroptionstext(options,method)
+text = '';
+% get optimizer decriptions and default options
+optinfo = feval(method);
+% add name of optimizer
+try
+    text0 = sprintf('%s%% Optimizer: %s\n',text,optinfo.name);
+catch
+    text0 = sprintf('%s%% Optimizer: %s\n',text,method);
+end
+% add description
+try text0 = sprintf('%s%% %s\n\nOPTIONS = [];',text0,optinfo.description); catch, end
+% parse the options structure and add to options text
+text = getdatatextstructSBPD(options,'OPTIONS',text0);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function text = getdatatextstruct(root,roottext)
+% converting given root level of a structure into text
+text = '';
+fn = fieldnames(root);
+for k=1:length(fn),
+    fv = getfield(root,fn{k});
+    if isnumeric(fv),
+        help = num2str(fv);
+        if length(fv) == 1,
+            text = sprintf('%s%s.%s = %s;\n',text,roottext,fn{k},help);
+        else
+            text = sprintf('%s%s.%s = [%s];\n',text,roottext,fn{k},help);
+        end
+    end
+    if ischar(fv),
+        text = sprintf('%s%s.%s = ''%s'';\n',text,roottext,fn{k},fv);
+    end
+    if iscell(fv),
+        help = '';
+        for k2 = 1:length(fv),
+            if ischar(fv{k2}),
+                help2 = ['''' fv{k2} ''''];
+            elseif isnumeric(fv{k2}),
+                help2 = num2str(fv{k2});
+            else
+                help2 = '';
+            end
+            help = sprintf('%s%s,',help,help2);
+        end
+        text = sprintf('%s%s.%s = {%s};\n',text,roottext,fn{k},help(1:end-1));
+    end
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function handles = clearProject(hObject, eventdata, handles)
+% remove other things
+handles.UserData = [];
+handles.UserData.projectOrig = SBPDproject();  % empty project
+handles.UserData.project = SBPDproject();      % empty project
+handles.UserData.allExperimentWeights = [];
+handles.UserData.estdata = [];
+handles.UserData.donotchangeexperimentsFlag = 0;
+handles.UserData.empty = 1;
+handles.donotchangeParameters = 0;
+% intergrator options
+handles.UserData.INTEGRATOROPTIONS = [];
+handles.UserData.INTEGRATOROPTIONS.abstol = 1e-6;
+handles.UserData.INTEGRATOROPTIONS.reltol = 1e-6;
+handles.UserData.INTEGRATOROPTIONS.minstep = 0;
+handles.UserData.INTEGRATOROPTIONS.maxstep = inf;
+handles.UserData.INTEGRATOROPTIONS.maxnumsteps = 1000;
+% clear GUI
+set(handles.experimentweights,'String',' ');
+set(handles.globalparaminfo,'String','');
+set(handles.localparaminfo,'String','');
+set(handles.icinfo,'String','');
+set(handles.estimationsettingnotes,'String','');
+% initialize right hand options for estimation
+handles = initializeEstimationOptions(handles);
+set(handles.listofestimations,'String',' '); % intentionally a space
+set(handles.listofmodels,'String',' '); % intentionally a space
+set(handles.listofexperiments,'String',' '); % intentionally a space
+set(handles.listofestimations,'Value',1); 
+set(handles.listofmodels,'Value',1); 
+set(handles.listofexperiments,'Value',1); 
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/auxiliary/editoptionsGUI.fig b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/auxiliary/editoptionsGUI.fig
new file mode 100644
index 0000000000000000000000000000000000000000..bf633a437b2f35c1124cd9d1e3a16cf46eb9fb3f
Binary files /dev/null and b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/auxiliary/editoptionsGUI.fig differ
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/auxiliary/editoptionsGUI.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/auxiliary/editoptionsGUI.m
new file mode 100644
index 0000000000000000000000000000000000000000..f28d5262b9cb97e475fccc333870217f5382a88c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/auxiliary/editoptionsGUI.m
@@ -0,0 +1,102 @@
+function varargout = editoptionsGUI(varargin)
+% Just takes some options text and allows to modify it.
+
+% Begin initialization code - DO NOT EDIT
+gui_Singleton = 1;
+gui_State = struct('gui_Name',       mfilename, ...
+                   'gui_Singleton',  gui_Singleton, ...
+                   'gui_OpeningFcn', @editoptionsGUI_OpeningFcn, ...
+                   'gui_OutputFcn',  @editoptionsGUI_OutputFcn, ...
+                   'gui_LayoutFcn',  [] , ...
+                   'gui_Callback',   []);
+if nargin && ischar(varargin{1})
+    gui_State.gui_Callback = str2func(varargin{1});
+end
+
+if nargout
+    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
+else
+    gui_mainfcn(gui_State, varargin{:});
+end
+% End initialization code - DO NOT EDIT
+
+% --- Executes just before editoptionsGUI is made visible.
+function editoptionsGUI_OpeningFcn(hObject, eventdata, handles, varargin)
+handles.output = hObject;
+% get the input argument and display it
+help = varargin{1};
+handles.UserData.optionstext = help{1};
+header = varargin{2};
+set(handles.optionstextEdit,'String',handles.UserData.optionstext);
+set(handles.header,'String',header);
+% Update handles structure
+guidata(hObject, handles);
+% wait for action
+uiwait(handles.figure1)
+return
+
+% --- Outputs from this function are returned to the command line.
+function varargout = editoptionsGUI_OutputFcn(hObject, eventdata, handles) 
+varargout{1} = handles.output;
+% close the GUI
+delete(hObject);
+return
+
+% --- Executes on button press in okbutton.
+function okbutton_Callback(hObject, eventdata, handles)
+% get the text
+text = get(handles.optionstextEdit,'String');
+% convert it to a normal string
+text = sprintf('%s',char([double(text) 10*ones(size(text,1),1)])');
+% evaluate it to see if it leads to an error
+OPTIONS = [];
+try 
+    texttest = strrep(text,sprintf('\n'),sprintf(';\n'));
+    eval(texttest); 
+catch
+    errordlg('Syntax error in the options definition.');
+    return
+end
+% otherwise update options text
+handles.output = text;
+% Update handles structure
+guidata(hObject, handles);
+% Resume
+uiresume(handles.figure1);
+return
+
+% --- Executes on button press in cancelbutton.
+function cancelbutton_Callback(hObject, eventdata, handles)
+handles.output = handles.UserData.optionstext;
+% Update handles structure
+guidata(hObject, handles);
+% Resume
+uiresume(handles.figure1);
+return
+
+
+
+
+
+function optionstextEdit_Callback(hObject, eventdata, handles)
+% hObject    handle to optionstextEdit (see GCBO)
+% eventdata  reserved - to be defined in a future version of MATLAB
+% handles    structure with handles and user data (see GUIDATA)
+
+% Hints: get(hObject,'String') returns contents of optionstextEdit as text
+%        str2double(get(hObject,'String')) returns contents of optionstextEdit as a double
+
+
+% --- Executes during object creation, after setting all properties.
+function optionstextEdit_CreateFcn(hObject, eventdata, handles)
+% hObject    handle to optionstextEdit (see GCBO)
+% eventdata  reserved - to be defined in a future version of MATLAB
+% handles    empty - handles not created until after all CreateFcns called
+
+% Hint: edit controls usually have a white background on Windows.
+%       See ISPC and COMPUTER.
+if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
+    set(hObject,'BackgroundColor','white');
+end
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/auxiliary/notepadGUI.fig b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/auxiliary/notepadGUI.fig
new file mode 100644
index 0000000000000000000000000000000000000000..e09f639386eb1e6413ec7129e892758d52a9e88d
Binary files /dev/null and b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/auxiliary/notepadGUI.fig differ
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/auxiliary/notepadGUI.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/auxiliary/notepadGUI.m
new file mode 100644
index 0000000000000000000000000000000000000000..4cd6846e58f145545146d6734fbd97b857fb3408
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/auxiliary/notepadGUI.m
@@ -0,0 +1,91 @@
+function varargout = notepadGUI(varargin)
+% Just takes some text and allows to modify it. Takes two input 
+% arguments. The first is the text to display and modify, the second
+% is the headline
+
+% Begin initialization code - DO NOT EDIT
+gui_Singleton = 1;
+gui_State = struct('gui_Name',       mfilename, ...
+                   'gui_Singleton',  gui_Singleton, ...
+                   'gui_OpeningFcn', @notepadGUI_OpeningFcn, ...
+                   'gui_OutputFcn',  @notepadGUI_OutputFcn, ...
+                   'gui_LayoutFcn',  [] , ...
+                   'gui_Callback',   []);
+if nargin && ischar(varargin{1})
+    gui_State.gui_Callback = str2func(varargin{1});
+end
+
+if nargout
+    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
+else
+    gui_mainfcn(gui_State, varargin{:});
+end
+% End initialization code - DO NOT EDIT
+
+% --- Executes just before notepadGUI is made visible.
+function notepadGUI_OpeningFcn(hObject, eventdata, handles, varargin)
+notestext = 'No Text';
+header = 'No Header';
+edit = 1;
+if nargin >= 4,
+    notestext = varargin{1};
+    notestext = notestext{1};
+end
+if nargin >= 5,
+    header = varargin{2};
+end
+if nargin >= 6,
+    edit = varargin{3};
+end
+if nargin > 7,
+    error('Incorrect number of input arguments.');
+end
+handles.output = notestext;
+% assign inputs
+handles.UserData.notestext = notestext;
+set(handles.notestextEdit,'String',handles.UserData.notestext);
+set(handles.header,'String',header);
+% check if edit or view
+if edit == 0,
+    set(handles.savechanges,'Visible','off');
+end
+% Update handles structure
+guidata(hObject, handles);
+% wait for action
+uiwait(handles.figure1)
+return
+
+% --- Outputs from this function are returned to the command line.
+function varargout = notepadGUI_OutputFcn(hObject, eventdata, handles) 
+varargout{1} = handles.output;
+varargout{2} = handles.output2;
+% close the GUI
+delete(hObject);
+return
+
+% --- Executes on button press in savechanges.
+function savechanges_Callback(hObject, eventdata, handles)
+% get the text
+text = get(handles.notestextEdit,'String');
+% convert it to a normal string
+text = sprintf('%s',char([double(text) 10*ones(size(text,1),1)])');
+% otherwise update optionstext
+handles.output = text;
+handles.output2 = 1;
+% Update handles structure
+guidata(hObject, handles);
+% Resume
+uiresume(handles.figure1);
+return
+
+% --- Executes on button press in exit.
+function exit_Callback(hObject, eventdata, handles)
+handles.output = handles.UserData.notestext;
+handles.output2 = 0;
+% Update handles structure
+guidata(hObject, handles);
+% Resume
+uiresume(handles.figure1);
+return
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/documentation/about.html b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/documentation/about.html
new file mode 100644
index 0000000000000000000000000000000000000000..6128a703accb683e177a7f17efde12166be78276
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/documentation/about.html
@@ -0,0 +1,75 @@
+<style>
+/* MAIN POSITION */
+body {
+  background-color: #ffffff;
+  margin: 5px;
+  FONT-FAMILY: Verdana, Arial, Helvetica, sans-serif; 
+  FONT-SIZE: 12px; 
+  color: #2e3640;
+  text-align : justify;
+  line-height: 150%;
+}
+
+h1 {  
+	COLOR: #ffffff;   
+	FONT-SIZE: 20px;   
+	FONT-WEIGHT: normal;   
+	BACKGROUND: #d4db7b; 
+	padding: 2px 2px 7px 5px;  /* t r b l */
+	margin: 0px 0px 10px 0px;
+	display: block;
+	text-align: left;
+}
+
+p {
+	margin-bottom : 5px;	
+}
+
+a { 
+	COLOR: #929d00; 
+}
+
+table {
+	padding: 0px 0px 0px 0px;
+	margin: 0px 0px 0px 0px;
+	background: #ffffff;
+}
+
+td { 
+	padding: 5px 5px 5px 5px;
+	background: #f3f5f7;
+	margin: 0px 0px 0px 0px;
+	color: #2e3640;
+	font-size: 12px;
+    line-height: 150%;  
+}
+
+td.announcement {
+	border-style: solid;
+	border-color: #b7c034;
+	border-width: 2px;
+}
+
+li {
+	margin: 0px 0px 4px 0px;
+}
+
+ul {
+	padding-top: 5px;
+	padding-bottom: 5px;
+}
+</style>
+<h1>About SBPD</h1>
+<img src="pics/green.jpg" width="200" align="right">
+The SBTOOLBOX2 and the SBPD addon package have been developed
+by <a href="http://www.hschmidt.de">Dr. Henning Schmidt</a>, 
+currently working at the University of Rostock, Germany.
+<p>
+In case of questions, feedback, employment offers, lottery-win notifications, 
+etc. please contact me via <a href="mailto:henning@sbtoolbox2.org">henning@sbtoolbox2.org</a>.
+<p>&nbsp;<p>
+<p>&nbsp;<p>
+<h1>License Information SBPD</h1>
+<a rel="license" href="http://creativecommons.org/licenses/by-nc-nd/2.0/de/deed.en"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by-nc-nd/2.0/de/88x31.png" align="left"></a>
+<span xmlns:dc="http://purl.org/dc/elements/1.1/" property="dc:title">SBPD</span> is licensed under a<br>
+<a rel="license" href="http://creativecommons.org/licenses/by-nc-nd/2.0/de/deed.en">Creative Commons Attribution-Non-Commercial-No Derivative Works 2.0 Germany License</a>.
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/documentation/documentation.html b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/documentation/documentation.html
new file mode 100644
index 0000000000000000000000000000000000000000..1dc406c27b491e49ce45ce2d4356dc4aaf7aba49
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/documentation/documentation.html
@@ -0,0 +1,90 @@
+<style>
+/* MAIN POSITION */
+body {
+  background-color: #ffffff;
+  margin: 5px;
+  FONT-FAMILY: Verdana, Arial, Helvetica, sans-serif; 
+  FONT-SIZE: 12px; 
+  color: #2e3640;
+  text-align : justify;
+  line-height: 150%;
+}
+
+h1 {  
+	COLOR: #ffffff;   
+	FONT-SIZE: 20px;   
+	FONT-WEIGHT: normal;   
+	BACKGROUND: #d4db7b; 
+	padding: 2px 2px 7px 5px;  /* t r b l */
+	margin: 0px 0px 10px 0px;
+	display: block;
+	text-align: left;
+}
+
+p {
+	margin-bottom : 5px;	
+}
+
+a { 
+	COLOR: #929d00; 
+}
+
+table {
+	padding: 0px 0px 0px 0px;
+	margin: 0px 0px 0px 0px;
+	background: #ffffff;
+}
+
+td { 
+	padding: 5px 5px 5px 5px;
+	background: #f3f5f7;
+	margin: 0px 0px 0px 0px;
+	color: #2e3640;
+	font-size: 12px;
+    line-height: 150%;  
+}
+
+td.announcement {
+	border-style: solid;
+	border-color: #b7c034;
+	border-width: 2px;
+}
+
+li {
+	margin: 0px 0px 4px 0px;
+}
+
+ul {
+	padding-top: 5px;
+	padding-bottom: 5px;
+}
+</style>
+<h1>Documentation SBPDgui</h1>
+<img src="pics/dart.png" width="200" align="right">
+<b>The SBPGgui is a graphical user-interface aiming at giving users,
+which are unfamiliar with the MATLAB command line interface, the possibility of using 
+the SBPD package for parameter estimation tasks.</b>
+<p>
+Its use is hopefully (almost) self-explaining. Essentially, the main steps are the following:
+<ol>
+    <li><em>Load</em> (or <em>Import</em>) a project using the <em>File</em> menu.
+    <li>Choose the parameters/initial conditions you want to estimate. You need to specify their names and
+        lower and upper bounds.
+        <ul>
+            <li>Global parameters are model parameters that are the same across all experiments.
+            <li>Local parameters are experiment dependent.
+            <li>Initial conditions are always estimated experiment dependent.
+        </ul>
+        The <em>Initialize</em> and <em>Write out</em> buttons help with this task. Try them out and you will see
+        what they do. Copy and paste and change as you need it.
+    <li>Select desired estimation settings.
+    <li>Run the parameter estimation.
+    <li>Following the parameter estimation you can perform a fit analysis. A good idea is to select the 
+        <em>simplexSB</em> or <em>SSmSB</em> (if availabe) optimization methods for that, using smaller settings
+        for the maximum number of iterations.
+    <li>Export or save the project using again the <em>File</em> menu.
+</ol>
+At all times other tasks can be run from the buttons to the left. Just try them out.
+<p>
+Please also have a look at the full SBPD documentation that 
+you can find here: <a href="http://www.sbtoolbox2.org/main.php?display=documentationSBPD&menu=userreference">SBPD Documentation</a>.
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/documentation/pics/dart.png b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/documentation/pics/dart.png
new file mode 100644
index 0000000000000000000000000000000000000000..daef88864b4d8c5964184dfd47247c730328c00a
Binary files /dev/null and b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/documentation/pics/dart.png differ
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/documentation/pics/green.jpg b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/documentation/pics/green.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..eb891f1918b30473121c6375042a1a310f0afece
Binary files /dev/null and b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDgui_dir/documentation/pics/green.jpg differ
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDplot_dir/SBPDplot.fig b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDplot_dir/SBPDplot.fig
new file mode 100644
index 0000000000000000000000000000000000000000..2d4d9bd051748d3790da399fb5be26d513317cd4
Binary files /dev/null and b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDplot_dir/SBPDplot.fig differ
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDplot_dir/SBPDplot.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDplot_dir/SBPDplot.m
new file mode 100644
index 0000000000000000000000000000000000000000..44dba21b3e19eeb23fc5339157a12be46671630d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/gui/SBPDplot_dir/SBPDplot.m
@@ -0,0 +1,273 @@
+function varargout = SBPDplot(varargin)
+% SBPDplot - allows to compare simulated experiments data to measurements
+%
+% USAGE:
+% ======
+% [] = SBPDplot(plotdata)
+%
+% plotdata: This datastructure is the output argument of the function 
+% SBPDcomparemeasurements. 
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INITIALIZATION CODE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Begin initialization code - DO NOT EDIT
+gui_Singleton = 1;
+gui_State = struct('gui_Name',       mfilename, ...
+                   'gui_Singleton',  gui_Singleton, ...
+                   'gui_OpeningFcn', @SBPDplot_OpeningFcn, ...
+                   'gui_OutputFcn',  @SBPDplot_OutputFcn, ...
+                   'gui_LayoutFcn',  [] , ...
+                   'gui_Callback',   []);
+if nargin && ischar(varargin{1})
+    gui_State.gui_Callback = str2func(varargin{1});
+end
+if nargout
+    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
+else
+    gui_mainfcn(gui_State, varargin{:});
+end
+% End initialization code - DO NOT EDIT
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INTERFACE FUNCTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% --- Executes just before SBPDplot is made visible.
+function SBPDplot_OpeningFcn(hObject, eventdata, handles, varargin)
+academicWarningSBPD
+if nargin ~= 4,
+    error('Incorrect number of input arguments.');
+end
+handles.plotdata = varargin{1};
+% set modelselection and choose first model
+set(handles.modelselection,'String',{handles.plotdata.model.name});
+set(handles.modelselection,'Value',1);
+% set experimentselection for first model and first experiment
+set(handles.experimentselection,'String',{handles.plotdata.model(1).experiment.name});
+set(handles.experimentselection,'Value',1);
+% select plottype 
+handles.dataPlotType = 'plot';     
+% set errorbarflag to 1
+handles.errorbars = 1;
+% Initialize export figure handle and grid flag
+handles.exportFigureHandle = [];
+handles.grid = 0;
+% Doing a first plot
+doPlot(handles);
+% Choose default command line output for SBPDplot
+handles.output = hObject;
+% Update handles structure
+guidata(hObject, handles);
+return
+
+% --- Outputs from this function are returned to the command line.
+function varargout = SBPDplot_OutputFcn(hObject, eventdata, handles) 
+%varargout{1} = handles.output;
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PLOT FUNCTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function doPlot(handles)
+colorvector = {'b','g','r','c','m','y','k'};
+%markervector = {'o','x','+','*','s','d','v','^','<','>','p','h'};
+warning off;
+% get the data to plot
+plotdata = handles.plotdata;
+m = get(handles.modelselection,'Value');
+e = get(handles.experimentselection,'Value');
+edata = plotdata.model(m).experiment(e);
+% general information
+titletext = regexprep(edata.name,'_',' ');
+xlabeltext = 'Time';
+% simulated data information
+sim_timevector = edata.timevector;
+sim_componentnames = edata.componentnames;
+sim_componentvalues = edata.componentvalues;
+if isempty(sim_componentvalues),
+    error('Please check if the names of the measured data appear in the model.');
+end
+% plot simulated data
+for k=1:size(sim_componentvalues,2),
+    feval(handles.dataPlotType,sim_timevector,sim_componentvalues(:,k),'linewidth',2,'color',colorvector{mod(k-1,7)+1}); hold on;
+end
+% measured data information 
+for meas=1:length(edata.measurement),
+    meas_timevector = edata.measurement(meas).timevector;
+    meas_componentnames = edata.measurement(meas).componentnames;
+    meas_componentvalues = edata.measurement(meas).componentvalues;   
+    meas_maxvalues = edata.measurement(meas).maxvalues;   
+    meas_minvalues = edata.measurement(meas).minvalues;   
+%     marker = markervector{mod(meas-1,length(markervector))+1};
+%     feval(handles.dataPlotType,meas_timevector,meas_componentvalues,['--' marker]); hold on;
+    for k=1:size(sim_componentvalues,2),
+        feval(handles.dataPlotType,meas_timevector,meas_componentvalues(:,k),['*:'],'linewidth',2,'color',colorvector{mod(k-1,7)+1}); hold on;
+    end
+    if handles.errorbars == 1 && strcmp(handles.dataPlotType,'plot'),
+        % plot error bounds
+        for k=1:length(meas_componentnames),
+            color = colorvector{mod(k-1,7)+1};
+%             for k1 = 1:size(meas_timevector,1),
+            for k1 = 1:length(meas_timevector),
+                feval(handles.dataPlotType,[meas_timevector(k1),meas_timevector(k1)],[meas_minvalues(k1,k),meas_maxvalues(k1,k)],['.:',color]);
+            end
+        end
+    end
+end
+hold off;
+hlhlx = legend(sim_componentnames);
+set(hlhlx,'Interpreter','none');
+
+hlhlx = title(titletext);
+set(hlhlx,'Interpreter','none');
+hlhlx = xlabel(xlabeltext);
+set(hlhlx,'Interpreter','none');
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXPORT FIGURE FUNCTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Export the figure
+function export_Callback(hObject, eventdata, handles)
+warning off;
+if isempty(handles.exportFigureHandle),
+    figH = figure;
+    handles.exportFigureHandle = figH;
+    % Update handles structure
+    guidata(hObject, handles);
+else
+    figH = handles.exportFigureHandle;
+    figure(figH);
+end
+nrow = str2num(get(handles.nrow,'String'));
+ncol = str2num(get(handles.ncol,'String'));
+nnumber = str2num(get(handles.nnumber,'String'));
+subplot(nrow,ncol,nnumber);
+doPlot(handles);
+if handles.grid == 1,
+    grid;
+end
+% set axes
+XLim = get(handles.plotarea,'Xlim');
+YLim = get(handles.plotarea,'Ylim');
+axis([XLim, YLim]);
+return
+
+% Request new figure for export
+function newexportfigure_Callback(hObject, eventdata, handles)
+handles.exportFigureHandle = [];
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% TRIVIAL FUNCTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% --- Executes on button press in zoombutton.
+function errorbarbutton_Callback(hObject, eventdata, handles)
+% toogle the errorbars in the figure
+if handles.errorbars == 0,
+    handles.errorbars = 1;
+else
+    handles.errorbars = 0;
+end
+% plot
+doPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+% --- Executes on button press in zoombutton.
+function zoombutton_Callback(hObject, eventdata, handles)
+% toogle the zoom in the figure
+zoom
+return
+
+% --- Executes on button press in gridbutton.
+function gridbutton_Callback(hObject, eventdata, handles)
+% toogle the grid in the figure
+grid
+if handles.grid == 1,
+    handles.grid = 0;
+else
+    handles.grid = 1;
+end
+% Update handles structure
+guidata(hObject, handles);
+return
+
+% --- Executes on selection change in modelselection.
+function modelselection_Callback(hObject, eventdata, handles)
+try
+    modelindex = get(handles.modelselection,'Value');
+    set(handles.experimentselection,'String',{handles.plotdata.model(modelindex).experiment.name});
+    doPlot(handles);
+catch
+    errordlg('This selection is not possible.','Error','on');               
+end
+return
+
+% --- Executes on selection change in experimentselection.
+function experimentselection_Callback(hObject, eventdata, handles)
+try
+    doPlot(handles);
+catch
+    errordlg('This selection is not possible.','Error','on');               
+end
+return
+
+% --- From R2014B the radiobutton groups are handled differently ...
+function plotAxesSelection_SelectionChangeFcn(hObject, eventdata, handles)
+handles.dataPlotType = eventdata.NewValue.String;
+% Update handles structure
+guidata(hObject, handles);
+doPlot(handles);
+return
+
+% --- Executes on button press in plot.
+function plot_Callback(hObject, eventdata, handles)
+handles.dataPlotType = 'plot';
+% disable errorbarbutton
+set(handles.errorbarbutton,'Visible','on');
+% Update handles structure
+guidata(hObject, handles);
+doPlot(handles);
+return
+
+% --- Executes on button press in loglog.
+function semilogx_Callback(hObject, eventdata, handles)
+handles.dataPlotType = 'semilogx';
+% disable errorbarbutton
+set(handles.errorbarbutton,'Visible','off');
+handles.errorbars = 0;
+% Update handles structure
+guidata(hObject, handles);
+doPlot(handles);
+return
+
+% --- Executes on button press in semilogx.
+function semilogy_Callback(hObject, eventdata, handles)
+handles.dataPlotType = 'semilogy';
+% disable errorbarbutton
+set(handles.errorbarbutton,'Visible','off');
+handles.errorbars = 0;
+% Update handles structure
+guidata(hObject, handles);
+doPlot(handles);
+return
+
+% --- Executes on button press in loglog.
+function loglog_Callback(hObject, eventdata, handles)
+handles.dataPlotType = 'loglog';
+% disable errorbarbutton
+set(handles.errorbarbutton,'Visible','off');
+handles.errorbars = 0;
+% Update handles structure
+guidata(hObject, handles);
+doPlot(handles);
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/identifiability/SBPDidentifiability.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/identifiability/SBPDidentifiability.m
new file mode 100644
index 0000000000000000000000000000000000000000..d2f56ea9a7a82389cfd4f27a3eb91620c0c52f9b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/identifiability/SBPDidentifiability.m
@@ -0,0 +1,236 @@
+function [varargout] = SBPDidentifiability(project,parameters,varargin)
+% SBPDidentifiability: Performs parameter identifiability analysis for a
+% given project, based on SBPDsensitivity and SBPDparametercorrelation.
+% The model and the experiments to consider can be chosen. 
+% Timepoints to take into account are determined from the measurement
+% data that are available in the project. More information can be found in
+% the help text to the SBPDparametercorrelation function.
+%
+% USAGE:
+% ======
+% output = SBPDidentifiability(project, parameters)
+% output = SBPDidentifiability(project, parameters, options)
+%
+% project: SBPDproject to analyze
+% parameters: Cell-array of parameternames for which to determine the
+%       identifiability
+% options: structure with the following fields:
+%       options.pValueFlag: =0: plot correlations, =1: plot p-values
+%       options.pValueCutOff: pValue for which to make a decision if
+%            correlated or not. (For plotting purposes the pValues below
+%            the threshold are set to zero)
+%       options.modelindex: Index of the model in the project to consider
+%       options.experimentindices: Vector of indices indicating the experiments to
+%                                  consider
+%       options.integratoroptions.abstol: abs tolerance
+%       options.integratoroptions.reltol: rel tolerance
+%       options.integratoroptions.minstep: min step-size of integrator
+%       options.integratoroptions.maxstep: max step-size of integrator
+%       options.integratoroptions.maxnumsteps: maximum number of steps to be
+%         taken by the solver in its attempt to reach the next
+%         output time 
+
+% DEFAULT VALUES:
+% ===============
+% options.pValueFlag:           0 (plot correlations)
+% options.pValueCutOff:         0.05 
+% options.modelindex:           1 (first model)
+% options.experimentindices:    1:n (all experiments)
+% options.integratoroptions.abstol: 1e-6
+% options.integratoroptions.reltol: 1e-6
+% options.integratoroptions.minstep: 0
+% options.integratoroptions.maxstep: inf
+% options.integratoroptions.maxnumsteps: 500
+%
+% Output Arguments:
+% =================
+% When called without an output argument the parameter correlation
+% information is graphically represented. Both the correlations and the 
+% P-values are plotted.
+% To be more consistent with the coloring not the P-values but (1-Pvalues)
+% are plotted. The lighter the color, the higher the correlation between
+% the corresponding parameters. 
+% 
+% If an output argument is given, the results are returned as a
+% MATLAB structure as follows:
+%      output.parameters: cell-array with parameter names
+%      output.correlationMatrix: parameter correlation matrix
+%      output.pValues: a matrix of p-values for testing
+%           the hypothesis of no correlation.  Each p-value is the probability
+%           of getting a correlation as large as the observed value by random
+%           chance, when the true correlation is zero.  If pValues(i,j) is small, say
+%           less than 0.05, then the correlation correlationMatrix(i,j) is
+%           significant.
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+global useSBPDguiFlag
+if useSBPDguiFlag ~= 1,
+    useSBPDguiFlag = 0;
+end
+
+projectstruct = SBPDstruct(project);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE INPUT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% default values
+modelindex = 1;
+experimentindices = [1:length(projectstruct.experiments)];
+pValueCutOff = 0.05;
+pValueFlag = 0;
+% varargins
+if nargin < 2 || nargin > 3,
+    error('Incorrect number of input arguments.');
+end
+if nargin == 3,
+    options = varargin{1};
+    if isfield(options,'modelindex'),
+        modelindex = options.modelindex;
+    end
+    if isfield(options,'experimentindices'),
+        experimentindices = options.experimentindices;
+    end
+    if isfield(options,'pValueCutOff'),
+        pValueCutOff = options.pValueCutOff;
+        if isempty(pValueCutOff),
+            pValueCutOff = 0;
+        end
+    end
+    if isfield(options,'pValueFlag'),
+        pValueFlag = options.pValueFlag;
+        if isempty(pValueFlag),
+            pValueFlag = 0;
+        end
+    end
+end
+if modelindex < 0 || modelindex > length(projectstruct.models),
+    error('''modelindex'' out of bounds.');
+end
+if min(experimentindices) < 1 || max(experimentindices) > length(projectstruct.experiments),
+    error('''experimentindices'' out of bounds.');
+end
+% get integratoroptions
+try integratoroptions = options.integratoroptions; catch, integratoroptions = []; end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% MERGE MODEL WITH EXPERIMENTS, CHECK, AND PERFORM SENSITIVITY SIMULATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modelexp = {};
+senssimdata = [];        % senssimdata for each experiment
+measuredcomponents = [];     % measured components for each experiment
+measuredcomponents.states = {};
+measuredcomponents.variables = {};
+
+if useSBPDguiFlag,
+    h = waitbar(0,'Calculating. Please wait...');
+end
+
+for e=1:length(experimentindices),
+    if useSBPDguiFlag,
+        waitbar(e/length(experimentindices),h)
+    end
+    modelexp{e} = SBmergemodexp(projectstruct.models{modelindex},projectstruct.experiments(experimentindices(e)).experiment);
+    % check if all parameters in the modelexp ... if not then error
+    getparamindicesSBPD(modelexp{e},parameters);
+    % construct the simulation time vector
+    timevector = [];
+    componentnames = {};
+    for m=1:length(projectstruct.experiments(experimentindices(e)).measurements),
+        [timevectormeas, componentnamesmeas] = SBmeasurementdata(projectstruct.experiments(experimentindices(e)).measurements{m});
+        timevector = [timevector(:); timevectormeas];
+        componentnames = {componentnames{:} componentnamesmeas{:}};
+    end
+    timevector = sort(unique(timevector));
+    componentnames = unique(componentnames);
+    % perform sensitivity simulation for chosen parameters
+    senssimdata{e} = SBPDsensitivity(modelexp{e},timevector, parameters,[],integratoroptions);
+    % save measured states and variables for each experiment
+    allmodelstates = SBstates(modelexp{e});
+    allmodelvariables = SBvariables(modelexp{e});
+    indexs = 1;
+    indexv = 1;
+    for k=1:length(componentnames),
+        if ~isempty(strmatchSB(componentnames{k},allmodelstates,'exact')),
+            measuredcomponents(e).states{indexs} = componentnames{k};
+            indexs = indexs+1;
+        end
+        if ~isempty(strmatchSB(componentnames{k},allmodelvariables,'exact')),
+            measuredcomponents(e).variables{indexv} = componentnames{k};
+            indexv = indexv+1;
+        end
+    end
+end
+if useSBPDguiFlag,
+    close(h);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PERFORM PARAMETER CORRELATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+paramcorrdata = SBPDparametercorrelation(senssimdata,parameters,measuredcomponents);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONSTRUCT OUTPUT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargout ~= 0,
+    output = [];
+    output.parameters = paramcorrdata.parameters;
+    output.correlationMatrix = paramcorrdata.correlationMatrix;
+    output.pValues = paramcorrdata.pValues;
+    output.corrcoefLB = paramcorrdata.corrcoefLB;
+    output.corrcoefUB = paramcorrdata.corrcoefUB;
+    varargout{1} = output;
+else
+    if pValueFlag == 0,
+        % Plot the correlation matrix (absolute values)
+        plotData = paramcorrdata.correlationMatrix;
+        titleText = 'Parameter Correlation Matrix (absolute values)';
+        % Plot the correlation matrix (absolute values)
+        % Prepare plot matrix
+        plotMatrix = [plotData zeros(size(plotData,1),1); -ones(1,size(plotData,2)+1)];
+        plotMatrix = abs(plotMatrix);
+        % Plot the result
+        figH = figure; clf;
+        axesH = gca(figH);
+        pcolor(plotMatrix);
+        axis square;
+        colorbar('EastOutside','YTick',[-1,-0.8,-0.6,-0.4,-0.2,0,0.2,0.4,0.6,0.8,1]);
+        xticklabel_rotate([1.5:size(plotData,1)+0.5],90,paramcorrdata.parameters);
+        set(axesH,'YTick',[1.5:size(plotData,1)+0.5]);
+        set(axesH,'YTickLabel',paramcorrdata.parameters);
+        colormap('Bone');
+        hlhlx = title(titleText);
+        set(hlhlx,'Interpreter','none');
+    else
+        % Plot the P-Value matrix
+        plotData = paramcorrdata.pValues;
+        if ~isempty(pValueCutOff),
+            plotData(find(plotData<pValueCutOff)) = 0;
+            titleText = sprintf('(1-P)-values. Cut-off threshold: 1-%g',pValueCutOff);
+        else
+            titleText = '(1-P)-values.';
+        end
+        plotData = 1-plotData;
+        plotData = plotData + eye(size(plotData));
+        % Prepare plot matrix
+        plotMatrix = [plotData zeros(size(plotData,1),1); -ones(1,size(plotData,2)+1)];
+        plotMatrix = abs(plotMatrix);
+        % Plot the result
+        figH = figure; clf;
+        axesH = gca(figH);
+        pcolor(plotMatrix);
+        axis square;
+        colorbar('EastOutside','YTick',[-1,-0.8,-0.6,-0.4,-0.2,0,0.2,0.4,0.6,0.8,1]);
+        xticklabel_rotate([1.5:size(plotData,1)+0.5],90,paramcorrdata.parameters);
+        set(axesH,'YTick',[1.5:size(plotData,1)+0.5]);
+        set(axesH,'YTickLabel',paramcorrdata.parameters);
+        colormap('Bone');
+        hlhlx = title(titleText);
+        set(hlhlx,'Interpreter','none');
+    end
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/identifiability/SBPDparametercorrelation.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/identifiability/SBPDparametercorrelation.m
new file mode 100644
index 0000000000000000000000000000000000000000..b0857af171959d5204320afc00a00b921500d5db
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/identifiability/SBPDparametercorrelation.m
@@ -0,0 +1,296 @@
+function [varargout] = SBPDparametercorrelation(senssimdata,sensparameters,measuredcomponents)
+% SBPDparametercorrelation: Function for determining parameter correlations 
+%   based on parametric sensitivities. The result can be used to check 
+%   a priori identifiability of parameters for given experimental settings.
+%   Several experiments can be combined. Measured states AND measured
+%   variables can be considered.
+%
+%   The method is based on:
+%   Jacquez, J.A. and Greif, P. (1985) Numerical parameter identifiability
+%   and estimability: Integrating identifiability, estimability, and
+%   optimal sampling design, Mathematical Biosciences, 77, pp. 201-227
+%
+% This function determines correlations between parameters. The inputs to
+% this function are parameter sensitivity trajectories returned from the
+% SBAOsenssim function, reflecting the sensitivity of the states and variables
+% to parameter changes during user-defined experiments. From this
+% information a parameter correlation matrix is determined. Off-diagonal
+% elements in this matrix that are close to +1 or -1 indicate problems in
+% identifying the corresponding parameters independently. Elements that are
+% close to zero indicate that there is no important correlation between the
+% corresponding elements and thus these parameters should be identifiable
+% independently without problem (for the defined experiments).
+%
+% A priori identifiability: The identifiability is a local property. For
+% different sets of parameter values different correlation matrices can be
+% obtained. Since unknown parameters are, by definition, unknown this might
+% lead to problems interpreting the results. However, one possible approach
+% is to run the identifiability analysis for different sets of parameter
+% values, randomly chosen in certain intervals around a best initial
+% guess.
+%
+% USAGE:
+% ======
+% output = SBPDparametercorrelation(senssimdata,sensparameters,measuredcomponents)
+%
+% senssimdata: cell-array with output arguments from the sensitivity analysis function
+%       SBPDsensitivity. The simulation should reflect (wrt, e.g., sampling
+%       time, stimuli) the experiments that are planned to obtain
+%       measurement data for the parameter estimation. 
+% sensparameters: cell-array with parameter names for which to determine
+%       the correlations
+% measuredcomponents: structure defining the measured states and variables:
+%       measuredcomponents.states
+%       measuredcomponents.variables
+%       It is possible to specify just one set of measured components. But
+%       it is also possible to specify one set per senssimdata.
+%
+% Output Arguments:
+% =================
+% When called without an output argument the parameter correlation matrix
+% is graphically represented. For easier graphical interpretation the
+% absolute values of the matrix elements are taken. White color indicates a
+% perfect correlation and black color indicates no correlation between
+% parameters. If an output argument is given, the results are returned as a
+% MATLAB structure as follows:
+%      output.parameters: cell-array with parameter names
+%      output.correlationMatrix: parameter correlation matrix
+%      output.G: stacked sensitivity matrix
+%      output.pValues: a matrix of p-values for testing
+%           the hypothesis of no correlation.  Each p-value is the probability
+%           of getting a correlation as large as the observed value by random
+%           chance, when the true correlation is zero.  If pValues(i,j) is small, say
+%           less than 0.05, then the correlation correlationMatrix(i,j) is significant.
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE INPUT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin ~= 3,
+    error('Incorrect number of input arguments.');
+end
+if isstruct(senssimdata),
+    senssimdata = {senssimdata};
+end
+if ischar(sensparameters),
+    sensparameters = {sensparameters};
+end
+if length(measuredcomponents) == 1 && length(senssimdata) ~= 1,
+    newmeascomp = [];
+    for k=1:length(senssimdata),
+        newmeascomp(k) = measuredcomponents;
+    end
+    measuredcomponents = newmeascomp;
+elseif length(measuredcomponents) ~= length(senssimdata),
+    error('Number of sensitivity datasets and measured component set does not match.');
+end
+% check if ok
+if ~isfield(measuredcomponents,'states'),
+    error('Measured states not defined (if none, set to empty).');
+end
+if ~isfield(measuredcomponents,'variables'),
+    error('Measured variables not defined (if none, set to empty).');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK THAT ALL SENSPARAMETERS AND MEASURED ELEMENTS EXIST IN THE SENSSIMDATA
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Additionally the sensitivity data corresponding to the selected parameters is extracted
+% and information about the indices of the state and variable
+% elements is gathered since it might be different due to different
+% experiments.
+datainfo = [];
+datainfo.sensparamindices = [];
+datainfo.measuredstateindices = [];
+datainfo.measuredvariableindices = [];
+datainfo.timevector = [];
+datainfo.sensestatetrajectories = [];
+datainfo.sensevariabletrajectories = [];
+for k = 1:length(senssimdata),
+    senssimdatak = senssimdata{k};
+    senssimparam = senssimdatak.sensparameters;
+    senssimstates = senssimdatak.states;
+    senssimvariables = senssimdatak.variables;
+    % check sensparameters
+    for k2=1:length(sensparameters),
+        index = strmatchSB(sensparameters{k2},senssimparam,'exact');
+        if isempty(index),
+            error('Parameter ''%s'' does not exist in the simulated sensitivity data.',sensparameters{k2});
+        else
+            datainfo(k).sensparamindices(k2) = index;
+        end
+    end
+    % check measured states
+    for k2=1:length(measuredcomponents(k).states),
+        index = strmatchSB(measuredcomponents(k).states{k2},senssimstates,'exact');
+        if isempty(index),
+            error('State ''%s'' does not exist in the simulated sensitivity data.',measuredcomponents(k).states{k2});
+        else
+            datainfo(k).measuredstateindices(k2) = index;
+        end
+    end
+    % check measured variables
+    for k2=1:length(measuredcomponents(k).variables),
+        index = strmatchSB(measuredcomponents(k).variables{k2},senssimvariables,'exact');
+        if isempty(index),
+            error('Variables ''%s'' does not exist in the simulated sensitivity data.',measuredcomponents(k).variables{k2});
+        else
+            datainfo(k).measuredvariableindices(k2) = index;
+        end
+    end
+    % get time vector for data 
+    datainfo(k).timevector = senssimdatak.time;
+    % get the sensitivities for the chosen parameters
+    datainfo(k).sensestatetrajectories = senssimdatak.paramtrajectories.states(datainfo(k).sensparamindices);
+    datainfo(k).sensevariabletrajectories = senssimdatak.paramtrajectories.variables(datainfo(k).sensparamindices);   
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE CORRELATIONS BY STACKING
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE THE STACKED SENSITIVITY MATRIX
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+G = [];
+for kdata = 1:length(datainfo),
+    for ktime = 1:length(datainfo(kdata).timevector),
+        Systates = []; % measured states in columns, sensparameters in rows
+        Syvariables = []; % measured variables in columns, sensparameters in rows
+        for kparam = 1:length(datainfo(kdata).sensestatetrajectories),
+            if ~isempty(datainfo(kdata).measuredstateindices),
+                Systates(:,end+1) = datainfo(kdata).sensestatetrajectories{kparam}(ktime,datainfo(kdata).measuredstateindices)';
+            end
+        end
+        for kparam = 1:length(datainfo(kdata).sensevariabletrajectories),
+            if ~isempty(datainfo(kdata).measuredvariableindices),
+                Syvariables(:,end+1) = datainfo(kdata).sensevariabletrajectories{kparam}(ktime,datainfo(kdata).measuredvariableindices)';
+            end
+        end
+        G = [G; Systates; Syvariables];
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE THE PARAMETER CORRELATION MATRIX
+% Take out parameters with zero variance!
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[n,m] = size(G);
+C = cov(G);
+zerovarianceindices = find(diag(C)==0);
+G(:,zerovarianceindices) = [];  % take out the parameters
+allsensparameters = sensparameters;
+sensparameters = sensparameters(setdiff([1:length(sensparameters)],zerovarianceindices));
+[correlationMatrix,P,LB,UB] = corrcoef(G);
+
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% % DETERMINE CORRELATIONS BY AVERAGING
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% % DETERMINE THE STACKED SENSITIVITY MATRIX FOR EACH EXPERIMENT
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% G = {};
+% for kdata = 1:length(datainfo),
+%     G{kdata} = [];
+%     for ktime = 1:length(datainfo(kdata).timevector),
+%         Systates = []; % measured states in columns, sensparameters in rows
+%         Syvariables = []; % measured variables in columns, sensparameters in rows
+%         for kparam = 1:length(datainfo(kdata).sensestatetrajectories),
+%             if ~isempty(datainfo(kdata).measuredstateindices),
+%                 Systates(:,end+1) = datainfo(kdata).sensestatetrajectories{kparam}(ktime,datainfo(kdata).measuredstateindices)';
+%             end
+%         end
+%         for kparam = 1:length(datainfo(kdata).sensevariabletrajectories),
+%             if ~isempty(datainfo(kdata).measuredvariableindices),
+%                 Syvariables(:,end+1) = datainfo(kdata).sensevariabletrajectories{kparam}(ktime,datainfo(kdata).measuredvariableindices)';
+%             end
+%         end
+%         G{kdata} = [G{kdata}; Systates; Syvariables];
+%     end
+% end
+% 
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% % DETERMINE THE PARAMETER CORRELATION MATRIX
+% % Take out parameters with zero variance!
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% cM = {};
+% zVI_All = [];
+% zVI = {};
+% 
+% for k=1:length(G),
+%     Gk = G{k};
+%     C = cov(Gk);
+%     zerovarianceindices = find(diag(C)==0);
+%     zVI{k} = zerovarianceindices
+%     % get common zero variances
+%     if k==1,
+%         zVI_All = zerovarianceindices;
+%     else
+%         zVI_All = intersect(zVI_All,zerovarianceindices);
+%     end
+%     % remove the zero variance parameters from Gk
+%     Gk(:,zerovarianceindices) = [];  % take out the parameters
+%     [cM{k},P,LB,UB] = corrcoef(Gk);
+% end
+% 
+% helpCM = zeros(size(G{1},2));
+% correlationMatrix = zeros(size(G{1},2));
+% for k=1:length(cM),
+%     x = setdiff([1:size(G{k},2)],zVI{k});
+%     helpCM(x,x) = cM{k};
+%     correlationMatrix = correlationMatrix+helpCM;
+% end
+% correlationMatrix = correlationMatrix/length(G);
+% correlationMatrix(:,zVI_All) = [];
+% correlationMatrix(zVI_All,:) = [];
+% allsensparameters = sensparameters;
+% sensparameters = sensparameters(setdiff([1:length(sensparameters)],zVI_All));
+% zerovarianceindices = zVI_All;
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DISPLAY NOTE IF PARAMTERS HAVE BEEN TAKEN OUT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(zerovarianceindices),
+    text = '';
+    for k=1:length(zerovarianceindices),
+        text = sprintf('%sParameter ''%s'' shows 0 variance. Taken out of consideration.\n',text,allsensparameters{zerovarianceindices(k)});
+    end
+    disp(text);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle the output
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargout > 1,
+    error('Incorrect number of output arguments.');
+elseif nargout == 1,
+    output = [];
+    output.parameters = sensparameters;
+    output.correlationMatrix = correlationMatrix;
+    output.pValues = P;
+    output.corrcoefLB = LB;
+    output.corrcoefUB = UB;
+    output.G = G;
+    varargout{1} = output;
+else
+    % Plot the correlation matrix (absolute values)
+    % Prepare plot matrix
+    plotMatrix = [correlationMatrix zeros(size(correlationMatrix,1),1); -ones(1,size(correlationMatrix,2)+1)];
+    plotMatrix = abs(plotMatrix);
+    % Plot the result
+    figH = figure; clf;
+    axesH = gca(figH);
+    pcolor(plotMatrix);
+    axis square;
+    colorbar('EastOutside','YTick',[-1,-0.8,-0.6,-0.4,-0.2,0,0.2,0.4,0.6,0.8,1]);
+    xticklabel_rotate([1.5:size(correlationMatrix,1)+0.5],90,sensparameters);
+    set(axesH,'YTick',[1.5:size(correlationMatrix,1)+0.5]);
+    set(axesH,'YTickLabel',sensparameters);
+    colormap('Bone');
+    title('Parameter Correlation Matrix (absolute values)');
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/modeling/SBPDdirectoptss.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/modeling/SBPDdirectoptss.m
new file mode 100644
index 0000000000000000000000000000000000000000..6b9bb0e5ddbc604e93cfb16e1b87dd697a2bf1c3
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/modeling/SBPDdirectoptss.m
@@ -0,0 +1,322 @@
+function [modelopt] = SBPDdirectoptss(model,ssStates,ssReactions,extravariables)
+% SBPDdirectoptss: This function applies the direct optimization method to 
+% impose a desired steady-state (in terms of state concentrations and
+% reaction rates) on the given model by adjusting the velocity rate
+% parameters of the reactions. Due to the latter, the function is only
+% applicable to models whos ODE right hand side are described by reactions
+% and stoichiometric coefficients. The adjustment of the velocity
+% parameters is done by multiplying determined numerical factors to the
+% rate expressions. Example:
+%
+%       R = k1*A - k2*B
+%
+% is changed to:
+% 
+%       R = factor*(k1*A-k2*B)
+%
+% REFERENCE:
+% ==========
+% The function is based on the method presented and used in:
+% F. Hynne, S. Dan�, P.G. S�rensen (2001) Full-scale model of glycolysis 
+% in Saccharomyces cerevisiae, Biophysical Chemistry, 94, 121-163
+%
+% USAGE:
+% ======
+% [modelopt] = SBdirectoptss(model, ssStates, ssReactions)
+%
+% model:            SBmodel to optimize
+% ssStates:         Desired steady-state of the model
+% ssReactions:      Reaction rates at desired steady-state
+%
+% Output Arguments:
+% =================
+% modelopt:   optimizied model with the desired steady-state
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% % check if symbolic toolbox is present
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% if ~symbolicpresentSBPD,
+%     error('The model reduction feature requires the presence of the symbolic toolbox.');
+% end
+
+academicWarningSBPD
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE NON-NUMERIC INITIAL CONDITIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% just by replacing them
+model = SBconvertNonNum2NumIC(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Parse all variables into reactions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%modelWork = substitutevarsSBPD(model);
+modelWork = model;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define required data
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+states = SBstates(modelWork);
+[reactions,reacformulas] = SBreactions(modelWork);
+[parameters, paramvalues] = SBparameters(modelWork);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input arguments against model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if length(ssStates) ~= length(states),
+    error('The number of provided steady-states does not match the number of states in the model.');
+end
+if length(ssReactions) ~= length(reactions),
+    error('The number of provided reaction steady-states does not match the number of reactions in the model.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check that model fully determined by the stoichiometric matrix
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+silentFlag = 1;  % no output from ss function
+rawFlag = 0; % value does not matter
+[N,components] = SBstoichiometry(modelWork,rawFlag,silentFlag);
+if length(states) ~= length(components),
+    error('Not all state ODEs are solely defined by reaction rates.');
+end
+
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% % Determine the names of the Vmax parameters for each reaction and their
+% % current values
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% VmaxParam = {};
+% VmaxParamValues = [];
+% states = SBstates(modelWork);
+% for k = 1:length(reactions),
+%     VmaxParam{k} = getVmaxParam(reacformulas{k},states,extravariables);
+%     if ~isempty(VmaxParam{k}),
+%         VmaxParamValues(k) = SBparameters(modelWork,VmaxParam{k});
+%     end
+% end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Set the initialconditions of the model to the desired steady-state
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modelWork = SBinitialconditions(modelWork,ssStates);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine the resulting reaction rates 
+% and the factors for the Vmax parameters as 
+% ration between desired and present
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[dummy1,dummy2,dummy3,dummy4,nonssRates] = SBreactions(modelWork,ssStates);
+factors = ssReactions./nonssRates;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% update the model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+sbs = SBstruct(modelWork);
+infotext = '';
+for k = 1:length(sbs.reactions),
+%     VmaxParameter = VmaxParam{k};
+%     % if Vmax parameter exists in reaction then change this parameter
+%     % otherwise just ad a numeric factor in front of the reaction
+%     % expression
+%     if ~isempty(VmaxParameter),
+%         % change the parameters value
+%         index = strmatchSB(VmaxParameter,parameters,'exact');
+%         sbs.parameters(index).value = factors(k)*VmaxParamValues(k);
+%         sbs.parameters(index).notes = sprintf('%s (directopt factor: %g)',sbs.parameters(index).notes,factors(k));
+%     else
+        if factor(k) ~= 1,
+            formula = sbs.reactions(k).formula;
+            newformula = sprintf('%f*(%s)',factors(k),formula);
+            sbs.reactions(k).formula = newformula;
+%            infotext = sprintf('%sReaction ''%s'' obtained a numeric factor.\n',infotext,sbs.reactions(k).name);
+        end
+%     end    
+end
+if ~isempty(infotext),
+    disp(infotext);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% build and return optimized model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modelopt = SBmodel(sbs);
+return
+
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% % Function determining the Vmax param name for given reaction expression
+% % If no Vmx param can be found [] is returned.
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% function [VmaxParameter] = getVmaxParam(formula,statenames,extravariables)
+% % define all specie names that should not be taken as parameters
+% % (states + extravariables)
+% allnames = {statenames{:} extravariables{:}};
+% variablessym = maplearraySBPD(allnames);
+% formulasym = sym(formula);
+% % determine the num and den and expand it
+% [numFsym, denFsym] = numden(formulasym);
+% % Get a symbolic expression with all the variable names (not being coefficients)
+% % Determine the coefficients in the num and den
+% for k = 1:length(allnames),
+%     numFsym = subs(numFsym,allnames{k},rand(1));
+%     denFsym = subs(denFsym,allnames{k},rand(1));
+% end
+% numF = char(numFsym);
+% denF = char(denFsym);
+% if denFsym == 1,
+%     denF = '';
+% end
+% par = 0;
+% for k = 1:length(numF),
+%     if numF(k) == '(',
+%         par = par + 1;
+%     end
+%     if numF(k) == ')',
+%         par = par - 1;
+%     end
+%     if (numF(k) == '+' || numF(k) == '-') && par == 0,
+%         numF(k) = ',';
+%     end
+% end
+% par = 0;
+% for k = 1:length(denF),
+%     if denF(k) == '(',
+%         par = par + 1;
+%     end
+%     if denF(k) == ')',
+%         par = par - 1;
+%     end
+%     if (denF(k) == '+' || denF(k) == '-') && par == 0,
+%         denF(k) = ',';
+%     end
+% end
+% numCoeffs = explodePCSB(numF);
+% % check if a denominator is present
+% if ~isempty(denF),
+%     denCoeffs = explodePCSB(denF);
+% else
+%     denCoeffs = [];
+% end
+% % delete empty elements (that can happen due to sign stuff ... symbolic toolbox ... argh!
+% temp = {};
+% for k = 1:length(numCoeffs),
+%     if ~isempty(numCoeffs{k}),
+%         temp{end+1} = numCoeffs{k};
+%     end
+% end
+% numCoeffs = temp;
+% temp = {};
+% for k = 1:length(denCoeffs),
+%     if ~isempty(denCoeffs{k}),
+%         temp{end+1} = denCoeffs{k};
+%     end
+% end
+% denCoeffs = temp;
+% % find all parameters that appear in num and den
+% numParam = {};
+% for k = 1:length(numCoeffs),
+%     add = explodePCSB(char(findsym(sym(numCoeffs{k}))));
+%     numParam = unique({numParam{:} add{:}});
+% end
+% denParam = {};
+% for k = 1:length(denCoeffs),
+%     add = explodePCSB(char(findsym(sym(denCoeffs{k}))));
+%     denParam = unique({denParam{:} add{:}});
+% end
+% allParam = unique({numParam{:} denParam{:}});
+% % check which of these parameters appears in
+% %   a) all terms in nom and not in den
+% %   b) in all terms in den and not in nom
+% numVpossible = {};
+% denVpossible = {};
+% for k = 1:length(allParam),
+%     found = 1;
+%     for k2 = 1:length(numCoeffs),
+%         test = ['#',numCoeffs{k2},'#'];
+%         if isempty(regexp(test,['\W', allParam{k}, '\W'])),
+%             found = 0;
+%             break
+%         end
+%     end
+%     if found == 1,
+%         numVpossible{end+1} = allParam{k};
+%     end
+%     found = 1;
+%     for k2 = 1:length(denCoeffs),
+%         test = ['#',denCoeffs{k2},'#'];
+%         if isempty(regexp(test,['\W', allParam{k}, '\W'])),
+%             found = 0;
+%             break
+%         end
+%     end
+%     if found == 1,
+%         denVpossible{end+1} = allParam{k};
+%     end
+% end
+% % Now check if elements in numVpossible appear in den and vice versa.
+% % If yes, then they are no possible
+% numVpossible2 = {};
+% denVpossible2 = {};
+% for k = 1:length(numVpossible),
+%     found = 0;
+%     for k2 = 1:length(denParam),
+%         if strcmp(numVpossible{k},denParam{k2}),
+%             found = 1;
+%             break;
+%         end
+%     end
+%     if found == 0,
+%         numVpossible2{end+1} = numVpossible{k};
+%     end
+% end
+% for k = 1:length(denVpossible),
+%     found = 0;
+%     for k2 = 1:length(numParam),
+%         if strcmp(denVpossible{k},numParam{k2}),
+%             found = 1;
+%             break;
+%         end
+%     end
+%     if found == 0,
+%         denVpossible2{end+1} = denVpossible{k};
+%     end
+% end
+% % Finally we need to divide each element in the num (den) by each element
+% % in the numV array to check that it appears only once.
+% numV = {};
+% denV = {};
+% for k = 1:length(numVpossible2),
+%     found = 0;
+%     for k2 = 1:length(numCoeffs),
+%         test = ['#' char(sym(numCoeffs{k2})/sym(numVpossible2{k})) '#'];
+%         if ~isempty(regexp(test,['\W', numVpossible2{k}, '\W'])),
+%             found = 1;
+%         end
+%     end
+%     if found == 0,
+%         numV{end+1} = numVpossible2{k};
+%     end
+% end
+% for k = 1:length(denVpossible2),
+%     found = 0;
+%     for k2 = 1:length(denCoeffs),
+%         test = ['#' char(sym(denCoeffs{k2})/sym(denVpossible2{k})) '#'];
+%         if ~isempty(regexp(test,['\W', denVpossible2{k}, '\W'])),
+%             found = 1;
+%         end
+%     end
+%     if found == 0,
+%         denV{end+1} = denVpossible2{k};
+%     end
+% end
+% allV = {numV{:} denV{:}};
+% try
+%     VmaxParameter = allV{1};
+% catch
+%     VmaxParameter = '';
+% end
+% return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/modelreduction/SBPDreducerateexpressions.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/modelreduction/SBPDreducerateexpressions.m
new file mode 100644
index 0000000000000000000000000000000000000000..d4b2ce952e65716d9487abb0de8a879e0f8bdfc8
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/modelreduction/SBPDreducerateexpressions.m
@@ -0,0 +1,151 @@
+function [projectout] = SBPDreducerateexpressions(project,modelindex,varargin)
+% SBPDreducerateexpressions: Function allowing the interactive and iterative
+% reduction of complex kinetic rate expressions. The function is directly
+% applicable to projects and will reduce a selected model of the project
+% using all or selected experiments from the project.
+% 
+% USAGE:
+% ======
+% [modelred] = SBPDreducerateexpressions(project)
+% [modelred] = SBPDreducerateexpressions(project, modelindex)
+% [modelred] = SBPDreducerateexpressions(project, modelindex, experimentindices)
+% [modelred] = SBPDreducerateexpressions(project, modelindex, experimentindices, options)
+%
+% project:              SBPDproject to consider for reduction
+% modelindex:           Index of the model to reduce
+% experimentindices:    Vector of indices of the experiments to consider
+%                       (time-points will be taken from the available
+%                       measurements. In case no measurements are available, 
+%                       they can be generated using the SBPDinsilicoexp function) 
+% options: structure containing options for the reduction algorithm:
+%        options.tol: tolerance for singularity detection (smallest SV)
+%        options.keeporigparameters: =0: do not keep original parameters
+%                                    =2: do always keep original parameters
+%                                    =1: keep original parameters only if
+%                                        it leads to fewer parameters
+%        options.numeratorweighting: =1: weight numerator terms and denumerator terms 
+%                                    such that numerators are kept
+%                                    =0: dont do any weighting
+%
+% DEFAULT VALUES:
+% ===============
+% options.tol:                  1e-5
+% options.keeporigparameters:   0
+% options.numeratorweighting:   0
+%
+% Output Arguments:
+% =================
+% project: new project in which the reduced model has been appended.
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+academicWarningSBPD
+
+
+disp('Please note that the reduction functionality is still a bit limited.');
+disp('Many special cases of models are not treated yet and thus a lot of errors might appear.');
+disp('It certainly does not work for models with varying compartment sizes, piecewise expressions');
+disp('in the rate expressions, etc. Just try it out and if it does not work correctly please');
+disp('contact me: henning@sbtoolbox2.org');
+disp(' ');
+disp('Press a key to start');
+pause;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% BASIC CHECK OF THE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBPDproject(project),
+    error('Input argument ''project'' is not an SBPDproject.');
+end
+projectstruct = SBPDstruct(project);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modelindex = 1;
+experimentindices = [1:length(projectstruct.experiments)];
+options = [];
+options.tol = 1e-5;
+options.keeporigparameters = 0;
+options.numeratorweighting = 0;
+if nargin == 1,
+    % do nothing
+elseif nargin == 2,
+    modelindex = varargin{1};
+elseif nargin == 3,
+    modelindex = varargin{1};
+    experimentindices = varargin{2};
+elseif nargin == 3,
+    modelindex = varargin{1};
+    experimentindices = varargin{2};
+    checkoptions = varargin{3};
+    if isfield(checkoptions,'tol'),
+        options.tol = checkoptions.tol;
+    end
+    if isfield(checkoptions,'keeporigparameters'),
+        options.keeporigparameters = checkoptions.keeporigparameters;
+    end
+    if isfield(checkoptions,'numeratorweighting'),
+        options.numeratorweighting = checkoptions.numeratorweighting;
+    end    
+else
+    error('Incorrect number of input arguments.');
+end
+if modelindex < 0 || modelindex > length(projectstruct.models),
+    error('''modelindex'' out of bounds.');
+end
+if min(experimentindices) < 1 || max(experimentindices) > length(projectstruct.experiments),
+    error('''experimentindices'' out of bounds.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PREPARE THE CALLING OF THE REDUCE FUNCTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+model = projectstruct.models{modelindex};
+experiments = {projectstruct.experiments(experimentindices).experiment};
+% get the timevectors for the experiments from the available measurement
+% data (if none available then error).
+timevectors = {};
+for e=1:length(projectstruct.experiments),
+    timevector = [];
+    for m=1:length(projectstruct.experiments(e).measurements),
+        tv = SBmeasurementdata(projectstruct.experiments(e).measurements{m});
+        timevector = [timevector; tv];
+    end
+    timevector = sort(unique(timevector));
+    if isempty(timevector),
+        % no measurements present
+        error('No measurement data present for experiment ''%d''. Could not determine timevector.\nUse SBPDinsilicoexpproj to generate insilico data with realistic timevector.',e);
+    end
+    timevectors{e} = timevector;
+end
+% Just no extravariables
+extravariables = {};
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONVERT RATE FUNCTIONS TO RATE FORMULAS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modelstruct = SBstruct(model);
+for k=1:length(modelstruct.reactions),
+    modelstruct.reactions(k).formula = getkinformulaSBPD(modelstruct.reactions(k).formula);
+end
+model = SBmodel(modelstruct);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PERFORM THE REDUCTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+disp('Starting reduction ...');
+modelred = SBredallreac(model,experiments,timevectors,options,extravariables);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ADD REDUCED MODEL TO THE PROJECT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+disp('Adding reduced model to the project ...');
+mrs = struct(modelred);
+mrs.name = [mrs.name '_reduced'];
+modelred = SBmodel(mrs);
+projectout = SBPDupdatemodel(project,modelred);
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/SBPDanalyzeresiduals.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/SBPDanalyzeresiduals.m
new file mode 100644
index 0000000000000000000000000000000000000000..3054320cc7fdb1a58e0b337a6e4687740168aff6
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/SBPDanalyzeresiduals.m
@@ -0,0 +1,307 @@
+function [varargout] = SBPDanalyzeresiduals(project,varargin)
+% SBPDanalyzeresiduals: Determines and analyzes the residuals for a 
+% given project. The function either returns the residuals and 
+% corresponding analysis information or plots the results.
+%
+% The residuals are statistically tested with the Null Hypothesis 
+% that they are normal with unspecified mean and variance. Currently, the
+% means are not tested agains the hypothesis that they have all the
+% properties of white noise. Furthermore, the autocorrelations of the
+% (mean-free) residuals are calculated. 
+%
+% USAGE:
+% ======
+% SBPDanalyzeresiduals(project)
+% SBPDanalyzeresiduals(project,modelindex)
+% SBPDanalyzeresiduals(project,estimation)
+% SBPDanalyzeresiduals(project,modelindex,alpha)
+% SBPDanalyzeresiduals(project,estimation,alpha)
+% [output] = SBPDanalyzeresiduals(project)
+% [output] = SBPDanalyzeresiduals(project,modelindex)
+% [output] = SBPDanalyzeresiduals(project,estimation)
+% [output] = SBPDanalyzeresiduals(project,modelindex,alpha)
+% [output] = SBPDanalyzeresiduals(project,estimation,alpha)
+%
+% project: SBPDproject to determine the residuals for.
+% modelindex: The index of the model in the project to use for residual
+%   determination. 
+% estimation: Same structure as used for parameter estimation
+%   (SBPDparameterestimation), defining the experiments to
+%   take into account. Additionally, if defined the timescalingFlag is
+%   taken into account.
+% alpha: The significance level for the test of the individual residuals
+%   against the Null Hypothesis that they are normally distributed.
+%
+% DEFAULT VALUES:
+% ===============
+% modelindex: 1
+% estimation: all experiments and measurements are taken into account
+% alpha = 0.05
+%
+% Output Arguments:
+% =================
+% If no output argument is specified, the residuals and
+% additional analysis information is plotted using the SBplot GUI, allowing
+% to also consider the FFT and the autocorrelation of the residuals.
+% Otherwise, the results are returned as a structure with the following
+% fields: 
+%
+% output(e).name: Name of the e-th experiment 
+% output(e).measurement: Results for the measurements in the e-th experiment
+% 
+% output(e).measurement(m).name: Name of the m-th measurement in the e-th experiment
+% output(e).measurement(m).components: Names of the measured components for
+%   which the residuals have been determined.
+% output(e).measurement(m).time: Timevector for the measurement
+% output(e).measurement(m).timescalingFlag: Value of the timescalingFlag
+%   used for the analysis. This flag can be defined via the estimation
+%   input argument. Hint: Keep it either on the same value as for parameter
+%   estimation or set it to zero.
+% output(e).measurement(m).residuals: Matrix with residuals (weighted
+%   according to the timescalingFlag setting). Rows correspond to
+%   time-points and columns to the measured components (same order as 
+%   in output(e).measurement(m).components).
+% output(e).measurement(m).pValue: are the p-values corresponding to each
+%   component residual. A pvalue is the probability of observing the given
+%   result (residuals) by chance given that the null hypothesis (residuals
+%   normally distributed) is true. Small values of  pValue cast doubt on
+%   the validity of the null hypothesis. 
+% output(e).measurement(m).alpha: The significance level for the test of
+%   the individual residuals against the Null Hypothesis that they are
+%   normally distributed. (Same value as input argument "alpha" or default
+%   setting).
+% output(e).measurement(m).H: Result of the hypothesis test for each
+%   component residuals. H=0 (alpha<pValue) => Null Hypothesis accepted,
+%   H=1 (alpha>=pValue) => Null Hypothesis rejected.
+% output(e).measurement(m).autocorrelation_Rxx: Normalized autocorrelations
+%   of the (mean-free) residuals. One column per residual.
+% output(e).measurement(m).autocorrelation_lag: The lags are useful for
+%   plotting the Rxx results.
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+% Force SBplot not to remove the zero frequency component for the fourier
+% analysis of the residuals
+global doRemoveZeroComponentFlag
+doRemoveZeroComponentFlag = 0;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% BASIC CHECK OF THE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBPDproject(project),
+    error('Input argument ''project'' is not an SBPDproject.');
+end
+projectstruct = SBPDstruct(project);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modelindex = 1;
+experimentindices = 1:length(projectstruct.experiments);
+alpha = 0.05;
+displayFlag = 0;        % not changed
+scalingFlag = 0;        % not changed
+timescalingFlag = 0;    % this is used if defined
+if nargin < 1 || nargin > 3,
+    error('Incorrect number of input arguments.');
+end
+if nargin >= 2,
+    if isstruct(varargin{1}),
+        estimation = varargin{1};
+        try modelindex = estimation.modelindex; catch, end
+        try experimentindices = estimation.experiments.indices; catch, end
+        try timescalingFlag = estimation.timescalingFlag; catch, end
+    else
+        modelindex = varargin{1};
+    end
+end
+if nargin >= 3,
+    alpha = varargin{2};
+end
+
+% try to get the integrator options from the estimation structure.
+% otherwise use default options
+try OPTIONS = estimation.integrator.options; catch, OPTIONS = []; end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS EXPERIMENT AND MEASUREMENT INFORMATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+model = projectstruct.models{modelindex};
+% HANDLE NON-NUMERIC INITIAL CONDITIONS just by replacing them
+% + warning ... as user feedback
+if ~hasonlynumericICsSB(model),
+    model = SBconvertNonNum2NumIC(model);
+    disp('Warning: The model contains non-numeric initial conditions. For this analysis these are replaced');
+    disp('by numeric initial conditions, determined from the non-numeric ones.');
+end
+experiments = projectstruct.experiments(experimentindices);
+work = getexpmeasinfoSBPD(model,modelindex,experiments,experimentindices,displayFlag,scalingFlag,timescalingFlag);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Simulate all experiments and add results to work structure
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for exp=1:length(work),
+    mexmodel = work(exp).model;
+    timevector = work(exp).timevector;
+    simdata = SBPDsimulate(mexmodel, timevector,[],[],[],OPTIONS);
+    work(exp).statevalues = simdata.statevalues;
+    work(exp).variablevalues = simdata.variablevalues;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine the residuals for each experiment and each measurement
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+residuals = [];
+for exp=1:length(work),
+    experiment = work(exp);
+    residuals(exp).name = ['Residuals for: ' experiment.experimentname];
+    AllRxx = [];
+    for meas=1:length(experiment.measurement),
+        measurement = experiment.measurement(meas);
+        timevectorindices = measurement.timevectorindices;
+        timevector = experiment.timevector(timevectorindices);
+        timescaling = measurement.timescaling(:);
+        % states
+        stateindices = measurement.stateindices;
+        if ~isempty(stateindices),
+            simstates = experiment.statevalues(timevectorindices,stateindices);
+            stateresiduals = measurement.statereferences - simstates;
+            statenames = measurement.statenames;
+        else
+            stateresiduals = [];
+            statenames = {};
+        end
+        % variables
+        variableindices = measurement.variableindices;
+        if ~isempty(variableindices),
+            simvariables = experiment.variablevalues(timevectorindices,variableindices);
+            variableresiduals = measurement.variablereferences - simvariables;
+            variablenames = measurement.variablenames;
+        else
+            variableresiduals = [];
+            variablenames = {};
+        end
+        values = [stateresiduals variableresiduals];
+        % apply the time scaling  
+        values = values.*timescaling(:,ones(1,size(values,2)));
+        % determine autocorrelations of residuals
+        allRxx = [];
+        allLag = [];
+        indexNaNlater = [];
+        for k=1:size(values,2),
+            % get values to resample and analyze
+            x1 = values(:,k);
+            t1 = timevector;
+            % remove NaNs
+            nanindex = find(isnan(x1));
+            x1(nanindex) = [];
+            t1(nanindex) = [];
+            % determine the sampling time (half the min size for finer resolution)
+            deltaT = min(t1(2:end)-t1(1:end-1))/2;
+            if ~isempty(x1),
+                [x2,t2] = resampleSB(t1,x1,deltaT,'linear');
+                x2 = x2-mean(x2); % make mean free
+                [Rxx,lag] = xcorrSB(x2,x2,length(x2)-1,'coeff');
+            else
+                lag = [];
+                Rxx = [];
+                indexNaNlater = [indexNaNlater k];
+            end
+            allLag = [allLag lag(:)];
+            allRxx = [allRxx Rxx(:)];
+        end
+        % handle indexNaNlater (insert columns of NaN values)
+        ncoltot = size(allRxx,2) + length(indexNaNlater);
+        distribindices = setdiff([1:ncoltot],indexNaNlater);
+        AllLag = allLag(:,1);
+        AllRxx(:,distribindices) = allRxx;
+        AllRxx(:,indexNaNlater) = NaN*ones(size(AllLag,1),length(indexNaNlater));
+        % add to residuals
+        residuals(exp).measurement(meas).name = ['Residuals for: ' measurement.name];
+        residuals(exp).measurement(meas).components = {statenames{:} variablenames{:}};
+        residuals(exp).measurement(meas).time = timevector;        
+        residuals(exp).measurement(meas).timescalingFlag = timescalingFlag;
+        residuals(exp).measurement(meas).residuals = values;
+        % do a statistical test to check if residuals are white
+        H = []; pValue = [];
+        for k=1:size(values,2),
+            vector = values(:,k);
+            vector(find(isnan(vector))) = [];
+            if length(vector) >= 3,
+                [H(k), pValue(k)] = swtestSB(vector,alpha,0);
+            else
+                H(k) = NaN;
+                pValue(k) = NaN;
+            end
+        end
+        residuals(exp).measurement(meas).pValue = pValue;
+        residuals(exp).measurement(meas).alpha = alpha;
+        residuals(exp).measurement(meas).H = H;
+        % add also the autocorrelation results
+        residuals(exp).measurement(meas).autocorrelation_Rxx = AllRxx;
+        residuals(exp).measurement(meas).autocorrelation_lag = AllLag;
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle the output
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargout == 0,
+    % Plot the results
+
+    % Prepare the data structures
+    datastructs = {};
+    for exp=1:length(residuals),
+        for meas=1:length(residuals(exp).measurement),
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Time series of residuals
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+            nameexp = residuals(exp).name;
+            namemeas = residuals(exp).measurement(meas).name;
+            names = residuals(exp).measurement(meas).components;
+            time = residuals(exp).measurement(meas).time(:);
+            values = residuals(exp).measurement(meas).residuals;
+            name = sprintf('Residuals for EXPERIMENT: %s, MEASUREMENT: %s',strrep(nameexp,'_',' '),strrep(namemeas,'_',' '));
+            % construct legend using the H values
+            H = residuals(exp).measurement(meas).H;
+            pValue = residuals(exp).measurement(meas).pValue;
+            legend = {};
+            for k=1:length(names),
+                if ~isnan(H(k)),
+                    if H(k) == 0,
+                        legend{k} = sprintf('%s (pV: %1.2g, H0 accepted with significance %g)',names{k},pValue(k),alpha);
+                    else
+                        legend{k} = sprintf('%s (pV: %1.2g, H0 rejected with significance %g)',names{k},pValue(k),alpha);
+                    end
+                else
+                    legend{k} = sprintf('%s (no data)',names{k});
+                end
+            end
+            datastructs{end+1} = createdatastructSBplotSB(time,values,names,legend,'o-',name);
+        end
+    end
+    % Do the plotting
+    text = '';
+    for k=1:length(datastructs),
+        text = sprintf('%sdatastructs{%d}, ',text,k);
+    end
+    text = text(1:end-2);
+    eval(sprintf('SBplot(%s)',text))
+else
+    varargout{1} = residuals;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DELETE MEX MODELS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+global compiledExpModelsSBPDgui % if not empty then models are precompiled and should not be deleted
+if isempty(compiledExpModelsSBPDgui),
+    clear mex
+    for e=1:length(work),
+        delete(work(e).mexfullpath);
+    end
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/SBPDmanualtuningGUI/SBPDmanualtuning.fig b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/SBPDmanualtuningGUI/SBPDmanualtuning.fig
new file mode 100644
index 0000000000000000000000000000000000000000..3a060c1a44ec593f147c618b72b0fbdb3a3e58d9
Binary files /dev/null and b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/SBPDmanualtuningGUI/SBPDmanualtuning.fig differ
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/SBPDmanualtuningGUI/SBPDmanualtuning.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/SBPDmanualtuningGUI/SBPDmanualtuning.m
new file mode 100644
index 0000000000000000000000000000000000000000..69963e0512d1bbbcdc6ec88707086dd7c1385cbf
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/SBPDmanualtuningGUI/SBPDmanualtuning.m
@@ -0,0 +1,1858 @@
+function varargout = SBPDmanualtuning(varargin)
+% SBPDmanualtuning: Allows to compare simulated experiments data to
+% measurements and perform manual parameter tuning. Additionally it is
+% possible to run simulations of selected experiments directly from the 
+% SBPDmanualtuning window, allowing for a deeper analysis of what happens 
+% in the system.
+%
+% USAGE:
+% ======
+% [project] = SBPDmanualtuning(project)
+% [project] = SBPDmanualtuning(project,modelindex)
+% [project] = SBPDmanualtuning(project,estimation)
+% [project] = SBPDmanualtuning(project,modelindex,additionalcomponents)
+% [project] =
+% SBPDmanualtuning(project,estimation,additionalcomponents)
+%
+% project: SBPDproject to tune manually. 
+% modelindex: The index of the model in the project to use for tuning.
+% estimation: Same structure as used for parameter estimation
+%   (SBPDparameterestimation), defining the (global) parameters and their
+%   bounds, and modelindex.
+% additionalcomponents: Cell-array containing the names of components
+%   (states or variables) that have not been measured but which should also
+%   be plotted in SBPDmanualtuning.
+%
+% DEFAULT VALUES:
+% ===============
+% modelindex: 1:n, where n is the number of the models in the project. This
+%             means that tuning is carried out for all models in the
+%             project if modelindex is not given
+% estimation: all global parameters and all models, bounds: nominalvalue*[0.01 100]
+% additionalcomponents: {} (none)
+%
+% Output Arguments:
+% =================
+% The manually tuned project is given back.
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INITIALIZATION CODE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Begin initialization code - DO NOT EDIT
+gui_Singleton = 1;
+gui_State = struct('gui_Name',       mfilename, ...
+                   'gui_Singleton',  gui_Singleton, ...
+                   'gui_OpeningFcn', @SBPDmanualtuning_OpeningFcn, ...
+                   'gui_OutputFcn',  @SBPDmanualtuning_OutputFcn, ...
+                   'gui_LayoutFcn',  [] , ...
+                   'gui_Callback',   []);
+if nargin && ischar(varargin{1})
+    gui_State.gui_Callback = str2func(varargin{1});
+end
+if nargout
+    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
+else
+    gui_mainfcn(gui_State, varargin{:});
+end
+% End initialization code - DO NOT EDIT
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INTERFACE FUNCTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% --- Executes just before SBPDmanualtuning is made visible.
+function SBPDmanualtuning_OpeningFcn(hObject, eventdata, handles, varargin)
+academicWarningSBPD
+% Handle variable input arguments
+estimation = [];
+if nargin >= 4,
+    project = varargin{1};
+    if ~isSBPDproject(project), error('Input argument is not an SBPDproject.'); end
+    projectstruct = SBPDstruct(project);
+    modelindex = [1:length(projectstruct.models)];
+end
+if nargin >= 5,
+    if ~isstruct(varargin{2}),
+        modelindex = varargin{2};
+    else
+        estimation = varargin{2};
+        modelindex = 1; % default value
+        try modelindex = estimation.modelindex; catch, end
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        % HANDLE PARAM DATA MATRIX
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        if iscell(estimation.parameters),
+            if ~isempty(estimation.parameters),
+                paramnames = estimation.parameters(:,1);
+                paramlowbounds = cell2mat(estimation.parameters(:,2));
+                paramhighbounds = cell2mat(estimation.parameters(:,3));
+            else
+                paramnames = {};
+                paramlowbounds = [];
+                paramhighbounds = [];
+            end
+            estimation.parameters = [];
+            estimation.parameters.names = paramnames;
+            estimation.parameters.lowbounds = paramlowbounds;
+            estimation.parameters.highbounds = paramhighbounds;
+        end
+        if iscell(estimation.parameterslocal),
+            if ~isempty(estimation.parameterslocal),
+                paramnameslocal = estimation.parameterslocal(:,1);
+                paramlowboundslocal = cell2mat(estimation.parameterslocal(:,2));
+                paramhighboundslocal = cell2mat(estimation.parameterslocal(:,3));
+            else
+                paramnameslocal = {};
+                paramlowboundslocal = [];
+                paramhighboundslocal = [];
+            end
+            estimation.parameterslocal = [];
+            estimation.parameterslocal.names = paramnameslocal;
+            estimation.parameterslocal.lowbounds = paramlowboundslocal;
+            estimation.parameterslocal.highbounds = paramhighboundslocal;
+        end
+        if iscell(estimation.initialconditions),
+            if ~isempty(estimation.initialconditions),
+                icnames = estimation.initialconditions(:,1);
+                iclowbounds = cell2mat(estimation.initialconditions(:,2));
+                ichighbounds = cell2mat(estimation.initialconditions(:,3));
+            else
+                icnames = {};
+                iclowbounds = [];
+                ichighbounds = [];
+            end
+            estimation.initialconditions = [];
+            estimation.initialconditions.names = icnames;
+            estimation.initialconditions.lowbounds = iclowbounds;
+            estimation.initialconditions.highbounds = ichighbounds;
+        end
+    end
+end
+if nargin >= 6,
+    additionalPlotNames = varargin{3};
+else 
+    additionalPlotNames = {};
+end
+if nargin<3 || nargin>6,
+    error('Incorrect number of input arguments.');
+end
+
+% get integrator options
+try
+    OPTIONS = estimation.integrator.options; 
+catch
+    OPTIONS = [];
+end
+
+handles.modelindex = modelindex;
+handles.projectstruct = struct(project);
+handles.estimation = estimation;
+handles.integratoroptions = OPTIONS;
+handles.boundsaxis = NaN;
+set(handles.bounds,'String','Nominal');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine ALL parameters changed by events (in all models and in all experiments)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Parameters that are changed by events are not allowed to be changed by the user during tuning
+pnames = {};
+for k=1:length(handles.projectstruct.models),
+    model = handles.projectstruct.models{k};
+    ms = struct(model);
+    pnames = {pnames{:} ms.parameters.name};
+end
+pnames = unique(pnames);
+apnames = {};
+% MODELS FIRST:
+for k1=1:length(handles.projectstruct.models),
+    model = handles.projectstruct.models{k1};
+    ms = struct(model);
+    % collect all assignment variables in all events that are parameters
+    for k=1:length(ms.events),
+        for k2=1:length(ms.events(k).assignment),
+            vname = ms.events(k).assignment(k2).variable;
+            if ~isempty(strmatchSB(vname,pnames,'exact')),
+                apnames{end+1} = vname;
+            end
+        end
+    end
+end
+% EXPERIMENTS SECOND:
+for k1=1:length(handles.projectstruct.experiments),
+    experiment = handles.projectstruct.experiments(k1).experiment;
+    es = struct(experiment);
+    % collect all assignment variables in all events that are parameters
+    for k=1:length(es.stateevents),
+        for k2=1:length(es.stateevents(k).assignment),
+            vname = es.stateevents(k).assignment(k2).variable;
+            if ~isempty(strmatchSB(vname,pnames,'exact')),
+                apnames{end+1} = vname;
+            end
+        end
+    end
+end
+% apnames are the names of the parameters that are changed by events.
+% these are not allowed to be tuned
+apnames = unique(apnames);
+% Save the info in the 
+handles.event_param_names = apnames;
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% handle experimentindices
+try 
+    experimentindices = estimation.experiments.indices; 
+catch
+    experimentindices = [1:length(handles.projectstruct.experiments)];
+end
+handles.nrsliders = 7;  % not really used everywhere yet
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ADD EXTRA PLOT NAMES TO THE MEASUREMENT STRUCTURES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% additionally save the unchanged project structure for output
+handles.saveORIGprojectstruct = handles.projectstruct;
+for e=1:length(handles.projectstruct.experiments),
+    measurements = handles.projectstruct.experiments(e).measurements;
+    for m=1:length(measurements),
+        msm = struct(measurements{m});
+        for k=1:length(additionalPlotNames),
+            % check if additional plot name is already present
+            if isempty(strmatchSB(additionalPlotNames{k},{msm.data(1:end).name},'exact')),
+                msm.data(end+1).name = additionalPlotNames{k};
+                msm.data(end).notes = 'User-selected additional component for plotting';
+                msm.data(end).values = NaN*ones(length(msm.time),1);
+                msm.data(end).maxvalues = NaN*ones(length(msm.time),1);
+                msm.data(end).minvalues = NaN*ones(length(msm.time),1);
+            end
+        end
+        measurements{m} = SBmeasurement(msm);
+    end
+    handles.projectstruct.experiments(e).measurements = measurements;
+end
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK WHICH EXPERIMENTS DO NOT HAVE MEASUREMENT DATA ASSIGNED TO
+% THESE ARE SKIPPED FROM THE CONSIDERATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+text = '';
+useexperimentindices = [];
+for e=1:length(experimentindices),
+    if isempty(handles.projectstruct.experiments(experimentindices(e)).measurements),
+        text = sprintf('%sExperiment %d has no measurements assigned to ... not considered here.\n',text,experimentindices(e));
+    else
+        useexperimentindices = [useexperimentindices experimentindices(e)];
+    end
+end
+if ~isempty(text),
+    disp(text);
+end
+if isempty(useexperimentindices),
+    error('No measurements present in the project. No comparison possible.');
+end
+handles.experimentindices = useexperimentindices;
+handles.plotdata = initializePlotdata(handles.projectstruct,modelindex,handles);
+% set modelselection and choose first model
+set(handles.modelselection,'String',{handles.plotdata.model.name});
+set(handles.modelselection,'Value',1);
+% set experimentselection for first model and first experiment
+set(handles.experimentselection,'String',{handles.plotdata.model(1).experiment.name});
+set(handles.experimentselection,'Value',1);
+% set component selection
+set(handles.componentselection,'String',handles.plotdata.model(1).allmeascomponents);
+set(handles.componentselection,'Value',[1:length(handles.plotdata.model(1).allmeascomponents)]);
+% determine parameter data
+handles = getparamdata(handles);
+% set all parameter selection boxes with parameter names (model dependent)
+initializeParameterLists(handles);
+% select plottype
+handles.dataPlotType = 'plot';     
+% set errorbarflag to 1
+handles.errorbars = 1;
+% set legendflag to 1
+handles.legendflag = 1;
+% Initialize export figure handle and grid flag
+handles.exportFigureHandle = [];
+handles.grid = 0;
+% Doing a first plot
+doPlot(handles);
+% Choose default command line output for SBPDmanualtuning
+handles.output = hObject;
+% Update handles structure
+guidata(hObject, handles);
+uiwait;
+return
+
+% --- Outputs from this function are returned to the command line.
+function varargout = SBPDmanualtuning_OutputFcn(hObject, eventdata, handles) 
+% varargout  cell array for returning output args (see VARARGOUT);
+varargout{1} = handles.output;
+% delete temporary MEX models
+global compiledExpModelsSBPDgui % if not empty then models are precompiled and should not be deleted
+if isempty(compiledExpModelsSBPDgui),
+    clear mex
+    for m=1:length(handles.plotdata.model)
+        for e=1:length(handles.plotdata.model(m).experiment),
+            delete(handles.plotdata.model(m).experiment(e).mexfullpath);
+        end
+    end
+end
+% close the GUI
+delete(hObject);
+return
+
+% --- Closed by user
+function SBPDmanualtuning_CloseRequestFcn(hObject, eventdata, handles)
+exit_Callback(hObject, eventdata, handles)
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXIT SBPDmanualtuning CALLBACK
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function exit_Callback(hObject, eventdata, handles)
+    % construct the output (its just an updated SBPDproject in which the 
+    % manually tuned parametervalues are entered)
+    % FOR THIS USE THE SAVED ORIG PROJECT!
+    for k=1:length(handles.modelindex),
+        m = handles.modelindex(k);
+        % get model to update
+        model = handles.saveORIGprojectstruct.models{m};
+        % set manually tuned parameters
+        % take away the things that are no parameters
+        noParamIndices = strmatchSB('No Parameter',handles.parammodel(k).names,'exact');
+        paramIndices = setdiff([1:length(handles.parammodel(k).names)],noParamIndices);
+        paramnames = handles.parammodel(k).names(paramIndices);
+        paramvalues = handles.parammodel(k).values(paramIndices);
+        model = SBparameters(model,paramnames,paramvalues);
+        % add model to project
+        handles.saveORIGprojectstruct.models{m} = model;
+    end
+    handles.output = SBPDproject(handles.saveORIGprojectstruct);
+    % Update handles structure
+    guidata(hObject, handles);
+    uiresume;
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SIMULATION FUNCTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function handles=doSimAndPlot(handles)
+% get the parameter values to use for simulation
+m = get(handles.modelselection,'Value');
+%pv = handles.parammodel(m).values;
+% run through all experiments and perform them for the parameter settings
+for e = 1:length(handles.plotdata.model(m).experiment),
+    mexmodel = handles.plotdata.model(m).experiment(e).mexmodel;
+    timevector = handles.plotdata.model(m).experiment(e).timevector;
+    ic = handles.plotdata.model(m).experiment(e).initialconditions;
+    % take away the things that are no parameters
+    noParamIndices = strmatchSB('No Parameter',handles.parammodel(m).names,'exact');
+    paramIndices = setdiff([1:length(handles.parammodel(m).names)],noParamIndices);
+    paramnames = handles.parammodel(m).names(paramIndices);
+    paramvalues = handles.parammodel(m).values(paramIndices);
+    % construct parameter vector for simulation
+    pv = makeparamvecSBPD(mexmodel,paramnames,paramvalues);
+    try
+        tmin = timevector(1); tmax = timevector(end);
+        tvec = [tmin:(tmax-tmin)/1000:tmax];
+        simdata = feval(mexmodel,tvec,ic,pv,handles.integratoroptions);        
+    catch
+        simdata = [];
+        break;
+    end
+    stateindices = handles.plotdata.model(m).experiment(e).stateindices;
+    statevalues = simdata.statevalues(:,stateindices);
+    variableindices = handles.plotdata.model(m).experiment(e).variableindices;
+    variablevalues = simdata.variablevalues(:,variableindices);
+    handles.plotdata.model(m).experiment(e).componentvalues = [statevalues variablevalues];
+end
+if ~isempty(simdata),
+    doPlot(handles);
+else
+    errordlg('Parameter setting leads to error.');
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PLOT FUNCTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function doPlot(handles)
+colorvector = {'b','g','r','c','m','y','k'};
+% markervector = {'o','x','+','*','s','d','v','^','<','>','p','h'};
+warning off;
+% get the data to plot
+plotdata = handles.plotdata;
+m = get(handles.modelselection,'Value');
+eall = get(handles.experimentselection,'Value');
+callnames = get(handles.componentselection,'String');
+callselected = get(handles.componentselection,'Value');
+NTOTAL = length(eall);
+NROW = ceil(sqrt(NTOTAL));
+NCOL = ceil(NTOTAL/NROW);
+for sp = 1:NTOTAL,
+    e = eall(sp);
+    subplot(NROW,NCOL,sp,'Parent',handles.plotpanel);
+    edata = plotdata.model(m).experiment(e);
+    % general information
+    titletext = regexprep(edata.name,'_',' ');
+    xlabeltext = 'Time';
+    % simulated data information
+    sim_timevector = edata.timevector;
+    sim_componentnames = edata.componentnames;
+    sim_componentvalues = edata.componentvalues;
+    for k=1:length(edata.componentnames),
+        if isempty(strmatchSB(edata.componentnames{k},callnames(callselected),'exact')),
+            sim_componentvalues(:,k) = NaN;
+        end
+    end
+    % plot simulated data
+if ~isnan(handles.boundsaxis),
+    [sim_timevector,sim_componentvalues] = stripSmallerTimes(sim_timevector,sim_componentvalues,handles.boundsaxis(1));    
+end
+
+    for kplotsim=1:size(sim_componentvalues,2)
+        feval(handles.dataPlotType,sim_timevector,sim_componentvalues(:,kplotsim),'linewidth',2,'color',colorvector{mod(kplotsim-1,7)+1}); hold on;
+    end
+    
+    
+    % measured data information
+    for meas=1:length(edata.measurement),
+        meas_timevector = edata.measurement(meas).timevector;
+        meas_componentnames = edata.measurement(meas).componentnames;
+        meas_componentvalues = edata.measurement(meas).componentvalues;
+        meas_maxvalues = edata.measurement(meas).maxvalues;
+        meas_minvalues = edata.measurement(meas).minvalues;
+        for k=1:length(edata.measurement(meas).componentnames),
+            if isempty(strmatchSB(edata.measurement(meas).componentnames{k},callnames(callselected),'exact')),
+                meas_componentvalues(:,k) = NaN;
+                meas_maxvalues(:,k) = NaN;
+                meas_minvalues(:,k) = NaN;
+            end
+        end
+        % continue
+%         marker = markervector{mod(meas-1,length(markervector))+1};
+%         feval(handles.dataPlotType,meas_timevector,meas_componentvalues,['--' marker]); hold on;
+        color4meas = colorvector{mod(meas-1,length(colorvector))+1};
+if ~isnan(handles.boundsaxis),
+    [meas_timevector,meas_componentvalues] = stripSmallerTimes(meas_timevector,meas_componentvalues,handles.boundsaxis(1));   
+end
+
+        for kplotsim=1:size(meas_componentvalues,2)
+            feval(handles.dataPlotType,meas_timevector,meas_componentvalues(:,kplotsim),'*','linewidth',2,'color',colorvector{mod(kplotsim-1,7)+1}); hold on;
+        end
+
+        if handles.errorbars == 1 && strcmp(handles.dataPlotType,'plot'),
+            % plot error bounds
+            for k=1:length(meas_componentnames),
+                color = colorvector{mod(k-1,7)+1};
+%                 for k1 = 1:size(meas_timevector,1),
+                for k1 = 1:length(meas_timevector),
+if ~isnan(handles.boundsaxis),
+    if meas_timevector(k1) >= handles.boundsaxis(1),
+                    feval(handles.dataPlotType,[meas_timevector(k1),meas_timevector(k1)],[meas_minvalues(k1,k),meas_maxvalues(k1,k)],['.:',color]);
+    end
+else
+                    feval(handles.dataPlotType,[meas_timevector(k1),meas_timevector(k1)],[meas_minvalues(k1,k),meas_maxvalues(k1,k)],['.:',color]);
+end
+                end
+            end
+        end
+    end
+    hold off;
+    if handles.legendflag == 1,
+        hlhlx = legend(sim_componentnames);
+        set(hlhlx,'Interpreter','none');
+    end
+    hlhlx = title(titletext);
+    set(hlhlx,'Interpreter','none');
+    hlhlx = xlabel(xlabeltext);
+    set(hlhlx,'Interpreter','none');
+
+if ~isnan(handles.boundsaxis),
+    axis(handles.boundsaxis)
+end
+
+end
+
+
+return
+
+function [t,y] = stripSmallerTimes(t,y,minT)
+    indexdel = find(t<minT);
+    t(indexdel) = [];
+    y(indexdel,:) = [];
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine parameter data and save in handles structure
+% Only parameters that appear in all expmmexmodels are considered.
+% Furthermore, they need to have the same values (so that they are not
+% modified due to experimental settings)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function handles = getparamdata(handles)
+if isempty(handles.estimation),
+    for m = 1:length(handles.plotdata.model),
+        % get parameter names that appear in all expmexmodels
+        for e = 1:length(handles.plotdata.model(m).experiment),
+            model = handles.plotdata.model(m).experiment(e).mexmodel;
+            if e == 1,
+                parameters = feval(model,'parameters');
+            else
+                parameters = intersect(parameters, feval(model,'parameters'));
+            end
+        end
+        % keep only those parameters that have the same value (not changed by
+        % experiment or changed equally)
+        indexdelete = [];
+        for e = 1:length(handles.plotdata.model(m).experiment),
+            model = handles.plotdata.model(m).experiment(e).mexmodel;
+            if e == 1,
+                % first run just get the parametervalues
+                parametervalues = SBparameters(model,parameters);
+            else
+                % subsequent runs ... check if equal and get the indices of the
+                % non equal entries
+                pv = SBparameters(model,parameters);
+                indexdelete = unique([indexdelete(:)', find(pv(:)'~=parametervalues(:)')]);
+            end
+        end
+        indexkeep = setdiff([1:length(parameters)],indexdelete);
+        parameters = parameters(indexkeep);
+        % FINALLY ALSO REMOVE THE PARAMETERS THAT ARE CHANGED BY EVENTS DURING
+        % THE SIMULATION (DEFINED IN: handles.event_param_names)
+        parameters = setdiff(parameters,handles.event_param_names);
+        parametervalues = SBparameters(model,parameters);
+        % add param info to structure
+        handles.parammodel(m).names = parameters;
+        handles.parammodel(m).values = parametervalues;
+        handles.parammodel(m).startvalues = parametervalues;
+        max = 100*parametervalues;
+        max(find(max==0)) = 1;
+        handles.parammodel(m).max = max;
+        handles.parammodel(m).startmax = max;
+        handles.parammodel(m).min = 0.01*parametervalues;
+        handles.parammodel(m).startmin = 0.01*parametervalues;
+    end
+else
+    % add param info to structure
+    % directly from estimation structure (just one model possible)
+    model = handles.plotdata.model(1).experiment(1).mexmodel;
+    handles.parammodel.names = handles.estimation.parameters.names;
+    parametervalues = SBparameters(model,handles.parammodel.names);
+    handles.parammodel.values = parametervalues;
+    handles.parammodel.startvalues = parametervalues;
+    if ~isfield(handles.estimation.parameters,'lowbounds'),
+        handles.estimation.parameters.lowbounds = [];
+    end
+    if ~isfield(handles.estimation.parameters,'highbounds'),
+        handles.estimation.parameters.highbounds = [];
+    end
+    if isempty(handles.estimation.parameters.lowbounds),
+        min = 0.01*parametervalues;
+    else
+        min = handles.estimation.parameters.lowbounds;
+    end
+    if isempty(handles.estimation.parameters.highbounds),
+        max = 100*parametervalues;
+    else
+        max = handles.estimation.parameters.highbounds;
+    end
+    max(find(max==0)) = 1;
+    handles.parammodel.max = max;
+    handles.parammodel.startmax = max;
+    handles.parammodel.min = min;
+    handles.parammodel.startmin = min;
+end
+% if fewer parameters than handles.nrsliders then add dummy ones
+if length(parametervalues) < handles.nrsliders,
+    for k=1:(handles.nrsliders-length(parametervalues)),
+        handles.parammodel.names{end+1} = 'No Parameter';
+        handles.parammodel.values(end+1) = NaN;
+        handles.parammodel.startvalues(end+1) = NaN;
+        handles.parammodel.max(end+1) = NaN;
+        handles.parammodel.startmax(end+1) = NaN;
+        handles.parammodel.min(end+1) = NaN;
+        handles.parammodel.startmin(end+1) = NaN;
+    end
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Initialize parameter lists
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [] = initializeParameterLists(handles,varargin)
+if nargin == 1,
+    i1 = 1;
+    i2 = 2;
+    i3 = 3;
+    i4 = 4;
+    i5 = 5;
+    i6 = 6;
+    i7 = 7;
+elseif nargin == 2,
+    if strcmp(varargin{1},'resetall'),
+        i1 = 1;
+        i2 = 2;
+        i3 = 3;
+        i4 = 4;
+        i5 = 5;
+        i6 = 6;
+        i7 = 7;
+    else
+        i1 = get(handles.manualparam1,'Value');
+        i2 = get(handles.manualparam2,'Value');
+        i3 = get(handles.manualparam3,'Value');
+        i4 = get(handles.manualparam4,'Value');
+        i5 = get(handles.manualparam5,'Value');
+        i6 = get(handles.manualparam6,'Value');
+        i7 = get(handles.manualparam7,'Value');
+    end
+end
+
+m = get(handles.modelselection,'Value');
+% get the models parameters and values
+parameters = handles.parammodel(m).names;
+parametervalues = handles.parammodel(m).values;
+parammax = handles.parammodel(m).max;
+parammin = handles.parammodel(m).min;
+% set the 7 parameter lists (adjust list of parameters)
+nrtakeaway = length(strmatchSB('No Parameter',parameters,'exact'));
+if nrtakeaway > 0,
+    endindex = handles.nrsliders-nrtakeaway;
+    set(handles.manualparam1,'String',parameters(1:endindex));
+    set(handles.manualparam2,'String',parameters(1:endindex));
+    set(handles.manualparam3,'String',parameters(1:endindex));
+    set(handles.manualparam4,'String',parameters(1:endindex));
+    set(handles.manualparam5,'String',parameters(1:endindex));
+    set(handles.manualparam6,'String',parameters(1:endindex));
+    set(handles.manualparam7,'String',parameters(1:endindex));
+else
+    set(handles.manualparam1,'String',parameters);
+    set(handles.manualparam2,'String',parameters);
+    set(handles.manualparam3,'String',parameters);
+    set(handles.manualparam4,'String',parameters);
+    set(handles.manualparam5,'String',parameters);
+    set(handles.manualparam6,'String',parameters);
+    set(handles.manualparam7,'String',parameters);
+end    
+% set selected values
+set(handles.manualparam1,'Value',i1);
+set(handles.manualparam2,'Value',i2);
+set(handles.manualparam3,'Value',i3);
+set(handles.manualparam4,'Value',i4);
+set(handles.manualparam5,'Value',i5);
+set(handles.manualparam6,'Value',i6);
+set(handles.manualparam7,'Value',i7);
+% set current parameter values
+set(handles.value1,'String',parametervalues(i1));
+set(handles.value2,'String',parametervalues(i2));
+set(handles.value3,'String',parametervalues(i3));
+set(handles.value4,'String',parametervalues(i4));
+set(handles.value5,'String',parametervalues(i5));
+set(handles.value6,'String',parametervalues(i6));
+set(handles.value7,'String',parametervalues(i7));
+% set max and min values per default to *100 / *0.01
+set(handles.manualmax1,'String',parammax(i1));
+set(handles.manualmax2,'String',parammax(i2));
+set(handles.manualmax3,'String',parammax(i3));
+set(handles.manualmax4,'String',parammax(i4));
+set(handles.manualmax5,'String',parammax(i5));
+set(handles.manualmax6,'String',parammax(i6));
+set(handles.manualmax7,'String',parammax(i7));
+set(handles.manualmin1,'String',parammin(i1));
+set(handles.manualmin2,'String',parammin(i2));
+set(handles.manualmin3,'String',parammin(i3));
+set(handles.manualmin4,'String',parammin(i4));
+set(handles.manualmin5,'String',parammin(i5));
+set(handles.manualmin6,'String',parammin(i6));
+set(handles.manualmin7,'String',parammin(i7));
+% set slider min max and value
+set(handles.manualslider1,'Max',101);
+set(handles.manualslider2,'Max',101);
+set(handles.manualslider3,'Max',101);
+set(handles.manualslider4,'Max',101);
+set(handles.manualslider5,'Max',101);
+set(handles.manualslider6,'Max',101);
+set(handles.manualslider7,'Max',101);
+set(handles.manualslider1,'Min',1);
+set(handles.manualslider2,'Min',1);
+set(handles.manualslider3,'Min',1);
+set(handles.manualslider4,'Min',1);
+set(handles.manualslider5,'Min',1);
+set(handles.manualslider6,'Min',1);
+set(handles.manualslider7,'Min',1);
+% construct vectors
+if parammin(i1) > 0,
+    vector1 = logspace(log(parammin(i1))/log(10),log(parammax(i1))/log(10),101);
+else
+    vector1 = [parammin(i1):(parammax(i1)-parammin(i1))/100:parammax(i1)];
+end
+if parammin(i2) > 0,
+    vector2 = logspace(log(parammin(i2))/log(10),log(parammax(i2))/log(10),101);
+else
+    vector2 = [parammin(i2):(parammax(i2)-parammin(i2))/100:parammax(i2)];
+end
+if parammin(i3) > 0,
+    vector3 = logspace(log(parammin(i3))/log(10),log(parammax(i3))/log(10),101);
+else
+    vector3 = [parammin(i3):(parammax(i3)-parammin(i3))/100:parammax(i3)];
+end
+if parammin(i4) > 0,
+    vector4 = logspace(log(parammin(i4))/log(10),log(parammax(i4))/log(10),101);
+else
+    vector4 = [parammin(i4):(parammax(i4)-parammin(i4))/100:parammax(i4)];
+end
+if parammin(i5) > 0,
+    vector5 = logspace(log(parammin(i5))/log(10),log(parammax(i5))/log(10),101);
+else
+    vector5 = [parammin(i5):(parammax(i5)-parammin(i5))/100:parammax(i5)];
+end
+if parammin(i6) > 0,
+    vector6 = logspace(log(parammin(i6))/log(10),log(parammax(i6))/log(10),101);
+else
+    vector6 = [parammin(i6):(parammax(i6)-parammin(i6))/100:parammax(i6)];
+end
+if parammin(i7) > 0,
+    vector7 = logspace(log(parammin(i7))/log(10),log(parammax(i7))/log(10),101);
+else
+    vector7 = [parammin(i7):(parammax(i7)-parammin(i7))/100:parammax(i7)];
+end
+% set sliders
+[dummy,index] = min(abs(vector1-parametervalues(i1)));
+set(handles.manualslider1,'Value',index);
+[dummy,index] = min(abs(vector2-parametervalues(i2)));
+set(handles.manualslider2,'Value',index);
+[dummy,index] = min(abs(vector3-parametervalues(i3)));
+set(handles.manualslider3,'Value',index);
+[dummy,index] = min(abs(vector4-parametervalues(i4)));
+set(handles.manualslider4,'Value',index);
+[dummy,index] = min(abs(vector5-parametervalues(i5)));
+set(handles.manualslider5,'Value',index);
+[dummy,index] = min(abs(vector6-parametervalues(i6)));
+set(handles.manualslider6,'Value',index);
+[dummy,index] = min(abs(vector7-parametervalues(i7)));
+set(handles.manualslider7,'Value',index);
+% set slider steps
+set(handles.manualslider1,'SliderStep',[0.01 0.01]);
+set(handles.manualslider2,'SliderStep',[0.01 0.01]);
+set(handles.manualslider3,'SliderStep',[0.01 0.01]);
+set(handles.manualslider4,'SliderStep',[0.01 0.01]);
+set(handles.manualslider5,'SliderStep',[0.01 0.01]);
+set(handles.manualslider6,'SliderStep',[0.01 0.01]);
+set(handles.manualslider7,'SliderStep',[0.01 0.01]);
+% set Enable to off for the elements
+nrtakeaway = length(strmatchSB('No Parameter',parameters,'exact'));
+if nrtakeaway >= 7,
+    set(handles.manualslider1,'Enable','off');
+    set(handles.manualmax1,'Enable','off');
+    set(handles.manualmin1,'Enable','off');
+    set(handles.manualparam1,'Enable','off');
+end
+if nrtakeaway >= 6,
+    set(handles.manualslider2,'Enable','off');
+    set(handles.manualmax2,'Enable','off');
+    set(handles.manualmin2,'Enable','off');
+    set(handles.manualparam2,'Enable','off');
+end
+if nrtakeaway >= 5,
+    set(handles.manualslider3,'Enable','off');
+    set(handles.manualmax3,'Enable','off');
+    set(handles.manualmin3,'Enable','off');
+    set(handles.manualparam3,'Enable','off');
+end
+if nrtakeaway >= 4,
+    set(handles.manualslider4,'Enable','off');
+    set(handles.manualmax4,'Enable','off');
+    set(handles.manualmin4,'Enable','off');
+    set(handles.manualparam4,'Enable','off');
+end
+if nrtakeaway >= 3,
+    set(handles.manualslider5,'Enable','off');
+    set(handles.manualmax5,'Enable','off');
+    set(handles.manualmin5,'Enable','off');
+    set(handles.manualparam5,'Enable','off');
+end
+if nrtakeaway >= 2,
+    set(handles.manualslider6,'Enable','off');
+    set(handles.manualmax6,'Enable','off');
+    set(handles.manualmin6,'Enable','off');
+    set(handles.manualparam6,'Enable','off');
+end
+if nrtakeaway >= 1,
+    set(handles.manualslider7,'Enable','off');
+    set(handles.manualmax7,'Enable','off');
+    set(handles.manualmin7,'Enable','off');
+    set(handles.manualparam7,'Enable','off');
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Slider1 handling function
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function slider1_Callback(hObject, eventdata, handles)
+% get slider settings
+v = ceil(get(handles.manualslider1,'Value'));                       %%%
+% get min max settings
+maxV = str2double(get(handles.manualmax1,'String'));                %%%
+minV = str2double(get(handles.manualmin1,'String'));                %%%
+% construct vectors
+if minV > 0,
+    vector = logspace(log(minV)/log(10),log(maxV)/log(10),101);
+else
+    vector = [minV:(maxV-minV)/100:maxV];
+end
+% get paramvalues
+value = vector(v);
+% set parameter value
+set(handles.value1,'String',value);                                 %%%
+% update parameter information structure in handles with new values
+m = get(handles.modelselection,'Value');
+pindex = get(handles.manualparam1,'Value');                         %%%
+handles.parammodel(m).values(pindex) = value;
+% sim and plot
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Slider2 handling function
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function slider2_Callback(hObject, eventdata, handles)
+% get slider settings
+v = ceil(get(handles.manualslider2,'Value'));                       %%%
+% get min max settings
+maxV = str2double(get(handles.manualmax2,'String'));                %%%
+minV = str2double(get(handles.manualmin2,'String'));                %%%
+% construct vectors
+if minV > 0,
+    vector = logspace(log(minV)/log(10),log(maxV)/log(10),101);
+else
+    vector = [minV:(maxV-minV)/100:maxV];
+end
+% get paramvalues
+value = vector(v);
+% set parameter value
+set(handles.value2,'String',value);                                 %%%
+% update parameter information structure in handles with new values
+m = get(handles.modelselection,'Value');
+pindex = get(handles.manualparam2,'Value');                         %%%
+handles.parammodel(m).values(pindex) = value;
+% sim and plot
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Slider3 handling function
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function slider3_Callback(hObject, eventdata, handles)
+% get slider settings
+v = ceil(get(handles.manualslider3,'Value'));                       %%%
+% get min max settings
+maxV = str2double(get(handles.manualmax3,'String'));                %%%
+minV = str2double(get(handles.manualmin3,'String'));                %%%
+% construct vectors
+if minV > 0,
+    vector = logspace(log(minV)/log(10),log(maxV)/log(10),101);
+else
+    vector = [minV:(maxV-minV)/100:maxV];
+end
+% get paramvalues
+value = vector(v);
+% set parameter value
+set(handles.value3,'String',value);                                 %%%
+% update parameter information structure in handles with new values
+m = get(handles.modelselection,'Value');
+pindex = get(handles.manualparam3,'Value');                         %%%
+handles.parammodel(m).values(pindex) = value;
+% sim and plot
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Slider4 handling function
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function slider4_Callback(hObject, eventdata, handles)
+% get slider settings
+v = ceil(get(handles.manualslider4,'Value'));                       %%%
+% get min max settings
+maxV = str2double(get(handles.manualmax4,'String'));                %%%
+minV = str2double(get(handles.manualmin4,'String'));                %%%
+% construct vectors
+if minV > 0,
+    vector = logspace(log(minV)/log(10),log(maxV)/log(10),101);
+else
+    vector = [minV:(maxV-minV)/100:maxV];
+end
+% get paramvalues
+value = vector(v);
+% set parameter value
+set(handles.value4,'String',value);                                 %%%
+% update parameter information structure in handles with new values
+m = get(handles.modelselection,'Value');
+pindex = get(handles.manualparam4,'Value');                         %%%
+handles.parammodel(m).values(pindex) = value;
+% sim and plot
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Slider5 handling function
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function slider5_Callback(hObject, eventdata, handles)
+% get slider settings
+v = ceil(get(handles.manualslider5,'Value'));                       %%%
+% get min max settings
+maxV = str2double(get(handles.manualmax5,'String'));                %%%
+minV = str2double(get(handles.manualmin5,'String'));                %%%
+% construct vectors
+if minV > 0,
+    vector = logspace(log(minV)/log(10),log(maxV)/log(10),101);
+else
+    vector = [minV:(maxV-minV)/100:maxV];
+end
+% get paramvalues
+value = vector(v);
+% set parameter value
+set(handles.value5,'String',value);                                 %%%
+% update parameter information structure in handles with new values
+m = get(handles.modelselection,'Value');
+pindex = get(handles.manualparam5,'Value');                         %%%
+handles.parammodel(m).values(pindex) = value;
+% sim and plot
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Slider6 handling function
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function slider6_Callback(hObject, eventdata, handles)
+% get slider settings
+v = ceil(get(handles.manualslider6,'Value'));                       %%%
+% get min max settings
+maxV = str2double(get(handles.manualmax6,'String'));                %%%
+minV = str2double(get(handles.manualmin6,'String'));                %%%
+% construct vectors
+if minV > 0,
+    vector = logspace(log(minV)/log(10),log(maxV)/log(10),101);
+else
+    vector = [minV:(maxV-minV)/100:maxV];
+end
+% get paramvalues
+value = vector(v);
+% set parameter value
+set(handles.value6,'String',value);                                 %%%
+% update parameter information structure in handles with new values
+m = get(handles.modelselection,'Value');
+pindex = get(handles.manualparam6,'Value');                         %%%
+handles.parammodel(m).values(pindex) = value;
+% sim and plot
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Slider7 handling function
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function slider7_Callback(hObject, eventdata, handles)
+% get slider settings
+v = ceil(get(handles.manualslider7,'Value'));                       %%%
+% get min max settings
+maxV = str2double(get(handles.manualmax7,'String'));                %%%
+minV = str2double(get(handles.manualmin7,'String'));                %%%
+% construct vectors
+if minV > 0,
+    vector = logspace(log(minV)/log(10),log(maxV)/log(10),101);
+else
+    vector = [minV:(maxV-minV)/100:maxV];
+end
+% get paramvalues
+value = vector(v);
+% set parameter value
+set(handles.value7,'String',value);                                 %%%
+% update parameter information structure in handles with new values
+m = get(handles.modelselection,'Value');
+pindex = get(handles.manualparam7,'Value');                         %%%
+handles.parammodel(m).values(pindex) = value;
+% sim and plot
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+
+
+% 
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% % Slider handling function
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% function slider_Callback(hObject, eventdata, handles)
+% % get slider settings
+% v1 = ceil(get(handles.manualslider1,'Value'));
+% v2 = ceil(get(handles.manualslider2,'Value'));
+% v3 = ceil(get(handles.manualslider3,'Value'));
+% v4 = ceil(get(handles.manualslider4,'Value'));
+% v5 = ceil(get(handles.manualslider5,'Value'));
+% v6 = ceil(get(handles.manualslider6,'Value'));
+% v7 = ceil(get(handles.manualslider7,'Value'));
+% % get min max settings
+% max1 = str2double(get(handles.manualmax1,'String'));
+% max2 = str2double(get(handles.manualmax2,'String'));
+% max3 = str2double(get(handles.manualmax3,'String'));
+% max4 = str2double(get(handles.manualmax4,'String'));
+% max5 = str2double(get(handles.manualmax5,'String'));
+% max6 = str2double(get(handles.manualmax6,'String'));
+% max7 = str2double(get(handles.manualmax7,'String'));
+% min1 = str2double(get(handles.manualmin1,'String'));
+% min2 = str2double(get(handles.manualmin2,'String'));
+% min3 = str2double(get(handles.manualmin3,'String'));
+% min4 = str2double(get(handles.manualmin4,'String'));
+% min5 = str2double(get(handles.manualmin5,'String'));
+% min6 = str2double(get(handles.manualmin6,'String'));
+% min7 = str2double(get(handles.manualmin7,'String'));
+% % construct vectors
+% if min1 > 0,
+%     vector1 = logspace(log(min1)/log(10),log(max1)/log(10),101);
+% else
+%     vector1 = [min1:(max1-min1)/100:max1];
+% end
+% if min2 > 0,
+%     vector2 = logspace(log(min2)/log(10),log(max2)/log(10),101);
+% else
+%     vector2 = [min2:(max2-min2)/100:max2];
+% end
+% if min3 > 0,
+%     vector3 = logspace(log(min3)/log(10),log(max3)/log(10),101);
+% else
+%     vector3 = [min3:(max3-min3)/100:max3];
+% end
+% if min4 > 0,
+%     vector4 = logspace(log(min4)/log(10),log(max4)/log(10),101);
+% else
+%     vector4 = [min4:(max4-min4)/100:max4];
+% end
+% if min5 > 0,
+%     vector5 = logspace(log(min5)/log(10),log(max5)/log(10),101);
+% else
+%     vector5 = [min5:(max5-min5)/100:max5];
+% end
+% if min6 > 0,
+%     vector6 = logspace(log(min6)/log(10),log(max6)/log(10),101);
+% else
+%     vector6 = [min6:(max6-min6)/100:max6];
+% end
+% if min7 > 0,
+%     vector7 = logspace(log(min7)/log(10),log(max7)/log(10),101);
+% else
+%     vector7 = [min7:(max7-min7)/100:max7];
+% end
+% % get paramvalues
+% values = [vector1(v1) vector2(v2) vector3(v3) vector4(v4) vector5(v5) vector6(v6) vector7(v7)];
+% % set parameter values
+% set(handles.value1,'String',values(1));
+% set(handles.value2,'String',values(2));
+% set(handles.value3,'String',values(3));
+% set(handles.value4,'String',values(4));
+% set(handles.value5,'String',values(5));
+% set(handles.value6,'String',values(6));
+% set(handles.value7,'String',values(7));
+% % update parameter information structure in handles with new values
+% m = get(handles.modelselection,'Value');
+% pindex = [];
+% pindex(end+1) = get(handles.manualparam1,'Value');
+% pindex(end+1) = get(handles.manualparam2,'Value');
+% pindex(end+1) = get(handles.manualparam3,'Value');
+% pindex(end+1) = get(handles.manualparam4,'Value');
+% pindex(end+1) = get(handles.manualparam5,'Value');
+% pindex(end+1) = get(handles.manualparam6,'Value');
+% pindex(end+1) = get(handles.manualparam7,'Value');
+% handles.parammodel(m).values(pindex) = values;
+% % sim and plot
+% handles = doSimAndPlot(handles);
+% % Update handles structure
+% guidata(hObject, handles);
+% return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Minmax handling function
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function minmax1_Callback(hObject, eventdata, handles)
+% get max min values
+max1 = str2double(get(handles.manualmax1,'String'));
+min1 = str2double(get(handles.manualmin1,'String'));
+% get slider setting
+v1 = ceil(get(handles.manualslider1,'Value'));
+% get current value
+value1 = str2double(get(handles.value1,'String'));
+% check and adjust bounds if needed
+if value1 < min1, value1 = min1; end
+if value1 > max1, value1 = max1; end
+% set slider value to correspond to value
+if min1 > 0,
+    vector1 = logspace(log(min1)/log(10),log(max1)/log(10),101);
+else
+    vector1 = [min1:(max1-min1)/100:max1];
+end
+[dummy,index] = min(abs(vector1-value1));
+set(handles.manualslider1,'Value',index);
+% update values field
+value1 = vector1(index);
+set(handles.value1,'String',value1);
+% update parameter information structure in handles with new value
+m = get(handles.modelselection,'Value');
+pindex = get(handles.manualparam1,'Value');
+handles.parammodel(m).max(pindex) = max1;
+handles.parammodel(m).min(pindex) = min1;
+handles.parammodel(m).values(pindex) = value1;
+% sim and plot
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+function minmax2_Callback(hObject, eventdata, handles)
+% get max min values
+max2 = str2double(get(handles.manualmax2,'String'));
+min2 = str2double(get(handles.manualmin2,'String'));
+% get slider setting
+v2 = ceil(get(handles.manualslider2,'Value'));
+% get current value
+value2 = str2double(get(handles.value2,'String'));
+% check and adjust bounds if needed
+if value2 < min2, value2 = min2; end
+if value2 > max2, value2 = max2; end
+% set slider value to correspond to value
+if min2 > 0,
+    vector2 = logspace(log(min2)/log(10),log(max2)/log(10),101);
+else
+    vector2 = [min2:(max2-min2)/100:max2];
+end
+[dummy,index] = min(abs(vector2-value2));
+set(handles.manualslider2,'Value',index);
+% update values field
+value2 = vector2(index);
+set(handles.value2,'String',value2);
+% update parameter information structure in handles with new value
+m = get(handles.modelselection,'Value');
+pindex = get(handles.manualparam2,'Value');
+handles.parammodel(m).max(pindex) = max2;
+handles.parammodel(m).min(pindex) = min2;
+handles.parammodel(m).values(pindex) = value2;
+% sim and plot
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+function minmax3_Callback(hObject, eventdata, handles)
+% get max min values
+max3 = str2double(get(handles.manualmax3,'String'));
+min3 = str2double(get(handles.manualmin3,'String'));
+% get slider setting
+v3 = ceil(get(handles.manualslider3,'Value'));
+% get current value
+value3 = str2double(get(handles.value3,'String'));
+% check and adjust bounds if needed
+if value3 < min3, value3 = min3; end
+if value3 > max3, value3 = max3; end
+% set slider value to correspond to value
+if min3 > 0,
+    vector3 = logspace(log(min3)/log(10),log(max3)/log(10),101);
+else
+    vector3 = [min3:(max3-min3)/100:max3];
+end
+[dummy,index] = min(abs(vector3-value3));
+set(handles.manualslider3,'Value',index);
+% update values field
+value3 = vector3(index);
+set(handles.value3,'String',value3);
+% update parameter information structure in handles with new value
+m = get(handles.modelselection,'Value');
+pindex = get(handles.manualparam3,'Value');
+handles.parammodel(m).max(pindex) = max3;
+handles.parammodel(m).min(pindex) = min3;
+handles.parammodel(m).values(pindex) = value3;
+% sim and plot
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+function minmax4_Callback(hObject, eventdata, handles)
+% get max min values
+max4 = str2double(get(handles.manualmax4,'String'));
+min4 = str2double(get(handles.manualmin4,'String'));
+% get slider setting
+v4 = ceil(get(handles.manualslider4,'Value'));
+% get current value
+value4 = str2double(get(handles.value4,'String'));
+% check and adjust bounds if needed
+if value4 < min4, value4 = min4; end
+if value4 > max4, value4 = max4; end
+% set slider value to correspond to value
+if min4 > 0,
+    vector4 = logspace(log(min4)/log(10),log(max4)/log(10),101);
+else
+    vector4 = [min4:(max4-min4)/100:max4];
+end
+[dummy,index] = min(abs(vector4-value4));
+set(handles.manualslider4,'Value',index);
+% update values field
+value4 = vector4(index);
+set(handles.value4,'String',value4);
+% update parameter information structure in handles with new value
+m = get(handles.modelselection,'Value');
+pindex = get(handles.manualparam4,'Value');
+handles.parammodel(m).max(pindex) = max4;
+handles.parammodel(m).min(pindex) = min4;
+handles.parammodel(m).values(pindex) = value4;
+% sim and plot
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+function minmax5_Callback(hObject, eventdata, handles)
+% get max min values
+max5 = str2double(get(handles.manualmax5,'String'));
+min5 = str2double(get(handles.manualmin5,'String'));
+% get slider setting
+v5 = ceil(get(handles.manualslider5,'Value'));
+% get current value
+value5 = str2double(get(handles.value5,'String'));
+% check and adjust bounds if needed
+if value5 < min5, value5 = min5; end
+if value5 > max5, value5 = max5; end
+% set slider value to correspond to value
+if min5 > 0,
+    vector5 = logspace(log(min5)/log(10),log(max5)/log(10),101);
+else
+    vector5 = [min5:(max5-min5)/100:max5];
+end
+[dummy,index] = min(abs(vector5-value5));
+set(handles.manualslider5,'Value',index);
+% update values field
+value5 = vector5(index);
+set(handles.value5,'String',value5);
+% update parameter information structure in handles with new value
+m = get(handles.modelselection,'Value');
+pindex = get(handles.manualparam5,'Value');
+handles.parammodel(m).max(pindex) = max5;
+handles.parammodel(m).min(pindex) = min5;
+handles.parammodel(m).values(pindex) = value5;
+% sim and plot
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+function minmax6_Callback(hObject, eventdata, handles)
+% get max min values
+max6 = str2double(get(handles.manualmax6,'String'));
+min6 = str2double(get(handles.manualmin6,'String'));
+% get slider setting
+v6 = ceil(get(handles.manualslider6,'Value'));
+% get current value
+value6 = str2double(get(handles.value6,'String'));
+% check and adjust bounds if needed
+if value6 < min6, value6 = min6; end
+if value6 > max6, value6 = max6; end
+% set slider value to correspond to value
+if min6 > 0,
+    vector6 = logspace(log(min6)/log(10),log(max6)/log(10),101);
+else
+    vector6 = [min6:(max6-min6)/100:max6];
+end
+[dummy,index] = min(abs(vector6-value6));
+set(handles.manualslider6,'Value',index);
+% update values field
+value6 = vector6(index);
+set(handles.value6,'String',value6);
+% update parameter information structure in handles with new value
+m = get(handles.modelselection,'Value');
+pindex = get(handles.manualparam6,'Value');
+handles.parammodel(m).max(pindex) = max6;
+handles.parammodel(m).min(pindex) = min6;
+handles.parammodel(m).values(pindex) = value6;
+% sim and plot
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+function minmax7_Callback(hObject, eventdata, handles)
+% get max min values
+max7 = str2double(get(handles.manualmax7,'String'));
+min7 = str2double(get(handles.manualmin7,'String'));
+% get slider setting
+v7 = ceil(get(handles.manualslider7,'Value'));
+% get current value
+value7 = str2double(get(handles.value7,'String'));
+% check and adjust bounds if needed
+if value7 < min7, value7 = min7; end
+if value7 > max7, value7 = max7; end
+% set slider value to correspond to value
+if min7 > 0,
+    vector7 = logspace(log(min7)/log(10),log(max7)/log(10),101);
+else
+    vector7 = [min7:(max7-min7)/100:max7];
+end
+[dummy,index] = min(abs(vector7-value7));
+set(handles.manualslider7,'Value',index);
+% update values field
+value7 = vector7(index);
+set(handles.value7,'String',value7);
+% update parameter information structure in handles with new value
+m = get(handles.modelselection,'Value');
+pindex = get(handles.manualparam7,'Value');
+handles.parammodel(m).max(pindex) = max7;
+handles.parammodel(m).min(pindex) = min7;
+handles.parammodel(m).values(pindex) = value7;
+% sim and plot
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% MODEL PARAMETER HANDLING
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function manualparam1_Callback(hObject, eventdata, handles)
+m = get(handles.modelselection,'Value');
+pindex = get(handles.manualparam1,'Value');
+paramvalue = handles.parammodel(m).values(pindex);
+% set current parameter values
+set(handles.value1,'String',paramvalue);
+% set max and min values 
+max = handles.parammodel(m).max(pindex);
+min = handles.parammodel(m).min(pindex);
+set(handles.manualmax1,'String',max);
+set(handles.manualmin1,'String',min);
+% set slider min max and value
+set(handles.manualslider1,'Max',101);
+set(handles.manualslider1,'Min',1);
+% set slider value to correspond to value
+if min > 0,
+    vector = logspace(log(min)/log(10),log(max)/log(10),101);
+else
+    vector = [min:(max-min)/100:max];
+end
+[dummy,index] = minfunct(abs(vector-paramvalue));
+set(handles.manualslider1,'Value',index);
+% set slider steps
+set(handles.manualslider1,'SliderStep',[0.01 0.01]);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+function [a,b] = minfunct(X)
+[a,b] = min(X);
+return
+
+function manualparam2_Callback(hObject, eventdata, handles)
+m = get(handles.modelselection,'Value');
+pindex = get(handles.manualparam2,'Value');
+paramvalue = handles.parammodel(m).values(pindex);
+% set current parameter values
+set(handles.value2,'String',paramvalue);
+% set max and min values 
+max = handles.parammodel(m).max(pindex);
+min = handles.parammodel(m).min(pindex);
+set(handles.manualmax2,'String',max);
+set(handles.manualmin2,'String',min);
+% set slider min max and value
+set(handles.manualslider2,'Max',101);
+set(handles.manualslider2,'Min',1);
+% set slider value to correspond to value
+if min > 0,
+    vector = logspace(log(min)/log(10),log(max)/log(10),101);
+else
+    vector = [min:(max-min)/100:max];
+end
+[dummy,index] = minfunct(abs(vector-paramvalue));
+set(handles.manualslider2,'Value',index);
+% set slider steps
+set(handles.manualslider2,'SliderStep',[0.01 0.01]);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+function manualparam3_Callback(hObject, eventdata, handles)
+m = get(handles.modelselection,'Value');
+pindex = get(handles.manualparam3,'Value');
+paramvalue = handles.parammodel(m).values(pindex);
+% set current parameter values
+set(handles.value3,'String',paramvalue);
+% set max and min values 
+max = handles.parammodel(m).max(pindex);
+min = handles.parammodel(m).min(pindex);
+set(handles.manualmax3,'String',max);
+set(handles.manualmin3,'String',min);
+% set slider min max and value
+set(handles.manualslider3,'Max',101);
+set(handles.manualslider3,'Min',1);
+% set slider value to correspond to value
+if min > 0,
+    vector = logspace(log(min)/log(10),log(max)/log(10),101);
+else
+    vector = [min:(max-min)/100:max];
+end
+[dummy,index] = minfunct(abs(vector-paramvalue));
+set(handles.manualslider3,'Value',index);
+% set slider steps
+set(handles.manualslider3,'SliderStep',[0.01 0.01]);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+function manualparam4_Callback(hObject, eventdata, handles)
+m = get(handles.modelselection,'Value');
+pindex = get(handles.manualparam4,'Value');
+paramvalue = handles.parammodel(m).values(pindex);
+% set current parameter values
+set(handles.value4,'String',paramvalue);
+% set max and min values 
+max = handles.parammodel(m).max(pindex);
+min = handles.parammodel(m).min(pindex);
+set(handles.manualmax4,'String',max);
+set(handles.manualmin4,'String',min);
+% set slider min max and value
+set(handles.manualslider4,'Max',101);
+set(handles.manualslider4,'Min',1);
+% set slider value to correspond to value
+if min > 0,
+    vector = logspace(log(min)/log(10),log(max)/log(10),101);
+else
+    vector = [min:(max-min)/100:max];
+end
+[dummy,index] = minfunct(abs(vector-paramvalue));
+set(handles.manualslider4,'Value',index);
+% set slider steps
+set(handles.manualslider4,'SliderStep',[0.01 0.01]);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+function manualparam5_Callback(hObject, eventdata, handles)
+m = get(handles.modelselection,'Value');
+pindex = get(handles.manualparam5,'Value');
+paramvalue = handles.parammodel(m).values(pindex);
+% set current parameter values
+set(handles.value5,'String',paramvalue);
+% set max and min values 
+max = handles.parammodel(m).max(pindex);
+min = handles.parammodel(m).min(pindex);
+set(handles.manualmax5,'String',max);
+set(handles.manualmin5,'String',min);
+% set slider min max and value
+set(handles.manualslider5,'Max',101);
+set(handles.manualslider5,'Min',1);
+% set slider value to correspond to value
+if min > 0,
+    vector = logspace(log(min)/log(10),log(max)/log(10),101);
+else
+    vector = [min:(max-min)/100:max];
+end
+[dummy,index] = minfunct(abs(vector-paramvalue));
+set(handles.manualslider5,'Value',index);
+% set slider steps
+set(handles.manualslider5,'SliderStep',[0.01 0.01]);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+function manualparam6_Callback(hObject, eventdata, handles)
+m = get(handles.modelselection,'Value');
+pindex = get(handles.manualparam6,'Value');
+paramvalue = handles.parammodel(m).values(pindex);
+% set current parameter values
+set(handles.value6,'String',paramvalue);
+% set max and min values 
+max = handles.parammodel(m).max(pindex);
+min = handles.parammodel(m).min(pindex);
+set(handles.manualmax6,'String',max);
+set(handles.manualmin6,'String',min);
+% set slider min max and value
+set(handles.manualslider6,'Max',101);
+set(handles.manualslider6,'Min',1);
+% set slider value to correspond to value
+if min > 0,
+    vector = logspace(log(min)/log(10),log(max)/log(10),101);
+else
+    vector = [min:(max-min)/100:max];
+end
+[dummy,index] = minfunct(abs(vector-paramvalue));
+set(handles.manualslider6,'Value',index);
+% set slider steps
+set(handles.manualslider6,'SliderStep',[0.01 0.01]);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+function manualparam7_Callback(hObject, eventdata, handles)
+m = get(handles.modelselection,'Value');
+pindex = get(handles.manualparam7,'Value');
+paramvalue = handles.parammodel(m).values(pindex);
+% set current parameter values
+set(handles.value7,'String',paramvalue);
+% set max and min values 
+max = handles.parammodel(m).max(pindex);
+min = handles.parammodel(m).min(pindex);
+set(handles.manualmax7,'String',max);
+set(handles.manualmin7,'String',min);
+% set slider min max and value
+set(handles.manualslider7,'Max',101);
+set(handles.manualslider7,'Min',1);
+% set slider value to correspond to value
+if min > 0,
+    vector = logspace(log(min)/log(10),log(max)/log(10),101);
+else
+    vector = [min:(max-min)/100:max];
+end
+[dummy,index] = minfunct(abs(vector-paramvalue));
+set(handles.manualslider7,'Value',index);
+% set slider steps
+set(handles.manualslider7,'SliderStep',[0.01 0.01]);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INITIALIZE PLOTDATA (includes MEXfile data)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [plotdata] = initializePlotdata(projectstruct,modelindex,handles)
+% GET ALL MEASUREMENT INFORMATION
+infostruct = [];
+for k=1:length(projectstruct.models(modelindex)),
+    model = projectstruct.models{modelindex(k)};
+    experiments = projectstruct.experiments(handles.experimentindices);
+    displayFlag = 0;
+    expmeasinfo = getexpmeasinfoSBPD(model,modelindex(k),experiments,handles.experimentindices,displayFlag);
+    infostruct(k).modelstruct = SBstruct(projectstruct.models{modelindex(k)});
+    infostruct(k).modelindex = modelindex(k);
+    infostruct(k).expinfostruct = expmeasinfo;
+end
+% ADD SIMULATION DATA TO THE STRUCTURE
+plotdata = [];
+plotdata.project = projectstruct.name;
+plotdata.notes = projectstruct.notes;
+plotdata.model = [];
+% run through all models
+for m=1:length(projectstruct.models(modelindex)),
+    % model data
+    modelstruct = infostruct(m).modelstruct;
+    plotdata.model(m).name = modelstruct.name;      
+    plotdata.model(m).notes = modelstruct.notes;
+    allmeasuredcomponents = {};
+    for e=1:length(infostruct(m).expinfostruct),
+        % experiment data
+        plotdata.model(m).experiment(e).name = infostruct(m).expinfostruct(e).experimentname;
+        plotdata.model(m).experiment(e).mexmodel = infostruct(m).expinfostruct(e).model;
+        plotdata.model(m).experiment(e).mexfullpath = infostruct(m).expinfostruct(e).mexfullpath;
+        timevector = infostruct(m).expinfostruct(e).timevector;
+        timestart = timevector(1);
+        timeend = timevector(end);
+        timevectorsim = [timestart:(timeend-timestart)/1000:timeend];
+        plotdata.model(m).experiment(e).timevector = timevectorsim;
+        expstatenames = infostruct(m).expinfostruct(e).statenames;          
+        expvariablenames = infostruct(m).expinfostruct(e).variablenames; 
+        plotdata.model(m).experiment(e).componentnames = {expstatenames{:} expvariablenames{:}};  
+        % simulate to get the state and variable values
+        mexmodel = infostruct(m).expinfostruct(e).model;
+        ic = infostruct(m).expinfostruct(e).initialconditions;
+        plotdata.model(m).experiment(e).initialconditions = ic;
+        try
+            simdata = feval(mexmodel,timevectorsim,ic,[],handles.integratoroptions);
+        catch
+            simdata.statevalues = NaN(length(timevectorsim),length(ic));
+            simdata.variablevalues = NaN(length(timevectorsim),length(ic));
+%            disp(sprintf('Integrator problems for experiment %d.',e));
+        end
+        % collect all states that are measured
+        stateindices = infostruct(m).expinfostruct(e).stateindices;
+        variableindices = infostruct(m).expinfostruct(e).variableindices;
+        plotdata.model(m).experiment(e).stateindices = stateindices;
+        plotdata.model(m).experiment(e).variableindices = variableindices;
+        statevalues = simdata.statevalues(:,stateindices);
+        variablevalues = simdata.variablevalues(:,variableindices);
+        % add simulated state trajectories
+        plotdata.model(m).experiment(e).componentvalues = [statevalues variablevalues];
+        for meas=1:length(infostruct(m).expinfostruct(e).measurement),
+            % measurement data
+            plotdata.model(m).experiment(e).measurement(meas).name = infostruct(m).expinfostruct(e).measurement(meas).name;
+            timevectormeas = timevector(infostruct(m).expinfostruct(e).measurement(meas).timevectorindices);
+            plotdata.model(m).experiment(e).measurement(meas).timevector = timevectormeas;
+            % reorder the measurements
+            measstatenames = infostruct(m).expinfostruct(e).measurement(meas).statenames;
+            measvariablenames = infostruct(m).expinfostruct(e).measurement(meas).variablenames;
+            % states 
+            for k=1:length(expstatenames),
+                index = strmatchSB(expstatenames{k},measstatenames,'exact');
+                if ~isempty(index),
+                    plotdata.model(m).experiment(e).measurement(meas).componentnames{k} = measstatenames{index};
+                    plotdata.model(m).experiment(e).measurement(meas).componentvalues(:,k) = infostruct(m).expinfostruct(e).measurement(meas).statereferences(:,index);
+                    plotdata.model(m).experiment(e).measurement(meas).maxvalues(:,k) = infostruct(m).expinfostruct(e).measurement(meas).statemaxvalues(:,index);
+                    plotdata.model(m).experiment(e).measurement(meas).minvalues(:,k) = infostruct(m).expinfostruct(e).measurement(meas).stateminvalues(:,index);
+                else
+                    plotdata.model(m).experiment(e).measurement(meas).componentnames{k} = 'not available';
+                    plotdata.model(m).experiment(e).measurement(meas).componnentvalues(:,k) = NaN(length(timevectormeas),1);
+                    plotdata.model(m).experiment(e).measurement(meas).maxvalues(:,k) = NaN(length(timevectormeas),1);
+                    plotdata.model(m).experiment(e).measurement(meas).minvalues(:,k) = NaN(length(timevectormeas),1);
+                end                    
+            end
+            offset = length(expstatenames);
+            % variables
+            for k=1:length(expvariablenames),
+                index = strmatchSB(expvariablenames{k},measvariablenames,'exact');
+                if ~isempty(index),
+                    plotdata.model(m).experiment(e).measurement(meas).componentnames{offset+k} = measvariablenames{index};
+                    plotdata.model(m).experiment(e).measurement(meas).componentvalues(:,offset+k) = infostruct(m).expinfostruct(e).measurement(meas).variablereferences(:,index);
+                    plotdata.model(m).experiment(e).measurement(meas).maxvalues(:,offset+k) = infostruct(m).expinfostruct(e).measurement(meas).variablemaxvalues(:,index);
+                    plotdata.model(m).experiment(e).measurement(meas).minvalues(:,offset+k) = infostruct(m).expinfostruct(e).measurement(meas).variableminvalues(:,index);
+                else
+                    plotdata.model(m).experiment(e).measurement(meas).componentnames{offset+k} = 'not available';
+                    plotdata.model(m).experiment(e).measurement(meas).componentvalues(:,offset+k) = NaN(length(timevectormeas),1);
+                    plotdata.model(m).experiment(e).measurement(meas).maxvalues(:,offset+k) = NaN(length(timevectormeas),1);
+                    plotdata.model(m).experiment(e).measurement(meas).minvalues(:,offset+k) = NaN(length(timevectormeas),1);
+                end                    
+            end      
+            allmeasuredcomponents = {allmeasuredcomponents{:} plotdata.model(m).experiment(e).measurement(meas).componentnames{:}};
+        end
+    end
+    allmeasuredcomponents = unique(allmeasuredcomponents);
+    plotdata.model(m).allmeascomponents = allmeasuredcomponents;
+end     
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% TRIVIAL FUNCTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% --- Executes on button press in zoombutton.
+function legendbutton_Callback(hObject, eventdata, handles)
+% toogle the legends in the figure
+if handles.legendflag == 0,
+    handles.legendflag = 1;
+else
+    handles.legendflag = 0;
+end
+% plot
+doPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+% --- Executes on button press in zoombutton.
+function errorbarbutton_Callback(hObject, eventdata, handles)
+% toogle the errorbars in the figure
+if handles.errorbars == 0,
+    handles.errorbars = 1;
+else
+    handles.errorbars = 0;
+end
+% plot
+doPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+% --- Executes on button press in zoombutton.
+function zoombutton_Callback(hObject, eventdata, handles)
+% toogle the zoom in the figure
+zoom
+return
+
+% --- Executes on button press in gridbutton.
+function gridbutton_Callback(hObject, eventdata, handles)
+% toogle the grid in the figure
+grid
+if handles.grid == 1,
+    handles.grid = 0;
+else
+    handles.grid = 1;
+end
+% Update handles structure
+guidata(hObject, handles);
+return
+
+% --- Executes on selection change in modelselection.
+function modelselection_Callback(hObject, eventdata, handles)
+try
+    modelindex = get(handles.modelselection,'Value');
+    set(handles.experimentselection,'String',{handles.plotdata.model(modelindex).experiment.name});
+    doPlot(handles);
+catch
+    errordlg('This selection is not possible.','Error','on');               
+end
+% set all parameter selection boxes with parameter names (model dependent)
+initializeParameterLists(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+% --- Executes on selection change in resetall.
+function resetall_Callback(hObject, eventdata, handles)
+m = get(handles.modelselection,'Value');
+% reset all values for current model to starting values
+handles.parammodel(m).values = handles.parammodel(m).startvalues;
+handles.parammodel(m).max = handles.parammodel(m).startmax;
+handles.parammodel(m).min = handles.parammodel(m).startmin;
+% reinitialize parameter list
+initializeParameterLists(handles,'resetall');
+% simulate and plot it
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+% --- Executes on selection change in resetcurrent.
+function resetcurrent_Callback(hObject, eventdata, handles)
+m = get(handles.modelselection,'Value');
+% reset all values for current model and current parameter selections to starting values
+% get current indices
+pindices = [];
+pindices(end+1) = get(handles.manualparam1,'Value');
+pindices(end+1) = get(handles.manualparam2,'Value');
+pindices(end+1) = get(handles.manualparam3,'Value');
+pindices(end+1) = get(handles.manualparam4,'Value');
+pindices(end+1) = get(handles.manualparam5,'Value');
+pindices(end+1) = get(handles.manualparam6,'Value');
+pindices(end+1) = get(handles.manualparam7,'Value');
+% reset values for current parameters
+handles.parammodel(m).values(pindices) = handles.parammodel(m).startvalues(pindices);
+handles.parammodel(m).max(pindices) = handles.parammodel(m).startmax(pindices);
+handles.parammodel(m).min(pindices) = handles.parammodel(m).startmin(pindices);
+% reinitialize parameter list
+initializeParameterLists(handles,'resetcurrent');
+% simulate and plot it
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+% --- Executes on selection change in experimentselection.
+function experimentselection_Callback(hObject, eventdata, handles)
+try
+    doPlot(handles);
+catch
+    errordlg('This selection is not possible.','Error','on');               
+end
+% check if only one experiment selected ... then show the simulate button
+% otherwise hide it
+eall = get(handles.experimentselection,'Value');
+if length(eall) > 1,
+    set(handles.simexpbutton,'Enable','off');
+    set(handles.simexpbutton,'BackgroundColor',[0.8 0.8 0.8]);
+else
+    set(handles.simexpbutton,'Enable','on');
+    set(handles.simexpbutton,'BackgroundColor',[1 0.745 0.49]);
+end
+% Update handles structure
+guidata(hObject, handles);
+return
+
+% --- Executes on selection change in experimentselection.
+function componentselection_Callback(hObject, eventdata, handles)
+try
+    doPlot(handles);
+catch
+    errordlg('This selection is not possible.','Error','on');               
+end
+return
+
+% --- Executes on button press in plot.
+function plot_Callback(hObject, eventdata, handles)
+handles.dataPlotType = 'plot';
+% disable errorbarbutton
+set(handles.errorbarbutton,'Visible','on');
+% Update handles structure
+guidata(hObject, handles);
+doPlot(handles);
+return
+
+% --- Executes on button press in loglog.
+function semilogx_Callback(hObject, eventdata, handles)
+handles.dataPlotType = 'semilogx';
+% disable errorbarbutton
+set(handles.errorbarbutton,'Visible','off');
+handles.errorbars = 0;
+% Update handles structure
+guidata(hObject, handles);
+doPlot(handles);
+return
+
+% --- Executes on button press in semilogx.
+function semilogy_Callback(hObject, eventdata, handles)
+handles.dataPlotType = 'semilogy';
+% disable errorbarbutton
+set(handles.errorbarbutton,'Visible','off');
+handles.errorbars = 0;
+% Update handles structure
+guidata(hObject, handles);
+doPlot(handles);
+return
+
+% --- Executes on button press in loglog.
+function loglog_Callback(hObject, eventdata, handles)
+handles.dataPlotType = 'loglog';
+% disable errorbarbutton
+set(handles.errorbarbutton,'Visible','off');
+handles.errorbars = 0;
+% Update handles structure
+guidata(hObject, handles);
+doPlot(handles);
+return
+
+% --- Simulate current model with current experiment and display in SBplot window
+function simulatebutton_Callback(hObject, eventdata, handles)
+m = get(handles.modelselection,'Value');
+e = get(handles.experimentselection,'Value');
+name = handles.plotdata.model(m).experiment(e).name;
+
+    mexmodel = handles.plotdata.model(m).experiment(e).mexmodel;
+    timevector = handles.plotdata.model(m).experiment(e).timevector;
+    ic = handles.plotdata.model(m).experiment(e).initialconditions;
+    % take away the things that are no parameters
+    noParamIndices = strmatchSB('No Parameter',handles.parammodel(m).names,'exact');
+    paramIndices = setdiff([1:length(handles.parammodel(m).names)],noParamIndices);
+    paramnames = handles.parammodel(m).names(paramIndices);
+    paramvalues = handles.parammodel(m).values(paramIndices);
+
+simdata = SBPDsimulate(mexmodel,timevector,ic,paramnames,paramvalues,handles.integratoroptions);
+% remove '_' from name
+name = strrep(name,'_',' ');
+plotdatastruct = createdatastruct2SBplotSB(simdata,name);
+SBplot(plotdatastruct);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+% --- Set axis bounds
+function bounds_Callback(hObject, eventdata, handles)
+try 
+    handles.boundsaxis = eval(get(handles.bounds,'String'));
+catch
+    handles.boundsaxis = NaN;
+    set(handles.bounds,'String','Nominal');
+end
+if length(handles.boundsaxis) ~= 4,
+    handles.boundsaxis = NaN;
+    set(handles.bounds,'String','Nominal');
+end    
+% Update handles structure
+guidata(hObject, handles);
+doPlot(handles);
+return
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/SBPDmodeltuningGUI/SBPDmodeltuning.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/SBPDmodeltuningGUI/SBPDmodeltuning.m
new file mode 100644
index 0000000000000000000000000000000000000000..4e1816f4f495ac9b5944470a55c95549501b7981
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/SBPDmodeltuningGUI/SBPDmodeltuning.m
@@ -0,0 +1,137 @@
+function [modeltuned] = SBPDmodeltuning(model,data,varargin)
+% SBPDmodeltuning: Allows to compare and tune a model to one or more sets
+% of data. Here: No experiment description is required, the model is
+% assumed to already include the experimental settings.
+% If no data is available, a time vector can be provided. The model can
+% then be tuned. For comparison the simulation result of the nominal model
+% is also shown.
+%
+% USAGE:
+% ======
+% modeltuned = SBPDmodeltuning(model,data)
+% modeltuned = SBPDmodeltuning(model,data,options)
+% modeltuned = SBPDmodeltuning(model,time)
+%
+% model: SBmodel to tune
+% data:  Single SBmeasurement object or cell-array with SBmeasurement
+%        objects to which to fit the model
+% time:  timevector to use for model simulation
+% options: still unused
+%
+% DEFAULT VALUES:
+% ===============
+%
+% Output Arguments:
+% =================
+% modeltuned: The tuned model with changed parameters
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 2,
+    options = [];
+elseif nargin == 3,
+    options = varargin{1};
+else 
+    error('Incorrect number of input arguments.');
+end
+if ~isSBmodel(model),
+    error('Function only defined for SBmodels.');
+end
+if iscell(data),
+    for k=1:length(data),
+        if ~isSBmeasurement(data{k}),
+            error('Error in the data input argument (SBmeasurement required).');
+        end
+    end
+elseif isSBmeasurement(data),
+    data = {data};
+elseif isnumeric(data),
+    time = data;
+    if length(time) == 1,
+        time = [0:time/1000:time];
+    end
+    data = {createDummyMeasurement(time,model)};
+else
+    error('Error in the data input argument (SBmeasurement required).');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CREATE DUMMY PROJECT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+p = SBPDproject();                          % create empty project
+p = SBPDupdatemodel(p,model);               % add model
+e = SBexperiment(); es = struct(e); es.name = 'Empty Experiment'; e = SBexperiment(es);
+p = SBPDupdateexperiment(p,e); % add empty experiment
+for k=1:length(data),
+    p = SBPDupdatemeasurement(p,1,data{k}); % add measurements
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine parameters changed by events
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Parameters that are changed by events are not allowed to be changed by the user during tuning
+ms = struct(model);
+pnames = {ms.parameters.name};
+% collect all assignment variables in all events that are parameters
+apnames = {};
+for k=1:length(ms.events),
+    for k2=1:length(ms.events(k).assignment),
+        vname = ms.events(k).assignment(k2).variable;
+        if ~isempty(strmatchSB(vname,pnames,'exact')),
+            apnames{end+1} = vname;
+        end
+    end
+end
+apnames = unique(apnames);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CALL SBPDmanualtuning
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ptuned = modeltuningGUISBPD(p,1,apnames);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET TUNED MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modeltuned = SBPDgetmodel(ptuned,1);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% FINSIHED => RETURN
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create a dummy measurement 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [dummymeas] = createDummyMeasurement(time,model)
+% Simulate the model over given time-vector
+simdata = SBPDsimulate(model,time);
+% create SBmeasurement structure
+ms = struct(SBmeasurement);
+ms.name = 'Nominal model';
+ms.notes = '';
+ms.time = time;
+for k=1:length(simdata.states),
+    ms.data(end+1).name = simdata.states{k};
+    ms.data(end).notes = '';
+    ms.data(end).values = simdata.statevalues(:,k);
+    x = NaN(size(simdata.statevalues(:,k)));
+    ms.data(end).maxvalues = x;
+    ms.data(end).minvalues = x;
+end
+for k=1:length(simdata.variables),
+    ms.data(end+1).name = simdata.variables{k};
+    ms.data(end).notes = '';
+    ms.data(end).values = simdata.variablevalues(:,k);
+    x = NaN(size(simdata.variablevalues(:,k)));
+    ms.data(end).maxvalues = x;
+    ms.data(end).minvalues = x;
+end
+dummymeas = SBmeasurement(ms);
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/SBPDmodeltuningGUI/modeltuningGUISBPD.fig b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/SBPDmodeltuningGUI/modeltuningGUISBPD.fig
new file mode 100644
index 0000000000000000000000000000000000000000..af4abe91de048cc2c145c8d2d183c542514efbcb
Binary files /dev/null and b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/SBPDmodeltuningGUI/modeltuningGUISBPD.fig differ
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/SBPDmodeltuningGUI/modeltuningGUISBPD.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/SBPDmodeltuningGUI/modeltuningGUISBPD.m
new file mode 100644
index 0000000000000000000000000000000000000000..fe0d748985faa1f6283a803cf5d52c037a1ff881
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/SBPDmodeltuningGUI/modeltuningGUISBPD.m
@@ -0,0 +1,1427 @@
+function varargout = modeltuningGUISBPD(varargin)
+% modeltuningGUISBPD: Allows to compare and tune a model to measured data.
+% Each measured component is displayed in a single plot against the
+% measured data (possible multiple measurements).
+%
+% Function to a very large extent based on SBPDmanualtuning. 
+%
+% NOTE: This function should not be called directly. It is called via the
+% SBPDmodeltuning function.
+% 
+% USAGE:
+% ======
+% [project] = modeltuningGUISBPD(project,modelindex,apnames,apvalues)
+%
+% project: SBPDproject to tune manually. 
+% modelindex: The index of the model in the project to use for tuning.
+% apnames: cell-array of model parameter names that are changed by events
+%   in the model (not allowed to be tuned and need to be reseted after each
+%   simulation)
+% apvalues: vector with the nominal values for the "apnames" parameters
+%
+% Output Arguments:
+% =================
+% The manually tuned project is given back.
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INITIALIZATION CODE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Begin initialization code - DO NOT EDIT
+gui_Singleton = 1;
+gui_State = struct('gui_Name',       mfilename, ...
+                   'gui_Singleton',  gui_Singleton, ...
+                   'gui_OpeningFcn', @modeltuningGUISBPD_OpeningFcn, ...
+                   'gui_OutputFcn',  @modeltuningGUISBPD_OutputFcn, ...
+                   'gui_LayoutFcn',  [] , ...
+                   'gui_Callback',   []);
+if nargin && ischar(varargin{1})
+    gui_State.gui_Callback = str2func(varargin{1});
+end
+if nargout
+    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
+else
+    gui_mainfcn(gui_State, varargin{:});
+end
+% End initialization code - DO NOT EDIT
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INTERFACE FUNCTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% --- Executes just before modeltuningGUISBPD is made visible.
+function modeltuningGUISBPD_OpeningFcn(hObject, eventdata, handles, varargin)
+if nargin~=6,
+    error('Incorrect number of input arguments.');
+end
+project = varargin{1};
+if ~isSBPDproject(project), 
+    error('Input argument is not an SBPDproject.'); 
+end
+modelindex = varargin{2};
+event_param_names = varargin{3};
+% Integrator options (could be input argument later on)
+OPTIONS = [];
+% OPTIONS.abstol = 1e-10;
+% OPTIONS.reltol = 1e-10;
+% disp('!!!!!!!!!!!!!!!!!!!!!!')
+% disp('TOLERANCE SET TO 1e-10')
+% disp('!!!!!!!!!!!!!!!!!!!!!!')
+
+% assignments in handles structure
+handles.modelindex = modelindex;
+handles.projectstruct = struct(project);
+handles.estimation = [];       % not used in here
+handles.integratoroptions = OPTIONS;
+handles.event_param_names = event_param_names;
+handles.nrsliders = 7;  % not really used everywhere yet
+handles.saveORIGprojectstruct = handles.projectstruct; % save the unchanged project structure for output 
+handles.experimentindices = 1; % just a single experiment
+
+% initialize the plotdata
+handles.plotdata = initializePlotdata(handles.projectstruct,modelindex,handles);
+
+% set modelselection and choose first model (only one model in project)
+handles.modelselection = 1;
+
+% set experimentselection and choose first experiment (only one experiment in the project)
+handles.experimentselection = 1;
+
+% set component selection
+set(handles.componentselection,'String',handles.plotdata.model(1).allmeascomponents);
+set(handles.componentselection,'Value',1);
+
+% determine parameter data
+handles = getparamdata(handles);
+
+% set all parameter selection boxes with parameter names (model dependent)
+initializeParameterLists(handles);
+% select plottype
+handles.dataPlotType = 'plot';     
+% set errorbarflag to 1
+handles.errorbars = 1;
+% Initialize export figure handle and grid flag
+handles.exportFigureHandle = [];
+handles.grid = 0;
+% Doing a first plot
+doPlot(handles);
+% Choose default command line output for modeltuningGUISBPD
+handles.output = hObject;
+% Update handles structure
+guidata(hObject, handles);
+uiwait;
+return
+
+% --- Outputs from this function are returned to the command line.
+function varargout = modeltuningGUISBPD_OutputFcn(hObject, eventdata, handles) 
+% varargout  cell array for returning output args (see VARARGOUT);
+varargout{1} = handles.output;
+% delete temporary MEX models
+global compiledExpModelsSBPDgui % if not empty then models are precompiled and should not be deleted
+if isempty(compiledExpModelsSBPDgui),
+    clear mex
+    for m=1:length(handles.plotdata.model)
+        for e=1:length(handles.plotdata.model(m).experiment),
+            delete(handles.plotdata.model(m).experiment(e).mexfullpath);
+        end
+    end
+end
+% close the GUI
+delete(hObject);
+return
+
+% --- Closed by user
+function modeltuningGUISBPD_CloseRequestFcn(hObject, eventdata, handles)
+exit_Callback(hObject, eventdata, handles)
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXIT modeltuningGUISBPD CALLBACK
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function exit_Callback(hObject, eventdata, handles)
+    % construct the output (its just an updated SBPDproject in which the 
+    % manually tuned parametervalues are entered)
+    % FOR THIS USE THE SAVED ORIG PROJECT!
+    for k=1:length(handles.modelindex),
+        m = handles.modelindex(k);
+        % get model to update
+        model = handles.saveORIGprojectstruct.models{m};
+        % set manually tuned parameters
+        % take away the things that are no parameters
+        noParamIndices = strmatchSB('No Parameter',handles.parammodel(k).names,'exact');
+        paramIndices = setdiff([1:length(handles.parammodel(k).names)],noParamIndices);
+        paramnames = handles.parammodel(k).names(paramIndices);
+        paramvalues = handles.parammodel(k).values(paramIndices);
+        model = SBparameters(model,paramnames,paramvalues);
+        % add model to project
+        handles.saveORIGprojectstruct.models{m} = model;
+    end
+    handles.output = SBPDproject(handles.saveORIGprojectstruct);
+    % Update handles structure
+    guidata(hObject, handles);
+    uiresume;
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SIMULATION FUNCTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function handles=doSimAndPlot(handles)
+% get the parameter values to use for simulation
+m = handles.modelselection;
+%pv = handles.parammodel(m).values;
+% run through all experiments and perform them for the parameter settings
+for e = 1:length(handles.plotdata.model(m).experiment),
+    mexmodel = handles.plotdata.model(m).experiment(e).mexmodel;
+    timevector = handles.plotdata.model(m).experiment(e).timevector;
+    ic = handles.plotdata.model(m).experiment(e).initialconditions;
+    % take away the things that are no parameters
+    noParamIndices = strmatchSB('No Parameter',handles.parammodel(m).names,'exact');
+    paramIndices = setdiff([1:length(handles.parammodel(m).names)],noParamIndices);
+    paramnames = handles.parammodel(m).names(paramIndices);
+    paramvalues = handles.parammodel(m).values(paramIndices);
+    % construct parameter vector for simulation
+    pv = makeparamvecSBPD(mexmodel,paramnames,paramvalues);
+    try
+        simdata = feval(mexmodel,timevector,ic,pv,handles.integratoroptions);
+    catch
+        simdata = [];
+        break;
+    end
+    stateindices = handles.plotdata.model(m).experiment(e).stateindices;
+    statevalues = simdata.statevalues(:,stateindices);
+    variableindices = handles.plotdata.model(m).experiment(e).variableindices;
+    variablevalues = simdata.variablevalues(:,variableindices);
+    handles.plotdata.model(m).experiment(e).componentvalues = [statevalues variablevalues];
+end
+if ~isempty(simdata),
+    doPlot(handles);
+else
+    errordlg('Parameter setting leads to error.');
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PLOT FUNCTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% For each selected component a single plot will be shown
+function doPlot(handles)
+colorvector = {'b','g','r','c','m','y','k'};
+warning off;
+% get the data to plot
+plotdata = handles.plotdata;
+m = handles.modelselection;
+e = handles.experimentselection;
+callnames = get(handles.componentselection,'String');
+callselected = get(handles.componentselection,'Value');
+NTOTAL = length(callselected);
+NROW = ceil(sqrt(NTOTAL));
+NCOL = ceil(NTOTAL/NROW);
+for sp = 1:NTOTAL,
+    % component name ... for plotting
+    cname = callnames{callselected(sp)};
+    % generate subplot and get data
+    subplot(NROW,NCOL,sp,'Parent',handles.plotpanel);
+    edata = plotdata.model(m).experiment(e);
+    % general information
+    titletext = cname;
+    xlabeltext = 'Time';
+    % simulated data information
+    sim_timevector = edata.timevector;
+    sim_componentnames = cname;
+    index = strmatchSB(cname,edata.componentnames,'exact');
+    sim_componentvalues = edata.componentvalues(:,index);
+    % plot simulated data
+    feval(handles.dataPlotType,sim_timevector,sim_componentvalues,'k','linewidth',2); hold on;
+    % plot measured data
+    for meas=1:length(edata.measurement),
+        meas_timevector = edata.measurement(meas).timevector;
+        meas_componentnames = edata.measurement(meas).componentnames;
+        meas_componentvalues = edata.measurement(meas).componentvalues;
+        meas_maxvalues = edata.measurement(meas).maxvalues;
+        meas_minvalues = edata.measurement(meas).minvalues;
+        index = strmatchSB(cname,meas_componentnames,'exact');
+        if ~isempty(index),
+            % plot the measured values
+            meas_componentvalues = meas_componentvalues(:,index);
+            color = colorvector{mod(meas-1,length(colorvector))+1};
+            feval(handles.dataPlotType,meas_timevector,meas_componentvalues,[color '.'],'linewidth',2); hold on;        
+            % plot the errorbars (if desired)
+            meas_maxvalues = meas_maxvalues(:,index);
+            meas_minvalues = meas_minvalues(:,index);
+            if handles.errorbars == 1 && strcmp(handles.dataPlotType,'plot'),
+                % plot errorbars
+                for k1 = 1:length(meas_timevector),
+                    feval(handles.dataPlotType,[meas_timevector(k1),meas_timevector(k1)],[meas_minvalues(k1),meas_maxvalues(k1)],['.:',color]);
+                end
+            end
+        end
+    end
+    hold off;
+    hlhlx = legend(sim_componentnames);
+    set(hlhlx,'Interpreter','none');
+    hlhlx = title(titletext);
+    set(hlhlx,'Interpreter','none');
+    hlhlx = xlabel(xlabeltext);
+    set(hlhlx,'Interpreter','none');
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine parameter data and save in handles structure
+% Only parameters that appear in all expmmexmodels are considered.
+% Furthermore, they need to have the same values (so that they are not
+% modified due to experimental settings)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function handles = getparamdata(handles)
+% CODE VALID ONLY IF HANDLES.ESTIMATION = [] (THE CASE HERE)
+for m = 1:length(handles.plotdata.model),
+    % get parameter names that appear in all expmexmodels
+    for e = 1:length(handles.plotdata.model(m).experiment),
+        model = handles.plotdata.model(m).experiment(e).mexmodel;
+        if e == 1,
+            parameters = feval(model,'parameters');
+        else
+            parameters = intersect(parameters, feval(model,'parameters'));
+        end
+    end
+    % keep only those parameters that have the same value (not changed by
+    % experiment or changed equally)
+    indexdelete = [];
+    for e = 1:length(handles.plotdata.model(m).experiment),
+        model = handles.plotdata.model(m).experiment(e).mexmodel;
+        if e == 1,
+            % first run just get the parametervalues
+            parametervalues = SBparameters(model,parameters);
+        else
+            % subsequent runs ... check if equal and get the indices of the
+            % non equal entries
+            pv = SBparameters(model,parameters);
+            indexdelete = unique([indexdelete(:)', find(pv(:)'~=parametervalues(:)')]);
+        end
+    end
+    indexkeep = setdiff([1:length(parameters)],indexdelete);
+    parameters = parameters(indexkeep);
+    % FINALLY ALSO REMOVE THE PARAMETERS THAT ARE CHANGED BY EVENTS DURING
+    % THE SIMULATION (DEFINED IN: handles.event_param_names)
+    parameters = setdiff(parameters,handles.event_param_names);
+    parametervalues = SBparameters(model,parameters);
+    % add param info to structure
+    handles.parammodel(m).names = parameters;
+    handles.parammodel(m).values = parametervalues;
+    handles.parammodel(m).startvalues = parametervalues;
+    max = 100*parametervalues;
+    max(find(max==0)) = 1;
+    handles.parammodel(m).max = max;
+    handles.parammodel(m).startmax = max;
+    handles.parammodel(m).min = 0.01*parametervalues;
+    handles.parammodel(m).startmin = 0.01*parametervalues;
+end
+% if fewer parameters than handles.nrsliders then add dummy ones
+if length(parametervalues) < handles.nrsliders,
+    for k=1:(handles.nrsliders-length(parametervalues)),
+        handles.parammodel.names{end+1} = 'No Parameter';
+        handles.parammodel.values(end+1) = NaN;
+        handles.parammodel.startvalues(end+1) = NaN;
+        handles.parammodel.max(end+1) = NaN;
+        handles.parammodel.startmax(end+1) = NaN;
+        handles.parammodel.min(end+1) = NaN;
+        handles.parammodel.startmin(end+1) = NaN;
+    end
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Initialize parameter lists
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [] = initializeParameterLists(handles,varargin)
+if nargin == 1,
+    i1 = 1;
+    i2 = 2;
+    i3 = 3;
+    i4 = 4;
+    i5 = 5;
+    i6 = 6;
+    i7 = 7;
+elseif nargin == 2,
+    if strcmp(varargin{1},'resetall'),
+        i1 = 1;
+        i2 = 2;
+        i3 = 3;
+        i4 = 4;
+        i5 = 5;
+        i6 = 6;
+        i7 = 7;
+    else
+        i1 = get(handles.manualparam1,'Value');
+        i2 = get(handles.manualparam2,'Value');
+        i3 = get(handles.manualparam3,'Value');
+        i4 = get(handles.manualparam4,'Value');
+        i5 = get(handles.manualparam5,'Value');
+        i6 = get(handles.manualparam6,'Value');
+        i7 = get(handles.manualparam7,'Value');
+    end
+end
+
+m = handles.modelselection;
+% get the models parameters and values
+parameters = handles.parammodel(m).names;
+parametervalues = handles.parammodel(m).values;
+parammax = handles.parammodel(m).max;
+parammin = handles.parammodel(m).min;
+% set the 7 parameter lists (adjust list of parameters)
+nrtakeaway = length(strmatchSB('No Parameter',parameters,'exact'));
+if nrtakeaway > 0,
+    endindex = handles.nrsliders-nrtakeaway;
+    set(handles.manualparam1,'String',parameters(1:endindex));
+    set(handles.manualparam2,'String',parameters(1:endindex));
+    set(handles.manualparam3,'String',parameters(1:endindex));
+    set(handles.manualparam4,'String',parameters(1:endindex));
+    set(handles.manualparam5,'String',parameters(1:endindex));
+    set(handles.manualparam6,'String',parameters(1:endindex));
+    set(handles.manualparam7,'String',parameters(1:endindex));
+else
+    set(handles.manualparam1,'String',parameters);
+    set(handles.manualparam2,'String',parameters);
+    set(handles.manualparam3,'String',parameters);
+    set(handles.manualparam4,'String',parameters);
+    set(handles.manualparam5,'String',parameters);
+    set(handles.manualparam6,'String',parameters);
+    set(handles.manualparam7,'String',parameters);
+end    
+% set selected values
+set(handles.manualparam1,'Value',i1);
+set(handles.manualparam2,'Value',i2);
+set(handles.manualparam3,'Value',i3);
+set(handles.manualparam4,'Value',i4);
+set(handles.manualparam5,'Value',i5);
+set(handles.manualparam6,'Value',i6);
+set(handles.manualparam7,'Value',i7);
+% set current parameter values
+set(handles.value1,'String',parametervalues(i1));
+set(handles.value2,'String',parametervalues(i2));
+set(handles.value3,'String',parametervalues(i3));
+set(handles.value4,'String',parametervalues(i4));
+set(handles.value5,'String',parametervalues(i5));
+set(handles.value6,'String',parametervalues(i6));
+set(handles.value7,'String',parametervalues(i7));
+% set max and min values per default to *100 / *0.01
+set(handles.manualmax1,'String',parammax(i1));
+set(handles.manualmax2,'String',parammax(i2));
+set(handles.manualmax3,'String',parammax(i3));
+set(handles.manualmax4,'String',parammax(i4));
+set(handles.manualmax5,'String',parammax(i5));
+set(handles.manualmax6,'String',parammax(i6));
+set(handles.manualmax7,'String',parammax(i7));
+set(handles.manualmin1,'String',parammin(i1));
+set(handles.manualmin2,'String',parammin(i2));
+set(handles.manualmin3,'String',parammin(i3));
+set(handles.manualmin4,'String',parammin(i4));
+set(handles.manualmin5,'String',parammin(i5));
+set(handles.manualmin6,'String',parammin(i6));
+set(handles.manualmin7,'String',parammin(i7));
+% set slider min max and value
+set(handles.manualslider1,'Max',101);
+set(handles.manualslider2,'Max',101);
+set(handles.manualslider3,'Max',101);
+set(handles.manualslider4,'Max',101);
+set(handles.manualslider5,'Max',101);
+set(handles.manualslider6,'Max',101);
+set(handles.manualslider7,'Max',101);
+set(handles.manualslider1,'Min',1);
+set(handles.manualslider2,'Min',1);
+set(handles.manualslider3,'Min',1);
+set(handles.manualslider4,'Min',1);
+set(handles.manualslider5,'Min',1);
+set(handles.manualslider6,'Min',1);
+set(handles.manualslider7,'Min',1);
+% construct vectors
+if parammin(i1) > 0,
+    vector1 = logspace(log(parammin(i1))/log(10),log(parammax(i1))/log(10),101);
+else
+    vector1 = [parammin(i1):(parammax(i1)-parammin(i1))/100:parammax(i1)];
+end
+if parammin(i2) > 0,
+    vector2 = logspace(log(parammin(i2))/log(10),log(parammax(i2))/log(10),101);
+else
+    vector2 = [parammin(i2):(parammax(i2)-parammin(i2))/100:parammax(i2)];
+end
+if parammin(i3) > 0,
+    vector3 = logspace(log(parammin(i3))/log(10),log(parammax(i3))/log(10),101);
+else
+    vector3 = [parammin(i3):(parammax(i3)-parammin(i3))/100:parammax(i3)];
+end
+if parammin(i4) > 0,
+    vector4 = logspace(log(parammin(i4))/log(10),log(parammax(i4))/log(10),101);
+else
+    vector4 = [parammin(i4):(parammax(i4)-parammin(i4))/100:parammax(i4)];
+end
+if parammin(i5) > 0,
+    vector5 = logspace(log(parammin(i5))/log(10),log(parammax(i5))/log(10),101);
+else
+    vector5 = [parammin(i5):(parammax(i5)-parammin(i5))/100:parammax(i5)];
+end
+if parammin(i6) > 0,
+    vector6 = logspace(log(parammin(i6))/log(10),log(parammax(i6))/log(10),101);
+else
+    vector6 = [parammin(i6):(parammax(i6)-parammin(i6))/100:parammax(i6)];
+end
+if parammin(i7) > 0,
+    vector7 = logspace(log(parammin(i7))/log(10),log(parammax(i7))/log(10),101);
+else
+    vector7 = [parammin(i7):(parammax(i7)-parammin(i7))/100:parammax(i7)];
+end
+% set sliders
+[dummy,index] = min(abs(vector1-parametervalues(i1)));
+set(handles.manualslider1,'Value',index);
+[dummy,index] = min(abs(vector2-parametervalues(i2)));
+set(handles.manualslider2,'Value',index);
+[dummy,index] = min(abs(vector3-parametervalues(i3)));
+set(handles.manualslider3,'Value',index);
+[dummy,index] = min(abs(vector4-parametervalues(i4)));
+set(handles.manualslider4,'Value',index);
+[dummy,index] = min(abs(vector5-parametervalues(i5)));
+set(handles.manualslider5,'Value',index);
+[dummy,index] = min(abs(vector6-parametervalues(i6)));
+set(handles.manualslider6,'Value',index);
+[dummy,index] = min(abs(vector7-parametervalues(i7)));
+set(handles.manualslider7,'Value',index);
+% set slider steps
+set(handles.manualslider1,'SliderStep',[0.01 0.01]);
+set(handles.manualslider2,'SliderStep',[0.01 0.01]);
+set(handles.manualslider3,'SliderStep',[0.01 0.01]);
+set(handles.manualslider4,'SliderStep',[0.01 0.01]);
+set(handles.manualslider5,'SliderStep',[0.01 0.01]);
+set(handles.manualslider6,'SliderStep',[0.01 0.01]);
+set(handles.manualslider7,'SliderStep',[0.01 0.01]);
+% set Enable to off for the elements
+nrtakeaway = length(strmatchSB('No Parameter',parameters,'exact'));
+if nrtakeaway >= 7,
+    set(handles.manualslider1,'Enable','off');
+    set(handles.manualmax1,'Enable','off');
+    set(handles.manualmin1,'Enable','off');
+    set(handles.manualparam1,'Enable','off');
+end
+if nrtakeaway >= 6,
+    set(handles.manualslider2,'Enable','off');
+    set(handles.manualmax2,'Enable','off');
+    set(handles.manualmin2,'Enable','off');
+    set(handles.manualparam2,'Enable','off');
+end
+if nrtakeaway >= 5,
+    set(handles.manualslider3,'Enable','off');
+    set(handles.manualmax3,'Enable','off');
+    set(handles.manualmin3,'Enable','off');
+    set(handles.manualparam3,'Enable','off');
+end
+if nrtakeaway >= 4,
+    set(handles.manualslider4,'Enable','off');
+    set(handles.manualmax4,'Enable','off');
+    set(handles.manualmin4,'Enable','off');
+    set(handles.manualparam4,'Enable','off');
+end
+if nrtakeaway >= 3,
+    set(handles.manualslider5,'Enable','off');
+    set(handles.manualmax5,'Enable','off');
+    set(handles.manualmin5,'Enable','off');
+    set(handles.manualparam5,'Enable','off');
+end
+if nrtakeaway >= 2,
+    set(handles.manualslider6,'Enable','off');
+    set(handles.manualmax6,'Enable','off');
+    set(handles.manualmin6,'Enable','off');
+    set(handles.manualparam6,'Enable','off');
+end
+if nrtakeaway >= 1,
+    set(handles.manualslider7,'Enable','off');
+    set(handles.manualmax7,'Enable','off');
+    set(handles.manualmin7,'Enable','off');
+    set(handles.manualparam7,'Enable','off');
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Slider1 handling function
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function slider1_Callback(hObject, eventdata, handles)
+% get slider settings
+v = ceil(get(handles.manualslider1,'Value'));                       %%%
+% get min max settings
+maxV = str2double(get(handles.manualmax1,'String'));                %%%
+minV = str2double(get(handles.manualmin1,'String'));                %%%
+% construct vectors
+if minV > 0,
+    vector = logspace(log(minV)/log(10),log(maxV)/log(10),101);
+else
+    vector = [minV:(maxV-minV)/100:maxV];
+end
+% get paramvalues
+value = vector(v);
+% set parameter value
+set(handles.value1,'String',value);                                 %%%
+% update parameter information structure in handles with new values
+m = handles.modelselection;
+pindex = get(handles.manualparam1,'Value');                         %%%
+handles.parammodel(m).values(pindex) = value;
+% sim and plot
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Slider2 handling function
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function slider2_Callback(hObject, eventdata, handles)
+% get slider settings
+v = ceil(get(handles.manualslider2,'Value'));                       %%%
+% get min max settings
+maxV = str2double(get(handles.manualmax2,'String'));                %%%
+minV = str2double(get(handles.manualmin2,'String'));                %%%
+% construct vectors
+if minV > 0,
+    vector = logspace(log(minV)/log(10),log(maxV)/log(10),101);
+else
+    vector = [minV:(maxV-minV)/100:maxV];
+end
+% get paramvalues
+value = vector(v);
+% set parameter value
+set(handles.value2,'String',value);                                 %%%
+% update parameter information structure in handles with new values
+m = handles.modelselection;
+pindex = get(handles.manualparam2,'Value');                         %%%
+handles.parammodel(m).values(pindex) = value;
+% sim and plot
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Slider3 handling function
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function slider3_Callback(hObject, eventdata, handles)
+% get slider settings
+v = ceil(get(handles.manualslider3,'Value'));                       %%%
+% get min max settings
+maxV = str2double(get(handles.manualmax3,'String'));                %%%
+minV = str2double(get(handles.manualmin3,'String'));                %%%
+% construct vectors
+if minV > 0,
+    vector = logspace(log(minV)/log(10),log(maxV)/log(10),101);
+else
+    vector = [minV:(maxV-minV)/100:maxV];
+end
+% get paramvalues
+value = vector(v);
+% set parameter value
+set(handles.value3,'String',value);                                 %%%
+% update parameter information structure in handles with new values
+m = handles.modelselection;
+pindex = get(handles.manualparam3,'Value');                         %%%
+handles.parammodel(m).values(pindex) = value;
+% sim and plot
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Slider4 handling function
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function slider4_Callback(hObject, eventdata, handles)
+% get slider settings
+v = ceil(get(handles.manualslider4,'Value'));                       %%%
+% get min max settings
+maxV = str2double(get(handles.manualmax4,'String'));                %%%
+minV = str2double(get(handles.manualmin4,'String'));                %%%
+% construct vectors
+if minV > 0,
+    vector = logspace(log(minV)/log(10),log(maxV)/log(10),101);
+else
+    vector = [minV:(maxV-minV)/100:maxV];
+end
+% get paramvalues
+value = vector(v);
+% set parameter value
+set(handles.value4,'String',value);                                 %%%
+% update parameter information structure in handles with new values
+m = handles.modelselection;
+pindex = get(handles.manualparam4,'Value');                         %%%
+handles.parammodel(m).values(pindex) = value;
+% sim and plot
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Slider5 handling function
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function slider5_Callback(hObject, eventdata, handles)
+% get slider settings
+v = ceil(get(handles.manualslider5,'Value'));                       %%%
+% get min max settings
+maxV = str2double(get(handles.manualmax5,'String'));                %%%
+minV = str2double(get(handles.manualmin5,'String'));                %%%
+% construct vectors
+if minV > 0,
+    vector = logspace(log(minV)/log(10),log(maxV)/log(10),101);
+else
+    vector = [minV:(maxV-minV)/100:maxV];
+end
+% get paramvalues
+value = vector(v);
+% set parameter value
+set(handles.value5,'String',value);                                 %%%
+% update parameter information structure in handles with new values
+m = handles.modelselection;
+pindex = get(handles.manualparam5,'Value');                         %%%
+handles.parammodel(m).values(pindex) = value;
+% sim and plot
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Slider6 handling function
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function slider6_Callback(hObject, eventdata, handles)
+% get slider settings
+v = ceil(get(handles.manualslider6,'Value'));                       %%%
+% get min max settings
+maxV = str2double(get(handles.manualmax6,'String'));                %%%
+minV = str2double(get(handles.manualmin6,'String'));                %%%
+% construct vectors
+if minV > 0,
+    vector = logspace(log(minV)/log(10),log(maxV)/log(10),101);
+else
+    vector = [minV:(maxV-minV)/100:maxV];
+end
+% get paramvalues
+value = vector(v);
+% set parameter value
+set(handles.value6,'String',value);                                 %%%
+% update parameter information structure in handles with new values
+m = handles.modelselection;
+pindex = get(handles.manualparam6,'Value');                         %%%
+handles.parammodel(m).values(pindex) = value;
+% sim and plot
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Slider7 handling function
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function slider7_Callback(hObject, eventdata, handles)
+% get slider settings
+v = ceil(get(handles.manualslider7,'Value'));                       %%%
+% get min max settings
+maxV = str2double(get(handles.manualmax7,'String'));                %%%
+minV = str2double(get(handles.manualmin7,'String'));                %%%
+% construct vectors
+if minV > 0,
+    vector = logspace(log(minV)/log(10),log(maxV)/log(10),101);
+else
+    vector = [minV:(maxV-minV)/100:maxV];
+end
+% get paramvalues
+value = vector(v);
+% set parameter value
+set(handles.value7,'String',value);                                 %%%
+% update parameter information structure in handles with new values
+m = handles.modelselection;
+pindex = get(handles.manualparam7,'Value');                         %%%
+handles.parammodel(m).values(pindex) = value;
+% sim and plot
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Minmax handling function
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function minmax1_Callback(hObject, eventdata, handles)
+% get max min values
+max1 = str2double(get(handles.manualmax1,'String'));
+min1 = str2double(get(handles.manualmin1,'String'));
+% get slider setting
+v1 = ceil(get(handles.manualslider1,'Value'));
+% get current value
+value1 = str2double(get(handles.value1,'String'));
+% check and adjust bounds if needed
+if value1 < min1, value1 = min1; end
+if value1 > max1, value1 = max1; end
+% set slider value to correspond to value
+if min1 > 0,
+    vector1 = logspace(log(min1)/log(10),log(max1)/log(10),101);
+else
+    vector1 = [min1:(max1-min1)/100:max1];
+end
+[dummy,index] = min(abs(vector1-value1));
+set(handles.manualslider1,'Value',index);
+% update values field
+value1 = vector1(index);
+set(handles.value1,'String',value1);
+% update parameter information structure in handles with new value
+m = handles.modelselection;
+pindex = get(handles.manualparam1,'Value');
+handles.parammodel(m).max(pindex) = max1;
+handles.parammodel(m).min(pindex) = min1;
+handles.parammodel(m).values(pindex) = value1;
+% sim and plot
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+function minmax2_Callback(hObject, eventdata, handles)
+% get max min values
+max2 = str2double(get(handles.manualmax2,'String'));
+min2 = str2double(get(handles.manualmin2,'String'));
+% get slider setting
+v2 = ceil(get(handles.manualslider2,'Value'));
+% get current value
+value2 = str2double(get(handles.value2,'String'));
+% check and adjust bounds if needed
+if value2 < min2, value2 = min2; end
+if value2 > max2, value2 = max2; end
+% set slider value to correspond to value
+if min2 > 0,
+    vector2 = logspace(log(min2)/log(10),log(max2)/log(10),101);
+else
+    vector2 = [min2:(max2-min2)/100:max2];
+end
+[dummy,index] = min(abs(vector2-value2));
+set(handles.manualslider2,'Value',index);
+% update values field
+value2 = vector2(index);
+set(handles.value2,'String',value2);
+% update parameter information structure in handles with new value
+m = handles.modelselection;
+pindex = get(handles.manualparam2,'Value');
+handles.parammodel(m).max(pindex) = max2;
+handles.parammodel(m).min(pindex) = min2;
+handles.parammodel(m).values(pindex) = value2;
+% sim and plot
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+function minmax3_Callback(hObject, eventdata, handles)
+% get max min values
+max3 = str2double(get(handles.manualmax3,'String'));
+min3 = str2double(get(handles.manualmin3,'String'));
+% get slider setting
+v3 = ceil(get(handles.manualslider3,'Value'));
+% get current value
+value3 = str2double(get(handles.value3,'String'));
+% check and adjust bounds if needed
+if value3 < min3, value3 = min3; end
+if value3 > max3, value3 = max3; end
+% set slider value to correspond to value
+if min3 > 0,
+    vector3 = logspace(log(min3)/log(10),log(max3)/log(10),101);
+else
+    vector3 = [min3:(max3-min3)/100:max3];
+end
+[dummy,index] = min(abs(vector3-value3));
+set(handles.manualslider3,'Value',index);
+% update values field
+value3 = vector3(index);
+set(handles.value3,'String',value3);
+% update parameter information structure in handles with new value
+m = handles.modelselection;
+pindex = get(handles.manualparam3,'Value');
+handles.parammodel(m).max(pindex) = max3;
+handles.parammodel(m).min(pindex) = min3;
+handles.parammodel(m).values(pindex) = value3;
+% sim and plot
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+function minmax4_Callback(hObject, eventdata, handles)
+% get max min values
+max4 = str2double(get(handles.manualmax4,'String'));
+min4 = str2double(get(handles.manualmin4,'String'));
+% get slider setting
+v4 = ceil(get(handles.manualslider4,'Value'));
+% get current value
+value4 = str2double(get(handles.value4,'String'));
+% check and adjust bounds if needed
+if value4 < min4, value4 = min4; end
+if value4 > max4, value4 = max4; end
+% set slider value to correspond to value
+if min4 > 0,
+    vector4 = logspace(log(min4)/log(10),log(max4)/log(10),101);
+else
+    vector4 = [min4:(max4-min4)/100:max4];
+end
+[dummy,index] = min(abs(vector4-value4));
+set(handles.manualslider4,'Value',index);
+% update values field
+value4 = vector4(index);
+set(handles.value4,'String',value4);
+% update parameter information structure in handles with new value
+m = handles.modelselection;
+pindex = get(handles.manualparam4,'Value');
+handles.parammodel(m).max(pindex) = max4;
+handles.parammodel(m).min(pindex) = min4;
+handles.parammodel(m).values(pindex) = value4;
+% sim and plot
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+function minmax5_Callback(hObject, eventdata, handles)
+% get max min values
+max5 = str2double(get(handles.manualmax5,'String'));
+min5 = str2double(get(handles.manualmin5,'String'));
+% get slider setting
+v5 = ceil(get(handles.manualslider5,'Value'));
+% get current value
+value5 = str2double(get(handles.value5,'String'));
+% check and adjust bounds if needed
+if value5 < min5, value5 = min5; end
+if value5 > max5, value5 = max5; end
+% set slider value to correspond to value
+if min5 > 0,
+    vector5 = logspace(log(min5)/log(10),log(max5)/log(10),101);
+else
+    vector5 = [min5:(max5-min5)/100:max5];
+end
+[dummy,index] = min(abs(vector5-value5));
+set(handles.manualslider5,'Value',index);
+% update values field
+value5 = vector5(index);
+set(handles.value5,'String',value5);
+% update parameter information structure in handles with new value
+m = handles.modelselection;
+pindex = get(handles.manualparam5,'Value');
+handles.parammodel(m).max(pindex) = max5;
+handles.parammodel(m).min(pindex) = min5;
+handles.parammodel(m).values(pindex) = value5;
+% sim and plot
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+function minmax6_Callback(hObject, eventdata, handles)
+% get max min values
+max6 = str2double(get(handles.manualmax6,'String'));
+min6 = str2double(get(handles.manualmin6,'String'));
+% get slider setting
+v6 = ceil(get(handles.manualslider6,'Value'));
+% get current value
+value6 = str2double(get(handles.value6,'String'));
+% check and adjust bounds if needed
+if value6 < min6, value6 = min6; end
+if value6 > max6, value6 = max6; end
+% set slider value to correspond to value
+if min6 > 0,
+    vector6 = logspace(log(min6)/log(10),log(max6)/log(10),101);
+else
+    vector6 = [min6:(max6-min6)/100:max6];
+end
+[dummy,index] = min(abs(vector6-value6));
+set(handles.manualslider6,'Value',index);
+% update values field
+value6 = vector6(index);
+set(handles.value6,'String',value6);
+% update parameter information structure in handles with new value
+m = handles.modelselection;
+pindex = get(handles.manualparam6,'Value');
+handles.parammodel(m).max(pindex) = max6;
+handles.parammodel(m).min(pindex) = min6;
+handles.parammodel(m).values(pindex) = value6;
+% sim and plot
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+function minmax7_Callback(hObject, eventdata, handles)
+% get max min values
+max7 = str2double(get(handles.manualmax7,'String'));
+min7 = str2double(get(handles.manualmin7,'String'));
+% get slider setting
+v7 = ceil(get(handles.manualslider7,'Value'));
+% get current value
+value7 = str2double(get(handles.value7,'String'));
+% check and adjust bounds if needed
+if value7 < min7, value7 = min7; end
+if value7 > max7, value7 = max7; end
+% set slider value to correspond to value
+if min7 > 0,
+    vector7 = logspace(log(min7)/log(10),log(max7)/log(10),101);
+else
+    vector7 = [min7:(max7-min7)/100:max7];
+end
+[dummy,index] = min(abs(vector7-value7));
+set(handles.manualslider7,'Value',index);
+% update values field
+value7 = vector7(index);
+set(handles.value7,'String',value7);
+% update parameter information structure in handles with new value
+m = handles.modelselection;
+pindex = get(handles.manualparam7,'Value');
+handles.parammodel(m).max(pindex) = max7;
+handles.parammodel(m).min(pindex) = min7;
+handles.parammodel(m).values(pindex) = value7;
+% sim and plot
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% MODEL PARAMETER HANDLING
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function manualparam1_Callback(hObject, eventdata, handles)
+m = handles.modelselection;
+pindex = get(handles.manualparam1,'Value');
+paramvalue = handles.parammodel(m).values(pindex);
+% set current parameter values
+set(handles.value1,'String',paramvalue);
+% set max and min values 
+max = handles.parammodel(m).max(pindex);
+min = handles.parammodel(m).min(pindex);
+set(handles.manualmax1,'String',max);
+set(handles.manualmin1,'String',min);
+% set slider min max and value
+set(handles.manualslider1,'Max',101);
+set(handles.manualslider1,'Min',1);
+% set slider value to correspond to value
+if min > 0,
+    vector = logspace(log(min)/log(10),log(max)/log(10),101);
+else
+    vector = [min:(max-min)/100:max];
+end
+[dummy,index] = minfunct(abs(vector-paramvalue));
+set(handles.manualslider1,'Value',index);
+% set slider steps
+set(handles.manualslider1,'SliderStep',[0.01 0.01]);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+function [a,b] = minfunct(X)
+[a,b] = min(X);
+return
+
+function manualparam2_Callback(hObject, eventdata, handles)
+m = handles.modelselection;
+pindex = get(handles.manualparam2,'Value');
+paramvalue = handles.parammodel(m).values(pindex);
+% set current parameter values
+set(handles.value2,'String',paramvalue);
+% set max and min values 
+max = handles.parammodel(m).max(pindex);
+min = handles.parammodel(m).min(pindex);
+set(handles.manualmax2,'String',max);
+set(handles.manualmin2,'String',min);
+% set slider min max and value
+set(handles.manualslider2,'Max',101);
+set(handles.manualslider2,'Min',1);
+% set slider value to correspond to value
+if min > 0,
+    vector = logspace(log(min)/log(10),log(max)/log(10),101);
+else
+    vector = [min:(max-min)/100:max];
+end
+[dummy,index] = minfunct(abs(vector-paramvalue));
+set(handles.manualslider2,'Value',index);
+% set slider steps
+set(handles.manualslider2,'SliderStep',[0.01 0.01]);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+function manualparam3_Callback(hObject, eventdata, handles)
+m = handles.modelselection;
+pindex = get(handles.manualparam3,'Value');
+paramvalue = handles.parammodel(m).values(pindex);
+% set current parameter values
+set(handles.value3,'String',paramvalue);
+% set max and min values 
+max = handles.parammodel(m).max(pindex);
+min = handles.parammodel(m).min(pindex);
+set(handles.manualmax3,'String',max);
+set(handles.manualmin3,'String',min);
+% set slider min max and value
+set(handles.manualslider3,'Max',101);
+set(handles.manualslider3,'Min',1);
+% set slider value to correspond to value
+if min > 0,
+    vector = logspace(log(min)/log(10),log(max)/log(10),101);
+else
+    vector = [min:(max-min)/100:max];
+end
+[dummy,index] = minfunct(abs(vector-paramvalue));
+set(handles.manualslider3,'Value',index);
+% set slider steps
+set(handles.manualslider3,'SliderStep',[0.01 0.01]);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+function manualparam4_Callback(hObject, eventdata, handles)
+m = handles.modelselection;
+pindex = get(handles.manualparam4,'Value');
+paramvalue = handles.parammodel(m).values(pindex);
+% set current parameter values
+set(handles.value4,'String',paramvalue);
+% set max and min values 
+max = handles.parammodel(m).max(pindex);
+min = handles.parammodel(m).min(pindex);
+set(handles.manualmax4,'String',max);
+set(handles.manualmin4,'String',min);
+% set slider min max and value
+set(handles.manualslider4,'Max',101);
+set(handles.manualslider4,'Min',1);
+% set slider value to correspond to value
+if min > 0,
+    vector = logspace(log(min)/log(10),log(max)/log(10),101);
+else
+    vector = [min:(max-min)/100:max];
+end
+[dummy,index] = minfunct(abs(vector-paramvalue));
+set(handles.manualslider4,'Value',index);
+% set slider steps
+set(handles.manualslider4,'SliderStep',[0.01 0.01]);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+function manualparam5_Callback(hObject, eventdata, handles)
+m = handles.modelselection;
+pindex = get(handles.manualparam5,'Value');
+paramvalue = handles.parammodel(m).values(pindex);
+% set current parameter values
+set(handles.value5,'String',paramvalue);
+% set max and min values 
+max = handles.parammodel(m).max(pindex);
+min = handles.parammodel(m).min(pindex);
+set(handles.manualmax5,'String',max);
+set(handles.manualmin5,'String',min);
+% set slider min max and value
+set(handles.manualslider5,'Max',101);
+set(handles.manualslider5,'Min',1);
+% set slider value to correspond to value
+if min > 0,
+    vector = logspace(log(min)/log(10),log(max)/log(10),101);
+else
+    vector = [min:(max-min)/100:max];
+end
+[dummy,index] = minfunct(abs(vector-paramvalue));
+set(handles.manualslider5,'Value',index);
+% set slider steps
+set(handles.manualslider5,'SliderStep',[0.01 0.01]);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+function manualparam6_Callback(hObject, eventdata, handles)
+m = handles.modelselection;
+pindex = get(handles.manualparam6,'Value');
+paramvalue = handles.parammodel(m).values(pindex);
+% set current parameter values
+set(handles.value6,'String',paramvalue);
+% set max and min values 
+max = handles.parammodel(m).max(pindex);
+min = handles.parammodel(m).min(pindex);
+set(handles.manualmax6,'String',max);
+set(handles.manualmin6,'String',min);
+% set slider min max and value
+set(handles.manualslider6,'Max',101);
+set(handles.manualslider6,'Min',1);
+% set slider value to correspond to value
+if min > 0,
+    vector = logspace(log(min)/log(10),log(max)/log(10),101);
+else
+    vector = [min:(max-min)/100:max];
+end
+[dummy,index] = minfunct(abs(vector-paramvalue));
+set(handles.manualslider6,'Value',index);
+% set slider steps
+set(handles.manualslider6,'SliderStep',[0.01 0.01]);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+function manualparam7_Callback(hObject, eventdata, handles)
+m = handles.modelselection;
+pindex = get(handles.manualparam7,'Value');
+paramvalue = handles.parammodel(m).values(pindex);
+% set current parameter values
+set(handles.value7,'String',paramvalue);
+% set max and min values 
+max = handles.parammodel(m).max(pindex);
+min = handles.parammodel(m).min(pindex);
+set(handles.manualmax7,'String',max);
+set(handles.manualmin7,'String',min);
+% set slider min max and value
+set(handles.manualslider7,'Max',101);
+set(handles.manualslider7,'Min',1);
+% set slider value to correspond to value
+if min > 0,
+    vector = logspace(log(min)/log(10),log(max)/log(10),101);
+else
+    vector = [min:(max-min)/100:max];
+end
+[dummy,index] = minfunct(abs(vector-paramvalue));
+set(handles.manualslider7,'Value',index);
+% set slider steps
+set(handles.manualslider7,'SliderStep',[0.01 0.01]);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INITIALIZE PLOTDATA (includes MEXfile data)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [plotdata] = initializePlotdata(projectstruct,modelindex,handles)
+% GET ALL MEASUREMENT INFORMATION
+infostruct = [];
+for k=1:length(projectstruct.models(modelindex)),
+    model = projectstruct.models{modelindex(k)};
+    experiments = projectstruct.experiments(handles.experimentindices);
+    displayFlag = 0;
+    expmeasinfo = getexpmeasinfoSBPD(model,modelindex(k),experiments,handles.experimentindices,displayFlag);
+    infostruct(k).modelstruct = SBstruct(projectstruct.models{modelindex(k)});
+    infostruct(k).modelindex = modelindex(k);
+    infostruct(k).expinfostruct = expmeasinfo;
+end
+% ADD SIMULATION DATA TO THE STRUCTURE
+plotdata = [];
+plotdata.project = projectstruct.name;
+plotdata.notes = projectstruct.notes;
+plotdata.model = [];
+% run through all models
+for m=1:length(projectstruct.models(modelindex)),
+    % model data
+    modelstruct = infostruct(m).modelstruct;
+    plotdata.model(m).name = modelstruct.name;      
+    plotdata.model(m).notes = modelstruct.notes;
+    allmeasuredcomponents = {};
+    for e=1:length(infostruct(m).expinfostruct),
+        % experiment data
+        plotdata.model(m).experiment(e).name = infostruct(m).expinfostruct(e).experimentname;
+        plotdata.model(m).experiment(e).mexmodel = infostruct(m).expinfostruct(e).model;
+        plotdata.model(m).experiment(e).mexfullpath = infostruct(m).expinfostruct(e).mexfullpath;
+        timevector = infostruct(m).expinfostruct(e).timevector;
+        timestart = timevector(1);
+        timeend = timevector(end);
+        timevectorsim = [timestart:(timeend-timestart)/1000:timeend];
+        plotdata.model(m).experiment(e).timevector = timevectorsim;
+        expstatenames = infostruct(m).expinfostruct(e).statenames;          
+        expvariablenames = infostruct(m).expinfostruct(e).variablenames; 
+        plotdata.model(m).experiment(e).componentnames = {expstatenames{:} expvariablenames{:}};  
+        % simulate to get the state and variable values
+        mexmodel = infostruct(m).expinfostruct(e).model;
+        ic = infostruct(m).expinfostruct(e).initialconditions;
+        plotdata.model(m).experiment(e).initialconditions = ic;
+        try
+            simdata = feval(mexmodel,timevectorsim,ic,[],handles.integratoroptions);
+        catch
+            simdata.statevalues = NaN(length(timevectorsim),length(ic));
+            simdata.variablevalues = NaN(length(timevectorsim),length(ic));
+        end
+        % collect all states that are measured
+        stateindices = infostruct(m).expinfostruct(e).stateindices;
+        variableindices = infostruct(m).expinfostruct(e).variableindices;
+        plotdata.model(m).experiment(e).stateindices = stateindices;
+        plotdata.model(m).experiment(e).variableindices = variableindices;
+        statevalues = simdata.statevalues(:,stateindices);
+        variablevalues = simdata.variablevalues(:,variableindices);
+        % add simulated state trajectories
+        plotdata.model(m).experiment(e).componentvalues = [statevalues variablevalues];
+        for meas=1:length(infostruct(m).expinfostruct(e).measurement),
+            % measurement data
+            plotdata.model(m).experiment(e).measurement(meas).name = infostruct(m).expinfostruct(e).measurement(meas).name;
+            timevectormeas = timevector(infostruct(m).expinfostruct(e).measurement(meas).timevectorindices);
+            plotdata.model(m).experiment(e).measurement(meas).timevector = timevectormeas;
+            % reorder the measurements
+            measstatenames = infostruct(m).expinfostruct(e).measurement(meas).statenames;
+            measvariablenames = infostruct(m).expinfostruct(e).measurement(meas).variablenames;
+            % states 
+            for k=1:length(expstatenames),
+                index = strmatchSB(expstatenames{k},measstatenames,'exact');
+                if ~isempty(index),
+                    plotdata.model(m).experiment(e).measurement(meas).componentnames{k} = measstatenames{index};
+                    plotdata.model(m).experiment(e).measurement(meas).componentvalues(:,k) = infostruct(m).expinfostruct(e).measurement(meas).statereferences(:,index);
+                    plotdata.model(m).experiment(e).measurement(meas).maxvalues(:,k) = infostruct(m).expinfostruct(e).measurement(meas).statemaxvalues(:,index);
+                    plotdata.model(m).experiment(e).measurement(meas).minvalues(:,k) = infostruct(m).expinfostruct(e).measurement(meas).stateminvalues(:,index);
+                else
+                    plotdata.model(m).experiment(e).measurement(meas).componentnames{k} = 'not available';
+                    plotdata.model(m).experiment(e).measurement(meas).componnentvalues(:,k) = NaN(length(timevectormeas),1);
+                    plotdata.model(m).experiment(e).measurement(meas).maxvalues(:,k) = NaN(length(timevectormeas),1);
+                    plotdata.model(m).experiment(e).measurement(meas).minvalues(:,k) = NaN(length(timevectormeas),1);
+                end                    
+            end
+            offset = length(expstatenames);
+            % variables
+            for k=1:length(expvariablenames),
+                index = strmatchSB(expvariablenames{k},measvariablenames,'exact');
+                if ~isempty(index),
+                    plotdata.model(m).experiment(e).measurement(meas).componentnames{offset+k} = measvariablenames{index};
+                    plotdata.model(m).experiment(e).measurement(meas).componentvalues(:,offset+k) = infostruct(m).expinfostruct(e).measurement(meas).variablereferences(:,index);
+                    plotdata.model(m).experiment(e).measurement(meas).maxvalues(:,offset+k) = infostruct(m).expinfostruct(e).measurement(meas).variablemaxvalues(:,index);
+                    plotdata.model(m).experiment(e).measurement(meas).minvalues(:,offset+k) = infostruct(m).expinfostruct(e).measurement(meas).variableminvalues(:,index);
+                else
+                    plotdata.model(m).experiment(e).measurement(meas).componentnames{offset+k} = 'not available';
+                    plotdata.model(m).experiment(e).measurement(meas).componentvalues(:,offset+k) = NaN(length(timevectormeas),1);
+                    plotdata.model(m).experiment(e).measurement(meas).maxvalues(:,offset+k) = NaN(length(timevectormeas),1);
+                    plotdata.model(m).experiment(e).measurement(meas).minvalues(:,offset+k) = NaN(length(timevectormeas),1);
+                end                    
+            end      
+            allmeasuredcomponents = {allmeasuredcomponents{:} plotdata.model(m).experiment(e).measurement(meas).componentnames{:}};
+        end
+    end
+    allmeasuredcomponents = unique(allmeasuredcomponents);
+    plotdata.model(m).allmeascomponents = allmeasuredcomponents;
+end     
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% TRIVIAL FUNCTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% --- Executes on button press in zoombutton.
+function errorbarbutton_Callback(hObject, eventdata, handles)
+% toogle the errorbars in the figure
+if handles.errorbars == 0,
+    handles.errorbars = 1;
+else
+    handles.errorbars = 0;
+end
+% plot
+doPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+% --- Executes on button press in zoombutton.
+function zoombutton_Callback(hObject, eventdata, handles)
+% toogle the zoom in the figure
+zoom
+return
+
+% --- Executes on button press in gridbutton.
+function gridbutton_Callback(hObject, eventdata, handles)
+% toogle the grid in the figure
+grid
+if handles.grid == 1,
+    handles.grid = 0;
+else
+    handles.grid = 1;
+end
+% Update handles structure
+guidata(hObject, handles);
+return
+
+% --- Executes on selection change in resetall.
+function resetall_Callback(hObject, eventdata, handles)
+m = handles.modelselection;
+% reset all values for current model to starting values
+handles.parammodel(m).values = handles.parammodel(m).startvalues;
+handles.parammodel(m).max = handles.parammodel(m).startmax;
+handles.parammodel(m).min = handles.parammodel(m).startmin;
+% reinitialize parameter list
+initializeParameterLists(handles,'resetall');
+% simulate and plot it
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+% --- Executes on selection change in resetcurrent.
+function resetcurrent_Callback(hObject, eventdata, handles)
+m = handles.modelselection;
+% reset all values for current model and current parameter selections to starting values
+% get current indices
+pindices = [];
+pindices(end+1) = get(handles.manualparam1,'Value');
+pindices(end+1) = get(handles.manualparam2,'Value');
+pindices(end+1) = get(handles.manualparam3,'Value');
+pindices(end+1) = get(handles.manualparam4,'Value');
+pindices(end+1) = get(handles.manualparam5,'Value');
+pindices(end+1) = get(handles.manualparam6,'Value');
+pindices(end+1) = get(handles.manualparam7,'Value');
+% reset values for current parameters
+handles.parammodel(m).values(pindices) = handles.parammodel(m).startvalues(pindices);
+handles.parammodel(m).max(pindices) = handles.parammodel(m).startmax(pindices);
+handles.parammodel(m).min(pindices) = handles.parammodel(m).startmin(pindices);
+% reinitialize parameter list
+initializeParameterLists(handles,'resetcurrent');
+% simulate and plot it
+handles = doSimAndPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+% --- Executes on selection change in componentselection.
+function componentselection_Callback(hObject, eventdata, handles)
+try
+    doPlot(handles);
+catch
+    errordlg('This selection is not possible.','Error','on');               
+end
+return
+
+% --- Executes on button press in plot.
+function plot_Callback(hObject, eventdata, handles)
+handles.dataPlotType = 'plot';
+% disable errorbarbutton
+set(handles.errorbarbutton,'Visible','on');
+% Update handles structure
+guidata(hObject, handles);
+doPlot(handles);
+return
+
+% --- Executes on button press in loglog.
+function semilogx_Callback(hObject, eventdata, handles)
+handles.dataPlotType = 'semilogx';
+% disable errorbarbutton
+set(handles.errorbarbutton,'Visible','off');
+handles.errorbars = 0;
+% Update handles structure
+guidata(hObject, handles);
+doPlot(handles);
+return
+
+% --- Executes on button press in semilogx.
+function semilogy_Callback(hObject, eventdata, handles)
+handles.dataPlotType = 'semilogy';
+% disable errorbarbutton
+set(handles.errorbarbutton,'Visible','off');
+handles.errorbars = 0;
+% Update handles structure
+guidata(hObject, handles);
+doPlot(handles);
+return
+
+% --- Executes on button press in loglog.
+function loglog_Callback(hObject, eventdata, handles)
+handles.dataPlotType = 'loglog';
+% disable errorbarbutton
+set(handles.errorbarbutton,'Visible','off');
+handles.errorbars = 0;
+% Update handles structure
+guidata(hObject, handles);
+doPlot(handles);
+return
+
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/SBPDparameterestimation.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/SBPDparameterestimation.m
new file mode 100644
index 0000000000000000000000000000000000000000..cdf2e438bc53a4f0f49778eea51e8e38d64ca249
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/SBPDparameterestimation.m
@@ -0,0 +1,474 @@
+function [output] = SBPDparameterestimation(project,estimation,varargin)
+% SBPDparameterestimation: This function performs parameter estimation for
+% a given SBPD project.
+% 
+% USAGE:
+% ======
+% [output] = SBPDparameterestimation(project,estimation)        
+% [output] = SBPDparameterestimation(project,estimation,noStopButtonFlag)        
+%
+% project: SBPDproject for which to do the estimation
+% noStopButtonFlag: 0: stop button, 1: no stop button
+% estimation: Structure that defines what to do.
+%     estimation.modelindex: index of the model in the project for which to
+%                            do the estimation
+%
+%     estimation.experiments.indices: vector with indices of the
+%                            experiments in the project for which to do the
+%                            estimation 
+%     estimation.experiments.measurementindices: cell-array with vector
+%                            entries, definining the indices of the
+%                            measurements to take into account for each
+%                            selected experiment
+%     estimation.experiments.weight: vector with weights of the
+%                            experiments in the project for which to do the
+%                            estimation 
+%     estimation.experiments.measurementweight: cell-array with vector
+%                            entries, definining the weight of the
+%                            measurements to take into account for each
+%                            selected experiment
+%
+%     Note that the measurementweights, if defined, override the weights
+%     on the experiments! Experiment weights are assigned equally to all 
+%     measurements within the corresponding experiment.
+% 
+%     The parameters to be estimated and their upper and lower bounds can
+%     be specified in a cell-matrix in which the first column contains the
+%     names of the parameters, the second column the lower bounds and the
+%     third column the upper bounds. This cell-matrix needs to be
+%     assigned to the following field:
+%                                       estimation.parameters
+%
+%     Alternatively, parameters and lower and upper bounds can be specified
+%     as follows:
+%
+%     estimation.parameters.names: cell-array with names of parameters to
+%                            be optimized
+%     estimation.parameters.lowbounds: lower bounds for the parameters. If
+%                            scalar, then this scalar is multiplied to the
+%                            initial guesses to obtain the lower bounds.
+%                            Otherwise, a vector can be specified with the
+%                            same length as the number of parameters to be
+%                            optimized.   
+%     estimation.parameters.highbounds: upper bounds for the parameters. If
+%                            scalar, then this scalar is multiplied to the
+%                            initial guesses to obtain the upper bounds.
+%                            Otherwise, a vector can be specified with the
+%                            same length as the number of parameters to be
+%                            optimized.
+%
+%     The local parameters to be estimated and their upper and lower bounds can
+%     be specified in a cell-matrix in which the first column contains the
+%     names of the parameters, the second column the lower bounds and the
+%     third column the upper bounds. This cell-matrix needs to be
+%     assigned to the following field:
+%                                       estimation.parameterslocal
+%
+%     Alternatively, local parameters and lower and upper bounds can be specified
+%     as follows:
+%
+%     estimation.parameterslocal.names: cell-array with names of parameters to
+%                            be optimized locally (independently for each
+%                            experiment).  Initial guesses are obtained from
+%                            the nominal model/nominal experiment.
+%     estimation.parameterslocal.lowbounds: same as for the parameters
+%                            above, just for the parameters to be estimated
+%                            locally. 
+%     estimation.parameterslocal.highbounds: same as for the parameters
+%                            above, just for the parameters to be estimated
+%                            locally. 
+%
+%     The states for which to estimate the initial conditions and their
+%     upper and lower bounds can be specified in a cell-matrix in which the
+%     first column contains the names of the states, the second column
+%     the lower bounds and the third column the upper bounds. This
+%     cell-matrix needs to be assigned to the following field:
+%
+%                                       estimation.initialconditions
+%
+%     NOTE THAT: initial conditions are always estimated independently for
+%     each experiment!
+%
+%     Alternatively, states and lower and upper bounds can be specified
+%     as follows:
+% 
+%     estimation.initialconditions.names: names of the states for which to
+%                            optimize the initial conditions. Optimization
+%                            is done for one experiment at a time. No
+%                            starting guesses can be specified. These are
+%                            taken from the model and the experiment
+%                            description + measurements.
+%     estimation.initialconditions.lowbounds: scalar or vector. Same
+%                            procedure as for parameter lowbounds.
+%     estimation.initialconditions.higbounds: scalar or vector. Same
+%                            procedure as for parameter highbounds.
+%
+%     estimation.optimization.method: name of an optimization function. This
+%                            function has to be present in the MATLAB path
+%                            and the input/output interface has to be the
+%                            same as in the SBTOOLBOX2 optimization methods.  
+%     estimation.optimization.options: options for the optimization method
+%                            (third input argument to the optimization
+%                            method). It is assumed that these options are
+%                            defined in a structure (see simplexSB.m as
+%                            example). 
+%
+%     estimation.integrator.options: options for the integration using MEX
+%                           simulation files. These are defined as a
+%                           structure. The available fields, etc. are
+%                           documented in the help text of the SBPDsimulate
+%                           function.
+% 
+%     estimation.initialconditionsFlag: 0=nominal from model or experiment
+%                            description, 1=average from first timepoint in
+%                            measurements  
+%     estimation.displayFlag: show output or not (0=none, 1=final,
+%                            2=1+iterations, 3=2+othermessages
+%     estimation.scalingFlag: 0=no scaling, 1=scaling by max(abs())
+%                            values in measurements, 2=scaling by mean
+%                            values of measurements, 3=scaling by min/max
+%                            bounds:
+%                            [x_measured(ti)-x(ti)]^2/[xmax(ti)-xmin(ti)]^2
+%                            This last scaling alternative is only
+%                            possible, if all max and min values for all
+%                            the measurements are defined in the
+%                            measurement data.
+%     estimation.timescalingFlag: timescaling is useful in cases of
+%                            nonequidistant sampling, where some ranges are
+%                            tightly sampled and others aren't. In the case
+%                            of equidistant sampling this flag has no
+%                            effect. Otherwise the effect is maximal if it
+%                            is set to 1, with decreasing effect as it
+%                            increases.
+%
+%     estimation.costfunction: string with the name of the costfunction
+%                            called by the costfunction interface.
+%     estimation.logscalingResidualsFlag: Flag to indicate if the residuals
+%                            should be scaled logarithmically or not. 0
+%                            means no logscaling, 1 means logscaling.
+%
+%
+% DEFAULT VALUES:
+% ===============
+% noStopButtonFlag: 0 
+%
+% estimation.modelindex: 1 (first model in project)
+% estimation.experiments.indices: [] (use all experiments available)
+% estimation.experiments.measurementindices: {} (use all measurements available)
+% estimation.experiments.weight: {} (all weights 1)
+% estimation.experiments.measuremenweight: {} (all weights 1}
+% estimation.parameters.names: {} (estimate all parameters in the model)
+% estimation.parameters.lowbounds: 1e-3 (1e-3*initialguess)
+% estimation.parameters.highbounds: 1e3 (1e3*initialguess)
+% estimation.parameterslocal.names: {} (don't do any local estimation)
+% estimation.parameterslocal.lowbounds: 1e-3 (1e-3*initialguess)
+% estimation.parameterslocal.highbounds: 1e3 (1e3*initialguess)
+% estimation.initialconditions.names: {} (don't estimate initial conditions)
+% estimation.initialconditions.lowbounds: 1e-3 (1e-3*nominalvalues)
+% estimation.initialconditions.highbounds: 1e3 (1e3*nominalvalues)
+% estimation.optimization.method: 'simplexSB'
+% estimation.optimization.options: [] (default options for optimization method)
+% estimation.integrator.options: [] (default options for integration)
+% estimation.initialconditionsFlag: 1 (average from first timepoint in measurements (if measured) otherwise from model or experiment description)
+% estimation.displayFlag: 2 (show iterations and final message)
+% estimation.scalingFlag: 2 (scaling by mean values)
+% estimation.timescalingFlag: 0 (no scaling)
+% estimation.costfunction: 'defaultcostparameterestimationSBPD'
+% estimation.logscalingResidualsFlag: 0 (no logscaling)
+%
+% Output Arguments:
+% =================
+% The output is given as a structure:
+%      parameters: cell-array with names of optimized parameters
+%            Popt: vector with values of optimized parameters
+% parameterslocal: cell-array with names of locally optimized parameters
+%                  (for each experiment indenpendently)
+%       PLOCALopt: vector with values of locally optimized parameters
+%         icnames: cell-array with names of states for which the initial conditions have been optimized
+%           ICopt: vector with values of optimized initial conditions
+%         FVALopt: optimal cost function value
+%      projectopt: SBPDproject with updated optimized model and initial conditions in the experiment descriptions
+%      estimation: The estimation input argument
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GLOBAL VARIABLES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+global workestimation parameters stopOptimization costfunction fh fh2
+global displayFlag initialconditionsFlag scalingFlag optimizerboundsFlag
+global timescalingFlag logscalingResidualsFlag
+global PICmin PICmax parameterslocal integratoroptions
+
+global compiledExpModelsSBPDgui
+
+stopOptimization = 0;
+
+noStopButton = 0;
+if nargin >= 3,
+    noStopButton = varargin{1};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% BASIC CHECK OF THE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBPDproject(project),
+    error('Input argument ''project'' is not an SBPDproject.');
+end
+if ~isstruct(estimation) && ~isempty(estimation),
+    error('Input argument ''estimation'' is not a structure.');
+end
+projectstruct = SBPDstruct(project);
+
+% get integrator options
+try
+    integratoroptions = estimation.integrator.options; 
+catch
+    integratoroptions = [];
+    integratoroptions.maxnumsteps = 1000;
+    estimation.integrator.options = integratoroptions;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE PARAM DATA MATRIX
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if iscell(estimation.parameters),
+    if ~isempty(estimation.parameters),
+        paramnames = estimation.parameters(:,1); 
+        paramlowbounds = cell2mat(estimation.parameters(:,2)); 
+        paramhighbounds = cell2mat(estimation.parameters(:,3)); 
+    else
+        paramnames = {}; 
+        paramlowbounds = []; 
+        paramhighbounds = []; 
+    end
+    estimation.parameters = [];
+    estimation.parameters.names = paramnames;
+    estimation.parameters.lowbounds = paramlowbounds;
+    estimation.parameters.highbounds = paramhighbounds; 
+end
+if iscell(estimation.parameterslocal),
+    if ~isempty(estimation.parameterslocal),
+        paramnameslocal = estimation.parameterslocal(:,1);
+        paramlowboundslocal = cell2mat(estimation.parameterslocal(:,2));
+        paramhighboundslocal = cell2mat(estimation.parameterslocal(:,3));
+    else
+        paramnameslocal = {};
+        paramlowboundslocal = [];
+        paramhighboundslocal = [];
+    end
+    estimation.parameterslocal = [];
+    estimation.parameterslocal.names = paramnameslocal;
+    estimation.parameterslocal.lowbounds = paramlowboundslocal;
+    estimation.parameterslocal.highbounds = paramhighboundslocal;
+end
+if iscell(estimation.initialconditions),
+    if ~isempty(estimation.initialconditions),
+        icnames = estimation.initialconditions(:,1);
+        iclowbounds = cell2mat(estimation.initialconditions(:,2));
+        ichighbounds = cell2mat(estimation.initialconditions(:,3));
+    else
+        icnames = {};
+        iclowbounds = [];
+        ichighbounds = [];
+    end
+    estimation.initialconditions = [];
+    estimation.initialconditions.names = icnames;
+    estimation.initialconditions.lowbounds = iclowbounds;
+    estimation.initialconditions.highbounds = ichighbounds;
+end
+
+if isempty(estimation.parameters.names),
+    error(sprintf('At least one global parameter needs to be estimated!\nJust choose one and set very tight bounds for it.'));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK INFO AND GET DATA FROM PROJECT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[model,experiments,parameters,parameterslocal,initialconditions,optimization,costfunction,estimation,experimentmeasurementweights] = checkandprocessinput(project,projectstruct,estimation);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE NON-NUMERIC INITIAL CONDITIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% just by replacing them
+% + warning ... as user feedback
+if ~hasonlynumericICsSB(model),
+    model = SBconvertNonNum2NumIC(model);
+    disp('Warning: The model contains non-numeric initial conditions. For this analysis these are replaced');
+    disp('by numeric initial conditions, determined from the non-numeric ones.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS EXPERIMENT AND MEASUREMENT INFORMATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+workestimation = getexpmeasinfoSBPD(model,estimation.modelindex,experiments,estimation.experiments.indices,displayFlag,scalingFlag,timescalingFlag,initialconditionsFlag,experimentmeasurementweights);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ADD PARAMETER INDICES AND NOMINAL VALUES TO WORKESTIMATION STRUCTURE
+% Could be different indices for different experiments ... so its done here
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+workestimation = addparameterindices(workestimation,parameters,parameterslocal);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXPAND THE INFO FOR THE LOCAL PARAMETERS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[parameterslocal,workestimation] = getparameterslocaldata(workestimation,parameterslocal);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ADD INDICES OF THE STATES FOR WHICH TO OPTIMIZE THE INITIAL CONDITIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+workestimation = addstateicoptimindices(workestimation,initialconditions);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET INITIAL CONDITIONS VECTOR AND LOW AND HIGH BOUNDS
+% ADD IC INDICES TO WORKESTIMATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[initialconditions,workestimation] = geticdata(workestimation,initialconditions);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% NOW WE CAN CHECK BOUNDS FOR LOCAL PARAM AND INITIAL CONDS
+% IF outside then warn and correct to be inside
+% SKIP the warning for now!
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+tol = 0.00001;
+indexhi = find(parameters.initialguesses(:)>=parameters.highbounds(:));
+parameters.initialguesses(indexhi) = parameters.highbounds(indexhi)*(1-tol);
+indexlo = find(parameters.initialguesses(:)<=parameters.lowbounds(:));
+parameters.initialguesses(indexlo) = parameters.lowbounds(indexlo)*(1+tol);
+
+indexhi = find(parameterslocal.pliv(:)>=parameterslocal.plhigherbounds(:));
+parameterslocal.pliv(indexhi) = parameterslocal.plhigherbounds(indexhi)*(1-tol);
+indexlo = find(parameterslocal.pliv(:)<=parameterslocal.pllowerbounds(:));
+parameterslocal.pliv(indexlo) = parameterslocal.pllowerbounds(indexlo)*(1+tol);
+
+indexhi = find(initialconditions.ic0(:)>=initialconditions.icupperbounds(:));
+initialconditions.ic0(indexhi) = initialconditions.icupperbounds(indexhi)*(1-tol);
+indexlo = find(initialconditions.ic0(:)<=initialconditions.iclowerbounds(:));
+initialconditions.ic0(indexlo) = initialconditions.iclowerbounds(indexlo)*(1+tol);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Take care of optimization methods that require (can handle) upper and lower bounds
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+optimizerboundsFlag = 0;
+try
+    info = feval(optimization.method);
+    if info.constrained == 1,
+        % chosen optimization method handles constraints 
+        % => disable SBPDparameterestimation bounds handling
+        optimizerboundsFlag = 1;
+    end
+catch
+    % if an external (from SBTOOLBOX2) optimization method has been called
+    % then catch the error and handle bounds outside the optimizer.
+    optimizerboundsFlag = 0;
+end
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Transform parameters and initial conditions to be optimized 
+% for taking into account upper and lower bounds
+% This allows to use -Inf and +Inf as optimization bounds
+% only done in the case that the chosen optimizer is not able
+% to handle bounds.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if optimizerboundsFlag == 1,
+    X0 = [parameters.initialguesses(:); parameterslocal.pliv(:); initialconditions.ic0(:)];
+else
+    PICmin = [parameters.lowbounds(:); parameterslocal.pllowerbounds(:); initialconditions.iclowerbounds(:)];
+    PICmax = [parameters.highbounds(:); parameterslocal.plhigherbounds(:); initialconditions.icupperbounds(:)];
+    PIC0 = [parameters.initialguesses(:); parameterslocal.pliv(:); initialconditions.ic0(:)];
+    X0 = log((PIC0(:)-PICmin(:))./(PICmax(:)-PIC0(:)));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% RUN THE ESTIMATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+createstopbutton();
+if noStopButton,
+    close(fh)
+end
+
+OPTIONS = setoptimizerOptions(optimization,length(X0)); % disable lowbounds,highbounds,silent & outputfunction
+if optimizerboundsFlag == 1,
+    % Add optimizer bounds if the optimization methods requires it.
+    OPTIONS.lowbounds = [parameters.lowbounds(:); parameterslocal.pllowerbounds(:); initialconditions.iclowerbounds(:)];
+    OPTIONS.highbounds = [parameters.highbounds(:); parameterslocal.plhigherbounds(:); initialconditions.icupperbounds(:)];
+    %%[OPTIONS.lowbounds(:), X0(:), OPTIONS.highbounds(:)]    
+end
+warning off
+[Xopt,FVALopt] = feval(optimization.method,@costFunctionInterface,X0,OPTIONS);
+warning on
+
+% For some strange reason does the call to javaaddpath clear all global
+% variables. This call is performed in the case that JavaEvA optimization
+% methods are used. The involved functions take care of keeping the global
+% variables but it is necessary to declare them again as global here in
+% this function. Stupid stupid stupid :)
+% so check if optimizerboundsFlag is still defined global in this function
+try 
+    optimizerboundsFlag;
+catch
+    % No, it isn't ... so lets make all the globals global again!
+    global workestimation parameters stopOptimization costfunction fh fh2
+    global displayFlag initialconditionsFlag scalingFlag optimizerboundsFlag
+    global timescalingFlag
+    global PICmin PICmax parameterslocal compiledExpModelsSBPDgui
+end
+
+% close the stop estimation button
+try close(fh); catch, end
+try close(fh2); catch, end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% BACKTRANSFORM OPTIMIZED PARAMETERS/ICS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if optimizerboundsFlag == 1,
+    Popt = Xopt(1:length(parameters.names));
+    PLOCALopt = Xopt(length(parameters.names)+1:length(parameters.names)+length(parameterslocal.names)*length(workestimation));
+    ICopt = Xopt(length(parameters.names)+length(parameterslocal.names)*length(workestimation)+1:end);
+else
+    PICopt = (PICmin(:)+PICmax(:).*exp(Xopt(:)))./(1+exp(Xopt(:)));
+    Popt = PICopt(1:length(parameters.names));
+    PLOCALopt = PICopt(length(parameters.names)+1:length(parameters.names)+length(parameterslocal.names)*length(workestimation));
+    ICopt = PICopt(length(parameters.names)+length(parameterslocal.names)*length(workestimation)+1:end);
+end
+% Set ICopts to 0 if between -10*eps and +10*eps
+for k=1:length(ICopt), if ICopt(k) < 10*eps && ICopt(k) > -10*eps, ICopt(k) = 0; end; end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% REPORT RESULTS IF WANTED
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[paramreporttext] = boundsconstructreport(parameters,Popt);
+[paramreporttextlocal] = boundsconstructreportlocal(parameterslocal,PLOCALopt);
+[icreporttext] = reportICoptimization(workestimation,initialconditions,estimation,ICopt);
+if displayFlag >= 1,
+    disp(' ');
+    disp(paramreporttext);
+    disp(paramreporttextlocal);
+    disp(icreporttext);
+    disp(sprintf('Optimal cost: %g',FVALopt));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OUTPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output = constructoutput(projectstruct,estimation,parameters,parameterslocal,initialconditions,experiments,workestimation,Popt,PLOCALopt,ICopt,FVALopt);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CLEAN UP AND RETURN
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if displayFlag == 3,
+    disp('Finished ...');
+end
+if isempty(compiledExpModelsSBPDgui),
+    deleteTempMEXmodels(workestimation);
+end
+% clear all global variables
+clear global workestimation parameters stopOptimization costfunction fh
+clear global displayFlag initialconditionsFlag scalingFlag optimizerboundsFlag
+clear global timescalingFlag 
+clear global PICmin PICmax parameterslocal integratoroptions
+return
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/SBPDparameterfitanalysis.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/SBPDparameterfitanalysis.m
new file mode 100644
index 0000000000000000000000000000000000000000..ec6058a50dc1b763992d71ff07ab6a1b385c55ea
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/SBPDparameterfitanalysis.m
@@ -0,0 +1,405 @@
+function [estdata] = SBPDparameterfitanalysis(project,estimation,varargin)
+% SBPDparameterfitanalysis: Parameter estimation for the given project is
+% repeated several times from randomly perturbed starting conditions. The
+% estimated parameters values are stored and can subsequently can be used
+% to obtain insight into correlations between parameters, local minima, etc.
+%
+% This function only generates the data, which then is analyzed by
+% specialized functions (SBPDfaboxplot, SBPDfaclustering, SBPDfahist).
+% 
+% USAGE:
+% ======
+% [estdata] = SBPDparameterfitanalysis(project,estimation)        
+% [estdata] = SBPDparameterfitanalysis(project,estimation,nrestimations,perttype)               
+% [estdata] = SBPDparameterfitanalysis(project,estimation,nrestimations,perttype,noStopButtonFlag)        
+%
+% project:        SBPDproject for which to do the estimation
+% estimation: Structure that defines what to do. Same structure as used for
+%   SBPDparameterestimation, thereforw not documented here again.
+% nrestimations:  number of estimations that are to be done from
+%                            varying initial conditions
+% perttype:       =0: perturbed parameters/initial conditions
+%                 chosen randomly distributed uniformly between
+%                 the low and high bounds. 
+%                 >0: perturbed parameters obtained from an
+%                 exponential distribution around the nominal
+%                 values: ppert=p0*10^(randn(1)*perttype)
+% noStopButtonFlag: 0: stop button, 1: no stop button
+%
+% DEFAULT VALUES:
+% ===============
+% estimation:            same as in SBPDparameterestimation
+% nrestimations:         50
+% perttype:              0.5 (exponential distribution around nominal parameter values/initial conditions
+% noStopButtonFlag: 0 
+%
+% Output Arguments:
+% =================
+% The output 'estdata' is given as a structure:
+%   nrestimations: number of estimations performed
+%        perttype: the chosen perturbation type
+%      parameters: cell-array with names of optimized parameters
+%            Popt: vector with values of optimized parameters
+% parameterslocal: cell-array with names of locally optimized parameters
+%                  (for each experiment indenpendently)
+%       PLOCALopt: vector with values of locally optimized parameters
+%         icnames: cell-array with names of states for which the initial conditions have been optimized
+%           ICopt: vector with values of optimized initial conditions
+%         FVALopt: optimal cost function value
+%       FVALstart: the cost at the starting conditions
+%     timeelapsed: the time needed for all the estimations
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GLOBAL VARIABLES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+global workestimation parameters stopOptimization costfunction fh
+global displayFlag initialconditionsFlag scalingFlag 
+global timescalingFlag 
+global PICmin PICmax parameterslocal optimizerboundsFlag integratoroptions
+
+global compiledExpModelsSBPDgui
+
+stopOptimization = 0;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% BASIC CHECK OF THE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBPDproject(project),
+    error('Input argument ''project'' is not an SBPDproject.');
+end
+if ~isstruct(estimation) && ~isempty(estimation),
+    error('Input argument ''estimation'' is not an structure.');
+end
+projectstruct = SBPDstruct(project);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE PARAM DATA MATRIX
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if iscell(estimation.parameters),
+    if ~isempty(estimation.parameters),
+        paramnames = estimation.parameters(:,1); 
+        paramlowbounds = cell2mat(estimation.parameters(:,2)); 
+        paramhighbounds = cell2mat(estimation.parameters(:,3)); 
+    else
+        paramnames = {}; 
+        paramlowbounds = []; 
+        paramhighbounds = []; 
+    end
+    estimation.parameters = [];
+    estimation.parameters.names = paramnames;
+    estimation.parameters.lowbounds = paramlowbounds;
+    estimation.parameters.highbounds = paramhighbounds; 
+end
+if iscell(estimation.parameterslocal),
+    if ~isempty(estimation.parameterslocal),
+        paramnameslocal = estimation.parameterslocal(:,1);
+        paramlowboundslocal = cell2mat(estimation.parameterslocal(:,2));
+        paramhighboundslocal = cell2mat(estimation.parameterslocal(:,3));
+    else
+        paramnameslocal = {};
+        paramlowboundslocal = [];
+        paramhighboundslocal = [];
+    end
+    estimation.parameterslocal = [];
+    estimation.parameterslocal.names = paramnameslocal;
+    estimation.parameterslocal.lowbounds = paramlowboundslocal;
+    estimation.parameterslocal.highbounds = paramhighboundslocal;
+end
+if iscell(estimation.initialconditions),
+    if ~isempty(estimation.initialconditions),
+        icnames = estimation.initialconditions(:,1);
+        iclowbounds = cell2mat(estimation.initialconditions(:,2));
+        ichighbounds = cell2mat(estimation.initialconditions(:,3));
+    else
+        icnames = {};
+        iclowbounds = [];
+        ichighbounds = [];
+    end
+    estimation.initialconditions = [];
+    estimation.initialconditions.names = icnames;
+    estimation.initialconditions.lowbounds = iclowbounds;
+    estimation.initialconditions.highbounds = ichighbounds;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK INFO AND GET DATA FROM PROJECT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[model,experiments,parameters,parameterslocal,initialconditions,optimization,costfunction,estimation,experimentmeasurementweights] = checkandprocessinput(project,projectstruct,estimation);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE NON-NUMERIC INITIAL CONDITIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% just by replacing them
+% + warning ... as user feedback
+if ~hasonlynumericICsSB(model),
+    model = SBconvertNonNum2NumIC(model);
+    disp('Warning: The model contains non-numeric initial conditions. For this analysis these are replaced');
+    disp('by numeric initial conditions, determined from the non-numeric ones.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+displayFlag = 0;
+nrestimations = 50;
+perttype = 0.5;
+noStopButton = 0;
+integratoroptions = [];
+integratoroptions.maxnumsteps = 1000;
+if nargin >= 3,
+    nrestimations = varargin{1};
+end
+if nargin >= 4,
+    perttype = varargin{2};
+end
+if nargin >= 5,
+    noStopButton = varargin{3};
+end
+if nargin<2 || nargin>5,
+    error('Incorrect number of input arguments.');
+end
+
+% get integrator options
+try
+    integratoroptions = estimation.integrator.options; 
+catch
+    integratoroptions = [];
+    integratoroptions.maxnumsteps = 1000;
+    estimation.integrator.options = integratoroptions;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS EXPERIMENT AND MEASUREMENT INFORMATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+workestimation = getexpmeasinfoSBPD(model,estimation.modelindex,experiments,estimation.experiments.indices,displayFlag,scalingFlag,timescalingFlag,initialconditionsFlag,experimentmeasurementweights);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ADD PARAMETER INDICES AND NOMINAL VALUES TO WORKESTIMATION STRUCTURE
+% Could be different indices for different experiments ... so its done here
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+workestimation = addparameterindices(workestimation,parameters,parameterslocal);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXPAND THE INFO FOR THE LOCAL PARAMETERS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[parameterslocal,workestimation] = getparameterslocaldata(workestimation,parameterslocal);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ADD INDICES OF THE STATES FOR WHICH TO OPTIMIZE THE INITIAL CONDITIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+workestimation = addstateicoptimindices(workestimation,initialconditions);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET INITIAL CONDITIONS VECTOR AND LOW AND HIGH BOUNDS
+% ADD IC INDICES TO WORKESTIMATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[initialconditions,workestimation] = geticdata(workestimation,initialconditions);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% NOW WE CAN CHECK BOUNDS FOR LOCAL PARAM AND INITIAL CONDS
+% IF outside then warn and correct to be inside
+% SKIP the warning for now!
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+tol = 0.00001;
+indexhi = find(parameters.initialguesses(:)>=parameters.highbounds(:));
+parameters.initialguesses(indexhi) = parameters.highbounds(indexhi)*(1-tol);
+indexlo = find(parameters.initialguesses(:)<=parameters.lowbounds(:));
+parameters.initialguesses(indexlo) = parameters.lowbounds(indexlo)*(1+tol);
+
+indexhi = find(parameterslocal.pliv(:)>=parameterslocal.plhigherbounds(:));
+parameterslocal.pliv(indexhi) = parameterslocal.plhigherbounds(indexhi)*(1-tol);
+indexlo = find(parameterslocal.pliv(:)<=parameterslocal.pllowerbounds(:));
+parameterslocal.pliv(indexlo) = parameterslocal.pllowerbounds(indexlo)*(1+tol);
+
+indexhi = find(initialconditions.ic0(:)>=initialconditions.icupperbounds(:));
+initialconditions.ic0(indexhi) = initialconditions.icupperbounds(indexhi)*(1-tol);
+indexlo = find(initialconditions.ic0(:)<=initialconditions.iclowerbounds(:));
+initialconditions.ic0(indexlo) = initialconditions.iclowerbounds(indexlo)*(1+tol);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Take care of optimization methods that require upper and lower bounds
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+optimizerboundsFlag = 0;
+info = feval(optimization.method);
+if info.constrained == 1,
+    % chosen optimization method handles constraints 
+    % => disable SBPDparameterestimation bounds handling
+    optimizerboundsFlag = 1;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Prepare estimation data structure
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+estdata = [];
+estdata.nrestimations = nrestimations;
+estdata.cutoffthreshold = inf;
+estdata.perttype = perttype;
+estdata.parameters = parameters.names(:)';
+estdata.parametershighbounds = parameters.highbounds(:)';
+estdata.parameterslowbounds = parameters.lowbounds(:)';
+estdata.Popt = [];
+estdata.parameterslocal = parameterslocal.names(:)';
+estdata.parameterslocalhighbounds = parameterslocal.plhigherbounds(:)';
+estdata.parameterslocallowbounds = parameterslocal.pllowerbounds(:)';
+estdata.PLOCALopt = [];
+estdata.icnames = initialconditions.names(:)';
+estdata.ichighbounds = initialconditions.icupperbounds(:)';
+estdata.iclowbounds = initialconditions.iclowerbounds(:)';
+estdata.ICopt = [];
+estdata.FVALopt = [];
+estdata.FVALstart = [];
+estdata.timeelapsed = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% START THE ESTIMATION LOOP
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+timestartall = clock;
+timesinglerun = [];
+timeelapsed = 0;
+createstopbutton();
+if noStopButton,
+    set(fh,'Visible','off');
+end
+
+for loop=1:nrestimations,
+    timestart = clock;
+    disp(sprintf('Parameter estimation #%d',loop));
+    % get nominal values, max and min bounds
+    paramnominal = [parameters.initialguesses(:); parameterslocal.pliv(:); initialconditions.ic0(:)];
+    parammax = [parameters.highbounds(:); parameterslocal.plhigherbounds(:); initialconditions.icupperbounds(:)];
+    parammin = [parameters.lowbounds(:); parameterslocal.pllowerbounds(:); initialconditions.iclowerbounds(:)];
+    
+    % perturb the parameters
+    if perttype == 0,
+        % uniform distribution between min and max values
+        parampert = rand(length(paramnominal),1).*(parammax-parammin)+parammin;
+    else
+        % exponential distribution
+        parampert = paramnominal.*10.^(randn(length(paramnominal),1)*perttype);
+    end
+    
+    % fix perturbed values to bounds
+    indexup = find(parampert>=parammax);
+    indexdn = find(parampert<=parammin);
+    tol = 0.00001;
+    parampert(indexup) = parammax(indexup)*(1-tol);
+    parampert(indexdn) = parammin(indexdn)*(1+tol);
+    
+    % Transform parameters and initial conditions to be optimized for taking into account upper and lower bounds
+    if optimizerboundsFlag == 1,
+        X0 = parampert;
+    else
+        PICmin = parammin;
+        PICmax = parammax;
+        PIC0 = parampert;
+        X0 = log((PIC0(:)-PICmin(:))./(PICmax(:)-PIC0(:)));
+    end
+
+    % SET OPTIMIZER OPTIONS
+    OPTIONS = setoptimizerOptions(optimization,length(X0)); % disable lowbounds,highbounds,silent & outputfunction
+    if optimizerboundsFlag == 1,
+        % Add optimizer bounds if the optimization methods requires it.
+        OPTIONS.lowbounds = [parameters.lowbounds(:); parameterslocal.pllowerbounds(:); initialconditions.iclowerbounds(:)];
+        OPTIONS.highbounds = [parameters.highbounds(:); parameterslocal.plhigherbounds(:); initialconditions.icupperbounds(:)];
+    end
+
+    % RUN THE ESTIMATION
+    warning off
+    [Xopt,FVALopt] = feval(optimization.method,@costFunctionInterface,X0,OPTIONS);
+    warning on
+    
+    % For some strange reason does the call to javaaddpath clear all global
+    % variables. This call is performed in the case that JavaEvA optimization
+    % methods are used. The involved functions take care of keeping the global
+    % variables but it is necessary to declare them again as global here in
+    % this function. Stupid stupid stupid :)
+
+    % so check if optimizerboundsFlag is still defined global in this function
+    try
+        optimizerboundsFlag;
+    catch
+        % No, it isn't ... so lets make all the globals global again!
+        global workestimation parameters stopOptimization costfunction fh
+        global displayFlag initialconditionsFlag scalingFlag optimizerboundsFlag
+        global timescalingFlag
+        global PICmin PICmax parameterslocal compiledExpModelsSBPDgui
+    end
+
+    % BACKTRANSFORM OPTIMIZED PARAMETERS/ICS
+    if optimizerboundsFlag == 1,
+        Popt = Xopt(1:length(parameters.names));
+        PLOCALopt = Xopt(length(parameters.names)+1:length(parameters.names)+length(parameterslocal.names)*length(workestimation));
+        ICopt = Xopt(length(parameters.names)+length(parameterslocal.names)*length(workestimation)+1:end);
+    else
+        PICopt = (PICmin(:)+PICmax(:).*exp(Xopt(:)))./(1+exp(Xopt(:)));
+        Popt = PICopt(1:length(parameters.names));
+        PLOCALopt = PICopt(length(parameters.names)+1:length(parameters.names)+length(parameterslocal.names)*length(workestimation));
+        ICopt = PICopt(length(parameters.names)+length(parameterslocal.names)*length(workestimation)+1:end);
+    end
+    % Set ICopts to 0 if between -10*eps and +10*eps
+    for k=1:length(ICopt), if ICopt(k) < 10*eps && ICopt(k) > -10*eps, ICopt(k) = 0; end; end
+
+    % If estimation stopped then quit the loop
+    if stopOptimization,
+        break;
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % COLLECT ESTIMATION DATA
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    estdata.Popt = [estdata.Popt; Popt(:)'];
+    estdata.PLOCALopt = [estdata.PLOCALopt; PLOCALopt(:)'];
+    estdata.ICopt = [estdata.ICopt; ICopt(:)'];
+    estdata.FVALopt = [estdata.FVALopt; FVALopt];
+    estdata.FVALstart = [estdata.FVALstart; costFunctionInterface(X0)];
+
+    % display some status information
+    timenow = clock;
+    timesinglerun = [timesinglerun, etime(timenow,timestart)];
+    timeelapsed = etime(timenow,timestartall);
+    timeleft = mean(timesinglerun)*nrestimations-timeelapsed;
+    disp(sprintf('Start/optimal cost: %g / %g - Time left for estimation: %d min',estdata.FVALstart(end),FVALopt,round(timeleft/60)));
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % END THE ESTIMATION LOOP
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+end
+estdata.timeelapsed = timeelapsed/60;
+estdata.nrestimations = size(estdata.Popt,1);
+% close the stopbutton window
+try close(fh); catch, end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CUT OFF THE DATA (CUT OFF CAN BE DONE AFTERWARDS ALSO
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+estdata = cutoffdataSBPD(estdata);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CLEAN UP AND RETURN
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if displayFlag == 3,
+    disp('Finished ...');
+end
+global compiledExpModelsSBPDgui % if not empty then models are precompiled and should not be deleted
+if isempty(compiledExpModelsSBPDgui),
+    deleteTempMEXmodels(workestimation);
+end
+% clear all global variables
+clear global workestimation parameters stopOptimization costfunction fh
+clear global displayFlag initialconditionsFlag scalingFlag optimizerboundsFlag
+clear global timescalingFlag 
+clear global PICmin PICmax parameterslocal 
+return
+
+
+
+
+
+
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/addparameterindices.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/addparameterindices.m
new file mode 100644
index 0000000000000000000000000000000000000000..1fea43d7af0501ed065f57a7fe3a823c4a27a526
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/addparameterindices.m
@@ -0,0 +1,15 @@
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ADD PARAMETER INDICES AND NOMINAL VALUES TO WORKESTIMATION STRUCTURE
+% Could be different indices for different experiments ... so its done here
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [workestimation] = addparameterindices(workestimation,parameters,parameterslocal)
+for k=1:length(workestimation),
+    [allparameters,nominalparamvalues] = SBparameters(workestimation(k).SBmodel);
+    paramindices = getnamevectorindices(allparameters,parameters.names);
+    paramindiceslocal = getnamevectorindices(allparameters,parameterslocal.names);
+    workestimation(k).paramindices = paramindices;
+    workestimation(k).paramindiceslocal = paramindiceslocal;
+    workestimation(k).paramnominal = nominalparamvalues;
+end
+return
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/addstateicoptimindices.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/addstateicoptimindices.m
new file mode 100644
index 0000000000000000000000000000000000000000..4859b769142addd724606af84fd4d6f96a1529eb
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/addstateicoptimindices.m
@@ -0,0 +1,8 @@
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ADD INDICES OF THE STATES FOR WHICH TO OPTIMIZE THE INITIAL CONDITIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [workestimation] = addstateicoptimindices(workestimation,initialconditions)
+for k=1:length(workestimation),
+    stateindicesicoptim = getnamevectorindices(SBstates(workestimation(k).model),initialconditions.names);
+    workestimation(k).stateindicesicoptim = stateindicesicoptim;
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/boundsconstructreport.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/boundsconstructreport.m
new file mode 100644
index 0000000000000000000000000000000000000000..1ded415ef53b409c1f2ec4086555ac1920419709
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/boundsconstructreport.m
@@ -0,0 +1,18 @@
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PARAMETER BOUNDS REPORT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [text] = boundsconstructreport(parameters,Popt)
+text = sprintf('Estimated parameters\n====================\n');
+for k=1:length(parameters.names),
+    % check if lower or higher bound tested
+    tol = 0.00001;
+    if str2num(sprintf('%g',Popt(k))) <= parameters.lowbounds(k)*(1+tol),
+        boundtext = sprintf('%% At lower bound');
+    elseif str2num(sprintf('%g',Popt(k))) >= parameters.highbounds(k)*(1-tol),
+        boundtext = sprintf('%% At upper bound');
+    else
+        boundtext = '';
+    end
+    text = sprintf('%s%s = %g   %s\n',text,parameters.names{k},Popt(k),boundtext);
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/boundsconstructreportlocal.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/boundsconstructreportlocal.m
new file mode 100644
index 0000000000000000000000000000000000000000..4497b12c93b2874834b4210cc1b949bc89964411
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/boundsconstructreportlocal.m
@@ -0,0 +1,22 @@
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% LOCAL PARAMETER BOUNDS REPORT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [text] = boundsconstructreportlocal(parameterslocal,PLOCALopt)
+if isempty(PLOCALopt), 
+    text = '';
+    return
+end
+text = sprintf('Estimated local parameters\n==========================\n');
+for k=1:length(PLOCALopt),
+    % check if lower or higher bound tested
+    tol = 0.00001;
+    if str2num(sprintf('%g',PLOCALopt(k))) <= parameterslocal.pllowerbounds(k)*(1+tol),
+        boundtext = sprintf('%% At lower bound');
+    elseif str2num(sprintf('%g',PLOCALopt(k))) >= parameterslocal.plhigherbounds(k)*(1-tol),
+        boundtext = sprintf('%% At upper bound');
+    else
+        boundtext = '';
+    end
+    text = sprintf('%s%s = %g   %s\n',text,parameterslocal.names{mod(k-1,length(parameterslocal.names))+1},PLOCALopt(k),boundtext);
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/checkandprocessinput.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/checkandprocessinput.m
new file mode 100644
index 0000000000000000000000000000000000000000..afba468b2397ee5f864d6ad20719251f2d9b7608
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/checkandprocessinput.m
@@ -0,0 +1,351 @@
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETAILED CHECK AND PROCESSING OF INPUT ARGUMENTS 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [model,experiments,parameters,parameterslocal,initialconditions,optimization,costfunction,estimation,experimentmeasurementweights] = checkandprocessinput(project,projectstruct,estimation)
+global displayFlag initialconditionsFlag scalingFlag 
+global timescalingFlag optimizeinitialconditionsFlag logscalingResidualsFlag
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECKING THE FIELDS OF ESTIMATION AND HANDLING DEFAULT VALUES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modelindex = 1; % default: model 1
+experimentindices = []; % default: all experiments
+experimentmeasurementindices = {}; % default: all measurements for all experiments
+experimentweights = []; % default: 1
+experimentmeasurementweights = {}; % default: 1
+parameternames = {}; % default: all parameters in the model 
+parameterlowbounds = 1e-3; % default: 1e-3*parameterinitialguesses
+parameterhighbounds = 1e3; % default: 1e3*parameterinitialguesses
+parameternameslocal = {}; % default: no parameters to be estimated locally
+parameterlowboundslocal = 1e-3; % default: 1e-3*parameterinitialguesseslocal
+parameterhighboundslocal = 1e3; % default: 1e3*parameterinitialguesseslocal
+icnames = {}; % default: all unmeasured and unset states in the model
+iclowbounds = 1e-3; % default: 1e-3*nomvalue
+ichighbounds = 1e3; % default: 1e3*nomvalue
+optimizationmethod = 'simplexSB'; % default: simplexSB
+optimizationoptions = []; % default: no additional options for the optimization method
+initialconditionsFlag = 1; % 0=nominal from model or experiment description, 1=average from first timepoint in measurements
+displayFlag = 2; % default: final message + iteration
+scalingFlag = 2; % 0=noscaling, 1=scaling by max(abs()) values in measurements, 2=scaling by mean values of measurements,3=scaling by difference between max and min values
+timescalingFlag = 0; % 0=no scaling, 1=log scaling
+optimizeinitialconditionsFlag = 0; % 0=no, 1=optimize initial conditions for states for which no measurements 
+                                   % and no experiment settings are available. estimated for each measurement 
+                                   % in each experiment
+costfunction = 'defaultcostparameterestimationSBPD';
+logscalingResidualsFlag = 0;
+try modelindex = estimation.modelindex; catch, end
+try experimentweights = estimation.experiments.weight; catch, end
+try experimentmeasurementweights = estimation.experiments.measurementweight; catch, end
+try experimentindices = estimation.experiments.indices; catch, end
+try experimentmeasurementindices = estimation.experiments.measurementindices; catch, end
+try parameternames = estimation.parameters.names; catch, end
+try parameterlowbounds = estimation.parameters.lowbounds; catch, end
+try parameterhighbounds = estimation.parameters.highbounds; catch, end
+try parameternameslocal = estimation.parameterslocal.names; catch, end
+try parameterlowboundslocal = estimation.parameterslocal.lowbounds; catch, end
+try parameterhighboundslocal = estimation.parameterslocal.highbounds; catch, end
+try icnames = estimation.initialconditions.names; catch, end
+try iclowbounds = estimation.initialconditions.lowbounds; catch, end
+try ichighbounds = estimation.initialconditions.highbounds; catch, end
+try optimizationmethod = estimation.optimization.method; catch, end
+try optimizationoptions = estimation.optimization.options; catch, end
+try displayFlag = estimation.displayFlag; catch, end
+try initialconditionsFlag = estimation.initialconditionsFlag; catch, end
+try scalingFlag = estimation.scalingFlag; catch, end
+try timescalingFlag = estimation.timescalingFlag; catch, end
+try costfunction = estimation.costfunction; catch, end
+try logscalingResidualsFlag = estimation.logscalingResidualsFlag; catch, end
+if displayFlag == 3,
+    disp('Checking and processing input arguments ...');
+end
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK FLAGS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if scalingFlag < 0 || scalingFlag > 3,
+    error('''estimation.scalingFlag'': Not set correctly.');
+end
+if timescalingFlag < 0,
+    error('''estimation.timescalingFlag'': Not set correctly.');
+end
+if initialconditionsFlag < 0 || initialconditionsFlag > 1,
+    error('''estimation.initialconditionsFlag'': Not set correctly.');
+end
+if displayFlag < 0 || displayFlag > 3,
+    error('''estimation.displayFlag'': Not set correctly.');
+end
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK AND PROCESS INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK AND MODEL
+if length(modelindex) > 1,
+    % more than one model is specified
+    error('''estimation.modelindex'': Only one model at a time can be specified.');
+else
+    % get the model
+    model = SBPDgetmodel(project,modelindex);
+end
+estimation.modelindex = modelindex;
+% CHECK AND GET EXPERIMENTS AND MEASUREMENTS
+if ~isempty(find(experimentindices<1)) || ~isempty(find(experimentindices>length(projectstruct.experiments))),
+    % experiment indices out of bounds
+    error('''estimation.experiments.indices'': Out of bounds.');
+end
+if isempty(experimentindices),
+    % if experimentindices is empty then use all experiments (default setting)
+    experimentindices = 1:length(projectstruct.experiments);
+end
+
+
+% CHECK EXPERIMENT AND MEASUREMENT WEIGHTS
+% check that every experiment has weights
+if ~isempty(experimentweights),
+    if length(experimentweights) ~= length(experimentindices),
+        % numbers of experiments and experimentweight do not fit
+        error('''estimation.experiments.weight'': Number of elements does not fit with number of elements in ''estimation.experiments.indices''.');
+    end
+end
+if ~isempty(experimentmeasurementweights),
+    if length(experimentmeasurementweights) ~= length(experimentindices),
+        % numbers of experiments and experimentweight do not fit
+        error('''estimation.experiments.measurementweight'': Number of elements does not fit with number of elements in ''estimation.experiments.experimentindices''.');
+    end
+    if ~isempty(experimentmeasurementindices),
+        for k=1:length(experimentindices),
+            if length(experimentmeasurementindices{k})~= length(experimentmeasurementweights{k}),
+                error(['''estimation.experiments.measurementweight{',num2str(k),'}'': Number of elements does not fit with number of elements in ''estimation.experiments.measurementindices{',num2str(k),'}''.']);
+            end
+        end
+    else
+        for k=1:length(experimentindices),
+            experimentindex = experimentindices(k);
+            if length(experimentmeasurementweights{k}) ~= length(projectstruct.experiments(experimentindex).measurements),
+                error(['''estimation.experiments.measurementweight{',num2str(k),'}'': Number of elements does not fit with number of elements in ''estimation.experiments.measurementindices{',num2str(k),'}''.']);
+            end
+            % check if elements are vectors
+            if ~isnumeric(experimentmeasurementweights{k}),
+                error('''estimation.experiments.measurementweight'': The elements in here should be scalars or vectors, but no cell-arrays.');
+            end
+        end
+    end
+else
+    % experimentmeasurementweights is empty ...
+    % assign 1 if weights are not specified and experiment weight to all
+    % measurements of the experiment
+    if isempty(experimentweights),
+        experimentweights=ones(1,length(experimentindices));
+    end
+    for k=1:length(experimentindices),
+        experimentindex = experimentindices(k);
+        experimentmeasurementweights{end+1}=experimentweights(k)*ones(1,length(projectstruct.experiments(experimentindex).measurements));
+    end
+end
+% check length of experiment weights and indices
+if length(experimentmeasurementweights) ~= length(experimentindices),
+    % numbers of experiments and experimentweight do not fit
+    error('''estimation.experiments.measurementweight'': Numbers of elements do not fit with numbers of elements in ''estimation.experiments.measurementindices''.');
+end
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK WHICH EXPERIMENTS DO NOT HAVE MEASUREMENT DATA ASSIGNED TO
+% THESE ARE SKIPPED FROM THE CONSIDERATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+experimentindices_checked = [];
+experimentmeasurementweights_checked = {};
+ind=1;
+for e=1:length(experimentindices),
+    index = experimentindices(e);
+    if isempty(projectstruct.experiments(index).measurements),
+        disp(sprintf('Experiment %d has no measurements assigned to ... not considered here.\n',index));
+    else
+        % delete experiment from consideration
+        experimentindices_checked = [experimentindices_checked index];
+        experimentmeasurementweights_checked{ind} = experimentmeasurementweights{e};
+        ind=ind+1;
+    end
+end
+experimentindices = experimentindices_checked;
+experimentmeasurementweights = experimentmeasurementweights_checked;
+if isempty(experimentindices),
+    error('No measurements present in the project. No estimation possible.');
+end
+% go on
+if isempty(experimentmeasurementindices),
+    % if experimentmeasurementindices then all measurements for all
+    % experiments given in experimentindices
+    for k=1:length(experimentindices),
+        experimentindex = experimentindices(k);
+        experimentmeasurementindices{end+1} = 1:length(projectstruct.experiments(experimentindex).measurements);
+    end
+end
+if length(experimentindices) ~= length(experimentmeasurementindices),
+    % numbers of experiments and experimentmeasurements do not fit
+    error('''estimation.experiments.measurementindices'': Numbers of elements do not fit with numbers of elements in ''estimation.experiments.indices''.');
+end
+for k=1:length(experimentindices),
+    experimentindex = experimentindices(k);
+    if isempty(experimentmeasurementindices{k}),
+        % if is empty then use all experiments for current experiment
+        experimentmeasurementindices{k} = 1:length(projectstruct.experiments(experimentindex).measurements);
+    elseif ~isempty(find(experimentmeasurementindices{k}<1)) || ~isempty(find(experimentmeasurementindices{k}>length(projectstruct.experiments(experimentindex).measurements))),
+        % experimentmeasurementindices are out of bounds
+        error('''estimation.experiments.measurementindices{%d}'': Out of bounds.',k);
+    end
+end
+for k=1:length(experimentindices),
+    % get experiments and measurements
+    experimentindex = experimentindices(k);
+    experiments(k).experiment = SBPDgetexperiment(project,experimentindex);
+    measurements = SBPDgetmeasurement(project,experimentindex,experimentmeasurementindices{k});
+    if ~iscell(measurements),
+        % convert also single measurements to a cell-array for easier handling
+        measurements = {measurements};
+    end
+    experiments(k).measurements = measurements;
+end
+% CHECK AND GET PARAMETERNAMES AND PARAMETERINITIALVALUES
+[modelparameters,modelparametervalues] = SBparameters(model);
+if isempty(parameternames),
+    % if no parameternames defined then use all in the model
+    parameters.names = modelparameters;
+else
+    parameters.names = parameternames;
+end
+% just call SBparameters with the parameters.names .... this checks
+% if all given parameters exist in the model and additionally gets 
+% possible start values if none provided.
+try
+    [selectedparametervalues] = SBparameters(model,parameters.names);
+catch
+    error('Error in parameters to be estimated: %s', lasterr);
+end
+% take them from the model
+parameters.initialguesses = selectedparametervalues;
+% CHECK AND GET LOWBOUNDS AND HIGHBOUNDS FOR PARAMETERS 
+if length(parameterlowbounds) == 1,
+    if length(parameters.names) == 1,
+        parameters.lowbounds = parameterlowbounds;
+    else
+        parameters.lowbounds = parameters.initialguesses*parameterlowbounds;
+    end
+else
+    if length(parameterlowbounds) ~= length(parameters.names),
+        error('''estimation.parameters.lowbounds'': Incorrect number of elements.');
+    end
+    parameters.lowbounds = parameterlowbounds;
+end
+if length(parameterhighbounds) == 1,
+    if length(parameters.names) == 1,
+        parameters.highbounds = parameterhighbounds;
+    else
+        parameters.highbounds = parameters.initialguesses*parameterhighbounds;
+    end
+else
+    if length(parameterhighbounds) ~= length(parameters.names),
+        error('''estimation.parameters.highbounds'': Incorrect number of elements.');
+    end
+    parameters.highbounds = parameterhighbounds;
+end
+% CHECK AND GET LOCAL PARAMETERNAMES AND PARAMETERINITIALVALUES 
+parameterslocal.names = parameternameslocal;
+try
+    dummy = SBparameters(model,parameterslocal.names);  % just an error check (SBparameters function returns 
+                                                        % error if parameter not defined in model)
+catch
+    error('Error in local parameters to be estimated: %s',lasterr);
+end
+% CHECK AND GET LOWBOUNDS AND HIGHBOUNDS FOR PARAMETERS 
+if length(parameterlowboundslocal) == 1,
+    parameterslocal.lowbounds = parameterlowboundslocal;
+else
+    if length(parameterlowboundslocal) ~= length(parameterslocal.names),
+        error('''estimation.parameterslocal.lowbounds'': Incorrect number of elements.');
+    end
+    parameterslocal.lowbounds = parameterlowboundslocal;
+end
+if length(parameterhighboundslocal) == 1,
+    parameterslocal.highbounds = parameterhighboundslocal;
+else
+    if length(parameterhighboundslocal) ~= length(parameterslocal.names),
+        error('''estimation.parameterslocal.highbounds'': Incorrect number of elements.');
+    end
+    parameterslocal.highbounds = parameterhighboundslocal;
+end
+% CHECK AND GET ICNAMES (if given the latter)
+try
+    icmodel = SBinitialconditions(model,icnames);  % just an error check (SBstates function returns 
+                                                   % error if state not defined in model)
+catch
+    error('Error in initial conditions to be estimated: %s',lasterr);
+end
+initialconditions.names = icnames;
+% set iclowbounds and ichighbounds to empty if no icnames given!
+if isempty(icnames),
+    iclowbounds = [];
+    ichighbounds = [];
+end
+% CHECK AND GET LOWBOUNDS and HIGHBOUNDS
+if length(iclowbounds) == 1,
+    if length(icnames) == 1,
+        initialconditions.lowbounds = iclowbounds;
+    else
+        initialconditions.lowbounds = iclowbounds*icmodel(:);
+    end
+else
+    if length(iclowbounds) ~= length(initialconditions.names),
+        error('''estimation.initialconditions.lowbounds'': Incorrect number of elements.');
+    end
+    initialconditions.lowbounds = iclowbounds(:);
+end
+if length(ichighbounds) == 1,
+    if length(icnames) == 1,
+        initialconditions.highbounds = ichighbounds;
+    else
+        initialconditions.highbounds = ichighbounds*icmodel(:);
+    end    
+else
+    if length(ichighbounds) ~= length(initialconditions.names),
+        error('''estimation.initialconditions.highbounds'': Incorrect number of elements.');
+    end
+    initialconditions.highbounds = ichighbounds(:);
+end
+% SET OPTIMIZE INITIALCONDITIONS FLAG
+if length(icnames) ~= 0,
+    optimizeinitialconditionsFlag = 1;
+else 
+    optimizeinitialconditionsFlag = 0;
+end
+% CHECK AND GET OPTIMIZATION METHOD AND OPTIONS
+if isempty(optimizationmethod),
+    optimizationmethod = 'brentSB';
+end
+if isfield(optimizationoptions,'lowbounds'),
+    warning('''estimation.optimization.options.lowbounds'': This setting is ignored. Please use ''estimation.parameters.lowbounds''.');
+end
+if isfield(optimizationoptions,'highbounds'),
+    warning('''estimation.optimization.options.highbounds'': This setting is ignored. Please use ''estimation.parameters.highbounds''.');
+end
+if ~exist(optimizationmethod),
+    error('''estimation.optimization.method'': Method does not exist.');
+else
+    optimization.method = optimizationmethod;
+    optimization.options = optimizationoptions;
+end
+% CHECK COSTFUNCTION
+if exist(costfunction) ~= 2 && exist(costfunction)~=3,
+    error('''estimation.costfunction'': Function does not exist.');
+end    
+% Finally check if global and local parameters intersect with a non empty set
+check = intersect(parameters.names,parameterslocal.names);
+if ~isempty(check),
+    text = sprintf('The following global and local parameters to be estimated do intersect:\n');
+    for k=1:length(check),
+        text = sprintf('%s%s\n',text,check{k});
+    end
+    error(text);
+end
+% Finally Finally update the estimation structure (if necessary)
+estimation.experiments.indices = experimentindices;
+return
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/checkstopbutton.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/checkstopbutton.m
new file mode 100644
index 0000000000000000000000000000000000000000..b85cfbc89d8cdbdaf9fad2e34cac407e0eeb89fa
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/checkstopbutton.m
@@ -0,0 +1,14 @@
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK STOP BUTTON
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [] = checkstopbutton()
+% Showing a button that allows stopping the estimation
+global stopOptimization fh fh2
+if gcf == fh,
+    stopOptimization = 1;
+    close(fh);
+    close(fh2);
+    disp('User Interrupt requested ... please wait!');
+end
+drawnow;
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/constructoutput.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/constructoutput.m
new file mode 100644
index 0000000000000000000000000000000000000000..5a23d371a365ddb7569a6497eddb8a0a6ee07288
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/constructoutput.m
@@ -0,0 +1,76 @@
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Construct the output argument of the parameter estimation
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [output] = constructoutput(projectstruct,estimation,parameters,parameterslocal,initialconditions,experiments,workestimation,Popt,PLOCALopt,ICopt,FVALopt)
+% construct optimized project 
+% 1) add optimized parameters to the model
+% 2) add optimized local parameters and initial conditions to the experiment descriptions
+projectoptstruct = projectstruct;
+projectoptstruct.models{estimation.modelindex} = SBparameters(projectoptstruct.models{estimation.modelindex},parameters.names,Popt);
+icnames = initialconditions.names;
+plnames = parameterslocal.names;
+for k=1:length(experiments),
+    experiment = experiments(k).experiment;
+    experimentstruct = struct(experiment);
+    allpresenticnames = {experimentstruct.paramicsettings.name}; % gets icnames and parameternames mixed! but thats ok ...
+    % optimized initialconditions
+    for k2=1:length(icnames),
+        % check if initial condition already defined in the experiment
+        index = strmatchSB(icnames{k2},allpresenticnames,'exact');
+        if ~isempty(index),
+            % overwrite
+            experimentstruct.paramicsettings(index).name = icnames{k2};
+            experimentstruct.paramicsettings(index).formula = sprintf('%g',ICopt(workestimation(k).indicesinICvector(k2)));
+            experimentstruct.paramicsettings(index).notes = 'optimized value';
+            experimentstruct.paramicsettings(index).icflag = 1;
+        else
+            % append
+            experimentstruct.paramicsettings(end+1).name = icnames{k2};
+            experimentstruct.paramicsettings(end).formula = sprintf('%g',ICopt(workestimation(k).indicesinICvector(k2)));
+            experimentstruct.paramicsettings(end).notes = 'optimized value';
+            experimentstruct.paramicsettings(end).icflag = 1;
+        end
+    end
+    % optimized local parameters
+    for k2=1:length(plnames),
+        % check if local parameter already defined in the experiment
+        index = strmatchSB(plnames{k2},allpresenticnames,'exact');
+        if ~isempty(index),
+            % overwrite
+            experimentstruct.paramicsettings(index).name = plnames{k2};
+            experimentstruct.paramicsettings(index).formula = sprintf('%g',PLOCALopt(workestimation(k).indicesinLOCALPARAMvector(k2)));
+            experimentstruct.paramicsettings(index).notes = 'optimized value';
+            experimentstruct.paramicsettings(index).icflag = 0;
+        else
+            % append
+            experimentstruct.paramicsettings(end+1).name = plnames{k2};
+            experimentstruct.paramicsettings(end).formula = sprintf('%g',PLOCALopt(workestimation(k).indicesinLOCALPARAMvector(k2)));
+            experimentstruct.paramicsettings(end).notes = 'optimized value';
+            experimentstruct.paramicsettings(end).icflag = 0;
+        end
+    end    
+    % get index of experiment in the project
+    indexexp = estimation.experiments.indices(k);
+    projectoptstruct.experiments(indexexp).experiment = SBexperiment(experimentstruct);
+end
+projectopt = SBPDproject(projectoptstruct);
+% output is a structure
+output = [];
+output.parameters = parameters.names;
+output.Popt = Popt;
+output.parameterslocal = parameterslocal.names;
+if ~isempty(parameterslocal.names),
+    output.PLOCALopt = reshape(PLOCALopt',length(parameterslocal.names),length(PLOCALopt)/length(parameterslocal.names))';
+else 
+    output.PLOCALopt = [];
+end
+output.icnames = initialconditions.names;
+if ~isempty(initialconditions.names),
+    output.ICopt = reshape(ICopt',length(initialconditions.names),length(ICopt)/length(initialconditions.names))';
+else 
+    output.ICopt = [];
+end
+output.FVALopt = FVALopt;
+output.projectopt = projectopt;
+output.estimation = estimation;
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/costFunctionInterface.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/costFunctionInterface.m
new file mode 100644
index 0000000000000000000000000000000000000000..cc322c3a4bb02762edcf39ef543bd020e400b912
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/costFunctionInterface.m
@@ -0,0 +1,95 @@
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% COST FUNCTION INTERFACE (CALLED BY THE OPTIMIZATION METHOD)
+% X is transformed to be able to handle min and max parameter bounds:
+% X = log((p-pmin)/(pmax-p)) where p=parameter value, pmin: lower bound, pmax: upper bound
+% In this function here a backtransformation needs to be done
+%
+% two additional output values were added 4/4/8
+% constr: allows the specification of constraints (here disabled by setting
+%         constr=0.
+% resid:  a vector of residuals for all experiments and measurements
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [cost,constr,resid] = costFunctionInterface(X)
+% need some global variables
+global workestimation parameters scalingFlag costfunction optimizerboundsFlag 
+global PICmin PICmax parameterslocal integratoroptions 
+%%%% handle residuals (determine dimension of residuals vector)
+resid = [];
+lengthresid = 0;
+for k=1:length(workestimation),
+    for k2=1:length(workestimation(k).measurement),
+        lengthresid = lengthresid + length(workestimation(k).measurement(k2).statereferences(:));
+        lengthresid = lengthresid + length(workestimation(k).measurement(k2).variablereferences(:));
+    end
+end
+%%%% setting default constraint output argument
+constr = 0; % just disable constraints
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK STOP BUTTON
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+checkstopbutton();
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% BACKTRANSFORM PARAMETERS IF NECESSARY
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if optimizerboundsFlag == 1,
+    parametervalues = X(1:length(parameters.names));
+    parametervalueslocal = X(length(parameters.names)+1:length(parameters.names)+length(parameterslocal.names)*length(workestimation));
+    icvalues = X(length(parameters.names)+length(parameterslocal.names)*length(workestimation)+1:end);
+else
+    PICvalues = (PICmin(:)+PICmax(:).*exp(X(:)))./(1+exp(X(:)));
+    parametervalues = PICvalues(1:length(parameters.names));
+    parametervalueslocal = PICvalues(length(parameters.names)+1:length(parameters.names)+length(parameterslocal.names)*length(workestimation));
+    icvalues = PICvalues(length(parameters.names)+length(parameterslocal.names)*length(workestimation)+1:end);
+end
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SIMULATE ALL EXPERIMENTS FOR GIVEN ICS AND PARAMETERS
+% GET THE COST FOR EACH EXPERIMENT AND SUM UP
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+cost = 0;
+for k=1:length(workestimation),
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % CONSTRUCT FULL PARAM AND IC VECTORS FOR SIMULATION
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % construct a full parameter value vector (include values being optimized)
+    pv = workestimation(k).paramnominal;
+    % add first the globally optimized parameters    
+    paramindices = workestimation(k).paramindices;
+    pv(paramindices) = parametervalues;
+    % then add the locally optimized parameters
+    indicesinLOCALPARAMvector = workestimation(k).indicesinLOCALPARAMvector;
+    paramindiceslocal = workestimation(k).paramindiceslocal;
+    pv(paramindiceslocal) = parametervalueslocal(indicesinLOCALPARAMvector);
+    % construct a full initial conditions vector (include values being optimized)
+    ic = workestimation(k).initialconditions;
+    stateindicesicoptim = workestimation(k).stateindicesicoptim;
+    indicesinICvector = workestimation(k).indicesinICvector;
+    ic(stateindicesicoptim) = icvalues(indicesinICvector);
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % DO THE SIMULATION OF THE EXPERIMENT
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    try
+        simstructure = feval(workestimation(k).model,workestimation(k).timevector,ic,pv,integratoroptions);
+    catch
+        cost = inf;
+        resid = 1e20*ones(1,lengthresid);
+        return
+    end
+    % check if the simulation result contains NaN values - then cost = inf
+    % and return
+    if sum(sum(isnan([simstructure.statevalues simstructure.variablevalues]))), 
+        cost = inf;
+        resid = 1e20*ones(1,lengthresid);
+        return
+    end
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % RUN THE COST FUNCTION AND GET THE COST FOR THIS EXPERIMENT
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % determine the cost for all the measurements in each experiment
+    [costExperiment residexp] = feval(costfunction,simstructure,workestimation(k),scalingFlag);
+resid = [resid residexp];    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % SUM UP TOTAL COST
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    cost = cost + costExperiment; 
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/createstopbutton.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/createstopbutton.m
new file mode 100644
index 0000000000000000000000000000000000000000..ec546566d5a73ee7b9b550e1bda4c19ad8383d1a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/createstopbutton.m
@@ -0,0 +1,13 @@
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CREATE STOP BUTTON
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [] = createstopbutton()
+global fh fh2
+fh = figure(999);
+set(fh,'Position',[800 600 120 90],'MenuBar','none','NumberTitle','off','Name','Click to stop estimation','Toolbar','none','Color',[1 1 0])
+uicontrol('Style', 'pushbutton', 'String', 'Stop Estimation','Position', [10 10 100 70], 'BackgroundColor',[1 0 0],'FontWeight','bold');
+fh2 = figure(998);
+set(fh2,'Position',[-10 -10 10 10],'MenuBar','none','NumberTitle','off','Name','','Toolbar','none','Color',[1 1 1])
+% set(fh2,'Visible','off')
+drawnow;
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/defaultcostparameterestimationSBPD.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/defaultcostparameterestimationSBPD.m
new file mode 100644
index 0000000000000000000000000000000000000000..09b93307e70711e6e1ef775a75fa57b479c517d1
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/defaultcostparameterestimationSBPD.m
@@ -0,0 +1,115 @@
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DEFAULT COST FUNCTION 
+%    - data have been simulated in the interface function.
+%    - this function simply compares the simulation to the measurements
+%      that have been done for the current experiment
+%    - sum of squared error
+%    - weighting: none, mean, max, diff. min/max
+%    - timeweighting: none, sampling interval difference dependent weighting
+%    - weighting of different measurements in different experiments
+% one additional output value was added 4/4/8
+% resid:  a vector of residuals for all measurements
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [cost,resid] = defaultcostparameterestimationSBPD(simstructure,workestimationk,scalingFlag)
+global logscalingResidualsFlag
+
+cost = 0;
+resid = [];
+% get the simulated states and variables data
+statedata = simstructure.statevalues;
+variabledata = simstructure.variablevalues;
+% Cycle through all the measurements in the current experiment
+% and sum up the cost
+for k2=1:length(workestimationk.measurement),
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % GET SIM AND MEAS DATA AND SCALING DATA
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    timevectorindicesmeas = workestimationk.measurement(k2).timevectorindices; % get the indices of the timevector at which measurements have been done
+    % check if states have been measured in this measurement
+    if isempty(workestimationk.measurement(k2).stateindices),
+        % no states => empty
+        statesimulatedmeas = [];
+        statereferencesmeas = [];
+        statescaling = [];
+    else
+        % get the simulated and corresponding measured data
+        statesimulatedmeas = statedata(timevectorindicesmeas,workestimationk.measurement(k2).stateindices);
+        statereferencesmeas = workestimationk.measurement(k2).statereferences;
+        statescaling = workestimationk.measurement(k2).statescaling;
+%         if (prod(double(isnan(statescaling))) == 1), 
+%             error(sprintf('Please check your scaling settings.\nIt might be that you chose min/max scaling (3) but did not provide\nany min/max information for at least one measurement.')); 
+%         end
+    end
+    % check if variables have been measured in this measurement
+    if isempty(workestimationk.measurement(k2).variableindices),
+        % no states => empty
+        variablesimulatedmeas = [];
+        variablereferencesmeas = [];
+        variablescaling = [];
+    else
+        % get the simulated and corresponding measured data
+        variablesimulatedmeas = variabledata(timevectorindicesmeas,workestimationk.measurement(k2).variableindices);
+        variablereferencesmeas = workestimationk.measurement(k2).variablereferences;
+        variablescaling = workestimationk.measurement(k2).variablescaling;
+%         if (prod(double(isnan(variablescaling))) == 1), 
+%             error(sprintf('Please check your scaling settings.\nIt might be that you chose min/max scaling (3) but did not provide\nany min/max information for at least one measurement.')); 
+%         end
+    end
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % GET RESIDUALS
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    stateresidualsmeas = statesimulatedmeas-statereferencesmeas;
+    variableresidualsmeas = variablesimulatedmeas-variablereferencesmeas;
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % GET TIMESCALING
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    timescalingvector = workestimationk.measurement(k2).timescaling;
+    timescalingstates = timescalingvector(:,ones(size(statesimulatedmeas,2),1));
+    timescalingvariables = timescalingvector(:,ones(size(variablesimulatedmeas,2),1));
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % APPLY SCALING AND TIMESCALING TO RESIDUALS
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    if isempty(stateresidualsmeas),
+        scaledstateresiduals = [];
+    else
+        scaledstateresiduals = (stateresidualsmeas./statescaling).*timescalingstates;
+    end
+    if isempty(variableresidualsmeas),
+        scaledvariableresiduals = [];
+    else
+        scaledvariableresiduals = (variableresidualsmeas./variablescaling).*timescalingvariables;
+    end
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % HANDLE NaN elements (neglect them)
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    scaledstateresiduals(find(isnan(scaledstateresiduals))) = 0;
+    scaledvariableresiduals(find(isnan(scaledvariableresiduals))) = 0;
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % DO SOME ADDITIONAL SCALING AND WEIGHTING
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    factor1 = sqrt(1/length(timescalingvector)/(size(scaledstateresiduals,2) + size(scaledvariableresiduals,2)));
+    factor2 = sqrt(workestimationk.measurement(k2).weight);
+    scaledstateresiduals = scaledstateresiduals*factor1*factor2;
+    scaledvariableresiduals = scaledvariableresiduals*factor1*factor2;
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % LOGSCALE RESIDUALS IF DESIRED
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    if logscalingResidualsFlag,
+        scaledstateresiduals = log(abs(scaledstateresiduals)+1);
+        scaledvariableresiduals = log(abs(scaledvariableresiduals)+1);
+    end
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % SAVE THE RESIDUALS
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    resid = [resid reshape(scaledstateresiduals,1,[]) reshape(scaledvariableresiduals,1,[])];
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % GET THE COST FOR CURRENT MEASUREMENT
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    costmeas = sum(sum(scaledstateresiduals.^2)) + sum(sum(scaledvariableresiduals.^2));
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % SUM UP THE COST PER MEASUREMENT
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    cost = cost + costmeas;
+end
+return
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/deleteTempMEXmodels.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/deleteTempMEXmodels.m
new file mode 100644
index 0000000000000000000000000000000000000000..7823b862ab2600a05b2c5cd011b053909d9a0749
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/deleteTempMEXmodels.m
@@ -0,0 +1,13 @@
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DELETE THE TEMPORARY MEX MODELS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [] = deleteTempMEXmodels(workestimation)
+global displayFlag
+if displayFlag == 3,
+    disp('Deleting the temporary MEX model(s) ...');
+end
+clear mex
+for k=1:length(workestimation),
+    delete(workestimation(k).mexfullpath);
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/geticdata.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/geticdata.m
new file mode 100644
index 0000000000000000000000000000000000000000..a76e48c665fc68833094694600f4af4b486a5895
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/geticdata.m
@@ -0,0 +1,31 @@
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Construct initial guess vector from workestimation.initialconditions  
+% for each experiment. Further, construct lowbound and highbounds vector.
+% Add indices in the vectors for each experiment to the workestimation structure
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [initialconditions,workestimation] = geticdata(workestimation,initialconditions)
+global optimizeinitialconditionsFlag
+ic0 = [];
+iclowerbounds = [];
+icupperbounds = [];
+if optimizeinitialconditionsFlag == 1,
+    for e=1:length(workestimation),
+        ic0e = workestimation(e).initialconditions(workestimation(e).stateindicesicoptim);
+        ic0 = [ic0(:); ic0e(:)];
+        indicesinICvector = length(ic0)+[1-length(ic0e):0];
+        workestimation(e).indicesinICvector = indicesinICvector;
+        iclowerbounds = [iclowerbounds(:); initialconditions.lowbounds]; 
+        icupperbounds = [icupperbounds(:); initialconditions.highbounds]; 
+    end
+    % determine lower/upper bounds
+    iclowerbounds(find(iclowerbounds==0)) = -eps;
+    icupperbounds(find(icupperbounds==0)) = 1e10;
+else
+    for e=1:length(workestimation),
+        workestimation(e).indicesinICvector = [];
+    end
+end
+initialconditions.ic0 = ic0;
+initialconditions.iclowerbounds = iclowerbounds;
+initialconditions.icupperbounds = icupperbounds;
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/getnamevectorindices.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/getnamevectorindices.m
new file mode 100644
index 0000000000000000000000000000000000000000..c3e305a3d1c3099d5f6429b2c95be01f9b8803af
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/getnamevectorindices.m
@@ -0,0 +1,13 @@
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OBTAIN INDICES FOR GIVEN LISTS OF ALLNAMES AND NAMES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [indices] = getnamevectorindices(allnames,names)
+indices = [];
+% cycle through names and add new values to output
+for k = 1:length(names),
+    index = strmatchSB(names{k},allnames,'exact');
+    if ~isempty(index),
+        indices(end+1) = index;
+    end
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/getparameterslocaldata.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/getparameterslocaldata.m
new file mode 100644
index 0000000000000000000000000000000000000000..0ebe872291f0baae5f4f15ba7b9b96ec9ddb24f4
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/getparameterslocaldata.m
@@ -0,0 +1,40 @@
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXPAND THE INFO FOR THE LOCAL PARAMETERS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [parameterslocal,workestimation] = getparameterslocaldata(workestimation,parameterslocal)
+pliv = [];
+pllowerbounds = [];
+plhigherbounds = [];
+for k=1:length(workestimation),
+    % determine initial guesses for each experiment
+    plivk = workestimation(k).paramnominal(workestimation(k).paramindiceslocal);
+    pliv = [pliv(:); plivk(:)];
+    % determine lower and upper bounds for local parameters in each experiment
+    if length(parameterslocal.lowbounds) == 1,
+        if length(parameterslocal.names) == 1,
+            lowerbounds = parameterslocal.lowbounds;
+        else
+            lowerbounds = parameterslocal.lowbounds*pliv;
+        end
+    else
+        lowerbounds = parameterslocal.lowbounds;
+    end
+    if length(parameterslocal.highbounds) == 1,
+        if length(parameterslocal.names) == 1,
+            higherbounds = parameterslocal.highbounds;
+        else
+            higherbounds = parameterslocal.highbounds*pliv;
+        end
+    else
+        higherbounds = parameterslocal.highbounds;
+    end    
+    % finally expand the information
+    pllowerbounds = [pllowerbounds(:); lowerbounds(:)];
+    plhigherbounds = [plhigherbounds(:); higherbounds(:)];
+    indicesinLOCALPARAMvector = length(pliv)+[1-length(plivk):0];
+    workestimation(k).indicesinLOCALPARAMvector = indicesinLOCALPARAMvector;
+end    
+parameterslocal.pliv = pliv;
+parameterslocal.pllowerbounds = pllowerbounds;
+parameterslocal.plhigherbounds = plhigherbounds;
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/reportICoptimization.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/reportICoptimization.m
new file mode 100644
index 0000000000000000000000000000000000000000..5c20ca6da2cd3105c0c07f79a12a00da13e46257
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/reportICoptimization.m
@@ -0,0 +1,20 @@
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Report IC optimization results
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [text] = reportICoptimization(workestimation,initialconditions,estimation,ICopt)
+global optimizeinitialconditionsFlag
+if optimizeinitialconditionsFlag ~= 1,
+    text = '';
+    return;
+end
+text = sprintf('Estimated initial conditions\n============================\n');
+for k=1:length(workestimation),
+    for k2=1:length(initialconditions.names),
+        icname = initialconditions.names{k2};
+        icvalue = ICopt(workestimation(k).indicesinICvector(k2));
+        numberexp = estimation.experiments.indices(k);
+        text = sprintf('%s%s=%g (Experiment %d)\n',text,icname,icvalue,numberexp);
+    end
+end
+return
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/setoptimizerOptions.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/setoptimizerOptions.m
new file mode 100644
index 0000000000000000000000000000000000000000..b2fcf428de299056ec0dd8c81e2bbe81a4bb8dc2
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/estimationauxiliary/setoptimizerOptions.m
@@ -0,0 +1,15 @@
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE OPTIMIZER OPTIONS (disable lowbounds,highbounds,silent & outputfunction)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [OPTIONS] = setoptimizerOptions(optimization,numberoptparam)
+global displayFlag
+OPTIONS = optimization.options;
+OPTIONS.lowbounds = -Inf*ones(numberoptparam,1);  % bounds handled by transformation
+OPTIONS.highbounds = Inf*ones(numberoptparam,1);  % bounds handled by transformation
+if displayFlag >= 2,
+    OPTIONS.silent = 0;         % show iteration information if displayFlag set to 2 or 3 (override user settings)
+else
+    OPTIONS.silent = 1;         % show iteration information if displayFlag set to 2 or 3 (override user settings)
+end
+OPTIONS.outputfunction = '';    % overwrite eventual outputfunction with '' (eventually one could add an output function specific for parameter estimation)
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/fitanalysis/SBPDfaboxplot.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/fitanalysis/SBPDfaboxplot.m
new file mode 100644
index 0000000000000000000000000000000000000000..b73c0f17a006c9834f28b5765a8a9b8146ecb9c3
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/fitanalysis/SBPDfaboxplot.m
@@ -0,0 +1,125 @@
+function [] = SBPDfaboxplot(estdata,varargin)
+% SBPDfaboxplot: Plots a box-and-whisker diagram for the estimation data,
+% visualizing the spread in the results. Separate plots are shown for
+% global and local parameters and initial conditions. Determine also mean
+% and standard deviation for all parameters and display them next to the
+% names.
+%
+% To normalize the data, the parameters are scaled such that the median of
+% each single parameter is 1. 
+%
+% USAGE:
+% ======
+% SBPDfaboxplot(estdata)        
+% SBPDfaboxplot(estdata, OPTIONS)        
+%
+% estdata: The estimation data returned by the function SBPDparameterfitanalysis
+% OPTIONS: Structure containing options for the function
+%       OPTIONS.boxWidth: Width of the boxes to be drawn
+%       OPTIONS.verticalFlag: Flag determining if the boxes are oriented
+%                             vertically (=1) or horizontally (=0)
+%
+% DEFAULT VALUES:
+% ===============
+% OPTIONS.boxWidth:       0.5
+% OPTIONS.verticalFlag:   0 (plot horizontally)
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 1,
+    OPTIONS = [];
+elseif nargin == 2,
+    OPTIONS = varargin{1};
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET THE DATA
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+Popt = estdata.Popt;
+PLOCALopt = estdata.PLOCALopt;
+ICopt = estdata.ICopt;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE MEAN AND STD
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% scale each single parameter by its median
+if ~isempty(Popt),
+    meanPopt = mean(Popt);
+    stdPopt = std(Popt);
+end
+if ~isempty(PLOCALopt),
+    meanPLOCALopt = mean(PLOCALopt);
+    stdPLOCALopt = std(PLOCALopt);
+end
+if ~isempty(ICopt),
+    meanICopt = mean(ICopt);
+    stdICopt = std(ICopt);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SCALE THE DATA SEPARATELY
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% scale each single parameter by its median
+if ~isempty(Popt),
+    S = diag(1./median(Popt));
+    Poptscaled = Popt*S;
+end
+if ~isempty(PLOCALopt),
+    S = diag(1./median(PLOCALopt));
+    PLOCALoptscaled = PLOCALopt*S;
+end
+if ~isempty(ICopt),
+    S = diag(1./median(ICopt));
+    ICoptscaled = ICopt*S;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE THE NAMES (add mean + std)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+globalnames = {};
+for k0 = 1:length(estdata.parameters),
+    globalnames{end+1} = sprintf('(%0.3g %s %0.3g)  %s',meanPopt(k0),char(177),stdPopt(k0),estdata.parameters{k0});
+end
+localnames = {};
+for k0 = 1:length(estdata.parameterslocal),
+    dataindex = [k0:length(estdata.parameterslocal):size(estdata.PLOCALopt,2)];
+    for k=1:length(dataindex),
+        localnames{end+1} = sprintf('(%0.3g %s %0.3g)  %s %d',meanPLOCALopt(dataindex(k)),char(177),stdPLOCALopt(dataindex(k)),estdata.parameterslocal{k0},k);
+    end
+end
+icnames = {};
+for k0 = 1:length(estdata.icnames),
+    dataindex = [k0:length(estdata.icnames):size(estdata.ICopt,2)];
+    for k=1:length(dataindex),
+        icnames{end+1} = sprintf('(%0.3g %s %0.3g)  %s %d',meanICopt(dataindex(k)),char(177),stdICopt(dataindex(k)),estdata.icnames{k0},k);
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DO THE PLOT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(Popt)
+    % add the names the options
+    OPTIONS.samplenames = globalnames;
+    boxplotSB(Poptscaled,OPTIONS);
+    title('Fitted and scaled GLOBAL parameters');
+end
+if ~isempty(PLOCALopt)
+    OPTIONS.samplenames = localnames;
+    boxplotSB(PLOCALoptscaled,OPTIONS);
+    title('Fitted and scaled LOCAL parameters');
+end
+if ~isempty(ICopt)
+    OPTIONS.samplenames = icnames;
+    boxplotSB(ICoptscaled,OPTIONS);
+    title('Fitted and scaled initial conditions');
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/fitanalysis/SBPDfaclustering.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/fitanalysis/SBPDfaclustering.m
new file mode 100644
index 0000000000000000000000000000000000000000..2895951ef94ff87a229f211b263180141e2a93e4
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/fitanalysis/SBPDfaclustering.m
@@ -0,0 +1,69 @@
+function [] = SBPDfaclustering(estdata,varargin)
+% SBPDfaclustering: This function performs hierarchical clustering based on
+% Euclidean distance of the estimated parameter sets. If the estimates are
+% grouped around a single minimum a single cluster tree should be seen.
+% However, if the parameter sets lie around different local minima the tree
+% will show several large branches.
+%
+% To normalize the data, the parameters are scaled such that the median of
+% each single parameter is 1.
+%
+% USAGE:
+% ======
+% SBPDfaclustering(estdata)        
+% SBPDfaclustering(estdata,fontsize)        
+%
+% estdata:  The estimation data returned by the function SBPDparameterfitanalysis
+% fontsize: Fontsize for the dendrogram (default: 10)
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fontsize = 10;
+if nargin == 2,
+    fontsize = varargin{1};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET THE DATA
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+Popt = estdata.Popt;
+PLOCALopt = estdata.PLOCALopt;
+ICopt = estdata.ICopt;
+ALL = [Popt, PLOCALopt, ICopt];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SCALE THE DATA
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% scale each single parameter by its median
+S = diag(1./median(ALL));
+iInf=find(S==Inf);
+S(iInf)=1;
+ALLscaled = ALL*S;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CALCULATE THE EUCLIDEAN DISTANCES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+D = pdistSB(ALLscaled);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DO THE CLUSTERING 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+topology = clusteringSB(D);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DO THE PLOT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+figure; clf;
+plot_dendrogram(topology,[],fontsize);
+title('Dendrogram of clustered parameter estimates');
+xlabel('Distance');
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/fitanalysis/SBPDfacorr.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/fitanalysis/SBPDfacorr.m
new file mode 100644
index 0000000000000000000000000000000000000000..05b374870682da94b2b30d649dbfec50f30cd4b4
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/fitanalysis/SBPDfacorr.m
@@ -0,0 +1,65 @@
+function [] = SBPDfacorr(estdata, varargin)
+% SBPDfacorr: This function determines the correlation matrix for the
+% parameter sets determined with the SBPDparameterfitanalysis function.
+% The closer the magnitude of the values is to one, the more correlated the
+% parameters. 
+%
+% Results are generated only for the global parameters.
+%
+% USAGE:
+% ======
+% SBPDfacorr(estdata)
+%
+% estdata:  The estimation data returned by the function SBPDparameterfitanalysis
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+% Get the parameter information
+parameters = estdata.parameters;
+G = estdata.Popt;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE THE PARAMETER CORRELATION MATRIX
+% Take out parameters with zero variance!
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[n,m] = size(G);
+C = cov(G);
+zerovarianceindices = find(diag(C)==0);
+G(:,zerovarianceindices) = [];  % take out these parameters
+allparameters = parameters;
+parameters = parameters(setdiff([1:length(parameters)],zerovarianceindices));
+[correlationMatrix,P,LB,UB] = corrcoef(G);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DISPLAY NOTE IF PARAMTERS HAVE BEEN TAKEN OUT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(zerovarianceindices),
+    text = '';
+    for k=1:length(zerovarianceindices),
+        text = sprintf('%sParameter ''%s'' shows 0 variance. Taken out of consideration.\n',text,allparameters{zerovarianceindices(k)});
+    end
+    disp(text);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle the output
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Plot the correlation matrix (absolute values)
+% Prepare plot matrix
+plotMatrix = [correlationMatrix zeros(size(correlationMatrix,1),1); 0*ones(1,size(correlationMatrix,2)+1)];
+plotMatrix = abs(plotMatrix);
+% Plot the result
+figH = figure; clf;
+axesH = gca(figH);
+pcolor(plotMatrix);
+axis square;
+colorbar('EastOutside','YTick',[-1,-0.8,-0.6,-0.4,-0.2,0,0.2,0.4,0.6,0.8,1]);
+xticklabel_rotate([1.5:size(correlationMatrix,1)+0.5],45,parameters);
+set(axesH,'YTick',[1.5:size(correlationMatrix,1)+0.5]);
+set(axesH,'YTickLabel',parameters);
+colormap('Bone');
+title('Parameter Correlation Matrix (absolute values)');
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/fitanalysis/SBPDfadetcorr/SBPDfadetcorr.fig b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/fitanalysis/SBPDfadetcorr/SBPDfadetcorr.fig
new file mode 100644
index 0000000000000000000000000000000000000000..bc9028a0b97295c86f402c1593a30f12d6bc4bba
Binary files /dev/null and b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/fitanalysis/SBPDfadetcorr/SBPDfadetcorr.fig differ
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/fitanalysis/SBPDfadetcorr/SBPDfadetcorr.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/fitanalysis/SBPDfadetcorr/SBPDfadetcorr.m
new file mode 100644
index 0000000000000000000000000000000000000000..6fe931007d5854d1e2baaa498df24df571040210
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/fitanalysis/SBPDfadetcorr/SBPDfadetcorr.m
@@ -0,0 +1,215 @@
+function varargout = SBPDfadetcorr(varargin)
+% SBPDfadetcorr: Plots detailed pairwise correlations between parameters.
+% Parameters to display on the X and Y axis should be selected. 
+%
+% USAGE:
+% ======
+% [project] = SBPDfadetcorr(estdata)
+%
+% estdata:  The estimation data returned by the function SBPDparameterfitanalysis
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INITIALIZATION CODE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Begin initialization code - DO NOT EDIT
+
+gui_Singleton = 1;
+gui_State = struct('gui_Name',       mfilename, ...
+                   'gui_Singleton',  gui_Singleton, ...
+                   'gui_OpeningFcn', @SBPDfadetcorr_OpeningFcn, ...
+                   'gui_OutputFcn',  @SBPDfadetcorr_OutputFcn, ...
+                   'gui_LayoutFcn',  [] , ...
+                   'gui_Callback',   []);
+if nargin && ischar(varargin{1})
+    gui_State.gui_Callback = str2func(varargin{1});
+end
+if nargout
+    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
+else
+    gui_mainfcn(gui_State, varargin{:});
+end
+% End initialization code - DO NOT EDIT
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INTERFACE FUNCTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% --- Executes just before SBPDfadetcorr is made visible.
+function SBPDfadetcorr_OpeningFcn(hObject, eventdata, handles, varargin)
+academicWarningSBPD
+if nargin ~= 4,
+    error('Incorrect number of input arguments.');
+else
+    estdata = varargin{1};
+end
+handles.estdata = estdata;
+set(handles.parametersx,'String',handles.estdata.parameters);
+set(handles.parametersx,'Value',1);
+set(handles.parametersy,'String',handles.estdata.parameters);
+set(handles.parametersy,'Value',1);
+% select plottype 
+handles.dataPlotType = 'plot';     
+% text flag
+handles.textFlag = 0;
+% Doing a first plot
+handles = doPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+% --- Outputs from this function are returned to the command line.
+function varargout = SBPDfadetcorr_OutputFcn(hObject, eventdata, handles) 
+varargout{1} = [];
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PLOT FUNCTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function handles = doPlot(handles)
+% get the data to plot
+try
+    estdata = handles.estdata;
+catch
+    return
+end
+% get x and y parameters
+xparamindices = get(handles.parametersx,'Value');
+yparamindices = get(handles.parametersy,'Value');
+xparamnames = estdata.parameters(xparamindices);
+yparamnames = estdata.parameters(yparamindices);
+NROW = length(yparamindices);
+NCOL = length(xparamindices);
+for sp = 1:NROW*NCOL,
+    nx = mod(sp-1,NCOL)+1;
+    ny = ceil(sp/NCOL);
+    subplot(NROW,NCOL,sp,'Parent',handles.plotpanel);
+    ylabeltext = xparamnames{nx};
+    xlabeltext = yparamnames{ny};
+    if ~strcmp(ylabeltext,xlabeltext),
+        xvalues = estdata.Popt(:,xparamindices(nx));
+        yvalues = estdata.Popt(:,yparamindices(ny));
+        feval(handles.dataPlotType,xvalues,yvalues,'o');
+    else
+        set(gca,'Color',[0 0 0]);
+    end
+    set(gca,'XTick',[]);
+    set(gca,'YTick',[]);    
+end
+% get plotpanel handle and initialize text elements
+ppH = handles.plotpanel;
+if handles.textFlag == 0,
+    XtextH = {};
+    YtextH = {};
+    
+    for k = 1:length(estdata.parameters),
+        XtextH{k} = uicontrol(ppH,'Style','text','String','','Position',[-100,-100,2,2]);
+    end
+    for k = 1:length(estdata.parameters),
+        YtextH{k} = uicontrol(ppH,'Style','text','String','','Position',[-100,-100,2,2]);
+    end
+    handles.XtextH = XtextH;    
+    handles.YtextH = YtextH;
+else
+    % reset the position of the text
+    for k = 1:length(estdata.parameters),
+        set(handles.XtextH{k},'Position',[-100,-100,2,2]);
+    end
+    for k = 1:length(estdata.parameters),
+        set(handles.YtextH{k},'Position',[-100,-100,2,2]);
+    end
+end
+
+% get size of plot panel in pixels
+fadetcorr = get(handles.SBPDfadetcorr,'Position');
+pp = get(ppH,'Position');
+screen = get(0,'ScreenSize');
+ppWidth = fadetcorr(3)*pp(3)*screen(3);
+ppHeight = fadetcorr(4)*pp(4)*screen(4);
+% get all x and y values where to place text
+positions = [];
+figH = get(handles.plotpanel,'Children');
+for k = 1:length(figH),
+    positions = [positions; get(figH(k),'Position')];
+end
+x = unique(positions(:,1));
+width = positions(:,3);
+y = unique(positions(:,2));
+height = positions(:,4);
+x(x<0) = [];
+y(y<0) = [];
+width(width>1) = [];
+height(height>1) = [];
+width = width(1);
+height = height(1);
+if handles.textFlag ~= 0,
+    % set the text
+    for k = 1:length(x),
+        set(handles.XtextH{k},'Position',[x(k)*ppWidth,y(1)*ppHeight-20,length(xparamnames{k})*8,10],'String',xparamnames{k});
+    end       
+    for k = 1:length(y),
+        set(handles.YtextH{k},'Position',[x(1)*ppWidth-120,y(k)*ppHeight+height/2*ppHeight-10,length(yparamnames{k})*8,10],'String',yparamnames{end-k+1});
+    end
+else
+    % add text elements the first time
+    handles.textFlag = 1;
+end
+return
+
+function parametersx_Callback(hObject, eventdata, handles)
+handles = doPlot(handles);
+return
+
+function parametersy_Callback(hObject, eventdata, handles)
+handles = doPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+% --- Executes on button press in zoombutton.
+function zoombutton_Callback(hObject, eventdata, handles)
+% toogle the zoom in the figure
+zoom
+return
+
+% --- Executes on button press in plot.
+function plot_Callback(hObject, eventdata, handles)
+handles.dataPlotType = 'plot';
+% Update handles structure
+guidata(hObject, handles);
+handles = doPlot(handles);
+return
+
+% --- Executes on button press in loglog.
+function semilogx_Callback(hObject, eventdata, handles)
+handles.dataPlotType = 'semilogx';
+% Update handles structure
+guidata(hObject, handles);
+handles = doPlot(handles);
+return
+
+% --- Executes on button press in semilogx.
+function semilogy_Callback(hObject, eventdata, handles)
+handles.dataPlotType = 'semilogy';
+% Update handles structure
+guidata(hObject, handles);
+handles = doPlot(handles);
+return
+
+% --- Executes on button press in loglog.
+function loglog_Callback(hObject, eventdata, handles)
+handles.dataPlotType = 'loglog';
+% Update handles structure
+guidata(hObject, handles);
+handles = doPlot(handles);
+return
+
+function resize_Callback(hObject, eventdata, handles)
+handles = doPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/fitanalysis/SBPDfahist.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/fitanalysis/SBPDfahist.m
new file mode 100644
index 0000000000000000000000000000000000000000..4765582a710cffa48df4bbf8a73b7bc720c67b9d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/fitanalysis/SBPDfahist.m
@@ -0,0 +1,118 @@
+function [] = SBPDfahist(estdata,varargin)
+% SBPDfahist: This function plots histograms for the parameter values that 
+% have been estimated using the SBPDparameterfitanalysis function. This
+% gives a first impression over how well the parameters can be determined.
+%
+% The bins are equally distributed over the parameter range given by the
+% upper and lower bounds.
+%
+% Results are displayed separately for global parameters, local parameters,
+% and initial conditions. For each estimated local parameter and initial
+% condition a new figure is displayed, since usually there will be several
+% experiments.
+%
+% USAGE:
+% ======
+% SBPDfahist(estdata)        
+% SBPDfahist(estdata,nrbins)        
+%
+% estdata:  The estimation data returned by the function SBPDparameterfitanalysis
+% nrbins:   Number of bins to sort the values into
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+academicWarningSBPD
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+nrbins = 15;
+if nargin == 2,
+    nrbins = varargin{1};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE GLOBAL PARAMETERS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+Popt = estdata.Popt;
+Pnames = estdata.parameters;
+if ~isempty(Popt),
+    figure; clf;
+    nrPlots = size(Popt,2);
+    nrCols = ceil(sqrt(nrPlots));
+    nrRows = ceil(nrPlots/nrCols);
+    for k=1:size(Popt,2),
+        subplot(nrRows,nrCols,k);
+        % create the bin center vector
+        dn = estdata.parameterslowbounds(k);
+        up = estdata.parametershighbounds(k);
+        delta=(up-dn)/nrbins; 
+        centervector = [dn+delta/2:delta:up-delta/2];
+        hist(Popt(:,k),centervector);
+        [N,X] = hist(Popt(:,k),centervector);
+        hlhlx = title(Pnames{k});
+        set(hlhlx,'Interpreter','none');
+        axis([dn up 0 max(N)*1.05]);
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE LOCAL PARAMETERS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+PLOCALopt = estdata.PLOCALopt;
+PLOCALnames = estdata.parameterslocal;
+if ~isempty(PLOCALopt),
+    for k0 = 1:length(PLOCALnames),
+        figure; clf;       
+        dataindex = [k0:length(PLOCALnames):size(PLOCALopt,2)];
+        nrPlots = length(dataindex);
+        nrCols = ceil(sqrt(nrPlots));
+        nrRows = ceil(nrPlots/nrCols);
+        for k=1:length(dataindex),
+            subplot(nrRows,nrCols,k);
+            % create the bin center vector
+            dn = estdata.parameterslocallowbounds(dataindex(k));
+            up = estdata.parameterslocalhighbounds(dataindex(k));
+            delta=(up-dn)/nrbins; 
+            centervector = [dn+delta/2:delta:up-delta/2];
+            hist(PLOCALopt(:,dataindex(k)),centervector);
+            [N,X] = hist(PLOCALopt(:,dataindex(k)),centervector);
+            hlhlx = title(sprintf('%s - Experiment %d',PLOCALnames{k0},k));
+            set(hlhlx,'Interpreter','none');
+            delta = (X(2)-X(1))/2;
+            axis([dn up 0 max(N)*1.05]);
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE INITIAL CONDITIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ICopt = estdata.ICopt;
+icnames = estdata.icnames;
+if ~isempty(ICopt),
+    for k0 = 1:length(icnames),
+        figure; clf;       
+        dataindex = [k0:length(icnames):size(ICopt,2)];
+        nrPlots = length(dataindex);
+        nrCols = ceil(sqrt(nrPlots));
+        nrRows = ceil(nrPlots/nrCols);
+        for k=1:length(dataindex),
+            subplot(nrRows,nrCols,k);
+            % create the bin center vector
+            dn = estdata.iclowbounds(dataindex(k));
+            up = estdata.ichighbounds(dataindex(k));
+            delta=(up-dn)/nrbins; 
+            centervector = [dn+delta/2:delta:up-delta/2];
+            hist(ICopt(:,dataindex(k)),centervector);
+            [N,X] = hist(ICopt(:,dataindex(k)),centervector);
+            hlhlx = title(sprintf('%s - Experiment %d',icnames{k0},k));
+            set(hlhlx,'Interpreter','none');
+            delta = (X(2)-X(1))/2;
+            axis([dn up 0 max(N)*1.05]);
+        end
+    end
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/fitanalysis/SBPDfasigncorr.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/fitanalysis/SBPDfasigncorr.m
new file mode 100644
index 0000000000000000000000000000000000000000..7dad6e71e45e6ca4c13d17973af697774d9b8e99
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/fitanalysis/SBPDfasigncorr.m
@@ -0,0 +1,83 @@
+function [] = SBPDfasigncorr(estdata, varargin)
+% SBPDfasigncorr: A matrix of p-values for testing
+% the hypothesis of no significant correlation is computed based on the 
+% results generated by SBPDparameterfitanalysis and displayed.
+% Each p-value is the probability of getting a correlation 
+% as large as the observed value by random chance, when 
+% the true correlation is zero.  If P(i,j) is small then the
+% correlation between these two parameters is significant. 
+%
+% Results are generated only for the global parameters.
+%
+% USAGE:
+% ======
+% SBPDfasigncorr(estdata)
+% SBPDfasigncorr(estdata,alpha)
+%
+% estdata:  The estimation data returned by the function SBPDparameterfitanalysis
+% alpha:    A number between 0 and 1 to specify a confidence
+%                   level of 100*(1-alpha)%.  
+%
+%           Default: alpha=0.05
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+alpha = 0.05;
+if nargin == 2,
+    alpha = varargin{1};
+    if alpha > 1 || alpha < 0,
+        error('Wrong value for alpha');
+    end
+end
+
+% Get the parameter information
+parameters = estdata.parameters;
+G = estdata.Popt;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE THE PARAMETER CORRELATION MATRIX
+% Take out parameters with zero variance!
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[n,m] = size(G);
+C = cov(G);
+zerovarianceindices = find(diag(C)==0);
+G(:,zerovarianceindices) = [];  % take out these parameters
+allparameters = parameters;
+parameters = parameters(setdiff([1:length(parameters)],zerovarianceindices));
+[correlationMatrix,P,LB,UB] = corrcoef(G,'alpha',alpha);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DISPLAY NOTE IF PARAMTERS HAVE BEEN TAKEN OUT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(zerovarianceindices),
+    text = '';
+    for k=1:length(zerovarianceindices),
+        text = sprintf('%sParameter ''%s'' shows 0 variance. Taken out of consideration.\n',text,allparameters{zerovarianceindices(k)});
+    end
+    disp(text);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle the output
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Plot the P matrix 
+% Prepare plot matrix
+plotMatrix = abs([P zeros(size(P,1),1); 0*ones(1,size(P,2)+1)]);
+% Plot the result
+figH = figure; clf;
+axesH = gca(figH);
+pcolor(plotMatrix);
+axis square;
+colorbar('EastOutside','YTick',[-1,-0.8,-0.6,-0.4,-0.2,0,0.2,0.4,0.6,0.8,1]);
+xticklabel_rotate([1.5:size(correlationMatrix,1)+0.5],45,parameters);
+set(axesH,'YTick',[1.5:size(correlationMatrix,1)+0.5]);
+set(axesH,'YTickLabel',parameters);
+colormap('Bone');
+title(sprintf('Significant Correlations (p-values with alpha=%g)',alpha));
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/fitanalysis/auxiliary/cutoffdataSBPD.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/fitanalysis/auxiliary/cutoffdataSBPD.m
new file mode 100644
index 0000000000000000000000000000000000000000..57f46f1f2bef62d1a5faa319f318883db894e675
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/fitanalysis/auxiliary/cutoffdataSBPD.m
@@ -0,0 +1,45 @@
+function [estdata] = cutoffdataSBPD(estdata)
+% cutoffdataSBPD: Function used to select a cut-off threshold for the
+% estimation data collected during the fit analysis.
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+if estdata.nrestimations > 0,
+    indices_out = [];
+    fhselect = figure(1);
+    cutoffthreshold = inf;
+    while 1,
+        figure(1); clf;
+        subplot(2,1,1);
+        semilogy(estdata.FVALopt,'-ok'); hold on;
+        semilogy(estdata.FVALstart,'-or');
+        legend('optimized cost','cost at start conditions');
+        title(sprintf('%d estimations from randomized starting conditions',estdata.nrestimations));
+        subplot(2,1,2);
+        selectedFVALopt = estdata.FVALopt;
+        selectedFVALopt(indices_out) = NaN;
+        plot(selectedFVALopt,'-ok'); hold on;
+        legend('optimized cost');
+        title(sprintf('Selected estimations for further analysis (press enter to continue)',estdata.nrestimations));
+        xlabel('Estimation number');
+        axis([1 estdata.nrestimations min(estdata.FVALopt) max(estdata.FVALopt)]);
+        input = ginput(1);
+        if isempty(input),
+            break;
+        end
+        cutoffthreshold = input(2)
+        indices_out = find(estdata.FVALopt > cutoffthreshold);
+    end
+    close(fhselect);
+    % apply the selection to the data
+    estdata.Popt(indices_out,:) = [];
+    estdata.PLOCALopt(indices_out,:) = [];
+    estdata.ICopt(indices_out,:) = [];
+    estdata.FVALopt(indices_out) = [];
+    estdata.FVALstart(indices_out) = [];
+    estdata.cutoffthreshold = cutoffthreshold;
+    estdata.nrestimations = size(estdata.Popt,1);
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/other/createrunestimationscriptSBPD.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/other/createrunestimationscriptSBPD.m
new file mode 100644
index 0000000000000000000000000000000000000000..edc4e36952aa746efea1983ee16247bdb831d062
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/other/createrunestimationscriptSBPD.m
@@ -0,0 +1,173 @@
+function createrunestimationscriptSBPD(project,varargin)
+% createrunestimationscriptSBPD: Creates a run estimation script for the
+% given project and eventually given modelindex. This script can
+% be seen as a template for parameter estimation and fit analysis tasks. 
+%
+% USAGE:
+% ======
+% createrunestimationscriptSBPD(project)
+% createrunestimationscriptSBPD(project,modelindex)
+% createrunestimationscriptSBPD(project,modelindex,filename)
+% createrunestimationscriptSBPD(project,modelindex,filename,OPTIONS)
+%
+% project: SBPDproject
+% modelindex: index of the model in the project to use
+% filename: name of the run estimation file (*.m)
+% OPTIONS: a structure with additional informations
+%   OPTIONS.lowerbounds: scalar factor, determining the lower bound for a
+%       parameter by: factor*"original parameter value".
+%   OPTIONS.highbounds: scalar factor, determining the upper bound for a
+%       parameter by: factor*"original parameter value".
+% 
+% DEFAULT VALUES:
+% ===============
+% modelindex: 1
+% filename: 'runEstimation.m'
+% OPTIONS.lowbounds: 0.1
+% OPTIONS.highbounds: 10
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLING VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modelindex = 1;
+filename = 'runEstimation.m';
+lowbounds = 0.1;
+highbounds = 10;
+handles = [];
+if nargin >= 2,
+    modelindex = varargin{1};
+end
+if nargin >= 3,
+    filename = varargin{2};
+end
+if nargin == 4,
+    OPTIONS = varargin{3};
+end
+if nargin < 1 || nargin > 4,
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% BASIC CHECK OF THE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBPDproject(project),
+    error('Input argument ''project'' is not an SBPDproject.');
+end
+if ~ischar(filename),
+    error('Input argument ''filename'' is not a string.');
+end
+ps = SBPDstruct(project);
+[dummy,filename] = fileparts(filename);
+try lowbounds = OPTIONS.lowbounds; catch, end
+try highbounds = OPTIONS.highbounds; catch, end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET PROJECT INFORMATION AND CHECK AGAIN
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+name = ps.name;
+nrmodels = length(ps.models);
+nrexperiments = length(ps.experiments);
+nrestimations = length(ps.estimations);
+if modelindex < 1 || modelindex > nrmodels,
+    error('''modelindex'' is out of bounds.');
+end
+OPTIONS = [];
+OPTIONS.lowbounds = lowbounds;
+OPTIONS.highbounds = highbounds;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% WRITE OUT THE SCRIPT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen([filename '.m'],'w');
+fprintf(fid,'%%%% Below you find a template script, allowing to run parameter estimation\n');
+fprintf(fid,'%% using command-line arguments. It is constructed in such a way that you can\n');
+fprintf(fid,'%% use the "cell-mode" of the MATLAB editor, increasing the ease of use.\n');
+fprintf(fid,'%% The cell-model can be enabled by choosing in the menu "Cell->Enable Cell Mode".\n');
+fprintf(fid,'%% Once enabled, you can execute the yellow cells in this script (assuming you\n');
+fprintf(fid,'%% opened it in the MATLAB editor) by selecting them and pressing "Ctrl-Enter".\n');
+fprintf(fid,'clc; clear all;close all\n');
+fprintf(fid,'\n');
+fprintf(fid,'%%%% LOAD THE PROJECT (SELECT ONE OF BOTH POSSIBILITIES)\n');
+fprintf(fid,'%% Only us one of the following two commands! Uncomment the other that you don''t need.\n');
+fprintf(fid,'sbp = SBPDproject(''projectfilename.sbp'');  %% Enter the name of the project file (*.sbp) to load\n',filename);
+fprintf(fid,'sbp = SBPDproject(''projectfoldername'');  %% Enter the name of the project folder to import\n',filename);
+fprintf(fid,'\n'); 
+fprintf(fid,'%%%% DISPLAY INFORMATION ABOUT THE PROJECT\n');
+fprintf(fid,'SBPDinfo(sbp);\n');
+fprintf(fid,'\n');
+fprintf(fid,'%%%% KEEP THE ORIGINAL PROJECT UNCHANGED\n');
+fprintf(fid,'sbpopt = sbp;\n');
+fprintf(fid,'\n'); 
+fprintf(fid,'%%%% COMPARE MEASUREMENTS WITH MODEL\n');
+fprintf(fid,'SBPDcomparemeasurements(sbp)\n');
+fprintf(fid,'\n');
+[output] = getparamictextSBPD(project,modelindex,OPTIONS);
+fprintf(fid,'%s',output.completeText);
+fprintf(fid,'\n'); 
+fprintf(fid,'%%%% DEFINE THE ESTIMATION INFORMATION (STRUCTURE)\n');
+fprintf(fid,'estimation = [];\n'); 
+fprintf(fid,'\n');
+fprintf(fid,'%% Model and experiment settings\n');
+fprintf(fid,'estimation.modelindex = 1;\n');
+e = SBPDgetexperiment(project);
+text = sprintf('%d, ',[1:length(e)]);
+fprintf(fid,'estimation.experiments.indices = [%s];\n',text(1:end-2));
+text = sprintf('%d, ',ones(1,length(e)));
+fprintf(fid,'estimation.experiments.weight = [%s];\n',text(1:end-2));
+fprintf(fid,'\n');
+fprintf(fid,'%% Optimization settings\n');
+fprintf(fid,'estimation.optimization.method = ''simplexSB'';\n');   
+fprintf(fid,'estimation.optimization.options.maxfunevals = 2000;\n');  
+fprintf(fid,'\n');
+fprintf(fid,'%% Integrator settings\n');
+fprintf(fid,'estimation.integrator.options.abstol = 1e-006;\n');
+fprintf(fid,'estimation.integrator.options.reltol = 1e-006;\n');
+fprintf(fid,'estimation.integrator.options.minstep = 0;\n');
+fprintf(fid,'estimation.integrator.options.maxstep = Inf;\n');
+fprintf(fid,'estimation.integrator.options.maxnumsteps = 1000;\n');
+fprintf(fid,'\n');
+fprintf(fid,'%% Flags\n');
+fprintf(fid,'estimation.displayFlag = 2; %% show iterations and final message\n');   
+fprintf(fid,'estimation.scalingFlag = 2; %% scale by mean values\n');  
+fprintf(fid,'estimation.timescalingFlag = 0; %% do not apply time-scaling\n');  
+fprintf(fid,'estimation.initialconditionsFlag = 1; %% do use initial conditions from measurement data (if available)\n');  
+fprintf(fid,'\n');
+fprintf(fid,'%% Always needed (do not change ... unless you know what you do)\n');
+fprintf(fid,'estimation.parameters = paramdata;\n');
+fprintf(fid,'estimation.parameterslocal = paramdatalocal;\n');
+fprintf(fid,'estimation.initialconditions = icdata;\n');
+fprintf(fid,'\n');
+fprintf(fid,'%% Run estimation\n');
+fprintf(fid,'output = SBPDparameterestimation(sbpopt,estimation)\n');
+fprintf(fid,'%% Get optimized project\n');
+fprintf(fid,'sbpopt = output.projectopt;\n');
+fprintf(fid,'\n');
+fprintf(fid,'%%%% COMPARE OPTIMIZED PROJECT WITH MEASUREMENTS\n');
+fprintf(fid,'SBPDcomparemeasurements(sbpopt,estimation.modelindex);\n');
+fprintf(fid,'\n');
+fprintf(fid,'%%%% ANALYSIS OF RESIDUALS\n');
+fprintf(fid,'SBPDanalyzeresiduals(sbpopt,estimation)\n');
+fprintf(fid,'\n'); 
+fprintf(fid,'%%%% RUN A-POSTERIORI IDENTIFIABILITY ANALYSIS (only considering global variables)\n');
+fprintf(fid,'SBPDidentifiability(sbpopt,paramdata(:,1))\n');
+fprintf(fid,'\n');
+fprintf(fid,'%%%% RUN SOME FIT ANALYSIS\n');
+fprintf(fid,'%% (after completion click in lower figure to remove outliers, corresponding\n');
+fprintf(fid,'%%  to local minima. Finish with "Enter")\n');
+fprintf(fid,'output = SBPDparameterfitanalysis(sbpopt,estimation)\n');
+fprintf(fid,'\n');
+fprintf(fid,'%%%% FITANALYSIS EVALUATION\n');
+fprintf(fid,'SBPDfaboxplot(output)\n');
+fprintf(fid,'SBPDfahist(output)\n');
+fprintf(fid,'SBPDfacorr(output)\n');
+fprintf(fid,'SBPDfaclustering(output)\n');
+fprintf(fid,'SBPDfadetcorr(output)\n');
+fprintf(fid,'SBPDfasigncorr(output)\n');
+fprintf(fid,'\n');
+fclose(fid);
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/other/getparamictextSBPD.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/other/getparamictextSBPD.m
new file mode 100644
index 0000000000000000000000000000000000000000..604a4452cdf454728046c6eccd87fb7834dd66ce
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/parameterestimation/other/getparamictextSBPD.m
@@ -0,0 +1,172 @@
+function [varargout] = getparamictextSBPD(varargin)
+% getparamictextSBPD: This function aids in constructing the text that is 
+% needed to define the global and local parameters and the initial
+% conditions for parameter estimation purposes. It works both on project
+% and models.
+%
+% USAGE:
+% ======
+% getparamictextSBPD(model)
+% getparamictextSBPD(project)
+% getparamictextSBPD(project,modelindex)
+% getparamictextSBPD(model,OPTIONS)
+% getparamictextSBPD(project,OPTIONS)
+% getparamictextSBPD(project,modelindex,OPTIONS)
+% [output] = getparamictextSBPD(model)
+% [output] = getparamictextSBPD(project)
+% [output] = getparamictextSBPD(project,modelindex)
+% [output] = getparamictextSBPD(model,OPTIONS)
+% [output] = getparamictextSBPD(project,OPTIONS)
+% [output] = getparamictextSBPD(project,modelindex,OPTIONS)
+% 
+% model: SBmodel
+% project: SBPDproject
+% modelindex: The index of the model in an SBPDproject to use
+% OPTIONS: a structure with additional informations
+%   OPTIONS.lowerbounds: scalar factor, determining the lower bound for a
+%       parameter by: factor*"original parameter value".
+%   OPTIONS.highbounds: scalar factor, determining the upper bound for a
+%       parameter by: factor*"original parameter value".
+%
+% DEFAULT VALUES:
+% ===============
+% modelindex: 1
+% OPTIONS.lowbounds: 0.1
+% OPTIONS.highbounds: 10
+%
+% Output Arguments:
+% =================
+% If no output argument is specified, the determined text it written out in
+% the matlab command window. Otherwise, the information is returned in a
+% structure:
+%
+% output.completeText: The complete text.
+% output.parametersText: Only the parameters with bounds
+% output.initialConditionsText: Only the initial conditions with bounds
+%
+% Note that automatically no distinction between parameters can be made
+% that are to be estimated locally or globally. Therefore, all parameters
+% appear in the complete text in the global parameter section. Just copy
+% and paste when you need it!
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin < 1 || nargin > 3,
+    error('Incorrect number of input arguments.');
+end
+modelindex = 1;
+OPTIONS = [];
+if nargin == 2,
+    if isstruct(varargin{2}),
+        OPTIONS = varargin{2};
+    else
+        modelindex = varargin{2};
+    end
+end
+if nargin == 3,
+    modelindex = varargin{2};
+    OPTIONS = varargin{3};
+end
+if isSBmodel(varargin{1}),
+    model = varargin{1};
+elseif isSBPDproject(varargin{1}),
+    project = varargin{1};
+    model = SBPDgetmodel(project,modelindex);
+else
+    error('Incorrect input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE NON-NUMERIC INITIAL CONDITIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% just by replacing them
+% + warning ... as user feedback
+if ~hasonlynumericICsSB(model),
+    model = SBconvertNonNum2NumIC(model);
+    disp('Warning: The model contains non-numeric initial conditions. For this analysis these are replaced');
+    disp('by numeric initial conditions, determined from the non-numeric ones.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET LOWER AND UPPER BOUND FACTORS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+lowbounds = 0.1;
+highbounds = 10;
+try lowbounds = OPTIONS.lowbounds; catch, end
+try highbounds = OPTIONS.highbounds; catch, end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET STATENAMES, ICs, PARAMNAMES, VALUES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[sn,dummy,ic] = SBstates(model);
+[pn,pv] = SBparameters(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONSTRUCT IC and PARAM TEXTs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+pgn = pn;
+pln = {};
+icn = sn;
+pglb = pv*lowbounds;
+pgub = pv*highbounds;
+pllb = [];
+plub = [];
+iclb = ic*lowbounds;
+icub = ic*highbounds;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE ZERO VALUE NOMINAL VALUES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+pgub(find(pv==0)) = 100;
+icub(find(ic==0)) = 100;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET TEXT PARTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[ictext,paramtext,paramlocaltext,maxlength] = helpparamictextSBPD(pgn,pglb,pgub,pln,pllb,plub,icn,iclb,icub);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONSTRUCT COMPLETE TEXT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+add = maxlength-length('Name');
+addText = char(32*ones(1,add));
+add2 = maxlength-length('Lower bounds');
+addText2 = char(32*ones(1,add2));
+completeText = '';
+completeText = sprintf('%s%%%% SELECT PARAMETERS/STATES TO ESTIMATE AND CORRESPONDING BOUNDS\n',completeText);
+completeText = sprintf('%s%% Global parameters\n',completeText);
+completeText = sprintf('%s%% Names%s  Lower bounds%s  Upper bounds\n',completeText,addText,addText2);
+completeText = sprintf('%sparamdata = {\n',completeText);
+completeText = sprintf('%s%s',completeText,paramtext);
+completeText = sprintf('%s};\n\n',completeText);
+
+completeText = sprintf('%s%% Local (experiment dependend) parameters\n',completeText);
+completeText = sprintf('%s%% Names%s  Lower bounds%s  Upper bounds\n',completeText,addText,addText2);
+completeText = sprintf('%sparamdatalocal = {\n',completeText);
+completeText = sprintf('%s};\n\n',completeText);
+
+completeText = sprintf('%s%% Initial conditions (always experiment dependend)\n',completeText);
+completeText = sprintf('%s%% Names%s  Lower bounds%s  Upper bounds\n',completeText,addText,addText2);
+completeText = sprintf('%sicdata = {\n',completeText);
+completeText = sprintf('%s%s',completeText,ictext);
+completeText = sprintf('%s};\n\n',completeText);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE THE OUTPUT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargout == 0,
+    disp(completeText);
+else
+    output = [];
+    output.completeText = completeText;
+	output.parametersText = paramtext;
+	output.initialConditionsText = ictext;
+    varargout{1} = output;
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/simulation/SBPDinsilicoexp.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/simulation/SBPDinsilicoexp.m
new file mode 100644
index 0000000000000000000000000000000000000000..4bcbd46e5440f174b5a2c99a097b48a6d9aa9c32
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/simulation/SBPDinsilicoexp.m
@@ -0,0 +1,209 @@
+function [varargout] = SBPDinsilicoexp(model,experiment,timevector,varargin)
+% SBPDinsilicoexp runs an in-silico experiment. Simulated data can be
+% returned in the SBmeasurement format, plotted, or written in a CSV
+% or Excel measurement file (the latter only under Windows).
+%
+% USAGE:
+% ======
+% [] = SBPDinsilicoexp(model,experiment,timevector [,OPTIONS])         
+% [] = SBPDinsilicoexp(model,experiment,timevector,measurements [,OPTIONS])         
+% [] = SBPDinsilicoexp(model,experiment,timevector,measurements,filetypeFlag [,OPTIONS])         
+% [] = SBPDinsilicoexp(model,experiment,timevector,measurements,filetypeFlag,filename [,OPTIONS])         
+% [output] = SBPDinsilicoexp(model,experiment,timevector [,OPTIONS])         
+% [output] = SBPDinsilicoexp(model,experiment,timevector,measurements [,OPTIONS])         
+%
+% model: SBmodel to perform the insilico experiment on
+% experiment: SBexperiment object to apply
+% timevector: Timevector to be used for simulation
+% measurements: cell-array with the names of the components to measure
+%               (states, variables, reactions)
+% filetypeFlag: 0=plot results, 1=CSV measurement file, 2=Excel measurement
+%               file
+% filename: Name of the measurement file (or of the measurement) to generate
+% OPTIONS: structure with integrator options.
+%        OPTIONS.abstol: abs tolerance
+%        OPTIONS.reltol: rel tolerance
+%        OPTIONS.minstep: min step-size of integrator
+%        OPTIONS.maxstep: max step-size of integrator
+%        OPTIONS.maxnumsteps: maximum number of steps to be
+%          taken by the solver in its attempt to reach the next
+%          output time 
+%
+% DEFAULT VALUES:
+% ===============
+% measurements: all states are measured
+% filetypeFlag: 0 (plot the results). If output argument is specified, the 
+%               setting of the filetype flag is ignored
+% filename: combination of model and experiment name
+% OPTIONS.abstol: 1e-6
+% OPTIONS.reltol: 1e-6
+% OPTIONS.minstep: 0
+% OPTIONS.maxstep: inf
+% OPTIONS.maxnumsteps: 500
+%
+% Output Arguments:
+% =================
+% output: An SBmeasurement object with the resulting data
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input arguments 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBmodel(model),
+    error('The first input argument needs to be an SBmodel.');
+end
+if ~isSBexperiment(experiment),
+    error('The first input argument needs to be an SBexperiment.');
+end
+if length(timevector) <= 1,
+    error('The timevector is set incorrectly.');
+end
+modelstruct = struct(model);
+experimentstruct = struct(experiment);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+filetypeFlag = 0;
+filename = [modelstruct.name '_' experimentstruct.name];
+measurements = {};
+OPTIONS = [];
+if nargin == 4,
+    if isstruct(varargin{1}) || (isempty(varargin{1}) && isnumeric(varargin{1})),
+        OPTIONS = varargin{1};
+    else
+        measurements = varargin{1};
+    end
+elseif nargin == 5,
+    measurements = varargin{1};
+    if isstruct(varargin{2}) || (isempty(varargin{2}) && isnumeric(varargin{2})),
+        OPTIONS = varargin{2};
+    else
+        filetypeFlag = varargin{2};
+    end
+elseif nargin == 6,
+    measurements = varargin{1};
+    filetypeFlag = varargin{2};
+    if isstruct(varargin{3}) || (isempty(varargin{3}) && isnumeric(varargin{3})),
+        OPTIONS = varargin{3};
+    else
+        filename = varargin{3};
+    end    
+elseif nargin == 7.
+    measurements = varargin{1};
+    filetypeFlag = varargin{2};
+    filename = varargin{3};
+    OPTIONS = varargin{4};
+end
+
+if isempty(measurements),
+    measurements = SBstates(model);
+end
+if ischar(measurements),
+    measurements = {measurements};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Merge model and experiment
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modexp = SBmergemodexp(model,experiment);
+modelstruct = struct(modexp);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check measurements
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+meascomponenttype = [];
+meascomponentindex = [];
+modelStates = SBstates(modexp);
+modelVariables = SBvariables(modexp);
+modelReactions = SBreactions(modexp);
+for k=1:length(measurements),
+    found = 0;
+    % check states
+    index = strmatchSB(measurements{k},modelStates,'exact');
+    if ~isempty(index),
+        found = 1;
+    end
+    % check variables (if not in states)
+    if found == 0,
+        index = strmatchSB(measurements{k},modelVariables,'exact');
+        if ~isempty(index),
+            found = 2;
+        end
+    end
+    % check reactions (if not in states and variables)
+    if found == 0,
+        index = strmatchSB(measurements{k},modelReactions,'exact');
+        if ~isempty(index),
+            found = 3;
+        end
+    end
+    % check if it exists at all
+    if found == 0,
+        error('Measured component ''%s'' does not exist in the model.',measurements{k});
+    end
+    % save type and index
+    meascomponenttype(end+1) = found;
+    meascomponentindex(end+1) = index;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Simulate the experiment model (Non-numeric ICs handled by not providing
+% an initial condition!)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+simdata = SBPDsimulate(modexp,timevector,[],[],[],OPTIONS);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create SBmeasurement object
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+measstruct = struct(SBmeasurement);
+measstruct.name = filename;
+measstruct.notes = sprintf('Insilico experiment measurements\n================================\nModel notes:\n------------\n%s\n\nExperiment notes:\n-----------------\n%s',modelstruct.notes,experimentstruct.notes);
+measstruct.time = timevector(:);
+for k=1:length(measurements),
+    type = meascomponenttype(k);
+    index = meascomponentindex(k);
+    if type == 1, % its a state
+        name = modelstruct.states(index).name;
+        notes = modelstruct.states(index).notes;
+        values = simdata.statevalues(:,index);
+    elseif type == 2, % its a variable
+        name = modelstruct.variables(index).name;
+        notes = modelstruct.variables(index).notes;
+        values = simdata.variablevalues(:,index);
+    elseif type == 3, % its a reaction
+        name = modelstruct.reactions(index).name;
+        notes = modelstruct.reactions(index).notes;
+        values = simdata.reactionvalues(:,index);
+    end        
+    maxvalues = NaN(size(values));
+    minvalues = maxvalues;
+    measstruct.data(k).name = name;
+    measstruct.data(k).notes = notes;
+    measstruct.data(k).values = values;
+    measstruct.data(k).maxvalues = maxvalues;
+    measstruct.data(k).minvalues = minvalues;
+end
+insilicomeas = SBmeasurement(measstruct);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle the output
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargout == 0,
+    if filetypeFlag == 0,
+        % just plot the measurement
+        SBvisualizemeasurement(insilicomeas);
+    elseif filetypeFlag == 1 || (filetypeFlag == 2 && ~ispc),
+        % export to CSV (also if XLS desired but no windows PC)
+        SBexportCSVmeasurement(insilicomeas,filename);
+    elseif filetypeFlag == 2 && ispc,
+        % export to XLS
+        SBexportXLSmeasurement(insilicomeas,filename);
+    end
+elseif nargout == 1,
+    varargout{1} = insilicomeas;
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/simulation/SBPDinsilicoexpproj.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/simulation/SBPDinsilicoexpproj.m
new file mode 100644
index 0000000000000000000000000000000000000000..66512477cb1ff0b1b73833b4a376cb6545831352
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tasks/simulation/SBPDinsilicoexpproj.m
@@ -0,0 +1,143 @@
+function [varargout] = SBPDinsilicoexpproj(project,modelindex,experimentindex,timevector,varargin)
+% SBPDinsilicoexpproj runs an in-silico experiment directly on a model and
+% experiment within a project. Simulated data can be returned in the 
+% SBmeasurement format, plotted, or written in a CSV
+% or Excel measurement file (the latter only under Windows).
+%
+% Note: In contrast to SBPDinsilicoexp, this function per default exports
+% the insilico generated data to a CSV measurement file.
+%
+% USAGE:
+% ======
+% [] = SBPDinsilicoexpproj(project,modelindex,experimentindex,timevector [,OPTIONS])         
+% [] = SBPDinsilicoexpproj(project,modelindex,experimentindex,timevector,measurements [,OPTIONS])         
+% [] = SBPDinsilicoexpproj(project,modelindex,experimentindex,timevector,measurements,filetypeFlag [,OPTIONS])         
+% [] = SBPDinsilicoexpproj(project,modelindex,experimentindex,timevector,measurements,filetypeFlag,filename [,OPTIONS])         
+% [output] = SBPDinsilicoexpproj(project,modelindex,experimentindex,timevector [,OPTIONS])         
+% [output] = SBPDinsilicoexpproj(project,modelindex,experimentindex,timevector,measurements [,OPTIONS])         
+%
+% project:           SBPDproject to perform the experiment on
+% modelindex:        Index of the model in the project to be used
+% experimentindex:   Index of the experiment to be used (scalar only)
+% timevector:        Timevector to be used for simulation
+% measurements:      cell-array with the names of the components to measure
+%                    (states, variables, reactions)
+% filetypeFlag:      0=plot results, 1=CSV measurement file, 2=Excel measurement
+%                    file
+% filename:          Name of the measurement file (or of the measurement) to generate
+% OPTIONS: structure with integrator options.
+%        OPTIONS.abstol: abs tolerance
+%        OPTIONS.reltol: rel tolerance
+%        OPTIONS.minstep: min step-size of integrator
+%        OPTIONS.maxstep: max step-size of integrator
+%        OPTIONS.maxnumsteps: maximum number of steps to be
+%          taken by the solver in its attempt to reach the next
+%          output time 
+%
+% DEFAULT VALUES:
+% ===============
+% measurements: all states are measured
+% filetypeFlag: 1 (export to CSV file). If output argument is specified, the 
+%               setting of the filetype flag is ignored
+% filename: combination of model and experiment name
+% OPTIONS.abstol: 1e-6
+% OPTIONS.reltol: 1e-6
+% OPTIONS.minstep: 0
+% OPTIONS.maxstep: inf
+% OPTIONS.maxnumsteps: 500
+%
+% Output Arguments:
+% =================
+% output: An SBmeasurement object with the resulting data
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+academicWarningSBPD
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK INPUTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBPDproject(project),
+    error('The first input argument needs to be an SBPDproject.');
+end
+projectstruct = SBPDstruct(project);
+if modelindex < 0 || modelindex > length(projectstruct.models),
+    error('''modelindex'' out of bounds.');
+end
+if experimentindex < 1 || experimentindex > length(projectstruct.experiments),
+    error('''experimentindex'' out of bounds.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Convert to SBPDinsilicoexp
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+model = projectstruct.models{modelindex};
+experiment = projectstruct.experiments(experimentindex).experiment;
+modelstruct = struct(model);
+experimentstruct = struct(experiment);
+filetypeFlag = 1; % per default: export as CSV file
+filename = [modelstruct.name '_' experimentstruct.name];
+measurements = SBstates(model);
+OPTIONS = [];
+optionsgiven = 0;
+if nargin == 5,
+    if isstruct(varargin{1}) || (isempty(varargin{1}) && isnumeric(varargin{1})),
+        OPTIONS = varargin{1};
+        optionsgiven = 1;        
+    else
+        measurements = varargin{1};
+    end
+elseif nargin == 6,
+    measurements = varargin{1};
+    if isstruct(varargin{2}) || (isempty(varargin{2}) && isnumeric(varargin{2})),
+        OPTIONS = varargin{2};
+        optionsgiven = 1;        
+    else
+        filetypeFlag = varargin{2};
+    end
+elseif nargin == 7,
+    measurements = varargin{1};
+    filetypeFlag = varargin{2};
+    if isstruct(varargin{3}) || (isempty(varargin{3}) && isnumeric(varargin{3})),
+        OPTIONS = varargin{3};
+        optionsgiven = 1;        
+    else
+        filename = varargin{3};
+    end    
+elseif nargin == 8.
+    measurements = varargin{1};
+    filetypeFlag = varargin{2};
+    filename = varargin{3};
+    OPTIONS = varargin{4};
+    optionsgiven = 1;        
+end
+if isempty(measurements),
+    measurements = SBstates(model);
+end
+
+mynargin = nargin;
+if optionsgiven == 1,
+    mynargin = mynargin - 1; % adapting to w/o options ...
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% RUN SBPDinsilicoexp
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargout == 0,
+    if mynargin >= 4 || mynargin <= 6,
+        SBPDinsilicoexp(model,experiment,timevector,measurements,filetypeFlag,OPTIONS);
+    elseif mynargin == 7,
+        SBPDinsilicoexp(model,experiment,timevector,measurements,filetypeFlag,filename,OPTIONS);
+    else
+        error('Incorrect number of input arguments');
+    end
+else
+    if mynargin >= 4 || mynargin <= 6,
+        varargout{1} = SBPDinsilicoexp(model,experiment,timevector,measurements,filetypeFlag,OPTIONS);
+    elseif mynargin == 7,
+        varargout{1} = SBPDinsilicoexp(model,experiment,timevector,measurements,filetypeFlag,filename,OPTIONS);
+    else
+        error('Incorrect number of input arguments');
+    end
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tools/symbolic/SBPDsymjacobian.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tools/symbolic/SBPDsymjacobian.m
new file mode 100644
index 0000000000000000000000000000000000000000..9ae5ff75b6efb87f5ee67e20da5f38c9c6c3ce4b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_ACADEMIC/tools/symbolic/SBPDsymjacobian.m
@@ -0,0 +1,142 @@
+function [output] = SBPDsymjacobian(model,varargin)
+% SBPDsymjacobian: Determines a symbolic Jacobian and the derivative of the
+% ODE right hand side with respect to given parameters. For the latter to
+% be computed, parameters need to be specified. The general computation for
+% all parameters in a model would be often to time costly.
+%
+% USAGE:
+% ======
+% output = SBPDsymjacobian(model)
+% output = SBPDsymjacobian(model, simpleflag)
+% output = SBPDsymjacobian(model, parameternames)
+% output = SBPDsymjacobian(model, parameternames, simpleflag)
+%
+% model: SBmodel
+% simpleflag: =0 => do not try to simplify (default), =1 => try to simplify (slower)
+% parameternames: cellarray with parameters to compute the derivative of
+% the ODE right hand side for. 
+%
+% Output Arguments:
+% =================
+% output: structure containing all output information:
+%   output.states: cellarray with all statenames in the model   
+%   output.jacobian: cell-matrix containing the symbolic expressions for the jacobian
+% If parameters are given the output contains additionally:   
+%   output.parameters: cellarray of considered parameters
+%   outputs.dfdp: cell-matrix containing the symbolic expressions for dfdp 
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+academicWarningSBPD
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK SYMBOLIC TOOLBOX
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~symbolicpresentSB(),
+    error('Symbolic toolboc needed, but not available.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK TYPE OF MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~strcmp(class(model),'SBmodel'),
+    error('Incorrect model input argument.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SIMPLE FLAG & PARAMETERS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+simpleflag = 0;
+parameternames = {};
+if nargin == 2,
+    if iscell(varargin{1}) || ischar(varargin{1}),
+        parameternames = varargin{1};
+    else
+        simpleflag = varargin{1};
+    end
+elseif nargin == 3,
+    parameternames = varargin{1};
+    simpleflag = varargin{2};
+end
+if ischar(parameternames),
+    parameternames = {parameternames};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET ALL FORMULAS AND ODES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[statenames,ODEs] = SBstates(model);
+[variablenames, variableformulas] = SBvariables(model);
+[reactionnames, reactionformulas] = SBreactions(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXPAND VARIABLES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k = 1:length(variablenames),
+    for k2 = k+1:length(variablenames),
+        variableformulas{k2} = char(subs(variableformulas{k2}, variablenames{k}, variableformulas{k}));
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INSERT VARIABLES TO REACTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k = 1:length(reactionnames),
+    for k2 = 1:length(variablenames),
+        reactionformulas{k} = char(subs(reactionformulas{k}, variablenames{k2}, variableformulas{k2}));
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INSERT VARIABLES AND REACTIONS INTO ODES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k = 1:length(ODEs),
+    for k2 = 1:length(variablenames),
+        ODEs{k} = char(subs(ODEs{k}, variablenames{k2}, variableformulas{k2}));
+    end
+    for k2 = 1:length(reactionnames),
+        ODEs{k} = char(subs(ODEs{k}, reactionnames{k2}, reactionformulas{k2}));
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE JACOBIAN
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+jacobian = cell(length(statenames));
+for k = 1:length(statenames),
+    for k2 = 1:length(statenames),
+        jacobian{k,k2} = char(diff(ODEs{k},statenames{k2}));
+        if simpleflag == 1,
+            jacobian{k,k2} = char(simple(sym(jacobian{k,k2})));
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE DFDP
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dfdp = {};
+if ~isempty(parameternames),
+    for k = 1:length(statenames),
+        for k2 = 1:length(parameternames),
+            dfdp{k,k2} = char(diff(ODEs{k},parameternames{k2}));
+            if simpleflag == 1,
+                dfdp{k,k2} = char(simple(sym(dfdp{k,k2})));
+            end
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONSTRUCT OUTPUT ARGUMENT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output = [];
+output.states = statenames;
+output.jacobian = jacobian;
+if ~isempty(dfdp),
+    output.parameters = parameternames;
+    output.dfdp = dfdp;
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_EXAMPLES/BIOMD14.xml b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_EXAMPLES/BIOMD14.xml
new file mode 100644
index 0000000000000000000000000000000000000000..dbb7480288bfd7b04bf81b621cb9282a2d1c81df
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_EXAMPLES/BIOMD14.xml
@@ -0,0 +1,11058 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<sbml level="2" metaid="_001885" version="1" xmlns="http://www.sbml.org/sbml/level2">
+  <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_001885">
+<dc:contributor rdf:parseType="Resource">
+<vCard:N rdf:parseType="Resource">
+<vCard:Family>Le Novère</vCard:Family>
+<vCard:Given>Nicolas</vCard:Given>
+</vCard:N>
+<vCard:EMAIL>lenov@ebi.ac.uk</vCard:EMAIL>
+<vCard:ORG>
+<vCard:Orgname>EMBL-EBI</vCard:Orgname>
+</vCard:ORG>
+</dc:contributor>
+<dcterms:created rdf:parseType="Resource">
+<dcterms:W3CDTF>2005-02-25T23:43:21</dcterms:W3CDTF>
+</dcterms:created>
+<dcterms:modified rdf:parseType="Resource">
+<dcterms:W3CDTF>2005-05-27T13:07:24</dcterms:W3CDTF>
+</dcterms:modified>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<model id="MAPK_in_Scaffold" metaid="_000001" name="Levchenko2000_MAPK_Scaffold">
+    <notes>
+      
+		<body xmlns="http://www.w3.org/1999/xhtml">
+			<h1>MAPK cascade on a scaffold</h1>
+
+			<table border="0" cellpadding="2" cellspacing="0">
+				<thead>
+					<tr>
+						<th align="left" bgcolor="#eeeeee" valign="middle">Citation</th>
+					</tr>
+				</thead>
+				<tbody>
+					<tr>
+						<td>Levchenko, A., Bruck, J., Sternberg, P.W. (2000)
+							.Scaffold proteins may biphasically affect the levels of mitogen-activated protein kinase signaling and reduce its threshold properties. Proc. Natl. Acad. Sci. USA 97(11):5818-5823.
+						<a href="http://www.pnas.org/cgi/content/abstract/97/11/5818">
+							http://www.pnas.org/cgi/content/abstract/97/11/5818
+						</a>
+</td>
+					</tr>
+				</tbody>
+			</table>
+			
+			<table border="0" cellpadding="2" cellspacing="0">
+				<thead>
+					<tr>
+						<th align="left" bgcolor="#eeeeee" valign="middle">Description</th>
+					</tr>
+				</thead>
+				<tbody>
+					<tr>
+						<td>This model describes a basic 3-stage Mitogen Activated Protein Kinase (MAPK). Kinases in solution are written as  K[3,J], K[2,J], K[1,J] for MAPKKK, MAPKK, and MAPK, respectively, J indicates the phosphorylation level, J=0,1 for K3 and J=0,1,2 for K2 and K1. Scaffolds have three slots, for MAPK, MAPKK, and MAPKKK, respectively. Bound and free scaffold are denoted as S[i,j,k], where i, j, and k indicate the binding of K[1,i], K[2,j] and K[3,k] in their respective slots. Here i,j=-1,0,1,or,2 and k=-1,0,or,1. A value of -1 means the slot is empty, 0 means the unphorphorylated kinase is bound, 1 means the singly phosphorylated kinase is bound, and 2 means the doubly phosphorylated kinase is bound. Thus S[1,-1,2] is a scaffold with K[3,1] bound in the first slot and K[1,2] in the third slot, while the second slot is empty.Note: Indices X[I,J,K] are translated into the unindexed variable X_I_J_K and so forth in the SBML.  Negative indices are translated as mI, etc, thus S[1,-1,2] becomes S_1_m1_2.</td>
+					</tr>
+				</tbody>
+			</table>
+			
+			<table border="0" cellpadding="2" cellspacing="0">
+				<thead>
+					<tr>
+						<th align="left" bgcolor="#eeeeee" valign="middle">Rate constant      </th>
+						<th align="left" bgcolor="#eeeeee" valign="middle">Reaction</th>
+					</tr>
+				</thead>
+				<tbody>
+					<tr>
+						<td>a10 = 5.</td>
+						<td>MAPKP + K[1, 2] -&gt; K_MAPKP[1, 2]</td>
+					</tr>
+					<tr>
+						<td>a1 = 1.</td>
+						<td>RAFK + K[3, 0] -&gt; K_RAFK[3, 0]</td>
+					</tr>
+					<tr>
+						<td>a2 = 0.5</td>
+						<td>RAFP + K[3, 1] -&gt; K_RAFP[3, 1]</td>
+					</tr>
+					<tr>
+						<td>a3 = 3.3</td>
+						<td>K[2, 0] + K[3, 1] -&gt; K_K[2, 0, 3,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>a4 = 10.</td>
+						<td>MEKP + K[2, 1] -&gt; K_MEKP[2, 1]</td>
+					</tr>
+					<tr>
+						<td>a5 = 3.3</td>
+						<td>K[2, 1] + K[3, 1] -&gt; K_K[2, 1, 3,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>a6 = 10.</td>
+						<td>MEKP + K[2, 2] -&gt; K_MEKP[2, 2]</td>
+					</tr>
+					<tr>
+						<td>a7 = 20.</td>
+						<td>K[1, 0] + K[2, 2] -&gt; K_K[1, 0, 2,
+							 2]</td>
+					</tr>
+					<tr>
+						<td>a8 = 5.</td>
+						<td>MAPKP + K[1, 1] -&gt; K_MAPKP[1, 1]</td>
+					</tr>
+					<tr>
+						<td>a9 = 20.</td>
+						<td>K[1, 1] + K[2, 2] -&gt; K_K[1, 1, 2,
+							 2]</td>
+					</tr>
+					<tr>
+						<td>d10 = 0.4</td>
+						<td>K_MAPKP[1, 2] -&gt; MAPKP + K[1, 2]</td>
+					</tr>
+					<tr>
+						<td>d1 = 0.4</td>
+						<td>K_RAFK[3, 0] -&gt; RAFK + K[3, 0]</td>
+					</tr>
+					<tr>
+						<td>d1a = 0</td>
+						<td>S_RAFK[0, 0, 0] -&gt; RAFK + S[0, 0, 0]</td>
+					</tr>
+					<tr>
+						<td>d1a = 0</td>
+						<td>S_RAFK[0, -1, 0] -&gt; RAFK + S[0, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>d1a = 0</td>
+						<td>S_RAFK[0, 1, 0] -&gt; RAFK + S[0, 1, 0]</td>
+					</tr>
+					<tr>
+						<td>d1a = 0</td>
+						<td>S_RAFK[0, 2, 0] -&gt; RAFK + S[0, 2, 0]</td>
+					</tr>
+					<tr>
+						<td>d1a = 0</td>
+						<td>S_RAFK[-1, 0, 0] -&gt; RAFK + S[-1, 0,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>d1a = 0</td>
+						<td>S_RAFK[1, 0, 0] -&gt; RAFK + S[1, 0, 0]</td>
+					</tr>
+					<tr>
+						<td>d1a = 0</td>
+						<td>S_RAFK[-1, -1, 0] -&gt; RAFK + S[-1, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>d1a = 0</td>
+						<td>S_RAFK[-1, 1, 0] -&gt; RAFK + S[-1, 1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>d1a = 0</td>
+						<td>S_RAFK[1, -1, 0] -&gt; RAFK + S[1, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>d1a = 0</td>
+						<td>S_RAFK[1, 1, 0] -&gt; RAFK + S[1, 1, 0]</td>
+					</tr>
+					<tr>
+						<td>d1a = 0</td>
+						<td>S_RAFK[-1, 2, 0] -&gt; RAFK + S[-1, 2,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>d1a = 0</td>
+						<td>S_RAFK[1, 2, 0] -&gt; RAFK + S[1, 2, 0]</td>
+					</tr>
+					<tr>
+						<td>d1a = 0</td>
+						<td>S_RAFK[2, 0, 0] -&gt; RAFK + S[2, 0, 0]</td>
+					</tr>
+					<tr>
+						<td>d1a = 0</td>
+						<td>S_RAFK[2, -1, 0] -&gt; RAFK + S[2, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>d1a = 0</td>
+						<td>S_RAFK[2, 1, 0] -&gt; RAFK + S[2, 1, 0]</td>
+					</tr>
+					<tr>
+						<td>d1a = 0</td>
+						<td>S_RAFK[2, 2, 0] -&gt; RAFK + S[2, 2, 0]</td>
+					</tr>
+					<tr>
+						<td>d2 = 0.5</td>
+						<td>K_RAFP[3, 1] -&gt; RAFP + K[3, 1]</td>
+					</tr>
+					<tr>
+						<td>d3 = 0.42</td>
+						<td>K_K[2, 0, 3, 1] -&gt; K[2, 0] + K[3,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>d4 = 0.8</td>
+						<td>K_MEKP[2, 1] -&gt; MEKP + K[2, 1]</td>
+					</tr>
+					<tr>
+						<td>d5 = 0.4</td>
+						<td>K_K[2, 1, 3, 1] -&gt; K[2, 1] + K[3,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>d6 = 0.8</td>
+						<td>K_MEKP[2, 2] -&gt; MEKP + K[2, 2]</td>
+					</tr>
+					<tr>
+						<td>d7 = 0.6</td>
+						<td>K_K[1, 0, 2, 2] -&gt; K[1, 0] + K[2,
+							 2]</td>
+					</tr>
+					<tr>
+						<td>d8 = 0.4</td>
+						<td>K_MAPKP[1, 1] -&gt; MAPKP + K[1, 1]</td>
+					</tr>
+					<tr>
+						<td>d9 = 0.6</td>
+						<td>K_K[1, 1, 2, 2] -&gt; K[1, 1] + K[2,
+							 2]</td>
+					</tr>
+					<tr>
+						<td>k10 = 0.1</td>
+						<td>K_MAPKP[1, 2] -&gt; MAPKP + K[1, 1]</td>
+					</tr>
+					<tr>
+						<td>k1 = 0.1</td>
+						<td>K_RAFK[3, 0] -&gt; RAFK + K[3, 1]</td>
+					</tr>
+					<tr>
+						<td>k1 = 0.1</td>
+						<td>S_RAFK[0, 0, 0] -&gt; RAFK + S[0, 0, 1]</td>
+					</tr>
+					<tr>
+						<td>k1 = 0.1</td>
+						<td>S_RAFK[0, -1, 0] -&gt; RAFK + S[0, -1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>k1 = 0.1</td>
+						<td>S_RAFK[0, 1, 0] -&gt; RAFK + S[0, 1, 1]</td>
+					</tr>
+					<tr>
+						<td>k1 = 0.1</td>
+						<td>S_RAFK[0, 2, 0] -&gt; RAFK + S[0, 2, 1]</td>
+					</tr>
+					<tr>
+						<td>k1 = 0.1</td>
+						<td>S_RAFK[-1, 0, 0] -&gt; RAFK + S[-1, 0,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>k1 = 0.1</td>
+						<td>S_RAFK[1, 0, 0] -&gt; RAFK + S[1, 0, 1]</td>
+					</tr>
+					<tr>
+						<td>k1 = 0.1</td>
+						<td>S_RAFK[-1, -1, 0] -&gt; RAFK + S[-1, -1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>k1 = 0.1</td>
+						<td>S_RAFK[-1, 1, 0] -&gt; RAFK + S[-1, 1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>k1 = 0.1</td>
+						<td>S_RAFK[1, -1, 0] -&gt; RAFK + S[1, -1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>k1 = 0.1</td>
+						<td>S_RAFK[1, 1, 0] -&gt; RAFK + S[1, 1, 1]</td>
+					</tr>
+					<tr>
+						<td>k1 = 0.1</td>
+						<td>S_RAFK[-1, 2, 0] -&gt; RAFK + S[-1, 2,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>k1 = 0.1</td>
+						<td>S_RAFK[1, 2, 0] -&gt; RAFK + S[1, 2, 1]</td>
+					</tr>
+					<tr>
+						<td>k1 = 0.1</td>
+						<td>S_RAFK[2, 0, 0] -&gt; RAFK + S[2, 0, 1]</td>
+					</tr>
+					<tr>
+						<td>k1 = 0.1</td>
+						<td>S_RAFK[2, -1, 0] -&gt; RAFK + S[2, -1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>k1 = 0.1</td>
+						<td>S_RAFK[2, 1, 0] -&gt; RAFK + S[2, 1, 1]</td>
+					</tr>
+					<tr>
+						<td>k1 = 0.1</td>
+						<td>S_RAFK[2, 2, 0] -&gt; RAFK + S[2, 2, 1]</td>
+					</tr>
+					<tr>
+						<td>k1a = 100</td>
+						<td>RAFK + S[0, 0, 0] -&gt; S_RAFK[0, 0, 0]</td>
+					</tr>
+					<tr>
+						<td>k1a = 100</td>
+						<td>RAFK + S[0, -1, 0] -&gt; S_RAFK[0, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>k1a = 100</td>
+						<td>RAFK + S[0, 1, 0] -&gt; S_RAFK[0, 1, 0]</td>
+					</tr>
+					<tr>
+						<td>k1a = 100</td>
+						<td>RAFK + S[0, 2, 0] -&gt; S_RAFK[0, 2, 0]</td>
+					</tr>
+					<tr>
+						<td>k1a = 100</td>
+						<td>RAFK + S[-1, 0, 0] -&gt; S_RAFK[-1, 0,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>k1a = 100</td>
+						<td>RAFK + S[1, 0, 0] -&gt; S_RAFK[1, 0, 0]</td>
+					</tr>
+					<tr>
+						<td>k1a = 100</td>
+						<td>RAFK + S[-1, -1, 0] -&gt; S_RAFK[-1, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>k1a = 100</td>
+						<td>RAFK + S[-1, 1, 0] -&gt; S_RAFK[-1, 1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>k1a = 100</td>
+						<td>RAFK + S[1, -1, 0] -&gt; S_RAFK[1, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>k1a = 100</td>
+						<td>RAFK + S[1, 1, 0] -&gt; S_RAFK[1, 1, 0]</td>
+					</tr>
+					<tr>
+						<td>k1a = 100</td>
+						<td>RAFK + S[-1, 2, 0] -&gt; S_RAFK[-1, 2,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>k1a = 100</td>
+						<td>RAFK + S[1, 2, 0] -&gt; S_RAFK[1, 2, 0]</td>
+					</tr>
+					<tr>
+						<td>k1a = 100</td>
+						<td>RAFK + S[2, 0, 0] -&gt; S_RAFK[2, 0, 0]</td>
+					</tr>
+					<tr>
+						<td>k1a = 100</td>
+						<td>RAFK + S[2, -1, 0] -&gt; S_RAFK[2, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>k1a = 100</td>
+						<td>RAFK + S[2, 1, 0] -&gt; S_RAFK[2, 1, 0]</td>
+					</tr>
+					<tr>
+						<td>k1a = 100</td>
+						<td>RAFK + S[2, 2, 0] -&gt; S_RAFK[2, 2, 0]</td>
+					</tr>
+					<tr>
+						<td>k2 = 0.1</td>
+						<td>K_RAFP[3, 1] -&gt; RAFP + K[3, 0]</td>
+					</tr>
+					<tr>
+						<td>k3 = 0.1</td>
+						<td>K_K[2, 0, 3, 1] -&gt; K[2, 1] + K[3,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>k3 = 0.1</td>
+						<td>S[0, 0, 1] -&gt; S[0, 1, 1]</td>
+					</tr>
+					<tr>
+						<td>k3 = 0.1</td>
+						<td>S[-1, 0, 1] -&gt; S[-1, 1, 1]</td>
+					</tr>
+					<tr>
+						<td>k3 = 0.1</td>
+						<td>S[1, 0, 1] -&gt; S[1, 1, 1]</td>
+					</tr>
+					<tr>
+						<td>k3 = 0.1</td>
+						<td>S[2, 0, 1] -&gt; S[2, 1, 1]</td>
+					</tr>
+					<tr>
+						<td>k4 = 0.1</td>
+						<td>K_MEKP[2, 1] -&gt; MEKP + K[2, 0]</td>
+					</tr>
+					<tr>
+						<td>k5 = 0.1</td>
+						<td>K_K[2, 1, 3, 1] -&gt; K[2, 2] + K[3,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>k5a = 0.1</td>
+						<td>S[0, 1, 1] -&gt; S[0, 2, 1]</td>
+					</tr>
+					<tr>
+						<td>k5a = 0.1</td>
+						<td>S[-1, 1, 1] -&gt; S[-1, 2, 1]</td>
+					</tr>
+					<tr>
+						<td>k5a = 0.1</td>
+						<td>S[1, 1, 1] -&gt; S[1, 2, 1]</td>
+					</tr>
+					<tr>
+						<td>k5a = 0.1</td>
+						<td>S[2, 1, 1] -&gt; S[2, 2, 1]</td>
+					</tr>
+					<tr>
+						<td>k6 = 0.1</td>
+						<td>K_MEKP[2, 2] -&gt; MEKP + K[2, 1]</td>
+					</tr>
+					<tr>
+						<td>k7 = 0.1</td>
+						<td>K_K[1, 0, 2, 2] -&gt; K[1, 1] + K[2,
+							 2]</td>
+					</tr>
+					<tr>
+						<td>k7 = 0.1</td>
+						<td>S[0, 2, 0] -&gt; S[1, 2, 0]</td>
+					</tr>
+					<tr>
+						<td>k7 = 0.1</td>
+						<td>S[0, 2, -1] -&gt; S[1, 2, -1]</td>
+					</tr>
+					<tr>
+						<td>k7 = 0.1</td>
+						<td>S[0, 2, 1] -&gt; S[1, 2, 1]</td>
+					</tr>
+					<tr>
+						<td>k8 = 0.1</td>
+						<td>K_MAPKP[1, 1] -&gt; MAPKP + K[1, 0]</td>
+					</tr>
+					<tr>
+						<td>k9 = 0.1</td>
+						<td>K_K[1, 1, 2, 2] -&gt; K[1, 2] + K[2,
+							 2]</td>
+					</tr>
+					<tr>
+						<td>k9a = 0.1</td>
+						<td>S[1, 2, 0] -&gt; S[2, 2, 0]</td>
+					</tr>
+					<tr>
+						<td>k9a = 0.1</td>
+						<td>S[1, 2, -1] -&gt; S[2, 2, -1]</td>
+					</tr>
+					<tr>
+						<td>k9a = 0.1</td>
+						<td>S[1, 2, 1] -&gt; S[2, 2, 1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[0, 0, 0] -&gt; K[1, 0] + S[-1, 0,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[0, 0, 0] -&gt; K[2, 0] + S[0, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[0, 0, 0] -&gt; K[3, 0] + S[0, 0,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[0, 0, -1] -&gt; K[1, 0] + S[-1, 0,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[0, 0, 1] -&gt; K[1, 0] + S[-1, 0,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[0, 0, -1] -&gt; K[2, 0] + S[0, -1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[0, 0, 1] -&gt; K[2, 0] + S[0, -1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[0, -1, 0] -&gt; K[1, 0] + S[-1, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[0, 1, 0] -&gt; K[1, 0] + S[-1, 1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[0, -1, 0] -&gt; K[3, 0] + S[0, -1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[0, 1, 0] -&gt; K[3, 0] + S[0, 1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[0, -1, -1] -&gt; K[1, 0] + S[-1, -1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[0, -1, 1] -&gt; K[1, 0] + S[-1, -1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[0, 1, -1] -&gt; K[1, 0] + S[-1, 1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[0, 1, 1] -&gt; K[1, 0] + S[-1, 1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[0, 2, 0] -&gt; K[1, 0] + S[-1, 2,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[0, 2, 0] -&gt; K[3, 0] + S[0, 2,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[0, 2, -1] -&gt; K[1, 0] + S[-1, 2,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[0, 2, 1] -&gt; K[1, 0] + S[-1, 2,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[-1, 0, 0] -&gt; K[2, 0] + S[-1, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[1, 0, 0] -&gt; K[2, 0] + S[1, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[-1, 0, 0] -&gt; K[3, 0] + S[-1, 0,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[1, 0, 0] -&gt; K[3, 0] + S[1, 0,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[-1, 0, -1] -&gt; K[2, 0] + S[-1, -1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[-1, 0, 1] -&gt; K[2, 0] + S[-1, -1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[1, 0, -1] -&gt; K[2, 0] + S[1, -1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[1, 0, 1] -&gt; K[2, 0] + S[1, -1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[-1, -1, 0] -&gt; K[3, 0] + S[-1, -1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[-1, 1, 0] -&gt; K[3, 0] + S[-1, 1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[1, -1, 0] -&gt; K[3, 0] + S[1, -1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[1, 1, 0] -&gt; K[3, 0] + S[1, 1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[-1, 2, 0] -&gt; K[3, 0] + S[-1, 2,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[1, 2, 0] -&gt; K[3, 0] + S[1, 2,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[2, 0, 0] -&gt; K[2, 0] + S[2, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[2, 0, 0] -&gt; K[3, 0] + S[2, 0,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[2, 0, -1] -&gt; K[2, 0] + S[2, -1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[2, 0, 1] -&gt; K[2, 0] + S[2, -1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[2, -1, 0] -&gt; K[3, 0] + S[2, -1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[2, 1, 0] -&gt; K[3, 0] + S[2, 1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>koff = 0.5</td>
+						<td>S[2, 2, 0] -&gt; K[3, 0] + S[2, 2,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[1, 0] + S[-1, 0, 0] -&gt; S[0, 0,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[1, 0] + S[-1, 0, -1] -&gt; S[0, 0,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[1, 0] + S[-1, 0, 1] -&gt; S[0, 0,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[1, 0] + S[-1, -1, 0] -&gt; S[0, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[1, 0] + S[-1, 1, 0] -&gt; S[0, 1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[1, 0] + S[-1, -1, -1] -&gt; S[0, -1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[1, 0] + S[-1, -1, 1] -&gt; S[0, -1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[1, 0] + S[-1, 1, -1] -&gt; S[0, 1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[1, 0] + S[-1, 1, 1] -&gt; S[0, 1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[1, 0] + S[-1, 2, 0] -&gt; S[0, 2,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[1, 0] + S[-1, 2, -1] -&gt; S[0, 2,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[1, 0] + S[-1, 2, 1] -&gt; S[0, 2,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[2, 0] + S[0, -1, 0] -&gt; S[0, 0,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[2, 0] + S[0, -1, -1] -&gt; S[0, 0,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[2, 0] + S[0, -1, 1] -&gt; S[0, 0,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[2, 0] + S[-1, -1, 0] -&gt; S[-1, 0,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[2, 0] + S[1, -1, 0] -&gt; S[1, 0,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[2, 0] + S[-1, -1, -1] -&gt; S[-1, 0,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[2, 0] + S[-1, -1, 1] -&gt; S[-1, 0,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[2, 0] + S[1, -1, -1] -&gt; S[1, 0,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[2, 0] + S[1, -1, 1] -&gt; S[1, 0,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[2, 0] + S[2, -1, 0] -&gt; S[2, 0,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[2, 0] + S[2, -1, -1] -&gt; S[2, 0,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[2, 0] + S[2, -1, 1] -&gt; S[2, 0,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[3, 0] + S[0, 0, -1] -&gt; S[0, 0,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[3, 0] + S[0, -1, -1] -&gt; S[0, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[3, 0] + S[0, 1, -1] -&gt; S[0, 1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[3, 0] + S[0, 2, -1] -&gt; S[0, 2,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[3, 0] + S[-1, 0, -1] -&gt; S[-1, 0,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[3, 0] + S[1, 0, -1] -&gt; S[1, 0,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[3, 0] + S[-1, -1, -1] -&gt; S[-1, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[3, 0] + S[-1, 1, -1] -&gt; S[-1, 1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[3, 0] + S[1, -1, -1] -&gt; S[1, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[3, 0] + S[1, 1, -1] -&gt; S[1, 1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[3, 0] + S[-1, 2, -1] -&gt; S[-1, 2,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[3, 0] + S[1, 2, -1] -&gt; S[1, 2,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[3, 0] + S[2, 0, -1] -&gt; S[2, 0,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[3, 0] + S[2, -1, -1] -&gt; S[2, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[3, 0] + S[2, 1, -1] -&gt; S[2, 1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kon = 10</td>
+						<td>K[3, 0] + S[2, 2, -1] -&gt; S[2, 2,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[0, 0, 1] -&gt; K[3, 1] + S[0, 0,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[0, 1, 0] -&gt; K[2, 1] + S[0, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[0, 1, -1] -&gt; K[2, 1] + S[0, -1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[0, 1, 1] -&gt; K[2, 1] + S[0, -1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[0, -1, 1] -&gt; K[3, 1] + S[0, -1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[0, 1, 1] -&gt; K[3, 1] + S[0, 1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[0, 2, 0] -&gt; K[2, 2] + S[0, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[0, 2, -1] -&gt; K[2, 2] + S[0, -1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[0, 2, 1] -&gt; K[2, 2] + S[0, -1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[0, 2, 1] -&gt; K[3, 1] + S[0, 2,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[1, 0, 0] -&gt; K[1, 1] + S[-1, 0,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[1, 0, -1] -&gt; K[1, 1] + S[-1, 0,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[1, 0, 1] -&gt; K[1, 1] + S[-1, 0,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[-1, 0, 1] -&gt; K[3, 1] + S[-1, 0,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[1, 0, 1] -&gt; K[3, 1] + S[1, 0,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[1, -1, 0] -&gt; K[1, 1] + S[-1, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[1, 1, 0] -&gt; K[1, 1] + S[-1, 1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[-1, 1, 0] -&gt; K[2, 1] + S[-1, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[1, 1, 0] -&gt; K[2, 1] + S[1, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[1, -1, -1] -&gt; K[1, 1] + S[-1, -1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[1, -1, 1] -&gt; K[1, 1] + S[-1, -1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[1, 1, -1] -&gt; K[1, 1] + S[-1, 1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[1, 1, 1] -&gt; K[1, 1] + S[-1, 1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[-1, 1, -1] -&gt; K[2, 1] + S[-1, -1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[-1, 1, 1] -&gt; K[2, 1] + S[-1, -1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[1, 1, -1] -&gt; K[2, 1] + S[1, -1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[1, 1, 1] -&gt; K[2, 1] + S[1, -1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[-1, -1, 1] -&gt; K[3, 1] + S[-1, -1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[-1, 1, 1] -&gt; K[3, 1] + S[-1, 1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[1, -1, 1] -&gt; K[3, 1] + S[1, -1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[1, 1, 1] -&gt; K[3, 1] + S[1, 1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[1, 2, 0] -&gt; K[1, 1] + S[-1, 2,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[-1, 2, 0] -&gt; K[2, 2] + S[-1, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[1, 2, 0] -&gt; K[2, 2] + S[1, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[1, 2, -1] -&gt; K[1, 1] + S[-1, 2,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[1, 2, 1] -&gt; K[1, 1] + S[-1, 2,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[-1, 2, -1] -&gt; K[2, 2] + S[-1, -1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[-1, 2, 1] -&gt; K[2, 2] + S[-1, -1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[1, 2, -1] -&gt; K[2, 2] + S[1, -1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[1, 2, 1] -&gt; K[2, 2] + S[1, -1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[-1, 2, 1] -&gt; K[3, 1] + S[-1, 2,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[1, 2, 1] -&gt; K[3, 1] + S[1, 2,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[2, 0, 0] -&gt; K[1, 2] + S[-1, 0,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[2, 0, -1] -&gt; K[1, 2] + S[-1, 0,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[2, 0, 1] -&gt; K[1, 2] + S[-1, 0,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[2, 0, 1] -&gt; K[3, 1] + S[2, 0,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[2, -1, 0] -&gt; K[1, 2] + S[-1, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[2, 1, 0] -&gt; K[1, 2] + S[-1, 1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[2, 1, 0] -&gt; K[2, 1] + S[2, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[2, -1, -1] -&gt; K[1, 2] + S[-1, -1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[2, -1, 1] -&gt; K[1, 2] + S[-1, -1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[2, 1, -1] -&gt; K[1, 2] + S[-1, 1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[2, 1, 1] -&gt; K[1, 2] + S[-1, 1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[2, 1, -1] -&gt; K[2, 1] + S[2, -1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[2, 1, 1] -&gt; K[2, 1] + S[2, -1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[2, -1, 1] -&gt; K[3, 1] + S[2, -1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[2, 1, 1] -&gt; K[3, 1] + S[2, 1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[2, 2, 0] -&gt; K[1, 2] + S[-1, 2,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[2, 2, 0] -&gt; K[2, 2] + S[2, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[2, 2, -1] -&gt; K[1, 2] + S[-1, 2,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[2, 2, 1] -&gt; K[1, 2] + S[-1, 2,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[2, 2, -1] -&gt; K[2, 2] + S[2, -1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[2, 2, 1] -&gt; K[2, 2] + S[2, -1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpoff = 0.05</td>
+						<td>S[2, 2, 1] -&gt; K[3, 1] + S[2, 2,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[1, 1] + S[-1, 0, 0] -&gt; S[1, 0,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[1, 1] + S[-1, 0, -1] -&gt; S[1, 0,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[1, 1] + S[-1, 0, 1] -&gt; S[1, 0,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[1, 1] + S[-1, -1, 0] -&gt; S[1, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[1, 1] + S[-1, 1, 0] -&gt; S[1, 1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[1, 1] + S[-1, -1, -1] -&gt; S[1, -1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[1, 1] + S[-1, -1, 1] -&gt; S[1, -1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[1, 1] + S[-1, 1, -1] -&gt; S[1, 1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[1, 1] + S[-1, 1, 1] -&gt; S[1, 1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[1, 1] + S[-1, 2, 0] -&gt; S[1, 2,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[1, 1] + S[-1, 2, -1] -&gt; S[1, 2,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[1, 1] + S[-1, 2, 1] -&gt; S[1, 2,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[1, 2] + S[-1, 0, 0] -&gt; S[2, 0,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[1, 2] + S[-1, 0, -1] -&gt; S[2, 0,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[1, 2] + S[-1, 0, 1] -&gt; S[2, 0,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[1, 2] + S[-1, -1, 0] -&gt; S[2, -1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[1, 2] + S[-1, 1, 0] -&gt; S[2, 1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[1, 2] + S[-1, -1, -1] -&gt; S[2, -1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[1, 2] + S[-1, -1, 1] -&gt; S[2, -1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[1, 2] + S[-1, 1, -1] -&gt; S[2, 1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[1, 2] + S[-1, 1, 1] -&gt; S[2, 1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[1, 2] + S[-1, 2, 0] -&gt; S[2, 2,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[1, 2] + S[-1, 2, -1] -&gt; S[2, 2,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[1, 2] + S[-1, 2, 1] -&gt; S[2, 2,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[2, 1] + S[0, -1, 0] -&gt; S[0, 1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[2, 1] + S[0, -1, -1] -&gt; S[0, 1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[2, 1] + S[0, -1, 1] -&gt; S[0, 1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[2, 1] + S[-1, -1, 0] -&gt; S[-1, 1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[2, 1] + S[1, -1, 0] -&gt; S[1, 1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[2, 1] + S[-1, -1, -1] -&gt; S[-1, 1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[2, 1] + S[-1, -1, 1] -&gt; S[-1, 1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[2, 1] + S[1, -1, -1] -&gt; S[1, 1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[2, 1] + S[1, -1, 1] -&gt; S[1, 1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[2, 1] + S[2, -1, 0] -&gt; S[2, 1,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[2, 1] + S[2, -1, -1] -&gt; S[2, 1,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[2, 1] + S[2, -1, 1] -&gt; S[2, 1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[2, 2] + S[0, -1, 0] -&gt; S[0, 2,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[2, 2] + S[0, -1, -1] -&gt; S[0, 2,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[2, 2] + S[0, -1, 1] -&gt; S[0, 2,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[2, 2] + S[-1, -1, 0] -&gt; S[-1, 2,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[2, 2] + S[1, -1, 0] -&gt; S[1, 2,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[2, 2] + S[-1, -1, -1] -&gt; S[-1, 2,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[2, 2] + S[-1, -1, 1] -&gt; S[-1, 2,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[2, 2] + S[1, -1, -1] -&gt; S[1, 2,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[2, 2] + S[1, -1, 1] -&gt; S[1, 2,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[2, 2] + S[2, -1, 0] -&gt; S[2, 2,
+							 0]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[2, 2] + S[2, -1, -1] -&gt; S[2, 2,
+							 -1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[2, 2] + S[2, -1, 1] -&gt; S[2, 2,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[3, 1] + S[0, 0, -1] -&gt; S[0, 0,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[3, 1] + S[0, -1, -1] -&gt; S[0, -1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[3, 1] + S[0, 1, -1] -&gt; S[0, 1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[3, 1] + S[0, 2, -1] -&gt; S[0, 2,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[3, 1] + S[-1, 0, -1] -&gt; S[-1, 0,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[3, 1] + S[1, 0, -1] -&gt; S[1, 0,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[3, 1] + S[-1, -1, -1] -&gt; S[-1, -1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[3, 1] + S[-1, 1, -1] -&gt; S[-1, 1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[3, 1] + S[1, -1, -1] -&gt; S[1, -1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[3, 1] + S[1, 1, -1] -&gt; S[1, 1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[3, 1] + S[-1, 2, -1] -&gt; S[-1, 2,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[3, 1] + S[1, 2, -1] -&gt; S[1, 2,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[3, 1] + S[2, 0, -1] -&gt; S[2, 0,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[3, 1] + S[2, -1, -1] -&gt; S[2, -1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[3, 1] + S[2, 1, -1] -&gt; S[2, 1,
+							 1]</td>
+					</tr>
+					<tr>
+						<td>kpon = 0</td>
+						<td>K[3, 1] + S[2, 2, -1] -&gt; S[2, 2,
+							 1]</td>
+					</tr>
+				</tbody>
+			</table>
+
+			<table border="0" cellpadding="2" cellspacing="0">
+				<thead>
+					<tr>
+						<th align="left" bgcolor="#eeeeee" valign="middle">Variable</th>
+						<th align="left" bgcolor="#eeeeee" valign="middle">IC  </th>
+						<th align="left" bgcolor="#eeeeee" valign="middle">ODE</th>
+					</tr>
+				</thead>
+				<tbody>
+					<tr>
+						<td>MAPKP</td>
+						<td>0.3</td>
+						<td>MAPKP'[t] == -(a8*MAPKP[t]*K[1, 1][t]) - a10*MAPKP[
+							t]*K[1, 2][t] + d8*K_MAPKP[1, 1][t] + k8*K_MAPKP[
+							1, 1][t] + d10*K_MAPKP[1, 2][t] + k10*K_MAPKP[1,
+							 2][t]</td>
+					</tr>
+					<tr>
+						<td>MEKP</td>
+						<td>0.2</td>
+						<td>MEKP'[t] == -(a4*MEKP[t]*K[2, 1][t]) - a6*MEKP[t]*
+							K[2, 2][t] + d4*K_MEKP[2, 1][t] + k4*K_MEKP[2,
+							 1][t] + d6*K_MEKP[2, 2][t] + k6*K_MEKP[2, 2]
+							[t]</td>
+					</tr>
+					<tr>
+						<td>RAFK</td>
+						<td>0.1</td>
+						<td>RAFK'[t] == -(a1*RAFK[t]*K[3, 0][t]) + d1*K_RAFK[3,
+							 0][t] + k1*K_RAFK[3, 0][t] - k1a*RAFK[t]*S[-1,
+							 -1, 0][t] - k1a*RAFK[t]*S[-1, 0, 0][t] -
+							 k1a*RAFK[t]*S[-1, 1, 0][t] - k1a*RAFK[t]*S[-1, 2,
+							 0][t] - k1a*RAFK[t]*S[0, -1, 0][t] - k1a*
+							RAFK[t]*S[0, 0, 0][t] - k1a*RAFK[t]*S[0, 1, 0][t]
+							 - k1a*RAFK[t]*S[0, 2, 0][t] - k1a*RAFK[t]*S[1,
+							 -1, 0][t] - k1a*RAFK[t]*S[1, 0, 0][t] -
+							 k1a*RAFK[t]*S[1, 1, 0][t] - k1a*RAFK[t]*S[1, 2,
+							 0][t] - k1a*RAFK[t]*S[2, -1, 0][t] - k1a*
+							RAFK[t]*S[2, 0, 0][t] - k1a*RAFK[t]*S[2, 1, 0][t]
+							 - k1a*RAFK[t]*S[2, 2, 0][t] + d1a*S_RAFK[-1,
+							 -1, 0][t] + k1*S_RAFK[-1, -1, 0][t] +
+							 d1a*S_RAFK[-1, 0, 0][t] + k1*S_RAFK[-1, 0,
+							 0][t] + d1a*S_RAFK[-1, 1, 0][t] + k1*S_RAFK[
+							-1, 1, 0][t] + d1a*S_RAFK[-1, 2, 0][t] +
+							 k1*S_RAFK[-1, 2, 0][t] + d1a*S_RAFK[0, -1,
+							 0][t] + k1*S_RAFK[0, -1, 0][t] + d1a*S_RAFK[
+							0, 0, 0][t] + k1*S_RAFK[0, 0, 0][t] +
+							 d1a*S_RAFK[0, 1, 0][t] + k1*S_RAFK[0, 1, 0][
+							t] + d1a*S_RAFK[0, 2, 0][t] + k1*S_RAFK[0, 2,
+							 0][t] + d1a*S_RAFK[1, -1, 0][t] + k1*S_RAFK[
+							1, -1, 0][t] + d1a*S_RAFK[1, 0, 0][t] +
+							 k1*S_RAFK[1, 0, 0][t] + d1a*S_RAFK[1, 1, 0][
+							t] + k1*S_RAFK[1, 1, 0][t] + d1a*S_RAFK[1, 2,
+							 0][t] + k1*S_RAFK[1, 2, 0][t] + d1a*S_RAFK[
+							2, -1, 0][t] + k1*S_RAFK[2, -1, 0][t] +
+							 d1a*S_RAFK[2, 0, 0][t] + k1*S_RAFK[2, 0, 0][
+							t] + d1a*S_RAFK[2, 1, 0][t] + k1*S_RAFK[2, 1,
+							 0][t] + d1a*S_RAFK[2, 2, 0][t] + k1*S_RAFK[
+							2, 2, 0][t]</td>
+					</tr>
+					<tr>
+						<td>RAFP</td>
+						<td>0.3</td>
+						<td>RAFP'[t] == -(a2*RAFP[t]*K[3, 1][t]) + d2*K_RAFP[3,
+							 1][t] + k2*K_RAFP[3, 1][t]</td>
+					</tr>
+					<tr>
+						<td>K[1, 0]</td>
+						<td>0.4</td>
+						<td>(K[1, 0])'[t] == -(a7*K[1, 0][t]*K[2, 2][t]) +
+							 d7*K_K[1, 0, 2, 2][t] + k8*K_MAPKP[1, 1][t]
+							 - kon*K[1, 0][t]*S[-1, -1, -1][t] - kon*K[1,
+							 0][t]*S[-1, -1, 0][t] - kon*K[1, 0][t]*S[-1,
+							 -1, 1][t] - kon*K[1, 0][t]*S[-1, 0, -1][t]
+							 - kon*K[1, 0][t]*S[-1, 0, 0][t] - kon*K[1,
+							 0][t]*S[-1, 0, 1][t] - kon*K[1, 0][t]*S[-1,
+							 1, -1][t] - kon*K[1, 0][t]*S[-1, 1, 0][t]
+							 - kon*K[1, 0][t]*S[-1, 1, 1][t] - kon*K[1,
+							 0][t]*S[-1, 2, -1][t] - kon*K[1, 0][t]*S[-1,
+							 2, 0][t] - kon*K[1, 0][t]*S[-1, 2, 1][t]
+							 + koff*S[0, -1, -1][t] + koff*S[0, -1,
+							 0][t] + koff*S[0, -1, 1][t] + koff*S[0,
+							 0, -1][t] + koff*S[0, 0, 0][t] + koff*
+							S[0, 0, 1][t] + koff*S[0, 1, -1][t] +
+							 koff*S[0, 1, 0][t] + koff*S[0, 1, 1][t]
+							 + koff*S[0, 2, -1][t] + koff*S[0, 2, 0]
+							[t] + koff*S[0, 2, 1][t]</td>
+					</tr>
+					<tr>
+						<td>K[1, 1]</td>
+						<td>0</td>
+						<td>(K[1, 1])'[t] == -(a8*MAPKP[t]*K[1, 1][t]) -
+							 a9*K[1, 1][t]*K[2, 2][t] + k7*K_K[1, 0, 2,
+							 2][t] + d9*K_K[1, 1, 2, 2][t] + d8*
+							K_MAPKP[1, 1][t] + k10*K_MAPKP[1, 2][t] - kpon*K[
+							1, 1][t]*S[-1, -1, -1][t] - kpon*K[1, 1][t]*S[-1,
+							 -1, 0][t] - kpon*K[1, 1][t]*S[-1, -1, 1][t]
+							 - kpon*K[1, 1][t]*S[-1, 0, -1][t] - kpon*K[
+							1, 1][t]*S[-1, 0, 0][t] - kpon*K[1, 1][t]*S[-1,
+							 0, 1][t] - kpon*K[1, 1][t]*S[-1, 1, -1][t]
+							 - kpon*K[1, 1][t]*S[-1, 1, 0][t] - kpon*K[1,
+							 1][t]*S[-1, 1, 1][t] - kpon*K[1, 1][t]*S[-1,
+							 2, -1][t] - kpon*K[1, 1][t]*S[-1, 2, 0][t]
+							 - kpon*K[1, 1][t]*S[-1, 2, 1][t] + kpoff*S[
+							1, -1, -1][t] + kpoff*S[1, -1, 0][t] +
+							 kpoff*S[1, -1, 1][t] + kpoff*S[1, 0, -1][t]
+							 + kpoff*S[1, 0, 0][t] + kpoff*S[1, 0,
+							 1][t] + kpoff*S[1, 1, -1][t] + kpoff*S[1,
+							 1, 0][t] + kpoff*S[1, 1, 1][t] + kpoff*
+							S[1, 2, -1][t] + kpoff*S[1, 2, 0][t] +
+							 kpoff*S[1, 2, 1][t]</td>
+					</tr>
+					<tr>
+						<td>K[1, 2]</td>
+						<td>0</td>
+						<td>(K[1, 2])'[t] == -(a10*MAPKP[t]*K[1, 2][t]) +
+							 k9*K_K[1, 1, 2, 2][t] + d10*K_MAPKP[1, 2][t]
+							 - kpon*K[1, 2][t]*S[-1, -1, -1][t] - kpon*K[
+							1, 2][t]*S[-1, -1, 0][t] - kpon*K[1, 2][t]*S[-1,
+							 -1, 1][t] - kpon*K[1, 2][t]*S[-1, 0, -1][t]
+							 - kpon*K[1, 2][t]*S[-1, 0, 0][t] - kpon*K[1,
+							 2][t]*S[-1, 0, 1][t] - kpon*K[1, 2][t]*S[-1,
+							 1, -1][t] - kpon*K[1, 2][t]*S[-1, 1, 0][t]
+							 - kpon*K[1, 2][t]*S[-1, 1, 1][t] - kpon*K[1,
+							 2][t]*S[-1, 2, -1][t] - kpon*K[1, 2][t]*S[-1,
+							 2, 0][t] - kpon*K[1, 2][t]*S[-1, 2, 1][t]
+							 + kpoff*S[2, -1, -1][t] + kpoff*S[2, -1,
+							 0][t] + kpoff*S[2, -1, 1][t] + kpoff*S[2,
+							 0, -1][t] + kpoff*S[2, 0, 0][t] +
+							 kpoff*S[2, 0, 1][t] + kpoff*S[2, 1, -1][t]
+							 + kpoff*S[2, 1, 0][t] + kpoff*S[2, 1,
+							 1][t] + kpoff*S[2, 2, -1][t] + kpoff*S[2,
+							 2, 0][t] + kpoff*S[2, 2, 1][t]</td>
+					</tr>
+					<tr>
+						<td>K[2, 0]</td>
+						<td>0.2</td>
+						<td>(K[2, 0])'[t] == -(a3*K[2, 0][t]*K[3, 1][t]) +
+							 d3*K_K[2, 0, 3, 1][t] + k4*K_MEKP[2, 1][t]
+							 - kon*K[2, 0][t]*S[-1, -1, -1][t] - kon*K[2,
+							 0][t]*S[-1, -1, 0][t] - kon*K[2, 0][t]*S[-1,
+							 -1, 1][t] + koff*S[-1, 0, -1][t] +
+							 koff*S[-1, 0, 0][t] + koff*S[-1, 0, 1][t]
+							 - kon*K[2, 0][t]*S[0, -1, -1][t] - kon*K[2,
+							 0][t]*S[0, -1, 0][t] - kon*K[2, 0][t]*S[0, -
+							1, 1][t] + koff*S[0, 0, -1][t] + koff*S[0,
+							 0, 0][t] + koff*S[0, 0, 1][t] - kon*K[
+							2, 0][t]*S[1, -1, -1][t] - kon*K[2, 0][t]*S[1,
+							 -1, 0][t] - kon*K[2, 0][t]*S[1, -1, 1][t]
+							 + koff*S[1, 0, -1][t] + koff*S[1, 0, 0]
+							[t] + koff*S[1, 0, 1][t] - kon*K[2, 0][t]*S[
+							2, -1, -1][t] - kon*K[2, 0][t]*S[2, -1, 0][t]
+							 - kon*K[2, 0][t]*S[2, -1, 1][t] + koff*S[2,
+							 0, -1][t] + koff*S[2, 0, 0][t] + koff*
+							S[2, 0, 1][t]</td>
+					</tr>
+					<tr>
+						<td>K[2, 1]</td>
+						<td>0</td>
+						<td>(K[2, 1])'[t] == -(a4*MEKP[t]*K[2, 1][t]) -
+							 a5*K[2, 1][t]*K[3, 1][t] + k3*K_K[2, 0, 3,
+							 1][t] + d5*K_K[2, 1, 3, 1][t] + d4*
+							K_MEKP[2, 1][t] + k6*K_MEKP[2, 2][t] - kpon*K[2,
+							 1][t]*S[-1, -1, -1][t] - kpon*K[2, 1][t]*S[-1,
+							 -1, 0][t] - kpon*K[2, 1][t]*S[-1, -1, 1][t]
+							 + kpoff*S[-1, 1, -1][t] + kpoff*S[-1, 1,
+							 0][t] + kpoff*S[-1, 1, 1][t] - kpon*K[2,
+							 1][t]*S[0, -1, -1][t] - kpon*K[2, 1][t]*S[0,
+							 -1, 0][t] - kpon*K[2, 1][t]*S[0, -1, 1][t]
+							 + kpoff*S[0, 1, -1][t] + kpoff*S[0, 1,
+							 0][t] + kpoff*S[0, 1, 1][t] - kpon*K[2,
+							 1][t]*S[1, -1, -1][t] - kpon*K[2, 1][t]*S[1,
+							 -1, 0][t] - kpon*K[2, 1][t]*S[1, -1, 1][t]
+							 + kpoff*S[1, 1, -1][t] + kpoff*S[1, 1,
+							 0][t] + kpoff*S[1, 1, 1][t] - kpon*K[2,
+							 1][t]*S[2, -1, -1][t] - kpon*K[2, 1][t]*S[2,
+							 -1, 0][t] - kpon*K[2, 1][t]*S[2, -1, 1][t]
+							 + kpoff*S[2, 1, -1][t] + kpoff*S[2, 1,
+							 0][t] + kpoff*S[2, 1, 1][t]</td>
+					</tr>
+					<tr>
+						<td>K[2, 2]</td>
+						<td>0</td>
+						<td>(K[2, 2])'[t] == -(a6*MEKP[t]*K[2, 2][t]) -
+							 a7*K[1, 0][t]*K[2, 2][t] - a9*K[1, 1][t]*K[2,
+							 2][t] + d7*K_K[1, 0, 2, 2][t] + k7*K_K[
+							1, 0, 2, 2][t] + d9*K_K[1, 1, 2, 2][t]
+							 + k9*K_K[1, 1, 2, 2][t] + k5*K_K[2, 1,
+							 3, 1][t] + d6*K_MEKP[2, 2][t] - kpon*K[2,
+							 2][t]*S[-1, -1, -1][t] - kpon*K[2, 2][t]*S[-1,
+							 -1, 0][t] - kpon*K[2, 2][t]*S[-1, -1, 1][t]
+							 + kpoff*S[-1, 2, -1][t] + kpoff*S[-1, 2,
+							 0][t] + kpoff*S[-1, 2, 1][t] - kpon*K[2,
+							 2][t]*S[0, -1, -1][t] - kpon*K[2, 2][t]*S[0,
+							 -1, 0][t] - kpon*K[2, 2][t]*S[0, -1, 1][t]
+							 + kpoff*S[0, 2, -1][t] + kpoff*S[0, 2,
+							 0][t] + kpoff*S[0, 2, 1][t] - kpon*K[2,
+							 2][t]*S[1, -1, -1][t] - kpon*K[2, 2][t]*S[1,
+							 -1, 0][t] - kpon*K[2, 2][t]*S[1, -1, 1][t]
+							 + kpoff*S[1, 2, -1][t] + kpoff*S[1, 2,
+							 0][t] + kpoff*S[1, 2, 1][t] - kpon*K[2,
+							 2][t]*S[2, -1, -1][t] - kpon*K[2, 2][t]*S[2,
+							 -1, 0][t] - kpon*K[2, 2][t]*S[2, -1, 1][t]
+							 + kpoff*S[2, 2, -1][t] + kpoff*S[2, 2,
+							 0][t] + kpoff*S[2, 2, 1][t]</td>
+					</tr>
+					<tr>
+						<td>K[3, 0]</td>
+						<td>0.3</td>
+						<td>(K[3, 0])'[t] == -(a1*RAFK[t]*K[3, 0][t]) +
+							 d1*K_RAFK[3, 0][t] + k2*K_RAFP[3, 1][t] -
+							 kon*K[3, 0][t]*S[-1, -1, -1][t] + koff*S[-1,
+							 -1, 0][t] - kon*K[3, 0][t]*S[-1, 0, -1][t]
+							 + koff*S[-1, 0, 0][t] - kon*K[3, 0][t]*S[-1,
+							 1, -1][t] + koff*S[-1, 1, 0][t] - kon*
+							K[3, 0][t]*S[-1, 2, -1][t] + koff*S[-1, 2, 0]
+							[t] - kon*K[3, 0][t]*S[0, -1, -1][t] + koff*
+							S[0, -1, 0][t] - kon*K[3, 0][t]*S[0, 0, -1][
+							t] + koff*S[0, 0, 0][t] - kon*K[3, 0][t]*S[0,
+							 1, -1][t] + koff*S[0, 1, 0][t] - kon*K[
+							3, 0][t]*S[0, 2, -1][t] + koff*S[0, 2, 0][t]
+							 - kon*K[3, 0][t]*S[1, -1, -1][t] + koff*S[1,
+							 -1, 0][t] - kon*K[3, 0][t]*S[1, 0, -1][t]
+							 + koff*S[1, 0, 0][t] - kon*K[3, 0][t]*S[1,
+							 1, -1][t] + koff*S[1, 1, 0][t] - kon*K[
+							3, 0][t]*S[1, 2, -1][t] + koff*S[1, 2, 0][t]
+							 - kon*K[3, 0][t]*S[2, -1, -1][t] + koff*S[2,
+							 -1, 0][t] - kon*K[3, 0][t]*S[2, 0, -1][t]
+							 + koff*S[2, 0, 0][t] - kon*K[3, 0][t]*S[2,
+							 1, -1][t] + koff*S[2, 1, 0][t] - kon*K[
+							3, 0][t]*S[2, 2, -1][t] + koff*S[2, 2, 0][t]</td>
+					</tr>
+					<tr>
+						<td>K[3, 1]</td>
+						<td>0</td>
+						<td>(K[3, 1])'[t] == -(a2*RAFP[t]*K[3, 1][t]) -
+							 a3*K[2, 0][t]*K[3, 1][t] - a5*K[2, 1][t]*K[3,
+							 1][t] + d3*K_K[2, 0, 3, 1][t] + k3*K_K[
+							2, 0, 3, 1][t] + d5*K_K[2, 1, 3, 1][t]
+							 + k5*K_K[2, 1, 3, 1][t] + k1*K_RAFK[3,
+							 0][t] + d2*K_RAFP[3, 1][t] - kpon*K[3, 1][t]
+							*S[-1, -1, -1][t] + kpoff*S[-1, -1, 1][t] -
+							 kpon*K[3, 1][t]*S[-1, 0, -1][t] + kpoff*S[-1,
+							 0, 1][t] - kpon*K[3, 1][t]*S[-1, 1, -1][t]
+							 + kpoff*S[-1, 1, 1][t] - kpon*K[3, 1][t]*S[-
+							1, 2, -1][t] + kpoff*S[-1, 2, 1][t] -
+							 kpon*K[3, 1][t]*S[0, -1, -1][t] + kpoff*S[0,
+							 -1, 1][t] - kpon*K[3, 1][t]*S[0, 0, -1][t]
+							 + kpoff*S[0, 0, 1][t] - kpon*K[3, 1][t]*S[0,
+							 1, -1][t] + kpoff*S[0, 1, 1][t] - kpon*
+							K[3, 1][t]*S[0, 2, -1][t] + kpoff*S[0, 2, 1][
+							t] - kpon*K[3, 1][t]*S[1, -1, -1][t] + kpoff*
+							S[1, -1, 1][t] - kpon*K[3, 1][t]*S[1, 0, -1][
+							t] + kpoff*S[1, 0, 1][t] - kpon*K[3, 1][t]*S[
+							1, 1, -1][t] + kpoff*S[1, 1, 1][t] -
+							 kpon*K[3, 1][t]*S[1, 2, -1][t] + kpoff*S[1,
+							 2, 1][t] - kpon*K[3, 1][t]*S[2, -1, -1][t]
+							 + kpoff*S[2, -1, 1][t] - kpon*K[3, 1][t]*S[
+							2, 0, -1][t] + kpoff*S[2, 0, 1][t] -
+							 kpon*K[3, 1][t]*S[2, 1, -1][t] + kpoff*S[2,
+							 1, 1][t] - kpon*K[3, 1][t]*S[2, 2, -1][t]
+							 + kpoff*S[2, 2, 1][t]</td>
+					</tr>
+					<tr>
+						<td>K_K[1, 0, 2, 2]</td>
+						<td>0</td>
+						<td>(K_K[1, 0, 2, 2])'[t] == a7*K[1, 0][t]*K[2,
+							 2][t] - d7*K_K[1, 0, 2, 2][t] - k7*K_K[
+							1, 0, 2, 2][t]</td>
+					</tr>
+					<tr>
+						<td>K_K[1, 1, 2, 2]</td>
+						<td>0</td>
+						<td>(K_K[1, 1, 2, 2])'[t] == a9*K[1, 1][t]*K[2,
+							 2][t] - d9*K_K[1, 1, 2, 2][t] - k9*K_K[
+							1, 1, 2, 2][t]</td>
+					</tr>
+					<tr>
+						<td>K_K[2, 0, 3, 1]</td>
+						<td>0</td>
+						<td>(K_K[2, 0, 3, 1])'[t] == a3*K[2, 0][t]*K[3,
+							 1][t] - d3*K_K[2, 0, 3, 1][t] - k3*K_K[
+							2, 0, 3, 1][t]</td>
+					</tr>
+					<tr>
+						<td>K_K[2, 1, 3, 1]</td>
+						<td>0</td>
+						<td>(K_K[2, 1, 3, 1])'[t] == a5*K[2, 1][t]*K[3,
+							 1][t] - d5*K_K[2, 1, 3, 1][t] - k5*K_K[
+							2, 1, 3, 1][t]</td>
+					</tr>
+					<tr>
+						<td>K_MAPKP[1, 1]</td>
+						<td>0</td>
+						<td>(K_MAPKP[1, 1])'[t] == a8*MAPKP[t]*K[1, 1][t] -
+							 d8*K_MAPKP[1, 1][t] - k8*K_MAPKP[1, 1][t]</td>
+					</tr>
+					<tr>
+						<td>K_MAPKP[1, 2]</td>
+						<td>0</td>
+						<td>(K_MAPKP[1, 2])'[t] == a10*MAPKP[t]*K[1, 2][t] -
+							 d10*K_MAPKP[1, 2][t] - k10*K_MAPKP[1, 2][t]</td>
+					</tr>
+					<tr>
+						<td>K_MEKP[2, 1]</td>
+						<td>0</td>
+						<td>(K_MEKP[2, 1])'[t] == a4*MEKP[t]*K[2, 1][t] -
+							 d4*K_MEKP[2, 1][t] - k4*K_MEKP[2, 1][t]</td>
+					</tr>
+					<tr>
+						<td>K_MEKP[2, 2]</td>
+						<td>0</td>
+						<td>(K_MEKP[2, 2])'[t] == a6*MEKP[t]*K[2, 2][t] -
+							 d6*K_MEKP[2, 2][t] - k6*K_MEKP[2, 2][t]</td>
+					</tr>
+					<tr>
+						<td>K_RAFK[3, 0]</td>
+						<td>0</td>
+						<td>(K_RAFK[3, 0])'[t] == a1*RAFK[t]*K[3, 0][t] -
+							 d1*K_RAFK[3, 0][t] - k1*K_RAFK[3, 0][t]</td>
+					</tr>
+					<tr>
+						<td>K_RAFP[3, 1]</td>
+						<td>0</td>
+						<td>(K_RAFP[3, 1])'[t] == a2*RAFP[t]*K[3, 1][t] -
+							 d2*K_RAFP[3, 1][t] - k2*K_RAFP[3, 1][t]</td>
+					</tr>
+					<tr>
+						<td>S[-1, -1, -1]</td>
+						<td>0.1</td>
+						<td>(S[-1, -1, -1])'[t] == -(kon*K[1, 0][t]*S[-1,
+							 -1, -1][t]) - kpon*K[1, 1][t]*S[-1, -1, -1][
+							t] - kpon*K[1, 2][t]*S[-1, -1, -1][t] - kon*
+							K[2, 0][t]*S[-1, -1, -1][t] - kpon*K[2, 1][t]*S[-
+							1, -1, -1][t] - kpon*K[2, 2][t]*S[-1, -1, -1]
+							[t] - kon*K[3, 0][t]*S[-1, -1, -1][t] - kpon*
+							K[3, 1][t]*S[-1, -1, -1][t] + koff*S[-1, -1,
+							 0][t] + kpoff*S[-1, -1, 1][t] + koff*S[-1,
+							 0, -1][t] + kpoff*S[-1, 1, -1][t] +
+							 kpoff*S[-1, 2, -1][t] + koff*S[0, -1, -1][t]
+							 + kpoff*S[1, -1, -1][t] + kpoff*S[2, -1,
+							 -1][t]</td>
+					</tr>
+					<tr>
+						<td>S[-1, -1, 0]</td>
+						<td>0</td>
+						<td>(S[-1, -1, 0])'[t] == kon*K[3, 0][t]*S[-1, -1,
+							 -1][t] - koff*S[-1, -1, 0][t] - k1a*RAFK[t]*
+							S[-1, -1, 0][t] - kon*K[1, 0][t]*S[-1, -1, 0]
+							[t] - kpon*K[1, 1][t]*S[-1, -1, 0][t] - kpon*
+							K[1, 2][t]*S[-1, -1, 0][t] - kon*K[2, 0][t]*S[-1,
+							 -1, 0][t] - kpon*K[2, 1][t]*S[-1, -1, 0][t]
+							 - kpon*K[2, 2][t]*S[-1, -1, 0][t] + koff*S[-
+							1, 0, 0][t] + kpoff*S[-1, 1, 0][t] +
+							 kpoff*S[-1, 2, 0][t] + koff*S[0, -1, 0][t]
+							 + kpoff*S[1, -1, 0][t] + kpoff*S[2, -1,
+							 0][t] + d1a*S_RAFK[-1, -1, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[-1, -1, 1]</td>
+						<td>0</td>
+						<td>(S[-1, -1, 1])'[t] == kpon*K[3, 1][t]*S[-1, -
+							1, -1][t] - kpoff*S[-1, -1, 1][t] - kon*K[1,
+							 0][t]*S[-1, -1, 1][t] - kpon*K[1, 1][t]*S[-1,
+							 -1, 1][t] - kpon*K[1, 2][t]*S[-1, -1, 1][t]
+							 - kon*K[2, 0][t]*S[-1, -1, 1][t] - kpon*K[2,
+							 1][t]*S[-1, -1, 1][t] - kpon*K[2, 2][t]*S[-1,
+							 -1, 1][t] + koff*S[-1, 0, 1][t] +
+							 kpoff*S[-1, 1, 1][t] + kpoff*S[-1, 2, 1][t]
+							 + koff*S[0, -1, 1][t] + kpoff*S[1, -1,
+							 1][t] + kpoff*S[2, -1, 1][t] + k1*S_RAFK[-1,
+							 -1, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[-1, 0, -1]</td>
+						<td>0</td>
+						<td>(S[-1, 0, -1])'[t] == kon*K[2, 0][t]*S[-1, -1,
+							 -1][t] - koff*S[-1, 0, -1][t] - kon*K[1,
+							 0][t]*S[-1, 0, -1][t] - kpon*K[1, 1][t]*S[-1,
+							 0, -1][t] - kpon*K[1, 2][t]*S[-1, 0, -1][t]
+							 - kon*K[3, 0][t]*S[-1, 0, -1][t] - kpon*K[3,
+							 1][t]*S[-1, 0, -1][t] + koff*S[-1, 0, 0][t]
+							 + kpoff*S[-1, 0, 1][t] + koff*S[0, 0, -
+							1][t] + kpoff*S[1, 0, -1][t] + kpoff*S[2, 0,
+							 -1][t]</td>
+					</tr>
+					<tr>
+						<td>S[-1, 0, 0]</td>
+						<td>0</td>
+						<td>(S[-1, 0, 0])'[t] == kon*K[2, 0][t]*S[-1, -1,
+							 0][t] + kon*K[3, 0][t]*S[-1, 0, -1][t] -
+							 2*koff*S[-1, 0, 0][t] - k1a*RAFK[t]*S[-1, 0,
+							 0][t] - kon*K[1, 0][t]*S[-1, 0, 0][t] -
+							 kpon*K[1, 1][t]*S[-1, 0, 0][t] - kpon*K[1,
+							 2][t]*S[-1, 0, 0][t] + koff*S[0, 0, 0][t]
+							 + kpoff*S[1, 0, 0][t] + kpoff*S[2, 0,
+							 0][t] + d1a*S_RAFK[-1, 0, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[-1, 0, 1]</td>
+						<td>0</td>
+						<td>(S[-1, 0, 1])'[t] == kon*K[2, 0][t]*S[-1, -1,
+							 1][t] + kpon*K[3, 1][t]*S[-1, 0, -1][t] -
+							 k3*S[-1, 0, 1][t] - koff*S[-1, 0, 1][t]
+							 - kpoff*S[-1, 0, 1][t] - kon*K[1, 0][t]*S[-
+							1, 0, 1][t] - kpon*K[1, 1][t]*S[-1, 0, 1][t]
+							 - kpon*K[1, 2][t]*S[-1, 0, 1][t] + koff*S[0,
+							 0, 1][t] + kpoff*S[1, 0, 1][t] + kpoff*
+							S[2, 0, 1][t] + k1*S_RAFK[-1, 0, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[-1, 1, -1]</td>
+						<td>0</td>
+						<td>(S[-1, 1, -1])'[t] == kpon*K[2, 1][t]*S[-1, -
+							1, -1][t] - kpoff*S[-1, 1, -1][t] - kon*K[1,
+							 0][t]*S[-1, 1, -1][t] - kpon*K[1, 1][t]*S[-1,
+							 1, -1][t] - kpon*K[1, 2][t]*S[-1, 1, -1][t]
+							 - kon*K[3, 0][t]*S[-1, 1, -1][t] - kpon*K[3,
+							 1][t]*S[-1, 1, -1][t] + koff*S[-1, 1, 0][t]
+							 + kpoff*S[-1, 1, 1][t] + koff*S[0, 1, -
+							1][t] + kpoff*S[1, 1, -1][t] + kpoff*S[2, 1,
+							 -1][t]</td>
+					</tr>
+					<tr>
+						<td>S[-1, 1, 0]</td>
+						<td>0</td>
+						<td>(S[-1, 1, 0])'[t] == kpon*K[2, 1][t]*S[-1, -1,
+							 0][t] + kon*K[3, 0][t]*S[-1, 1, -1][t] -
+							 koff*S[-1, 1, 0][t] - kpoff*S[-1, 1, 0][t]
+							 - k1a*RAFK[t]*S[-1, 1, 0][t] - kon*K[1, 0][
+							t]*S[-1, 1, 0][t] - kpon*K[1, 1][t]*S[-1, 1,
+							 0][t] - kpon*K[1, 2][t]*S[-1, 1, 0][t] +
+							 koff*S[0, 1, 0][t] + kpoff*S[1, 1, 0][t]
+							 + kpoff*S[2, 1, 0][t] + d1a*S_RAFK[-1, 1,
+							 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[-1, 1, 1]</td>
+						<td>0</td>
+						<td>(S[-1, 1, 1])'[t] == kpon*K[2, 1][t]*S[-1, -1,
+							 1][t] + k3*S[-1, 0, 1][t] + kpon*K[3,
+							 1][t]*S[-1, 1, -1][t] - k5a*S[-1, 1, 1][t]
+							 - 2*kpoff*S[-1, 1, 1][t] - kon*K[1, 0][t]*S[
+							-1, 1, 1][t] - kpon*K[1, 1][t]*S[-1, 1, 1][t]
+							 - kpon*K[1, 2][t]*S[-1, 1, 1][t] + koff*S[0,
+							 1, 1][t] + kpoff*S[1, 1, 1][t] + kpoff*
+							S[2, 1, 1][t] + k1*S_RAFK[-1, 1, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[-1, 2, -1]</td>
+						<td>0</td>
+						<td>(S[-1, 2, -1])'[t] == kpon*K[2, 2][t]*S[-1, -
+							1, -1][t] - kpoff*S[-1, 2, -1][t] - kon*K[1,
+							 0][t]*S[-1, 2, -1][t] - kpon*K[1, 1][t]*S[-1,
+							 2, -1][t] - kpon*K[1, 2][t]*S[-1, 2, -1][t]
+							 - kon*K[3, 0][t]*S[-1, 2, -1][t] - kpon*K[3,
+							 1][t]*S[-1, 2, -1][t] + koff*S[-1, 2, 0][t]
+							 + kpoff*S[-1, 2, 1][t] + koff*S[0, 2, -
+							1][t] + kpoff*S[1, 2, -1][t] + kpoff*S[2, 2,
+							 -1][t]</td>
+					</tr>
+					<tr>
+						<td>S[-1, 2, 0]</td>
+						<td>0</td>
+						<td>(S[-1, 2, 0])'[t] == kpon*K[2, 2][t]*S[-1, -1,
+							 0][t] + kon*K[3, 0][t]*S[-1, 2, -1][t] -
+							 koff*S[-1, 2, 0][t] - kpoff*S[-1, 2, 0][t]
+							 - k1a*RAFK[t]*S[-1, 2, 0][t] - kon*K[1, 0][
+							t]*S[-1, 2, 0][t] - kpon*K[1, 1][t]*S[-1, 2,
+							 0][t] - kpon*K[1, 2][t]*S[-1, 2, 0][t] +
+							 koff*S[0, 2, 0][t] + kpoff*S[1, 2, 0][t]
+							 + kpoff*S[2, 2, 0][t] + d1a*S_RAFK[-1, 2,
+							 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[-1, 2, 1]</td>
+						<td>0</td>
+						<td>(S[-1, 2, 1])'[t] == kpon*K[2, 2][t]*S[-1, -1,
+							 1][t] + k5a*S[-1, 1, 1][t] + kpon*K[3,
+							 1][t]*S[-1, 2, -1][t] - 2*kpoff*S[-1, 2, 1][
+							t] - kon*K[1, 0][t]*S[-1, 2, 1][t] - kpon*K[
+							1, 1][t]*S[-1, 2, 1][t] - kpon*K[1, 2][t]*S[-1,
+							 2, 1][t] + koff*S[0, 2, 1][t] + kpoff*
+							S[1, 2, 1][t] + kpoff*S[2, 2, 1][t] +
+							 k1*S_RAFK[-1, 2, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[0, -1, -1]</td>
+						<td>0</td>
+						<td>(S[0, -1, -1])'[t] == kon*K[1, 0][t]*S[-1, -1,
+							 -1][t] - koff*S[0, -1, -1][t] - kon*K[2,
+							 0][t]*S[0, -1, -1][t] - kpon*K[2, 1][t]*S[0,
+							 -1, -1][t] - kpon*K[2, 2][t]*S[0, -1, -1][t]
+							 - kon*K[3, 0][t]*S[0, -1, -1][t] - kpon*K[3,
+							 1][t]*S[0, -1, -1][t] + koff*S[0, -1, 0][t]
+							 + kpoff*S[0, -1, 1][t] + koff*S[0, 0, -
+							1][t] + kpoff*S[0, 1, -1][t] + kpoff*S[0, 2,
+							 -1][t]</td>
+					</tr>
+					<tr>
+						<td>S[0, -1, 0]</td>
+						<td>0</td>
+						<td>(S[0, -1, 0])'[t] == kon*K[1, 0][t]*S[-1, -1,
+							 0][t] + kon*K[3, 0][t]*S[0, -1, -1][t] -
+							 2*koff*S[0, -1, 0][t] - k1a*RAFK[t]*S[0, -1,
+							 0][t] - kon*K[2, 0][t]*S[0, -1, 0][t] -
+							 kpon*K[2, 1][t]*S[0, -1, 0][t] - kpon*K[2,
+							 2][t]*S[0, -1, 0][t] + koff*S[0, 0, 0][t]
+							 + kpoff*S[0, 1, 0][t] + kpoff*S[0, 2,
+							 0][t] + d1a*S_RAFK[0, -1, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[0, -1, 1]</td>
+						<td>0</td>
+						<td>(S[0, -1, 1])'[t] == kon*K[1, 0][t]*S[-1, -1,
+							 1][t] + kpon*K[3, 1][t]*S[0, -1, -1][t] -
+							 koff*S[0, -1, 1][t] - kpoff*S[0, -1, 1][t]
+							 - kon*K[2, 0][t]*S[0, -1, 1][t] - kpon*K[2,
+							 1][t]*S[0, -1, 1][t] - kpon*K[2, 2][t]*S[0,
+							 -1, 1][t] + koff*S[0, 0, 1][t] + kpoff*
+							S[0, 1, 1][t] + kpoff*S[0, 2, 1][t] +
+							 k1*S_RAFK[0, -1, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[0, 0, -1]</td>
+						<td>0</td>
+						<td>(S[0, 0, -1])'[t] == kon*K[1, 0][t]*S[-1, 0,
+							 -1][t] + kon*K[2, 0][t]*S[0, -1, -1][t] -
+							 2*koff*S[0, 0, -1][t] - kon*K[3, 0][t]*S[0,
+							 0, -1][t] - kpon*K[3, 1][t]*S[0, 0, -1][t]
+							 + koff*S[0, 0, 0][t] + kpoff*S[0, 0, 1]
+							[t]</td>
+					</tr>
+					<tr>
+						<td>S[0, 0, 0]</td>
+						<td>0</td>
+						<td>(S[0, 0, 0])'[t] == kon*K[1, 0][t]*S[-1, 0,
+							 0][t] + kon*K[2, 0][t]*S[0, -1, 0][t] +
+							 kon*K[3, 0][t]*S[0, 0, -1][t] - 3*koff*S[0,
+							 0, 0][t] - k1a*RAFK[t]*S[0, 0, 0][t] +
+							 d1a*S_RAFK[0, 0, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[0, 0, 1]</td>
+						<td>0</td>
+						<td>(S[0, 0, 1])'[t] == kon*K[1, 0][t]*S[-1, 0,
+							 1][t] + kon*K[2, 0][t]*S[0, -1, 1][t] +
+							 kpon*K[3, 1][t]*S[0, 0, -1][t] - k3*S[0, 0,
+							 1][t] - 2*koff*S[0, 0, 1][t] - kpoff*S[0,
+							 0, 1][t] + k1*S_RAFK[0, 0, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[0, 1, -1]</td>
+						<td>0</td>
+						<td>(S[0, 1, -1])'[t] == kon*K[1, 0][t]*S[-1, 1,
+							 -1][t] + kpon*K[2, 1][t]*S[0, -1, -1][t] -
+							 koff*S[0, 1, -1][t] - kpoff*S[0, 1, -1][t]
+							 - kon*K[3, 0][t]*S[0, 1, -1][t] - kpon*K[3,
+							 1][t]*S[0, 1, -1][t] + koff*S[0, 1, 0][t]
+							 + kpoff*S[0, 1, 1][t]</td>
+					</tr>
+					<tr>
+						<td>S[0, 1, 0]</td>
+						<td>0</td>
+						<td>(S[0, 1, 0])'[t] == kon*K[1, 0][t]*S[-1, 1,
+							 0][t] + kpon*K[2, 1][t]*S[0, -1, 0][t] +
+							 kon*K[3, 0][t]*S[0, 1, -1][t] - 2*koff*S[0,
+							 1, 0][t] - kpoff*S[0, 1, 0][t] - k1a*
+							RAFK[t]*S[0, 1, 0][t] + d1a*S_RAFK[0, 1, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[0, 1, 1]</td>
+						<td>0</td>
+						<td>(S[0, 1, 1])'[t] == kon*K[1, 0][t]*S[-1, 1,
+							 1][t] + kpon*K[2, 1][t]*S[0, -1, 1][t] +
+							 k3*S[0, 0, 1][t] + kpon*K[3, 1][t]*S[0, 1,
+							 -1][t] - k5a*S[0, 1, 1][t] - koff*S[0,
+							 1, 1][t] - 2*kpoff*S[0, 1, 1][t] + k1*
+							S_RAFK[0, 1, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[0, 2, -1]</td>
+						<td>0</td>
+						<td>(S[0, 2, -1])'[t] == kon*K[1, 0][t]*S[-1, 2,
+							 -1][t] + kpon*K[2, 2][t]*S[0, -1, -1][t] -
+							 k7*S[0, 2, -1][t] - koff*S[0, 2, -1][t]
+							 - kpoff*S[0, 2, -1][t] - kon*K[3, 0][t]*S[0,
+							 2, -1][t] - kpon*K[3, 1][t]*S[0, 2, -1][t]
+							 + koff*S[0, 2, 0][t] + kpoff*S[0, 2, 1]
+							[t]</td>
+					</tr>
+					<tr>
+						<td>S[0, 2, 0]</td>
+						<td>0</td>
+						<td>(S[0, 2, 0])'[t] == kon*K[1, 0][t]*S[-1, 2,
+							 0][t] + kpon*K[2, 2][t]*S[0, -1, 0][t] +
+							 kon*K[3, 0][t]*S[0, 2, -1][t] - k7*S[0, 2,
+							 0][t] - 2*koff*S[0, 2, 0][t] - kpoff*S[0,
+							 2, 0][t] - k1a*RAFK[t]*S[0, 2, 0][t] +
+							 d1a*S_RAFK[0, 2, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[0, 2, 1]</td>
+						<td>0</td>
+						<td>(S[0, 2, 1])'[t] == kon*K[1, 0][t]*S[-1, 2,
+							 1][t] + kpon*K[2, 2][t]*S[0, -1, 1][t] +
+							 k5a*S[0, 1, 1][t] + kpon*K[3, 1][t]*S[0, 2,
+							 -1][t] - k7*S[0, 2, 1][t] - koff*S[0,
+							 2, 1][t] - 2*kpoff*S[0, 2, 1][t] + k1*
+							S_RAFK[0, 2, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[1, -1, -1]</td>
+						<td>0</td>
+						<td>(S[1, -1, -1])'[t] == kpon*K[1, 1][t]*S[-1, -
+							1, -1][t] - kpoff*S[1, -1, -1][t] - kon*K[2,
+							 0][t]*S[1, -1, -1][t] - kpon*K[2, 1][t]*S[1,
+							 -1, -1][t] - kpon*K[2, 2][t]*S[1, -1, -1][t]
+							 - kon*K[3, 0][t]*S[1, -1, -1][t] - kpon*K[3,
+							 1][t]*S[1, -1, -1][t] + koff*S[1, -1, 0][t]
+							 + kpoff*S[1, -1, 1][t] + koff*S[1, 0, -
+							1][t] + kpoff*S[1, 1, -1][t] + kpoff*S[1, 2,
+							 -1][t]</td>
+					</tr>
+					<tr>
+						<td>S[1, -1, 0]</td>
+						<td>0</td>
+						<td>(S[1, -1, 0])'[t] == kpon*K[1, 1][t]*S[-1, -1,
+							 0][t] + kon*K[3, 0][t]*S[1, -1, -1][t] -
+							 koff*S[1, -1, 0][t] - kpoff*S[1, -1, 0][t]
+							 - k1a*RAFK[t]*S[1, -1, 0][t] - kon*K[2, 0][
+							t]*S[1, -1, 0][t] - kpon*K[2, 1][t]*S[1, -1,
+							 0][t] - kpon*K[2, 2][t]*S[1, -1, 0][t] +
+							 koff*S[1, 0, 0][t] + kpoff*S[1, 1, 0][t]
+							 + kpoff*S[1, 2, 0][t] + d1a*S_RAFK[1, -1,
+							 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[1, -1, 1]</td>
+						<td>0</td>
+						<td>(S[1, -1, 1])'[t] == kpon*K[1, 1][t]*S[-1, -1,
+							 1][t] + kpon*K[3, 1][t]*S[1, -1, -1][t] -
+							 2*kpoff*S[1, -1, 1][t] - kon*K[2, 0][t]*S[1,
+							 -1, 1][t] - kpon*K[2, 1][t]*S[1, -1, 1][t]
+							 - kpon*K[2, 2][t]*S[1, -1, 1][t] + koff*S[1,
+							 0, 1][t] + kpoff*S[1, 1, 1][t] + kpoff*
+							S[1, 2, 1][t] + k1*S_RAFK[1, -1, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[1, 0, -1]</td>
+						<td>0</td>
+						<td>(S[1, 0, -1])'[t] == kpon*K[1, 1][t]*S[-1, 0,
+							 -1][t] + kon*K[2, 0][t]*S[1, -1, -1][t] -
+							 koff*S[1, 0, -1][t] - kpoff*S[1, 0, -1][t]
+							 - kon*K[3, 0][t]*S[1, 0, -1][t] - kpon*K[3,
+							 1][t]*S[1, 0, -1][t] + koff*S[1, 0, 0][t]
+							 + kpoff*S[1, 0, 1][t]</td>
+					</tr>
+					<tr>
+						<td>S[1, 0, 0]</td>
+						<td>0</td>
+						<td>(S[1, 0, 0])'[t] == kpon*K[1, 1][t]*S[-1, 0,
+							 0][t] + kon*K[2, 0][t]*S[1, -1, 0][t] +
+							 kon*K[3, 0][t]*S[1, 0, -1][t] - 2*koff*S[1,
+							 0, 0][t] - kpoff*S[1, 0, 0][t] - k1a*
+							RAFK[t]*S[1, 0, 0][t] + d1a*S_RAFK[1, 0, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[1, 0, 1]</td>
+						<td>0</td>
+						<td>(S[1, 0, 1])'[t] == kpon*K[1, 1][t]*S[-1, 0,
+							 1][t] + kon*K[2, 0][t]*S[1, -1, 1][t] +
+							 kpon*K[3, 1][t]*S[1, 0, -1][t] - k3*S[1, 0,
+							 1][t] - koff*S[1, 0, 1][t] - 2*kpoff*S[1,
+							 0, 1][t] + k1*S_RAFK[1, 0, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[1, 1, -1]</td>
+						<td>0</td>
+						<td>(S[1, 1, -1])'[t] == kpon*K[1, 1][t]*S[-1, 1,
+							 -1][t] + kpon*K[2, 1][t]*S[1, -1, -1][t] -
+							 2*kpoff*S[1, 1, -1][t] - kon*K[3, 0][t]*S[1,
+							 1, -1][t] - kpon*K[3, 1][t]*S[1, 1, -1][t]
+							 + koff*S[1, 1, 0][t] + kpoff*S[1, 1, 1]
+							[t]</td>
+					</tr>
+					<tr>
+						<td>S[1, 1, 0]</td>
+						<td>0</td>
+						<td>(S[1, 1, 0])'[t] == kpon*K[1, 1][t]*S[-1, 1,
+							 0][t] + kpon*K[2, 1][t]*S[1, -1, 0][t] +
+							 kon*K[3, 0][t]*S[1, 1, -1][t] - koff*S[1, 1,
+							 0][t] - 2*kpoff*S[1, 1, 0][t] - k1a*RAFK[t]*
+							S[1, 1, 0][t] + d1a*S_RAFK[1, 1, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[1, 1, 1]</td>
+						<td>0</td>
+						<td>(S[1, 1, 1])'[t] == kpon*K[1, 1][t]*S[-1, 1,
+							 1][t] + kpon*K[2, 1][t]*S[1, -1, 1][t] +
+							 k3*S[1, 0, 1][t] + kpon*K[3, 1][t]*S[1, 1,
+							 -1][t] - k5a*S[1, 1, 1][t] - 3*kpoff*S[1,
+							 1, 1][t] + k1*S_RAFK[1, 1, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[1, 2, -1]</td>
+						<td>0</td>
+						<td>(S[1, 2, -1])'[t] == kpon*K[1, 1][t]*S[-1, 2,
+							 -1][t] + k7*S[0, 2, -1][t] + kpon*K[2,
+							 2][t]*S[1, -1, -1][t] - k9a*S[1, 2, -1][t]
+							 - 2*kpoff*S[1, 2, -1][t] - kon*K[3, 0][t]*S[
+							1, 2, -1][t] - kpon*K[3, 1][t]*S[1, 2, -1][t]
+							 + koff*S[1, 2, 0][t] + kpoff*S[1, 2, 1]
+							[t]</td>
+					</tr>
+					<tr>
+						<td>S[1, 2, 0]</td>
+						<td>0</td>
+						<td>(S[1, 2, 0])'[t] == kpon*K[1, 1][t]*S[-1, 2,
+							 0][t] + k7*S[0, 2, 0][t] + kpon*K[2, 2]
+							[t]*S[1, -1, 0][t] + kon*K[3, 0][t]*S[1, 2, -
+							1][t] - k9a*S[1, 2, 0][t] - koff*S[1, 2,
+							 0][t] - 2*kpoff*S[1, 2, 0][t] - k1a*RAFK[t]*
+							S[1, 2, 0][t] + d1a*S_RAFK[1, 2, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[1, 2, 1]</td>
+						<td>0</td>
+						<td>(S[1, 2, 1])'[t] == kpon*K[1, 1][t]*S[-1, 2,
+							 1][t] + k7*S[0, 2, 1][t] + kpon*K[2, 2]
+							[t]*S[1, -1, 1][t] + k5a*S[1, 1, 1][t] +
+							 kpon*K[3, 1][t]*S[1, 2, -1][t] - k9a*S[1, 2,
+							 1][t] - 3*kpoff*S[1, 2, 1][t] + k1*S_RAFK[1,
+							 2, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[2, -1, -1]</td>
+						<td>0</td>
+						<td>(S[2, -1, -1])'[t] == kpon*K[1, 2][t]*S[-1, -
+							1, -1][t] - kpoff*S[2, -1, -1][t] - kon*K[2,
+							 0][t]*S[2, -1, -1][t] - kpon*K[2, 1][t]*S[2,
+							 -1, -1][t] - kpon*K[2, 2][t]*S[2, -1, -1][t]
+							 - kon*K[3, 0][t]*S[2, -1, -1][t] - kpon*K[3,
+							 1][t]*S[2, -1, -1][t] + koff*S[2, -1, 0][t]
+							 + kpoff*S[2, -1, 1][t] + koff*S[2, 0, -
+							1][t] + kpoff*S[2, 1, -1][t] + kpoff*S[2, 2,
+							 -1][t]</td>
+					</tr>
+					<tr>
+						<td>S[2, -1, 0]</td>
+						<td>0</td>
+						<td>(S[2, -1, 0])'[t] == kpon*K[1, 2][t]*S[-1, -1,
+							 0][t] + kon*K[3, 0][t]*S[2, -1, -1][t] -
+							 koff*S[2, -1, 0][t] - kpoff*S[2, -1, 0][t]
+							 - k1a*RAFK[t]*S[2, -1, 0][t] - kon*K[2, 0][
+							t]*S[2, -1, 0][t] - kpon*K[2, 1][t]*S[2, -1,
+							 0][t] - kpon*K[2, 2][t]*S[2, -1, 0][t] +
+							 koff*S[2, 0, 0][t] + kpoff*S[2, 1, 0][t]
+							 + kpoff*S[2, 2, 0][t] + d1a*S_RAFK[2, -1,
+							 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[2, -1, 1]</td>
+						<td>0</td>
+						<td>(S[2, -1, 1])'[t] == kpon*K[1, 2][t]*S[-1, -1,
+							 1][t] + kpon*K[3, 1][t]*S[2, -1, -1][t] -
+							 2*kpoff*S[2, -1, 1][t] - kon*K[2, 0][t]*S[2,
+							 -1, 1][t] - kpon*K[2, 1][t]*S[2, -1, 1][t]
+							 - kpon*K[2, 2][t]*S[2, -1, 1][t] + koff*S[2,
+							 0, 1][t] + kpoff*S[2, 1, 1][t] + kpoff*
+							S[2, 2, 1][t] + k1*S_RAFK[2, -1, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[2, 0, -1]</td>
+						<td>0</td>
+						<td>(S[2, 0, -1])'[t] == kpon*K[1, 2][t]*S[-1, 0,
+							 -1][t] + kon*K[2, 0][t]*S[2, -1, -1][t] -
+							 koff*S[2, 0, -1][t] - kpoff*S[2, 0, -1][t]
+							 - kon*K[3, 0][t]*S[2, 0, -1][t] - kpon*K[3,
+							 1][t]*S[2, 0, -1][t] + koff*S[2, 0, 0][t]
+							 + kpoff*S[2, 0, 1][t]</td>
+					</tr>
+					<tr>
+						<td>S[2, 0, 0]</td>
+						<td>0</td>
+						<td>(S[2, 0, 0])'[t] == kpon*K[1, 2][t]*S[-1, 0,
+							 0][t] + kon*K[2, 0][t]*S[2, -1, 0][t] +
+							 kon*K[3, 0][t]*S[2, 0, -1][t] - 2*koff*S[2,
+							 0, 0][t] - kpoff*S[2, 0, 0][t] - k1a*
+							RAFK[t]*S[2, 0, 0][t] + d1a*S_RAFK[2, 0, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[2, 0, 1]</td>
+						<td>0</td>
+						<td>(S[2, 0, 1])'[t] == kpon*K[1, 2][t]*S[-1, 0,
+							 1][t] + kon*K[2, 0][t]*S[2, -1, 1][t] +
+							 kpon*K[3, 1][t]*S[2, 0, -1][t] - k3*S[2, 0,
+							 1][t] - koff*S[2, 0, 1][t] - 2*kpoff*S[2,
+							 0, 1][t] + k1*S_RAFK[2, 0, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[2, 1, -1]</td>
+						<td>0</td>
+						<td>(S[2, 1, -1])'[t] == kpon*K[1, 2][t]*S[-1, 1,
+							 -1][t] + kpon*K[2, 1][t]*S[2, -1, -1][t] -
+							 2*kpoff*S[2, 1, -1][t] - kon*K[3, 0][t]*S[2,
+							 1, -1][t] - kpon*K[3, 1][t]*S[2, 1, -1][t]
+							 + koff*S[2, 1, 0][t] + kpoff*S[2, 1, 1]
+							[t]</td>
+					</tr>
+					<tr>
+						<td>S[2, 1, 0]</td>
+						<td>0</td>
+						<td>(S[2, 1, 0])'[t] == kpon*K[1, 2][t]*S[-1, 1,
+							 0][t] + kpon*K[2, 1][t]*S[2, -1, 0][t] +
+							 kon*K[3, 0][t]*S[2, 1, -1][t] - koff*S[2, 1,
+							 0][t] - 2*kpoff*S[2, 1, 0][t] - k1a*RAFK[t]*
+							S[2, 1, 0][t] + d1a*S_RAFK[2, 1, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[2, 1, 1]</td>
+						<td>0</td>
+						<td>(S[2, 1, 1])'[t] == kpon*K[1, 2][t]*S[-1, 1,
+							 1][t] + kpon*K[2, 1][t]*S[2, -1, 1][t] +
+							 k3*S[2, 0, 1][t] + kpon*K[3, 1][t]*S[2, 1,
+							 -1][t] - k5a*S[2, 1, 1][t] - 3*kpoff*S[2,
+							 1, 1][t] + k1*S_RAFK[2, 1, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[2, 2, -1]</td>
+						<td>0</td>
+						<td>(S[2, 2, -1])'[t] == kpon*K[1, 2][t]*S[-1, 2,
+							 -1][t] + k9a*S[1, 2, -1][t] + kpon*K[2,
+							 2][t]*S[2, -1, -1][t] - 2*kpoff*S[2, 2, -1][
+							t] - kon*K[3, 0][t]*S[2, 2, -1][t] - kpon*K[
+							3, 1][t]*S[2, 2, -1][t] + koff*S[2, 2, 0][t]
+							 + kpoff*S[2, 2, 1][t]</td>
+					</tr>
+					<tr>
+						<td>S[2, 2, 0]</td>
+						<td>0</td>
+						<td>(S[2, 2, 0])'[t] == kpon*K[1, 2][t]*S[-1, 2,
+							 0][t] + k9a*S[1, 2, 0][t] + kpon*K[2,
+							 2][t]*S[2, -1, 0][t] + kon*K[3, 0][t]*S[2,
+							 2, -1][t] - koff*S[2, 2, 0][t] - 2*
+							kpoff*S[2, 2, 0][t] - k1a*RAFK[t]*S[2, 2, 0][t]
+							 + d1a*S_RAFK[2, 2, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S[2, 2, 1]</td>
+						<td>0</td>
+						<td>(S[2, 2, 1])'[t] == kpon*K[1, 2][t]*S[-1, 2,
+							 1][t] + k9a*S[1, 2, 1][t] + kpon*K[2,
+							 2][t]*S[2, -1, 1][t] + k5a*S[2, 1, 1][t]
+							 + kpon*K[3, 1][t]*S[2, 2, -1][t] - 3*kpoff*
+							S[2, 2, 1][t] + k1*S_RAFK[2, 2, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S_RAFK[-1, -1, 0]</td>
+						<td>0</td>
+						<td>(S_RAFK[-1, -1, 0])'[t] == k1a*RAFK[t]*S[-1, -1,
+							 0][t] - d1a*S_RAFK[-1, -1, 0][t] - k1*
+							S_RAFK[-1, -1, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S_RAFK[-1, 0, 0]</td>
+						<td>0</td>
+						<td>(S_RAFK[-1, 0, 0])'[t] == k1a*RAFK[t]*S[-1, 0,
+							 0][t] - d1a*S_RAFK[-1, 0, 0][t] - k1*S_RAFK[
+							-1, 0, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S_RAFK[-1, 1, 0]</td>
+						<td>0</td>
+						<td>(S_RAFK[-1, 1, 0])'[t] == k1a*RAFK[t]*S[-1, 1,
+							 0][t] - d1a*S_RAFK[-1, 1, 0][t] - k1*S_RAFK[
+							-1, 1, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S_RAFK[-1, 2, 0]</td>
+						<td>0</td>
+						<td>(S_RAFK[-1, 2, 0])'[t] == k1a*RAFK[t]*S[-1, 2,
+							 0][t] - d1a*S_RAFK[-1, 2, 0][t] - k1*S_RAFK[
+							-1, 2, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S_RAFK[0, -1, 0]</td>
+						<td>0</td>
+						<td>(S_RAFK[0, -1, 0])'[t] == k1a*RAFK[t]*S[0, -1,
+							 0][t] - d1a*S_RAFK[0, -1, 0][t] - k1*S_RAFK[
+							0, -1, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S_RAFK[0, 0, 0]</td>
+						<td>0</td>
+						<td>(S_RAFK[0, 0, 0])'[t] == k1a*RAFK[t]*S[0, 0,
+							 0][t] - d1a*S_RAFK[0, 0, 0][t] - k1*S_RAFK[
+							0, 0, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S_RAFK[0, 1, 0]</td>
+						<td>0</td>
+						<td>(S_RAFK[0, 1, 0])'[t] == k1a*RAFK[t]*S[0, 1,
+							 0][t] - d1a*S_RAFK[0, 1, 0][t] - k1*S_RAFK[
+							0, 1, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S_RAFK[0, 2, 0]</td>
+						<td>0</td>
+						<td>(S_RAFK[0, 2, 0])'[t] == k1a*RAFK[t]*S[0, 2,
+							 0][t] - d1a*S_RAFK[0, 2, 0][t] - k1*S_RAFK[
+							0, 2, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S_RAFK[1, -1, 0]</td>
+						<td>0</td>
+						<td>(S_RAFK[1, -1, 0])'[t] == k1a*RAFK[t]*S[1, -1,
+							 0][t] - d1a*S_RAFK[1, -1, 0][t] - k1*S_RAFK[
+							1, -1, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S_RAFK[1, 0, 0]</td>
+						<td>0</td>
+						<td>(S_RAFK[1, 0, 0])'[t] == k1a*RAFK[t]*S[1, 0,
+							 0][t] - d1a*S_RAFK[1, 0, 0][t] - k1*S_RAFK[
+							1, 0, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S_RAFK[1, 1, 0]</td>
+						<td>0</td>
+						<td>(S_RAFK[1, 1, 0])'[t] == k1a*RAFK[t]*S[1, 1,
+							 0][t] - d1a*S_RAFK[1, 1, 0][t] - k1*S_RAFK[
+							1, 1, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S_RAFK[1, 2, 0]</td>
+						<td>0</td>
+						<td>(S_RAFK[1, 2, 0])'[t] == k1a*RAFK[t]*S[1, 2,
+							 0][t] - d1a*S_RAFK[1, 2, 0][t] - k1*S_RAFK[
+							1, 2, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S_RAFK[2, -1, 0]</td>
+						<td>0</td>
+						<td>(S_RAFK[2, -1, 0])'[t] == k1a*RAFK[t]*S[2, -1,
+							 0][t] - d1a*S_RAFK[2, -1, 0][t] - k1*S_RAFK[
+							2, -1, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S_RAFK[2, 0, 0]</td>
+						<td>0</td>
+						<td>(S_RAFK[2, 0, 0])'[t] == k1a*RAFK[t]*S[2, 0,
+							 0][t] - d1a*S_RAFK[2, 0, 0][t] - k1*S_RAFK[
+							2, 0, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S_RAFK[2, 1, 0]</td>
+						<td>0</td>
+						<td>(S_RAFK[2, 1, 0])'[t] == k1a*RAFK[t]*S[2, 1,
+							 0][t] - d1a*S_RAFK[2, 1, 0][t] - k1*S_RAFK[
+							2, 1, 0][t]</td>
+					</tr>
+					<tr>
+						<td>S_RAFK[2, 2, 0]</td>
+						<td>0</td>
+						<td>(S_RAFK[2, 2, 0])'[t] == k1a*RAFK[t]*S[2, 2,
+							 0][t] - d1a*S_RAFK[2, 2, 0][t] - k1*S_RAFK[
+							2, 2, 0][t]</td>
+					</tr>
+				</tbody>
+			</table>
+			<p>Generated by Cellerator Version 1.0 update 2.1203 using Mathematica 4.2 for 
+				Mac OS X (June 4, 2002), December 4, 2002 15:06:10, using (PowerMac,PowerPC,Mac 
+				OS X,MacOSX,Darwin)</p>
+			<p>author=B.E.Shapiro</p>
+
+		</body>
+	
+    </notes>
+    <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_000001">
+                  
+<dc:relation>
+<rdf:Bag>
+
+
+
+
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0000165"/>
+<rdf:li rdf:resource="http://www.ncbi.nlm.nih.gov/Taxonomy/#8355"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/biomodels/#BIOMD0000000014"/>
+
+<rdf:li rdf:resource="http://www.ncbi.nlm.nih.gov/PubMed/#10823939"/>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0005078"/>
+</rdf:Bag>
+</dc:relation>
+
+<dc:creator rdf:parseType="Resource">
+<rdf:Bag>
+<rdf:li rdf:parseType="Resource">
+<vCard:N rdf:parseType="Resource">
+<vCard:Family>Shapiro</vCard:Family>
+<vCard:Given>Bruce</vCard:Given>
+</vCard:N>
+<vCard:EMAIL>bshapiro@jpl.nasa.gov</vCard:EMAIL>
+<vCard:ORG>
+<vCard:Orgname>NASA Jet Propulsion Laboratory</vCard:Orgname>
+</vCard:ORG>
+</rdf:li>
+</rdf:Bag>
+</dc:creator>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+    <listOfCompartments>
+      <compartment id="Cytoplasm" metaid="_801486" size="1">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_801486">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0005737"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</compartment>
+    </listOfCompartments>
+    <listOfSpecies>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="MAPKP" initialAmount="0.3" metaid="_801521" name="MAPK phosphatase">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_801521">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q90W58"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="MEKP" initialAmount="0.2" metaid="_801552" name="MEK phosphatase"/>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="RAFK" initialAmount="0.1" metaid="_801582" name="RAF kinase"/>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="RAFP" initialAmount="0.3" metaid="_801612" name="RAF phosphatase"/>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="K_1_0" initialAmount="0.4" metaid="_801641" name="MAPK">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_801641">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="K_1_1" initialAmount="0" metaid="_801671" name="MAPK-P">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_801671">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="K_1_2" initialAmount="0" metaid="_801701" name="MAPK-PP">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_801701">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="K_2_0" initialAmount="0.2" metaid="_801731" name="MEK">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_801731">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="K_2_1" initialAmount="0" metaid="_801761" name="MEK-P">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_801761">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="K_2_2" initialAmount="0" metaid="_801791" name="MEK-PP">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_801791">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="K_3_0" initialAmount="0.3" metaid="_801821" name="RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_801821">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="K_3_1" initialAmount="0" metaid="_801851" name="RAF-P">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_801851">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="K_K_1_0_2_2" initialAmount="0" metaid="_801882" name="MAPK_MEK-PP">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_801882">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="K_K_1_1_2_2" initialAmount="0" metaid="_801911" name="MAPK-P_MEK-PP">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_801911">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="K_K_2_0_3_1" initialAmount="0" metaid="_801941" name="MEK_RAF-P">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_801941">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="K_K_2_1_3_1" initialAmount="0" metaid="_801971" name="MEK-P_RAF-P">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_801971">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="K_MAPKP_1_1" initialAmount="0" metaid="_802001" name="MAPK-P_MAPKPase">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802001">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q90W58"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="K_MAPKP_1_2" initialAmount="0" metaid="_802032" name="MAPK-PP_MAPKPase">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802032">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q90W58"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="K_MEKP_2_1" initialAmount="0" metaid="_802061" name="MEK-P_MEKPase">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802061">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="K_MEKP_2_2" initialAmount="0" metaid="_802092" name="MEK-PP_MEKPase">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802092">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="K_RAFK_3_0" initialAmount="0" metaid="_802121" name="RAF_RAFK">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802121">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="K_RAFP_3_1" initialAmount="0" metaid="_802151" name="RAF-P_RAFPase">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802151">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_m1_m1_m1" initialAmount="0.1" metaid="_802181" name="Scaffold"/>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_m1_m1_0" initialAmount="0" metaid="_802211" name="Scaffold_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802211">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_m1_m1_1" initialAmount="0" metaid="_802241" name="Scaffold_RAF-P">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802241">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_m1_0_m1" initialAmount="0" metaid="_802271" name="Scaffold_MEK">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802271">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_m1_0_0" initialAmount="0" metaid="_802301" name="Scaffold_MEK_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802301">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_m1_0_1" initialAmount="0" metaid="_802332" name="Scaffold_MEK_RAF-P">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802332">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_m1_1_m1" initialAmount="0" metaid="_802362" name="Scaffold_MEK-P">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802362">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_m1_1_0" initialAmount="0" metaid="_802392" name="Scaffold_MEK-P_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802392">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_m1_1_1" initialAmount="0" metaid="_802421" name="Scaffold_MEK-P_RAF-P">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802421">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_m1_2_m1" initialAmount="0" metaid="_802451" name="Scaffold_MEK-PP">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802451">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_m1_2_0" initialAmount="0" metaid="_802481" name="Scaffold_MEK-PP_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802481">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_m1_2_1" initialAmount="0" metaid="_802511" name="Scaffold_MEK-PP_RAF-P">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802511">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_0_m1_m1" initialAmount="0" metaid="_802541" name="Scaffold_MAPK">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802541">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_0_m1_0" initialAmount="0" metaid="_802571" name="Scaffold_MAPK_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802571">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_0_m1_1" initialAmount="0" metaid="_802602" name="Scaffold_MAPK_RAF-P">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802602">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_0_0_m1" initialAmount="0" metaid="_802631" name="Scaffold_MAPK_MEK">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802631">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_0_0_0" initialAmount="0" metaid="_802661" name="Scaffold_MAPK_MEK_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802661">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_0_0_1" initialAmount="0" metaid="_802691" name="Scaffold_MAPK_MEK_RAF-P">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802691">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_0_1_m1" initialAmount="0" metaid="_802721" name="Scaffold_MAPK_MEK-P">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802721">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_0_1_0" initialAmount="0" metaid="_802751" name="Scaffold_MAPK_MEK-P_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802751">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_0_1_1" initialAmount="0" metaid="_802781" name="Scaffold_MAPK_MEK-P_RAF-P">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802781">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_0_2_m1" initialAmount="0" metaid="_802812" name="Scaffold_MAPK_MEK-PP">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802812">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_0_2_0" initialAmount="0" metaid="_802842" name="Scaffold_MAPK_MEK-PP_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802842">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_0_2_1" initialAmount="0" metaid="_802871" name="Scaffold_MAPK_MEK-PP_RAF-P">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802871">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_1_m1_m1" initialAmount="0" metaid="_802901" name="Scaffold_MAPK-P">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802901">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_1_m1_0" initialAmount="0" metaid="_802931" name="Scaffold_MAPK-P_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802931">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_1_m1_1" initialAmount="0" metaid="_802961" name="Scaffold_MAPK-P_RAF-P">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802961">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_1_0_m1" initialAmount="0" metaid="_802991" name="Scaffold_MAPK-P_MEK">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_802991">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_1_0_0" initialAmount="0" metaid="_803021" name="Scaffold_MAPK-P_MEK_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803021">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_1_0_1" initialAmount="0" metaid="_803051" name="Scaffold_MAPK-P_MEK_RAF-P">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803051">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_1_1_m1" initialAmount="0" metaid="_803082" name="Scaffold_MAPK-P_MEK-P">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803082">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_1_1_0" initialAmount="0" metaid="_803111" name="Scaffold_MAPK-P_MEK-P_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803111">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_1_1_1" initialAmount="0" metaid="_803141" name="Scaffold_MAPK-P_MEK-P_RAF-P">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803141">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_1_2_m1" initialAmount="0" metaid="_803171" name="Scaffold_MAPK-P_MEK-PP">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803171">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_1_2_0" initialAmount="0" metaid="_803201" name="Scaffold_MAPK-P_MEK-PP_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803201">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_1_2_1" initialAmount="0" metaid="_803231" name="Scaffold_MAPK-P_MEK-PP_RAF-P">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803231">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_2_m1_m1" initialAmount="0" metaid="_803261" name="Scaffold_MAPK-PP">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803261">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_2_m1_0" initialAmount="0" metaid="_803291" name="Scaffold_MAPK-PP_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803291">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_2_m1_1" initialAmount="0" metaid="_803322" name="Scaffold_MAPK-PP_RAF-P">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803322">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_2_0_m1" initialAmount="0" metaid="_803351" name="Scaffold_MAPK-PP_MEK">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803351">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_2_0_0" initialAmount="0" metaid="_803382" name="Scaffold_MAPK-PP_MEK_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803382">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_2_0_1" initialAmount="0" metaid="_803411" name="Scaffold_MAPK-PP_MEK_RAF-P">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803411">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_2_1_m1" initialAmount="0" metaid="_803441" name="Scaffold_MAPK-PP_MEK-P">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803441">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_2_1_0" initialAmount="0" metaid="_803471" name="Scaffold_MAPK-PP_MEK-P_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803471">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_2_1_1" initialAmount="0" metaid="_803501" name="Scaffold_MAPK-PP_MEK-P_RAF-P">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803501">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_2_2_m1" initialAmount="0" metaid="_803531" name="Scaffold_MAPK-PP_MEK-PP">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803531">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_2_2_0" initialAmount="0" metaid="_803561" name="Scaffold_MAPK-PP_MEK-PP_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803561">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_2_2_1" initialAmount="0" metaid="_803591" name="Scaffold_MAPK-PP_MEK-PP_RAF-P">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803591">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_RAFK_m1_m1_0" initialAmount="0" metaid="_803621" name="Scaffold_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803621">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_RAFK_m1_0_0" initialAmount="0" metaid="_803651" name="Scaffold_MEK_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803651">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_RAFK_m1_1_0" initialAmount="0" metaid="_803681" name="Scaffold_MEK-P_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803681">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_RAFK_m1_2_0" initialAmount="0" metaid="_803711" name="Scaffold_MEK-PP_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803711">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_RAFK_0_m1_0" initialAmount="0" metaid="_803741" name="Scaffold_MAPK_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803741">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_RAFK_0_0_0" initialAmount="0" metaid="_803771" name="Scaffold_MAPK_MEK_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803771">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_RAFK_0_1_0" initialAmount="0" metaid="_803801" name="Scaffold_MAPK_MEK-P_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803801">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_RAFK_0_2_0" initialAmount="0" metaid="_803831" name="Scaffold_MAPK_MEK-PP_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803831">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_RAFK_1_m1_0" initialAmount="0" metaid="_803861" name="Scaffold_MAPK-P_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803861">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_RAFK_1_0_0" initialAmount="0" metaid="_803891" name="Scaffold_MAPK-P_MEK_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803891">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_RAFK_1_1_0" initialAmount="0" metaid="_803921" name="Scaffold_MAPK-P_MEK-P_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803921">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_RAFK_1_2_0" initialAmount="0" metaid="_803951" name="Scaffold_MAPK-P_MEK-PP_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803951">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_RAFK_2_m1_0" initialAmount="0" metaid="_803981" name="Scaffold_MAPK-PP_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_803981">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_RAFK_2_0_0" initialAmount="0" metaid="_804011" name="Scaffold_MAPK-PP_MEK_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_804011">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_RAFK_2_1_0" initialAmount="0" metaid="_804041" name="Scaffold_MAPK-PP_MEK-P_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_804041">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+      <species compartment="Cytoplasm" hasOnlySubstanceUnits="true" id="S_RAFK_2_2_0" initialAmount="0" metaid="_804071" name="Scaffold_MAPK-PP_MEK-PP_RAF">
+<annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_804071">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.uniprot.org/#P26696"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#Q05116"/>
+<rdf:li rdf:resource="http://www.uniprot.org/#P09560"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+</species>
+    </listOfSpecies>
+    <listOfReactions>
+      <reaction id="Reaction1" metaid="_804118" name="binding of RAF and RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="K_3_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_RAFK_3_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> a1 </ci>
+              <ci> RAFK </ci>
+              <ci> K_3_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="a1" value="1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction2" metaid="_804185" name="dissociation of RAF_RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_RAFK_3_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="K_3_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> d1 </ci>
+              <ci> K_RAFK_3_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="d1" value="0.4"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction3" metaid="_804255" name="phosphorylation of RAF" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_804255">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0000185"/>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0008349"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_RAFK_3_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="K_3_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1 </ci>
+              <ci> K_RAFK_3_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction4" metaid="_804325" name="binding of RAF-P and RAF phosphatase" reversible="false">
+        <listOfReactants>
+          <speciesReference species="RAFP"/>
+          <speciesReference species="K_3_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_RAFP_3_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> a2 </ci>
+              <ci> RAFP </ci>
+              <ci> K_3_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="a2" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction5" metaid="_804395" name="dissociation of RAF-P_RAFPase" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_RAFP_3_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFP"/>
+          <speciesReference species="K_3_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> d2 </ci>
+              <ci> K_RAFP_3_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="d2" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction6" metaid="_804466" name="dephosphorylation of RAF-P" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_804466">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 3.1.3.16"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_RAFP_3_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFP"/>
+          <speciesReference species="K_3_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k2 </ci>
+              <ci> K_RAFP_3_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k2" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction7" metaid="_804536" name="binding of MEK and RAF-P" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_0"/>
+          <speciesReference species="K_3_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_K_2_0_3_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> a3 </ci>
+              <ci> K_2_0 </ci>
+              <ci> K_3_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="a3" value="3.3"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction8" metaid="_804605" name="dissociation of MEK_RAF-P" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_K_2_0_3_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_0"/>
+          <speciesReference species="K_3_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> d3 </ci>
+              <ci> K_K_2_0_3_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="d3" value="0.42"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction9" metaid="_804677" name="phosphorylation of MEK" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_804677">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0004709"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_K_2_0_3_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_1"/>
+          <speciesReference species="K_3_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k3 </ci>
+              <ci> K_K_2_0_3_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k3" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction10" metaid="_804745" name="binding of MEK-P and MEK phosphatase" reversible="false">
+        <listOfReactants>
+          <speciesReference species="MEKP"/>
+          <speciesReference species="K_2_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_MEKP_2_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> a4 </ci>
+              <ci> MEKP </ci>
+              <ci> K_2_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="a4" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction11" metaid="_804815" name="dissociation of MEK-P_MEKPase" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_MEKP_2_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="MEKP"/>
+          <speciesReference species="K_2_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> d4 </ci>
+              <ci> K_MEKP_2_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="d4" value="0.8"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction12" metaid="_804885" name="dephosphorylation of MEK-P" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_804885">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 3.1.3.16"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_MEKP_2_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="MEKP"/>
+          <speciesReference species="K_2_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k4 </ci>
+              <ci> K_MEKP_2_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k4" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction13" metaid="_804955" name="binding of MEK-P and RAF-P" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_1"/>
+          <speciesReference species="K_3_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_K_2_1_3_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> a5 </ci>
+              <ci> K_2_1 </ci>
+              <ci> K_3_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="a5" value="3.3"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction14" metaid="_805026" name="dissociation of MEK-P_RAF-P" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_K_2_1_3_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_1"/>
+          <speciesReference species="K_3_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> d5 </ci>
+              <ci> K_K_2_1_3_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="d5" value="0.4"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction15" metaid="_805095" name="phosphorylation of MEK-P" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_805095">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0004709"/>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0000186"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_K_2_1_3_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_2"/>
+          <speciesReference species="K_3_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k5 </ci>
+              <ci> K_K_2_1_3_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k5" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction16" metaid="_805165" name="binding of MEK-PP and MEK phosphatase" reversible="false">
+        <listOfReactants>
+          <speciesReference species="MEKP"/>
+          <speciesReference species="K_2_2"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_MEKP_2_2"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> a6 </ci>
+              <ci> MEKP </ci>
+              <ci> K_2_2 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="a6" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction17" metaid="_805235" name="dissociation of MEK-PP_MEKPase" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_MEKP_2_2"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="MEKP"/>
+          <speciesReference species="K_2_2"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> d6 </ci>
+              <ci> K_MEKP_2_2 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="d6" value="0.8"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction18" metaid="_805305" name="dephosphorylation of MEK-PP" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_805305">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 3.1.3.16"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_MEKP_2_2"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="MEKP"/>
+          <speciesReference species="K_2_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k6 </ci>
+              <ci> K_MEKP_2_2 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k6" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction19" metaid="_805375" name="binding of MAPK and MEK-PP" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_805375">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_0"/>
+          <speciesReference species="K_2_2"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_K_1_0_2_2"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> a7 </ci>
+              <ci> K_1_0 </ci>
+              <ci> K_2_2 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="a7" value="20"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction20" metaid="_805445" name="dissociation of MAPK_MEK-PP" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_K_1_0_2_2"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_0"/>
+          <speciesReference species="K_2_2"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> d7 </ci>
+              <ci> K_K_1_0_2_2 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="d7" value="0.6"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction21" metaid="_805515" name="phosphorylation of MAPK" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_805515">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0004708"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_K_1_0_2_2"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_1"/>
+          <speciesReference species="K_2_2"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k7 </ci>
+              <ci> K_K_1_0_2_2 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k7" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction22" metaid="_805585" name="binding of MAPK-P and MAPK phosphatase" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_805585">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="MAPKP"/>
+          <speciesReference species="K_1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_MAPKP_1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> a8 </ci>
+              <ci> MAPKP </ci>
+              <ci> K_1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="a8" value="5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction23" metaid="_805655" name="dissociation of MAPK-P_MAPKPase" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_MAPKP_1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="MAPKP"/>
+          <speciesReference species="K_1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> d8 </ci>
+              <ci> K_MAPKP_1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="d8" value="0.4"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction24" metaid="_805725" name="dephosphorylation of MAPK-P" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_805725">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 3.1.3.16"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_MAPKP_1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="MAPKP"/>
+          <speciesReference species="K_1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k8 </ci>
+              <ci> K_MAPKP_1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k8" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction25" metaid="_805801" name="binding of MAPK-P and MEK-PP" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_805801">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_1"/>
+          <speciesReference species="K_2_2"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_K_1_1_2_2"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> a9 </ci>
+              <ci> K_1_1 </ci>
+              <ci> K_2_2 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="a9" value="20"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction26" metaid="_805865" name="dissociation of MAPK-P_MEK-PP" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_K_1_1_2_2"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_1"/>
+          <speciesReference species="K_2_2"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> d9 </ci>
+              <ci> K_K_1_1_2_2 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="d9" value="0.6"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction27" metaid="_805935" name="phosphorylation of MAPK-P" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_805935">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0004708"/>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0000187"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_K_1_1_2_2"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_2"/>
+          <speciesReference species="K_2_2"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k9 </ci>
+              <ci> K_K_1_1_2_2 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k9" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction28" metaid="_806005" name="binding of MAPK-PP and MAPK phosphatase" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_806005">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="MAPKP"/>
+          <speciesReference species="K_1_2"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_MAPKP_1_2"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> a10 </ci>
+              <ci> MAPKP </ci>
+              <ci> K_1_2 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="a10" value="5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction29" metaid="_806075" name="dissociation of MAPK-PP_MAPKPase" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_MAPKP_1_2"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="MAPKP"/>
+          <speciesReference species="K_1_2"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> d10 </ci>
+              <ci> K_MAPKP_1_2 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="d10" value="0.4"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction30" metaid="_806145" name="dephosphorylation of MAPK-PP" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_806145">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0000188"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 3.1.3.16"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_MAPKP_1_2"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="MAPKP"/>
+          <speciesReference species="K_1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k10 </ci>
+              <ci> K_MAPKP_1_2 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k10" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction31" metaid="_806215" name="binding of MAPK on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_806215">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_0"/>
+          <speciesReference species="S_m1_m1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_m1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_1_0 </ci>
+              <ci> S_m1_m1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction32" metaid="_806285" name="dissociation of MAPK from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_0_m1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_0"/>
+          <speciesReference species="S_m1_m1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_0_m1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction33" metaid="_806355" name="binding of MAPK on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_806355">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_0"/>
+          <speciesReference species="S_m1_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_1_0 </ci>
+              <ci> S_m1_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction34" metaid="_806425" name="dissociation of MAPK from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_0_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_0"/>
+          <speciesReference species="S_m1_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_0_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction35" metaid="_806495" name="binding of MAPK on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_806495">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_0"/>
+          <speciesReference species="S_m1_m1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_m1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_1_0 </ci>
+              <ci> S_m1_m1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction36" metaid="_806565" name="dissociation of MAPK from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_0_m1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_0"/>
+          <speciesReference species="S_m1_m1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_0_m1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction37" metaid="_806635" name="binding of MAPK on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_806635">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_0"/>
+          <speciesReference species="S_m1_0_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_0_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_1_0 </ci>
+              <ci> S_m1_0_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction38" metaid="_806705" name="dissociation of MAPK from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_0_0_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_0"/>
+          <speciesReference species="S_m1_0_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_0_0_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction39" metaid="_806775" name="binding of MAPK on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_806775">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_0"/>
+          <speciesReference species="S_m1_0_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_0_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_1_0 </ci>
+              <ci> S_m1_0_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction40" metaid="_806845" name="dissociation of MAPK from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_0_0_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_0"/>
+          <speciesReference species="S_m1_0_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_0_0_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction41" metaid="_806915" name="binding of MAPK on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_806915">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_0"/>
+          <speciesReference species="S_m1_0_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_0_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_1_0 </ci>
+              <ci> S_m1_0_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction42" metaid="_806986" name="dissociation of MAPK from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_0_0_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_0"/>
+          <speciesReference species="S_m1_0_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_0_0_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction43" metaid="_807057" name="binding of MAPK on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_807057">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_0"/>
+          <speciesReference species="S_m1_1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_1_0 </ci>
+              <ci> S_m1_1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction44" metaid="_807125" name="dissociation of MAPK from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_0_1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_0"/>
+          <speciesReference species="S_m1_1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_0_1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction45" metaid="_807195" name="binding of MAPK on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_807195">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_0"/>
+          <speciesReference species="S_m1_1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_1_0 </ci>
+              <ci> S_m1_1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction46" metaid="_807265" name="dissociation of MAPK from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_0_1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_0"/>
+          <speciesReference species="S_m1_1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_0_1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction47" metaid="_807335" name="binding of MAPK on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_807335">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_0"/>
+          <speciesReference species="S_m1_1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_1_0 </ci>
+              <ci> S_m1_1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction48" metaid="_807405" name="dissociation of MAPK from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_0_1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_0"/>
+          <speciesReference species="S_m1_1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_0_1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction49" metaid="_807475" name="binding of MAPK on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_807475">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_0"/>
+          <speciesReference species="S_m1_2_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_2_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_1_0 </ci>
+              <ci> S_m1_2_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction50" metaid="_807545" name="dissociation of MAPK from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_0_2_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_0"/>
+          <speciesReference species="S_m1_2_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_0_2_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction51" metaid="_807615" name="binding of MAPK on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_807615">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_0"/>
+          <speciesReference species="S_m1_2_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_2_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_1_0 </ci>
+              <ci> S_m1_2_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction52" metaid="_807685" name="dissociation of MAPK from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_0_2_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_0"/>
+          <speciesReference species="S_m1_2_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_0_2_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction53" metaid="_807755" name="binding of MAPK on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_807755">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_0"/>
+          <speciesReference species="S_m1_2_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_2_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_1_0 </ci>
+              <ci> S_m1_2_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction54" metaid="_807825" name="dissociation of MAPK from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_0_2_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_0"/>
+          <speciesReference species="S_m1_2_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_0_2_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction55" metaid="_807895" name="binding of MAPK-P on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_807895">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_1"/>
+          <speciesReference species="S_m1_m1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_m1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_1_1 </ci>
+              <ci> S_m1_m1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction56" metaid="_807965" name="dissociation of MAPK-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_1_m1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_1"/>
+          <speciesReference species="S_m1_m1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_1_m1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction57" metaid="_808035" name="binding of MAPK-P on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_808035">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_1"/>
+          <speciesReference species="S_m1_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_1_1 </ci>
+              <ci> S_m1_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction58" metaid="_808105" name="dissociation of MAPK-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_1_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_1"/>
+          <speciesReference species="S_m1_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_1_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction59" metaid="_808175" name="binding of MAPK-P on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_808175">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_1"/>
+          <speciesReference species="S_m1_m1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_m1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_1_1 </ci>
+              <ci> S_m1_m1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction60" metaid="_808245" name="dissociation of MAPK-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_1_m1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_1"/>
+          <speciesReference species="S_m1_m1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_1_m1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction61" metaid="_808315" name="binding of MAPK-P on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_808315">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_1"/>
+          <speciesReference species="S_m1_0_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_0_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_1_1 </ci>
+              <ci> S_m1_0_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction62" metaid="_808385" name="dissociation of MAPK-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_1_0_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_1"/>
+          <speciesReference species="S_m1_0_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_1_0_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction63" metaid="_808455" name="binding of MAPK-P on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_808455">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_1"/>
+          <speciesReference species="S_m1_0_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_0_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_1_1 </ci>
+              <ci> S_m1_0_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction64" metaid="_808525" name="dissociation of MAPK-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_1_0_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_1"/>
+          <speciesReference species="S_m1_0_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_1_0_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction65" metaid="_808595" name="binding of MAPK-P on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_808595">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_1"/>
+          <speciesReference species="S_m1_0_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_0_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_1_1 </ci>
+              <ci> S_m1_0_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction66" metaid="_808665" name="dissociation of MAPK-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_1_0_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_1"/>
+          <speciesReference species="S_m1_0_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_1_0_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction67" metaid="_808735" name="binding of MAPK-P on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_808735">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_1"/>
+          <speciesReference species="S_m1_1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_1_1 </ci>
+              <ci> S_m1_1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction68" metaid="_808805" name="dissociation of MAPK-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_1_1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_1"/>
+          <speciesReference species="S_m1_1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_1_1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction69" metaid="_808876" name="binding of MAPK-P on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_808876">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_1"/>
+          <speciesReference species="S_m1_1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_1_1 </ci>
+              <ci> S_m1_1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction70" metaid="_808945" name="dissociation of MAPK-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_1_1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_1"/>
+          <speciesReference species="S_m1_1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_1_1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction71" metaid="_809015" name="binding of MAPK-P on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_809015">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_1"/>
+          <speciesReference species="S_m1_1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_1_1 </ci>
+              <ci> S_m1_1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction72" metaid="_809085" name="dissociation of MAPK-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_1_1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_1"/>
+          <speciesReference species="S_m1_1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_1_1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction73" metaid="_809155" name="binding of MAPK-P on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_809155">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_1"/>
+          <speciesReference species="S_m1_2_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_2_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_1_1 </ci>
+              <ci> S_m1_2_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction74" metaid="_809225" name="dissociation of MAPK-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_1_2_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_1"/>
+          <speciesReference species="S_m1_2_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_1_2_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction75" metaid="_809295" name="binding of MAPK-P on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_809295">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_1"/>
+          <speciesReference species="S_m1_2_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_2_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_1_1 </ci>
+              <ci> S_m1_2_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction76" metaid="_809365" name="dissociation of MAPK-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_1_2_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_1"/>
+          <speciesReference species="S_m1_2_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_1_2_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction77" metaid="_809435" name="binding of MAPK-P on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_809435">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_1"/>
+          <speciesReference species="S_m1_2_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_2_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_1_1 </ci>
+              <ci> S_m1_2_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction78" metaid="_809505" name="dissociation of MAPK-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_1_2_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_1"/>
+          <speciesReference species="S_m1_2_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_1_2_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction79" metaid="_809575" name="binding of MAPK-PP on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_809575">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_2"/>
+          <speciesReference species="S_m1_m1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_m1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_1_2 </ci>
+              <ci> S_m1_m1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction80" metaid="_809646" name="dissociation of MAPK-PP from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_2_m1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_2"/>
+          <speciesReference species="S_m1_m1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_2_m1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction81" metaid="_809715" name="binding of MAPK-PP on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_809715">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_2"/>
+          <speciesReference species="S_m1_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_1_2 </ci>
+              <ci> S_m1_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction82" metaid="_809785" name="dissociation of MAPK-PP from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_2_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_2"/>
+          <speciesReference species="S_m1_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_2_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction83" metaid="_809855" name="binding of MAPK-PP on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_809855">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_2"/>
+          <speciesReference species="S_m1_m1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_m1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_1_2 </ci>
+              <ci> S_m1_m1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction84" metaid="_809925" name="dissociation of MAPK-PP from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_2_m1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_2"/>
+          <speciesReference species="S_m1_m1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_2_m1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction85" metaid="_809995" name="binding of MAPK-PP on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_809995">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_2"/>
+          <speciesReference species="S_m1_0_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_0_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_1_2 </ci>
+              <ci> S_m1_0_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction86" metaid="_810065" name="dissociation of MAPK-PP from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_2_0_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_2"/>
+          <speciesReference species="S_m1_0_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_2_0_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction87" metaid="_810135" name="binding of MAPK-PP on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_810135">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_2"/>
+          <speciesReference species="S_m1_0_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_0_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_1_2 </ci>
+              <ci> S_m1_0_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction88" metaid="_810205" name="dissociation of MAPK-PP from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_2_0_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_2"/>
+          <speciesReference species="S_m1_0_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_2_0_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction89" metaid="_810275" name="binding of MAPK-PP on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_810275">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_2"/>
+          <speciesReference species="S_m1_0_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_0_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_1_2 </ci>
+              <ci> S_m1_0_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction90" metaid="_810345" name="dissociation of MAPK-PP from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_2_0_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_2"/>
+          <speciesReference species="S_m1_0_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_2_0_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction91" metaid="_810415" name="binding of MAPK-PP on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_810415">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_2"/>
+          <speciesReference species="S_m1_1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_1_2 </ci>
+              <ci> S_m1_1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction92" metaid="_810485" name="dissociation of MAPK-PP from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_2_1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_2"/>
+          <speciesReference species="S_m1_1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_2_1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction93" metaid="_810555" name="binding of MAPK-PP on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_810555">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_2"/>
+          <speciesReference species="S_m1_1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_1_2 </ci>
+              <ci> S_m1_1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction94" metaid="_810625" name="dissociation of MAPK-PP from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_2_1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_2"/>
+          <speciesReference species="S_m1_1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_2_1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction95" metaid="_810695" name="binding of MAPK-PP on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_810695">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_2"/>
+          <speciesReference species="S_m1_1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_1_2 </ci>
+              <ci> S_m1_1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction96" metaid="_810765" name="dissociation of MAPK-PP from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_2_1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_2"/>
+          <speciesReference species="S_m1_1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_2_1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction97" metaid="_810835" name="binding of MAPK-PP on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_810835">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_2"/>
+          <speciesReference species="S_m1_2_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_2_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_1_2 </ci>
+              <ci> S_m1_2_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction98" metaid="_810908" name="dissociation of MAPK-PP from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_2_2_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_2"/>
+          <speciesReference species="S_m1_2_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_2_2_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction99" metaid="_810975" name="binding of MAPK-PP on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_810975">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_2"/>
+          <speciesReference species="S_m1_2_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_2_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_1_2 </ci>
+              <ci> S_m1_2_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction100" metaid="_811045" name="dissociation of MAPK-PP from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_2_2_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_2"/>
+          <speciesReference species="S_m1_2_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_2_2_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction101" metaid="_811117" name="binding of MAPK-PP on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">
+<rdf:Description rdf:about="#_811117">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0051019"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="K_1_2"/>
+          <speciesReference species="S_m1_2_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_2_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_1_2 </ci>
+              <ci> S_m1_2_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction102" metaid="_811185" name="dissociation of MAPK-PP from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_2_2_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_1_2"/>
+          <speciesReference species="S_m1_2_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_2_2_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction103" metaid="_811255" name="binding of MEK on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_0"/>
+          <speciesReference species="S_m1_m1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_m1_0_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_2_0 </ci>
+              <ci> S_m1_m1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction104" metaid="_811325" name="dissociation of MEK from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_m1_0_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_0"/>
+          <speciesReference species="S_m1_m1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_m1_0_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction105" metaid="_811395" name="binding of MEK on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_0"/>
+          <speciesReference species="S_m1_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_m1_0_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_2_0 </ci>
+              <ci> S_m1_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction106" metaid="_811466" name="dissociation of MEK from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_m1_0_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_0"/>
+          <speciesReference species="S_m1_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_m1_0_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction107" metaid="_811536" name="binding of MEK on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_0"/>
+          <speciesReference species="S_m1_m1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_m1_0_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_2_0 </ci>
+              <ci> S_m1_m1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction108" metaid="_811605" name="dissociation of MEK from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_m1_0_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_0"/>
+          <speciesReference species="S_m1_m1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_m1_0_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction109" metaid="_811675" name="binding of MEK-P on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_1"/>
+          <speciesReference species="S_m1_m1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_m1_1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_2_1 </ci>
+              <ci> S_m1_m1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction110" metaid="_811745" name="dissociation of MEK-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_m1_1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_1"/>
+          <speciesReference species="S_m1_m1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_m1_1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction111" metaid="_811815" name="binding of MEK-P on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_1"/>
+          <speciesReference species="S_m1_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_m1_1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_2_1 </ci>
+              <ci> S_m1_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction112" metaid="_811885" name="dissociation of MEK-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_m1_1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_1"/>
+          <speciesReference species="S_m1_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_m1_1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction113" metaid="_811955" name="binding of MEK-P on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_1"/>
+          <speciesReference species="S_m1_m1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_m1_1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_2_1 </ci>
+              <ci> S_m1_m1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction114" metaid="_812025" name="dissociation of MEK-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_m1_1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_1"/>
+          <speciesReference species="S_m1_m1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_m1_1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction115" metaid="_812095" name="binding of MEK-PP on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_2"/>
+          <speciesReference species="S_m1_m1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_m1_2_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_2_2 </ci>
+              <ci> S_m1_m1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction116" metaid="_812165" name="dissociation of MEK-PP from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_m1_2_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_2"/>
+          <speciesReference species="S_m1_m1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_m1_2_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction117" metaid="_812235" name="binding of MEK-PP on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_2"/>
+          <speciesReference species="S_m1_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_m1_2_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_2_2 </ci>
+              <ci> S_m1_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction118" metaid="_812305" name="dissociation of MEK-PP from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_m1_2_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_2"/>
+          <speciesReference species="S_m1_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_m1_2_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction119" metaid="_812375" name="binding of MEK-PP on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_2"/>
+          <speciesReference species="S_m1_m1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_m1_2_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_2_2 </ci>
+              <ci> S_m1_m1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction120" metaid="_812445" name="dissociation of MEK-PP from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_m1_2_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_2"/>
+          <speciesReference species="S_m1_m1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_m1_2_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction121" metaid="_812515" name="binding of MEK on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_0"/>
+          <speciesReference species="S_0_m1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_0_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_2_0 </ci>
+              <ci> S_0_m1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction122" metaid="_812585" name="dissociation of MEK from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_0_0_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_0"/>
+          <speciesReference species="S_0_m1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_0_0_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction123" metaid="_812655" name="binding of MEK on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_0"/>
+          <speciesReference species="S_0_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_0_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_2_0 </ci>
+              <ci> S_0_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction124" metaid="_812725" name="dissociation of MEK from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_0_0_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_0"/>
+          <speciesReference species="S_0_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_0_0_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction125" metaid="_812795" name="binding of MEK on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_0"/>
+          <speciesReference species="S_0_m1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_0_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_2_0 </ci>
+              <ci> S_0_m1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction126" metaid="_812865" name="dissociation of MEK from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_0_0_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_0"/>
+          <speciesReference species="S_0_m1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_0_0_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction127" metaid="_812935" name="binding of MEK-P on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_1"/>
+          <speciesReference species="S_0_m1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_2_1 </ci>
+              <ci> S_0_m1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction128" metaid="_813005" name="dissociation of MEK-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_0_1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_1"/>
+          <speciesReference species="S_0_m1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_0_1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction129" metaid="_813075" name="binding of MEK-P on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_1"/>
+          <speciesReference species="S_0_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_2_1 </ci>
+              <ci> S_0_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction130" metaid="_813145" name="dissociation of MEK-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_0_1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_1"/>
+          <speciesReference species="S_0_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_0_1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction131" metaid="_813216" name="binding of MEK-P on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_1"/>
+          <speciesReference species="S_0_m1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_2_1 </ci>
+              <ci> S_0_m1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction132" metaid="_813285" name="dissociation of MEK-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_0_1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_1"/>
+          <speciesReference species="S_0_m1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_0_1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction133" metaid="_813355" name="binding of MEK-PP on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_2"/>
+          <speciesReference species="S_0_m1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_2_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_2_2 </ci>
+              <ci> S_0_m1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction134" metaid="_813425" name="dissociation of MEK-PP from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_0_2_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_2"/>
+          <speciesReference species="S_0_m1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_0_2_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction135" metaid="_813495" name="binding of MEK-PP on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_2"/>
+          <speciesReference species="S_0_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_2_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_2_2 </ci>
+              <ci> S_0_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction136" metaid="_813565" name="dissociation of MEK-PP from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_0_2_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_2"/>
+          <speciesReference species="S_0_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_0_2_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction137" metaid="_813635" name="binding of MEK-PP on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_2"/>
+          <speciesReference species="S_0_m1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_2_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_2_2 </ci>
+              <ci> S_0_m1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction138" metaid="_813705" name="dissociation of MEK-PP from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_0_2_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_2"/>
+          <speciesReference species="S_0_m1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_0_2_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction139" metaid="_813775" name="binding of MEK on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_0"/>
+          <speciesReference species="S_1_m1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_0_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_2_0 </ci>
+              <ci> S_1_m1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction140" metaid="_813845" name="dissociation of MEK from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_1_0_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_0"/>
+          <speciesReference species="S_1_m1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_1_0_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction141" metaid="_813915" name="binding of MEK on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_0"/>
+          <speciesReference species="S_1_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_0_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_2_0 </ci>
+              <ci> S_1_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction142" metaid="_813985" name="dissociation of MEK from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_1_0_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_0"/>
+          <speciesReference species="S_1_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_1_0_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction143" metaid="_814055" name="binding of MEK on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_0"/>
+          <speciesReference species="S_1_m1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_0_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_2_0 </ci>
+              <ci> S_1_m1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction144" metaid="_814125" name="dissociation of MEK from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_1_0_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_0"/>
+          <speciesReference species="S_1_m1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_1_0_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction145" metaid="_814199" name="binding of MEK-P on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_1"/>
+          <speciesReference species="S_1_m1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_2_1 </ci>
+              <ci> S_1_m1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction146" metaid="_814265" name="dissociation of MEK-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_1_1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_1"/>
+          <speciesReference species="S_1_m1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_1_1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction147" metaid="_814338" name="binding of MEK-P on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_1"/>
+          <speciesReference species="S_1_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_2_1 </ci>
+              <ci> S_1_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction148" metaid="_814405" name="dissociation of MEK-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_1_1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_1"/>
+          <speciesReference species="S_1_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_1_1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction149" metaid="_814475" name="binding of MEK-P on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_1"/>
+          <speciesReference species="S_1_m1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_2_1 </ci>
+              <ci> S_1_m1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction150" metaid="_814549" name="dissociation of MEK-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_1_1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_1"/>
+          <speciesReference species="S_1_m1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_1_1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction151" metaid="_814615" name="binding of MEK-PP on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_2"/>
+          <speciesReference species="S_1_m1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_2_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_2_2 </ci>
+              <ci> S_1_m1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction152" metaid="_814685" name="dissociation of MEK-PP from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_1_2_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_2"/>
+          <speciesReference species="S_1_m1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_1_2_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction153" metaid="_814755" name="binding of MEK-PP on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_2"/>
+          <speciesReference species="S_1_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_2_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_2_2 </ci>
+              <ci> S_1_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction154" metaid="_814825" name="dissociation of MEK-PP from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_1_2_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_2"/>
+          <speciesReference species="S_1_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_1_2_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction155" metaid="_814895" name="binding of MEK-PP on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_2"/>
+          <speciesReference species="S_1_m1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_2_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_2_2 </ci>
+              <ci> S_1_m1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction156" metaid="_814965" name="dissociation of MEK-PP from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_1_2_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_2"/>
+          <speciesReference species="S_1_m1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_1_2_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction157" metaid="_815035" name="binding of MEK on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_0"/>
+          <speciesReference species="S_2_m1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_0_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_2_0 </ci>
+              <ci> S_2_m1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction158" metaid="_815105" name="dissociation of MEK from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_2_0_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_0"/>
+          <speciesReference species="S_2_m1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_2_0_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction159" metaid="_815175" name="binding of MEK on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_0"/>
+          <speciesReference species="S_2_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_0_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_2_0 </ci>
+              <ci> S_2_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction160" metaid="_815245" name="dissociation of MEK from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_2_0_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_0"/>
+          <speciesReference species="S_2_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_2_0_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction161" metaid="_815315" name="binding of MEK on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_0"/>
+          <speciesReference species="S_2_m1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_0_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_2_0 </ci>
+              <ci> S_2_m1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction162" metaid="_815385" name="dissociation of MEK from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_2_0_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_0"/>
+          <speciesReference species="S_2_m1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_2_0_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction163" metaid="_815455" name="binding of MEK-P on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_1"/>
+          <speciesReference species="S_2_m1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_2_1 </ci>
+              <ci> S_2_m1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction164" metaid="_815525" name="dissociation of MEK-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_2_1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_1"/>
+          <speciesReference species="S_2_m1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_2_1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction165" metaid="_815595" name="binding of MEK-P on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_1"/>
+          <speciesReference species="S_2_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_2_1 </ci>
+              <ci> S_2_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction166" metaid="_815665" name="dissociation of MEK-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_2_1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_1"/>
+          <speciesReference species="S_2_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_2_1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction167" metaid="_815735" name="binding of MEK-P on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_1"/>
+          <speciesReference species="S_2_m1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_2_1 </ci>
+              <ci> S_2_m1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction168" metaid="_815805" name="dissociation of MEK-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_2_1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_1"/>
+          <speciesReference species="S_2_m1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_2_1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction169" metaid="_815875" name="binding of MEK-PP on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_2"/>
+          <speciesReference species="S_2_m1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_2_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_2_2 </ci>
+              <ci> S_2_m1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction170" metaid="_815945" name="dissociation of MEK-PP from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_2_2_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_2"/>
+          <speciesReference species="S_2_m1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_2_2_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction171" metaid="_816017" name="binding of MEK-PP on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_2"/>
+          <speciesReference species="S_2_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_2_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_2_2 </ci>
+              <ci> S_2_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction172" metaid="_816085" name="dissociation of MEK-PP from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_2_2_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_2"/>
+          <speciesReference species="S_2_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_2_2_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction173" metaid="_816155" name="binding of MEK-PP on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_2_2"/>
+          <speciesReference species="S_2_m1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_2_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_2_2 </ci>
+              <ci> S_2_m1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction174" metaid="_816225" name="dissociation of MEK-PP from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_2_2_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_2_2"/>
+          <speciesReference species="S_2_m1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_2_2_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction175" metaid="_816295" name="binding of RAF on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_m1_m1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_m1_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_3_0 </ci>
+              <ci> S_m1_m1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction176" metaid="_816365" name="dissociation of RAF from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_m1_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_m1_m1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_m1_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction177" metaid="_816435" name="binding of RAF-P on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_m1_m1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_m1_m1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_3_1 </ci>
+              <ci> S_m1_m1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction178" metaid="_816504" name="dissociation of RAF-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_m1_m1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_m1_m1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_m1_m1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction179" metaid="_816575" name="binding of RAF on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_m1_0_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_m1_0_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_3_0 </ci>
+              <ci> S_m1_0_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction180" metaid="_816645" name="dissociation of RAF from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_m1_0_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_m1_0_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_m1_0_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction181" metaid="_816715" name="binding of RAF-P on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_m1_0_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_m1_0_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_3_1 </ci>
+              <ci> S_m1_0_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction182" metaid="_816785" name="dissociation of RAF-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_m1_0_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_m1_0_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_m1_0_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction183" metaid="_816855" name="binding of RAF on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_m1_1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_m1_1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_3_0 </ci>
+              <ci> S_m1_1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction184" metaid="_816924" name="dissociation of RAF from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_m1_1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_m1_1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_m1_1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction185" metaid="_816994" name="binding of RAF-P on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_m1_1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_m1_1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_3_1 </ci>
+              <ci> S_m1_1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction186" metaid="_817078" name="dissociation of RAF-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_m1_1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_m1_1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_m1_1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction187" metaid="_817145" name="binding of RAF on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_m1_2_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_m1_2_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_3_0 </ci>
+              <ci> S_m1_2_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction188" metaid="_817215" name="dissociation of RAF from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_m1_2_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_m1_2_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_m1_2_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction189" metaid="_817285" name="binding of RAF-P on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_m1_2_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_m1_2_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_3_1 </ci>
+              <ci> S_m1_2_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction190" metaid="_817355" name="dissociation of RAF-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_m1_2_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_m1_2_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_m1_2_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction191" metaid="_817424" name="binding of RAF on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_0_m1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_3_0 </ci>
+              <ci> S_0_m1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction192" metaid="_817495" name="dissociation of RAF from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_0_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_0_m1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_0_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction193" metaid="_817565" name="binding of RAF-P on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_0_m1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_m1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_3_1 </ci>
+              <ci> S_0_m1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction194" metaid="_817634" name="dissociation of RAF-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_0_m1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_0_m1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_0_m1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction195" metaid="_817705" name="binding of RAF on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_0_0_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_0_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_3_0 </ci>
+              <ci> S_0_0_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction196" metaid="_817774" name="dissociation of RAF from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_0_0_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_0_0_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_0_0_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction197" metaid="_817845" name="binding of RAF-P on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_0_0_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_0_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_3_1 </ci>
+              <ci> S_0_0_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction198" metaid="_817915" name="dissociation of RAF from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_0_0_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_0_0_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_0_0_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction199" metaid="_817985" name="binding of RAF on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_0_1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_3_0 </ci>
+              <ci> S_0_1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction200" metaid="_818056" name="dissociation of RAF from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_0_1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_0_1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_0_1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction201" metaid="_818125" name="binding of RAF-P on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_0_1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_3_1 </ci>
+              <ci> S_0_1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction202" metaid="_818195" name="dissociation of RAF-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_0_1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_0_1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_0_1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction203" metaid="_818264" name="binding of RAF on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_0_2_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_2_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_3_0 </ci>
+              <ci> S_0_2_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction204" metaid="_818334" name="dissociation of RAF from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_0_2_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_0_2_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_0_2_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction205" metaid="_818405" name="binding of RAF-P on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_0_2_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_2_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_3_1 </ci>
+              <ci> S_0_2_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction206" metaid="_818475" name="dissociation of RAF-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_0_2_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_0_2_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_0_2_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction207" metaid="_818545" name="binding of RAF on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_1_m1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_3_0 </ci>
+              <ci> S_1_m1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction208" metaid="_818614" name="dissociation of RAF from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_1_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_1_m1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_1_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction209" metaid="_818685" name="binding of RAF-P on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_1_m1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_m1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_3_1 </ci>
+              <ci> S_1_m1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction210" metaid="_818755" name="dissociation of RAF-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_1_m1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_1_m1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_1_m1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction211" metaid="_818824" name="binding of RAF on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_1_0_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_0_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_3_0 </ci>
+              <ci> S_1_0_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction212" metaid="_818894" name="dissociation of RAF from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_1_0_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_1_0_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_1_0_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction213" metaid="_818965" name="binding of RAF-P on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_1_0_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_0_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_3_1 </ci>
+              <ci> S_1_0_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction214" metaid="_819034" name="dissociation of RAF-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_1_0_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_1_0_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_1_0_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction215" metaid="_819104" name="binding of RAF on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_1_1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_3_0 </ci>
+              <ci> S_1_1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction216" metaid="_819174" name="dissociation of RAF from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_1_1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_1_1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_1_1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction217" metaid="_819246" name="binding of RAF-P on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_1_1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_3_1 </ci>
+              <ci> S_1_1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction218" metaid="_819314" name="dissociation of RAF-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_1_1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_1_1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_1_1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction219" metaid="_819385" name="binding of RAF on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_1_2_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_2_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_3_0 </ci>
+              <ci> S_1_2_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction220" metaid="_819455" name="dissociation of RAF from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_1_2_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_1_2_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_1_2_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction221" metaid="_819526" name="binding of RAF-P on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_1_2_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_2_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_3_1 </ci>
+              <ci> S_1_2_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction222" metaid="_819595" name="dissociation of RAF-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_1_2_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_1_2_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_1_2_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction223" metaid="_819664" name="binding of RAF on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_2_m1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_3_0 </ci>
+              <ci> S_2_m1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction224" metaid="_819734" name="dissociation of RAF from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_2_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_2_m1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_2_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction225" metaid="_819804" name="binding of RAF-P on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_2_m1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_m1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_3_1 </ci>
+              <ci> S_2_m1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction226" metaid="_819874" name="dissociation of RAF-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_2_m1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_2_m1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_2_m1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction227" metaid="_819945" name="binding of RAF on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_2_0_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_0_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_3_0 </ci>
+              <ci> S_2_0_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction228" metaid="_820015" name="dissociation of RAF from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_2_0_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_2_0_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_2_0_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction229" metaid="_820084" name="binding of RAF-P on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_2_0_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_0_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_3_1 </ci>
+              <ci> S_2_0_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction230" metaid="_820154" name="dissociation of RAF-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_2_0_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_2_0_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_2_0_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction231" metaid="_820226" name="binding of RAF on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_2_1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_3_0 </ci>
+              <ci> S_2_1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction232" metaid="_820295" name="dissociation of RAF from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_2_1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_2_1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_2_1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction233" metaid="_820364" name="binding of RAF-P on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_2_1_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_3_1 </ci>
+              <ci> S_2_1_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction234" metaid="_820434" name="dissociation of RAF-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_2_1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_2_1_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_2_1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction235" metaid="_820504" name="binding of RAF on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_2_2_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_2_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kon </ci>
+              <ci> K_3_0 </ci>
+              <ci> S_2_2_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kon" value="10"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction236" metaid="_820574" name="dissociation of RAF from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_2_2_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_0"/>
+          <speciesReference species="S_2_2_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> koff </ci>
+              <ci> S_2_2_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="koff" value="0.5"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction237" metaid="_820644" name="binding of RAF-P on scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_2_2_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_2_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpon </ci>
+              <ci> K_3_1 </ci>
+              <ci> S_2_2_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpon" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction238" metaid="_820714" name="dissociation of RAF-P from scaffold" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_2_2_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="K_3_1"/>
+          <speciesReference species="S_2_2_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> kpoff </ci>
+              <ci> S_2_2_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="kpoff" value="0.05"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction239" metaid="_820784" name="phosphorylation of MAPK on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_820784">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0004708"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_0_2_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_2_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k7 </ci>
+              <ci> S_0_2_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k7" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction240" metaid="_820837" name="phosphorylation of MAPK on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_820837">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0004708"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_0_2_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_2_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k7 </ci>
+              <ci> S_0_2_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k7" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction241" metaid="_820887" name="phosphorylation of MAPK on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_820887">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0004708"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_0_2_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_2_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k7 </ci>
+              <ci> S_0_2_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k7" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction242" metaid="_820937" name="phosphorylation of MAPK-P on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_820937">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0004708"/>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0000187"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_1_2_m1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_2_m1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k9a </ci>
+              <ci> S_1_2_m1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k9a" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction243" metaid="_820987" name="phosphorylation of MAPK-P on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_820987">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0004708"/>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0000187"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_1_2_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_2_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k9a </ci>
+              <ci> S_1_2_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k9a" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction244" metaid="_821037" name="phosphorylation of MAPK-P on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_821037">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0004708"/>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0000187"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_1_2_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_2_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k9a </ci>
+              <ci> S_1_2_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k9a" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction245" metaid="_821087" name="phosphorylation of MEK on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_821087">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0004709"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_m1_0_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_m1_1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k3 </ci>
+              <ci> S_m1_0_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k3" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction246" metaid="_821137" name="phosphorylation of MEK-P on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_821137">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0004709"/>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0000186"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_m1_1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_m1_2_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k5a </ci>
+              <ci> S_m1_1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k5a" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction247" metaid="_821187" name="phosphorylation of MEK on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_821187">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0004709"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_0_0_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k3 </ci>
+              <ci> S_0_0_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k3" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction248" metaid="_821237" name="phosphorylation of MEK-P on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_821237">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0004709"/>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0000186"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_0_1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_0_2_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k5a </ci>
+              <ci> S_0_1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k5a" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction249" metaid="_821287" name="phosphorylation of MEK on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_821287">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0004709"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_1_0_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k3 </ci>
+              <ci> S_1_0_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k3" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction250" metaid="_821337" name="phosphorylation of MEK-P on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_821337">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0004709"/>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0000186"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_1_1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_1_2_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k5a </ci>
+              <ci> S_1_1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k5a" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction251" metaid="_821387" name="phosphorylation of MEK on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_821387">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0004709"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_2_0_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k3 </ci>
+              <ci> S_2_0_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k3" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction252" metaid="_821437" name="phosphorylation of MEK-P on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_821437">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0004709"/>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0000186"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_2_1_1"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_2_2_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k5a </ci>
+              <ci> S_2_1_1 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k5a" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction253" metaid="_821487" name="binding of RAF and RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_m1_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_RAFK_m1_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1a </ci>
+              <ci> RAFK </ci>
+              <ci> S_m1_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1a" value="100"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction254" metaid="_821555" name="dissociation of RAF_RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_RAFK_m1_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_m1_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> d1a </ci>
+              <ci> S_RAFK_m1_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="d1a" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction255" metaid="_821624" name="phosphorylation of RAF on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_821624">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0000185"/>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0008349"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_RAFK_m1_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_m1_m1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1 </ci>
+              <ci> S_RAFK_m1_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction256" metaid="_821694" name="binding of RAF and RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_m1_0_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_RAFK_m1_0_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1a </ci>
+              <ci> RAFK </ci>
+              <ci> S_m1_0_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1a" value="100"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction257" metaid="_821764" name="dissociation of RAF_RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_RAFK_m1_0_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_m1_0_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> d1a </ci>
+              <ci> S_RAFK_m1_0_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="d1a" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction258" metaid="_821834" name="phosphorylation of RAF on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_821834">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0000185"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_RAFK_m1_0_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_m1_0_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1 </ci>
+              <ci> S_RAFK_m1_0_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction259" metaid="_821904" name="binding of RAF and RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_m1_1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_RAFK_m1_1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1a </ci>
+              <ci> RAFK </ci>
+              <ci> S_m1_1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1a" value="100"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction260" metaid="_821974" name="dissociation of RAF_RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_RAFK_m1_1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_m1_1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> d1a </ci>
+              <ci> S_RAFK_m1_1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="d1a" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction261" metaid="_822044" name="phosphorylation of RAF on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_822044">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0000185"/>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0008349"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_RAFK_m1_1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_m1_1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1 </ci>
+              <ci> S_RAFK_m1_1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction262" metaid="_822114" name="binding of RAF and RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_m1_2_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_RAFK_m1_2_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1a </ci>
+              <ci> RAFK </ci>
+              <ci> S_m1_2_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1a" value="100"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction263" metaid="_822186" name="dissociation of RAF_RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_RAFK_m1_2_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_m1_2_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> d1a </ci>
+              <ci> S_RAFK_m1_2_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="d1a" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction264" metaid="_822254" name="phosphorylation of RAF on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_822254">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0000185"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_RAFK_m1_2_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_m1_2_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1 </ci>
+              <ci> S_RAFK_m1_2_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction265" metaid="_822324" name="binding of RAF and RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_0_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_RAFK_0_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1a </ci>
+              <ci> RAFK </ci>
+              <ci> S_0_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1a" value="100"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction266" metaid="_822394" name="dissociation of RAF_RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_RAFK_0_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_0_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> d1a </ci>
+              <ci> S_RAFK_0_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="d1a" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction267" metaid="_822464" name="phosphorylation of RAF on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_822464">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0000185"/>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0008349"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_RAFK_0_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_0_m1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1 </ci>
+              <ci> S_RAFK_0_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction268" metaid="_822534" name="binding of RAF and RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_0_0_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_RAFK_0_0_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1a </ci>
+              <ci> RAFK </ci>
+              <ci> S_0_0_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1a" value="100"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction269" metaid="_822604" name="dissociation of RAF_RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_RAFK_0_0_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_0_0_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> d1a </ci>
+              <ci> S_RAFK_0_0_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="d1a" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction270" metaid="_822674" name="phosphorylation of RAF on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_822674">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0000185"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_RAFK_0_0_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_0_0_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1 </ci>
+              <ci> S_RAFK_0_0_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction271" metaid="_822744" name="binding of RAF and RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_0_1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_RAFK_0_1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1a </ci>
+              <ci> RAFK </ci>
+              <ci> S_0_1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1a" value="100"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction272" metaid="_822814" name="dissociation of RAF_RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_RAFK_0_1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_0_1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> d1a </ci>
+              <ci> S_RAFK_0_1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="d1a" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction273" metaid="_822884" name="phosphorylation of RAF on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_822884">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0000185"/>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0008349"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_RAFK_0_1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_0_1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1 </ci>
+              <ci> S_RAFK_0_1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction274" metaid="_822954" name="binding of RAF and RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_0_2_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_RAFK_0_2_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1a </ci>
+              <ci> RAFK </ci>
+              <ci> S_0_2_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1a" value="100"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction275" metaid="_823024" name="dissociation of RAF_RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_RAFK_0_2_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_0_2_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> d1a </ci>
+              <ci> S_RAFK_0_2_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="d1a" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction276" metaid="_823094" name="phosphorylation of RAF on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_823094">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0000185"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_RAFK_0_2_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_0_2_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1 </ci>
+              <ci> S_RAFK_0_2_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction277" metaid="_823164" name="binding of RAF and RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_1_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_RAFK_1_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1a </ci>
+              <ci> RAFK </ci>
+              <ci> S_1_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1a" value="100"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction278" metaid="_823234" name="dissociation of RAF_RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_RAFK_1_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_1_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> d1a </ci>
+              <ci> S_RAFK_1_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="d1a" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction279" metaid="_823304" name="phosphorylation of RAF on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_823304">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0000185"/>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0008349"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_RAFK_1_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_1_m1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1 </ci>
+              <ci> S_RAFK_1_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction280" metaid="_823374" name="binding of RAF and RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_1_0_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_RAFK_1_0_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1a </ci>
+              <ci> RAFK </ci>
+              <ci> S_1_0_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1a" value="100"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction281" metaid="_823444" name="dissociation of RAF_RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_RAFK_1_0_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_1_0_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> d1a </ci>
+              <ci> S_RAFK_1_0_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="d1a" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction282" metaid="_823514" name="phosphorylation of RAF on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_823514">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0000185"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_RAFK_1_0_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_1_0_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1 </ci>
+              <ci> S_RAFK_1_0_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction283" metaid="_823584" name="binding of RAF and RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_1_1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_RAFK_1_1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1a </ci>
+              <ci> RAFK </ci>
+              <ci> S_1_1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1a" value="100"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction284" metaid="_823654" name="dissociation of RAF_RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_RAFK_1_1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_1_1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> d1a </ci>
+              <ci> S_RAFK_1_1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="d1a" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction285" metaid="_823724" name="phosphorylation of RAF on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_823724">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0000185"/>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0008349"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_RAFK_1_1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_1_1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1 </ci>
+              <ci> S_RAFK_1_1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction286" metaid="_823794" name="binding of RAF and RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_1_2_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_RAFK_1_2_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1a </ci>
+              <ci> RAFK </ci>
+              <ci> S_1_2_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1a" value="100"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction287" metaid="_823864" name="dissociation of RAF_RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_RAFK_1_2_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_1_2_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> d1a </ci>
+              <ci> S_RAFK_1_2_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="d1a" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction288" metaid="_823934" name="phosphorylation of RAF on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_823934">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0000185"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_RAFK_1_2_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_1_2_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1 </ci>
+              <ci> S_RAFK_1_2_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction289" metaid="_824004" name="binding of RAF and RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_2_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_RAFK_2_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1a </ci>
+              <ci> RAFK </ci>
+              <ci> S_2_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1a" value="100"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction290" metaid="_824074" name="dissociation of RAF_RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_RAFK_2_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_2_m1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> d1a </ci>
+              <ci> S_RAFK_2_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="d1a" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction291" metaid="_824144" name="phosphorylation of RAF on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_824144">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0000185"/>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0008349"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_RAFK_2_m1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_2_m1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1 </ci>
+              <ci> S_RAFK_2_m1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction292" metaid="_824218" name="binding of RAF and RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_2_0_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_RAFK_2_0_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1a </ci>
+              <ci> RAFK </ci>
+              <ci> S_2_0_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1a" value="100"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction293" metaid="_824284" name="dissociation of RAF_RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_RAFK_2_0_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_2_0_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> d1a </ci>
+              <ci> S_RAFK_2_0_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="d1a" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction294" metaid="_824354" name="phosphorylation of RAF on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_824354">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0000185"/>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0008349"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_RAFK_2_0_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_2_0_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1 </ci>
+              <ci> S_RAFK_2_0_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction295" metaid="_824424" name="binding of RAF and RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_2_1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_RAFK_2_1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1a </ci>
+              <ci> RAFK </ci>
+              <ci> S_2_1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1a" value="100"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction296" metaid="_824496" name="dissociation of RAF_RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_RAFK_2_1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_2_1_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> d1a </ci>
+              <ci> S_RAFK_2_1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="d1a" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction297" metaid="_824564" name="phosphorylation of RAF on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_824564">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0000185"/>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0008349"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_RAFK_2_1_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_2_1_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1 </ci>
+              <ci> S_RAFK_2_1_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction298" metaid="_824634" name="binding of RAF and RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_2_2_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="S_RAFK_2_2_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1a </ci>
+              <ci> RAFK </ci>
+              <ci> S_2_2_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1a" value="100"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction299" metaid="_824704" name="dissociation of RAF_RAFK" reversible="false">
+        <listOfReactants>
+          <speciesReference species="S_RAFK_2_2_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_2_2_0"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> d1a </ci>
+              <ci> S_RAFK_2_2_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="d1a" value="0"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+      <reaction id="Reaction300" metaid="_824774" name="phosphorylation of RAF on scaffold" reversible="false">
+        <annotation>
+<rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#">
+<rdf:Description rdf:about="#_824774">
+<dc:relation>
+<rdf:Bag>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0000185"/>
+<rdf:li rdf:resource="http://www.geneontology.org/#GO:0008349"/>
+<rdf:li rdf:resource="http://www.ebi.ac.uk/IntEnz/#EC 2.7.1.37"/>
+</rdf:Bag>
+</dc:relation>
+</rdf:Description>
+</rdf:RDF>
+</annotation>
+<listOfReactants>
+          <speciesReference species="S_RAFK_2_2_0"/>
+        </listOfReactants>
+        <listOfProducts>
+          <speciesReference species="RAFK"/>
+          <speciesReference species="S_2_2_1"/>
+        </listOfProducts>
+        <kineticLaw>
+          <math xmlns="http://www.w3.org/1998/Math/MathML">
+            <apply>
+              <times/>
+              <ci> k1 </ci>
+              <ci> S_RAFK_2_2_0 </ci>
+            </apply>
+          </math>
+          <listOfParameters>
+            <parameter id="k1" value="0.1"/>
+          </listOfParameters>
+        </kineticLaw>
+      </reaction>
+    </listOfReactions>
+  </model>
+</sbml>
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_EXAMPLES/Glycolysis.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_EXAMPLES/Glycolysis.txt
new file mode 100644
index 0000000000000000000000000000000000000000..cdb4dbed96326ba68a521e8cb60ba4719a9557a0
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_EXAMPLES/Glycolysis.txt
@@ -0,0 +1,172 @@
+********** MODEL NAME
+GlycolysisModel
+
+********** MODEL NOTES
+<h1>Full-scale model of glycolysis in Saccharomyces cerevisiae</h1>
+F. Hynne, S. Dano, and PG, Sorensen<br>
+Biophysical Chemistry 94 (2001) 121-163<p>
+
+Units in minutes and mM, Stiff intergrator should be used<p>
+
+Initialconditions do not give a steady-state, but a state-that allows
+to see the oscillations when simulating.
+
+In the ODES /yvol has been exchanged against 0.0169491525423729*
+in order to be able to determine the stoichiometric matrix
+
+********** MODEL STATES
+d/dt(Glcx) = inGlc-0.0169491525423729*GlcTrans
+d/dt(Glc) = GlcTrans-HK
+d/dt(ATP) = -HK-PFK+lpPEP+PK-storage-consum-AK
+d/dt(G6P) = HK-PGI-storage
+d/dt(ADP) = HK+PFK-lpPEP-PK+storage+consum+2*AK
+d/dt(F6P) = PGI-PFK
+d/dt(FBP) = PFK-ALD
+d/dt(GAP) = ALD+TIM-GAPDH
+d/dt(DHAP) = ALD-TIM-lpGlyc
+d/dt(NADplus) = -GAPDH+ADH+lpGlyc
+d/dt(BPG) = GAPDH-lpPEP
+d/dt(NADH) = GAPDH-ADH-lpGlyc
+d/dt(PEP) = lpPEP-PK
+d/dt(Pyr) = PK-PDC
+d/dt(ACA) = PDC-ADH-difACA
+d/dt(EtOH) = ADH-difEtOH
+d/dt(EtOHx) = 0.0169491525423729*difEtOH-outEtOH
+d/dt(Glyc) = lpGlyc-difGlyc
+d/dt(Glycx) = 0.0169491525423729*difGlyc-outGlyc
+d/dt(ACAx) = 0.0169491525423729*difACA-outACA-lacto
+d/dt(CNxminus) = -lacto+inCN
+d/dt(AMP) = -AK
+
+Glcx(0) = 2.8024
+Glc(0) = 1.1689
+ATP(0) = 2.1568
+G6P(0) = 4.4873
+ADP(0) = 1.4667
+F6P(0) = 0.5250
+FBP(0) = 4.5826
+GAP(0) = 0.1139
+DHAP(0) = 2.9386
+NADplus(0) = 0.6589
+BPG(0) = 0.0003
+NADH(0) = 0.3211
+PEP(0) = 0.0403
+Pyr(0) = 14.4864
+ACA(0) = 1.5385
+EtOH(0) = 19.4498
+EtOHx(0) = 16.6474
+Glyc(0) = 4.3142
+Glycx(0) = 1.7352
+ACAx(0) = 1.3271
+CNxminus(0) = 5.1928
+AMP(0) = 0.3065
+
+********** MODEL PARAMETERS
+yvol = 59 % volume ratio
+k0 = 0.048 % specific flow rate at bifurcation
+Glcx0 = 20 % mixed flow concentration, glucose
+CNxminus0 = 5.6 % mixed flow concentration, cyanide
+
+V2m = 1.01496e3
+V3m = 5.17547e1
+V4m = 4.96042e2
+V5m = 4.54327e1
+V6f = 2.20782e3
+V6r = 1.10391e4
+V7m = 1.16365e2
+V8m = 8.33858e2
+k9f = 4.43866e5
+k9r = 1.52862e3
+V10m = 3.43096e2
+V11m = 5.31328e1
+V12m = 8.98023e1
+k13 = 1.67200e1
+V15m = 8.14797e1
+k16 = 1.9
+k18 = 2.47e1
+k20 = 2.83828e-3
+k22 = 2.25932
+k23 = 3.20760
+k24f = 4.32900e2
+k24r = 1.33333e2
+K2Glc = 1.7
+K2IG6P = 1.2
+K2IIG6P = 7.2
+P2 = 1
+K3ATP = 0.1
+K3Glc = 0
+K3DGlc = 0.37
+K4G6P = 0.8
+K4F6P = 0.15
+K4eq = 0.13
+K5 = 0.021
+kappa5 = 0.15
+K6eq = 0.081
+K6FBP = 0.3
+K6GAP = 4.0
+K6DHAP = 2.0
+K6IGAP = 10.0
+K7DHAP = 1.23
+K7GAP = 1.27
+K7eq = 0.055
+K8GAP = 0.6
+K8BPG = 0.01
+K8NAD = 0.1
+K8NADH = 0.06
+K8eq = 0.0055
+K10ADP = 0.17
+K10PEP = 0.2
+K11 = 0.3
+K12ACA = 0.71
+K12NADH = 0.1
+K15NADH = 0.13
+K15DHAP = 25
+K15INADH = 0.034
+K15INAD = 0.13
+
+********** MODEL VARIABLES
+GlcTransF = V2m*(Glcx/K2Glc)/(1+ Glcx/K2Glc+ (P2*Glcx/K2Glc+1) / (P2*Glc/K2Glc+1)*(1+ (Glc/K2Glc)+ (G6P/K2IG6P)+ (Glc*G6P/(K2Glc*K2IIG6P))))
+GlcTransR = V2m*(Glc/K2Glc)/(1+Glc/K2Glc+(P2*Glc/K2Glc+1)/(P2*Glcx/K2Glc+1)*(1+Glcx/K2Glc)+G6P/K2IG6P+Glc*G6P / (K2Glc*K2IIG6P))
+HKF = V3m * ATP * Glc / (K3DGlc*K3ATP + K3Glc * ATP + K3ATP * Glc + Glc * ATP)
+PGIF = V4m * G6P / (K4G6P + G6P + (K4G6P/K4F6P)*F6P)
+PGIR = V4m * (F6P/K4eq) / (K4G6P + G6P + (K4G6P/K4F6P)*F6P)
+PFKF = V5m * (F6P*F6P) / (K5*(1 + kappa5*((ATP*ATP)/(AMP*AMP))) +(F6P*F6P))
+ALDden = K6FBP + FBP + (GAP * K6DHAP * V6f) / (K6eq * V6r) + (DHAP * K6GAP * V6f) / (K6eq * V6r) + (FBP * GAP) / K6IGAP + (GAP * DHAP * V6f) / (K6eq * V6r)
+ALDF = (V6f * FBP) / ALDden
+ALDR = V6f * (GAP * DHAP) / K6eq / ALDden 
+TIMden = K7DHAP + DHAP + (K7DHAP/K7GAP) * GAP
+TIMF = V7m * DHAP / TIMden
+TIMR = V7m * GAP / K7eq / TIMden
+GAPDHden = K8GAP * K8NAD * (1 + (GAP/K8GAP) + (BPG/K8BPG)) * (1 + (NADplus/K8NAD) + (NADH/K8NADH)) 
+GAPDHF = V8m * GAP * NADplus / GAPDHden
+GAPDHR = V8m * BPG * NADH / K8eq / GAPDHden
+lpGlycF = V15m * DHAP / (K15DHAP * (1 + (K15INADH/NADH) * (1 + (NADplus/K15INAD)))+ DHAP * (1 + (K15NADH/NADH)*(1 + NADplus/K15INAD)))
+
+********** MODEL REACTIONS
+inGlc =k0*(Glcx0 - Glcx)
+GlcTrans = GlcTransF - GlcTransR
+HK = HKF
+PGI = PGIF - PGIR
+PFK = PFKF
+ALD = ALDF - ALDR
+TIM = TIMF - TIMR
+GAPDH = GAPDHF - GAPDHR
+lpPEP = k9f * BPG * ADP - k9r * PEP * ATP
+PK = (V10m * ADP * PEP) / ((K10PEP + PEP) * (K10ADP + ADP))
+PDC = V11m * Pyr / (K11 + Pyr)
+ADH = V12m * ACA * NADH / ((K12NADH + NADH) * (K12ACA + ACA))
+difEtOH = k13*(EtOH - EtOHx)
+outEtOH = k0*EtOHx
+lpGlyc = lpGlycF
+difGlyc = k16*(Glyc - Glycx)
+outGlyc = k0*Glycx
+difACA = k18*(ACA-ACAx)
+outACA = k0*ACAx
+lacto = k20*ACAx*CNxminus
+inCN = k0*(CNxminus0 - CNxminus)
+storage = k22*ATP*G6P
+consum = k23*ATP
+AK = k24f*AMP*ATP - k24r*ADP*ADP
+
+********** MODEL FUNCTIONS
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_EXAMPLES/NovakTysonModel.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_EXAMPLES/NovakTysonModel.txt
new file mode 100644
index 0000000000000000000000000000000000000000..5f2557bc08b2b2691eb17f15797a442ba7d1c050
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_EXAMPLES/NovakTysonModel.txt
@@ -0,0 +1,95 @@
+********** MODEL NAME
+Novak-Tyson Model
+
+********** MODEL NOTES
+Novak-Tyson cell cycle model, described in J. theor. Biol. (1998) 195, 69-85
+
+********** MODEL STATES
+d/dt(Cyclin) = R1-R2-R3+R15 {isSpecie::concentration} %state
+d/dt(YT) = R4-R5-R6-R7+R8+R3 {isSpecie::concentration} %state
+d/dt(PYT) = R5-R8-R9-R10+R11 {isSpecie::concentration} %state
+d/dt(PYTP) = R12-R11-R13-R14+R9 {isSpecie::concentration} %state
+d/dt(MPF) = R6-R4-R12-R15+R13 {isSpecie::concentration} %state
+d/dt(Cdc25P) = R16 {isSpecie::concentration} %state
+d/dt(Wee1P) = R17 {isSpecie::concentration} %state
+d/dt(IEP) = R18 {isSpecie::concentration} %state
+d/dt(APCstar) = R19 {isSpecie::concentration} %state
+
+Cyclin(0) = 0.017200
+YT(0) = 0.011600
+PYT(0) = 0.000900
+PYTP(0) = 0.019800
+MPF(0) = 0.073000
+Cdc25P(0) = 0.949900
+Wee1P(0) = 0.949900
+IEP(0) = 0.242000
+APCstar(0) = 0.313200
+
+********** MODEL PARAMETERS
+Ka = 0.1 {isParameter} %parameter
+Kb = 1  {isParameter}%parameter
+Kc = 0.01  {isParameter}%parameter
+Kd = 1  {isParameter}%parameter
+Ke = 0.1  {isParameter}%parameter
+Kf = 1  {isParameter}%parameter
+Kg = 0.01  {isParameter}%parameter
+Kh = 0.01  {isParameter}%parameter
+k1 = 0.01  {isParameter}%parameter
+k3 = 0.5  {isParameter}%parameter
+V2p = 0.005  {isParameter}%parameter
+V2pp = 0.25  {isParameter}%parameter
+V25p = 0.017  {isParameter}%parameter
+V25pp = 0.17  {isParameter}%parameter
+Vweep = 0.01  {isParameter}%parameter
+Vweepp = 1  {isParameter}%parameter
+kcak = 0.64  {isParameter}%parameter
+kpp = 0.004  {isParameter}%parameter
+kas = 2  {isParameter}%parameter
+kbs = 0.1  {isParameter}%parameter
+kcs = 0.13  {isParameter}%parameter
+kds = 0.13  {isParameter}%parameter
+kes = 2  {isParameter}%parameter
+kfs = 0.1  {isParameter}%parameter
+kgs = 2  {isParameter}%parameter
+khs = 0.15  {isParameter}%parameter
+
+
+********** MODEL VARIABLES
+k2 = V2p+APCstar*(V2pp-V2p)  {isParameter}%variable
+kwee = Vweepp+Wee1P*(Vweep-Vweepp)  {isParameter}%variable
+k25 = V25p+Cdc25P*(V25pp-V25p)  {isParameter}%variable
+Cdc25 = 1-Cdc25P {isSpecie::concentration}
+Wee1 = 1-Wee1P {isSpecie::concentration}
+IE = 1-IEP {isSpecie::concentration}
+APC = 1-APCstar {isSpecie::concentration}
+
+********** MODEL REACTIONS
+R1 = k1 %reaction
+R2 = k2*Cyclin %reaction
+R3 = k3*Cyclin %reaction
+R4 = kpp*MPF %reaction
+R5 = kwee*YT %reaction
+R6 = kcak*YT %reaction
+R7 = k2*YT %reaction
+R8 = k25*PYT %reaction
+R9 = kcak*PYT %reaction
+R10 = k2*PYT %reaction
+R11 = kpp*PYTP %reaction
+R12 = kwee*MPF %reaction
+R13 = k25*PYTP %reaction
+R14 = k2*PYTP %reaction
+R15 = k2*MPF %reaction
+R16 = kas*MPF*(Cdc25)/(Ka+Cdc25)-kbs*Cdc25P/(Kb+Cdc25P) {reversible} %reaction
+R17 = kes*MPF*(Wee1)/(Ke+Wee1)-kfs*Wee1P/(Kf+Wee1P) {reversible} %reaction
+R18 = kgs*MPF*(IE)/(Kg+IE)-khs*IEP/(Kh+IEP) {reversible} %reaction
+R19 = kcs*IEP*(APC)/(Kc+APC)-kds*APCstar/(Kd+APCstar) {reversible} %reaction
+
+
+********** MODEL FUNCTIONS
+
+
+********** MODEL EVENTS
+
+
+********** MODEL MATLAB FUNCTIONS
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_EXAMPLES/run_benchmark.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_EXAMPLES/run_benchmark.m
new file mode 100644
index 0000000000000000000000000000000000000000..b3dba3c2e3e5ef34ac1bddd37a2b8c68be2c66a4
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/_EXAMPLES/run_benchmark.m
@@ -0,0 +1,114 @@
+function run_benchmark
+% This benchmark compares the SBPD MEX simulation with the standard MATLAB 
+% simulation using the ODE15S integrator. The presence of the Systems 
+% Biology Toolbox 2 for MATLAB is required (www.sbtoolbox2.org). In order to 
+% run the third example also SBML toolbox
+% (http://sbml.org/software/sbmltoolbox/) needs to be installed. 
+%
+% Results on a DELL Latitude D610, Centrino 2GHz, 512MB/800MHz, Windows XP,
+% MATLAB 7.2. The MinGW compiler was used for the compilation of the MEX
+% files. 
+%
+% Comparison between the ODE15s and the SBPD performance
+% Model Nr     ODE15s average time [s]      SBPD average time [s]    Speedup
+%    1         3.45631                      0.02401                  144.0x
+%    2         3.44565                      0.06789                  50.8x
+%    3         0.73779                      0.02426                  30.4x
+%
+% Results on a DELL Latitude D610, Centrino 2GHz, 512MB/800MHz, Windows XP
+% Matlabs own 'lcc' compiler was used for the compilation of the MEX files.
+%
+% Comparison between the ODE15s and the SBPD performance
+% Model Nr     ODE15s average time [s]      SBPD average time [s]    Speedup
+%    1         3.44241                      0.06050                  56.9x
+%    2         3.44793                      0.20492                  16.8x
+%    3         0.74270                      0.08720                  8.5x
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GENERAL SETTINGS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ATOL = 1e-8;    % absolute tolerance
+RTOL = 1e-8;    % relative tolerance
+NRSIM = 20;    % number of simulations
+disp('Performance comparison between the ODE15s and the SBPD');
+disp('Model     ODE15s avg. time [s]      SBPD avg. time [s]    Speedup');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Model 1: (Novak Tyson Cell Cycle) 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+model = SBmodel('NovakTysonModel.txt');
+TEND = 1000;
+NRPOINTS = 1000;
+[avgtimeODE15s, avgtimeSBPD] = simulateModel(model,TEND,NRPOINTS,ATOL,RTOL,NRSIM,[]);
+disp(sprintf('   1      %1.5f                   %1.5f               %3.1fx',avgtimeODE15s, avgtimeSBPD, avgtimeODE15s/avgtimeSBPD));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Model 2: (22 state model of glycolytic oscillations in yeast) 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+model = SBmodel('Glycolysis.txt');
+TEND = 50;
+NRPOINTS = 200;
+[avgtimeODE15s, avgtimeSBPD] = simulateModel(model,TEND,NRPOINTS,ATOL,RTOL,NRSIM,[]);
+disp(sprintf('   2      %1.5f                   %1.5f               %3.1fx',avgtimeODE15s, avgtimeSBPD, avgtimeODE15s/avgtimeSBPD));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Model 3: (Model 14 from the Biomodels.net database) 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if exist('TranslateSBML'),
+    model = SBmodel('BIOMD14.xml');
+    TEND = 300;
+    NRPOINTS = 300;
+    [avgtimeODE15s, avgtimeSBPD] = simulateModel(model,TEND,NRPOINTS,ATOL,RTOL,NRSIM,[]);
+    disp(sprintf('   3      %1.5f                   %1.5f               %3.1fx',avgtimeODE15s, avgtimeSBPD, avgtimeODE15s/avgtimeSBPD));
+else
+    disp('Model 3 can not be run since the SBMLtoolbox (http://sbml.org/software/sbmltoolbox/) is not installed on your system.');
+end
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Delete temporary files
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+clear mex
+delete simfileSBPD.*
+delete simfileM.m
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Function performing the simulations
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [avgtimeODE15s, avgtimeSBPD] = simulateModel(model,TEND,NRPOINTS,ATOL,RTOL,NRSIM,MAXSTEP)
+% Simulation using MATLABs ODE15s solver
+SBcreateODEfile(model,'simfileM'); rehash;
+avgtime=0;
+if isempty(MAXSTEP),
+    options = odeset('RelTol',RTOL,'AbsTol',ATOL);
+else
+    options = odeset('RelTol',RTOL,'AbsTol',ATOL,'MaxStep',MAXSTEP);
+end
+inicond = simfileM;
+for k=1:NRSIM,
+    tic;
+    simdata = ode15s('simfileM',[0:TEND/NRPOINTS:TEND],inicond,options);
+    avgtime = avgtime+toc/NRSIM;
+end
+avgtimeODE15s = avgtime;
+% Simulation using SBPD
+SBPDmakeMEXmodel(model,'simfileSBPD');
+avgtime=0;
+options = [];
+options.reltol = RTOL;
+options.abstol = ATOL;
+options.maxstep = MAXSTEP;
+inicond = simfileSBPD;
+for k=1:NRSIM,
+    tic;
+    simdata = simfileSBPD([0:TEND/NRPOINTS:TEND],inicond,[],options);
+    avgtime = avgtime+toc/NRSIM;
+end 
+avgtimeSBPD = avgtime;
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/auxiliary/academicWarningSBPD.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/auxiliary/academicWarningSBPD.m
new file mode 100644
index 0000000000000000000000000000000000000000..e8c18882e3baba8ab82ba25e3dfa49e257f986cc
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/auxiliary/academicWarningSBPD.m
@@ -0,0 +1,26 @@
+% Information:
+% ============
+% Copyright (C) 2005-2013 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+FLAGacademicWarning = 1;
+
+if FLAGacademicWarning,
+warning(sprintf('Function is located in the "_ACADEMIC" folder of the SBPD package.\n\nThis means:\n    - No unit tests have been developed for this function\n    - This function is not subject to validation requirements for use\n      in clinical drug development projects\n    - This function should NOT be used in clinical drug development projects\n      where validated software is required\n    - You can still use this function for academic or exploratory purposes\n\nIf you do not want to get this message everytime you run this function,\nplease set the flag in the "academicWarningSBPD.m" file from 1 to 0.\n\n'));
+end
+      
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/auxiliary/lookforSBPD.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/auxiliary/lookforSBPD.m
new file mode 100644
index 0000000000000000000000000000000000000000..dbee8bbd5c4b87ad4cc313c450100b0e23989efa
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/auxiliary/lookforSBPD.m
@@ -0,0 +1,56 @@
+function [] = lookforSBPD(text)
+% lookforSBPD: searches all m-files in the SBPD folder tree for the 
+% text given as argument. It displays the filenames in which the text
+% appears and additionally opens the files in the editor.
+
+% Information:
+% ============
+% Copyright (C) 2005-2013 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+old = pwd;
+cd([fileparts(which('installSB')) '/..']);
+recurseFolder('SBPD',text);
+cd(old);
+return
+
+
+function recurseFolder(folder,text)
+% change folder
+cd(folder);
+% check all m files in folder for the text
+mfiles = dir('*.m');
+for k = 1:length(mfiles),
+    % read file
+    content = fileread(mfiles(k).name);
+    if strfind(content,text),
+        disp(mfiles(k).name);
+        edit(mfiles(k).name);
+    else
+%        edit(mfiles(k).name);
+    end
+end
+% recurse in all subfolders
+allfiles = dir;
+for k = 1:length(allfiles),
+    if ~strcmp(allfiles(k).name,'.git') && ~strcmp(allfiles(k).name,'..') && ~strcmp(allfiles(k).name,'.') && allfiles(k).isdir == 1,
+        recurseFolder(allfiles(k).name,text);
+    end
+end
+% up we go
+cd ..
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/installSBPD.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/installSBPD.m
new file mode 100644
index 0000000000000000000000000000000000000000..a9eee212c383f3aa429ce2db0065a43b33f4addb
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/installSBPD.m
@@ -0,0 +1,93 @@
+function [] = installSBPD()
+% installSBPD
+% Installation function for the SBPD package. 
+%
+%       installSBPD
+%
+% This adds the SBPD and all subdirectories to the MATLAB path.
+% Additionally, the command builds the necessary libraries.
+
+% Information:
+% ============
+% Copyright (C) 2005-2013 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check that installSBPD is started in the right folder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+currentDir = pwd;
+installSBPDDir = fileparts(which('installSBPD.m'));
+if ~strcmp(currentDir,installSBPDDir),
+    error('Run the ''installSBPD'' script from the folder where it is located.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check that correct local path (network paths are not allowed)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp(currentDir(1:2),'\\'),
+    error(sprintf('The installation can not be run from a network path (\\\\...).\nPlease run the installation from a local path.'));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if SBPD already installed
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBPDver = ver('SBPD');
+if length(SBPDver) >= 1,
+    error('You seem to already have an installation of SBPD. Please use "restoredefaultpath" before installing a different version.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add SBPD to the path 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+addpath(genpath(pwd));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Compile and install the needed packages 
+% Compilation is done for Unix AND Windows systems
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+PATH_SBPD = pwd();
+if ~ispc,
+    cd(fileparts(which('buildCVODElibunix.m')));
+    buildCVODElibunix
+    cd(PATH_SBPD);
+else
+    cd(fileparts(which('buildCVODElib.m')));
+    buildCVODElib
+    cd(PATH_SBPD);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Output license information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+disp(sprintf('SBPD for SBTOOLBOX2'));
+disp('Copyright (C) 2008-2013 Henning Schmidt, info@sbtoolbox2.org');
+disp(' ');
+disp(sprintf('This program is Free Open Source Software: you can redistribute it and/or modify '));
+disp(sprintf('it under the terms of the GNU General Public License as published by '));
+disp(sprintf('the Free Software Foundation, either version 3 of the License, or '));
+disp(sprintf('(at your option) any later version. '));
+disp(sprintf(' '));
+disp(sprintf('This program is distributed in the hope that it will be useful, '));
+disp(sprintf('but WITHOUT ANY WARRANTY; without even the implied warranty of '));
+disp(sprintf('MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the '));
+disp(sprintf('GNU General Public License for more details. '));
+disp(sprintf(' '));
+disp(sprintf('You should have received a copy of the GNU General Public License '));
+disp(sprintf('along with this program. If not, see <http://www.gnu.org/licenses/>.'));
+disp(sprintf(' '));
+disp(sprintf(' '));
+disp(sprintf(' '));
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/license.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/license.txt
new file mode 100644
index 0000000000000000000000000000000000000000..65e0ebf47690538cf3e698281babeb102a06b81f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/license.txt
@@ -0,0 +1,674 @@
+					 GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/allkineticlaws.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/allkineticlaws.m
new file mode 100644
index 0000000000000000000000000000000000000000..fba31c81f29dac299e25756dbe0d710db82371a6
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/allkineticlaws.m
@@ -0,0 +1,119 @@
+allLawsNames = {    
+    'kin_allosteric_inihib_empirical_rev'
+    'kin_allosteric_inihib_mwc_irr'
+    'kin_catalytic_activation_irr'
+    'kin_catalytic_activation_rev'
+    'kin_comp_inihib_irr'
+    'kin_comp_inihib_rev'
+    'kin_constantflux'
+    'kin_degradation'
+    'kin_hill_1_modifier_rev'
+    'kin_hill_2_modifiers_rev'
+    'kin_hill_cooperativity_irr'
+    'kin_hill_rev'
+    'kin_hyperbolic_modifier_irr'
+    'kin_hyperbolic_modifier_rev'
+    'kin_iso_uni_uni_rev'
+    'kin_mass_action_irr'
+    'kin_mass_action_rev'
+    'kin_michaelis_menten_irr'
+    'kin_michaelis_menten_rev'
+    'kin_mixed_activation_irr'
+    'kin_mixed_activation_rev'
+    'kin_mixed_inihib_irr'
+    'kin_mixed_inihib_rev'
+    'kin_noncomp_inihib_irr'
+    'kin_noncomp_inihib_rev'
+    'kin_ordered_bi_bi_rev'
+    'kin_ordered_bi_uni_rev'
+    'kin_ordered_uni_bi_rev'
+    'kin_ping_pong_bi_bi_rev'
+    'kin_specific_activation_irr'
+    'kin_specific_activation_rev'
+    'kin_substrate_activation_irr'
+    'kin_substrate_inihib_irr'
+    'kin_substrate_inihib_rev'
+    'kin_uncomp_inihib_irr'
+    'kin_uncomp_inihib_rev'
+    'kin_uni_uni_rev'
+};
+
+allLawsArguments = {
+{'Vf','substrate','Kms','Vr','product','Kmp','inhibitor','Ki','n'}
+{'V','substrate','Ks','n','L','inhibitor','Ki'}
+{'V','substrate','activator','Kms','Ka'}
+{'Vf','substrate','Kms','Vr','product','Kmp','activator','Ka'}
+{'V','substrate','Km','inhibitor','Ki'}
+{'Vf','substrate','Kms','Vr','product','Kmp','inhibitor','Ki'}
+{'v'}
+{'kdeg','substrate'}
+{'Vf','substrate','Shalve','product','Keq','Phalve','h','modifier','Mhalve','alpha'}
+{'Vf','substrate','Shalve','product','Keq','Phalve','h','modifierA','MAhalve','modifierB','MBhalve','alphaA','alphaB','alphaAB'}
+{'V','substrate','h','Shalve'}
+{'Vf','substrate','Shalve','product','Keq','Phalve','h'}
+{'V','substrate','b','modifier','a','Kd','Km'}
+{'Vf','substrate','Kms','Vr','product','Kmp','b','modifier','a','Kd'}
+{'Vf','substrate','product','Keq','Kii','Kms','Kmp'}
+{'k','substrate'}
+{'k1','substrate','k2','product'}
+{'V','substrate','Km'}
+{'Vf','substrate','Kms','Vr','product','Kmp'}
+{'V','substrate','activator','Kms','Kas','Kac'}
+{'Vf','substrate','Kms','Vr','product','Kmp','activator','Kas','Kac'}
+{'V','substrate','Km','inhibitor','Kis','Kic'}
+{'Vf','substrate','Kms','Vr','product','Kmp','inhibitor','Kis','Kic'}
+{'V','substrate','Km','inhibitor','Ki'}
+{'Vf','substrate','Kms','Vr','product','Kmp','inhibitor','Ki'}
+{'Vf','substratea','substrateb','productp','productq','Keq','Kip','Kma','Kmb','Kia','Vr','Kmq','Kmp','Kib'}
+{'Vf','substratea','substrateb','product','Keq','Kma','Kmb','Vr','Kmp','Kia'}
+{'Vf','substrate','productp','productq','Keq','Kms','Kip','Vr','Kmq','Kmp'}
+{'Vf','substratea','substrateb','productp','productq','Keq','Kiq','Kma','Kmb','Vr','Kmq','Kia','Kmp'}
+{'V','substrate','activator','Kms','Ka'}
+{'Vf','substrate','Kms','Vr','product','Kmp','activator','Ka'}
+{'V','substrate','Ksa','Ksc'}
+{'V','substrate','Km','Ki'}
+{'Vf','substrate','Kms','Vr','product','Kmp','Ki'}
+{'V','substrate','Km','inhibitor','Ki'}
+{'Vf','substrate','Kms','Vr','product','Kmp','inhibitor','Ki'}
+{'Vf','substrate','product','Keq','Kms','Kmp'}
+};
+
+allLawsFormulas = {
+'((Vf*substrate/Kms - Vr*product/Kmp) / (1 + substrate/Kms + product/Kmp + (inhibitor/Ki)^n))'
+'(V*substrate*(Ks+substrate)^(n-1) / ( L*(Ks*(1+inhibitor/Ki))^n + (Ks+substrate)^n ))'
+'(V*substrate*activator / ( (Kms + substrate)*(Ka+activator) )'
+'(( Vf*substrate/Kms - Vr*product/Kmp )*activator / ( (1+substrate/Kms+product/Kmp)*(Ka+activator) ))'
+'(V*substrate / ( Km*(1+inhibitor/Ki) + substrate ))'
+'((Vf*substrate/Kms - Vr*product/Kmp) / ( 1+substrate/Kms+product/Kmp+inhibitor/Ki ))'
+'(v)'
+'(kdeg*substrate)'
+'(Vf*substrate/Shalve*(1-product/(substrate*Keq))*(substrate/Shalve+product/Phalve)^(h-1) / ( (1+(modifier/Mhalve)^h)/(1+alpha*(modifier/Mhalve)^h)+(substrate/Shalve + product/Phalve)^h ))'
+'(Vf*substrate/Shalve*(1-product/(substrate*Keq))*(substrate/Shalve+product/Phalve)^(h-1) / ( (1+(modifierA/MAhalve)^h + 1+(modifierB/MBhalve)^h) / ( 1+alphaA*(modifierA/MAhalve)^h+alphaB*(modifierB/MBhalve)^h+alphaA*alphaB*alphaAB*(modifierA/MAhalve)^h*(modifierB/MBhalve)^h ) + (substrate/Shalve + product/Phalve)^h ))'
+'(V*substrate^h / ( Shalve^h + substrate^h ))'
+'(Vf*substrate/Shalve*(1-product/(substrate*Keq))*(substrate/Shalve+product/Phalve)^(h-1) / ( 1+(substrate/Shalve + product/Phalve)^h ))'
+'(V*substrate*(1+b*modifier/(a*Kd)) / ( Km*(1+modifier/Kd) + substrate*(1+modifier/(a*Kd)) ))'
+'((Vf*substrate/Kms - Vr*product/Kmp)*(1+b*modifier/(a*Kd)) / ( 1+modifier/Kd+(substrate/Kms+product/Kmp)*(1+modifier/(a*Kd)) ))'
+'(Vf*(substrate-product/Keq) / ( substrate*(1+product/Kii) + Kms*(1+product/Kmp) ))'
+'(k*substrate)'
+'(k1*substrate-k2*product)'
+'(V*substrate / ( Km + substrate ))'
+'((Vf*substrate/Kms+Vr*product/Kmp) / ( 1+substrate/Kms+product/Kmp ) )'
+'(V*substrate*activator / ( Kms*(Kas+activator) + substrate*(Kac+activator) ))'
+'((Vf*substrate/Kms - Vr*product/Kmp)*activator / ( Kas+activator+(substrate/Kms+product/Kmp)*(Kac+activator) ))'
+'(V*substrate / ( (Km*(1+inhibitor/Kis) + substrate*(1+inhibitor/Kic) ))'
+'((Vf*substrate/Kms - Vr*product/Kmp) / ( 1+inhibitor/Kis+(substrate/Kms+product/Kmp)*(1+inhibitor/Kic) ))'
+'(V*substrate / ( (Km+substrate)*(1+inhibitor/Ki) ))'
+'((Vf*substrate/Kms-Vr*product/Kmp) / ( (1+substrate/Kms+product/Kmp)*(1+inhibitor/Ki) ))'
+'(Vf*(substratea*substrateb-productp*productq/Keq) / (substratea*substrateb*(1+productp/Kip) + Kma*substrateb + Kmb*(substratea+Kia)+Vf/(Vr*Keq)*(Kmq*productp*(1+substratea/Kia) + productq*(Kmp*(1+Kia*substrateb/(Kma*Kmb))+productp*(1+substrateb/Kib))) ))'
+'(Vf*(substratea*substrateb-product/Keq) / ( substratea*substrateb+Kma*substrateb+Kmb*substratea+Vf/(Vr*Keq)*(Kmp+product*(1+substratea/Kia)) ))'
+'(Vf*(substrate-productp*productq/Keq) / ( Kms+substrate*(1+productp/Kip)+Vf/(Vr*Keq)*(Kmq*productp+Kmp*productq+productp*productq) );)'
+'(Vf*( substratea*substrateb-productp*productq/Keq ) / (substratea*substrateb*(1+productq/Kiq)+Kma*substrateb+Kmb*substratea+Vf/(Vr*Keq)*(Kmq*productp*(1+substratea/Kia)+productq*(Kmp+productp))))'
+'(V*substrate*activator/( Kms*Ka+(Kms+substrate)*activator )'
+'(( Vf*substrate/Kms-Vr*product/Kmp )*activator / ( Ka+(1+substrate/Kms+product/Kmp)*activator ))'
+'(V*(substrate/Ksa)^2 / ( 1+substrate/Ksc+substrate/Ksa+(substrate/Ksa)^2 ))'
+'(V*substrate / ( Km + substrate + Km*(substrate/Ki)^2 ))'
+'((Vf*substrate/Kms-Vr*product/Kmp) / ( 1+substrate/Kms+product/Kmp+(substrate/Ki)^2 ))'
+'(V*substrate / ( Km + substrate*(1+inhibitor/Ki) ))'
+'(( Vf*substrate/Kms-Vr*product/Kmp ) / ( 1+(substrate/Kms+product/Kmp)*(1+inhibitor/Ki) ))'
+'(Vf*( substrate-product/Keq ) / ( substrate+Kms*(1+product/Kmp) ))'
+};
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/getkinformulaSBPD.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/getkinformulaSBPD.m
new file mode 100644
index 0000000000000000000000000000000000000000..21f7935fba2f1988d4d344139572531b88599e93
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/getkinformulaSBPD.m
@@ -0,0 +1,53 @@
+function [R] = getkinformulaSBPD(R)
+% getkinformulaSBPD: auxiliary function to convert rate law functions to
+% formulas.
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+Rorig = R;
+R = ['#' R '#'];
+% Load names of all kinetic laws
+allkineticlaws
+
+% Check if kinetic rate expression present
+found = 0;
+for k=1:length(allLawsNames),
+    if ~isempty(regexp(R,['\W' allLawsNames{k} '\W'])),
+        % it is present
+        % get the arguments of the reaction
+        ratelawname = allLawsNames{k};
+        indexstart = strfind(R,ratelawname);
+        arguments = R(indexstart+length(ratelawname):end);
+        parentheses = 0;
+        for k2=1:length(arguments),
+            if arguments(k2) == '(',
+                parentheses = parentheses+1;
+            end
+            if arguments(k2) == ')',
+                parentheses = parentheses-1;
+                if parentheses == 0,
+                    break;
+                end
+            end
+        end
+        arguments = arguments(2:k2-1);
+        arguments = explodePCSB(arguments);
+        preLaw = R(1:indexstart-1);
+        postLaw = R(k2+indexstart+length(ratelawname):end);
+        R = [preLaw(2:end) allLawsFormulas{k} postLaw(1:end-1)];
+        % finally exchange the argument names
+        changearguments = allLawsArguments{k};
+        R = regexprep(R,'(\W)',' $1 ');
+        for k2=1:length(arguments),
+            R = regexprep(R,['\W' changearguments{k2} '\W'], arguments{k2});
+        end
+        R = regexprep(R,' ','');
+        found = 1;
+    end
+end
+if found == 0,
+    R = Rorig;
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_allosteric_inihib_empirical_rev.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_allosteric_inihib_empirical_rev.m
new file mode 100644
index 0000000000000000000000000000000000000000..4715965257339ec1419d46c80eddb4d3892f9688
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_allosteric_inihib_empirical_rev.m
@@ -0,0 +1,24 @@
+function [R] = kin_allosteric_inihib_empirical_rev(Vf,substrate,Kms,Vr,product,Kmp,inhibitor,Ki,n)
+% kin_allosteric_inihib_empirical_rev: Allosteric inhibition (reversible) kinetics
+% 
+% Application restrictions: 
+% =========================
+%   - Only reversible
+%   - exactly 1 substrate
+%   - exactly 1 product
+%
+% USAGE:
+% ======
+% R = kin_allosteric_inihib_empirical_rev(Vf,substrate,Kms,Vr,product,Kmp,inhibitor,Ki,n)
+%
+% Output Arguments:
+% =================
+% R = (Vf*substrate/Kms - Vr*product/Kmp) / (1 + substrate/Kms + product/Kmp + (inhibitor/Ki)^n)
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = (Vf*substrate/Kms - Vr*product/Kmp) / (1 + substrate/Kms + product/Kmp + (inhibitor/Ki)^n);
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_allosteric_inihib_mwc_irr.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_allosteric_inihib_mwc_irr.m
new file mode 100644
index 0000000000000000000000000000000000000000..383670c8dda34e0acd5ea15066af5deaa36dad53
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_allosteric_inihib_mwc_irr.m
@@ -0,0 +1,23 @@
+function [R] = kin_allosteric_inihib_mwc_irr(V,substrate,Ks,n,L,inhibitor,Ki)
+% kin_allosteric_inihib_mwc_irr: Allosteric inhibition (irreversible) kinetics
+%
+% Application restrictions: 
+% =========================
+%   - Only irreversible
+%   - exactly 1 substrate
+%
+% USAGE:
+% ======
+% R = kin_allosteric_inihib_mwc_irr(V,substrate,Ks,n,L,inhibitor,Ki)
+%
+% Output Arguments:
+% =================
+% R = V*substrate*(Ks+substrate)^(n-1) / ( L*(Ks*(1+inhibitor/Ki))^n + (Ks+substrate)^n )
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = V*substrate*(Ks+substrate)^(n-1) / ( L*(Ks*(1+inhibitor/Ki))^n + (Ks+substrate)^n );
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_catalytic_activation_irr.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_catalytic_activation_irr.m
new file mode 100644
index 0000000000000000000000000000000000000000..ebdecc977dbc0b48794cda1292be7dd08fa0704e
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_catalytic_activation_irr.m
@@ -0,0 +1,23 @@
+function [R] = kin_catalytic_activation_irr(V,substrate,activator,Kms,Ka)
+% kin_catalytic_activation_irr: Catalytic activation (irreversible) kinetics
+%
+% Application restrictions: 
+% =========================
+%   - Only irreversible
+%   - exactly 1 substrate
+%
+% USAGE:
+% ======
+% R = kin_catalytic_activation_irr(V,substrate,activator,Kms,Ka)
+%
+% Output Arguments:
+% =================
+% R = V*substrate*activator / ( (Kms + substrate)*(Ka+activator) )
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = V*substrate*activator / ( (Kms + substrate)*(Ka+activator) )
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_catalytic_activation_rev.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_catalytic_activation_rev.m
new file mode 100644
index 0000000000000000000000000000000000000000..347c1a00e4faad6a2f056a2fd4532e5d8167bf4f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_catalytic_activation_rev.m
@@ -0,0 +1,24 @@
+function [R] = kin_catalytic_activation_rev(Vf,substrate,Kms,Vr,product,Kmp,activator,Ka)
+% kin_catalytic_activation_rev: Catalytic activation (reversible) kinetics
+%
+% Application restrictions: 
+% =========================
+%   - Only reversible
+%   - exactly 1 substrate
+%   - exactly 1 product
+%
+% USAGE:
+% ======
+% R = kin_catalytic_activation_rev(Vf,substrate,Kms,Vr,product,Kmp,activator,Ka)
+%
+% Output Arguments:
+% =================
+% R = ( Vf*substrate/Kms - Vr*product/Kmp )*activator / ( (1+substrate/Kms+product/Kmp)*(Ka+activator) )
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = ( Vf*substrate/Kms - Vr*product/Kmp )*activator / ( (1+substrate/Kms+product/Kmp)*(Ka+activator) );
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_comp_inihib_irr.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_comp_inihib_irr.m
new file mode 100644
index 0000000000000000000000000000000000000000..8743be4ce7cdcfdb22e2cb43098942498dceedcb
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_comp_inihib_irr.m
@@ -0,0 +1,23 @@
+function [R] = kin_comp_inihib_irr(V,substrate,Km,inhibitor,Ki)
+% kin_comp_inihib_irr: Competitive inhibition (irreversible) kinetics
+%
+% Application restrictions: 
+% =========================
+%   - Only irreversible
+%   - exactly 1 substrate
+%
+% USAGE:
+% ======
+% R = kin_comp_inihib_irr(V,substrate,Km,inhibitor,Ki)
+%
+% Output Arguments:
+% =================
+% R = V*substrate / ( Km*(1+inhibitor/Ki) + substrate )
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = V*substrate / ( Km*(1+inhibitor/Ki) + substrate );
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_comp_inihib_rev.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_comp_inihib_rev.m
new file mode 100644
index 0000000000000000000000000000000000000000..583fa9eb5fbdecc9557d56004038d6ce4edb83fa
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_comp_inihib_rev.m
@@ -0,0 +1,24 @@
+function [R] = kin_comp_inihib_rev(Vf,substrate,Kms,Vr,product,Kmp,inhibitor,Ki)
+% kin_comp_inihib_rev: Competitive inhibition (reversible) kinetics
+%
+% Application restrictions: 
+% =========================
+%   - Only reversible
+%   - exactly 1 substrate
+%   - exactly 1 product
+%
+% USAGE:
+% ======
+% R = kin_comp_inihib_rev(Vf,substrate,Kms,Vr,product,Kmp,inhibitor,Ki)
+%
+% Output Arguments:
+% =================
+% R = (Vf*substrate/Kms - Vr*product/Kmp) / ( 1+substrate/Kms+product/Kmp+inhibitor/Ki )
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = (Vf*substrate/Kms - Vr*product/Kmp) / ( 1+substrate/Kms+product/Kmp+inhibitor/Ki );
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_constantflux.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_constantflux.m
new file mode 100644
index 0000000000000000000000000000000000000000..3e268daaa7b5859b1e7b5fe8b63a80d0cfc03bd1
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_constantflux.m
@@ -0,0 +1,22 @@
+function [R] = kin_constantflux(v)
+% kin_constantflux: Competitive inhibition (reversible) kinetics
+%
+% Application restrictions: 
+% =========================
+%   - Be careful that concentrations do not become negative!
+%
+% USAGE:
+% ======
+% R = kin_constantflux(v)
+%
+% Output Arguments:
+% =================
+% R = v
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = v;
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_degradation.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_degradation.m
new file mode 100644
index 0000000000000000000000000000000000000000..d694302e4c048a23e87750184987efc4ce1e5982
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_degradation.m
@@ -0,0 +1,23 @@
+function [R] = kin_degradation(kdeg,substrate)
+% kin_degradation: Linear degradation kinetics
+%
+% Application restrictions: 
+% =========================
+%   - Only irreversible
+%   - exactly 1 substrate
+%
+% USAGE:
+% ======
+% R = kin_degradation(kdeg,substrate)
+%
+% Output Arguments:
+% =================
+% R = kdeg*substrate
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = kdeg*substrate;
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_hill_1_modifier_rev.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_hill_1_modifier_rev.m
new file mode 100644
index 0000000000000000000000000000000000000000..3f90d4bd4ccc308b61c2eb99516ce422507c7a42
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_hill_1_modifier_rev.m
@@ -0,0 +1,23 @@
+function [R] = kin_hill_1_modifier_rev(Vf,substrate,Shalve,product,Keq,Phalve,h,modifier,Mhalve,alpha)
+% kin_hill_1_modifier_rev: Reversible Hill type kinetics with one modifier
+%
+% Application restrictions: 
+% =========================
+%   - Only reversible
+%   - exactly 1 substrate
+%   - exactly 1 product
+%
+% USAGE:
+% ======
+% R = kin_hill_1_modifier_rev(Vf,substrate,Shalve,product,Keq,Phalve,h,modifier,Mhalve,alpha)
+%
+% Output Arguments:
+% =================
+% R = Vf*substrate/Shalve*(1-product/(substrate*Keq))*(substrate/Shalve+product/Phalve)^(h-1) / ( (1+(modifier/Mhalve)^h)/(1+alpha*(modifier/Mhalve)^h)+(substrate/Shalve + product/Phalve)^h ) 
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = Vf*substrate/Shalve*(1-product/(substrate*Keq))*(substrate/Shalve+product/Phalve)^(h-1) / ( (1+(modifier/Mhalve)^h)/(1+alpha*(modifier/Mhalve)^h)+(substrate/Shalve + product/Phalve)^h );
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_hill_2_modifiers_rev.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_hill_2_modifiers_rev.m
new file mode 100644
index 0000000000000000000000000000000000000000..75c3236b16869e701eca83f19416ca1a666b3a9a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_hill_2_modifiers_rev.m
@@ -0,0 +1,23 @@
+function [R] = kin_hill_2_modifiers_rev(Vf,substrate,Shalve,product,Keq,Phalve,h,modifierA,MAhalve,modifierB,MBhalve,alphaA,alphaB,alphaAB)
+% kin_hill_2_modifiers_rev: Reversible Hill type kinetics with one modifier
+%
+% Application restrictions: 
+% =========================
+%   - Only reversible
+%   - exactly 1 substrate
+%   - exactly 1 product
+%
+% USAGE:
+% ======
+% R = kin_hill_2_modifiers_rev(Vf,substrate,Shalve,product,Keq,Phalve,h,modifierA,MAhalve,modifierB,MBhalve,alphaA,alphaB,alphaAB)
+%
+% Output Arguments:
+% =================
+% R = Vf*substrate/Shalve*(1-product/(substrate*Keq))*(substrate/Shalve+product/Phalve)^(h-1) / ( (1+(modifierA/MAhalve)^h + 1+(modifierB/MBhalve)^h) / ( 1+alphaA*(modifierA/MAhalve)^h+alphaB*(modifierB/MBhalve)^h+alphaA*alphaB*alphaAB*(modifierA/MAhalve)^h*(modifierB/MBhalve)^h ) + (substrate/Shalve + product/Phalve)^h ) 
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = Vf*substrate/Shalve*(1-product/(substrate*Keq))*(substrate/Shalve+product/Phalve)^(h-1) / ( (1+(modifierA/MAhalve)^h + 1+(modifierB/MBhalve)^h) / ( 1+alphaA*(modifierA/MAhalve)^h+alphaB*(modifierB/MBhalve)^h+alphaA*alphaB*alphaAB*(modifierA/MAhalve)^h*(modifierB/MBhalve)^h ) + (substrate/Shalve + product/Phalve)^h );
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_hill_cooperativity_irr.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_hill_cooperativity_irr.m
new file mode 100644
index 0000000000000000000000000000000000000000..fe7ce7487b72b2e7f46ccd514a62f07efec3836d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_hill_cooperativity_irr.m
@@ -0,0 +1,23 @@
+function [R] = kin_hill_cooperativity_irr(V,substrate,h,Shalve)
+% kin_hill_cooperativity_irr: Hill type (irreversible) kinetics
+%
+% Application restrictions: 
+% =========================
+%   - Only irreversible
+%   - exactly 1 substrate
+%
+% USAGE:
+% ======
+% R = kin_hill_cooperativity_irr(V,substrate,h,Shalve)
+%
+% Output Arguments:
+% =================
+% R = V*substrate^h / ( Shalve^h + substrate^h )
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = V*substrate^h / ( Shalve^h + substrate^h );
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_hill_rev.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_hill_rev.m
new file mode 100644
index 0000000000000000000000000000000000000000..867a79fe6ae502f5ab2c94ae11747efce1ddb92c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_hill_rev.m
@@ -0,0 +1,24 @@
+function [R] = kin_hill_rev(Vf,substrate,Shalve,product,Keq,Phalve,h)
+% kin_hill_rev: Hill type (reversible) kinetics
+%
+% Application restrictions: 
+% =========================
+%   - Only reversible
+%   - exactly 1 substrate
+%   - exactly 1 product
+%
+% USAGE:
+% ======
+% R = kin_hill_rev(Vf,substrate,Shalve,product,Keq,Phalve,h)
+%
+% Output Arguments:
+% =================
+% R = Vf*substrate/Shalve*(1-product/(substrate*Keq))*(substrate/Shalve+product/Phalve)^(h-1) / ( 1+(substrate/Shalve + product/Phalve)^h ) 
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org 
+
+R = Vf*substrate/Shalve*(1-product/(substrate*Keq))*(substrate/Shalve+product/Phalve)^(h-1) / ( 1+(substrate/Shalve + product/Phalve)^h );
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_hyperbolic_modifier_irr.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_hyperbolic_modifier_irr.m
new file mode 100644
index 0000000000000000000000000000000000000000..4c4770d74e3f6669d64776c5be73398422affa2d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_hyperbolic_modifier_irr.m
@@ -0,0 +1,23 @@
+function [R] = kin_hyperbolic_modifier_irr(V,substrate,b,modifier,a,Kd,Km)
+% kin_hyperbolic_modifier_irr: Hyperbolic modifier (irreversible) kinetics
+%
+% Application restrictions: 
+% =========================
+%   - Only irreversible
+%   - exactly 1 substrate
+%
+% USAGE:
+% ======
+% R = kin_hyperbolic_modifier_irr(V,substrate,b,modifier,a,Kd,Km)
+%
+% Output Arguments:
+% =================
+% R = V*substrate*(1+b*modifier/(a*Kd)) / ( Km*(1+modifier/Kd) + substrate*(1+modifier/(a*Kd)) )
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = V*substrate*(1+b*modifier/(a*Kd)) / ( Km*(1+modifier/Kd) + substrate*(1+modifier/(a*Kd)) );
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_hyperbolic_modifier_rev.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_hyperbolic_modifier_rev.m
new file mode 100644
index 0000000000000000000000000000000000000000..f841085072306ea3c8c7a2af761a8a32bb7b0b4d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_hyperbolic_modifier_rev.m
@@ -0,0 +1,24 @@
+function [R] = kin_hyperbolic_modifier_rev(Vf,substrate,Kms,Vr,product,Kmp,b,modifier,a,Kd)
+% kin_hyperbolic_modifier_rev: Hyperbolic modifier (reversible) kinetics
+%
+% Application restrictions: 
+% =========================
+%   - Only reversible
+%   - exactly 1 substrate
+%   - exactly 1 product
+%
+% USAGE:
+% ======
+% R = kin_hyperbolic_modifier_rev(Vf,substrate,Kms,Vr,product,Kmp,b,modifier,a,Kd)
+%
+% Output Arguments:
+% =================
+% R = (Vf*substrate/Kms - Vr*product/Kmp)*(1+b*modifier/(a*Kd)) / ( 1+modifier/Kd+(substrate/Kms+product/Kmp)*(1+modifier/(a*Kd) )
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = (Vf*substrate/Kms - Vr*product/Kmp)*(1+b*modifier/(a*Kd)) / ( 1+modifier/Kd+(substrate/Kms+product/Kmp)*(1+modifier/(a*Kd)) );
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_iso_uni_uni_rev.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_iso_uni_uni_rev.m
new file mode 100644
index 0000000000000000000000000000000000000000..f8c9d7a2e18eec86a3b88f9526af12bb2a675e5f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_iso_uni_uni_rev.m
@@ -0,0 +1,24 @@
+function [R] = kin_iso_uni_uni_rev(Vf,substrate,product,Keq,Kii,Kms,Kmp)
+% kin_iso_uni_uni_rev: enzyme isomerization product inhibition
+%
+% Application restrictions: 
+% =========================
+%   - Only reversible
+%   - exactly 1 substrate
+%   - exactly 1 product
+%
+% USAGE:
+% ======
+% R = kin_iso_uni_uni_rev(Vf,substrate,product,Keq,Kii,Kms,Kmp)
+%
+% Output Arguments:
+% =================
+% R = Vf*(substrate-product/Keq) / ( substrate*(1+product/Kii) + Kms*(1+product/Kmp) )
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = Vf*(substrate-product/Keq) / ( substrate*(1+product/Kii) + Kms*(1+product/Kmp) );
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_mass_action_irr.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_mass_action_irr.m
new file mode 100644
index 0000000000000000000000000000000000000000..370c5168b440a9285dce6330cdd70e386863e021
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_mass_action_irr.m
@@ -0,0 +1,24 @@
+function [R] = kin_mass_action_irr(k,substrate)
+% kin_mass_action_irr: Mass action (irreversible) kinetics
+%
+% Application restrictions: 
+% =========================
+%   - Only irreversible
+%   - exactly 1 substrate (several substrates can be realized by
+%   substrate=substrate1*substrate2*...
+%
+% USAGE:
+% ======
+% R = kin_mass_action_irr(k,substrate)
+%
+% Output Arguments:
+% =================
+% R = k*substrate
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = k*substrate;
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_mass_action_rev.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_mass_action_rev.m
new file mode 100644
index 0000000000000000000000000000000000000000..de44230f61f5da98f64b5375d71348aac7de0a88
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_mass_action_rev.m
@@ -0,0 +1,26 @@
+function [R] = kin_mass_action_rev(k1,substrate,k2,product)
+% kin_mass_action_rev: Mass action (reversible) kinetics
+%
+% Application restrictions: 
+% =========================
+%   - Only reversible
+%   - exactly 1 substrate (several substrates can be realized by
+%   substrate=substrate1*substrate2*...
+%   - exactly 1 product (several products can be realized by
+%   product=product1*product2*...
+%
+% USAGE:
+% ======
+% R = kin_mass_action_rev(k1,substrate,k2,product)
+%
+% Output Arguments:
+% =================
+% R = k1*substrate-k2*product
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = k1*substrate-k2*product;
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_michaelis_menten_irr.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_michaelis_menten_irr.m
new file mode 100644
index 0000000000000000000000000000000000000000..a9cba2fab96fec27131b2b4ff55c51131794367d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_michaelis_menten_irr.m
@@ -0,0 +1,23 @@
+function [R] = kin_michaelis_menten_irr(V,substrate,Km)
+% kin_michaelis_menten_irr: Michaelis Menten (irreversible) kinetics
+%
+% Application restrictions: 
+% =========================
+%   - Only irreversible
+%   - exactly 1 substrate
+%
+% USAGE:
+% ======
+% R = kin_michaelis_menten_irr(V,substrate,Km)
+%
+% Output Arguments:
+% =================
+% R = V*substrate / ( Km + substrate )
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = V*substrate / ( Km + substrate );
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_michaelis_menten_rev.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_michaelis_menten_rev.m
new file mode 100644
index 0000000000000000000000000000000000000000..4e4c18c4fd4815146b6a909d43b382bc005c6c8f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_michaelis_menten_rev.m
@@ -0,0 +1,24 @@
+function [R] = kin_michaelis_menten_rev(Vf,substrate,Kms,Vr,product,Kmp)
+% kin_michaelis_menten_rev: Michaelis Menten (reversible) kinetics
+%
+% Application restrictions: 
+% =========================
+%   - Only reversible
+%   - exactly 1 substrate
+%   - exactly 1 product
+%
+% USAGE:
+% ======
+% R = kin_michaelis_menten_rev(Vf,substrate,Kms,Vr,product,Kmp)
+%
+% Output Arguments:
+% =================
+% R = (Vf*substrate/Kms+Vr*product/Kmp) / ( 1+substrate/Kms+product/Kmp ) 
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = (Vf*substrate/Kms+Vr*product/Kmp) / ( 1+substrate/Kms+product/Kmp ) ;
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_mixed_activation_irr.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_mixed_activation_irr.m
new file mode 100644
index 0000000000000000000000000000000000000000..c3367dca1c6d4e6e8342b994837fab1e07e24cd8
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_mixed_activation_irr.m
@@ -0,0 +1,23 @@
+function [R] = kin_mixed_activation_irr(V,substrate,activator,Kms,Kas,Kac)
+% kin_mixed_activation_irr: Mixed activation irreversible
+%
+% Application restrictions: 
+% =========================
+%   - Only irreversible
+%   - exactly 1 substrate
+%
+% USAGE:
+% ======
+% R = kin_mixed_activation_irr(V,substrate,activator,Kms,Kas,Kac)
+%
+% Output Arguments:
+% =================
+% R = V*substrate*activator / ( Kms*(Kas+activator) + substrate*(Kac+activator) )
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = V*substrate*activator / ( Kms*(Kas+activator) + substrate*(Kac+activator) );
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_mixed_activation_rev.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_mixed_activation_rev.m
new file mode 100644
index 0000000000000000000000000000000000000000..068947c003499c521e334ca07e4677ce11fb6b12
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_mixed_activation_rev.m
@@ -0,0 +1,24 @@
+function [R] = kin_mixed_activation_rev(Vf,substrate,Kms,Vr,product,Kmp,activator,Kas,Kac)
+% kin_mixed_activation_rev: Mixed activation reversible
+%
+% Application restrictions: 
+% =========================
+%   - Only reversible
+%   - exactly 1 substrate
+%   - exactly 1 product
+%
+% USAGE:
+% ======
+% R = kin_mixed_activation_rev(Vf,substrate,Kms,Vr,product,Kmp,activator,Kas,Kac)
+%
+% Output Arguments:
+% =================
+% R = (Vf*substrate/Kms - Vr*product/Kmp)*activator / ( Kas+activator+(substrate/Kms+product/Kmp)*(Kac+activator) )
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = (Vf*substrate/Kms - Vr*product/Kmp)*activator / ( Kas+activator+(substrate/Kms+product/Kmp)*(Kac+activator) );
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_mixed_inihib_irr.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_mixed_inihib_irr.m
new file mode 100644
index 0000000000000000000000000000000000000000..08cb361f31f1d0e7c3758f1fe0180625457ca4e8
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_mixed_inihib_irr.m
@@ -0,0 +1,23 @@
+function [R] = kin_mixed_inihib_irr(V,substrate,Km,inhibitor,Kis,Kic)
+% kin_mixed_inihib_irr: Mixed inhibition (irreversible) kinetics
+%
+% Application restrictions: 
+% =========================
+%   - Only irreversible
+%   - exactly 1 substrate
+%
+% USAGE:
+% ======
+% R = kin_mixed_inihib_irr(V,substrate,Km,inhibitor,Kis,Kic)
+%
+% Output Arguments:
+% =================
+% R = V*substrate / ( (Km*(1+inhibitor/Kis) + substrate*(1+inhibitor/Kic) )
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = V*substrate / ( Km*(1+inhibitor/Kis) + substrate*(1+inhibitor/Kic) );
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_mixed_inihib_rev.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_mixed_inihib_rev.m
new file mode 100644
index 0000000000000000000000000000000000000000..99f67262585e15f716924e3ea410cb777e5b9cf0
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_mixed_inihib_rev.m
@@ -0,0 +1,24 @@
+function [R] = kin_mixed_inihib_rev(Vf,substrate,Kms,Vr,product,Kmp,inhibitor,Kis,Kic)
+% kin_mixed_inihib_rev: Mixed inhibition (reversible) kinetics
+%
+% Application restrictions: 
+% =========================
+%   - Only reversible
+%   - exactly 1 substrate
+%   - exactly 1 product
+%
+% USAGE:
+% ======
+% R = kin_mixed_inihib_rev(Vf,substrate,Kms,Vr,product,Kmp,inhibitor,Kis,Kic)
+%
+% Output Arguments:
+% =================
+% R = (Vf*substrate/Kms - Vr*product/Kmp) / ( 1+inhibitor/Kis+(substrate/Kms+product/Kmp)*(1+inhibitor/Kic) )
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = (Vf*substrate/Kms - Vr*product/Kmp) / ( 1+inhibitor/Kis+(substrate/Kms+product/Kmp)*(1+inhibitor/Kic) );
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_noncomp_inihib_irr.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_noncomp_inihib_irr.m
new file mode 100644
index 0000000000000000000000000000000000000000..47c209dc17512050ccb7c15dfed256cee9384b0e
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_noncomp_inihib_irr.m
@@ -0,0 +1,23 @@
+function [R] = kin_noncomp_inihib_irr(V,substrate,Km,inhibitor,Ki)
+% kin_noncomp_inihib_irr: Noncompetitive inhibition (irreversible) kinetics
+%
+% Application restrictions: 
+% =========================
+%   - Only irreversible
+%   - exactly 1 substrate
+%
+% USAGE:
+% ======
+% R = kin_noncomp_inihib_irr(V,substrate,Km,inhibitor,Ki)
+%
+% Output Arguments:
+% =================
+% R = V*substrate / ( (Km+substrate)*(1+inhibitor/Ki) )
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = V*substrate / ( (Km+substrate)*(1+inhibitor/Ki) );
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_noncomp_inihib_rev.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_noncomp_inihib_rev.m
new file mode 100644
index 0000000000000000000000000000000000000000..5a8c1c179e413186dff02c2158dcd2e7b52a5555
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_noncomp_inihib_rev.m
@@ -0,0 +1,24 @@
+function [R] = kin_noncomp_inihib_rev(Vf,substrate,Kms,Vr,product,Kmp,inhibitor,Ki)
+% kin_noncomp_inihib_rev: Noncompetitive inhibition (reversible) kinetics
+%
+% Application restrictions: 
+% =========================
+%   - Only reversible
+%   - exactly 1 substrate
+%   - exactly 1 product
+%
+% USAGE:
+% ======
+% R = kin_noncomp_inihib_rev(Vf,substrate,Kms,Vr,product,Kmp,inhibitor,Ki)
+%
+% Output Arguments:
+% =================
+% R = (Vf*substrate/Kms-Vr*product/Kmp) / ( (1+substrate/Kms+product/Kmp)*(1+inhibitor/Ki) )
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = (Vf*substrate/Kms-Vr*product/Kmp) / ( (1+substrate/Kms+product/Kmp)*(1+inhibitor/Ki) );
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_ordered_bi_bi_rev.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_ordered_bi_bi_rev.m
new file mode 100644
index 0000000000000000000000000000000000000000..3ebec527965e813ea5d31905c689029391ac339c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_ordered_bi_bi_rev.m
@@ -0,0 +1,24 @@
+function [R] = kin_ordered_bi_bi_rev(Vf,substratea,substrateb,productp,productq,Keq,Kip,Kma,Kmb,Kia,Vr,Kmq,Kmp,Kib)
+% kin_ordered_bi_bi_rev: ordered bi-bi reversible
+%
+% Application restrictions: 
+% =========================
+%   - Only reversible
+%   - exactly 2 substrates
+%   - exactly 2 products
+%
+% USAGE:
+% ======
+% R = kin_ordered_bi_bi_rev(Vf,substratea,substrateb,productp,productq,Keq,Kip,Kma,Kmb,Kia,Vr,Kmq,Kmp,Kib)
+%
+% Output Arguments:
+% =================
+% R = Vf*(substratea*substrateb-productp*productq/Keq) / (substratea*substrateb*(1+productp/Kip) + Kma*substrateb + Kmb*(substratea+Kia)+Vf/(Vr*Keq)*(Kmq*productp*(1+substratea/Kia) + productq*(Kmp*(1+Kia*substrateb/(Kma*Kmb))+productp*(1+substrateb/Kib))) )
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = Vf*(substratea*substrateb-productp*productq/Keq) / (substratea*substrateb*(1+productp/Kip) + Kma*substrateb + Kmb*(substratea+Kia)+Vf/(Vr*Keq)*(Kmq*productp*(1+substratea/Kia) + productq*(Kmp*(1+Kia*substrateb/(Kma*Kmb))+productp*(1+substrateb/Kib))) );
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_ordered_bi_uni_rev.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_ordered_bi_uni_rev.m
new file mode 100644
index 0000000000000000000000000000000000000000..743114162fc71bae8fecf80196cafb8bc19184fb
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_ordered_bi_uni_rev.m
@@ -0,0 +1,24 @@
+function [R] = kin_ordered_bi_uni_rev(Vf,substratea,substrateb,product,Keq,Kma,Kmb,Vr,Kmp,Kia)
+% kin_ordered_bi_uni_rev: ordered bi-uni reversible
+%
+% Application restrictions: 
+% =========================
+%   - Only reversible
+%   - exactly 2 substrates
+%   - exactly 1 product
+%
+% USAGE:
+% ======
+% R = kin_ordered_bi_uni_rev(Vf,substratea,substrateb,product,Keq,Kma,Kmb,Vr,Kmp,Kia)
+%
+% Output Arguments:
+% =================
+% R = Vf*(substratea*substrateb-product/Keq) / ( substratea*substrateb+Kma*substrateb+Kmb*substratea+Vf/(Vr*Keq)*(Kmp+product*(1+substratea/Kia)) ) 
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = Vf*(substratea*substrateb-product/Keq) / ( substratea*substrateb+Kma*substrateb+Kmb*substratea+Vf/(Vr*Keq)*(Kmp+product*(1+substratea/Kia)) );
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_ordered_uni_bi_rev.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_ordered_uni_bi_rev.m
new file mode 100644
index 0000000000000000000000000000000000000000..5124e6b766bd34cd9db97ef01012577b365b54c0
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_ordered_uni_bi_rev.m
@@ -0,0 +1,24 @@
+function [R] = kin_ordered_uni_bi_rev(Vf,substrate,productp,productq,Keq,Kms,Kip,Vr,Kmq,Kmp)
+% kin_ordered_uni_bi_rev: ordered uni-bi reversible
+%
+% Application restrictions: 
+% =========================
+%   - Only reversible
+%   - exactly 1 substrate
+%   - exactly 2 products
+%
+% USAGE:
+% ======
+% R = kin_ordered_uni_bi_rev(Vf,substrate,productp,productq,Keq,Kms,Kip,Vr,Kmq,Kmp)
+%
+% Output Arguments:
+% =================
+% R = Vf*(substrate-productp*productq/Keq) / ( Kms+substrate*(1+productp/Kip)+Vf/(Vr*Keq)*(Kmq*productp+Kmp*productq+productp*productq) ) 
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = Vf*(substrate-productp*productq/Keq) / ( Kms+substrate*(1+productp/Kip)+Vf/(Vr*Keq)*(Kmq*productp+Kmp*productq+productp*productq) ); 
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_ping_pong_bi_bi_rev.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_ping_pong_bi_bi_rev.m
new file mode 100644
index 0000000000000000000000000000000000000000..cec2ed9e55b9d1e5b5bd33aa9ebba6a8c7b9a437
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_ping_pong_bi_bi_rev.m
@@ -0,0 +1,24 @@
+function [R] = kin_ping_pong_bi_bi_rev(Vf,substratea,substrateb,productp,productq,Keq,Kiq,Kma,Kmb,Vr,Kmq,Kia,Kmp)
+% kin_ping_pong_bi_bi_rev: Ping pong bi bi kinetics (reversible) 
+%
+% Application restrictions: 
+% =========================
+%   - Only reversible
+%   - exactly 2 substrates
+%   - exactly 2 products
+%
+% USAGE:
+% ======
+% R = kin_ping_pong_bi_bi_rev(Vf,substratea,substrateb,productp,productq,Keq,Kiq,Kma,Kmb,Vr,Kmq,Kia,Kmp)
+%
+% Output Arguments:
+% =================
+% R = Vf*( substratea*substrateb-productp*productq/Keq ) / (substratea*substrateb*(1+productq/Kiq)+Kma*substrateb+Kmb*substratea+Vf/(Vr*Keq)*(Kmq*productp*(1+substratea/Kia)+productq*(Kmp+productp)))
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = Vf*( substratea*substrateb-productp*productq/Keq ) / (substratea*substrateb*(1+productq/Kiq)+Kma*substrateb+Kmb*substratea+Vf/(Vr*Keq)*(Kmq*productp*(1+substratea/Kia)+productq*(Kmp+productp)));
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_specific_activation_irr.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_specific_activation_irr.m
new file mode 100644
index 0000000000000000000000000000000000000000..57dde82484af1deb961352fb1157d17f05bf15e3
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_specific_activation_irr.m
@@ -0,0 +1,23 @@
+function [R] = kin_specific_activation_irr(V,substrate,activator,Kms,Ka)
+% kin_specific_activation_irr: Specific activation (irreversible) kinetics
+%
+% Application restrictions: 
+% =========================
+%   - Only irreversible
+%   - exactly 1 substrate
+%
+% USAGE:
+% ======
+% R = kin_specific_activation_irr(V,substrate,activator,Kms,Ka)
+%
+% Output Arguments:
+% =================
+% R = V*substrate*activator/( Kms*Ka+(Kms+substrate)*activator )
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = V*substrate*activator/( Kms*Ka+(Kms+substrate)*activator );
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_specific_activation_rev.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_specific_activation_rev.m
new file mode 100644
index 0000000000000000000000000000000000000000..cae0867ea1a66c352e1afff5e6daea573e841f14
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_specific_activation_rev.m
@@ -0,0 +1,24 @@
+function [R] = kin_specific_activation_rev(Vf,substrate,Kms,Vr,product,Kmp,activator,Ka)
+% kin_specific_activation_rev: Specific activation (reversible) kinetics
+%
+% Application restrictions: 
+% =========================
+%   - Only reversible
+%   - exactly 1 substrate
+%   - exactly 1 product
+%
+% USAGE:
+% ======
+% R = kin_specific_activation_rev(Vf,substrate,Kms,Vr,product,Kmp,activator,Ka)
+%
+% Output Arguments:
+% =================
+% R = ( Vf*substrate/Kms-Vr*product/Kmp )*activator / ( Ka+(1+substrate/Kms+product/Kmp)*activator )  
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = ( Vf*substrate/Kms-Vr*product/Kmp )*activator / ( Ka+(1+substrate/Kms+product/Kmp)*activator );
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_substrate_activation_irr.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_substrate_activation_irr.m
new file mode 100644
index 0000000000000000000000000000000000000000..ee4e419738476ab593116b867075aa09bd045c54
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_substrate_activation_irr.m
@@ -0,0 +1,23 @@
+function [R] = kin_substrate_activation_irr(V,substrate,Ksa,Ksc)
+% kin_substrate_activation_irr: Substrate activation (irreversible) kinetics
+%
+% Application restrictions: 
+% =========================
+%   - Only irreversible
+%   - exactly 1 substrate
+%
+% USAGE:
+% ======
+% R = kin_substrate_activation_irr(V,substrate,Ksa,Ksc)
+%
+% Output Arguments:
+% =================
+% R = V*(substrate/Ksa)^2 / ( 1+substrate/Ksc+substrate/Ksa+(substrate/Ksa)^2 ) 
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = V*(substrate/Ksa)^2 / ( 1+substrate/Ksc+substrate/Ksa+(substrate/Ksa)^2 );
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_substrate_inihib_irr.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_substrate_inihib_irr.m
new file mode 100644
index 0000000000000000000000000000000000000000..86883236c4a7896fd66eb9ab2e959289fd533116
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_substrate_inihib_irr.m
@@ -0,0 +1,23 @@
+function [R] = kin_substrate_inihib_irr(V,substrate,Km,Ki)
+% kin_substrate_inihib_irr: Substrate inhibition (irreversible) kinetics
+%
+% Application restrictions: 
+% =========================
+%   - Only irreversible
+%   - exactly 1 substrate
+%
+% USAGE:
+% ======
+% R = kin_substrate_inihib_irr(V,substrate,Km,Ki)
+%
+% Output Arguments:
+% =================
+% R = V*substrate / ( Km + substrate + Km*(substrate/Ki)^2 )
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = V*substrate / ( Km + substrate + Km*(substrate/Ki)^2 );
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_substrate_inihib_rev.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_substrate_inihib_rev.m
new file mode 100644
index 0000000000000000000000000000000000000000..d445b46f18e2a485b4daea45963161377e073b70
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_substrate_inihib_rev.m
@@ -0,0 +1,24 @@
+function [R] = kin_substrate_inihib_rev(Vf,substrate,Kms,Vr,product,Kmp,Ki)
+% kin_substrate_inihib_rev: Substrate inhibition (reversible) kinetics
+%
+% Application restrictions: 
+% =========================
+%   - Only reversible
+%   - exactly 1 substrate
+%   - exactly 1 product
+%
+% USAGE:
+% ======
+% R = kin_substrate_inihib_rev(Vf,substrate,Kms,Vr,product,Kmp,Ki)
+%
+% Output Arguments:
+% =================
+% R = (Vf*substrate/Kms-Vr*product/Kmp) / ( 1+substrate/Kms+product/Kmp+(substrate/Ki)^2 ) 
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = (Vf*substrate/Kms-Vr*product/Kmp) / ( 1+substrate/Kms+product/Kmp+(substrate/Ki)^2 );
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_uncomp_inihib_irr.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_uncomp_inihib_irr.m
new file mode 100644
index 0000000000000000000000000000000000000000..2ca6c110bce2e410c4edb411acee439c51944291
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_uncomp_inihib_irr.m
@@ -0,0 +1,23 @@
+function [R] = kin_uncomp_inihib_irr(V,substrate,Km,inhibitor,Ki)
+% kin_uncomp_inihib_irr: Uncompetitive inhibition (irreversible) kinetics
+%
+% Application restrictions: 
+% =========================
+%   - Only irreversible
+%   - exactly 1 substrate
+%
+% USAGE:
+% ======
+% R = kin_uncomp_inihib_irr(V,substrate,Km,inhibitor,Ki)
+%
+% Output Arguments:
+% =================
+% R = V*substrate / ( Km + substrate*(1+inhibitor/Ki) )
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = V*substrate / ( Km + substrate*(1+inhibitor/Ki) );
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_uncomp_inihib_rev.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_uncomp_inihib_rev.m
new file mode 100644
index 0000000000000000000000000000000000000000..32ffc13c858fd22182d10b405785dbcd0fa732c9
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_uncomp_inihib_rev.m
@@ -0,0 +1,24 @@
+function [R] = kin_uncomp_inihib_rev(Vf,substrate,Kms,Vr,product,Kmp,inhibitor,Ki)
+% kin_uncomp_inihib_rev: Uncompetitive inhibition (reversible) kinetics
+%
+% Application restrictions: 
+% =========================
+%   - Only reversible
+%   - exactly 1 substrate
+%   - exactly 1 product
+%
+% USAGE:
+% ======
+% R = kin_uncomp_inihib_rev(Vf,substrate,Kms,Vr,product,Kmp,inhibitor,Ki)
+%
+% Output Arguments:
+% =================
+% R = ( Vf*substrate/Kms-Vr*product/Kmp ) / ( 1+(substrate/Kms+product/Kmp)*(1+inhibitor/Ki) ) 
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = ( Vf*substrate/Kms-Vr*product/Kmp ) / ( 1+(substrate/Kms+product/Kmp)*(1+inhibitor/Ki) );
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_uni_uni_rev.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_uni_uni_rev.m
new file mode 100644
index 0000000000000000000000000000000000000000..a47d552405aa8dd3d5c4a91b2c483c8739ea041c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/modelling/kineticlaws/kin_uni_uni_rev.m
@@ -0,0 +1,24 @@
+function [R] = kin_uni_uni_rev(Vf,substrate,product,Keq,Kms,Kmp)
+% kin_uni_uni_rev: uni uni reversible kinetics
+%
+% Application restrictions: 
+% =========================
+%   - Only reversible
+%   - exactly 1 substrate
+%   - exactly 1 product
+%
+% USAGE:
+% ======
+% R = kin_uni_uni_rev(Vf,substrate,product,Keq,Kms,Kmp)
+%
+% Output Arguments:
+% =================
+% R = Vf*( substrate-product/Keq ) / ( substrate+Kms*(1+product/Kmp) )
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+R = Vf*( substrate-product/Keq ) / ( substrate+Kms*(1+product/Kmp) );
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/simulation/SBPDsensitivity.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/simulation/SBPDsensitivity.m
new file mode 100644
index 0000000000000000000000000000000000000000..18069311557a865b61df7a61bea6c12807eda35c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/simulation/SBPDsensitivity.m
@@ -0,0 +1,349 @@
+function [varargout] = SBPDsensitivity(model,timevector,varargin)
+% SBPDsensitivity: The SBPDsensitivity function is able to determine the 
+% sensitivities of states and variables with respect to initial conditions
+% and parameters, using a final difference approach.
+%
+% USAGE:
+% ======
+% output = SBPDsensitivity(model, timevector)
+% output = SBPDsensitivity(model, timevector, parameternames)
+% output = SBPDsensitivity(model, timevector, parameternames, statenames)
+% output = SBPDsensitivity(model, timevector, parameternames, statenames, options)
+% output = SBPDsensitivity(model, timevector, parameternames, statenames, options, nomparamvalues, nomicvalues)
+%
+% model: SBmodel or MEX simulation function
+% timevector: a vector of time steps at which to return the simulation data
+% parameternames: cell-array containing the names of the parameters for which to 
+%       calculate the sensitivities. (default: all parameters
+%       in the model)
+% statenames: cell-array containing the names of the states for whose initial
+%       conditions to calculate the sensitivities. (default: no states)
+% options: structure with options for the integrator and sensitivity
+%          calculation
+%               options.pertfactor: relative perturbation if parameter not
+%                   equal to zero. Otherwise absolute peturbation
+%               options.abstol: absolute tolerance
+%               options.reltol: relative tolerance
+%               options.minstep: minimal integrator step size
+%               options.maxstep: maximal integrator step size
+%               options.maxnumsteps: maximum number of steps to be
+%                   taken by the solver in its attempt to reach the next
+%                   output time 
+% nomparamvalues: vector of nominal parameter values
+% nomicvalues: vector of nominal initial condition values
+%
+% DEFAULT VALUES:
+% ===============
+% parameternames: (all parameters)
+% statenames:     (no states)
+% options.pertfactor: 1e-5 
+% options.abstol: 1e-6
+% options.reltol: 1e-6
+% options.minstep: 0
+% options.maxstep: inf
+% options.maxnumsteps: 500
+% nomparamvalues: parameter values stored in the model
+% nomicvalues: initial condition values stored in the model
+%
+% Output Arguments:
+% =================
+% If no output arguments are given, the result of the simulation is plotted
+% after finished simulation (only states, variables, reactions). The
+% sensitivities are not plotted!
+%
+% The output of SBPDsensitivity is realized as a structure:
+% output.time:              vector with time instants for the results
+% output.states:            cell-array with state names
+% output.statevalues:       matrix with state values. Each row corresponds to
+%                           one time instant
+%
+% The following fields are only present in case options.simdata = 'all' is
+% defined.
+% output.variables:         cell-array with variable names
+% output.variablevalues:    matrix with variable values. Each row corresponds to
+%                           one time instant
+% output.reactions:         cell-array with reaction names
+% output.reactionvalues:    matrix with reaction values. Each row corresponds to
+%                           one time instant
+%
+% In the case events are present in the model the following fields are
+% present in the output structure additionally:
+% output.events:            cell-arra with the names of the events
+% output.eventtimes:        vector with time instants at which events
+%                           happened
+% output.eventflags:        matrix of dimension: 'number of events' x
+%                           'number of event time instants'. Each column in
+%                           this matrix correponds to one timeinstant in
+%                           the output.eventtimes vector. The row numbers
+%                           correspond to the numbers of the events. A "1"
+%                           element in the matrix indicates that the
+%                           corresponding event has happened at the
+%                           corresponding time. A "0" element tells you
+%                           that the event has not been fired at the
+%                           corresponding instant.
+%
+% Sensitivity trajectoried are returned as follows:
+% output.sensparameters:         cell-array containing the names of the
+%                                parameters for which sensitivities are determined
+% output.paramtrajectories.states:    cell-array containing one entry for each
+%                                parameter in output.sensparameters (same order).
+%                                Each entry consists of a matrix, where the
+%                                columns correspond to state sensitivities wrt
+%                                to the parameter and the rows correspond to
+%                                the different integration time points, given in
+%                                output.time.
+% output.paramtrajectories.variables: same as above just for variables
+% output.paramtrajectories.reactions: same as above just for reactions
+% output.sensicstates:           cell-array containing the names of the
+%                                states for which initial conditions
+%                                sensitivities are determined
+% output.ictrajectories.states:    cell-array containing one entry for each
+%                                state in output.sensicstates (same order).
+%                                Each entry consists of a matrix, where the
+%                                columns correspond to state sensitivities wrt
+%                                to the initial conditions and the rows correspond to
+%                                the different integration time points, given in
+%                                output.time.
+% output.ictrajectories.variables: same as above just for variables
+% output.ictrajectories.reactions: same as above just for reactions
+
+% Information:
+% ============
+% Copyright (C) 2005-2013 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+pertfactor = 1e-5;
+% HANDLE NON-NUMERIC INITIAL CONDITIONS
+nomicvalues = SBcalcICvector(model);
+[dummy,nomparamvalues] = SBparameters(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK TYPE OF MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBmodel(model) && ~ischar(model),
+    error('Model is not an SBmodel or the name of a MEX simulation function.');
+end
+if length(timevector) <=1,
+    error('''timevector'' input argument needs to be a vector.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+parameternames = SBparameters(model);
+statenames = [];
+options = [];
+if nargin >= 3,
+    parameternames = varargin{1};
+    if ischar(parameternames), 
+        parameternames = {parameternames}; 
+    end
+end
+if nargin >= 4,
+    statenames = varargin{2};
+    if ischar(statenames), 
+        statenames = {statenames}; 
+    end
+end
+if nargin >= 5,
+    options = varargin{3};
+    % reset the pertfactor if set in options
+	if isfield(options,'pertfactor')
+        pertfactor = options.pertfactor;
+	end
+end
+if nargin >= 6,
+    nomparamvalues = varargin{4};
+end
+if nargin == 7,
+    nomicvalues = varargin{5};
+end
+if nargin > 7,
+    error('Incorrect number of input arguments');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CREATE THE MEX MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ischar(model),
+    MEXmodel = model;
+    MEXmodelfullpath = '';
+else
+    [MEXmodel, MEXmodelfullpath] = makeTempMEXmodelSBPD(model);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET NOMINAL VALUES AND INDICES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% nom values for all params and states
+allparamvaluesnom = nomparamvalues;
+allicvaluesnom = nomicvalues;
+% nom values for params and states for which to compute the sensitivities
+paramindices = getparamindicesSBPD(model,parameternames);
+paramvaluesnom = allparamvaluesnom(paramindices);
+icindices = getstateindicesSBPD(model,statenames);
+icvaluesnom = allicvaluesnom(icindices);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% RUN A NOMINAL SIMULATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+nomsimdata = feval(MEXmodel,timevector,allicvaluesnom,allparamvaluesnom,options);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% RUN THE SENSITIVITY ANALYSIS (PARAMETERS)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+parampertsimdata = {};
+paramdeltapertvalue = [];
+for k=1:length(parameternames),
+    % perturb the parameter
+    paramkindex = paramindices(k);
+    paramk = paramvaluesnom(k);
+    if paramk ~= 0,
+        deltapert = paramk*pertfactor;
+    else
+        deltapert = pertfactor;
+    end
+    paramdeltapertvalue(end+1) = deltapert;
+    pertparamk = paramk + deltapert;
+    % create parameter vector
+    pv = allparamvaluesnom;
+    pv(paramkindex) = pertparamk;
+    % simulate the perturbed model
+    parampertsimdata{end+1} = feval(MEXmodel,timevector,allicvaluesnom,pv,options);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% RUN THE SENSITIVITY ANALYSIS (INITIAL CONDITIONS)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+icpertsimdata = {};
+icdeltapertvalue = [];
+for k=1:length(statenames),
+    % perturb the ic
+    ickindex = icindices(k);
+    ick = icvaluesnom(k);
+    if ick ~= 0,
+        deltapert = ick*pertfactor;
+    else
+        deltapert = pertfactor;
+    end
+    icdeltapertvalue(end+1) = deltapert;
+    pertick = ick + deltapert;
+    % create ic vector
+    ic = allicvaluesnom;
+    ic(ickindex) = pertick;
+    % simulate the perturbed model
+    icpertsimdata{end+1} = feval(MEXmodel,timevector,ic,allparamvaluesnom,options);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE SENSITIVITIES (STATES)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+states_sensparamtrajectories = {};
+nomstates = nomsimdata.statevalues;
+for k=1:length(parameternames),
+    parampertstates = parampertsimdata{k}.statevalues;
+    states_sensparamtrajectories{end+1} = (parampertstates-nomstates)/paramdeltapertvalue(k);
+end
+states_sensictrajectories = {};
+for k=1:length(statenames),
+    icpertstates = icpertsimdata{k}.statevalues;
+    states_sensictrajectories{end+1} = (icpertstates-nomstates)/icdeltapertvalue(k);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE SENSITIVITIES (VARIABLES)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+variables_sensparamtrajectories = {};
+nomvariables = nomsimdata.variablevalues;
+for k=1:length(parameternames),
+    parampertvariables = parampertsimdata{k}.variablevalues;
+    variables_sensparamtrajectories{end+1} = (parampertvariables-nomvariables)/paramdeltapertvalue(k);
+end
+variables_sensictrajectories = {};
+for k=1:length(statenames),
+    icpertvariables = icpertsimdata{k}.variablevalues;
+    variables_sensictrajectories{end+1} = (icpertvariables-nomvariables)/icdeltapertvalue(k);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE SENSITIVITIES (REACTIONS)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+reactions_sensparamtrajectories = {};
+nomreactions = nomsimdata.reactionvalues;
+for k=1:length(parameternames),
+    parampertreactions = parampertsimdata{k}.reactionvalues;
+    reactions_sensparamtrajectories{end+1} = (parampertreactions-nomreactions)/paramdeltapertvalue(k);
+end
+reactions_sensictrajectories = {};
+for k=1:length(statenames),
+    icpertreactions = icpertsimdata{k}.reactionvalues;
+    reactions_sensictrajectories{end+1} = (icpertreactions-nomreactions)/icdeltapertvalue(k);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% BUILD OUTPUT STRUCTURE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output = nomsimdata;
+output.sensparameters = parameternames;
+output.paramtrajectories.states = states_sensparamtrajectories;
+output.paramtrajectories.variables = variables_sensparamtrajectories;
+output.paramtrajectories.reactions = reactions_sensparamtrajectories;
+output.sensicstates = statenames;
+output.ictrajectories.states = states_sensictrajectories;
+output.ictrajectories.variables = variables_sensictrajectories;
+output.ictrajectories.reactions = reactions_sensictrajectories;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABLE OUTPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargout == 0,
+    % prepare data for plotting
+    time = output.time;
+    datanames = {};
+    dataindex = 1;
+    for k = 1:length(output.states),
+        datanames{dataindex} = sprintf('%s (state)',output.states{k});
+        dataindex = dataindex + 1;
+    end
+    if isfield(output,'variables'),
+        for k = 1:length(output.variables),
+            datanames{dataindex} = sprintf('%s (variable)',output.variables{k});
+            dataindex = dataindex + 1;
+        end
+        for k = 1:length(output.reactions),
+            datanames{dataindex} = sprintf('%s (reaction rate)',output.reactions{k});
+            dataindex = dataindex + 1;
+        end
+        datavalues = [output.statevalues, output.variablevalues, output.reactionvalues];
+    else
+        datavalues = [output.statevalues];
+    end
+    SBplot(createdatastructSBplotSB(time(:),datavalues,datanames));
+elseif nargout == 1,
+    varargout{1} = output;
+else 
+    error('Incorrect number of output arguments!');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DELETE TEMP MEX MODEL IF CREATED
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(MEXmodelfullpath),
+    clear mex;
+    delete(MEXmodelfullpath);
+end
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/simulation/SBPDsimulate.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/simulation/SBPDsimulate.m
new file mode 100644
index 0000000000000000000000000000000000000000..d41a5952a8621c65be82b990e6be499037044a0b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tasks/simulation/SBPDsimulate.m
@@ -0,0 +1,226 @@
+function [varargout] = SBPDsimulate(mmodel,varargin)
+% SBPDsimulate: Function allowing to simulate SBmodels and MEX simulation
+% functions. SBmodels are first converted to temporary MEX simulation
+% functions, so that a conversion overhead is present.
+%
+% USAGE:
+% ======
+% output = SBPDsimulate(model)
+% output = SBPDsimulate(model, time)
+% output = SBPDsimulate(model, time, ICs)
+% output = SBPDsimulate(model, time, ICs, paramNames, paramValues)
+% output = SBPDsimulate(model, time, ICs, paramNames, paramValues, OPTIONS)
+%
+% model: Name of MEX simulation function OR SBmodel 
+% time: Either simulation end time (scalar) or simulation time vector.
+% ICs: Vector of initial conditions.
+% paramNames: Cell-array with the names of the parameters for which the
+%             values are to be changed to given values.
+% paramValues: Vector of parameter values for the given parameters.
+% OPTIONS: structure with integrator options.
+%       OPTIONS.showIntegratorStats: =0 (off), =1 shows integrator
+%               statistics in the MATLAB console window
+%       OPTIONS.method:             'stiff' or 'nonstiff' (default: 'stiff')
+%       OPTIONS.abstol:             abs tolerance (default: 1e-6)
+%       OPTIONS.reltol:             rel tolerance (default: 1e-6)
+%       OPTIONS.minstep:            min step-size integrator (default: 0)
+%       OPTIONS.maxstep:            max step-size integrator (default: inf)
+%       OPTIONS.maxnumsteps:        max number of steps between two output
+%                                   points (default: 100000)
+%       OPTIONS.maxerrtestfails:    maximum number of error test failures
+%                                   permitted in attempting one step
+%                                   (default: 50)
+%       OPTIONS.maxorder:           maximum order of the linear multistep
+%                                   method (default: 5 BDF, 12 ADAMS)
+%       OPTIONS.maxconvfails:       maximum number of nonlinear solver convergence 
+%                                   failures permitted during one step
+%                                   (default: 10)
+%       OPTIONS.initstep:           initial step size to be attempted
+%                                   (default: 0)
+%       OPTIONS.maxnonlineariter:   maximum number of nonlinear solver
+%                                   iterations permitted per step 
+%                                   (default: 3)
+%
+% DEFAULT VALUES:
+% ===============
+% time: 20 
+% ICs: values stored in the model
+% paramNames: {}  do not change any parameters
+% paramValues: []   
+%
+% Output Arguments:
+% =================
+% If no output arguments are given, the result of the simulation is plotted
+% after finished simulation.
+%
+% The output of SBPDsimulate is realized as a structure:
+% output.time:              vector with time instants for the results
+% output.states:            cell-array with state names
+% output.statevalues:       matrix with state values. Each row corresponds to
+%                           one time instant
+%
+% output.variables:         cell-array with variable names
+% output.variablevalues:    matrix with variable values. Each row corresponds to
+%                           one time instant
+% output.reactions:         cell-array with reaction names
+% output.reactionvalues:    matrix with reaction values. Each row corresponds to
+%                           one time instant
+%
+% In the case events are present in the model the following fields are
+% present in the output structure additionally:
+% output.events:            cell-arra with the names of the events
+% output.eventtimes:        vector with time instants at which events
+%                           happened
+% output.eventflags:        matrix of dimension: 'number of events' x
+%                           'number of event time instants'. Each column in
+%                           this matrix correponds to one timeinstant in
+%                           the output.eventtimes vector. The row numbers
+%                           correspond to the numbers of the events. A "1"
+%                           element in the matrix indicates that the
+%                           corresponding event has happened at the
+%                           corresponding time. A "0" element tells you
+%                           that the event has not been fired at the
+%                           corresponding instant.
+
+% Information:
+% ============
+% Copyright (C) 2005-2013 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% FIRST CHECK THE GIVEN MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isSBmodel(mmodel),
+    % create the MEX simulation function
+    [MEXmodel, MEXmodelfullpath] = makeTempMEXmodelSBPD(mmodel);
+elseif exist(mmodel) == 3,
+    MEXmodel = mmodel;
+    MEXmodelfullpath = '';
+else
+    error('Model input argument is no SBmodel and no MEX simulation function.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+timevector = [0:0.01:20];  % just the default timevector
+time = [];
+ICs = [];
+paramvec = [];
+paramNames = {};
+OPTIONS = [];
+if nargin<1 || nargin==4 || nargin > 6,
+    error('Incorrect number of input arguments');
+elseif nargin == 2,
+    time = varargin{1};
+elseif nargin == 3,
+    time = varargin{1};
+    ICs = varargin{2};
+elseif nargin == 5,
+    time = varargin{1};
+    ICs = varargin{2};
+    paramNames = varargin{3};
+    paramValues = varargin{4};
+elseif nargin == 6,
+    time = varargin{1};
+    ICs = varargin{2};
+    paramNames = varargin{3};
+    paramValues = varargin{4};
+    OPTIONS = varargin{5};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS INPUTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(time),
+    if length(time) == 1,
+        timevector = [0:time/1000:time];
+    elseif length(time) > 1,
+        timevector = time;
+    end
+end
+if ~isempty(paramNames),
+    paramvec = makeparamvecSBPD(MEXmodel,paramNames,paramValues);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF DELAY PRESENT ... THEN ERROR
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isSBmodel(mmodel),
+    if usedelaySB(mmodel),
+        error('The model contains delays. This is not supported for MEX file simulation.');
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% IF EVENTS ARE PRESENT THEN USE A DEFAULT MAXSTEP
+% Only do that in case of an SBmodel
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isSBmodel(mmodel),
+    if useeventSB(mmodel),
+        if ~isfield(OPTIONS,'maxstep'),
+            % change only if not user provided 
+            OPTIONS.maxstep = timevector(end)/1000;
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% RUN THE MEX SIMULATION FUNCTION WITH GIVEN INPUT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+simdata = feval(MEXmodel,timevector,ICs,paramvec,OPTIONS);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABLE OUTPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargout == 0,
+    % NO OUTPUT => DO PLOT RESULTS
+    time = simdata.time;
+    datanames = {};
+    dataindex = 1;
+    for k = 1:length(simdata.states),
+        datanames{dataindex} = sprintf('%s (state)',simdata.states{k});
+        dataindex = dataindex + 1;
+    end
+    if isfield(simdata,'variables'),
+        for k = 1:length(simdata.variables),
+            datanames{dataindex} = sprintf('%s (variable)',simdata.variables{k});
+            dataindex = dataindex + 1;
+        end
+        for k = 1:length(simdata.reactions),
+            datanames{dataindex} = sprintf('%s (reaction rate)',simdata.reactions{k});
+            dataindex = dataindex + 1;
+        end
+        datavalues = [simdata.statevalues, simdata.variablevalues, simdata.reactionvalues];
+    else
+        datavalues = [simdata.statevalues];
+    end
+    SBplot(createdatastructSBplotSB(time(:),datavalues,datanames));
+elseif nargout == 1,
+    varargout{1} = simdata;
+else 
+    error('Incorrect number of simdata arguments!');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DELETE THE TEMPORARY MEX SIMULATION FUNCTION IF IT HAS BEEN CREATED
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(MEXmodelfullpath),
+    clear mex;
+    delete(MEXmodelfullpath);
+end
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/SBPDmakeMEXmodel.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/SBPDmakeMEXmodel.m
new file mode 100644
index 0000000000000000000000000000000000000000..70a056f31f1bb43bda1f3f081bb8f811430681a9
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/SBPDmakeMEXmodel.m
@@ -0,0 +1,1178 @@
+function [] = SBPDmakeMEXmodel(model,varargin)
+% SBPDmakeMEXmodel: This function converts an SBmodel to an executable
+% C-code
+% MEX model and links it with the CVODE integrator from SUNDIALS.
+% 
+% USAGE:
+% ======
+% [] = SBPDmakeMEXmodel(model)
+% [] = SBPDmakeMEXmodel(model, MEXfile)
+% [] = SBPDmakeMEXmodel(model, MEXfile, doNOTcompileFlag)
+%
+% model: SBmodel
+% MEXfile: the name of the MEX file (default: models name)
+% doNOTcompileFlag: =0 (default): create executable MEX simulation file 
+%                   =1: only create the source code but do not compile
+%
+% The calling syntax of the MEX simulation function is the following:
+%           
+%   output = MEXfile()                     % returns vector with initial conditions
+%   output = MEXfile('states')             % returns cell array with state names
+%   output = MEXfile('parameters')         % returns cell array with parameter names
+%   output = MEXfile('parametervalues')    % returns vector with parameter values
+%   output = MEXfile(timevector)
+%   output = MEXfile(timevector, ICs)
+%   output = MEXfile(timevector, ICs, param)
+%   output = MEXfile(timevector, ICs, param, OPTIONS)
+%   
+%   INPUT ARGUMENTS TO 'MEXfile':
+%   timevector: simulation time vector
+%   ICs: full initial condition vector
+%   param: full parametervalue vector
+%   OPTIONS: structure with OPTIONS for the integrator
+%       OPTIONS.showIntegratorStats: =0 (off), =1 shows integrator
+%               statistics in the MATLAB console window
+%       OPTIONS.method:             'stiff' or 'nonstiff' (default: 'stiff')
+%       OPTIONS.abstol:             abs tolerance (default: 1e-6)
+%       OPTIONS.reltol:             rel tolerance (default: 1e-6)
+%       OPTIONS.minstep:            min step-size integrator (default: 0)
+%       OPTIONS.maxstep:            max step-size integrator (default: inf)
+%       OPTIONS.maxnumsteps:        max number of steps between two output
+%                                   points (default: 100000)
+%       OPTIONS.maxerrtestfails:    maximum number of error test failures
+%                                   permitted in attempting one step
+%                                   (default: 50)
+%       OPTIONS.maxorder:           maximum order of the linear multistep
+%                                   method (default: 5 BDF, 12 ADAMS)
+%       OPTIONS.maxconvfails:       maximum number of nonlinear solver convergence 
+%                                   failures permitted during one step
+%                                   (default: 10)
+%       OPTIONS.initstep:           initial step size to be attempted
+%                                   (default: 0)
+%       OPTIONS.maxnonlineariter:   maximum number of nonlinear solver
+%                                   iterations permitted per step 
+%                                   (default: 3)
+%       OPTIONS.xdotcalc: =0: do integration, =1: return RHS of ODEs for
+%                         given state and parameter values. Time information
+%                         is neglected and it is assumed that time=0.
+    
+% Information:
+% ============
+% Copyright (C) 2005-2013 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+global MAX_NRPERROW 
+MAX_NRPERROW = 20;  % Max. number of elements per rows
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GENERATE DELAY BASE NAME
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+global delaycount delaybase
+delaycount = 0;
+[dummy,delaybase] = fileparts(tempname);
+delaybase = char([double('delaybase_') double(delaybase(1:8))]);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GENERATE interpcseSB, etc. counters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+global interpcseSBcount interpcseSlopeSBcount
+interpcseSBcount = 0;
+interpcseSlopeSBcount = 0;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK THE MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~strcmp('SBmodel',class(model)),
+    error('Function only defined for SBmodels.');
+end
+if ~isempty(SBfunctionsMATLAB(model)),
+    error('Matlab functions present in model. Conversion to MEX simulation file not possible.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ADD PIECEWISE TRIGGERS AS EVENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+model = addpiecewiseeventsSB(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF DELAY PRESENT ... THEN ERROR
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if usedelaySB(model),
+    error('The model contains delays. This is not supported for MEX file simulation.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET THE UNDERLYING MODEL STRUCTURE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modelstruct = SBstruct(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DEFAULT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+MEXfile = regexprep(modelstruct.name,'[\W]','');  % name of model as default MEX function name
+doNOTcompileFlag = 0;         % do compile per default
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% TAKE CAR OF VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin < 1 || nargin > 3,
+    error('Incorrect number of input arguments.');
+end
+if nargin == 2,
+    MEXfile = varargin{1};
+elseif nargin == 3,
+    MEXfile = varargin{1};
+    doNOTcompileFlag = varargin{2};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE AN EVENTUAL FULL PATH (GET PATH AND THE NAME OF THE FUNCTION)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[MEXfunctionPath,MEXfunctionName] = fileparts(MEXfile);
+filenameH = fullfile(MEXfunctionPath,strcat(MEXfunctionName,'.h'));
+filenameC = fullfile(MEXfunctionPath,strcat(MEXfunctionName,'.c'));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET THE MODELS ELEMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[staten,stateode,stateICs] = SBstates(model);
+[parametern, parameterv] = SBparameters(model);
+[variablen, variablef] = SBvariables(model);
+[reactionn, reactionf] = SBreactions(model);
+[functionn,functionf,functiona] = SBfunctions(model);
+[eventn,eventt,eventv,eventf] = SBevents(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET NUMBER OF THE MODELS ELEMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+NRSTATES = length(staten);
+NRPARAMETERS = length(parametern);
+NRVARIABLES = length(variablen);
+NRREACTIONS = length(reactionn);
+NRFUNCTIONS = length(functionn);
+NREVENTS = length(eventn);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXCHANGE SPECIAL NAMES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Certain reserved element names might have to be exchanged. Example:
+% "default", which is an often used name for the root compartment in SBML,
+% but it is a reserved name in C.
+staten = exchangeNames(staten);
+parametern = exchangeNames(parametern); 
+variablen = exchangeNames(variablen);
+reactionn = exchangeNames(reactionn);
+functionn = exchangeNames(functionn);
+eventn = exchangeNames(eventn); 
+eventt = exchangeNames(eventt);
+for k=1:length(eventn),
+    eventv{k} = exchangeNames(eventv{k});
+end
+functiona = exchangeNames(functiona);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DEAL WITH THE FORMULAS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% For C the double representation needs to be made (1->1.0) ...
+% Furthermore, several other things need to be fixed.
+stateode = dealFormulas(stateode);
+variablef = dealFormulas(variablef); 
+reactionf = dealFormulas(reactionf); 
+functionf = dealFormulas(functionf); 
+eventt = dealFormulas(eventt);
+for k = 1:length(eventf),
+    eventf{k} = dealFormulas(eventf{k});
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% WRITE THE MODEL HEADER FILE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen(filenameH,'w');
+fprintf(fid,'#include "mex.h"\n\n');
+fprintf(fid,'const int NRSTATES = %d;\n',NRSTATES);
+fprintf(fid,'const int NRPARAMETERS = %d;\n',NRPARAMETERS);
+fprintf(fid,'const int NRVARIABLES = %d;\n',NRVARIABLES);
+fprintf(fid,'const int NRREACTIONS = %d;\n',NRREACTIONS);
+fprintf(fid,'const int NREVENTS = %d;\n',NREVENTS);
+fprintf(fid,'\n');
+% add flag for numeric or non-numeric ICs
+if hasonlynumericICsSB(model),
+    fprintf(fid,'const int hasOnlyNumericICs = 1;\n');
+    outputHeaderData(fid,'defaultICs_num',NRSTATES,stateICs)
+    fprintf(fid,'char *defaultICs_nonnum[1];\n');    
+else
+    fprintf(fid,'const int hasOnlyNumericICs = 0;\n');
+    fprintf(fid,'double defaultICs_num[1];\n');    
+    outputHeaderData(fid,'defaultICs_nonnum',NRSTATES,stateICs)
+end
+fprintf(fid,'\n');
+if isempty(parameterv), parameterv = []; end
+outputHeaderData(fid,'defaultParam',NRPARAMETERS,parameterv)
+outputHeaderData(fid,'stateNames',NRSTATES,staten)
+outputHeaderData(fid,'parameterNames',NRPARAMETERS,parametern)
+outputHeaderData(fid,'variableNames',NRVARIABLES,variablen)
+outputHeaderData(fid,'reactionNames',NRREACTIONS,reactionn)
+outputHeaderData(fid,'eventNames',NREVENTS,eventn)
+fprintf(fid,'\n');
+fprintf(fid,'void model(double time, double *stateVector, double *DDTvector, ParamData *paramdataPtr, int DOflag, double *variableVector, double *reactionVector, double *gout, int *eventVector);\n');
+fprintf(fid,'void calc_ic_model(double *icVector, ParamData *paramdataPtr);\n\n');
+fprintf(fid,'void CVODEmex25(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]);\n');
+fprintf(fid,'void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n');
+fprintf(fid,'{\n    CVODEmex25(nlhs, plhs, nrhs, prhs);\n}\n');
+fclose(fid);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% WRITE THE MODEL C FILE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen(filenameC,'w');
+fprintf(fid,'#include "stddef.h"\n');
+fprintf(fid,'#include "stdarg.h"\n');
+fprintf(fid,'#include "math.h"\n');
+fprintf(fid,'#include "CVODEmex25.h"\n');
+fprintf(fid,'#include "%s"\n',strcat(MEXfunctionName,'.h'));
+fprintf(fid,'#include "mexsplineaddon.h"\n');
+fprintf(fid,'#include "mexmathaddon.h"\n');
+fprintf(fid,'#include "kineticformulas.h"\n\n');
+fprintf(fid,'double time;\n\n');
+% First define the functions
+for k = 1:NRFUNCTIONS,
+    % write declaration
+    fprintf(fid,'static double %s(',functionn{k});
+    % write arguments
+    arguments = explodePCSB(functiona{k},','); for k2 = 1:length(arguments), if k2 < length(arguments), fprintf(fid,'double %s,',arguments{k2}); else fprintf(fid,'double %s)\n',arguments{k2}); end; end
+    % write forumla and return
+    fprintf(fid,'{\n'); fprintf(fid,'    return %s;\n',functionf{k}); fprintf(fid,'}\n'); fprintf(fid,'\n');
+end
+% Define the model function
+fprintf(fid,'void model(double time_local, double *stateVector, double *DDTvector, ParamData *paramdataPtr, int DOflag, double *variableVector, double *reactionVector, double *gout, int *eventVector)\n');
+fprintf(fid,'{\n');
+outputDeclarationData(fid,NRSTATES,staten)
+outputDeclarationData(fid,NRPARAMETERS,parametern)
+outputDeclarationData(fid,NRVARIABLES,variablen)
+outputDeclarationData(fid,NRREACTIONS,reactionn)
+eventassignn = {};
+for k=1:NREVENTS,
+    eventassignformulak = eventf{k};
+    for k2=1:length(eventassignformulak),
+        eventassignn{end+1} = sprintf('eventassign_%d_%d',k,k2);
+    end
+end
+outputDeclarationData(fid,length(eventassignn),eventassignn)
+fprintf(fid,'\n');
+fprintf(fid,'    time = time_local;\n');
+fprintf(fid,'\n');
+for k=1:NRSTATES, fprintf(fid,'    %s = stateVector[%d];\n',staten{k},k-1); end
+for k=1:NRPARAMETERS, fprintf(fid,'    %s = paramdataPtr->parametervector[%d]; /* %g */\n',parametern{k},k-1,parameterv(k)); end
+%for k=1:NRVARIABLES, fprintf(fid,'    %s = %s;\n',variablen{k},variablef{k}); end
+%for k=1:NRREACTIONS, fprintf(fid,'    %s = %s;\n',reactionn{k},reactionf{k}); end
+for k=1:NRVARIABLES, writeOutFormulasConvertPiecewise(fid,variablen{k},variablef{k},sprintf('\t')); end
+for k=1:NRREACTIONS, writeOutFormulasConvertPiecewise(fid,reactionn{k},reactionf{k},sprintf('\t')); end
+for k=1:NREVENTS,
+    eventassignformulak = eventf{k};
+    for k2=1:length(eventassignformulak),
+        namevar = sprintf('eventassign_%d_%d',k,k2);
+        fprintf(fid,'    %s = %s;\n',namevar,eventassignformulak{k2}); 
+    end
+end
+fprintf(fid,'    if (DOflag == DOFLAG_DDT) {\n');
+%for k=1:NRSTATES, fprintf(fid,'        DDTvector[%d] = %s;\n',k-1,stateode{k}); end
+for k=1:NRSTATES, writeOutFormulasConvertPiecewise(fid,sprintf('\tDDTvector[%d]',k-1),stateode{k},sprintf('\t\t')); end
+fprintf(fid,'    } else if (DOflag == DOFLAG_VARREAC) {\n');
+for k=1:NRVARIABLES, fprintf(fid,'        variableVector[%d] = %s;\n',k-1,variablen{k}); end
+for k=1:NRREACTIONS, fprintf(fid,'        reactionVector[%d] = %s;\n',k-1,reactionn{k}); end
+fprintf(fid,'    } else if (DOflag == DOFLAG_EVENTS) {\n');
+for k = 1:NREVENTS,
+    tExpr = getTriggerExpression(eventt{k});
+    fprintf(fid,'        gout[%d] = %s;\n',k-1,tExpr);
+end
+fprintf(fid,'    } else if (DOflag == DOFLAG_EVENTASSIGN) {\n');
+for k = 1:NREVENTS,
+    fprintf(fid,'        if (eventVector[%d] == 1 && gout[%d] < 0) {\n',k-1,k-1);
+    fprintf(fid,'            DDTvector[0] = 1;\n');
+    vars = eventv{k};
+    for k2 = 1:length(vars),
+        index = strmatchSB(vars{k2},staten,'exact')-1;
+        if ~isempty(index),
+            fprintf(fid,'            stateVector[%d] = eventassign_%d_%d;\n',index,k,k2);
+        end
+        index = strmatchSB(vars{k2},parametern,'exact')-1;
+        if ~isempty(index),
+            fprintf(fid,'            paramdataPtr->parametervector[%d] = eventassign_%d_%d;\n',index,k,k2);
+        end
+    end
+    fprintf(fid,'        }\n');
+end
+fprintf(fid,'    }\n');
+fprintf(fid,'}\n');
+fprintf(fid,'\n');
+fprintf(fid,'\n');
+fprintf(fid,'/* Function for initial condition calculation */\n');
+fprintf(fid,'void calc_ic_model(double *icVector, ParamData *paramdataPtr)\n');
+fprintf(fid,'{\n');
+outputDeclarationData(fid,NRSTATES,staten)
+outputDeclarationData(fid,NRPARAMETERS,parametern)
+for k=1:NRPARAMETERS, fprintf(fid,'    %s = paramdataPtr->parametervector[%d]; /* %g */\n',parametern{k},k-1,parameterv(k)); end
+modelics = SBinitialconditions(model);
+for k = 1:NRSTATES,
+    if hasonlynumericICsSB(model),
+        value = modelics(k);
+    else
+        value = modelics{k};
+    end
+    if isnumeric(value),
+        value = sprintf('%g',value);
+    end
+    stateIC = dealFormulas({value});
+    fprintf(fid,'    %s = %s;\n',staten{k},stateIC{1});
+end
+for k = 1:NRSTATES,
+    fprintf(fid,'    icVector[%d] = %s;\n',k-1,staten{k});
+end
+fprintf(fid,'}\n');
+fprintf(fid,'\n');
+fclose(fid);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% COMPILE THE MEX MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~doNOTcompileFlag,
+    mexcompileSBPD(MEXfunctionName);
+    delete(filenameC);
+    delete(filenameH);
+end
+
+clear delaycount delaybase interpcseSBcount interpcseSlopeSBcount
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% WRITING OUT FORMULAS AND REPLACING PIECEWISESB BY IF THEN ELSE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [] = writeOutFormulasConvertPiecewise(fid,lhs,rhs,pretext)
+% check if rhs starts with a piecewiseSB expression
+rhs = strtrim(rhs);
+% Search for both the normal and the T0 type of piecewise expressions
+index1 = strfind(rhs,'piecewiseSB(');
+index2 = strfind(rhs,'piecewiseT0SB(');
+index = [index1(:)', index2(:)'];
+if isempty(index),
+    % not a piecewise expression
+    fprintf(fid,'    %s = %s;\n',lhs,rhs); 
+    return
+elseif length(index) > 1,
+    % more than one piecewise expression
+    fprintf(fid,'    %s = %s;\n',lhs,rhs); 
+    return
+elseif index ~= 1,
+    % does not start with a piecewise expression
+    fprintf(fid,'    %s = %s;\n',lhs,rhs); 
+    return
+end
+% At this point the rhs has a single piecewiseSB or piecewiseT0SB expression and starts with
+% it. We only need to check if after the piecewiseSB expression there are
+% other components in the rhs.
+parOpen = 1;
+if ~isempty(index1),
+    indexStart = length('piecewiseSB(')+1; 
+else
+    indexStart = length('piecewiseT0SB(')+1; 
+end    
+indexEnd   = indexStart;
+while parOpen ~= 0,
+    indexEnd = indexEnd + 1;
+    if rhs(indexEnd) == '(',
+        parOpen = parOpen + 1;
+    elseif rhs(indexEnd) == ')',
+        parOpen = parOpen - 1;
+    end
+end
+if ~isempty(rhs(indexEnd+1:end)),
+    % piecewiseSB expression is not the single component on the RHS => not if then else
+    fprintf(fid,'    %s = %s;\n',lhs,rhs); 
+    return
+end
+% Finally we are left with only the rhs which only contain a single piecewise expression
+% that easily can be represented in terms of if else if else if else ...
+% Get only the arguments as comma separated list
+arguments = rhs(indexStart:indexEnd-1);
+% Explode to get the terms
+terms = explodePCSB(arguments);
+% First term gives the number of arguments. Needs to be an odd number,
+% because otherwise the default value is missing and this is not good :)
+% We still do not use the number ... since the length-1 gives the same
+% result.
+n = length(terms)-1;
+% Check if n is odd 
+if 2*round(n/2) == n,
+    error('All piecewise expressions need an odd number of arguments to specify also a default value.');
+end
+% Construct the if statement and write it out
+terms = terms(2:end);
+for k=2:2:n-1,
+    if k==2,
+        fprintf(fid,'%sif (%s) {\n',pretext,terms{k});
+    else
+        fprintf(fid,'%s} else if (%s) {\n',pretext,terms{k});
+    end
+    fprintf(fid,'%s\t%s = %s;\n',pretext,lhs,terms{k-1});
+end
+fprintf(fid,'%s} else {\n',pretext);
+fprintf(fid,'%s\t%s = %s;\n%s}\n',pretext,lhs,terms{n},pretext);
+return
+
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE THE TRIGGER EXPRESSION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [tExpr] = getTriggerExpression(data)
+tExpr = sprintf('%s-0.5',data);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OUTPUT HEADER DATA
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [] = outputHeaderData(fid,name,NR,data)
+global MAX_NRPERROW 
+if NR == 0,
+    if iscell(data),
+        fprintf(fid,'char *%s[1];\n',name);
+    else
+        fprintf(fid,'double %s[1];\n',name);
+    end
+else
+    if iscell(data),
+        fprintf(fid,'char *%s[%d] = {\n\t',name,NR);
+    else
+        fprintf(fid,'double %s[%d] = {\n\t',name,NR);
+    end        
+    nrperrow = 0;
+    for k=1:NR,
+        if nrperrow == MAX_NRPERROW, fprintf(fid,'\n\t'); nrperrow = 0; end
+        if iscell(data),   
+            if ~isnumeric(data{k}),
+                if k<NR, fprintf(fid,'"%s",',data{k}); else fprintf(fid,'"%s"',data{k}); end
+            else
+                % handling numeric entries in cell-arrays: happening if
+                % non-numeric ICs
+                if k<NR, fprintf(fid,'"%g",',data{k}); else fprintf(fid,'"%g"',data{k}); end
+            end
+        else
+            if k<NR, fprintf(fid,'%g,',data(k)); else fprintf(fid,'%g',data(k)); end
+        end
+        nrperrow = nrperrow + 1;
+    end
+    fprintf(fid,'};\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OUTPUT DECLARATION DATA
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [] = outputDeclarationData(fid,NR,data)
+global MAX_NRPERROW 
+nrperrow = 0;
+for k=1:NR,
+    if nrperrow==0, fprintf(fid,'    double '); end
+    if k<NR && nrperrow<MAX_NRPERROW-1, fprintf(fid,'%s,',data{k}); else fprintf(fid,'%s',data{k}); end
+    nrperrow = nrperrow + 1;
+    if nrperrow == MAX_NRPERROW, fprintf(fid,';\n'); nrperrow = 0; end
+end
+if nrperrow ~= 0, fprintf(fid,';\n'); end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXCHANGE THE NAMES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [names] = exchangeNames(names)
+if isempty(names), return; end
+% do not allow "default" being used as component name!!!
+if ~isempty(strmatchSB('default',names,'exact')),
+    error(sprintf('The name "default" is not allowed to be used in an SBmodel when you want\nto create MEX simulation functions. The reason is that "default" is a reserved\n"C" word. Of course this is the case also for all other reserved "C" words.\nPlease rename the "default" component in your model with another name!\n'));
+end
+oldText = {}; 
+newText = {};
+names = regexprep(names,oldText,newText);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE INTERP1SB (LOOKUP TABLE W/ LINEAR INTERPOLATION)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [textnew] = exchangeInterp1SB(text)
+textnew = text;
+indexstart = strfind(text,'interp1SB(')+length('interp1SB(');
+if length(indexstart) > 1,
+    error('The ''interp1SB'' function is only allowed to be present once in each formula.');
+end
+if ~isempty(indexstart),
+    % interp1SB found ... handle it
+    % cut out the content using the parentheses
+    % Get the end index of the k-th statement (closing parentheses
+    % belonging to the opening)
+    % count parentheses
+    pc = 1;
+    cstart = indexstart;
+    cend = cstart;
+    while pc ~= 0,
+        cend = cend + 1;
+        if textnew(cend) == '(',
+            pc = pc+1;
+        elseif textnew(cend) == ')',
+            pc = pc-1;
+        end
+    end
+    indexend = cend-1;
+    indexafter = indexend+1;
+    % indexstart/indexend identify the content in the parentheses to be
+    % processed and replaced
+    textinside = textnew(indexstart:indexend);
+    terms = explodePCSB(textinside,',',{'(','['},{')',']'});
+    % fine so far. We need now to make sure that the elements in the
+    % vectors are separated using commata (otherwise big problem)!
+    xtermstring = terms{1};
+    ytermstring = terms{2};
+    % remove parentheses
+    xtermstring = xtermstring(2:end-1);
+    ytermstring = ytermstring(2:end-1);
+    % get single elements
+    xtermelements = explodePCSB(xtermstring);
+    ytermelements = explodePCSB(ytermstring);
+    if length(xtermelements) == 1,
+        error(sprintf('The elements of the lookup table using the interp1SB function need to be separated by commata!\nAre you sure you have done that correctly?'));
+    end
+    if length(xtermelements) ~= length(ytermelements),
+        error('x and y arguments for interp1SB function do not have same number of elements.');
+    end
+    pwText = sprintf('%s,lt(%s,%s),',ytermelements{1},terms{3},xtermelements{1});
+    for k=1:length(xtermelements)-1,
+        pwText = sprintf('%s(%s-(%s))/(%s-(%s))*(%s-(%s))+(%s)',pwText,ytermelements{k+1},ytermelements{k},xtermelements{k+1},xtermelements{k},terms{3},xtermelements{k},ytermelements{k});
+        if k<length(xtermelements)-1,
+            pwText = sprintf('%s,andSB(lt(%s,%s),ge(%s,%s)),',pwText,terms{3},xtermelements{k+1},terms{3},xtermelements{k});
+        end
+    end
+    pwText = sprintf('%s,andSB(lt(%s,%s),ge(%s,%s)),%s',pwText,terms{3},xtermelements{end},terms{3},xtermelements{end-1},ytermelements{end});
+    textnew = [text(1:indexstart-1) pwText text(indexend+1:end)];
+    textnew = strrep(textnew,'interp1SB','piecewiseSB');
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE INTERP0SB (LOOKUP TABLE W/ ZERO-ORDER INTERPOLATION)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [textnew] = exchangeInterp0SB(text)
+textnew = text;
+indexstart = strfind(text,'interp0SB(')+length('interp0SB(');
+if length(indexstart) > 1,
+    error('The ''interp0SB'' function is only allowed to be present once in each formula.');
+end
+if ~isempty(indexstart),
+    % interp0SB found ... handle it
+    % cut out the content using the parentheses
+    % Get the end index of the k-th statement (closing parentheses
+    % belonging to the opening)
+    % count parentheses
+    pc = 1;
+    cstart = indexstart;
+    cend = cstart;
+    while pc ~= 0,
+        cend = cend + 1;
+        if textnew(cend) == '(',
+            pc = pc+1;
+        elseif textnew(cend) == ')',
+            pc = pc-1;
+        end
+    end
+    indexend = cend-1;
+    indexafter = indexend+1;
+    % indexstart/indexend identify the content in the parentheses to be
+    % processed and replaced
+    textinside = textnew(indexstart:indexend);
+    terms = explodePCSB(textinside,',',{'(','['},{')',']'});
+    % fine so far. We need now to make sure that the elements in the
+    % vectors are separated using commata (otherwise big problem)!
+    xtermstring = terms{1};
+    ytermstring = terms{2};
+    % remove parentheses
+    xtermstring = xtermstring(2:end-1);
+    ytermstring = ytermstring(2:end-1);
+    % get single elements
+    xtermelements = explodePCSB(xtermstring);
+    ytermelements = explodePCSB(ytermstring);
+    if length(xtermelements) == 1,
+        error(sprintf('The elements of the lookup table using the interp0SB function need to be separated by commata!\nAre you sure you have done that correctly?'));
+    end
+    if length(xtermelements) == 2,
+        error('The interp0SB function requires at least 3 points on the x and y axis.');
+    end
+    if length(xtermelements) ~= length(ytermelements),
+        error('x and y arguments for interp0SB function do not have same number of elements.');
+    end
+    pwText = sprintf('%s,lt(%s,%s),',ytermelements{1},terms{3},xtermelements{2});
+    for k=2:length(xtermelements)-1,
+        pwText = sprintf('%s(%s)',pwText,ytermelements{k});
+        if k<length(xtermelements)-1,
+            pwText = sprintf('%s,andSB(lt(%s,%s),ge(%s,%s)),',pwText,terms{3},xtermelements{k+1},terms{3},xtermelements{k});
+        end
+    end
+    pwText = sprintf('%s,andSB(lt(%s,%s),ge(%s,%s)),%s',pwText,terms{3},xtermelements{end},terms{3},xtermelements{end-1},ytermelements{end});
+    textnew = [text(1:indexstart-1) pwText text(indexend+1:end)];
+    textnew = strrep(textnew,'interp0SB','piecewiseSB');
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE INTERPCSSB (LOOKUP TABLE W/ CUBIC SPLINE INTERPOLATION)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [textnew] = exchangeInterpcsSB(text)
+textnew = text;
+indexbefore = strfind(text,'interpcsSB(');
+indexstart = indexbefore+length('interpcsSB(');
+if length(indexstart) > 1,
+    error('The ''interpcsSB'' function is only allowed to be present once in each formula.');
+end
+if ~isempty(indexstart),
+    % interpcsSB found ... handle it
+    % cut out the content using the parentheses
+    % Get the end index of the k-th statement (closing parentheses
+    % belonging to the opening)
+    % count parentheses
+    pc = 1;
+    cstart = indexstart;
+    cend = cstart;
+    while pc ~= 0,
+        cend = cend + 1;
+        if textnew(cend) == '(',
+            pc = pc+1;
+        elseif textnew(cend) == ')',
+            pc = pc-1;
+        end
+    end
+    indexend = cend-1;
+    indexafter = indexend+1;
+    % indexstart/indexend identify the content in the parentheses to be
+    % processed and replaced
+    textinside = textnew(indexstart:indexend);
+    terms = explodePCSB(textinside,',',{'(','['},{')',']'});
+    if length(terms) ~= 3, 
+        error('interpcsSB function has wrong number of input arguments.');
+    end
+    % fine so far. We need now to make sure that the elements in the
+    % vectors are separated using commata (otherwise big problem)!
+    xtermstring = terms{1};
+    ytermstring = terms{2};
+    % remove parentheses
+    xtermstring = xtermstring(2:end-1);
+    ytermstring = ytermstring(2:end-1);
+    % get single elements
+    xtermelements = explodePCSB(xtermstring);
+    ytermelements = explodePCSB(ytermstring);
+    if length(xtermelements) == 1,
+        error(sprintf('The elements of the lookup table using the interpcsSB function need to be separated by commata!\nAre you sure you have done that correctly?'));
+    end
+    if length(xtermelements) ~= length(ytermelements),
+        error('x and y arguments for interpcsSB function do not have same number of elements.');
+    end
+    newexpr = sprintf('%d,%s',length(xtermelements),terms{3});
+    newexpr = strcat('interpcsSB(',newexpr,',',xtermstring,',',ytermstring,')');
+    textnew = strcat(text(1:indexbefore-1),newexpr,text(indexend+2:end));
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE INTERPCSeSB (LOOKUP TABLE W/ CUBIC SPLINE INTERPOLATION and
+% possible endpoint-slope definition
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [textnew] = exchangeInterpcseSB(text)
+global interpcseSBcount
+
+% Determine the number of required replacements (number of interpcseSB functions)
+nrRep = length(strfind(text,'interpcseSB('));
+% Create new text string from input string
+textnew = text;
+
+% Replace on after the other expression sequentially
+% if interpcseSB not present then nothing is done ... simple
+for k=1:nrRep,
+    % Find start of interpcseSB in modified string
+    indexbefore = strfind(textnew,'interpcseSB(');
+    % Get the start index for modification for the k-th modification
+    indexbefore = indexbefore(k);
+    indexstart = indexbefore+length('interpcseSB(');
+    % Get the end index of the k-th statement (closing parentheses
+    % belonging to the opening)
+    % count parentheses
+    pc = 1;
+    cstart = indexstart;
+    cend = cstart;
+    while pc ~= 0,
+        cend = cend + 1;
+        if textnew(cend) == '(',
+            pc = pc+1;
+        elseif textnew(cend) == ')',
+            pc = pc-1;
+        end
+    end
+    indexend = cend-1;
+    indexafter = indexend+1;
+    % indexstart/indexend identify the content in the parentheses to be
+    % processed and replaced
+    textinside = textnew(indexstart:indexend);
+    terms = explodePCSB(textinside,',',{'(','['},{')',']'});
+    nterms = length(terms);
+    if nterms ~= 3 && nterms ~= 5, 
+        error('interpcseSB function has wrong number of input arguments.');
+    end
+    % fine so far. We need now to make sure that the elements in the
+    % vectors are separated using commata (otherwise big problem)!
+    xtermstring = terms{1};
+    ytermstring = terms{2};
+    % remove parentheses
+    xtermstring = xtermstring(2:end-1);
+    ytermstring = ytermstring(2:end-1);
+    % get single elements
+    xtermelements = explodePCSB(xtermstring);
+    ytermelements = explodePCSB(ytermstring);
+    if length(xtermelements) == 1,
+        error(sprintf('The elements of the lookup table using the interpcseSB function need to be separated by commata!\nAre you sure you have done that correctly?'));
+    end
+    if length(xtermelements) ~= length(ytermelements),
+        error('x and y arguments for interpcseSB function do not have same number of elements.');
+    end
+    % construct the text to replace with
+    if nterms == 3,
+        reptextnew = [sprintf('interpcseSB(%d,%d',interpcseSBcount,length(xtermelements)),',',terms{3} ',',xtermstring,',',ytermstring,')'];
+    else
+        reptextnew = [sprintf('interpcseSB(%d,%d',interpcseSBcount,length(xtermelements)),',',terms{3},',',terms{4},',',terms{5} ',',xtermstring,',',ytermstring,')'];
+    end
+    % get the text to replace
+    reptextold = textnew(indexbefore:indexafter);
+    % do a simple strrep operation
+    textnew = strrep(textnew,reptextold,reptextnew);
+    % increment the interpcseSB counter
+    interpcseSBcount = interpcseSBcount + 1;
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE INTERPCSeSlopeSB (LOOKUP TABLE W/ CUBIC SPLINE INTERPOLATION and
+% possible endpoint-slope definition - DERIVATIVE)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [textnew] = exchangeInterpcseSlopeSB(text)
+global interpcseSlopeSBcount
+
+% Determine the number of required replacements (number of interpcseSlopeSB functions)
+nrRep = length(strfind(text,'interpcseSlopeSB('));
+% Create new text string from input string
+textnew = text;
+
+% Replace on after the other expression sequentially
+% if interpcseSlopeSB not present then nothing is done ... simple
+for k=1:nrRep,
+    % Find start of interpcseSlopeSB in modified string
+    indexbefore = strfind(textnew,'interpcseSlopeSB(');
+    % Get the start index for modification for the k-th modification
+    indexbefore = indexbefore(k);
+    indexstart = indexbefore+length('interpcseSlopeSB(');
+    % Get the end index of the k-th statement (closing parentheses
+    % belonging to the opening)
+    % count parentheses
+    pc = 1;
+    cstart = indexstart;
+    cend = cstart;
+    while pc ~= 0,
+        cend = cend + 1;
+        if textnew(cend) == '(',
+            pc = pc+1;
+        elseif textnew(cend) == ')',
+            pc = pc-1;
+        end
+    end
+    indexend = cend-1;
+    indexafter = indexend+1;
+    % indexstart/indexend identify the content in the parentheses to be
+    % processed and replaced
+    textinside = textnew(indexstart:indexend);
+    terms = explodePCSB(textinside,',',{'(','['},{')',']'});
+    nterms = length(terms);
+    if nterms ~= 3 && nterms ~= 5, 
+        error('interpcseSlopeSB function has wrong number of input arguments.');
+    end
+    % fine so far. We need now to make sure that the elements in the
+    % vectors are separated using commata (otherwise big problem)!
+    xtermstring = terms{1};
+    ytermstring = terms{2};
+    % remove parentheses
+    xtermstring = xtermstring(2:end-1);
+    ytermstring = ytermstring(2:end-1);
+    % get single elements
+    xtermelements = explodePCSB(xtermstring);
+    ytermelements = explodePCSB(ytermstring);
+    if length(xtermelements) == 1,
+        error(sprintf('The elements of the lookup table using the interpcseSlopeSB function need to be separated by commata!\nAre you sure you have done that correctly?'));
+    end
+    if length(xtermelements) ~= length(ytermelements),
+        error('x and y arguments for interpcseSlopeSB function do not have same number of elements.');
+    end
+    % construct the text to replace with
+    if nterms == 3,
+        reptextnew = [sprintf('interpcseSlopeSB(%d,%d',interpcseSlopeSBcount,length(xtermelements)),',',terms{3} ',',xtermstring,',',ytermstring,')'];
+    else
+        reptextnew = [sprintf('interpcseSlopeSB(%d,%d',interpcseSlopeSBcount,length(xtermelements)),',',terms{3},',',terms{4},',',terms{5} ',',xtermstring,',',ytermstring,')'];
+    end
+    % get the text to replace
+    reptextold = textnew(indexbefore:indexafter);
+    % do a simple strrep operation
+    textnew = strrep(textnew,reptextold,reptextnew);
+    % increment the interpcseSlopeSB counter
+    interpcseSlopeSBcount = interpcseSlopeSBcount + 1;
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE INTERPCSexSB (LOOKUP TABLE W/ CUBIC SPLINE INTERPOLATION and
+% possible endpoint-slope definition
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [textnew] = exchangeInterpcsexSB(text)
+% Determine the number of required replacements (number of interpcsexSB functions)
+nrRep = length(strfind(text,'interpcsexSB('));
+% Create new text string from input string
+textnew = text;
+
+% Replace on after the other expression sequentially
+% if interpcsexSB not present then nothing is done ... simple
+for k=1:nrRep,
+    % Find start of interpcseSB in modified string
+    indexbefore = strfind(textnew,'interpcsexSB(');
+    % Get the start index for modification for the k-th modification
+    indexbefore = indexbefore(k);
+    indexstart = indexbefore+length('interpcsexSB(');
+    % Get the end index of the k-th statement (closing parentheses
+    % belonging to the opening)
+    % count parentheses
+    pc = 1;
+    cstart = indexstart;
+    cend = cstart;
+    while pc ~= 0,
+        cend = cend + 1;
+        if textnew(cend) == '(',
+            pc = pc+1;
+        elseif textnew(cend) == ')',
+            pc = pc-1;
+        end
+    end
+    indexend = cend-1;
+    indexafter = indexend+1;
+    % indexstart/indexend identify the content in the parentheses to be
+    % processed and replaced
+    textinside = textnew(indexstart:indexend);
+    terms = explodePCSB(textinside,',',{'(','['},{')',']'});
+    nterms = length(terms);
+    if nterms ~= 3 && nterms ~= 5, 
+        error('interpcsexSB function has wrong number of input arguments.');
+    end
+    % fine so far. We need now to make sure that the elements in the
+    % vectors are separated using commata (otherwise big problem)!
+    xtermstring = terms{1};
+    ytermstring = terms{2};
+    % remove parentheses
+    xtermstring = xtermstring(2:end-1);
+    ytermstring = ytermstring(2:end-1);
+    % get single elements
+    xtermelements = explodePCSB(xtermstring);
+    ytermelements = explodePCSB(ytermstring);
+    if length(xtermelements) == 1,
+        error(sprintf('The elements of the lookup table using the interpcsexSB function need to be separated by commata!\nAre you sure you have done that correctly?'));
+    end
+    if length(xtermelements) ~= length(ytermelements),
+        error('x and y arguments for interpcsexSB function do not have same number of elements.');
+    end
+    % construct the text to replace with
+    if nterms == 3,
+        reptextnew = [sprintf('interpcsexSB(%d',length(xtermelements)) ',',xtermstring,',',ytermstring,',',terms{3},')'];
+    else
+        reptextnew = [sprintf('interpcsexSB(%d',length(xtermelements)),',',terms{4},',',terms{5} ',',xtermstring,',',ytermstring,',',terms{3},')'];
+    end
+    % get the text to replace
+    reptextold = textnew(indexbefore:indexafter);
+    % do a simple strrep operation
+    textnew = strrep(textnew,reptextold,reptextnew);
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE INTERPCSexSB (LOOKUP TABLE W/ CUBIC SPLINE INTERPOLATION and
+% possible endpoint-slope definition
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [textnew] = exchangeInterpcsexSlopeSB(text)
+% Determine the number of required replacements (number of interpcsexSlopeSB functions)
+nrRep = length(strfind(text,'interpcsexSlopeSB('));
+% Create new text string from input string
+textnew = text;
+
+% Replace on after the other expression sequentially
+% if interpcsexSlopeSB not present then nothing is done ... simple
+for k=1:nrRep,
+    % Find start of interpcsexSlopeSB in modified string
+    indexbefore = strfind(textnew,'interpcsexSlopeSB(');
+    % Get the start index for modification for the k-th modification
+    indexbefore = indexbefore(k);
+    indexstart = indexbefore+length('interpcsexSlopeSB(');
+    % Get the end index of the k-th statement (closing parentheses
+    % belonging to the opening)
+    % count parentheses
+    pc = 1;
+    cstart = indexstart;
+    cend = cstart;
+    while pc ~= 0,
+        cend = cend + 1;
+        if textnew(cend) == '(',
+            pc = pc+1;
+        elseif textnew(cend) == ')',
+            pc = pc-1;
+        end
+    end
+    indexend = cend-1;
+    indexafter = indexend+1;
+    % indexstart/indexend identify the content in the parentheses to be
+    % processed and replaced
+    textinside = textnew(indexstart:indexend);
+    terms = explodePCSB(textinside,',',{'(','['},{')',']'});
+    nterms = length(terms);
+    if nterms ~= 3 && nterms ~= 5, 
+        error('interpcsexSlopeSB function has wrong number of input arguments.');
+    end
+    % fine so far. We need now to make sure that the elements in the
+    % vectors are separated using commata (otherwise big problem)!
+    xtermstring = terms{1};
+    ytermstring = terms{2};
+    % remove parentheses
+    xtermstring = xtermstring(2:end-1);
+    ytermstring = ytermstring(2:end-1);
+    % get single elements
+    xtermelements = explodePCSB(xtermstring);
+    ytermelements = explodePCSB(ytermstring);
+    if length(xtermelements) == 1,
+        error(sprintf('The elements of the lookup table using the interpcsexSlopeSB function need to be separated by commata!\nAre you sure you have done that correctly?'));
+    end
+    if length(xtermelements) ~= length(ytermelements),
+        error('x and y arguments for interpcsexSlopeSB function do not have same number of elements.');
+    end
+    % construct the text to replace with
+    if nterms == 3,
+        reptextnew = [sprintf('interpcsexSlopeSB(%d',length(xtermelements)) ',',xtermstring,',',ytermstring,',',terms{3},')'];
+    else
+        reptextnew = [sprintf('interpcsexSlopeSB(%d',length(xtermelements)),',',terms{4},',',terms{5} ',',xtermstring,',',ytermstring,',',terms{3},')'];
+    end
+    % get the text to replace
+    reptextold = textnew(indexbefore:indexafter);
+    % do a simple strrep operation
+    textnew = strrep(textnew,reptextold,reptextnew);
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DEAL WITH THE FORMULAS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [newformulaArray] = dealFormulas(formulaArray)
+if isempty(formulaArray),
+    newformulaArray = formulaArray;
+    return
+end
+
+% replace names first (and we do it once more after the handling of the
+% formulas ... at least for power that is necessary)
+oldElements = {'\<nthroot\>','\<and\>','\<or\>','\<power\>','\<abs\>'};
+newElements = {'nthrootSB','andSB','orSB','pow','absSB'};
+formulaArray = regexprep(formulaArray,oldElements,newElements);
+
+% handle calls with variable number of input arguments (these get the
+% number of input arguments as first (additional) argument).
+checkElements = {'\<indexmaxSB\>','\<minSB\>','\<maxSB\>','\<andSB\>','\<orSB\>','\<piecewiseSB\>','\<interpcsSB\>','\<interpcseSB\>','\<interpcsexSB\>','\<piecewiseT0SB\>','\<interpcseSlopeSB\>','\<interpcsexSlopeSB\>'};
+for k0=1:length(formulaArray),
+    formula = formulaArray{k0};
+    % handle interp1SB -> piecewiseSB
+    formula = exchangeInterp1SB(formula);
+    % handle interp0SB -> piecewiseSB
+    formula = exchangeInterp0SB(formula);
+    % handle interpcsSB: changing the syntax
+    formula = exchangeInterpcsSB(formula);
+    % handle interpcseSB: changing the syntax
+    formula = exchangeInterpcseSB(formula);
+    % handle interpcseSlopeSB: changing the syntax
+    formula = exchangeInterpcseSlopeSB(formula);
+    % handle interpcsexSB: changing the syntax
+    formula = exchangeInterpcsexSB(formula);
+    % handle interpcsexSlopeSB: changing the syntax
+    formula = exchangeInterpcsexSlopeSB(formula);
+    % handle the power operator
+    formula = convertPowerOperator(formula);
+    % handle delay operator
+%    [formula] = processDelayCallSB(formula);
+    % fix the c notation of doubles
+    formula = regexprep(formula,'((?<!\d*[eE][-+])(?<!\.)\<\d*\>(?!\.))','$1.0');
+    % delete "." at end
+    formula = regexprep(formula,'([\w])+[.]{1}([\W])','$1$2');
+    formula = regexprep(formula,'([\W])+[.]{1}([\W])','$1$2');
+    % Add number of variable input arguments to function calls as first
+    % input argument (for the functions, defined above)
+    % Add number of variable input arguments to function calls as first
+    % input argument (for the functions, defined above)
+    for k1=1:length(checkElements),
+        index = regexp(formula,checkElements{k1});
+        if ~isempty(index),
+            for k2 = 1:length(index),
+                indexStart = index(k2)+length(checkElements{k1})-4;
+                indexEnd = indexStart;
+                parOpen = 1;
+                while parOpen ~= 0,
+                    indexEnd = indexEnd + 1;
+                    if formula(indexEnd) == '(',
+                        parOpen = parOpen + 1;
+                    elseif formula(indexEnd) == ')',
+                        parOpen = parOpen - 1;
+                    end
+                end
+                oldarguments = formula(indexStart+1:indexEnd-1);
+                newargstring = sprintf('%d,%s',length(explodePCSB(oldarguments,',')),oldarguments);
+                command = checkElements{k1};
+                oldrep  = [command(3:end-2) '(' oldarguments ')'];
+                newrep = [command(3:end-2) '(' newargstring ')'];
+                formula = strrep(formula,oldrep,newrep);
+                index = index + length(newargstring)-length(oldarguments);
+            end
+        end
+    end
+    formulaArray{k0} = formula;
+end
+
+% replace names again
+oldElements = {'\<nthroot\>','\<and\>','\<or\>','\<power\>','\<abs\>'};
+newElements = {'nthrootSB','andSB','orSB','pow','absSB'};
+formulaArray = regexprep(formulaArray,oldElements,newElements);
+
+% ready
+newformulaArray = formulaArray;
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE THE POWER OPERATOR
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [formula] = convertPowerOperator(formula)
+% remove whitespaces from formula
+formula = regexprep(formula,'\s','');
+% first fix the simple problem
+formula = regexprep(formula,'([\w]+[.]?[\w]*)\^([\w]+[.]?[\w]*)','power($1,$2)');
+% then do the more complicated stuff
+indices = strfind(formula,'^');
+while ~isempty(indices),
+    index = indices(1);
+    formula1 = strtrim(formula(1:index-1));
+    formula2 = strtrim(formula(index+1:end));
+    % check formula1 from the right
+    firstargument = regexp(formula1,'([\w]+[.]?[\w]*)$','match');
+    if isempty(firstargument),
+        % check if last character is a closing parenthesis
+        if formula1(end) ~= ')',
+            error(sprintf('Error in formula: %s',formula));
+        end
+        % count parentheses
+        pc = 1; 
+        cend = length(formula1);
+        cstart = cend;
+        while pc ~= 0,
+            cstart = cstart - 1;
+            if formula1(cstart) == ')',
+                pc = pc+1;
+            elseif formula1(cstart) == '(',
+                pc = pc-1;
+            end
+        end
+        firstargument = formula1(cstart+1:cend-1);
+    else
+        firstargument = firstargument{1};
+        cstart = length(formula1)-length(firstargument)+1; 
+    end
+    cendfirst = cstart;
+    % check formula2 from the left
+    secondargument = regexp(formula2,'^([\w]+[.]?[\w]*)','match');
+    if isempty(secondargument),
+        % check if first character is an opening parenthesis
+        if formula2(1) ~= '(',
+            error(sprintf('Error in formula: %s',formula));
+        end
+        % count parentheses
+        pc = 1; 
+        cstart = 1;
+        cend = cstart;
+        while pc ~= 0,
+            cend = cend + 1;
+            if formula2(cend) == '(',
+                pc = pc+1;
+            elseif formula2(cend) == ')',
+                pc = pc-1;
+            end
+        end
+        secondargument = formula2(cstart+1:cend-1);
+    else
+        secondargument = secondargument{1};    
+        cend = length(secondargument);
+    end
+    cstartsecond = cend;
+    % construct power expression
+    powerexp = sprintf('pow(%s,%s)',firstargument,secondargument);
+    % construct new formula
+    formula = [formula1(1:cendfirst-1) powerexp formula2(cstartsecond+1:end)];
+    % get new indices for '^' character
+    indices = strfind(formula,'^');
+end
+return
+
+% function [formula] = processDelayCallSB(formula)
+% global delaycount delaybase
+% count = 1;
+% while 1,
+%     index = strfind(formula,'delaySB(');
+%     if length(index) < count,
+%         break;
+%     end
+%     indexstart = index(count)+length('delaySB(');
+%     indexend = indexstart;
+%     
+%     % search the end of the delay argument definition
+%     parOpen = 1;
+%     while parOpen ~= 0,
+%         if formula(indexend) == '(',
+%             parOpen = parOpen + 1;
+%         elseif formula(indexend) == ')',
+%             parOpen = parOpen - 1;
+%         end
+%         indexend = indexend + 1;
+%     end
+%     % check if the delaybasename has to be changed
+%     if length(index) > 1,
+%         delayname = [delaybase '_' sprintf('%d', delaycount) '_' sprintf('%d', count)];
+%     else
+%         delayname = [delaybase '_' sprintf('%d', delaycount)];
+%     end
+%     % add info to delaySB call
+%     firstpart = formula(1:indexend-2);
+%     lastpart = formula(indexend-1:end);
+%     middlepart = sprintf(',time,"%s"',delayname);
+%     formula = char([double(firstpart) double(middlepart) double(lastpart)]);
+%     % increase counters
+%     count = count + 1;
+%     delaycount = delaycount + 1;
+% end
+% return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/include/CVODEmex25.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/include/CVODEmex25.h
new file mode 100644
index 0000000000000000000000000000000000000000..65a4792a3fc903b80cf54bdcaa5bdc06b5c37df7
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/include/CVODEmex25.h
@@ -0,0 +1,33 @@
+/*
+ * CVODEmex25.h: MEX/CVODES Interface for Sundials CVODES version 2.5
+ *
+ * Information:
+ * ============
+ * SBPD Package - Systems Biology Parameter Determination Package
+ * Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+ */
+
+/* CVODE related flags */
+#define DOFLAG_DDT 0
+#define DOFLAG_VARREAC 1
+#define DOFLAG_EVENTS 2
+#define DOFLAG_EVENTASSIGN 3
+#define DOFLAG_CALCICS 4
+
+/* ParamData (contains pointer to parameter values passed to integrator) */
+typedef struct {
+    double *parametervector;
+} ParamData;
+
+/* Variables defined outside the library */
+extern double defaultICs_num[], defaultParam[];
+extern char  *defaultICs_nonnum[];
+extern char  *stateNames[], *parameterNames[], *variableNames[], *reactionNames[], *eventNames[]; 
+extern const int NRSTATES, NRPARAMETERS, NRVARIABLES, NRREACTIONS, NREVENTS;
+extern const int hasOnlyNumericICs;
+extern int   *interpcseSB_check; /* needed for spline function in mexsplineaddon.h */
+extern int   *interpcseSlopeSB_check; /* needed for spline function in mexsplineaddon.h */
+
+/* Functions containing the model equations */
+extern void model(double time, double *stateVector, double *DDTvector, ParamData *paramdataPtr, int DOflag, double *variableVector, double *reactionVector, double *gout, int *eventVector);
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/include/kineticformulas.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/include/kineticformulas.h
new file mode 100644
index 0000000000000000000000000000000000000000..c4bc94146bccd779f88fbb2a6ec01d843ee350b2
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/include/kineticformulas.h
@@ -0,0 +1,194 @@
+/*
+ * kineticformulas.h: Include file for specification of useful kinetic formulas
+ *
+ * Information:
+ * ============
+ * SBPD Package - Systems Biology Parameter Determination Package
+ * Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+ */
+
+double kin_mass_action_irr(double k, double substrate)
+{
+    return k*substrate;    
+}
+
+double kin_mass_action_rev(double k1, double substrate, double k2, double product)
+{
+    return k1*substrate - k2*product;    
+}
+
+double kin_degradation(double kdeg, double substrate)
+{
+    return kdeg*substrate;    
+}
+
+double kin_michaelis_menten_irr(double V, double substrate, double Km)
+{
+    return V*substrate / ( Km + substrate );    
+}
+
+double kin_hill_cooperativity_irr(double V, double substrate, double h, double Shalve)
+{
+    return V*pow(substrate,h) / (pow(Shalve,h) + pow(substrate,h));    
+}
+
+double kin_mixed_inihib_irr(double V, double substrate, double Km, double inhibitor, double Kis, double Kic)
+{
+    return V*substrate / ( Km*(1+inhibitor/Kis) + substrate*(1+inhibitor/Kic) );    
+}
+
+double kin_noncomp_inihib_irr(double V, double substrate, double Km, double inhibitor, double Ki)
+{
+    return V*substrate / ( (Km+substrate)*(1+inhibitor/Ki) );
+}
+
+double kin_uncomp_inihib_irr(double V, double substrate, double Km, double inhibitor, double Ki)
+{
+    return V*substrate / ( Km + substrate*(1+inhibitor/Ki) );
+}
+
+double kin_comp_inihib_irr(double V, double substrate, double Km, double inhibitor, double Ki)
+{
+    return V*substrate / ( Km*(1+inhibitor/Ki) + substrate );
+}
+
+double kin_substrate_inihib_irr(double V, double substrate, double Km, double Ki)
+{
+    return V*substrate / ( Km + substrate + Km*pow((substrate/Ki),2.0) );
+}
+
+double kin_allosteric_inihib_mwc_irr(double V, double substrate, double Ks, double n, double L, double inhibitor, double Ki)
+{
+    return V*substrate*pow((Ks+substrate),(n-1.0)) / ( L*pow((Ks*(1+inhibitor/Ki)),n) + pow((Ks+substrate),n) );
+}
+
+double kin_allosteric_inihib_empirical_rev(double Vf, double substrate, double Kms, double Vr, double product, double Kmp, double inhibitor, double Ki, double n)
+{
+    return (Vf*substrate/Kms - Vr*product/Kmp) / (1 + substrate/Kms + product/Kmp + pow((inhibitor/Ki),n));
+}
+
+double kin_catalytic_activation_irr(double V, double substrate, double activator, double Kms, double Ka)
+{
+    return V*substrate*activator / ( (Kms + substrate)*(Ka+activator) );
+}
+
+double kin_catalytic_activation_rev(double Vf, double substrate, double Kms, double Vr, double product, double Kmp, double activator, double Ka)
+{
+    return ( Vf*substrate/Kms - Vr*product/Kmp )*activator / ( (1+substrate/Kms+product/Kmp)*(Ka+activator) );
+}
+
+double kin_comp_inihib_rev(double Vf, double substrate, double Kms, double Vr, double product, double Kmp, double inhibitor, double Ki)
+{
+    return (Vf*substrate/Kms - Vr*product/Kmp) / ( 1+substrate/Kms+product/Kmp+inhibitor/Ki );
+}
+
+double kin_constantflux(double v)
+{
+    return v;
+}
+
+double kin_hyperbolic_modifier_irr(double V,double substrate,double b,double modifier,double a,double Kd,double Km)
+{
+    return V*substrate*(1+b*modifier/(a*Kd)) / ( Km*(1+modifier/Kd) + substrate*(1+modifier/(a*Kd)) );
+}
+
+double kin_hyperbolic_modifier_rev(double Vf,double substrate,double Kms,double Vr,double product,double Kmp,double b,double modifier,double a,double Kd)
+{
+    return (Vf*substrate/Kms - Vr*product/Kmp)*(1+b*modifier/(a*Kd)) / ( 1+modifier/Kd+(substrate/Kms+product/Kmp)*(1+modifier/(a*Kd)) );
+}
+
+double kin_hill_rev(double Vf,double substrate,double Shalve,double product,double Keq,double Phalve,double h)
+{
+    return Vf*substrate/Shalve*(1-product/(substrate*Keq))*pow((substrate/Shalve+product/Phalve),(h-1.0)) / ( 1+pow((substrate/Shalve + product/Phalve),h) );
+}
+
+double kin_iso_uni_uni_rev(double Vf,double substrate,double product,double Keq,double Kii,double Kms,double Kmp)
+{
+    return Vf*(substrate-product/Keq) / ( substrate*(1+product/Kii) + Kms*(1+product/Kmp) );
+}
+
+double kin_mixed_activation_irr(double V,double substrate,double activator,double Kms,double Kas,double Kac)
+{
+    return V*substrate*activator / ( Kms*(Kas+activator) + substrate*(Kac+activator) );
+}
+
+double kin_mixed_activation_rev(double Vf,double substrate,double Kms,double Vr,double product,double Kmp,double activator,double Kas,double Kac)
+{
+    return (Vf*substrate/Kms - Vr*product/Kmp)*activator / ( Kas+activator+(substrate/Kms+product/Kmp)*(Kac+activator) );
+}
+
+double kin_mixed_inihib_rev(double Vf,double substrate,double Kms,double Vr,double product,double Kmp,double inhibitor,double Kis,double Kic)
+{
+    return (Vf*substrate/Kms - Vr*product/Kmp) / ( 1+inhibitor/Kis+(substrate/Kms+product/Kmp)*(1+inhibitor/Kic) );
+}
+
+double kin_noncomp_inihib_rev(double Vf,double substrate,double Kms,double Vr,double product,double Kmp,double inhibitor,double Ki)
+{
+    return (Vf*substrate/Kms-Vr*product/Kmp) / ( (1+substrate/Kms+product/Kmp)*(1+inhibitor/Ki) );
+}
+
+double kin_ordered_bi_bi_rev(double Vf,double substratea,double substrateb,double productp,double productq,double Keq,double Kip,double Kma,double Kmb,double Kia,double Vr,double Kmq,double Kmp,double Kib)
+{
+    return Vf*(substratea*substrateb-productp*productq/Keq) / (substratea*substrateb*(1+productp/Kip) + Kma*substrateb + Kmb*(substratea+Kia)+Vf/(Vr*Keq)*(Kmq*productp*(1+substratea/Kia) + productq*(Kmp*(1+Kia*substrateb/(Kma*Kmb))+productp*(1+substrateb/Kib))) );
+}
+
+double kin_ordered_bi_uni_rev(double Vf,double substratea,double substrateb,double product,double Keq,double Kma,double Kmb,double Vr,double Kmp,double Kia)
+{
+    return Vf*(substratea*substrateb-product/Keq) / ( substratea*substrateb+Kma*substrateb+Kmb*substratea+Vf/(Vr*Keq)*(Kmp+product*(1+substratea/Kia)) );
+}
+
+double kin_ordered_uni_bi_rev(double Vf,double substrate,double productp,double productq,double Keq,double Kms,double Kip,double Vr,double Kmq,double Kmp)
+{
+    return Vf*(substrate-productp*productq/Keq) / ( Kms+substrate*(1+productp/Kip)+Vf/(Vr*Keq)*(Kmq*productp+Kmp*productq+productp*productq) );
+}
+
+double kin_michaelis_menten_rev(double Vf,double substrate,double Kms,double Vr,double product,double Kmp)
+{
+    return (Vf*substrate/Kms+Vr*product/Kmp) / ( 1+substrate/Kms+product/Kmp );
+}
+
+double kin_substrate_inihib_rev(double Vf,double substrate,double Kms,double Vr,double product,double Kmp,double Ki)
+{
+    return (Vf*substrate/Kms-Vr*product/Kmp) / ( 1+substrate/Kms+product/Kmp+pow((substrate/Ki),2.0) );
+}
+
+double kin_uncomp_inihib_rev(double Vf,double substrate,double Kms,double Vr,double product,double Kmp,double inhibitor,double Ki)
+{
+    return ( Vf*substrate/Kms-Vr*product/Kmp ) / ( 1+(substrate/Kms+product/Kmp)*(1+inhibitor/Ki) );
+}
+
+double kin_uni_uni_rev(double Vf,double substrate,double product,double Keq,double Kms,double Kmp)
+{
+    return Vf*( substrate-product/Keq ) / ( substrate+Kms*(1+product/Kmp) );
+}
+
+double kin_specific_activation_irr(double V,double substrate,double activator,double Kms,double Ka)
+{
+    return V*substrate*activator/( Kms*Ka+(Kms+substrate)*activator );
+}
+
+double kin_specific_activation_rev(double Vf,double substrate,double Kms,double Vr,double product,double Kmp,double activator,double Ka)
+{
+    return ( Vf*substrate/Kms-Vr*product/Kmp )*activator / ( Ka+(1+substrate/Kms+product/Kmp)*activator );
+}
+
+double kin_substrate_activation_irr(double V,double substrate,double Ksa,double Ksc)
+{
+    return V*pow((substrate/Ksa),2.0) / ( 1+substrate/Ksc+substrate/Ksa+pow((substrate/Ksa),2.0) );
+}
+
+double kin_ping_pong_bi_bi_rev(double Vf,double substratea,double substrateb,double productp,double productq,double Keq,double Kiq,double Kma,double Kmb,double Vr,double Kmq,double Kia,double Kmp)
+{
+    return Vf*( substratea*substrateb-productp*productq/Keq ) / (substratea*substrateb*(1+productq/Kiq)+Kma*substrateb+Kmb*substratea+Vf/(Vr*Keq)*(Kmq*productp*(1+substratea/Kia)+productq*(Kmp+productp)));
+}
+
+double kin_hill_1_modifier_rev(double Vf,double substrate,double Shalve,double product,double Keq,double Phalve,double h,double modifier,double Mhalve,double alpha)
+{
+    return Vf*substrate/Shalve*(1-product/(substrate*Keq))*pow((substrate/Shalve+product/Phalve),(h-1.0)) / ( (1+pow((modifier/Mhalve),h))/(1+alpha*pow((modifier/Mhalve),h))+pow((substrate/Shalve + product/Phalve),h) );
+}
+
+double kin_hill_2_modifiers_rev(double Vf,double substrate,double Shalve,double product,double Keq,double Phalve,double h,double modifierA,double MAhalve,double modifierB,double MBhalve,double alphaA,double alphaB,double alphaAB)
+{
+    return Vf*substrate/Shalve*(1-product/(substrate*Keq))*pow((substrate/Shalve+product/Phalve),(h-1.0)) / ( (1+pow((modifierA/MAhalve),h) + 1+pow((modifierB/MBhalve),h)) / ( 1+alphaA*pow((modifierA/MAhalve),h)+alphaB*pow((modifierB/MBhalve),h)+alphaA*alphaB*alphaAB*pow((modifierA/MAhalve),h)*pow((modifierB/MBhalve),h) ) + pow((substrate/Shalve + product/Phalve),h) );
+}
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/include/mexmathaddon.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/include/mexmathaddon.h
new file mode 100644
index 0000000000000000000000000000000000000000..9f781153aada50d5355e4a9295571ff0e9e49d7b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/include/mexmathaddon.h
@@ -0,0 +1,279 @@
+/*
+ * mexmathaddon.h: Include file for automatically generated MEX model files.
+ *
+ * Information:
+ * ============
+ * SBPD Package - Systems Biology Parameter Determination Package
+ * Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+ */
+
+#define pi 3.141592653589793
+
+#ifdef __LCC__
+double max(double a, double b)
+{
+    if (a<b) return b;
+    else return a;
+}
+
+double min(double a, double b)
+{
+    if (a>b) return b;
+    else return a;
+}
+#endif
+
+#ifdef __GNUC__
+double max(double a, double b)
+{
+    return fmax(a,b);
+}
+
+double min(double a, double b)
+{
+    return fmin(a,b);
+}
+#endif
+
+
+
+double minSB(int nargs, ...)
+{
+    int k;
+    double minimum;
+    double checkmin;
+    va_list vararg;
+    va_start(vararg, nargs);
+    minimum = va_arg(vararg, double);
+    for (k=1; k<nargs; k++ ) {
+        checkmin = va_arg(vararg, double);
+        if (checkmin < minimum) {
+            minimum = checkmin;
+        }
+    }
+    va_end (vararg);
+    return minimum;
+}
+
+double maxSB(int nargs, ...)
+{
+    int k;
+    double maximum;
+    double checkmax;
+    va_list vararg;
+    va_start(vararg, nargs);
+    maximum = va_arg(vararg, double);
+    for (k=1; k<nargs; k++ ) {
+        checkmax = va_arg(vararg, double);
+        if (checkmax > maximum) {
+            maximum = checkmax;
+        }
+    }
+    va_end (vararg);
+    return maximum;
+}
+
+double indexmaxSB(int nargs, ...)
+{
+    int k;
+    double maximum;
+    double indexmaximum;
+    double checkmax;
+    va_list vararg;
+    va_start(vararg, nargs);
+    maximum = va_arg(vararg, double);
+    indexmaximum = 1;
+    for (k=1; k<nargs; k++ ) {
+        checkmax = va_arg(vararg, double);
+        if (checkmax > maximum) {
+            maximum = checkmax;
+            indexmaximum = (double)k+1;
+        }
+    }
+    va_end (vararg);
+    return indexmaximum;
+}
+
+double sign(double a)
+{
+    if (a<0) return -1;
+    else if (a==0) return 0;
+    else if (a>0) return 1;
+    else return a;
+}
+
+double absSB(double a)
+{
+    if (a < 0) return -a;
+    else return a;
+}
+
+double mod(double a, double b)
+{
+    if (b == 0) return a;
+    else if (a == b) return 0;
+    return sign(b)*absSB(a-floor(a/b)*b);
+}
+
+double nthrootSB(double a, double n)
+{
+    return pow(a,1.0/n);
+}
+
+double andSB(int nargs, ...)
+{
+    int k;
+    va_list vararg;
+    va_start(vararg, nargs);
+    for (k=0; k<nargs; k++ ) {
+        if (va_arg(vararg, double) == 0) {
+            va_end (vararg);
+            return 0;
+        }
+    }
+    va_end (vararg);
+    return 1;
+}
+
+double orSB(int nargs, ...)
+{
+    int k;
+    va_list vararg;
+    va_start(vararg, nargs);
+    for (k=0; k<nargs; k++ ) {
+        if (va_arg(vararg, double) != 0) {
+            va_end (vararg);
+            return 1;
+        }
+    }
+    va_end (vararg);
+    return 0;
+}
+
+double piecewiseSB(int nargs, ...)
+{
+    int k, oddnumber;
+    double *data;
+    double returnvalue;
+    va_list vararg;
+    va_start(vararg, nargs);
+    /* Read in all variable input arguments in double array */
+    data = (double *)mxCalloc(nargs,sizeof(double));
+    for (k=0; k<nargs; k++ ) {
+        data[k] = va_arg(vararg, double);
+    }
+    /* 
+       Determine result
+       Check if odd or even number of input arguments
+     */
+    oddnumber = nargs % 2;
+    for (k=0;k<nargs-oddnumber;k+=2) {
+        if (data[k+1] != 0) {
+            returnvalue = data[k];
+            mxFree(data); /* free temporary array */
+            return returnvalue;
+        }
+    }
+    if (oddnumber != 0) {
+            returnvalue = data[nargs-1];
+            mxFree(data); /* free temporary array */
+            return returnvalue;
+    }
+    else {
+        mexErrMsgTxt("A piecewise statement is wrongly defined - missing (but needed) default value.");
+        mxFree(data); /* free temporary array */
+        return 0; /* statement never reached */
+    }
+}
+
+double piecewiseT0SB(int nargs, ...) /* does the same as the piecewiseSB function but does not lead to added events in the simulation model */
+{
+    int k, oddnumber;
+    double *data;
+    double returnvalue;
+    va_list vararg;
+    va_start(vararg, nargs);
+    /* Read in all variable input arguments in double array */
+    data = (double *)mxCalloc(nargs,sizeof(double));
+    for (k=0; k<nargs; k++ ) {
+        data[k] = va_arg(vararg, double);
+    }
+    /* 
+       Determine result
+       Check if odd or even number of input arguments
+     */
+    oddnumber = nargs % 2;
+    for (k=0;k<nargs-oddnumber;k+=2) {
+        if (data[k+1] != 0) {
+            returnvalue = data[k];
+            mxFree(data); /* free temporary array */
+            return returnvalue;
+        }
+    }
+    if (oddnumber != 0) {
+            returnvalue = data[nargs-1];
+            mxFree(data); /* free temporary array */
+            return returnvalue;
+    }
+    else {
+        mexErrMsgTxt("A piecewise statement is wrongly defined - missing (but needed) default value.");
+        mxFree(data); /* free temporary array */
+        return 0; /* statement never reached */
+    }
+}
+
+
+double piecewiseSmoothSB(double t,double y0,double y1,double alpha) 
+{
+
+return (y0+y1*exp(alpha*t))/(1+exp(alpha*t));
+
+}
+        
+
+double gt(double a, double b)
+{
+    if (a > b) return 1;
+    else return 0;
+}
+
+double ge(double a, double b)
+{
+    if (a >= b) return 1;
+    else return 0;
+}
+
+double lt(double a, double b)
+{
+    if (a < b) return 1;
+    else return 0;
+}
+
+double le(double a, double b)
+{
+    if (a <= b) return 1;
+    else return 0;
+}
+
+double eq(double a, double b)
+{
+    if (a*b < 0) return 0;
+    else if ( absSB(a-b) < 10.0*mxGetEps() ) return 1;
+    else return 0;
+}
+
+/* THIS FUNCTION IS NOT NEEDED ANYMORE ... in SBPDmakeMEXmodel the relevant parts have been commented out 
+ * and in SBPDsimulate a check has been included that gives an error is a model contains a delaySB function.
+ *
+double delaySB(double input, double tau, double time, char *queuename)
+{
+    mxArray *callArg[4];
+    mxArray *outArg[1];
+    callArg[0] = mxCreateDoubleScalar(input);
+    callArg[1] = mxCreateDoubleScalar(tau);
+    callArg[2] = mxCreateDoubleScalar(time);
+    callArg[3] = mxCreateString(queuename);
+    mexCallMATLAB(1, outArg, 4, callArg, "delaySB");
+    return mxGetScalar(outArg[0]);
+}
+*/
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/include/mexsplineaddon.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/include/mexsplineaddon.h
new file mode 100644
index 0000000000000000000000000000000000000000..ce7bfda5212b4b89c4f4533a7744135bac94e317
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/include/mexsplineaddon.h
@@ -0,0 +1,1895 @@
+/*
+ * mexsplineaddon.h: contains the function interpcseSB, interpcsexSB and '
+ *      the function interpcsSB
+ *      Cubic spline interpolation with (and without) endpoints for use 
+ *      by the CVODE integrator in the SBPD package
+ *
+ * The interpcsSB is a function for cubic spline interpolation, but without the 
+ * possibility of defining slopes at the endpoints.
+ * 
+ * The interpcseSB function allows to define slopes at the endpoints. The 
+ * spline coefficients are only calculated once and then only evaluated (faster)
+ * 
+ * the interpcsexSB function determines the spline coefficients each time, allowing to 
+ * implement time dependent spline functions (slower).
+ *
+ */
+
+/* interpcseSB and interpcsexSB FUNCTIONS:
+ * Original C-code for spline interpolation taken from:
+ *   http://www.mech.uq.edu.au/staff/jacobs/nm_lib/cmathsrc/spline.c
+ *
+ * The syntax of this MEX function (to be used via CVODE interface) is as follows:
+ *
+ * yy = interpcseSB(nargs,n,x1,x2,...,xn,y1,y2,...,yn,xx)
+ * yy = interpcseSB(nargs,n,e1,e2,x1,x2,...,xn,y1,y2,...,yn,xx)
+ *
+ * nargs:  number of arguments
+ * n:      number of points in the x and y vectors
+ * xi:     x-values 
+ * yi:     y-values
+ * xx:     x-value at which to evaluate the spline function (do NOT allow multiple)
+ * e1,e2:  endpoint derivatives (if specified, both need to be given)
+ * yy:     interpolated value
+ */
+
+/*
+ *========================================================================
+ * Initialization of the spline related functions
+ *========================================================================
+ */
+void spline (int n, int e1, int e2, double s1, double s2, double x[], double y[], double b[], double c[], double d[], int *flag);
+double seval (int n, double xx, double x[], double y[], double b[], double c[], double d[], int *last);
+double deriv (int n, double xx, double x[], double b[], double c[], double d[], int *last);
+
+/*
+ *========================================================================
+ * Declare variables for the interpcseSB function
+ *========================================================================
+ */
+#define MAX_INTERPCSESB 10000    /* defined maximum number of interpcseSB functions in the model */
+int*    interpcseSB_check = NULL; /* is initialized each new integration start to NULL ... required */
+double* xvec[MAX_INTERPCSESB];
+double* yvec[MAX_INTERPCSESB];
+double* bvec[MAX_INTERPCSESB];
+double* cvec[MAX_INTERPCSESB];
+double* dvec[MAX_INTERPCSESB];
+
+int*    interpcseSlopeSB_check = NULL; /* is initialized each new integration start to NULL ... required */
+double* xvecslope[MAX_INTERPCSESB];
+double* yvecslope[MAX_INTERPCSESB];
+double* bvecslope[MAX_INTERPCSESB];
+double* cvecslope[MAX_INTERPCSESB];
+double* dvecslope[MAX_INTERPCSESB];
+
+/*
+ *========================================================================
+ * INTERFACE FUNCTION for interpcseSB ... 
+ *========================================================================
+ */
+double interpcseSB(int nargs, ...)
+{
+    /*************************************************************/
+    /* Define the variables needed for the spline function calls */
+    /*************************************************************/
+    int    index_pw; /* index of the interpcseSB function */
+    int    n;
+    double *x;
+    double *y;
+    double xx;
+    double s1,s2;
+    int    e1,e2;
+    double *b;
+    double *c;
+    double *d;
+    int    flag;
+    int    last;
+    int    k;
+    double yy;
+    int    newCall;
+    double b2,c2,d2,x0,x1,y0,y1;
+    
+    /***************************************/
+    /* Handle the variable input arguments */
+    /***************************************/
+    /* Initialize the va_list */
+    va_list vararg;
+    va_start(vararg, nargs);
+    /* Get the index of the current interpcseSB function */
+    index_pw = (int) va_arg(vararg, double);
+    /* Get the number of the x and y axis nodes for interpolation */
+    n = (int) va_arg(vararg, double);
+    /* Get the xx value at which to interpolate */
+    xx = va_arg(vararg, double);
+    
+    /* Check if too many interpcseSB functions in the model (unlikely) */
+    if (index_pw >= MAX_INTERPCSESB) {
+        mexErrMsgTxt("interpcseSB_CVODE: To many calls to interpcseSB in the model.");
+    }
+    
+    /* Check if memory already obtained for handling the different calls */
+    if (interpcseSB_check == NULL) interpcseSB_check = (int *) mxCalloc(MAX_INTERPCSESB, sizeof(int));
+    
+    /* Check if new call or subsequent call */
+    if (interpcseSB_check[index_pw] == 69) {
+        newCall = 0;
+    } else {
+        newCall = 1;
+        interpcseSB_check[index_pw] = 69;
+    }
+
+    if (newCall == 1 || n == 2) {
+        /* First call to this function ... get the information */
+        /* Check if the number of input argument is plausible and define slopes */
+        if (nargs == 3+2*n) {
+            /* Plausible, but no slopes defined */
+            e1 = 0; s1 = 0; /* set s1 to 0 but it is not used */
+            e2 = 0; s2 = 0; /* set s2 to 0 but it is not used */
+        } else if (nargs == 3+2*n+2) {
+            /* Plausible, slopes are defined */
+            e1 = 1; s1 = va_arg(vararg, double);
+            e2 = 1; s2 = va_arg(vararg, double);
+        } else {
+            mexErrMsgTxt("interpcseSB_CVODE: Incorrect number of input arguments (increase MAX_INTERPCSESB in mexsplineaddon.h).");
+        }
+        
+        /***********/
+        /* If n==2 */
+        /***********/
+        if (n == 2) {
+            if (e1 == 0 || e2 == 0) mexErrMsgTxt("interpcseSB: n=2 requires the definition of slopes.");
+            x0 = va_arg(vararg, double);
+            x1 = va_arg(vararg, double);
+            y0 = va_arg(vararg, double);
+            y1 = va_arg(vararg, double);
+            /* End the variable input handling */
+            va_end (vararg);
+            b2 = s1;
+            c2 = -(-3.0*y1+3.0*y0+(s2+2.0*s1)*x1+(-s2-2.0*s1)*x0)/(pow(x1, 2.0)-2.0*x0*x1+pow(x0, 2.0));
+            d2 = (-2.0*y1+2.0*y0+(s2+s1)*x1+(-s2-s1)*x0)/(pow(x1, 3.0)-3.0*x0*pow(x1, 2.0)+3.0*pow(x0, 2.0)*x1-pow(x0, 3.0));
+            yy = y0 + b2*(xx-x0) + c2*pow(xx-x0, 2.0) + d2*pow(xx-x0, 3.0);   
+        } else {
+            /***********/
+            /* If n!=2 */
+            /***********/
+            /* Allocate memory for x and y */
+            x  = (double *) mxCalloc(n, sizeof(double));
+            y  = (double *) mxCalloc(n, sizeof(double));
+            /* Parse input arguments into x and y */
+            for (k=0;k<n;k++) x[k] = va_arg(vararg, double);
+            for (k=0;k<n;k++) y[k] = va_arg(vararg, double);
+            /* End the variable input handling */
+            va_end (vararg);
+        
+            /*****************************/
+            /* Allocate memory for b,c,d */
+            /*****************************/
+            b  = (double *) mxCalloc(n, sizeof(double));
+            c  = (double *) mxCalloc(n, sizeof(double));
+            d  = (double *) mxCalloc(n, sizeof(double));
+            
+            /****************************/
+            /* Call the spline function */
+            /****************************/
+            spline(n, e1, e2, s1, s2, x, y, b, c, d, &flag);
+            
+            /*********************************/
+            /* Save b,c,d,x,y for next calls */
+            /*********************************/
+            xvec[index_pw] = x;
+            yvec[index_pw] = y;
+            bvec[index_pw] = b;
+            cvec[index_pw] = c;
+            dvec[index_pw] = d;
+            
+            /***************************************/
+            /* Call the spline evaluation function */
+            /***************************************/
+            yy = seval (n, xx, x, y, b, c, d, &last);            
+        }
+    } else {
+        /* get x,y,b,c,d pointers */
+        x = xvec[index_pw];
+        y = yvec[index_pw];
+        b = bvec[index_pw];
+        c = cvec[index_pw];
+        d = dvec[index_pw];
+        /***************************************/
+        /* Call the spline evaluation function */
+        /***************************************/
+        yy = seval(n, xx, x, y, b, c, d, &last);
+    }
+    
+    /*********************************/
+    /* Return the interpolated value */
+    /*********************************/
+    return yy;
+}
+
+
+/*
+ *========================================================================
+ * INTERFACE FUNCTION for interpcseSB ... 
+ *========================================================================
+ */
+double interpcseSlopeSB(int nargs, ...)
+{
+    /*************************************************************/
+    /* Define the variables needed for the spline function calls */
+    /*************************************************************/
+    int    index_pw; /* index of the interpcseSlopeSB function */
+    int    n;
+    double *x;
+    double *y;
+    double xx;
+    double s1,s2;
+    int    e1,e2;
+    double *b;
+    double *c;
+    double *d;
+    int    flag;
+    int    last;
+    int    k;
+    double yy;
+    int    newCall;
+    double b2,c2,d2,x0,x1,y0,y1;
+    
+    /***************************************/
+    /* Handle the variable input arguments */
+    /***************************************/
+    /* Initialize the va_list */
+    va_list vararg;
+    va_start(vararg, nargs);
+    /* Get the index of the current interpcseSlopeSB function */
+    index_pw = (int) va_arg(vararg, double);
+    /* Get the number of the x and y axis nodes for interpolation */
+    n = (int) va_arg(vararg, double);
+    /* Get the xx value at which to interpolate */
+    xx = va_arg(vararg, double);
+    
+    /* Check if too many interpcseSlopeSB functions in the model (unlikely) */
+    if (index_pw >= MAX_INTERPCSESB) {
+        mexErrMsgTxt("interpcseSlopeSB_CVODE: To many calls to interpcseSB in the model.");
+    }
+    
+    /* Check if memory already obtained for handling the different calls */
+    if (interpcseSlopeSB_check == NULL) interpcseSlopeSB_check = (int *) mxCalloc(MAX_INTERPCSESB, sizeof(int));
+    
+    /* Check if new call or subsequent call */
+    if (interpcseSlopeSB_check[index_pw] == 69) {
+        newCall = 0;
+    } else {
+        newCall = 1;
+        interpcseSlopeSB_check[index_pw] = 69;
+    }
+
+    if (newCall == 1 || n == 2) {
+        /* First call to this function ... get the information */
+        /* Check if the number of input argument is plausible and define slopes */
+        if (nargs == 3+2*n) {
+            /* Plausible, but no slopes defined */
+            e1 = 0; s1 = 0; /* set s1 to 0 but it is not used */
+            e2 = 0; s2 = 0; /* set s2 to 0 but it is not used */
+        } else if (nargs == 3+2*n+2) {
+            /* Plausible, slopes are defined */
+            e1 = 1; s1 = va_arg(vararg, double);
+            e2 = 1; s2 = va_arg(vararg, double);
+        } else {
+            mexErrMsgTxt("interpcseSlopeSB_CVODE: Incorrect number of input arguments (increase MAX_INTERPCSESB in mexsplineaddon.h).");
+        }
+        
+        /***********/
+        /* If n==2 */
+        /***********/
+        if (n == 2) {
+            if (e1 == 0 || e2 == 0) mexErrMsgTxt("interpcseSlopeSB_CVODE: n=2 requires the definition of slopes.");
+            x0 = va_arg(vararg, double);
+            x1 = va_arg(vararg, double);
+            y0 = va_arg(vararg, double);
+            y1 = va_arg(vararg, double);
+            /* End the variable input handling */
+            va_end (vararg);
+            b2 = s1;
+            c2 = -(-3.0*y1+3.0*y0+(s2+2.0*s1)*x1+(-s2-2.0*s1)*x0)/(pow(x1, 2.0)-2.0*x0*x1+pow(x0, 2.0));
+            d2 = (-2.0*y1+2.0*y0+(s2+s1)*x1+(-s2-s1)*x0)/(pow(x1, 3.0)-3.0*x0*pow(x1, 2.0)+3.0*pow(x0, 2.0)*x1-pow(x0, 3.0));
+            yy = b2 + 2.0*c2*(xx-x0) + 3.0*d2*pow(xx-x0, 2.0);   
+        } else {
+            /***********/
+            /* If n!=2 */
+            /***********/
+            /* Allocate memory for x and y */
+            x  = (double *) mxCalloc(n, sizeof(double));
+            y  = (double *) mxCalloc(n, sizeof(double));
+            /* Parse input arguments into x and y */
+            for (k=0;k<n;k++) x[k] = va_arg(vararg, double);
+            for (k=0;k<n;k++) y[k] = va_arg(vararg, double);
+            /* End the variable input handling */
+            va_end (vararg);
+        
+            /*****************************/
+            /* Allocate memory for b,c,d */
+            /*****************************/
+            b  = (double *) mxCalloc(n, sizeof(double));
+            c  = (double *) mxCalloc(n, sizeof(double));
+            d  = (double *) mxCalloc(n, sizeof(double));
+            
+            /****************************/
+            /* Call the spline function */
+            /****************************/
+            spline(n, e1, e2, s1, s2, x, y, b, c, d, &flag);
+            
+            /*********************************/
+            /* Save b,c,d,x,y for next calls */
+            /*********************************/
+            xvecslope[index_pw] = x;
+            yvecslope[index_pw] = y;
+            bvecslope[index_pw] = b;
+            cvecslope[index_pw] = c;
+            dvecslope[index_pw] = d;
+            
+            /***************************************/
+            /* Call the spline evaluation function */
+            /***************************************/
+            yy = deriv(n, xx, x, b, c, d, &last);            
+        }
+    } else {
+        /* get x,y,b,c,d pointers */
+        x = xvecslope[index_pw];
+        y = yvecslope[index_pw];
+        b = bvecslope[index_pw];
+        c = cvecslope[index_pw];
+        d = dvecslope[index_pw];
+        /***************************************/
+        /* Call the spline evaluation function */
+        /***************************************/
+        yy = deriv(n, xx, x, b, c, d, &last);
+    }
+    
+    /*********************************/
+    /* Return the interpolated value */
+    /*********************************/
+    return yy;
+}
+
+/*
+ *========================================================================
+ * INTERFACE FUNCTION for interpcsexSB ... 
+ *========================================================================
+ */
+double interpcsexSB(int nargs, ...)
+{
+    /*************************************************************/
+    /* Define the variables needed for the spline function calls */
+    /*************************************************************/
+    int    n;
+    double *x;
+    double *y;
+    double xx;
+    double s1,s2;
+    int    e1,e2;
+    double *b;
+    double *c;
+    double *d;
+    int    flag;
+    int    last;
+    int    k;
+    double yy;
+    double b2, c2, d2;
+    double x0,x1,y0,y1;
+    
+    /***************************************/
+    /* Handle the variable input arguments */
+    /***************************************/
+    /* Initialize the va_list */
+    va_list vararg;
+    va_start(vararg, nargs);
+    /* Get the number of the x and y axis nodes for interpolation */
+    n = (int) va_arg(vararg, double);
+    /* Check if the number of input argument is plausible and define slopes */
+    if (nargs == 1+2*n+1) {
+        /* Plausible, but no slopes defined */
+        e1 = 0; s1 = 0; /* set s1 to 0 but it is not used */
+        e2 = 0; s2 = 0; /* set s2 to 0 but it is not used */
+    } else if (nargs == 1+2*n+1+2) {
+        /* Plausible, slopes are defined */
+        e1 = 1; s1 = va_arg(vararg, double);
+        e2 = 1; s2 = va_arg(vararg, double);
+    } else {
+        mexErrMsgTxt("interpcseSB_CVODE: Incorrect number of input arguments.");
+    }
+    
+    /***********/
+    /* If n==2 */
+    /***********/
+    if (n==2) {        
+        if (e1 == 0 || e2 == 0) mexErrMsgTxt("interpcseSB: n=2 requires the definition of slopes.");
+        x0 = va_arg(vararg, double);
+        x1 = va_arg(vararg, double);
+        y0 = va_arg(vararg, double);
+        y1 = va_arg(vararg, double);
+
+        /* Get the xx value at which to interpolate */
+        xx = va_arg(vararg, double);
+        /* End the variable input handling */
+        va_end(vararg);
+
+        b2 = s1;
+        c2 = -(-3.0*y1+3.0*y0+(s2+2.0*s1)*x1+(-s2-2.0*s1)*x0)/(pow(x1,2.0)-2.0*x0*x1+pow(x0,2.0));
+        d2 = (-2.0*y1+2.0*y0+(s2+s1)*x1+(-s2-s1)*x0)/(pow(x1,3.0)-3.0*x0*pow(x1,2.0)+3.0*pow(x0,2.0)*x1-pow(x0,3.0));
+        yy = y0 + b2*(xx-x0) + c2*pow(xx-x0,2.0) + d2*pow(xx-x0,3.0);
+    } else {
+        /***********/
+        /* If n!=2 */
+        /***********/
+        /* Allocate memory for x and y */
+        x  = (double *) mxCalloc(n, sizeof(double));
+        y  = (double *) mxCalloc(n, sizeof(double));
+        /* Parse input arguments into x and y */
+        for (k=0;k<n;k++) x[k] = va_arg(vararg, double);
+        for (k=0;k<n;k++) y[k] = va_arg(vararg, double);
+        
+        /* Get the xx value at which to interpolate */
+        xx = va_arg(vararg, double);
+        /* End the variable input handling */
+        va_end(vararg);
+        
+        /*****************************/
+        /* Allocate memory for b,c,d */
+        /*****************************/
+        b  = (double *) mxCalloc(n, sizeof(double));
+        c  = (double *) mxCalloc(n, sizeof(double));
+        d  = (double *) mxCalloc(n, sizeof(double));
+        
+        /****************************/
+        /* Call the spline function */
+        /****************************/
+        spline(n, e1, e2, s1, s2, x, y, b, c, d, &flag);
+        
+        /***************************************/
+        /* Call the spline evaluation function */
+        /***************************************/
+        yy = seval(n, xx, x, y, b, c, d, &last);
+        
+        /***************/
+        /* Free memory */
+        /***************/
+        mxFree(x);
+        mxFree(y);
+        mxFree(b);
+        mxFree(c);
+        mxFree(d);
+    }
+    
+    /*********************************/
+    /* Return the interpolated value */
+    /*********************************/
+    return yy;
+}
+
+
+/*
+ *========================================================================
+ * INTERFACE FUNCTION for interpcsexSlopeSB ... 
+ *========================================================================
+ */
+double interpcsexSlopeSB(int nargs, ...)
+{
+    /*************************************************************/
+    /* Define the variables needed for the spline function calls */
+    /*************************************************************/
+    int    n;
+    double *x;
+    double *y;
+    double xx;
+    double s1,s2;
+    int    e1,e2;
+    double *b;
+    double *c;
+    double *d;
+    int    flag;
+    int    last;
+    int    k;
+    double yy;
+    double b2, c2, d2;
+    double x0,x1,y0,y1;
+    
+    /***************************************/
+    /* Handle the variable input arguments */
+    /***************************************/
+    /* Initialize the va_list */
+    va_list vararg;
+    va_start(vararg, nargs);
+    /* Get the number of the x and y axis nodes for interpolation */
+    n = (int) va_arg(vararg, double);
+    /* Check if the number of input argument is plausible and define slopes */
+    if (nargs == 1+2*n+1) {
+        /* Plausible, but no slopes defined */
+        e1 = 0; s1 = 0; /* set s1 to 0 but it is not used */
+        e2 = 0; s2 = 0; /* set s2 to 0 but it is not used */
+    } else if (nargs == 1+2*n+1+2) {
+        /* Plausible, slopes are defined */
+        e1 = 1; s1 = va_arg(vararg, double);
+        e2 = 1; s2 = va_arg(vararg, double);
+    } else {
+        mexErrMsgTxt("interpcsexSlopeSB_CVODE: Incorrect number of input arguments.");
+    }
+    
+    /***********/
+    /* If n==2 */
+    /***********/
+    if (n==2) {        
+        if (e1 == 0 || e2 == 0) mexErrMsgTxt("interpcsexSlopeSB: n=2 requires the definition of slopes.");
+        x0 = va_arg(vararg, double);
+        x1 = va_arg(vararg, double);
+        y0 = va_arg(vararg, double);
+        y1 = va_arg(vararg, double);
+
+        /* Get the xx value at which to interpolate */
+        xx = va_arg(vararg, double);
+        /* End the variable input handling */
+        va_end(vararg);
+
+        b2 = s1;
+        c2 = -(-3.0*y1+3.0*y0+(s2+2.0*s1)*x1+(-s2-2.0*s1)*x0)/(pow(x1,2.0)-2.0*x0*x1+pow(x0,2.0));
+        d2 = (-2.0*y1+2.0*y0+(s2+s1)*x1+(-s2-s1)*x0)/(pow(x1,3.0)-3.0*x0*pow(x1,2.0)+3.0*pow(x0,2.0)*x1-pow(x0,3.0));
+        yy = b2 + 2.0*c2*(xx-x0) + 3.0*d2*pow(xx-x0,2.0);
+    } else {
+        /***********/
+        /* If n!=2 */
+        /***********/
+        /* Allocate memory for x and y */
+        x  = (double *) mxCalloc(n, sizeof(double));
+        y  = (double *) mxCalloc(n, sizeof(double));
+        /* Parse input arguments into x and y */
+        for (k=0;k<n;k++) x[k] = va_arg(vararg, double);
+        for (k=0;k<n;k++) y[k] = va_arg(vararg, double);
+        
+        /* Get the xx value at which to interpolate */
+        xx = va_arg(vararg, double);
+        /* End the variable input handling */
+        va_end(vararg);
+        
+        /*****************************/
+        /* Allocate memory for b,c,d */
+        /*****************************/
+        b  = (double *) mxCalloc(n, sizeof(double));
+        c  = (double *) mxCalloc(n, sizeof(double));
+        d  = (double *) mxCalloc(n, sizeof(double));
+        
+        /****************************/
+        /* Call the spline function */
+        /****************************/
+        spline(n, e1, e2, s1, s2, x, y, b, c, d, &flag);
+        
+        /***************************************/
+        /* Call the spline evaluation function */
+        /***************************************/
+        yy = deriv(n, xx, x, b, c, d, &last);
+        
+        /***************/
+        /* Free memory */
+        /***************/
+        mxFree(x);
+        mxFree(y);
+        mxFree(b);
+        mxFree(c);
+        mxFree(d);
+    }
+    
+    /*********************************/
+    /* Return the interpolated value */
+    /*********************************/
+    return yy;
+}
+
+/*=========================================================================
+   Cubic spline coefficients
+   -------------------------
+   Evaluate the coefficients b[i], c[i], d[i], i = 0, 1, .. n-1 for
+   a cubic interpolating spline
+
+   S(xx) = Y[i] + b[i] * w + c[i] * w**2 + d[i] * w**3
+   where w = xx - x[i]
+   and   x[i] <= xx <= x[i+1]
+
+   The n supplied data points are x[i], y[i], i = 0 ... n-1.
+
+   Input :
+   -------
+   n       : The number of data points or knots (n >= 2)
+   end1,
+   end2    : = 1 to specify the slopes at the end points
+             = 0 to obtain the default conditions
+   slope1,
+   slope2  : the slopes at the end points x[0] and x[n-1]
+             respectively
+   x[]     : the abscissas of the knots in strictly
+             increasing order
+   y[]     : the ordinates of the knots
+
+   Output :
+   --------
+   b, c, d : arrays of spline coefficients as defined above
+             (See note 2 for a definition.)
+   iflag   : status flag
+            = 0 normal return
+            = 1 less than two data points; cannot interpolate
+            = 2 x[] are not in ascending order
+
+   This C code written by ...  Peter & Nigel,
+   ----------------------      Design Software,
+                               42 Gubberley St,
+                               Kenmore, 4069,
+                               Australia.
+
+   Version ... 1.1, 30 September 1987
+   -------     2.0, 6 April 1989    (start with zero subscript)
+                                     remove ndim from parameter list
+               2.1, 28 April 1989   (check on x[])
+               2.2, 10 Oct   1989   change number order of matrix
+
+   Notes ...
+   -----
+   (1) The accompanying function seval() may be used to evaluate the
+       spline while deriv will provide the first derivative.
+   (2) Using p to denote differentiation
+       y[i] = S(X[i])
+       b[i] = Sp(X[i])
+       c[i] = Spp(X[i])/2
+       d[i] = Sppp(X[i])/6  ( Derivative from the right )
+   (3) Since the zero elements of the arrays ARE NOW used here,
+       all arrays to be passed from the main program should be
+       dimensioned at least [n].  These routines will use elements
+       [0 .. n-1].
+   (4) Adapted from the text
+       Forsythe, G.E., Malcolm, M.A. and Moler, C.B. (1977)
+       "Computer Methods for Mathematical Computations"
+       Prentice Hall
+   (5) Note that although there are only n-1 polynomial segments,
+       n elements are requird in b, c, d.  The elements b[n-1],
+       c[n-1] and d[n-1] are set to continue the last segment
+       past x[n-1].
+=========================================================================*/
+void spline (int n, int end1, int end2,
+            double slope1, double slope2,
+            double x[], double y[],
+            double b[], double c[], double d[],
+            int *iflag)
+{  /* begin procedure spline() */
+
+int    nm1, ib, i;
+double t;
+int    ascend;
+
+nm1    = n - 1;
+*iflag = 0;
+
+if (n < 2)
+  {  /* no possible interpolation */
+  *iflag = 1;
+  return;
+  }
+
+ascend = 1;
+for (i = 1; i < n; ++i) if (x[i] <= x[i-1]) ascend = 0;
+if (!ascend)
+   {
+   *iflag = 2;
+   return;
+   }
+
+if (n >= 3)
+   {    /* ---- At least quadratic ---- */
+
+   /* ---- Set up the symmetric tri-diagonal system
+           b = diagonal
+           d = offdiagonal
+           c = right-hand-side  */
+   d[0] = x[1] - x[0];
+   c[1] = (y[1] - y[0]) / d[0];
+   for (i = 1; i < nm1; ++i)
+      {
+      d[i]   = x[i+1] - x[i];
+      b[i]   = 2.0 * (d[i-1] + d[i]);
+      c[i+1] = (y[i+1] - y[i]) / d[i];
+      c[i]   = c[i+1] - c[i];
+      }
+
+   /* ---- Default End conditions
+           Third derivatives at x[0] and x[n-1] obtained
+           from divided differences  */
+   b[0]   = -d[0];
+   b[nm1] = -d[n-2];
+   c[0]   = 0.0;
+   c[nm1] = 0.0;
+   if (n != 3)
+      {
+      c[0]   = c[2] / (x[3] - x[1]) - c[1] / (x[2] - x[0]);
+      c[nm1] = c[n-2] / (x[nm1] - x[n-3]) - c[n-3] / (x[n-2] - x[n-4]);
+      c[0]   = c[0] * d[0] * d[0] / (x[3] - x[0]);
+      c[nm1] = -c[nm1] * d[n-2] * d[n-2] / (x[nm1] - x[n-4]);
+      }
+
+   /* Alternative end conditions -- known slopes */
+   if (end1 == 1)
+      {
+      b[0] = 2.0 * (x[1] - x[0]);
+      c[0] = (y[1] - y[0]) / (x[1] - x[0]) - slope1;
+      }
+   if (end2 == 1)
+      {
+      b[nm1] = 2.0 * (x[nm1] - x[n-2]);
+      c[nm1] = slope2 - (y[nm1] - y[n-2]) / (x[nm1] - x[n-2]);
+      }
+
+   /* Forward elimination */
+   for (i = 1; i < n; ++i)
+     {
+     t    = d[i-1] / b[i-1];
+     b[i] = b[i] - t * d[i-1];
+     c[i] = c[i] - t * c[i-1];
+     }
+
+   /* Back substitution */
+   c[nm1] = c[nm1] / b[nm1];
+   for (ib = 0; ib < nm1; ++ib)
+      {
+      i    = n - ib - 2;
+      c[i] = (c[i] - d[i] * c[i+1]) / b[i];
+      }
+
+   /* c[i] is now the sigma[i] of the text */
+
+   /* Compute the polynomial coefficients */
+   b[nm1] = (y[nm1] - y[n-2]) / d[n-2] + d[n-2] * (c[n-2] + 2.0 * c[nm1]);
+   for (i = 0; i < nm1; ++i)
+      {
+      b[i] = (y[i+1] - y[i]) / d[i] - d[i] * (c[i+1] + 2.0 * c[i]);
+      d[i] = (c[i+1] - c[i]) / d[i];
+      c[i] = 3.0 * c[i];
+      }
+   c[nm1] = 3.0 * c[nm1];
+   d[nm1] = d[n-2];
+
+   }  /* at least quadratic */
+
+else  /* if n >= 3 */
+   {  /* linear segment only  */
+   b[0] = (y[1] - y[0]) / (x[1] - x[0]);
+   c[0] = 0.0;
+   d[0] = 0.0;
+   b[1] = b[0];
+   c[1] = 0.0;
+   d[1] = 0.0;
+   }
+}  /* end of spline() */
+
+
+/*-------------------------------------------------------------------*/
+/*-----------------------------------------------------------------*/
+/*-----------------------------------------------------------------*/
+double seval (int n, double u,
+              double x[], double y[],
+              double b[], double c[], double d[],
+              int *last)
+/*-----------------------------------------------------------------*/
+/*Purpose ...
+  -------
+  Evaluate the cubic spline function
+
+  S(xx) = y[i] + b[i] * w + c[i] * w**2 + d[i] * w**3
+  where w = u - x[i]
+  and   x[i] <= u <= x[i+1]
+  Note that Horner's rule is used.
+  If u < x[0]   then i = 0 is used.
+  If u > x[n-1] then i = n-1 is used.
+
+  Input :
+  -------
+  n       : The number of data points or knots (n >= 2)
+  u       : the abscissa at which the spline is to be evaluated
+  Last    : the segment that was last used to evaluate U
+  x[]     : the abscissas of the knots in strictly increasing order
+  y[]     : the ordinates of the knots
+  b, c, d : arrays of spline coefficients computed by spline().
+
+  Output :
+  --------
+  seval   : the value of the spline function at u
+  Last    : the segment in which u lies
+
+  Notes ...
+  -----
+  (1) If u is not in the same interval as the previous call then a
+      binary search is performed to determine the proper interval.
+
+*/
+/*-------------------------------------------------------------------*/
+{  /* begin function seval() */
+
+int    i, j, k;
+double w;
+
+i = *last;
+if (i >= n-1) i = 0;
+if (i < 0)  i = 0;
+
+if ((x[i] > u) || (x[i+1] < u))
+  {  /* ---- perform a binary search ---- */
+  i = 0;
+  j = n;
+  do
+    {
+    k = (i + j) / 2;         /* split the domain to search */
+    if (u < x[k])  j = k;    /* move the upper bound */
+    if (u >= x[k]) i = k;    /* move the lower bound */
+    }                        /* there are no more segments to search */
+  while (j > i+1);
+  }
+*last = i;
+
+/* ---- Evaluate the spline ---- */
+w = u - x[i];
+w = y[i] + w * (b[i] + w * (c[i] + w * d[i]));
+return (w);
+}
+/*-------------------------------------------------------------------*/
+
+/*-------------------------------------------------------------------*/
+/*-----------------------------------------------------------------*/
+/*-----------------------------------------------------------------*/
+double deriv (int n, double u,
+              double x[],
+              double b[], double c[], double d[],
+              int *last)
+/*-----------------------------------------------------------------*/
+/* Purpose ...
+   -------
+   Evaluate the derivative of the cubic spline function
+
+   S(x) = B[i] + 2.0 * C[i] * w + 3.0 * D[i] * w**2
+   where w = u - X[i]
+   and   X[i] <= u <= X[i+1]
+   Note that Horner's rule is used.
+   If U < X[0] then i = 0 is used.
+   If U > X[n-1] then i = n-1 is used.
+
+   Input :
+   -------
+   n       : The number of data points or knots (n >= 2)
+   u       : the abscissa at which the derivative is to be evaluated
+   last    : the segment that was last used
+   x       : the abscissas of the knots in strictly increasing order
+   b, c, d : arrays of spline coefficients computed by spline()
+
+   Output :
+   --------
+   deriv : the value of the derivative of the spline
+           function at u
+   last  : the segment in which u lies
+
+   Notes ...
+   -----
+   (1) If u is not in the same interval as the previous call then a
+       binary search is performed to determine the proper interval.
+
+*/
+/*-------------------------------------------------------------------*/
+{  /* begin function deriv() */
+
+int    i, j, k;
+double w;
+
+i = *last;
+if (i >= n-1) i = 0;
+if (i < 0) i = 0;
+
+if ((x[i] > u) || (x[i+1] < u))
+  {  /* ---- perform a binary search ---- */
+  i = 0;
+  j = n;
+  do
+    {
+    k = (i + j) / 2;          /* split the domain to search */
+    if (u < x[k])  j = k;     /* move the upper bound */
+    if (u >= x[k]) i = k;     /* move the lower bound */
+    }                         /* there are no more segments to search */
+  while (j > i+1);
+  }
+*last = i;
+
+/* ---- Evaluate the derivative ---- */
+w = u - x[i];
+w = b[i] + w * (2.0 * c[i] + w * 3.0 * d[i]);
+return (w);
+
+} /* end of deriv() */
+/*-------------------------------------------------------------------*/
+
+
+
+
+
+
+
+
+
+
+
+
+
+/*************************************************************/
+/*************************************************************/
+/*************************************************************/
+/*************************************************************/
+/*************************************************************/
+/* interpcsSB function ... MEX version for CVODE use in SBPD */
+/*************************************************************/
+
+void spline_pchip_set( int n, double x[], double f[], double d[] );
+void spline_pchip_val( int n, double x[], double f[], double d[],  int ne, double xe, double *feptr );
+int i4_max( int i1, int i2 );
+int chfev( double x1, double x2, double f1, double f2, double d1, double d2, int ne, double xe, double *feptr, int next[] );
+double r8_min( double x, double y );
+double r8_max( double x, double y );
+double pchst( double arg1, double arg2 );
+
+
+/****************************************************************************/
+
+double interpcsSB(int nargs, int n, double xe, ...)
+
+/****************************************************************************
+
+  Purpose:
+
+    interpcsSB is the calling function to evaluate a piecewise cubic spline 
+    function and calculte the Hermite interpolant.
+
+
+  Modified:
+
+    1 October 2007
+
+  Author:
+
+    Basti Bergdahl,
+    Department of Applied Microbiology,
+    Lund Insitute of Technology.
+
+  Calling syntax:
+
+    interpcsSB(NARGS, N, XE, X1,...,XN,F1,...,FN)
+
+  Parameters:
+
+    Input, int NARGS, the total number of input arguments (not counting NARGS itself).
+    The number should be even, otherwise an error will occure.
+
+    Input, int N, the number of data points (rows in the table).  N must be at least 2.
+
+    Input, double XE, point at which the function is to be evaluated.
+
+    Input, double X1,...,XN, the strictly increasing independent variable values.
+
+    Input, double F1,...,FN, dependent variable values to be interpolated.  This
+    routine is designed for monotonic data, but it will work for any F-array.
+    It will force extrema at points where monotonicity switches direction.
+
+    Output, double FE, the value of the cubic Hermite function at XE.
+*/
+{
+    va_list vararg;
+    int k, oddnumber;
+    int ne = 1;
+    double *data, *x, *f, *d, *feptr;
+    double fe;
+
+    /* Check if table data has been given */
+    if (nargs == 2)
+    {
+        mexErrMsgTxt("interpcsSB error: Input incorrect. No data for the table has been supplied.");
+        return 0;
+    }
+
+    /* Check if odd or even number of input arguments */
+    oddnumber = nargs % 2;
+    if (oddnumber != 0)
+    {
+        mexErrMsgTxt("interpcsSB error: Input incorrect. The number of inputs should be even.");
+        return 0;
+    }
+
+    /* If number of input arguments in odd, check if
+     * the X and Y vectors are of the same size */
+    if ((nargs-2)/2 != n)
+    {
+        mexErrMsgTxt("interpcsSB error: Input incorrect. The X and Y vectors are either of different lengths or");
+        mexErrMsgTxt("an incorrect number for the data points has been given.");
+        return 0;
+    }
+
+    /* Read in all variable input arguments in double array */    
+    va_start(vararg, xe);
+    data = (double *)mxCalloc((n*2),sizeof(double));
+    for (k=0; k<nargs-2; k++ )
+    {
+        data[k] = va_arg(vararg, double);
+    }
+
+    /* Create the X and Y arrays making up the table */
+    x = (double *)mxCalloc(n,sizeof(double));
+    f = (double *)mxCalloc(n,sizeof(double));
+    for (k=0; k<n; k++)
+    {
+        x[k] = data[k];
+        f[k] = data[k+n];
+    }
+    mxFree(data); /* free temporary array */
+
+    /* handle off limit values */
+    if (xe < x[0]) return(f[0]);
+    if (xe > x[n-1]) return(f[n-1]);
+    
+    /* Calculate the derivatives for the piecewise cubic Hermite interpolant */
+    d = (double *)mxCalloc(n,sizeof(double));
+    spline_pchip_set(n, x, f, d);
+
+    /* Evaluate the cubic Hermite function at x */    
+    feptr = &fe;
+    spline_pchip_val(n, x, f, d, ne, xe, feptr);
+
+    return(fe);
+}
+
+
+
+/****************************************************************************/
+
+void spline_pchip_set( int n, double x[], double f[], double d[] )
+
+/****************************************************************************
+
+  Purpose:
+
+    SPLINE_PCHIP_SET sets derivatives for a piecewise cubic Hermite interpolant.
+
+  Discussion:
+
+    This routine computes what would normally be called a Hermite
+    interpolant.  However, the user is only required to supply function
+    values, not derivative values as well.  This routine computes
+    "suitable" derivative values, so that the resulting Hermite interpolant
+    has desirable shape and monotonicity properties.
+
+    The interpolant will have an extremum at each point where
+    monotonicity switches direction.
+
+    The resulting piecewise cubic Hermite function may be evaluated
+    by SPLINE_PCHIP_VAL..
+
+    This routine was originally called "PCHIM".
+
+  Modified:
+
+    14 August 2005
+
+  Author:
+
+    Fred Fritsch,
+    Mathematics and Statistics Division,
+    Lawrence Livermore National Laboratory.
+
+    C++ translation by John Burkardt.
+
+  Reference:
+
+    Fred Fritsch, Ralph Carlson,
+    Monotone Piecewise Cubic Interpolation,
+    SIAM Journal on Numerical Analysis,
+    Volume 17, Number 2, April 1980, pages 238-246.
+
+    Fred Fritsch, Judy Butland,
+    A Method for Constructing Local Monotone Piecewise
+    Cubic Interpolants,
+    SIAM Journal on Scientific and Statistical Computing,
+    Volume 5, Number 2, 1984, pages 300-304.
+
+  Parameters:
+
+    Input, int N, the number of data points.  N must be at least 2.
+
+    Input, double X[N], the strictly increasing independent
+    variable values.
+
+    Input, double F[N], dependent variable values to be interpolated.  This
+    routine is designed for monotonic data, but it will work for any F-array.
+    It will force extrema at points where monotonicity switches direction.
+
+    Output, double D[N], the derivative values at the
+    data points.  If the data are monotonic, these values will determine
+    a monotone cubic Hermite function.
+*/
+{
+  double del1;
+  double del2;
+  double dmax;
+  double dmin;
+  double drat1;
+  double drat2;
+  double dsave;
+  double h1;
+  double h2;
+  double hsum;
+  double hsumt3;
+  int i;
+  int ierr;
+  int nless1;
+  double temp;
+  double w1;
+  double w2;
+
+  /*  Check the arguments. */
+
+  if ( n < 2 )
+  {
+    ierr = -1;
+    mexErrMsgTxt("\n");
+    mexErrMsgTxt("SPLINE_PCHIP_SET - Fatal error!\n");
+    mexErrMsgTxt("  Number of data points less than 2.\n");
+    exit ( ierr );
+  }
+
+  for ( i = 1; i < n; i++ )
+  {
+    if ( x[i] <= x[i-1] )
+    {
+      ierr = -3;
+      mexErrMsgTxt("\n");
+      mexErrMsgTxt("SPLINE_PCHIP_SET - Fatal error!\n");
+      mexErrMsgTxt("  X array not strictly increasing.\n");
+      exit ( ierr );
+    }
+  }
+
+  ierr = 0;
+  nless1 = n - 1;
+  h1 = x[1] - x[0];
+  del1 = ( f[1] - f[0] ) / h1;
+  dsave = del1;
+
+/*  Special case N=2, use linear interpolation. */
+
+  if ( n == 2 )
+  {
+    d[0] = del1;
+    d[n-1] = del1;
+    return;
+  }
+
+/*  Normal case, 3 <= N. */
+
+  h2 = x[2] - x[1];
+  del2 = ( f[2] - f[1] ) / h2;
+
+/*  Set D(1) via non-centered three point formula, adjusted to be
+    shape preserving. */
+
+  hsum = h1 + h2;
+  w1 = ( h1 + hsum ) / hsum;
+  w2 = -h1 / hsum;
+  d[0] = w1 * del1 + w2 * del2;
+
+  if ( pchst ( d[0], del1 ) <= 0.0 )
+  {
+    d[0] = 0.0;
+  }
+
+/*  Need do this check only if monotonicity switches. */
+
+  else if ( pchst ( del1, del2 ) < 0.0 )
+  {
+     dmax = 3.0 * del1;
+
+     if ( fabs ( dmax ) < fabs ( d[0] ) )
+     {
+       d[0] = dmax;
+     }
+
+  }
+
+/*  Loop through interior points. */
+
+  for ( i = 2; i <= nless1; i++ )
+  {
+    if ( 2 < i )
+    {
+      h1 = h2;
+      h2 = x[i] - x[i-1];
+      hsum = h1 + h2;
+      del1 = del2;
+      del2 = ( f[i] - f[i-1] ) / h2;
+    }
+
+/*  Set D(I)=0 unless data are strictly monotonic. */
+
+    d[i-1] = 0.0;
+
+    temp = pchst ( del1, del2 );
+
+    if ( temp < 0.0 )
+    {
+      ierr = ierr + 1;
+      dsave = del2;
+    }
+
+/*  Count number of changes in direction of monotonicity. */
+
+    else if ( temp == 0.0 )
+    {
+      if ( del2 != 0.0 )
+      {
+        if ( pchst ( dsave, del2 ) < 0.0 )
+        {
+          ierr = ierr + 1;
+        }
+        dsave = del2;
+      }
+    }
+
+/*  Use Brodlie modification of Butland formula. */
+
+    else
+    {
+      hsumt3 = 3.0 * hsum;
+      w1 = ( hsum + h1 ) / hsumt3;
+      w2 = ( hsum + h2 ) / hsumt3;
+      dmax = r8_max ( fabs ( del1 ), fabs ( del2 ) );
+      dmin = r8_min ( fabs ( del1 ), fabs ( del2 ) );
+      drat1 = del1 / dmax;
+      drat2 = del2 / dmax;
+      d[i-1] = dmin / ( w1 * drat1 + w2 * drat2 );
+    }
+  }
+
+/*  Set D(N) via non-centered three point formula, adjusted to be
+    shape preserving. */
+
+  w1 = -h2 / hsum;
+  w2 = ( h2 + hsum ) / hsum;
+  d[n-1] = w1 * del1 + w2 * del2;
+
+  if ( pchst ( d[n-1], del2 ) <= 0.0 )
+  {
+    d[n-1] = 0.0;
+  }
+  else if ( pchst ( del1, del2 ) < 0.0 )
+  {
+
+/*  Need do this check only if monotonicity switches. */
+
+    dmax = 3.0 * del2;
+
+    if ( fabs ( dmax ) < abs ( d[n-1] ) )
+    {
+      d[n-1] = dmax;
+    }
+
+  }
+  return;
+}
+
+/****************************************************************************/
+
+void spline_pchip_val( int n, double x[], double f[], double d[],
+  int ne, double xe, double *feptr )
+
+/****************************************************************************
+
+  Purpose:
+
+    SPLINE_PCHIP_VAL evaluates a piecewise cubic Hermite function.
+
+  Description:
+
+    This routine may be used by itself for Hermite interpolation, or as an
+    evaluator for SPLINE_PCHIP_SET.
+
+    This routine evaluates the cubic Hermite function at the points XE.
+
+    Most of the coding between the call to CHFEV and the end of
+    the IR loop could be eliminated if it were permissible to
+    assume that XE is ordered relative to X.
+
+    CHFEV does not assume that X1 is less than X2.  Thus, it would
+    be possible to write a version of SPLINE_PCHIP_VAL that assumes a strictly
+    decreasing X array by simply running the IR loop backwards
+    and reversing the order of appropriate tests.
+
+    The present code has a minor bug, which I have decided is not
+    worth the effort that would be required to fix it.
+    If XE contains points in [X(N-1),X(N)], followed by points less than
+    X(N-1), followed by points greater than X(N), the extrapolation points
+    will be counted (at least) twice in the total returned in IERR.
+
+    The evaluation will be most efficient if the elements of XE are
+    increasing relative to X; that is, for all J <= K,
+      X(I) <= XE(J)
+    implies
+      X(I) <= XE(K).
+
+    If any of the XE are outside the interval [X(1),X(N)],
+    values are extrapolated from the nearest extreme cubic,
+    and a warning error is returned.
+
+    This routine was originally named "PCHFE".
+
+  Modified:
+
+    14 August 2005
+
+  Author:
+
+    Fred Fritsch,
+    Mathematics and Statistics Division,
+    Lawrence Livermore National Laboratory.
+
+    C++ translation by John Burkardt.
+
+  Reference:
+
+    Fred Fritsch, Ralph Carlson,
+    Monotone Piecewise Cubic Interpolation,
+    SIAM Journal on Numerical Analysis,
+    Volume 17, Number 2, April 1980, pages 238-246.
+
+  Parameters:
+
+    Input, int N, the number of data points.  N must be at least 2.
+
+    Input, double X[N], the strictly increasing independent
+    variable values.
+
+    Input, double F[N], the function values.
+
+    Input, double D[N], the derivative values.
+
+    Input, int NE, the number of evaluation points.
+
+    Input, double XE, point at which the function is to
+    be evaluated.
+
+    Output, double FE, the value of the cubic Hermite
+    function at XE.
+*/
+{
+  int i;
+  int ierc;
+  int ierr;
+  int ir;
+  int j;
+  int j_first;
+  int j_new;
+  int j_save;
+  int next[2];
+  int nj;
+
+/*  Check arguments. */
+
+  if ( n < 2 )
+  {
+    ierr = -1;
+    mexErrMsgTxt("\n");
+    mexErrMsgTxt("SPLINE_PCHIP_VAL - Fatal error!\n");
+    mexErrMsgTxt("Number of data points less than 2.\n");
+    exit ( ierr );
+  }
+
+  for ( i = 1; i < n; i++ )
+  {
+    if ( x[i] <= x[i-1] )
+    {
+      ierr = -3;
+      mexErrMsgTxt("\n");
+      mexErrMsgTxt("SPLINE_PCHIP_VAL - Fatal error!\n");
+      mexErrMsgTxt("X array not strictly increasing.\n");
+      exit ( ierr );
+    }
+  }
+
+  if ( ne < 1 )
+  {
+    ierr = -4;
+    mexErrMsgTxt("\n");
+    mexErrMsgTxt("SPLINE_PCHIP_VAL - Fatal error!\n");
+    mexErrMsgTxt("Number of evaluation points less than 1.\n");
+    return;
+  }
+
+  ierr = 0;
+
+/*  Loop over intervals.
+  The interval index is IL = IR-1.
+  The interval is X(IL) <= X < X(IR).
+*/
+  j_first = 1;
+  ir = 2;
+
+  for ( ; ; )
+  {
+/*
+  Skip out of the loop if have processed all evaluation points.
+*/
+    if ( ne < j_first )
+    {
+      break;
+    }
+/*
+  Locate all points in the interval.
+*/
+    j_save = ne + 1;
+
+    for ( j = j_first; j <= ne; j++ )
+    {
+      if ( x[ir-1] <= xe )
+      {
+        j_save = j;
+        if ( ir == n )
+        {
+          j_save = ne + 1;
+        }
+        break;
+      }
+    }
+/*
+  Have located first point beyond interval.
+*/
+    j = j_save;
+
+    nj = j - j_first;
+/*
+  Skip evaluation if no points in interval.
+*/
+    if ( nj != 0 )
+    {
+/*
+  Evaluate cubic at XE(J_FIRST:J-1).
+*/
+      ierc = chfev ( x[ir-2], x[ir-1], f[ir-2], f[ir-1], d[ir-2], d[ir-1],
+        nj, xe, feptr, next );
+
+      if ( ierc < 0 )
+      {
+        ierr = -5;
+        mexErrMsgTxt("\n");
+        mexErrMsgTxt("SPLINE_PCHIP_VAL - Fatal error!\n");
+        mexErrMsgTxt("Error return from CHFEV.\n");
+        exit ( ierr );
+      }
+/*
+  In the current set of XE points, there are NEXT(2) to the right of X(IR).
+*/
+      if ( next[1] != 0 )
+      {
+        if ( ir < n )
+        {
+          ierr = -5;
+          mexErrMsgTxt("\n");
+          mexErrMsgTxt("SPLINE_PCHIP_VAL - Fatal error!\n");
+          mexErrMsgTxt("IR < N.\n");
+          exit ( ierr );
+        }
+/*
+  These are actually extrapolation points.
+*/
+        ierr = ierr + next[1];
+
+      }
+/*
+  In the current set of XE points, there are NEXT(1) to the left of X(IR-1).
+*/
+      if ( next[0] != 0 )
+      {
+/*
+  These are actually extrapolation points.
+*/
+        if ( ir <= 2 )
+        {
+          ierr = ierr + next[0];
+        }
+        else
+        {
+          j_new = -1;
+
+          for ( i = j_first; i <= j-1; i++ )
+          {
+            if ( xe < x[ir-2] )
+            {
+              j_new = i;
+              break;
+            }
+          }
+
+          if ( j_new == -1 )
+          {
+            ierr = -5;
+            mexErrMsgTxt("\n");
+            mexErrMsgTxt("SPLINE_PCHIP_VAL - Fatal error!\n");
+            mexErrMsgTxt("  Could not bracket the data point.\n");
+            exit ( ierr );
+          }
+/*
+  Reset J.  This will be the new J_FIRST.
+*/
+          j = j_new;
+/*
+  Now find out how far to back up in the X array.
+*/
+          for ( i = 1; i <= ir-1; i++ )
+          {
+            if ( xe < x[i-1] )
+            {
+              break;
+            }
+          }
+/*
+  At this point, either XE(J) < X(1) or X(i-1) <= XE(J) < X(I) .
+
+  Reset IR, recognizing that it will be incremented before cycling.
+*/
+          ir = i4_max ( 1, i-1 );
+        }
+      }
+
+      j_first = j;
+    }
+
+    ir = ir + 1;
+
+    if ( n < ir )
+    {
+      break;
+    }
+
+  }
+
+  return;
+}
+
+/****************************************************************************/
+
+int chfev( double x1, double x2, double f1, double f2, double d1, double d2,
+  int ne, double xe, double *feptr, int next[] )
+
+/****************************************************************************
+
+  Purpose:
+
+    CHFEV evaluates a cubic polynomial given in Hermite form.
+
+  Discussion:
+
+    This routine evaluates a cubic polynomial given in Hermite form at an
+    array of points.  While designed for use by SPLINE_PCHIP_VAL, it may
+    be useful directly as an evaluator for a piecewise cubic
+    Hermite function in applications, such as graphing, where
+    the interval is known in advance.
+
+    The cubic polynomial is determined by function values
+    F1, F2 and derivatives D1, D2 on the interval [X1,X2].
+
+  Modified:
+
+    12 August 2005
+
+  Author:
+
+    Fred Fritsch,
+    Mathematics and Statistics Division,
+    Lawrence Livermore National Laboratory.
+
+    C++ translation by John Burkardt.
+
+  Reference:
+
+    Fred Fritsch, Ralph Carlson,
+    Monotone Piecewise Cubic Interpolation,
+    SIAM Journal on Numerical Analysis,
+    Volume 17, Number 2, April 1980, pages 238-246.
+
+    David Kahaner, Cleve Moler, Steven Nash,
+    Numerical Methods and Software,
+    Prentice Hall, 1989,
+    ISBN: 0-13-627258-4,
+    LC: TA345.K34.
+
+  Parameters:
+
+    Input, double X1, X2, the endpoints of the interval of
+    definition of the cubic.  X1 and X2 must be distinct.
+
+    Input, double F1, F2, the values of the function at X1 and
+    X2, respectively.
+
+    Input, double D1, D2, the derivative values at X1 and
+    X2, respectively.
+
+    Input, int NE, the number of evaluation points.
+
+    Input, double XE, the point at which the function is to
+    be evaluated.  If the value of XE is outside the interval
+    [X1,X2], a warning error is returned in NEXT.
+
+    Output, double FE, the value of the cubic function
+    at the point XE.
+
+    Output, int NEXT[2], indicates the number of extrapolation points:
+    NEXT[0] = number of evaluation points to the left of interval.
+    NEXT[1] = number of evaluation points to the right of interval.
+
+    Output, int CHFEV, error flag.
+    0, no errors.
+    -1, NE < 1.
+    -2, X1 == X2.
+*/
+{
+  double c2;
+  double c3;
+  double del1;
+  double del2;
+  double delta;
+  double h;
+  int ierr;
+  double x;
+  double fe;
+  double xma;
+  double xmi;
+
+  if ( ne < 1 )
+  {
+    ierr = -1;
+    mexErrMsgTxt("\n");
+    mexErrMsgTxt("CHFEV - Fatal error!\n");
+    mexErrMsgTxt("  Number of evaluation points is less than 1.\n");
+    printf("  NE = %d\n", ne);
+    return ierr;
+  }
+
+  h = x2 - x1;
+
+  if ( h == 0.0 )
+  {
+    ierr = -2;
+    mexErrMsgTxt("\n");
+    mexErrMsgTxt("CHFEV - Fatal error!\n");
+    mexErrMsgTxt("  The interval [X1,X2] is of zero length.\n");
+    return ierr;
+  }
+/*
+  Initialize.
+*/
+  ierr = 0;
+  next[0] = 0;
+  next[1] = 0;
+  xmi = r8_min ( 0.0, h );
+  xma = r8_max ( 0.0, h );
+/*
+  Compute cubic coefficients expanded about X1.
+*/
+  delta = ( f2 - f1 ) / h;
+  del1 = ( d1 - delta ) / h;
+  del2 = ( d2 - delta ) / h;
+  c2 = -( del1 + del1 + del2 );
+  c3 = ( del1 + del2 ) / h;
+    x = xe - x1;
+    fe = f1 + x * ( d1 + x * ( c2 + x * c3 ) );
+    *feptr = fe;
+/*
+  Count the extrapolation points.
+*/
+    if ( x < xmi )
+    {
+      next[0] = next[0] + 1;
+    }
+
+    if ( xma < x )
+    {
+      next[1] = next[1] + 1;
+    }
+
+
+  return 0;
+}
+
+/****************************************************************************/
+
+double pchst( double arg1, double arg2 )
+
+/****************************************************************************
+
+  Purpose:
+
+    PCHST: PCHIP sign-testing routine.
+
+  Discussion:
+
+    This routine essentially computes the sign of ARG1 * ARG2.
+
+    The object is to do this without multiplying ARG1 * ARG2, to avoid
+    possible over/underflow problems.
+
+  Modified:
+
+    12 August 2005
+
+  Author:
+
+    Fred Fritsch,
+    Mathematics and Statistics Division,
+    Lawrence Livermore National Laboratory.
+
+    C++ translation by John Burkardt.
+
+  Reference:
+
+    Fred Fritsch, Ralph Carlson,
+    Monotone Piecewise Cubic Interpolation,
+    SIAM Journal on Numerical Analysis,
+    Volume 17, Number 2, April 1980, pages 238-246.
+
+  Parameters:
+
+    Input, double ARG1, ARG2, two values to check.
+
+    Output, double PCHST,
+    -1.0, if ARG1 and ARG2 are of opposite sign.
+     0.0, if either argument is zero.
+    +1.0, if ARG1 and ARG2 are of the same sign.
+*/
+{
+  double value;
+
+  if ( arg1 == 0.0 )
+  {
+    value = 0.0;
+  }
+  else if ( arg1 < 0.0 )
+  {
+    if ( arg2 < 0.0 )
+    {
+      value = 1.0;
+    }
+    else if ( arg2 == 0.0 )
+    {
+      value = 0.0;
+    }
+    else if ( 0.0 < arg2 )
+    {
+      value = -1.0;
+    }
+  }
+  else if ( 0.0 < arg1 )
+  {
+    if ( arg2 < 0.0 )
+    {
+      value = -1.0;
+    }
+    else if ( arg2 == 0.0 )
+    {
+      value = 0.0;
+    }
+    else if ( 0.0 < arg2 )
+    {
+      value = 1.0;
+    }
+  }
+
+  return(value);
+}
+
+/****************************************************************************/
+
+double r8_max( double x, double y )
+
+/****************************************************************************
+
+  Purpose:
+
+    R8_MAX returns the maximum of two R8's.
+
+  Modified:
+
+    10 January 2002
+
+  Author:
+
+    John Burkardt
+
+  Parameters:
+
+    Input, double X, Y, the quantities to compare.
+
+    Output, double R8_MAX, the maximum of X and Y.
+*/
+{
+  if ( y < x )
+  {
+    return(x);
+  }
+  else
+  {
+    return(y);
+  }
+}
+/****************************************************************************/
+
+double r8_min( double x, double y )
+
+/****************************************************************************
+
+  Purpose:
+
+    R8_MIN returns the minimum of two R8's.
+
+  Modified:
+
+    09 May 2003
+
+  Author:
+
+    John Burkardt
+
+  Parameters:
+
+    Input, double X, Y, the quantities to compare.
+
+    Output, double R8_MIN, the minimum of X and Y.
+*/
+{
+  if ( y < x )
+  {
+    return(y);
+  }
+  else
+  {
+    return(x);
+  }
+}
+
+
+/****************************************************************************/
+
+int i4_max ( int i1, int i2 )
+
+/****************************************************************************
+
+  Purpose:
+
+    I4_MAX returns the maximum of two I4's.
+
+  Modified:
+
+    13 October 1998
+
+  Author:
+
+    John Burkardt
+
+  Parameters:
+
+    Input, int I1, I2, are two integers to be compared.
+
+    Output, int I4_MAX, the larger of I1 and I2.
+
+*/
+{
+  if ( i2 < i1 )
+  {
+    return(i1);
+  }
+  else
+  {
+    return(i2);
+  }
+
+}
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/lib/CVODEmex25.lib b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/lib/CVODEmex25.lib
new file mode 100644
index 0000000000000000000000000000000000000000..73a0d7c8c9873732a59eb29984a6006c67763b49
Binary files /dev/null and b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/lib/CVODEmex25.lib differ
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/CVODEmex25.c b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/CVODEmex25.c
new file mode 100644
index 0000000000000000000000000000000000000000..9933d89a6d45e4344eba21cf620fb8fc75f02971
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/CVODEmex25.c
@@ -0,0 +1,809 @@
+/*
+ * CVODEmex25.c: MEX/CVODES Interface for Sundials CVODES version 2.5
+ *
+ * Information:
+ * ============
+ * SBPD Package - Systems Biology Parameter Determination Package
+ * Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+ */
+
+#include <mex.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <stdarg.h>
+#include <string.h>
+#include <matrix.h>
+#include <math.h>
+
+/* CVODES includes */
+#include <cvodes/cvodes.h>
+#include <nvector/nvector_serial.h>
+#include <sundials/sundials_types.h>
+#include <sundials/sundials_math.h>
+#include "CVODEmex25.h"
+
+/* Definitions for CVODES */
+#define ABSTOL  1.0e-6  
+#define RELTOL  1.0e-6  
+#define MAXNUMSTEPS     100000  /* default in CVODE is 500 but higher is better for general purpose */
+#define MAXERRTESTFAILS 50      /* default is 7 */
+#define Ith(v,i) NV_Ith_S(v,i-1)
+
+/* Initialize functions */
+static void doInitilizationVariables();
+static mxArray* handleInputArguments(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]);
+static mxArray* doXdotCalc();
+static void allocSimMemory();
+static void initCVODE();
+static void integrate();
+static void reportSTATS();
+static mxArray* constructOutput();
+static void addVec2Mat(double *matrix, double *rowvector, int row, int nrows, int ncols);
+static int f(double time, N_Vector u, N_Vector udot, void *f_data);
+static int g(double time, N_Vector y, double *gout, void *g_data);
+static void errorMsg(char *text);
+static void freeMem();
+
+/* Some global variables for the interface */
+int k,k2;   /* some loop variables */
+
+int length2check;
+
+char stringbuffer[256];
+
+mxArray *timesimvectorMX = NULL;
+double *timesimvector = NULL;
+
+mxArray *parametervectorMX = NULL;
+double *parametervector = NULL;
+double *parametervectorCVODES = NULL; 
+
+mxArray *initialconditionsMX = NULL;
+double *initialconditions = NULL;
+
+mxArray *optionsMX = NULL;
+
+mxArray *showIntegratorStatsMX = NULL; 
+int showIntegratorStats = 0;            /* Flag defining if integrator stats shown or not */
+
+
+mxArray *minstepMX = NULL;
+double minstep;
+mxArray *maxstepMX = NULL;
+double maxstep;
+mxArray *maxnumstepsMX = NULL;
+long int maxnumsteps;
+mxArray *reltolMX = NULL;
+double reltol;
+mxArray *abstolMX = NULL;
+double abstol;
+mxArray *maxerrtestfailsMX = NULL;
+int maxerrtestfails;
+mxArray *maxorderMX = NULL;
+int maxorder;
+mxArray *maxconvfailsMX = NULL;
+int maxconvfails;
+mxArray *initstepMX = NULL;
+double initstep;
+mxArray *maxnonlineariterMX = NULL;
+int maxnonlineariter;
+
+
+
+
+mxArray *xdotcalcMX = NULL;
+double xdotcalc;
+
+int numbertimesteps;
+
+mxArray *resultMX = NULL;
+double *result = NULL;
+
+mxArray *statesMX = NULL;
+
+mxArray *statevaluesMX = NULL;
+double *statevalues = NULL;
+
+mxArray *variablesMX = NULL;
+
+mxArray *variablevaluesMX = NULL;
+double *variablevalues = NULL;
+
+mxArray *reactionsMX = NULL;
+
+mxArray *reactionvaluesMX = NULL;
+double *reactionvalues = NULL;
+
+mxArray *eventsMX = NULL;
+
+mxArray *eventtimesMX = NULL;
+double *eventtimes = NULL;
+
+mxArray *eventflagsMX = NULL;
+double *eventflags = NULL;
+
+/* CVODES needed data */
+ParamData modeldata;
+N_Vector u = NULL;
+void *cvode_mem;
+int flag, flagroot;
+double treturn;
+double tendstep;
+
+/* Interface to model RHS */
+double *statevec = NULL;
+double *variablevec = NULL;
+double *reactionvec = NULL;
+int *eventvec = NULL;
+double *eventdataold = NULL;
+int nreventshappend;
+double *eventflagsdata = NULL;
+double eventcorrecttest;
+
+/* Error Flags */
+int timevectorEmpty = 0;
+int timevectorNotVector = 0;
+int timevectorIsScalar = 0;
+
+/* Method (stiff, nonstiff) Variables */
+mxArray *methodMX = NULL;
+int method;
+
+/* Integrator Statistics */
+long int STATS_nsteps;
+long int STATS_nfevals;
+long int STATS_netfails;
+double STATS_hinused;
+double STATS_tolsfac;
+  
+/*
+ *========================================================================
+ * MEX INTERFACE FOR MEX SIMULATION MODELS
+ *========================================================================
+ */
+void CVODEmex25(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
+{
+    /* Initialize variables that are needed externally */
+    interpcseSB_check = NULL; /* needed for spline function in mexsplineaddon.h */
+    interpcseSlopeSB_check = NULL; /* needed for spline function in mexsplineaddon.h */
+
+    /* Initialize all other variables that are initialized during their definition
+     * Needs to be redone since not re-defined/initialized if MEX file recalled */
+    doInitilizationVariables();
+    
+    /* Handle variable input arguments */
+    resultMX = handleInputArguments(nlhs, plhs, nrhs, prhs);
+    if (resultMX != NULL) {
+        /* No integration requested */
+        plhs[0] = resultMX;
+        return;
+    }
+    
+    /* Check if timevector defined */
+    if (timevectorEmpty == 1) mexErrMsgTxt("Timevector is empty.");
+        
+    /* check if integration or xdot calculation */
+    if (xdotcalc != 0) {
+        /* return the RHS of the ODEs at given state and parameter values */
+        resultMX = doXdotCalc();
+        plhs[0] = resultMX;
+        return;
+    }
+    
+    /* Do error checks ... timevector needs to be defined if integration is to be done! */
+    if (timevectorNotVector == 1 || timevectorIsScalar == 1) mexErrMsgTxt("'timevector' input argument needs to be a vector if you want to do a simulation.");
+    /* Otherwise do the integration */
+    /* Allocate memory for the simulation */
+    allocSimMemory();
+    /* Initialize CVODES */
+    initCVODE();
+    /* Integrate */
+    integrate();
+    /* Report Statistics of Integration */
+    reportSTATS();
+    /* Construct result */
+    plhs[0] = constructOutput();
+    /* Free allocated memory */
+    freeMem();
+}
+
+/*
+ *========================================================================
+ * Integration statistics report function
+ *========================================================================
+ */
+static void reportSTATS()
+{
+    /* Get the statistics */
+    CVodeGetNumSteps(cvode_mem,&STATS_nsteps);
+    CVodeGetNumRhsEvals(cvode_mem,&STATS_nfevals);
+    CVodeGetNumErrTestFails(cvode_mem,&STATS_netfails);
+    CVodeGetActualInitStep(cvode_mem,&STATS_hinused);
+    CVodeGetTolScaleFactor(cvode_mem,&STATS_tolsfac);
+    /* Report statistics */
+    if (showIntegratorStats != 0) {
+        mexPrintf("\nIntegrator Statistics\n");
+        mexPrintf("=====================\n");
+        mexPrintf("Cumulative number of internal steps:    %ld\n",STATS_nsteps);
+        mexPrintf("No. of calls to r.h.s. function:        %ld\n",STATS_nfevals);
+        mexPrintf("No. of local error test failures:       %ld\n",STATS_netfails);
+        mexPrintf("Actual init step size used:             %g\n",STATS_hinused);
+        mexPrintf("Suggested factor for tolerance scaling: %g\n\n",STATS_tolsfac);
+    }
+}
+
+/*
+ *========================================================================
+ * Help function to add a row vector to a matrix
+ *========================================================================
+ */
+static void addVec2Mat(double *matrix, double *rowvector, int row, int nrrows, int nrcols)
+{
+    int k;
+    for (k=0;k<nrcols;k++) {
+        matrix[row+k*nrrows] = rowvector[k];
+    }
+}
+
+/*
+ *========================================================================
+ * RHS function f(t,u) 
+ *========================================================================
+ */
+static int f(double time, N_Vector u, N_Vector udot, void *f_data)
+{
+    double *statevec, *DDTvector;
+    ParamData *paramdataPtr;
+    /* get pointer to modeldata */
+    paramdataPtr = (ParamData*) f_data;
+    /* connect input and result data */
+    statevec = NV_DATA_S(u);
+    DDTvector = NV_DATA_S(udot);
+    /* run the model */
+    model(time, statevec, DDTvector, paramdataPtr, DOFLAG_DDT, NULL, NULL, NULL, NULL);
+    return(0);
+}
+
+/*
+ *========================================================================
+ * Event function 
+ *========================================================================
+ */
+static int g(double time, N_Vector y, double *gout, void *g_data)
+{
+    double *statevec;
+    ParamData *paramdataPtr;
+    /* get pointer to model data */
+    paramdataPtr = (ParamData*) g_data;
+    /* connect input data */
+    statevec = NV_DATA_S(y);
+    /* run the event function */
+    model(time, statevec, NULL, paramdataPtr, DOFLAG_EVENTS, NULL, NULL, gout, NULL);
+    return(0);
+}
+
+/*
+ *========================================================================
+ * Error function 
+ *========================================================================
+ */
+static void errorMsg(char *text)
+{
+    /* First free the allocated memory */
+    freeMem();
+    /* Then print error message and exit */
+    mexErrMsgTxt(text);
+}
+
+/*
+ *========================================================================
+ * Free the memory 
+ *========================================================================
+ */
+static void freeMem()
+{
+    /* Free all CVODE related memory */
+    N_VDestroy_Serial(u);  /* Free the u vector */
+    CVodeFree(&cvode_mem);  /* Free the integrator memory */
+}
+
+    /*
+     * ==============================================
+     * HANDLE THE VARIABLE INPUT ARGUMENTS
+     * ==============================================
+     */
+static mxArray* handleInputArguments(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
+{
+    mxArray *rhs[1], *lhs[1]; /* for calling matlab function "convertNNCa2NANNCaSBPD" */
+
+    /* need to set to NULL some things for checking */
+    parametervectorMX = NULL;
+    initialconditionsMX = NULL;
+    optionsMX = NULL;
+    
+    if (nrhs == 0) {
+        /***************************************************/
+        /* no input arguments => return initial conditions */
+        /***************************************************/
+        
+        /* check if only numeric initial conditions */
+        if (hasOnlyNumericICs) {
+            /* numeric */
+            resultMX = mxCreateDoubleMatrix(NRSTATES, 1, mxREAL);
+            result = mxGetPr(resultMX);
+            for (k=0; k<NRSTATES; k++) result[k] = defaultICs_num[k];
+            return resultMX;
+        } else {
+            /* non-numeric */
+            resultMX = mxCreateCellMatrix(NRSTATES, 1);
+            result = mxGetPr(resultMX);
+            for (k=0; k<NRSTATES; k++) mxSetCell(resultMX,k,mxCreateString(defaultICs_nonnum[k]));
+            /* call matlab function with resultMX as input to convert numeric strings to numbers ... */
+            rhs[0] = resultMX;
+            mexCallMATLAB(1, lhs, 1, rhs, "convertNNCa2NANNCaSBPD");
+            return lhs[0];
+        }
+    } else if (nrhs == 1) {
+        /***************************************************/
+        /* handle single input argument                    */
+        /***************************************************/
+        
+        if (mxIsEmpty(prhs[0])) {
+            mexErrMsgTxt("Timevector is empty.");
+        } 
+        if (mxIsChar(prhs[0])) {
+            length2check = (mxGetM(prhs[0]) * mxGetN(prhs[0]));
+            if (length2check == 6) {       
+                resultMX = mxCreateCellMatrix(NRSTATES, 1);
+                for (k=0; k<NRSTATES; k++) mxSetCell(resultMX,k,mxCreateString(stateNames[k]));
+                return resultMX;
+            }
+            else if (length2check == 10) { 
+                resultMX = mxCreateCellMatrix(NRPARAMETERS, 1);
+                for (k=0; k<NRPARAMETERS; k++) mxSetCell(resultMX,k,mxCreateString(parameterNames[k]));
+                return resultMX;
+            }
+            else if (length2check == 15) { 
+                resultMX = mxCreateDoubleMatrix(NRPARAMETERS, 1, mxREAL);
+                result = mxGetPr(resultMX);
+                for (k=0; k<NRPARAMETERS; k++) result[k] = defaultParam[k];
+                return resultMX;
+            } else mexErrMsgTxt("Incorrect input argument.");
+        } else {
+            if (!mxIsDouble(prhs[0])) mexErrMsgTxt("Check the 'timevector' (first) input argument.");
+            /* if no error then the first argument is the timevector for simulation */
+            timesimvectorMX = (mxArray *) prhs[0];
+        }
+    } else {
+        /***************************************************/
+        /* handle other numbers of input arguments         */
+        /***************************************************/
+        
+        if (!mxIsDouble(prhs[0])) mexErrMsgTxt("Check 'timevector' (first) input argument.");
+        timesimvectorMX = (mxArray *) prhs[0];
+        if (nrhs >= 2) {
+            if (!mxIsDouble(prhs[1]) && !mxIsEmpty(prhs[1])) mexErrMsgTxt("Check 'initialconditions' (second) input argument.");
+            initialconditionsMX = (mxArray *) prhs[1];
+        }
+        if (nrhs >= 3) {
+            if (!mxIsDouble(prhs[2]) && !mxIsEmpty(prhs[2])) mexErrMsgTxt("Check 'parametervector' (third) input argument.");
+            parametervectorMX = (mxArray *) prhs[2];
+        } 
+        if (nrhs >= 4) {
+            if (!mxIsStruct(prhs[3]) && !mxIsEmpty(prhs[3])) mexErrMsgTxt("Check 'options' (fourth) input argument.");
+            optionsMX = (mxArray *) prhs[3];
+        }
+        if (nrhs >= 5) {
+            mexErrMsgTxt("Incorrect number of input arguments.");
+        }
+    }
+    /***************************************************/
+    /* process input arguments                         */
+    /***************************************************/
+
+    /* process timevector only if not empty */
+    if (!mxIsEmpty(timesimvectorMX)) {
+        timesimvector = mxGetPr(timesimvectorMX);
+        /* Get some flags to check usability of time vector */
+        numbertimesteps = mxGetM(timesimvectorMX)*mxGetN(timesimvectorMX);
+        if (numbertimesteps == 1) timevectorIsScalar = 1; /* needed if xdotcalc */
+        if (mxGetN(timesimvectorMX) > 1 && mxGetM(timesimvectorMX) > 1) timevectorNotVector = 1; /* vector needed for simulation */
+    } else {
+        /* set error flag for simulation case */
+        timevectorEmpty = 1;
+    }
+    /* check parametervector */
+    /* needs to be done before initial conditions in order to be able to handle non-numeric ICs */
+    /* we need to get new memory for the parametervector in order to create an independent copy of
+     * the default parameter vector. Otherwise events on parameters do change the default parameter vector 
+     * which definitely is not desired!!! */
+    parametervector = (double *) mxCalloc(NRPARAMETERS, sizeof(double));
+    /* Copy default parameters into the parametervector */
+    for (k=0; k<NRPARAMETERS; k++) parametervector[k] = defaultParam[k];
+    
+    if (parametervectorMX != NULL) {
+        if (!mxIsEmpty(parametervectorMX)) {
+            if (mxGetN(parametervectorMX)*mxGetM(parametervectorMX) != NRPARAMETERS || (mxGetN(parametervectorMX) > 1 && mxGetM(parametervectorMX) > 1)) mexErrMsgTxt("'parametervector' needs to be a vector of 'number parameters' length.");
+            parametervector = mxGetPr(parametervectorMX);
+        }
+    }
+    /* assign parametervector to modeldata struct */
+    modeldata.parametervector = parametervector;
+    /* process initial conditions */
+    initialconditions = (double *) mxCalloc(NRSTATES,sizeof(double));
+    /* For the initial conditions we need to take care of eventual non-numeric initial conditions */
+    /* These can depend on parameters (both nominal and user-provided ones */
+    /* If the user provides initial conditions, these overwrite all other ones and the non-numeric equations */
+    /* will not be used anymore. */
+    if (hasOnlyNumericICs == 1) {
+        for (k=0;k<NRSTATES;k++) initialconditions[k] = defaultICs_num[k];
+    } else {
+        calc_ic_model(initialconditions, &modeldata);
+    }
+    if (initialconditionsMX != NULL) {
+        if (!mxIsEmpty(initialconditionsMX)) {
+            if (mxGetN(initialconditionsMX)*mxGetM(initialconditionsMX) != NRSTATES || (mxGetN(initialconditionsMX) > 1 && mxGetM(initialconditionsMX) > 1)) mexErrMsgTxt("'initialconditions' needs to be a vector of 'number states' length.");
+            initialconditions = mxGetPr(mxDuplicateArray(initialconditionsMX));
+        }
+    }    
+    /* check options */
+    showIntegratorStats = 0;
+    minstep = 0.0;  /* default value in CVODE */
+    maxstep = 0.0;  /* default value in CVODE => infinity */
+    maxnumsteps = MAXNUMSTEPS;          /* we set a value different from CVODE default values as default */
+    maxerrtestfails = MAXERRTESTFAILS;  /* we set a value different from CVODE default values as default */
+    maxorder = 5; /* default value for default method (stiff) */
+    maxconvfails = 10;      /* default value in CVODE */
+    initstep = 0.0;         /* default value in CVODE */
+    maxnonlineariter = 3;   /* default value in CVODE */
+    method = 0;        /* 0 = stiff, 1 = nonstiff, default: 0 */
+    reltol = RELTOL;   /* we set a value different from CVODE default values as default */
+    abstol = ABSTOL;   /* we set a value different from CVODE default values as default */
+    xdotcalc = 0;
+    if (optionsMX != NULL) {
+        if (!mxIsEmpty(optionsMX)) {
+            showIntegratorStatsMX = mxGetField(optionsMX, 0, "showIntegratorStats");
+            if (showIntegratorStatsMX != NULL) 
+                if (mxIsDouble(showIntegratorStatsMX)) 
+                    showIntegratorStats = (int)mxGetScalar(showIntegratorStatsMX); 
+                else 
+                    mexErrMsgTxt("'options.showIntegratorStats' wrongly defined.");
+
+            minstepMX = mxGetField(optionsMX, 0, "minstep");
+            if (minstepMX != NULL) 
+                if (mxIsDouble(minstepMX)) 
+                    minstep = mxGetScalar(minstepMX); 
+                else 
+                    mexErrMsgTxt("'options.minstep' wrongly defined.");
+            maxstepMX = mxGetField(optionsMX, 0, "maxstep");
+            if (maxstepMX != NULL) 
+                if (mxIsDouble(maxstepMX)) 
+                    maxstep = mxGetScalar(maxstepMX); 
+                else 
+                    mexErrMsgTxt("'options.maxstep' wrongly defined.");
+            maxnumstepsMX = mxGetField(optionsMX, 0, "maxnumsteps");
+            if (maxnumstepsMX != NULL) 
+                if (mxIsDouble(maxnumstepsMX)) 
+                    maxnumsteps = (long int)mxGetScalar(maxnumstepsMX); 
+                else 
+                    mexErrMsgTxt("'options.maxnumsteps' wrongly defined.");
+            methodMX = mxGetField(optionsMX, 0, "method");
+            if (methodMX != NULL) {
+                if (mxIsChar(methodMX)) {
+                    if (mxGetM(methodMX) * mxGetN(methodMX) == 8) {
+                        method = 1; /* "nonstiff" method ... just check the length of the string */
+                    } else if (mxGetM(methodMX) * mxGetN(methodMX) == 5) {
+                        method = 0; /* "stiff method */
+                    } else {
+                        mexErrMsgTxt("'options.method' wrongly defined.");
+                    }
+                } else {
+                    mexErrMsgTxt("'options.method' wrongly defined.");
+                }
+            }
+
+            /* Set maxorder, depending on the method chosen to the default values */
+			if (method==0) maxorder = 5;  /* stiff BDF */
+			else maxorder = 12;           /* nonstiff Adams */
+			
+			reltolMX = mxGetField(optionsMX, 0, "reltol");
+            if (reltolMX != NULL) 
+                if (mxIsDouble(reltolMX)) 
+                    reltol = mxGetScalar(reltolMX); 
+                else 
+                    mexErrMsgTxt("'options.reltol' wrongly defined.");
+            abstolMX = mxGetField(optionsMX, 0, "abstol");
+            if (abstolMX != NULL) 
+                if (mxIsDouble(abstolMX)) 
+                    abstol = mxGetScalar(abstolMX); 
+                else 
+                    mexErrMsgTxt("'options.abstol' wrongly defined.");
+            xdotcalcMX = mxGetField(optionsMX, 0, "xdotcalc");
+            if (xdotcalcMX != NULL) 
+                if (mxIsDouble(xdotcalcMX)) 
+                    xdotcalc = mxGetScalar(xdotcalcMX); 
+                else 
+                    mexErrMsgTxt("'options.xdotcalc' wrongly defined.");
+
+            
+            /* Additional Options */
+            maxerrtestfailsMX = mxGetField(optionsMX, 0, "maxerrtestfails");
+            if (maxerrtestfailsMX != NULL) 
+                if (mxIsDouble(maxerrtestfailsMX)) 
+                    maxerrtestfails = (int)mxGetScalar(maxerrtestfailsMX); 
+                else 
+                    mexErrMsgTxt("'options.maxerrtestfails' wrongly defined.");            
+
+            maxorderMX = mxGetField(optionsMX, 0, "maxorder");
+            if (maxorderMX != NULL) 
+                if (mxIsDouble(maxorderMX)) 
+                    maxorder = (int)mxGetScalar(maxorderMX); 
+                else 
+                    mexErrMsgTxt("'options.maxorder' wrongly defined.");            
+
+            maxconvfailsMX = mxGetField(optionsMX, 0, "maxconvfails");
+            if (maxconvfailsMX != NULL) 
+                if (mxIsDouble(maxconvfailsMX)) 
+                    maxconvfails = (int)mxGetScalar(maxconvfailsMX); 
+                else 
+                    mexErrMsgTxt("'options.maxconvfails' wrongly defined.");    
+            
+            initstepMX = mxGetField(optionsMX, 0, "initstep");
+            if (initstepMX != NULL) 
+                if (mxIsDouble(initstepMX)) 
+                    initstep = (double)mxGetScalar(initstepMX); 
+                else 
+                    mexErrMsgTxt("'options.initstep' wrongly defined.");                
+
+            maxnonlineariterMX = mxGetField(optionsMX, 0, "maxnonlineariter");
+            if (maxnonlineariterMX != NULL) 
+                if (mxIsDouble(maxnonlineariterMX)) 
+                    maxnonlineariter = (double)mxGetScalar(maxnonlineariterMX); 
+                else 
+                    mexErrMsgTxt("'options.maxnonlineariter' wrongly defined.");                
+        }
+    }
+    return NULL;
+}
+
+    /*
+     * ==============================================
+     * GET RHS OF ODEs (fir time = 0)
+     * ==============================================
+     */
+static mxArray* doXdotCalc()
+{
+    /* Check if timevector is a scalar */
+    if (timevectorIsScalar != 1) mexErrMsgTxt("'timevector' input argument needs to be a scalar if you want to calculate the RHS.");
+    resultMX = mxCreateDoubleMatrix(NRSTATES, 1, mxREAL);
+    result = mxGetPr(resultMX);
+    model(timesimvector[0], initialconditions, result, &modeldata, DOFLAG_DDT, NULL, NULL, NULL, NULL);
+    return resultMX;
+}
+
+    /*
+     * ==============================================
+     * ALLOCATE MEMORY 
+     * ==============================================
+     */
+static void allocSimMemory()
+{
+    statevaluesMX = mxCreateDoubleMatrix(numbertimesteps, NRSTATES, mxREAL);
+    statevalues = mxGetPr(statevaluesMX);
+    if (NRVARIABLES > 0) {
+        variablevec = (double *) mxCalloc(NRVARIABLES, sizeof(double));
+        variablevaluesMX = mxCreateDoubleMatrix(numbertimesteps, NRVARIABLES, mxREAL);
+        variablevalues = mxGetPr(variablevaluesMX);
+    }
+    if (NRREACTIONS > 0) {
+        reactionvec = (double *) mxCalloc(NRREACTIONS, sizeof(double));
+        reactionvaluesMX = mxCreateDoubleMatrix(numbertimesteps, NRREACTIONS, mxREAL);
+        reactionvalues = mxGetPr(reactionvaluesMX);
+    }
+    if (NREVENTS > 0) {
+        eventvec = (int *) mxCalloc(NREVENTS, sizeof(int));
+        eventdataold = (double *) mxCalloc(NREVENTS, sizeof(double));
+    }
+}
+    
+    /*
+     * ==============================================
+     * INITIALIZE INTEGRATOR
+     * ==============================================
+     */
+static void initCVODE()
+{
+    u = N_VMake_Serial(NRSTATES,initialconditions);
+    /* Set integration method (stiff or non-stiff) */
+    if (method == 0) cvode_mem = CVodeCreate(CV_BDF, CV_NEWTON);    /* default (stiff) */
+    else cvode_mem = CVodeCreate(CV_ADAMS, CV_FUNCTIONAL);          /* nonstiff */
+    CVodeMalloc(cvode_mem, f, timesimvector[0], u, CV_SS, reltol, &abstol);
+    if (NREVENTS > 0) {
+        CVodeRootInit(cvode_mem, NREVENTS, g, &modeldata);
+    }
+    CVodeSetFdata(cvode_mem, &modeldata);
+    if (minstep > 0) CVodeSetMinStep(cvode_mem, minstep);
+    if (maxstep > 0) CVodeSetMaxStep(cvode_mem, maxstep);
+    if (maxnumsteps > 0) CVodeSetMaxNumSteps(cvode_mem, maxnumsteps);
+    CVodeSetMaxErrTestFails(cvode_mem, maxerrtestfails);
+    CVodeSetMaxOrd(cvode_mem, maxorder);
+    CVodeSetMaxConvFails(cvode_mem, maxconvfails);
+    CVodeSetInitStep(cvode_mem, initstep);
+    CVodeSetMaxNonlinIters(cvode_mem, maxnonlineariter);
+    CVDense(cvode_mem,NRSTATES);
+}
+
+    /*
+     * ==============================================
+     * DO THE INTEGRATION
+     * ==============================================
+     */
+static void integrate()
+{
+    addVec2Mat(statevalues,initialconditions,0,numbertimesteps,NRSTATES);
+    model(timesimvector[0], initialconditions, NULL, &modeldata, DOFLAG_VARREAC, variablevec, reactionvec,NULL,NULL);
+    if (NRVARIABLES > 0) addVec2Mat(variablevalues,variablevec,0,numbertimesteps,NRVARIABLES);
+    if (NRREACTIONS > 0) addVec2Mat(reactionvalues,reactionvec,0,numbertimesteps,NRREACTIONS);
+    if (NREVENTS > 0) /* determine eventdataold to be able to detect directions of events */
+        model(timesimvector[0], initialconditions, NULL, &modeldata, DOFLAG_EVENTS, NULL, NULL, eventdataold, NULL);
+    k = 1;
+    tendstep = timesimvector[k]; 
+    nreventshappend = 0; 
+    while(1) {
+        flag = CVode(cvode_mem, tendstep, u, &treturn, CV_NORMAL);
+        if (flag < 0) {
+            if (flag == CV_TOO_MUCH_WORK) errorMsg("CVODE Error: CV_TOO_MUCH_WORK");
+            else if (flag == CV_TOO_MUCH_ACC) errorMsg("CVODE Error: CV_TOO_MUCH_ACC");
+            else if (flag == CV_ERR_FAILURE || flag == CV_CONV_FAILURE) errorMsg("CVODE Error: CV_ERR_FAILURE");
+            else {
+                sprintf(stringbuffer, "CVODE Error Flag: %d",flag);
+                errorMsg(stringbuffer);
+            }
+        }
+        statevec = NV_DATA_S(u);
+        if (flag == CV_ROOT_RETURN) {
+            /* Event happened */
+            CVodeGetRootInfo(cvode_mem, eventvec);
+            eventcorrecttest = 0;
+            model(treturn, statevec, &eventcorrecttest, &modeldata, DOFLAG_EVENTASSIGN, NULL, NULL, eventdataold, eventvec);
+            flag = CVodeReInit(cvode_mem, f, treturn, u, CV_SS, reltol, &abstol);
+            if (eventcorrecttest > 0) {
+                nreventshappend += 1;  
+                if (nreventshappend == 1) {
+                    eventtimes = (double *) mxCalloc(1, sizeof(double));
+                    eventflagsdata = (double *) mxCalloc(NREVENTS, sizeof(double));
+                } else {
+                    eventtimes = (double *) mxRealloc((void *) eventtimes, nreventshappend*sizeof(double));
+                    eventflagsdata = (double *) mxRealloc((void *) eventflagsdata, NREVENTS*nreventshappend*sizeof(double));
+                }
+                eventtimes[nreventshappend-1] = treturn;
+                for (k2=0;k2<NREVENTS;k2++) eventflagsdata[NREVENTS*(nreventshappend-1)+k2] = (double)eventvec[k2];
+            }
+        }
+        if (tendstep == treturn) { 
+            addVec2Mat(statevalues,statevec,k,numbertimesteps,NRSTATES);
+            model(tendstep, statevec, NULL, &modeldata, DOFLAG_VARREAC, variablevec, reactionvec, NULL, NULL);
+            if (NRVARIABLES > 0) addVec2Mat(variablevalues,variablevec,k,numbertimesteps,NRVARIABLES);
+            if (NRREACTIONS > 0) addVec2Mat(reactionvalues,reactionvec,k,numbertimesteps,NRREACTIONS);
+            k = k+1;
+            if (k < numbertimesteps) 
+                tendstep = timesimvector[k];
+            else 
+                break; 
+        }
+        if (NREVENTS > 0) /* determine eventdataold to be able to detect directions of events */
+            model(treturn, statevec, NULL, &modeldata, DOFLAG_EVENTS, NULL, NULL, eventdataold, NULL);
+    }
+}
+
+    /*
+     * ==============================================
+     * CONSTRUCT OUTPUT VARIABLE
+     * ==============================================
+     */
+static mxArray* constructOutput()
+{
+    resultMX = mxCreateStructMatrix(1,1,0,NULL);
+    /* Create fields in result structure */
+    mxAddField(resultMX,"time");
+    mxAddField(resultMX,"states");
+    mxAddField(resultMX,"statevalues");
+    mxAddField(resultMX,"variables");
+    mxAddField(resultMX,"variablevalues");
+    mxAddField(resultMX,"reactions");
+    mxAddField(resultMX,"reactionvalues");
+    if (NREVENTS > 0) {
+        mxAddField(resultMX,"events");
+        mxAddField(resultMX,"eventtimes");
+        mxAddField(resultMX,"eventflags");
+    }
+    mxSetField(resultMX, 0, "time", mxDuplicateArray(timesimvectorMX));
+    mxSetField(resultMX, 0, "statevalues", statevaluesMX);
+    if (NRVARIABLES > 0) mxSetField(resultMX, 0, "variablevalues", variablevaluesMX);
+    if (NRREACTIONS > 0) mxSetField(resultMX, 0, "reactionvalues", reactionvaluesMX);
+    statesMX = mxCreateCellMatrix(1, NRSTATES);
+    for (k=0;k<NRSTATES;k++) mxSetCell(statesMX,k,mxCreateString(stateNames[k]));
+    mxSetField(resultMX, 0, "states", statesMX);
+    if (NRVARIABLES > 0) {
+        variablesMX = mxCreateCellMatrix(1, NRVARIABLES);
+        for (k=0;k<NRVARIABLES;k++) mxSetCell(variablesMX,k,mxCreateString(variableNames[k]));
+        mxSetField(resultMX, 0, "variables", variablesMX);
+    }
+    if (NRREACTIONS > 0) {
+        reactionsMX = mxCreateCellMatrix(1, NRREACTIONS);
+        for (k=0;k<NRREACTIONS;k++) mxSetCell(reactionsMX,k,mxCreateString(reactionNames[k]));
+        mxSetField(resultMX, 0, "reactions", reactionsMX);
+    }
+    if (NREVENTS > 0) {
+        eventsMX = mxCreateCellMatrix(1, NREVENTS);
+        for (k=0;k<NREVENTS;k++) mxSetCell(eventsMX,k,mxCreateString(eventNames[k]));
+        mxSetField(resultMX, 0, "events", eventsMX);
+        if (nreventshappend > 0) {
+            eventtimesMX = mxCreateDoubleMatrix(1,nreventshappend,mxREAL);
+            mxSetData(eventtimesMX, eventtimes);
+            mxSetField(resultMX, 0, "eventtimes", eventtimesMX);
+            eventflagsMX = mxCreateDoubleMatrix(NREVENTS,nreventshappend,mxREAL);
+            mxSetData(eventflagsMX, eventflagsdata);
+            mxSetField(resultMX, 0, "eventflags", eventflagsMX);
+        }
+    }
+    return resultMX;
+}
+
+/*
+ *========================================================================
+ * Initialization of variables
+ *========================================================================
+ */
+static void doInitilizationVariables()
+ {
+    timesimvectorMX = NULL;
+    timesimvector = NULL;
+    parametervectorMX = NULL;
+    parametervector = NULL;
+    parametervectorCVODES = NULL;
+    initialconditionsMX = NULL;
+    initialconditions = NULL;
+    optionsMX = NULL;
+    showIntegratorStatsMX = NULL;
+    showIntegratorStats = 0;
+    minstepMX = NULL;
+    maxstepMX = NULL;
+    maxnumstepsMX = NULL;
+    reltolMX = NULL;
+    abstolMX = NULL;
+    maxerrtestfailsMX = NULL;
+    maxorderMX = NULL;
+    maxconvfailsMX = NULL;
+    initstepMX = NULL;
+    maxnonlineariterMX = NULL;
+    xdotcalcMX = NULL;
+    resultMX = NULL;
+    result = NULL;
+    statesMX = NULL;
+    statevaluesMX = NULL;
+    statevalues = NULL;
+    variablesMX = NULL;
+    variablevaluesMX = NULL;
+    variablevalues = NULL;
+    reactionsMX = NULL;
+    reactionvaluesMX = NULL;
+    reactionvalues = NULL;
+    eventsMX = NULL;
+    eventtimesMX = NULL;
+    eventtimes = NULL;
+    eventflagsMX = NULL;
+    eventflags = NULL;
+    u = NULL;
+    statevec = NULL;
+    variablevec = NULL;
+    reactionvec = NULL;
+    eventvec = NULL;
+    eventdataold = NULL;
+    eventflagsdata = NULL;
+    timevectorEmpty = 0;
+    timevectorNotVector = 0;
+    timevectorIsScalar = 0;
+    methodMX = NULL;
+}
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/CVODEmex25.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/CVODEmex25.h
new file mode 100644
index 0000000000000000000000000000000000000000..65a4792a3fc903b80cf54bdcaa5bdc06b5c37df7
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/CVODEmex25.h
@@ -0,0 +1,33 @@
+/*
+ * CVODEmex25.h: MEX/CVODES Interface for Sundials CVODES version 2.5
+ *
+ * Information:
+ * ============
+ * SBPD Package - Systems Biology Parameter Determination Package
+ * Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+ */
+
+/* CVODE related flags */
+#define DOFLAG_DDT 0
+#define DOFLAG_VARREAC 1
+#define DOFLAG_EVENTS 2
+#define DOFLAG_EVENTASSIGN 3
+#define DOFLAG_CALCICS 4
+
+/* ParamData (contains pointer to parameter values passed to integrator) */
+typedef struct {
+    double *parametervector;
+} ParamData;
+
+/* Variables defined outside the library */
+extern double defaultICs_num[], defaultParam[];
+extern char  *defaultICs_nonnum[];
+extern char  *stateNames[], *parameterNames[], *variableNames[], *reactionNames[], *eventNames[]; 
+extern const int NRSTATES, NRPARAMETERS, NRVARIABLES, NRREACTIONS, NREVENTS;
+extern const int hasOnlyNumericICs;
+extern int   *interpcseSB_check; /* needed for spline function in mexsplineaddon.h */
+extern int   *interpcseSlopeSB_check; /* needed for spline function in mexsplineaddon.h */
+
+/* Functions containing the model equations */
+extern void model(double time, double *stateVector, double *DDTvector, ParamData *paramdataPtr, int DOflag, double *variableVector, double *reactionVector, double *gout, int *eventVector);
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/SUNDIALS_VERSION_2.5.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/SUNDIALS_VERSION_2.5.txt
new file mode 100644
index 0000000000000000000000000000000000000000..ad1a2c0dbcf0225ff2997468e417e93d1c65d70f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/SUNDIALS_VERSION_2.5.txt
@@ -0,0 +1 @@
+ Just a reminder about which version of SUNDIALS CVODES is used :)
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/ar32.exe b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/ar32.exe
new file mode 100644
index 0000000000000000000000000000000000000000..86bccf5dc6f980d6338b9b37d03d498e68720f27
Binary files /dev/null and b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/ar32.exe differ
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/ar64.exe b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/ar64.exe
new file mode 100644
index 0000000000000000000000000000000000000000..befe5958086797d9c9fc9fdcc0eae6faa4697060
Binary files /dev/null and b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/ar64.exe differ
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/buildCVODElib.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/buildCVODElib.m
new file mode 100644
index 0000000000000000000000000000000000000000..848766d207581cb24814a6ad7bc2de429a56e3db
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/buildCVODElib.m
@@ -0,0 +1,69 @@
+% This script generates a static library file for the CVODES integrator 
+% package, including the MEX interface for MATLAB. Windows Version.
+% Compiler used: LCC (MATLAB inbuild)
+%
+% Usually the user does not need to run this script, since for windows the 
+% precompiled library is distributed along with the SBPD package.
+% However, if the user wants to change the source code of the interface the
+% new library can be build by running this script. The library file and 
+% the header files are then automatically copied/installed at the correct 
+% locations.
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+
+% Copy files
+disp('Copying files ...');
+!copy CVODEmex25.c source_SUNDIALS_CVODES_25
+!copy CVODEmex25.h include_SUNDIALS_CVODES_25
+!copy mexmathaddon.h include_SUNDIALS_CVODES_25
+!copy mexsplineaddon.h include_SUNDIALS_CVODES_25
+
+% Change into source folder
+cd source_SUNDIALS_CVODES_25
+
+% Compile all files to object code using MinGW
+disp('Compiling files ...');
+mex -O -c -I../include_SUNDIALS_CVODES_25 CVODEmex25.c cvodea.c cvodea_io.c cvodes.c cvodes_band.c cvodes_bandpre.c cvodes_bbdpre.c cvodes_dense.c cvodes_diag.c cvodes_io.c cvodes_spbcgs.c cvodes_spbcgs.c cvodes_spils.c cvodes_sptfqmr.c nvector_serial.c sundials_band.c sundials_dense.c sundials_iterative.c sundials_math.c sundials_nvector.c sundials_smalldense.c sundials_spbcgs.c sundials_spgmr.c sundials_sptfqmr.c
+
+% Delete the copied files again
+disp('Deleting copied files ');
+delete CVODEmex25.c
+delete ../include_SUNDIALS_CVODES_25/CVODEmex25.h
+delete ../include_SUNDIALS_CVODES_25/mexmathaddon.h
+delete ../include_SUNDIALS_CVODES_25/mexsplineaddon.h
+
+% Bind the object code files into a library.
+disp('Generating library ');
+% Use different ar's for 32 and 64 bit systems
+if ~isempty(strfind(mexext,'32')),
+    % 32 bit system
+    system('"../ar32" rc CVODEmex25.lib *.obj');
+elseif ~isempty(strfind(mexext,'64')),
+    % 64 bit system
+    system('"../ar64" rc CVODEmex25.lib CVODEmex25.obj cvodes_band.obj cvodes_diag.obj cvodes_sptfqmr.obj sundials_iterative.obj sundials_spbcgs.obj cvodea.obj cvodes_bandpre.obj cvodes_io.obj nvector_serial.obj sundials_math.obj sundials_spgmr.obj cvodea_io.obj cvodes_bbdpre.obj cvodes_spbcgs.obj sundials_band.obj sundials_nvector.obj sundials_sptfqmr.obj cvodes.obj cvodes_dense.obj cvodes_spils.obj sundials_dense.obj sundials_smalldense.obj');
+else
+    error('You got a strange system from the future ... or from the past?');
+end
+
+% Delete all object code files
+disp('Deleting object files ');
+delete *.obj
+
+% Move generated lib file to parent folder
+disp('Finishing ');
+!move *.lib ../../lib
+cd ..
+
+% copy needed header files into the include folder of the package
+!copy CVODEmex25.h "../include"
+!copy mexmathaddon.h "../include"
+!copy kineticformulas.h "../include"
+!copy mexsplineaddon.h "../include"
+
+% display success message
+disp('The library has been build and all necessary files have been installed.');
+disp(' ');
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/buildCVODElibunix.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/buildCVODElibunix.m
new file mode 100644
index 0000000000000000000000000000000000000000..817a38cb74668f3b97f46867f2957b134c257c9d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/buildCVODElibunix.m
@@ -0,0 +1,73 @@
+% This script generates a static library file for the CVODES integrator 
+% package, including the MEX interface for MATLAB. Unix/Linux Version.
+%
+% Before using the SBaddon package to create MEX simulation functions the 
+% user needs to build a static library that contains the SUNDIALS CVODES
+% package and the MEX interface functions. This library can be build by
+% running this script. The library file and the header files are then
+% automatically copied/installed at the correct locations.
+
+% Information:
+% ============
+% SBPD Package - Systems Biology Parameter Determination Package
+% Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+
+
+% Copy files
+disp('Copying files ...');
+!cp CVODEmex25.c source_SUNDIALS_CVODES_25
+!cp CVODEmex25.h include_SUNDIALS_CVODES_25
+!cp mexmathaddon.h include_SUNDIALS_CVODES_25
+!cp mexsplineaddon.h include_SUNDIALS_CVODES_25
+
+% Change into source folder
+cd source_SUNDIALS_CVODES_25
+
+% Compile all files to object code
+disp('Compiling files ...');
+mex -c -O -I../include_SUNDIALS_CVODES_25 ...
+        CVODEmex25.c ...
+        cvodea.c                cvodea_io.c ...
+        cvodes.c                cvodes_band.c ...
+        cvodes_bandpre.c        cvodes_bbdpre.c ...
+        cvodes_dense.c          cvodes_diag.c ...
+        cvodes_io.c             cvodes_spbcgs.c ...
+        cvodes_spbcgs.c         cvodes_spils.c ...
+        cvodes_sptfqmr.c        nvector_serial.c ...
+        sundials_band.c         ...
+        sundials_dense.c        sundials_iterative.c ...
+        sundials_math.c         sundials_nvector.c ...
+        sundials_smalldense.c   sundials_spbcgs.c ...
+        sundials_spgmr.c        sundials_sptfqmr.c
+
+% Delete the copied files again
+disp('Deleting copied files ...');
+delete CVODEmex25.c
+delete ../include_SUNDIALS_CVODES_25/CVODEmex25.h
+delete ../include_SUNDIALS_CVODES_25/mexmathaddon.h
+delete ../include_SUNDIALS_CVODES_25/mexsplineaddon.h
+
+% Bind the object code files into a library.
+% To be able to do that the lib.exe needs to be 
+% in the system path.
+disp('Generating library ...');
+!ar rc CVODEmex25.a *.o
+
+% Delete all object code files
+disp('Deleting object files ...');
+delete *.o
+
+% Move generated lib file to parent folder
+disp('Finishing ...');
+!mv *.a ../../lib
+cd ..
+
+% copy needed header files into the include folder of the package
+!cp CVODEmex25.h ../include
+!cp mexmathaddon.h ../include
+!cp kineticformulas.h ../include
+!cp mexsplineaddon.h "../include"
+
+% display success message
+disp('The library has been build and all necessary files have been installed.');
+disp(' ');
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes.h
new file mode 100644
index 0000000000000000000000000000000000000000..cab8a95d95514f64d6b896879c51e7e5f90e3258
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes.h
@@ -0,0 +1,1604 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2005, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the interface file for the main CVODES integrator.
+ * -----------------------------------------------------------------
+ *
+ * CVODES is used to solve numerically the ordinary initial value    
+ * problem:                                                          
+ *                                                                   
+ *                 y' = f(t,y),                                      
+ *                 y(t0) = y0,                                       
+ *                                                                   
+ * where t0, y0 in R^N, and f: R x R^N -> R^N are given.             
+ *                                                                   
+ * Optionally, CVODES can perform forward or adjoint sensitivity 
+ * analysis to find sensitivities of the solution y with respect 
+ * to parameters in the right hand side f and/or in the initial         
+ * conditions y0.                                                    
+ *
+ * -----------------------------------------------------------------
+ */
+
+#ifndef _CVODES_H
+#define _CVODES_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#include <stdio.h>
+
+#include <sundials/sundials_nvector.h>
+
+  /*
+   * =================================================================
+   *              C V O D E S     C O N S T A N T S
+   * =================================================================
+   */
+
+  /*
+   * -----------------------------------------------------------------
+   * Enumerations for inputs to CVodeCreate, CVodeMalloc,
+   * CVodeReInit, CVodeSensMalloc, CVodeSensReInit, CVodeQuadMalloc,
+   * CVodeQuadReInit, CVodeSet*, CVode, and CVadjMalloc.
+   * -----------------------------------------------------------------
+   * Symbolic constants for the lmm, iter, and itol input parameters 
+   * to CVodeMalloc and CVodeReInit, the input parameter itask to CVode, 
+   * and the input parameter interp to CVadjMalloc, are given below.
+   *
+   * lmm:   The user of the CVODES package specifies whether to use
+   *        the CV_ADAMS or CV_BDF (backward differentiation formula)
+   *        linear multistep method. The BDF method is recommended
+   *        for stiff problems, and the CV_ADAMS method is recommended
+   *        for nonstiff problems.
+   *
+   * iter:  At each internal time step, a nonlinear equation must
+   *        be solved. The user can specify either CV_FUNCTIONAL
+   *        iteration, which does not require linear algebra, or a
+   *        CV_NEWTON iteration, which requires the solution of linear
+   *        systems. In the CV_NEWTON case, the user also specifies a
+   *        CVODE linear solver. CV_NEWTON is recommended in case of
+   *        stiff problems.
+   *
+   * itol:  This parameter specifies the relative and absolute
+   *        tolerance types to be used. The CV_SS tolerance type means
+   *        a scalar relative and absolute tolerance. The CV_SV
+   *        tolerance type means a scalar relative tolerance and a
+   *        vector absolute tolerance (a potentially different
+   *        absolute tolerance for each vector component). The CV_WF
+   *        tolerance type means that the user provides a function
+   *        (of type CVEwtFn) to set the error weight vector.
+   *
+   * ism:   This parameter specifies the sensitivity corrector type
+   *        to be used. In the CV_SIMULTANEOUS case, the nonlinear
+   *        systems for states and all sensitivities are solved
+   *        simultaneously. In the CV_STAGGERED case, the nonlinear
+   *        system for states is solved first and then, the
+   *        nonlinear systems for all sensitivities are solved
+   *        at the same time. Finally, in the CV_STAGGERED1 approach
+   *        all nonlinear systems are solved in a sequence.
+   *
+   * itask: The itask input parameter to CVode indicates the job
+   *        of the solver for the next user step. The CV_NORMAL
+   *        itask is to have the solver take internal steps until
+   *        it has reached or just passed the user specified tout
+   *        parameter. The solver then interpolates in order to
+   *        return an approximate value of y(tout). The CV_ONE_STEP
+   *        option tells the solver to just take one internal step
+   *        and return the solution at the point reached by that
+   *        step. The CV_NORMAL_TSTOP and CV_ONE_STEP_TSTOP modes are
+   *        similar to CV_NORMAL and CV_ONE_STEP, respectively, except
+   *        that the integration never proceeds past the value
+   *        tstop (specified through the routine CVodeSetStopTime).
+   *
+   * interp: Specifies the interpolation type used to evaluate the
+   *        forward solution during the backward integration phase.
+   *        CV_HERMITE specifies cubic Hermite interpolation.
+   *        CV_POYNOMIAL specifies the polynomial interpolation
+   * -----------------------------------------------------------------
+   */
+
+  /* lmm */
+#define CV_ADAMS          1
+#define CV_BDF            2
+
+  /* iter */
+#define CV_FUNCTIONAL     1
+#define CV_NEWTON         2
+
+  /* itol */
+#define CV_SS             1
+#define CV_SV             2
+#define CV_WF             3
+#define CV_EE             4
+
+  /* itask */
+#define CV_NORMAL         1
+#define CV_ONE_STEP       2
+#define CV_NORMAL_TSTOP   3
+#define CV_ONE_STEP_TSTOP 4
+
+  /* ism */
+#define CV_SIMULTANEOUS   1
+#define CV_STAGGERED      2
+#define CV_STAGGERED1     3
+
+  /* DQtype */
+#define CV_CENTERED       1
+#define CV_FORWARD        2
+
+  /* interp */
+#define CV_HERMITE        1
+#define CV_POLYNOMIAL     2
+
+  /* 
+   * ----------------------------------------
+   * CVODES return flags
+   * ----------------------------------------
+   */
+
+#define CV_SUCCESS               0
+#define CV_TSTOP_RETURN          1
+#define CV_ROOT_RETURN           2
+
+#define CV_WARNING              99
+
+#define CV_TOO_MUCH_WORK        -1
+#define CV_TOO_MUCH_ACC         -2
+#define CV_ERR_FAILURE          -3
+#define CV_CONV_FAILURE         -4
+
+#define CV_LINIT_FAIL           -5
+#define CV_LSETUP_FAIL          -6
+#define CV_LSOLVE_FAIL          -7
+#define CV_RHSFUNC_FAIL         -8
+#define CV_FIRST_RHSFUNC_ERR    -9
+#define CV_REPTD_RHSFUNC_ERR    -10
+#define CV_UNREC_RHSFUNC_ERR    -11
+#define CV_RTFUNC_FAIL          -12
+
+#define CV_MEM_FAIL             -20
+#define CV_MEM_NULL             -21
+#define CV_ILL_INPUT            -22
+#define CV_NO_MALLOC            -23
+#define CV_BAD_K                -24
+#define CV_BAD_T                -25
+#define CV_BAD_DKY              -26
+#define CV_TOO_CLOSE            -27
+
+#define CV_NO_QUAD              -30
+#define CV_QRHSFUNC_FAIL        -31
+#define CV_FIRST_QRHSFUNC_ERR   -32
+#define CV_REPTD_QRHSFUNC_ERR   -33
+#define CV_UNREC_QRHSFUNC_ERR   -34
+
+#define CV_BAD_IS               -40
+#define CV_NO_SENS              -41
+#define CV_SRHSFUNC_FAIL        -42
+#define CV_FIRST_SRHSFUNC_ERR   -43
+#define CV_REPTD_SRHSFUNC_ERR   -44
+#define CV_UNREC_SRHSFUNC_ERR   -45
+
+  /* 
+   * ----------------------------------------
+   * CVODEA return flags
+   * ----------------------------------------
+   */
+
+#define CV_ADJMEM_NULL         -101
+#define CV_BAD_TB0             -103
+#define CV_BCKMEM_NULL         -104
+#define CV_REIFWD_FAIL         -105
+#define CV_FWD_FAIL            -106
+#define CV_BAD_ITASK           -107
+#define CV_BAD_TBOUT           -108
+#define CV_GETY_BADT           -109
+
+  /*
+   * =================================================================
+   *              F U N C T I O N   T Y P E S
+   * =================================================================
+   */
+
+  /*
+   * -----------------------------------------------------------------
+   * Type : CVRhsFn
+   * -----------------------------------------------------------------
+   * The f function which defines the right hand side of the ODE
+   * system y' = f(t,y) must have type CVRhsFn.
+   * f takes as input the independent variable value t, and the
+   * dependent variable vector y.  It stores the result of f(t,y)
+   * in the vector ydot.  The y and ydot arguments are of type
+   * N_Vector.
+   * (Allocation of memory for ydot is handled within CVODES)
+   * The f_data parameter is the same as the f_data
+   * parameter set by the user through the CVodeSetFdata routine.
+   * This user-supplied pointer is passed to the user's f function
+   * every time it is called.
+   *
+   * A CVRhsFn should return 0 if successful, a negative value if
+   * an unrecoverable error occured, and a positive value if a 
+   * recoverable error (e.g. invalid y values) occured. 
+   * If an unrecoverable occured, the integration is halted. 
+   * If a recoverable error occured, then (in most cases) CVODES
+   * will try to correct and retry.
+   * -----------------------------------------------------------------
+   */
+
+  typedef int (*CVRhsFn)(realtype t, N_Vector y,
+                         N_Vector ydot, void *f_data);
+
+  /*
+   * -----------------------------------------------------------------
+   * Type : CVRootFn
+   * -----------------------------------------------------------------
+   * A function g, which defines a set of functions g_i(t,y) whose
+   * roots are sought during the integration, must have type CVRootFn.
+   * The function g takes as input the independent variable value
+   * t, and the dependent variable vector y.  It stores the nrtfn
+   * values g_i(t,y) in the realtype array gout.
+   * (Allocation of memory for gout is handled within CVODE.)
+   * The g_data parameter is the same as that passed by the user
+   * to the CVodeRootInit routine.  This user-supplied pointer is
+   * passed to the user's g function every time it is called.
+   *
+   * A CVRootFn should return 0 if successful or a non-zero value
+   * if an error occured (in which case the integration will be halted).
+   * -----------------------------------------------------------------
+   */
+
+  typedef int (*CVRootFn)(realtype t, N_Vector y, realtype *gout,
+                          void *g_data);
+
+  /*
+   * -----------------------------------------------------------------
+   * Type : CVEwtFn
+   * -----------------------------------------------------------------
+   * A function e, which sets the error weight vector ewt, must have
+   * type CVEwtFn.
+   * The function e takes as input the current dependent variable y.
+   * It must set the vector of error weights used in the WRMS norm:
+   * 
+   *   ||y||_WRMS = sqrt [ 1/N * sum ( ewt_i * y_i)^2 ]
+   *
+   * Typically, the vector ewt has components:
+   * 
+   *   ewt_i = 1 / (reltol * |y_i| + abstol_i)
+   *
+   * The e_data parameter is the same as that passed by the user
+   * to the CVodeSetEdata routine.  This user-supplied pointer is
+   * passed to the user's e function every time it is called.
+   * A CVEwtFn e must return 0 if the error weight vector has been
+   * successfuly set and a non-zero value otherwise.
+   * -----------------------------------------------------------------
+   */
+
+  typedef int (*CVEwtFn)(N_Vector y, N_Vector ewt, void *e_data);
+
+
+  /*
+   * -----------------------------------------------------------------
+   * Type : CVErrHandlerFn
+   * -----------------------------------------------------------------
+   * A function eh, which handles error messages, must have type
+   * CVErrHandlerFn.
+   * The function eh takes as input the error code, the name of the
+   * module reporting the error, the error message, and a pointer to
+   * user data, the same as that passed to CVodeSetErrHandlerFn.
+   * 
+   * All error codes are negative, except CV_WARNING which indicates 
+   * a warning (the solver continues).
+   *
+   * A CVErrHandlerFn has no return value.
+   * -----------------------------------------------------------------
+   */
+  
+  typedef void (*CVErrHandlerFn)(int error_code, 
+                                 const char *module, const char *function, 
+                                 char *msg, void *eh_data); 
+
+  /*
+   * -----------------------------------------------------------------
+   * Type : CVQuadRhsFn
+   * -----------------------------------------------------------------
+   * The fQ function which defines the right hand side of the
+   * quadrature equations yQ' = fQ(t,y) must have type CVQuadRhsFn.
+   * fQ takes as input the value of the independent variable t,
+   * the vector of states y and must store the result of fQ in
+   * yQdot. (Allocation of memory for yQdot is handled by CVODES).
+   * The fQ_data parameter is the same as the fQ_data parameter
+   * set by the user through the CVodeSetQuadFdata routine and is
+   * passed to the fQ function every time it is called.
+   *
+   * A CVQuadRhsFn should return 0 if successful, a negative value if
+   * an unrecoverable error occured, and a positive value if a 
+   * recoverable error (e.g. invalid y values) occured. 
+   * If an unrecoverable occured, the integration is halted. 
+   * If a recoverable error occured, then (in most cases) CVODES
+   * will try to correct and retry.
+   * -----------------------------------------------------------------
+   */
+
+  typedef int (*CVQuadRhsFn)(realtype t, N_Vector y, N_Vector yQdot,
+                             void *fQ_data);
+
+  /*
+   * -----------------------------------------------------------------
+   * Type : CVSensRhsFn
+   * -----------------------------------------------------------------
+   * The fS function which defines the right hand side of the
+   * sensitivity ODE systems s' = f_y * s + f_p must have type
+   * CVSensRhsFn.
+   * fS takes as input the number of sensitivities Ns, the
+   * independent variable value t, the states y and the
+   * corresponding value of f(t,y) in ydot, and the dependent
+   * sensitivity vectors yS. It stores the result of fS in ySdot.
+   * (Allocation of memory for ySdot is handled within CVODES)
+   * The fS_data parameter is the same as the fS_data parameter
+   * set by the user through the CVodeSetSensFdata routine and is
+   * passed to the fS function every time it is called.
+   *
+   * A CVSensRhsFn should return 0 if successful, a negative value if
+   * an unrecoverable error occured, and a positive value if a 
+   * recoverable error (e.g. invalid y or yS values) occured. 
+   * If an unrecoverable occured, the integration is halted. 
+   * If a recoverable error occured, then (in most cases) CVODES
+   * will try to correct and retry.
+   * -----------------------------------------------------------------
+   */
+
+  typedef int (*CVSensRhsFn)(int Ns, realtype t,
+                             N_Vector y, N_Vector ydot,
+                             N_Vector *yS, N_Vector *ySdot,
+                             void *fS_data,
+                             N_Vector tmp1, N_Vector tmp2);
+
+  /*
+   * -----------------------------------------------------------------
+   * Type : CVSensRhs1Fn
+   * -----------------------------------------------------------------
+   * The fS1 function which defines the right hand side of the i-th
+   * sensitivity ODE system s_i' = f_y * s_i + f_p must have type
+   * CVSensRhs1Fn.
+   * fS1 takes as input the number of sensitivities Ns, the current
+   * sensitivity iS, the independent variable value t, the states y
+   * and the corresponding value of f(t,y) in ydot, and the
+   * dependent sensitivity vector yS. It stores the result of fS in
+   * ySdot.
+   * (Allocation of memory for ySdot is handled within CVODES)
+   * The fS_data parameter is the same as the fS_data parameter
+   * set by the user through the CVodeSetSensFdata routine and is
+   * passed to the fS1 function every time it is called.
+   *
+   * A CVSensRhs1Fn should return 0 if successful, a negative value if
+   * an unrecoverable error occured, and a positive value if a 
+   * recoverable error (e.g. invalid y or yS values) occured. 
+   * If an unrecoverable occured, the integration is halted. 
+   * If a recoverable error occured, then (in most cases) CVODES
+   * will try to correct and retry.
+   * -----------------------------------------------------------------
+   */
+
+  typedef int (*CVSensRhs1Fn)(int Ns, realtype t,
+                              N_Vector y, N_Vector ydot,
+                              int iS, N_Vector yS, N_Vector ySdot,
+                              void *fS_data,
+                              N_Vector tmp1, N_Vector tmp2);
+
+  /*
+   * -----------------------------------------------------------------
+   * CVRhsFnB
+   *    The fB function which defines the right hand side of the
+   *    ODE systems to be integrated backwards must have type CVRhsFnB.
+   * -----------------------------------------------------------------
+   * CVQuadRhsFnB
+   *    The fQB function which defines the quadratures to be integrated
+   *    backwards must have type CVQuadRhsFnB.
+   * -----------------------------------------------------------------
+   */
+  
+  typedef int (*CVRhsFnB)(realtype t, N_Vector y,
+                          N_Vector yB, N_Vector yBdot,
+                          void *f_dataB);
+  
+  typedef int (*CVQuadRhsFnB)(realtype t, N_Vector y,
+                              N_Vector yB, N_Vector qBdot,
+                              void *fQ_dataB);
+
+  /*
+   * =================================================================
+   *          U S E R - C A L L A B L E   R O U T I N E S
+   * =================================================================
+   */
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVodeCreate
+   * -----------------------------------------------------------------
+   * CVodeCreate creates an internal memory block for a problem to
+   * be solved by CVODES.
+   *
+   * lmm  is the type of linear multistep method to be used.
+   *      The legal values are CV_ADAMS and CV_BDF (see previous
+   *      description).
+   *
+   * iter  is the type of iteration used to solve the nonlinear
+   *       system that arises during each internal time step.
+   *       The legal values are CV_FUNCTIONAL and CV_NEWTON.
+   *
+   * If successful, CVodeCreate returns a pointer to initialized
+   * problem memory. This pointer should be passed to CVodeMalloc.
+   * If an initialization error occurs, CVodeCreate prints an error
+   * message to standard err and returns NULL.
+   * -----------------------------------------------------------------
+   */
+
+  void *CVodeCreate(int lmm, int iter);
+
+  /*
+   * -----------------------------------------------------------------
+   * Integrator optional input specification functions
+   * -----------------------------------------------------------------
+   * The following functions can be called to set optional inputs
+   * to values other than the defaults given below:
+   *
+   * Function                |  Optional input / [ default value ]
+   * -----------------------------------------------------------------
+   *                         |
+   * CVodeSetErrHandlerFn    | user-provided ErrHandler function.
+   *                         | [internal]
+   *                         |
+   * CVodeSetErrFile         | the file pointer for an error file
+   *                         | where all CVODE warning and error
+   *                         | messages will be written if the default
+   *                         | internal error handling function is used. 
+   *                         | This parameter can be stdout (standard 
+   *                         | output), stderr (standard error), or a 
+   *                         | file pointer (corresponding to a user 
+   *                         | error file opened for writing) returned 
+   *                         | by fopen.
+   *                         | If not called, then all messages will
+   *                         | be written to the standard error stream.
+   *                         | [stderr]
+   *                         |
+   * CVodeSetFdata           | a pointer to user data that will be
+   *                         | passed to the user's f function every
+   *                         | time f is called.
+   *                         | [NULL]
+   *                         |
+   * CVodeSetEwtFn           | user-provide EwtSet function e and 
+   *                         | a pointer to user data that will be
+   *                         | passed to the user's e function every
+   *                         | time e is called.
+   *                         | [NULL]
+   *                         | [NULL]
+   *                         |
+   * CVodeSetMaxOrd          | maximum lmm order to be used by the
+   *                         | solver.
+   *                         | [12 for Adams , 5 for BDF]
+   *                         |
+   * CVodeSetMaxNumSteps     | maximum number of internal steps to be
+   *                         | taken by the solver in its attempt to
+   *                         | reach tout.
+   *                         | [500]
+   *                         |
+   * CVodeSetMaxHnilWarns    | maximum number of warning messages
+   *                         | issued by the solver that t+h==t on the
+   *                         | next internal step. A value of -1 means
+   *                         | no such messages are issued.
+   *                         | [10]
+   *                         |
+   * CVodeSetStabLimDet      | flag to turn on/off stability limit
+   *                         | detection (TRUE = on, FALSE = off).
+   *                         | When BDF is used and order is 3 or
+   *                         | greater, CVsldet is called to detect
+   *                         | stability limit.  If limit is detected,
+   *                         | the order is reduced.
+   *                         | [FALSE]
+   *                         |
+   * CVodeSetInitStep        | initial step size.
+   *                         | [estimated by CVODES]
+   *                         |
+   * CVodeSetMinStep         | minimum absolute value of step size
+   *                         | allowed.
+   *                         | [0.0]
+   *                         |
+   * CVodeSetMaxStep         | maximum absolute value of step size
+   *                         | allowed.
+   *                         | [infinity]
+   *                         |
+   * CVodeSetStopTime        | the independent variable value past
+   *                         | which the solution is not to proceed.
+   *                         | [infinity]
+   *                         |
+   * CVodeSetMaxErrTestFails | Maximum number of error test failures
+   *                         | in attempting one step.
+   *                         | [7]
+   *                         |
+   * CVodeSetMaxNonlinIters  | Maximum number of nonlinear solver
+   *                         | iterations at one solution.
+   *                         | [3]
+   *                         |
+   * CVodeSetMaxConvFails    | Maximum number of allowable conv.
+   *                         | failures in attempting one step.
+   *                         | [10]
+   *                         |
+   * CVodeSetNonlinConvCoef  | Coeficient in the nonlinear conv.
+   *                         | test.
+   *                         | [0.1]
+   *                         |
+   * -----------------------------------------------------------------
+   *                         |
+   * CVodeSetIterType        | Changes the current nonlinear iteration
+   *                         | type.
+   *                         | [set by CVodecreate]
+   *                         |
+   * CVodeSetTolerances      | Changes the integration tolerances
+   *                         | between calls to CVode().
+   *                         | [set by CVodeMalloc/CVodeReInit]
+   *                         |
+   * -----------------------------------------------------------------
+   * Return flag:
+   *   CV_SUCCESS   if successful
+   *   CV_MEM_NULL  if the cvode memory is NULL
+   *   CV_ILL_INPUT if an argument has an illegal value
+   * -----------------------------------------------------------------
+   */
+
+  int CVodeSetErrHandlerFn(void *cvode_mem, CVErrHandlerFn ehfun, void *eh_data);
+  int CVodeSetErrFile(void *cvode_mem, FILE *errfp);
+  int CVodeSetFdata(void *cvode_mem, void *f_data);
+  int CVodeSetEwtFn(void *cvode_mem, CVEwtFn efun, void *e_data);
+  int CVodeSetMaxOrd(void *cvode_mem, int maxord);
+  int CVodeSetMaxNumSteps(void *cvode_mem, long int mxsteps);
+  int CVodeSetMaxHnilWarns(void *cvode_mem, int mxhnil);
+  int CVodeSetStabLimDet(void *cvode_mem, booleantype stldet);
+  int CVodeSetInitStep(void *cvode_mem, realtype hin);
+  int CVodeSetMinStep(void *cvode_mem, realtype hmin);
+  int CVodeSetMaxStep(void *cvode_mem, realtype hmax);
+  int CVodeSetStopTime(void *cvode_mem, realtype tstop);
+  int CVodeSetMaxErrTestFails(void *cvode_mem, int maxnef);
+  int CVodeSetMaxNonlinIters(void *cvode_mem, int maxcor);
+  int CVodeSetMaxConvFails(void *cvode_mem, int maxncf);
+  int CVodeSetNonlinConvCoef(void *cvode_mem, realtype nlscoef);
+
+  int CVodeSetIterType(void *cvode_mem, int iter);
+  int CVodeSetTolerances(void *cvode_mem,
+                         int itol, realtype reltol, void *abstol);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVodeMalloc
+   * -----------------------------------------------------------------
+   * CVodeMalloc allocates and initializes memory for a problem to
+   * to be solved by CVODES.
+   *
+   * cvode_mem is pointer to CVODES memory returned by CVodeCreate.
+   *
+   * f       is the right hand side function in y' = f(t,y).
+   *
+   * t0      is the initial value of t.
+   *
+   * y0      is the initial condition vector y(t0).
+   *
+   * itol    is the type of tolerances to be used.
+   *         The legal values are:
+   *            CV_SS (scalar relative and absolute  tolerances),
+   *            CV_SV (scalar relative tolerance and vector
+   *                  absolute tolerance).
+   *            CV_WF (indicates that the user will provide a
+   *                function to evaluate the error weights.
+   *                In this case, reltol and abstol are ignored.)
+   *
+   * reltol  is the relative tolerance scalar.
+   *
+   * abstol  is a pointer to the absolute tolerance scalar or
+   *         an N_Vector of absolute tolerances.
+   *
+   * The parameters itol, reltol, and abstol define a vector of
+   * error weights, ewt, with components
+   *   ewt[i] = 1/(reltol*abs(y[i]) + abstol)   (if itol = CV_SS), or
+   *   ewt[i] = 1/(reltol*abs(y[i]) + abstol[i])   (if itol = CV_SV).
+   * This vector is used in all error and convergence tests, which
+   * use a weighted RMS norm on all error-like vectors v:
+   *    WRMSnorm(v) = sqrt( (1/N) sum(i=1..N) (v[i]*ewt[i])^2 ),
+   * where N is the problem dimension.
+   *
+   * If successful, CVodeMalloc returns SUCCESS. If an argument has
+   * an illegal value, CVodeMalloc prints an error message to the
+   * file specified by errfp and returns one of the error flags
+   * defined below.
+   * -----------------------------------------------------------------
+   */
+
+  int CVodeMalloc(void *cvode_mem, CVRhsFn f,
+                  realtype t0, N_Vector y0,
+                  int itol, realtype reltol, void *abstol);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVodeReInit
+   * -----------------------------------------------------------------
+   * CVodeReInit re-initializes CVode for the solution of a problem,
+   * where a prior call to CVodeMalloc has been made with the same
+   * problem size N. CVodeReInit performs the same input checking
+   * and initializations that CVodeMalloc does.
+   * But it does no memory allocation, assuming that the existing
+   * internal memory is sufficient for the new problem.
+   *
+   * The use of CVodeReInit requires that the maximum method order,
+   * maxord, is no larger for the new problem than for the problem
+   * specified in the last call to CVodeMalloc.  This condition is
+   * automatically fulfilled if the multistep method parameter lmm
+   * is unchanged (or changed from CV_ADAMS to CV_BDF) and the default
+   * value for maxord is specified.
+   *
+   * The first argument to CVodeReInit is:
+   *
+   * cvode_mem = pointer to CVODES memory returned by CVodeCreate.
+   *
+   * All the remaining arguments to CVodeReInit have names and
+   * meanings identical to those of CVodeMalloc.
+   *
+   * The return value of CVodeReInit is equal to CV_SUCCESS = 0 if
+   * there were no errors; otherwise it is a negative int equal to:
+   *   CV_MEM_NULL  indicating cvode_mem was NULL (i.e.,
+   *                CVodeCreate has not been called).
+   *   CV_NO_MALLOC indicating that cvode_mem has not been
+   *                allocated (i.e., CVodeMalloc has not been
+   *                called).
+   *   CV_ILL_INPUT indicating an input argument was illegal
+   *                (including an attempt to increase maxord).
+   * In case of an error return, an error message is also printed.
+   * -----------------------------------------------------------------
+   */
+
+  int CVodeReInit(void *cvode_mem, CVRhsFn f,
+                  realtype t0, N_Vector y0,
+                  int itol, realtype reltol, void *abstol);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVodeRootInit
+   * -----------------------------------------------------------------
+   * CVodeRootInit initializes a rootfinding problem to be solved
+   * during the integration of the ODE system.  It must be called
+   * after CVodeCreate, and before CVode.  The arguments are:
+   *
+   * cvode_mem = pointer to CVODE memory returned by CVodeCreate.
+   *
+   * nrtfn     = number of functions g_i, an int >= 0.
+   *
+   * g         = name of user-supplied function, of type CVRootFn,
+   *             defining the functions g_i whose roots are sought.
+   *
+   * g_data    = a pointer to user data that will be passed to the 
+   *             user's g function every time g is called.
+   *
+   * If a new problem is to be solved with a call to CVodeReInit,
+   * where the new problem has no root functions but the prior one
+   * did, then call CVodeRootInit with nrtfn = 0.
+   *
+   * The return value of CVodeRootInit is CV_SUCCESS = 0 if there were
+   * no errors; otherwise it is a negative int equal to:
+   *   CV_MEM_NULL    indicating cvode_mem was NULL, or
+   *   CV_MEM_FAIL    indicating a memory allocation failed.
+   *                  (including an attempt to increase maxord).
+   *   CV_ILL_INPUT   indicating nrtfn > 0 but g = NULL.
+   * In case of an error return, an error message is also printed.
+   * -----------------------------------------------------------------
+   */
+
+  int CVodeRootInit(void *cvode_mem, int nrtfn, CVRootFn g, void *g_data);
+
+  /*
+   * -----------------------------------------------------------------
+   * Quadrature optional input specification functions
+   * -----------------------------------------------------------------
+   * The following functions can be called to set optional inputs
+   * to values other than the defaults given below:
+   *
+   * Function             |  Optional input / [ default value ]
+   * --------------------------------------------------------------
+   *                      |
+   * CVodeSetQuadFdata    | a pointer to user data that will be
+   *                      | passed to the user's fQ function every
+   *                      | time fQ is called.
+   *                      | [NULL]
+   *                      |
+   * CVodeSetQuadErrCon   | are quadrature variables considered in
+   *                      | the error control?
+   *                      | If yes, set tolerances for quadrature
+   *                      | integration. 
+   *                      | [errconQ = FALSE]
+   *                      | [ not tolerances]
+   *                      |
+   * -----------------------------------------------------------------
+   * If successful, these functions return CV_SUCCESS. If an argument
+   * has an illegal value, they return one of the error flags
+   * defined for the CVodeSet* routines.
+   * -----------------------------------------------------------------
+   */
+
+  int CVodeSetQuadFdata(void *cvode_mem, void *fQ_data);
+  int CVodeSetQuadErrCon(void *cvode_mem, booleantype errconQ, 
+                         int itolQ, realtype reltolQ, void *abstolQ);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVodeQuadMalloc
+   * -----------------------------------------------------------------
+   * CVodeQuadMalloc allocates and initializes memory related to
+   * quadrature integration.
+   *
+   * cvode_mem is a pointer to CVODES memory returned by CVodeCreate
+   *
+   * fQ    is the user-provided integrand routine.
+   *
+   * yQ0   is an N_Vector with initial values for quadratures
+   *       (typically yQ0 has all zero components).
+   *
+   * Return values:
+   *  CV_SUCCESS if successful
+   *  CV_MEM_NULL if the cvode memory was NULL
+   *  CV_MEM_FAIL if a memory allocation failed
+   * -----------------------------------------------------------------
+   */
+
+  int CVodeQuadMalloc(void *cvode_mem, CVQuadRhsFn fQ, N_Vector yQ0);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVodeQuadReInit
+   * -----------------------------------------------------------------
+   * CVodeQuadReInit re-initializes CVODES's quadrature related
+   * memory for a problem, assuming it has already been allocated
+   * in prior calls to CVodeMalloc and CVodeQuadMalloc.
+   *
+   * All problem specification inputs are checked for errors.
+   * The number of quadratures Nq is assumed to be unchanged
+   * since the previous call to CVodeQuadMalloc.
+   *
+   * Return values:
+   *  CV_SUCCESS  if successful
+   *  CV_MEM_NULL if the cvode memory was NULL
+   *  CV_NO_QUAD  if quadratures were not initialized
+   * -----------------------------------------------------------------
+   */
+
+  int CVodeQuadReInit(void *cvode_mem, CVQuadRhsFn fQ, N_Vector yQ0);
+
+  /*
+   * -----------------------------------------------------------------
+   * Forward sensitivity optional input specification functions
+   * -----------------------------------------------------------------
+   * The following functions can be called to set optional inputs
+   * to other values than the defaults given below:
+   *
+   * Function                   |  Optional input / [ default value ]
+   * -----------------------------------------------------------------
+   *                            |
+   * CVodeSetSensRhsFn          | sensitivity right hand side function
+   *                            | and user data pointer.
+   *                            | This function must compute right hand
+   *                            | sides for all sensitivity equations.
+   *                            | [CVODES difference quotient approx.]
+   *                            | [internal]
+   *                            |
+   * CVodeSetSensRhs1Fn         | the sensitivity right hand side
+   *                            | and user data pointer.
+   *                            | This function must compute right hand
+   *                            | sides for one sensitivity equation at a
+   *                            | time.
+   *                            | [CVODES difference quotient approx.]
+   *                            | [internal]
+   *                            |
+   * CVodeSetSensDQMethod       | controls the selection of finite
+   *                            | difference schemes used in evaluating
+   *                            | the sensitivity right hand sides:
+   *                            | (centered vs. forward and 
+   *                            | simultaneous vs. separate)
+   *                            | [DQtype=CV_CENTERED]
+   *                            | [DQrhomax=0.0]
+   *                            |
+   * CVodeSetSensParams         | parameter information:
+   *                            | p: pointer to problem parameters
+   *                            | plist: list of parameters with respect
+   *                            |        to which sensitivities are to be
+   *                            |        computed.
+   *                            | pbar: order of magnitude info. 
+   *                            |       Typically, if p[plist[i]] is nonzero, 
+   *                            |       pbar[i]=p[plist[i]].
+   *                            | [p=NULL]
+   *                            | [plist=NULL]
+   *                            | [pbar=NULL]
+   *                            |
+   * CVodeSetSensErrCon         | are sensitivity variables considered in
+   *                            | the error control?
+   *                            | [FALSE]
+   *                            |
+   * CVodeSetSensTolerances     | type of sensi absolute tolerances.
+   *                            |
+   *                            | sensitivity relative tolerance scalar.
+   *                            |
+   *                            | pointer to the array of sensi
+   *                            | abs tol scalars or a pointer
+   *                            | to the array of N_Vector sensi
+   *                            | absolute tolerances.
+   *                            | [itolS = itol]
+   *                            | [reltolS = reltol]
+   *                            | [abstolS estimated by CVODES]
+   *                            |
+   * CVodeSetSensMaxNonlinIters | Maximum number of nonlinear solver
+   *                            | iterations at one solution.
+   *                            | [3]
+   *                            |
+   * -----------------------------------------------------------------
+   * The return values are the same as for CVodeSet*
+   * -----------------------------------------------------------------
+   */
+
+  int CVodeSetSensRhsFn(void *cvode_mem, CVSensRhsFn f, void *fS_dataS);
+  int CVodeSetSensRhs1Fn(void *cvode_mem, CVSensRhs1Fn fS, void *fS_data);
+  int CVodeSetSensDQMethod(void *cvode_mem, int DQtype, realtype DQrhomax);
+  int CVodeSetSensErrCon(void *cvode_mem, booleantype errconS);
+  int CVodeSetSensMaxNonlinIters(void *cvode_mem, int maxcorS);
+  int CVodeSetSensParams(void *cvode_mem, realtype *p, realtype *pbar, int *plist);
+  int CVodeSetSensTolerances(void *cvode_mem, int itolS,
+                             realtype reltolS, void *abstolS);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVodeSensMalloc
+   * -----------------------------------------------------------------
+   * CVodeSensMalloc allocates and initializes memory related to
+   * sensitivity computations.
+   *
+   * cvode_mem is pointer to CVODES memory returned by CVodeCreate
+   *
+   * Ns        is the number of sensitivities to be computed.
+   *
+   * ism       is the type of corrector used in sensitivity
+   *           analysis. The legal values are: CV_SIMULTANEOUS,
+   *           CV_STAGGERED, and CV_STAGGERED1 (see previous description)
+   *
+   * yS0       is the array of initial condition vectors for
+   *           sensitivity variables.
+   *
+   * Return values:
+   *   CV_SUCCESS
+   *   CV_MEM_NULL
+   *   CV_ILL_INPUT 
+   *   CV_MEM_FAIL
+   * -----------------------------------------------------------------
+   */
+
+  int CVodeSensMalloc(void *cvode_mem, int Ns, int ism, N_Vector *yS0);
+    
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVodeSensReInit
+   * -----------------------------------------------------------------
+   * CVodeSensReInit re-initializes CVODES's sensitivity related
+   * memory for a problem, assuming it has already been allocated
+   * in prior calls to CVodeMalloc and CvodeSensMalloc.
+   *
+   * All problem specification inputs are checked for errors.
+   * The number of sensitivities Ns is assumed to be unchanged
+   * since the previous call to CVodeSensMalloc.
+   * If any error occurs during initialization, it is reported to
+   * the file whose file pointer is errfp.
+   *
+   * CVodeSensReInit potentially does some minimal memory allocation
+   * (for the sensitivity absolute tolerance and for arrays of
+   * counters used by the CV_STAGGERED1 method).
+   *
+   * The return value is equal to CV_SUCCESS = 0 if there were no
+   * errors; otherwise it is a negative int equal to:
+   *   CV_MEM_NULL  indicating cvode_mem was NULL, or
+   *   CV_NO_SENS   indicating there was not a prior call to
+   *                CVodeSensMalloc.
+   *   CV_ILL_INPUT indicating an input argument was illegal
+   *                (including an attempt to increase maxord).
+   *   CV_MEM_FAIL  indicating a memory request failed.
+   * In case of an error return, an error message is also printed.
+   * -----------------------------------------------------------------
+   */
+
+  int CVodeSensReInit(void *cvode_mem, int ism, N_Vector *yS0);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVodeSensToggleOff
+   * -----------------------------------------------------------------
+   * CVodeSensToggleOff deactivates sensitivity calculations.
+   * It does NOT deallocate sensitivity-related memory so that 
+   * sensitivity computations can be later toggled ON (through
+   * CVodeSensReInit).
+   * 
+   * The return value is equal to CV_SUCCESS = 0 if there were no
+   * errors or CV_MEM_NULL if cvode_mem was NULL
+   * -----------------------------------------------------------------
+   */
+
+  int CVodeSensToggleOff(void *cvode_mem);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVode
+   * -----------------------------------------------------------------
+   * CVode integrates the ODE over an interval in t.
+   * If itask is CV_NORMAL, then the solver integrates from its
+   * current internal t value to a point at or beyond tout, then
+   * interpolates to t = tout and returns y(tout) in the user-
+   * allocated vector yout. If itask is CV_ONE_STEP, then the solver
+   * takes one internal time step and returns in yout the value of
+   * y at the new internal time. In this case, tout is used only
+   * during the first call to CVode to determine the direction of
+   * integration and the rough scale of the problem.  If itask is
+   * CV_NORMAL_TSTOP or CV_ONE_STEP_TSTOP, then CVode returns the
+   * solution at tstop if that comes sooner than tout or the end of
+   * the next internal step, respectively.  In any case,
+   * the time reached by the solver is placed in (*tret). The
+   * user is responsible for allocating the memory for this value.
+   *
+   * cvode_mem is the pointer to CVODES memory returned by
+   *           CVodeCreate.
+   *
+   * tout  is the next time at which a computed solution is desired.
+   *
+   * yout  is the computed solution vector. In CV_NORMAL mode with no
+   *       errors and no roots found, yout=y(tout).
+   *
+   * tret  is a pointer to a real location. CVode sets (*tret) to
+   *       the time reached by the solver and returns yout=y(*tret).
+   *
+   * itask is CV_NORMAL, CV_ONE_STEP, CV_NORMAL_TSTOP, or CV_ONE_STEP_TSTOP.
+   *       These four modes are described above.
+   *
+   * Here is a brief description of each return value:
+   *
+   * CV_SUCCESS:     CVode succeeded and no roots were found.
+   *
+   * CV_ROOT_RETURN: CVode succeeded, and found one or more roots.
+   *                 If nrtfn > 1, call CVodeGetRootInfo to see
+   *                 which g_i were found to have a root at (*tret).
+   *
+   * CV_TSTOP_RETURN: CVode succeded and returned at tstop.
+   *
+   * CV_MEM_NULL:    The cvode_mem argument was NULL.
+   *
+   * CV_NO_MALLOC:   cvode_mem was not allocated.
+   *
+   * CV_ILL_INPUT:   One of the inputs to CVode is illegal. This
+   *                 includes the situation when a component of the
+   *                 error weight vectors becomes < 0 during
+   *                 internal time-stepping. The ILL_INPUT flag
+   *                 will also be returned if the linear solver
+   *                 routine CV--- (called by the user after
+   *                 calling CVodeCreate) failed to set one of the
+   *                 linear solver-related fields in cvode_mem or
+   *                 if the linear solver's init routine failed. In
+   *                 any case, the user should see the printed
+   *                 error message for more details.
+   *
+   * CV_TOO_MUCH_WORK: The solver took mxstep internal steps but
+   *                 could not reach tout. The default value for
+   *                 mxstep is MXSTEP_DEFAULT = 500.
+   *
+   * CV_TOO_MUCH_ACC: The solver could not satisfy the accuracy
+   *                 demanded by the user for some internal step.
+   *
+   * CV_ERR_FAILURE: Error test failures occurred too many times
+   *                 (= MXNEF = 7) during one internal time step or
+   *                 occurred with |h| = hmin.
+   *
+   * CV_CONV_FAILURE: Convergence test failures occurred too many
+   *                 times (= MXNCF = 10) during one internal time
+   *                 step or occurred with |h| = hmin.
+   *
+   * CV_LINIT_FAIL:  The linear solver's initialization function 
+   *                 failed.
+   *
+   * CV_LSETUP_FAIL: The linear solver's setup routine failed in an
+   *                 unrecoverable manner.
+   *
+   * CV_LSOLVE_FAIL: The linear solver's solve routine failed in an
+   *                 unrecoverable manner.
+   * -----------------------------------------------------------------
+   */
+
+  int CVode(void *cvode_mem, realtype tout, N_Vector yout,
+            realtype *tret, int itask);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVodeGetDky
+   * -----------------------------------------------------------------
+   * CVodeGetDky computes the kth derivative of the y function at
+   * time t, where tn-hu <= t <= tn, tn denotes the current
+   * internal time reached, and hu is the last internal step size
+   * successfully used by the solver. The user may request
+   * k=0, 1, ..., qu, where qu is the current order. The
+   * derivative vector is returned in dky. This vector must be
+   * allocated by the caller. It is only legal to call this
+   * function after a successful return from CVode.
+   *
+   * cvode_mem is the pointer to CVODES memory returned by
+   *           CVodeCreate.
+   *
+   * t   is the time at which the kth derivative of y is evaluated.
+   *     The legal range for t is [tn-hu,tn] as described above.
+   *
+   * k   is the order of the derivative of y to be computed. The
+   *     legal range for k is [0,qu] as described above.
+   *
+   * dky is the output derivative vector [(D_k)y](t).
+   *
+   * The return values for CVodeGetDky are defined below.
+   * Here is a brief description of each return value:
+   *
+   * CV_SUCCESS: CVodeGetDky succeeded.
+   *
+   * CV_BAD_K : k is not in the range 0, 1, ..., qu.
+   *
+   * CV_BAD_T : t is not in the interval [tn-hu,tn].
+   *
+   * CV_BAD_DKY : The dky argument was NULL.
+   *
+   * CV_MEM_NULL : The cvode_mem argument was NULL.
+   * -----------------------------------------------------------------
+   */
+
+  int CVodeGetDky(void *cvode_mem, realtype t, int k, N_Vector dky);
+
+  /*
+   * -----------------------------------------------------------------
+   * Integrator optional output extraction functions
+   * -----------------------------------------------------------------
+   * The following functions can be called to get optional outputs
+   * and statistics related to the main integrator.
+   * -----------------------------------------------------------------
+   * CVodeGetWorkSpace returns the CVODES real and integer workspaces
+   * CVodeGetNumSteps returns the cumulative number of internal
+   *                  steps taken by the solver
+   * CVodeGetNumRhsEvals returns the number of calls to the user's
+   *                  f function
+   * CVodeGetNumLinSolvSetups returns the number of calls made to
+   *                  the linear solver's setup routine
+   * CVodeGetNumErrTestFails returns the number of local error test
+   *                  failures that have occured
+   * CVodeGetLastOrder returns the order used during the last
+   *                  internal step
+   * CVodeGetCurrentOrder returns the order to be used on the next
+   *                  internal step
+   * CVodeGetNumStabLimOrderReds returns the number of order
+   *                  reductions due to stability limit detection
+   * CVodeGetActualInitStep returns the actual initial step size
+   *                  used by CVODES
+   * CVodeGetLastStep returns the step size for the last internal
+   *                  step
+   * CVodeGetCurrentStep returns the step size to be attempted on
+   *                  the next internal step
+   * CVodeGetCurrentTime returns the current internal time reached
+   *                  by the solver
+   * CVodeGetTolScaleFactor returns a suggested factor by which the
+   *                  user's tolerances should be scaled when too
+   *                  much accuracy has been requested for some
+   *                  internal step
+   * CVodeGetErrWeights returns the current error weight vector.
+   *                    The user must allocate space for eweight.
+   * CVodeGetEstLocalErrors returns the vector of estimated local
+   *                  errors. The user must allocate space for ele.
+   * CVodeGetNumGEvals returns the number of calls to the user's
+   *                  g function (for rootfinding)
+   * CVodeGetRootInfo returns the indices for which g_i was found to 
+   *                  have a root. The user must allocate space for 
+   *                  rootsfound. For i = 0 ... nrtfn-1, 
+   *                  rootsfound[i] = 1 if g_i has a root, and = 0 if not.
+   *
+   * CVodeGet* return values:
+   *   CV_SUCCESS   if succesful
+   *   CV_MEM_NULL  if the cvode memory was NULL
+   *   CV_NO_SLDET  if stability limit was not turned on
+   * -----------------------------------------------------------------
+   */
+
+  int CVodeGetWorkSpace(void *cvode_mem, long int *lenrw, long int *leniw);
+  int CVodeGetNumSteps(void *cvode_mem, long int *nsteps);
+  int CVodeGetNumRhsEvals(void *cvode_mem, long int *nfevals);
+  int CVodeGetNumLinSolvSetups(void *cvode_mem, long int *nlinsetups);
+  int CVodeGetNumErrTestFails(void *cvode_mem, long int *netfails);
+  int CVodeGetLastOrder(void *cvode_mem, int *qlast);
+  int CVodeGetCurrentOrder(void *cvode_mem, int *qcur);
+  int CVodeGetNumStabLimOrderReds(void *cvode_mem, long int *nslred);
+  int CVodeGetActualInitStep(void *cvode_mem, realtype *hinused);
+  int CVodeGetLastStep(void *cvode_mem, realtype *hlast);
+  int CVodeGetCurrentStep(void *cvode_mem, realtype *hcur);
+  int CVodeGetCurrentTime(void *cvode_mem, realtype *tcur);
+  int CVodeGetTolScaleFactor(void *cvode_mem, realtype *tolsfac);
+  int CVodeGetErrWeights(void *cvode_mem, N_Vector eweight);
+  int CVodeGetEstLocalErrors(void *cvode_mem, N_Vector ele);
+  int CVodeGetNumGEvals(void *cvode_mem, long int *ngevals);
+  int CVodeGetRootInfo(void *cvode_mem, int *rootsfound);
+
+  /*
+   * -----------------------------------------------------------------
+   * As a convenience, the following functions provides the
+   * optional outputs in one group.
+   * -----------------------------------------------------------------
+   */
+
+  int CVodeGetIntegratorStats(void *cvode_mem, long int *nsteps,
+                              long int *nfevals, long int *nlinsetups,
+                              long int *netfails, int *qlast,
+                              int *qcur, realtype *hinused, realtype *hlast,
+                              realtype *hcur, realtype *tcur);
+
+  /*
+   * -----------------------------------------------------------------
+   * Nonlinear solver optional output extraction functions
+   * -----------------------------------------------------------------
+   * The following functions can be called to get optional outputs
+   * and statistics related to the nonlinear solver.
+   * -----------------------------------------------------------------
+   * CVodeGetNumNonlinSolvIters returns the number of nonlinear
+   *                            solver iterations performed.
+   * CVodeGetNumNonlinSolvConvFails returns the number of nonlinear
+   *                                convergence failures.
+   * -----------------------------------------------------------------
+   */
+
+  int CVodeGetNumNonlinSolvIters(void *cvode_mem, long int *nniters);
+  int CVodeGetNumNonlinSolvConvFails(void *cvode_mem, long int *nncfails);
+
+  /*
+   * -----------------------------------------------------------------
+   * As a convenience, the following function provides the
+   * nonlinear solver optional outputs in a group.
+   * -----------------------------------------------------------------
+   */
+
+  int CVodeGetNonlinSolvStats(void *cvode_mem, long int *nniters,
+                              long int *nncfails);
+
+
+  /*
+   * -----------------------------------------------------------------
+   * The following function returns the name of the constant 
+   * associated with a CVODES return flag
+   * -----------------------------------------------------------------
+   */
+
+  char *CVodeGetReturnFlagName(int flag);
+
+  /*
+   * -----------------------------------------------------------------
+   * Quadrature integration solution extraction routines
+   * -----------------------------------------------------------------
+   * The following functions can be called to obtain the quadrature
+   * variables after a successful integration step.
+   * If quadratures were not computed, they return CV_NO_QUAD.
+   * -----------------------------------------------------------------
+   */
+
+  int CVodeGetQuad(void *cvode_mem, realtype t, N_Vector yQout);
+  int CVodeGetQuadDky(void *cvode_mem, realtype t, int k, N_Vector dky);
+
+  /*
+   * -----------------------------------------------------------------
+   * Quadrature integration optional output extraction routines
+   * -----------------------------------------------------------------
+   * The following functions can be called to get optional outputs
+   * and statistics related to the integration of quadratures.
+   * -----------------------------------------------------------------
+   * CVodeGetQuadNumRhsEvals returns the number of calls to the
+   *                         user function fQ defining the right hand
+   *                         side of the quadrature variables.
+   * CVodeGetQuadNumErrTestFails returns the number of local error
+   *                             test failures for quadrature variables.
+   * CVodeGetQuadErrWeights returns the vector of error weights for
+   *                        the quadrature variables. The user must
+   *                        allocate space for ewtQ.
+   * -----------------------------------------------------------------
+   */
+
+  int CVodeGetQuadNumRhsEvals(void *cvode_mem, long int *nfQevals);
+  int CVodeGetQuadNumErrTestFails(void *cvode_mem, long int *nQetfails);
+  int CVodeGetQuadErrWeights(void *cvode_mem, N_Vector eQweight);
+
+  /*
+   * -----------------------------------------------------------------
+   * As a convenience, the following function provides the
+   * optional outputs in a group.
+   * -----------------------------------------------------------------
+   */
+
+  int CVodeGetQuadStats(void *cvode_mem, long int *nfQevals,
+                        long int *nQetfails);
+
+  /*
+   * -----------------------------------------------------------------
+   * Forward sensitivity solution extraction routines
+   * -----------------------------------------------------------------
+   * CVodeGetSensDky1 computes the kth derivative of the is-th
+   * sensitivity (is=1, 2, ..., Ns) of the y function at time t,
+   * where tn-hu <= t <= tn, tn denotes the current internal time
+   * reached, and hu is the last internal step size successfully
+   * used by the solver. The user may request k=0, 1, ..., qu,
+   * where qu is the current order.
+   * The is-th sensitivity derivative vector is returned in dky.
+   * This vector must be allocated by the caller. It is only legal
+   * to call this function after a successful return from CVode
+   * with sensitivty computations enabled.
+   * Arguments have the same meaning as in CVodeDky.
+   *
+   * CVodeGetSensDky computes the k-th derivative of all
+   * sensitivities of the y function at time t. It repeatedly calls
+   * CVodeGetSensDky. The argument dkyA must be a pointer to
+   * N_Vector and must be allocated by the user to hold at least Ns
+   * vectors.
+   *
+   * CVodeGetSens1 returns the is-th sensitivity of the y function
+   * at the time t. The argument ySout must be an N_Vector and must
+   * be allocated by the user.
+   *
+   * CVodeGetSens returns sensitivities of the y function at
+   * the time t. The argument ySout must be a pointer to N_Vector
+   * and must be allocated by the user to hold at least Ns vectors.
+   *
+   * Return values are similar to those of CVodeDky. Additionally,
+   * CVodeSensDky can return CV_NO_SENS if sensitivities were
+   * not computed and CV_BAD_IS if is < 0 or is >= Ns.
+   * -----------------------------------------------------------------
+   */
+
+  int CVodeGetSens(void *cvode_mem, realtype t, N_Vector *ySout);
+  int CVodeGetSens1(void *cvode_mem, realtype t, int is, N_Vector ySout);
+  int CVodeGetSensDky(void *cvode_mem, realtype t, int k,
+                      N_Vector *dkyA);
+  int CVodeGetSensDky1(void *cvode_mem, realtype t, int k,
+                       int is, N_Vector dky);
+
+  /*
+   * -----------------------------------------------------------------
+   * Forward sensitivity optional output extraction routines
+   * -----------------------------------------------------------------
+   * The following functions can be called to get optional outputs
+   * and statistics related to the integration of sensitivities.
+   * -----------------------------------------------------------------
+   * CVodeGetNumSensRhsEvals returns the number of calls to the
+   *                         sensitivity right hand side routine.
+   * CVodeGetNumRhsEvalsSens returns the number of calls to the
+   *                         user f routine due to finite difference
+   *                         evaluations of the sensitivity equations.
+   * CVodeGetNumSensErrTestFails returns the number of local error
+   *                             test failures for sensitivity variables.
+   * CVodeGetNumSensLinSolvSetups returns the number of calls made
+   *                              to the linear solver's setup routine
+   *                              due to sensitivity computations.
+   * CVodeGetSensErrWeights returns the sensitivity error weight
+   *                        vectors. The user need not allocate space
+   *                        for ewtS.
+   * -----------------------------------------------------------------
+   */
+
+  int CVodeGetNumSensRhsEvals(void *cvode_mem, long int *nfSevals);
+  int CVodeGetNumRhsEvalsSens(void *cvode_mem, long int *nfevalsS);
+  int CVodeGetNumSensErrTestFails(void *cvode_mem, long int *nSetfails);
+  int CVodeGetNumSensLinSolvSetups(void *cvode_mem, long int *nlinsetupsS);
+  int CVodeGetSensErrWeights(void *cvode_mem, N_Vector_S eSweight);
+
+  /*
+   * -----------------------------------------------------------------
+   * As a convenience, the following function provides the
+   * optional outputs in a group.
+   * -----------------------------------------------------------------
+   */
+
+  int CVodeGetSensStats(void *cvode_mem, long int *nfSevals, long int *nfevalsS,
+                        long int *nSetfails, long int *nlinsetupsS);
+
+  /*
+   * -----------------------------------------------------------------
+   * Sensitivity nonlinear solver optional output extraction
+   * -----------------------------------------------------------------
+   * The following functions can be called to get optional outputs
+   * and statistics related to the sensitivity nonlinear solver.
+   * -----------------------------------------------------------------
+   * CVodeGetNumSensNonlinSolvIters returns the total number of
+   *                                nonlinear iterations for sensitivity
+   *                                variables.
+   * CVodeGetNumSensNonlinSolvConvFails returns the total number of
+   *                                    nonlinear convergence failures
+   *                                    for sensitivity variables
+   * CVodeGetNumStgrSensNonlinSolvIters returns a vector of Ns
+   *                                    nonlinear iteration counters
+   *                                    for sensitivity variables
+   *                                    in the CV_STAGGERED1 method.
+   * CVodeGetNumStgrSensNonlinSolvConvFails returns a vector of Ns
+   *                                        nonlinear solver convergence
+   *                                        failure counters for
+   *                                        sensitivity variables in
+   *                                        the CV_STAGGERED1 method.
+   * -----------------------------------------------------------------
+   */
+
+  int CVodeGetNumSensNonlinSolvIters(void *cvode_mem, long int *nSniters);
+  int CVodeGetNumSensNonlinSolvConvFails(void *cvode_mem, long int *nSncfails);
+  int CVodeGetNumStgrSensNonlinSolvIters(void *cvode_mem, long int *nSTGR1niters);
+  int CVodeGetNumStgrSensNonlinSolvConvFails(void *cvode_mem, 
+                                             long int *nSTGR1ncfails);
+
+  /*
+   * -----------------------------------------------------------------
+   * As a convenience, the following function provides the      
+   * optional outputs in groups.                                    
+   * -----------------------------------------------------------------
+   */
+
+  int CVodeGetSensNonlinSolvStats(void *cvode_mem, long int *nSniters,
+                                  long int *nSncfails);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVodeFree
+   * -----------------------------------------------------------------
+   * CVodeFree frees the problem memory cvode_mem allocated by
+   * CVodeMalloc.  Its only argument is the pointer cvode_mem
+   * returned by CVodeCreate.
+   * -----------------------------------------------------------------
+   */
+
+  void CVodeFree(void **cvode_mem);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVodeQuadFree
+   * -----------------------------------------------------------------
+   * CVodeQuadFree frees the problem memory in cvode_mem allocated
+   * for quadrature integration. Its only argument is the pointer
+   * cvode_mem returned by CVodeCreate.
+   * -----------------------------------------------------------------
+   */
+
+  void CVodeQuadFree(void *cvode_mem);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVodeSensFree
+   * -----------------------------------------------------------------
+   * CVodeSensFree frees the problem memory in cvode_mem allocated
+   * for sensitivity analysis. Its only argument is the pointer
+   * cvode_mem returned by CVodeCreate.
+   * -----------------------------------------------------------------
+   */
+
+  void CVodeSensFree(void *cvode_mem);
+
+  /*
+   * -----------------------------------------------------------------
+   * CVadjMalloc
+   * -----------------------------------------------------------------
+   * CVadjMalloc specifies some parameters for the adjoint problem and
+   * allocates space for the global CVODEA memory structure.
+   * -----------------------------------------------------------------
+   */
+  
+  void *CVadjMalloc(void *cvode_mem, long int steps, int interp);
+
+  /*
+   * -----------------------------------------------------------------
+   * CVadjSetInterpType
+   * -----------------------------------------------------------------
+   * Changes the interpolation type. 
+   * Must be called only after CVadjMalloc
+   * -----------------------------------------------------------------
+   */
+  
+  int CVadjSetInterpType(void *cvadj_mem, int interp);
+
+  /*
+   * -----------------------------------------------------------------
+   * CVodeF
+   * -----------------------------------------------------------------
+   * CVodeF integrates towards tout and returns solution into yout.
+   * In the same time, it stores check point data every 'steps'.
+   *
+   * CVodeF can be called repeatedly by the user.
+   *
+   * ncheckPtr points to the number of check points stored so far.
+   *
+   * Return values:
+   *    CV_SUCCESS
+   *    CVADJ_MEM_FAIL
+   *    any CVode return value
+   * -----------------------------------------------------------------
+   */
+
+  int CVodeF(void *cvadj_mem, realtype tout, N_Vector yout,
+             realtype *tret, int itask, int *ncheckPtr);
+
+  /*
+   * -----------------------------------------------------------------
+   * Interfaces to CVODES functions for setting-up the
+   *  backward integration
+   * -----------------------------------------------------------------
+   * CVodeCreateB, CVodeMallocB, CVodeSet*B
+   *    These functions are just wrappers around the corresponding
+   *    functions in cvodes.h, with some particularizations for the
+   *    backward integration.
+   * -----------------------------------------------------------------
+   * CVodeSetQuad*B, CVodeQuadMallocB, CVodeQuadReInitB
+   * -----------------------------------------------------------------
+   */
+
+  int CVodeCreateB(void *cvadj_mem, int lmmB, int iterB);
+
+  int CVodeMallocB(void *cvadj_mem, CVRhsFnB fB,
+                   realtype tB0, N_Vector yB0,
+                   int itolB, realtype reltolB, void *abstolB);
+  
+  int CVodeSetErrHandlerFnB(void *cvadj_mem, CVErrHandlerFn ehfunB, void *eh_dataB);
+  int CVodeSetErrFileB(void *cvadj_mem, FILE *errfpB);
+  int CVodeSetIterTypeB(void *cvadj_mem, int iterB);
+  int CVodeSetFdataB(void *cvadj_mem, void *f_dataB);
+  int CVodeSetMaxOrdB(void *cvadj_mem, int maxordB);
+  int CVodeSetMaxNumStepsB(void *cvadj_mem, long int mxstepsB);
+  int CVodeSetStabLimDetB(void *cvadj_mem, booleantype stldetB);
+  int CVodeSetInitStepB(void *cvadj_mem, realtype hinB);
+  int CVodeSetMinStepB(void *cvadj_mem, realtype hminB);
+  int CVodeSetMaxStepB(void *cvadj_mem, realtype hmaxB);
+  
+  int CVodeReInitB(void *cvadj_mem, CVRhsFnB fB,
+                   realtype tB0, N_Vector yB0,
+                   int itolB, realtype reltolB, void *abstolB);
+    
+  int CVodeSetQuadFdataB(void *cvadj_mem, void *fQ_dataB);
+  int CVodeSetQuadErrConB(void *cvadj_mem, booleantype errconQB,
+                          int itolQB, realtype reltolQB, void *abstolQB);
+  int CVodeQuadMallocB(void *cvadj_mem, CVQuadRhsFnB fQB, N_Vector yQB0);
+  int CVodeQuadReInitB(void *cvadj_mem, CVQuadRhsFnB fQB, N_Vector yQB0);
+    
+  /*
+   * -----------------------------------------------------------------
+   * CVodeB
+   * -----------------------------------------------------------------
+   * CVodeB performs the backward integration from tfinal to
+   * tinitial through a sequence of forward-backward runs in
+   * between consecutive check points. It returns the values of
+   * the adjoint variables and any existing quadrature variables
+   * at tinitial.
+   * -----------------------------------------------------------------
+   */
+  
+  int CVodeB(void *cvadj_mem, realtype tBout, N_Vector yBout,
+             realtype *tBret, int itaskB);
+  
+  /*
+   * -----------------------------------------------------------------
+   * CVodeGetQuadB
+   * -----------------------------------------------------------------
+   * CVodeGetQuadB extracts values for quadrature variables in
+   * the N_Vector qB.
+   * -----------------------------------------------------------------
+   */
+  
+  int CVodeGetQuadB(void *cvadj_mem, N_Vector qB);
+  
+  /*
+   * -----------------------------------------------------------------
+   * CVadjFree
+   * -----------------------------------------------------------------
+   * CVadjFree frees the memory allocated by CVadjMalloc.
+   * -----------------------------------------------------------------
+   */
+  
+  void CVadjFree(void **cvadj_mem);
+  
+  /*
+   * -----------------------------------------------------------------
+   * CVadjGetCVodeBmem
+   * -----------------------------------------------------------------
+   * CVadjGetCVodeBmem returns a (void *) pointer to the CVODES
+   * memory allocated for the backward problem. This pointer can
+   * then be used to call any of the CVodeGet* CVODES routines to
+   * extract optional output for the backward integration phase.
+   * -----------------------------------------------------------------
+   */
+  
+  void *CVadjGetCVodeBmem(void *cvadj_mem);
+
+  /*
+   * -----------------------------------------------------------------
+   * The following function returns the name of the constant 
+   * associated with a CVODEA-specific return flag
+   * -----------------------------------------------------------------
+   */
+  
+  char *CVadjGetReturnFlagName(int flag);
+
+
+  /*
+   * -----------------------------------------------------------------
+   * CVadjGetY
+   *    Returns the interpolated forward solution at time t. This
+   *    function is a wrapper around the interpType-dependent internal
+   *    function.
+   *    The calling function must allocate space for y.
+   * -----------------------------------------------------------------
+   */
+
+  int CVadjGetY(void *cvadj_mem, realtype t, N_Vector y);
+
+  /*
+   * -----------------------------------------------------------------
+   * CVadjGetCheckPointsInfo
+   *    Loads an array of nckpnts structures of type CVadjCheckPointRec.
+   *    The user must allocate space for ckpnt (ncheck+1).
+   * -----------------------------------------------------------------
+   */
+
+  typedef struct {
+    void *my_addr;
+    void *next_addr;
+    realtype t0;
+    realtype t1;
+    long int nstep;
+    int order;
+    realtype step;
+  } CVadjCheckPointRec;
+
+  int CVadjGetCheckPointsInfo(void *cvadj_mem, CVadjCheckPointRec *ckpnt);
+
+  /*
+   * -----------------------------------------------------------------
+   * CVadjGetDataPointHermite
+   *    Returns the 2 vectors stored for cubic Hermite interpolation 
+   *    at the data point 'which'. The user must allocate space for
+   *    y and yd. Returns CVADJ_MEM_NULL if cvadj_mem is NULL.
+   *    Returns CV_ILL_INPUT if interpType != CV_HERMITE.
+   * CVadjGetDataPointPolynomial
+   *    Returns the vector stored for polynomial interpolation 
+   *    at the data point 'which'. The user must allocate space for
+   *    y. Returns CVADJ_MEM_NULL if cvadj_mem is NULL.
+   *    Returns CV_ILL_INPUT if interpType != CV_POLYNOMIAL.
+   * -----------------------------------------------------------------
+   */
+
+  int CVadjGetDataPointHermite(void *cvadj_mem, long int which,
+                               realtype *t, N_Vector y, N_Vector yd);
+  
+  int CVadjGetDataPointPolynomial(void *cvadj_mem, long int which,
+                                  realtype *t, int *order, N_Vector y);
+
+  /* 
+   * ===============================================================
+   * DEVELOPMENT USER-CALLABLE FUNCTIONS
+   * ===============================================================
+   */
+
+  /*
+   * -----------------------------------------------------------------
+   * CVadjGetCurrentCheckPoint
+   *    Returns the address of the 'active' check point.
+   * -----------------------------------------------------------------
+   */
+
+  int CVadjGetCurrentCheckPoint(void *cvadj_mem, void **addr);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes_band.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes_band.h
new file mode 100644
index 0000000000000000000000000000000000000000..8d441f996a84117747de9e76545d5c7a974ab131
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes_band.h
@@ -0,0 +1,294 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2005, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the header file for the CVODES band linear solver, CVBAND.
+ *
+ *
+ * Part I contains type definitions and function prototypes for using
+ * CVBAND on forward problems (IVP integration and/or FSA)
+ *
+ * Part II contains type definitions and function prototypes for using
+ * CVBAND on adjoint (backward) problems
+ * -----------------------------------------------------------------
+ */
+
+#ifndef _CVSBAND_H
+#define _CVSBAND_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#include <sundials/sundials_band.h>
+#include <sundials/sundials_nvector.h>
+
+  /*
+   * -----------------------------------------------------------------
+   * CVBAND solver constants
+   * -----------------------------------------------------------------
+   * CVB_MSBJ : maximum number of steps between band Jacobian
+   *            evaluations
+   *
+   * CVB_DGMAX : maximum change in gamma between band Jacobian
+   *             evaluations
+   * -----------------------------------------------------------------
+   */
+
+#define CVB_MSBJ  50
+#define CVB_DGMAX RCONST(0.2)
+
+  /*
+   * -----------------------------------------------------------------
+   * CVBAND return values
+   * -----------------------------------------------------------------
+   */
+
+#define CVBAND_SUCCESS           0
+#define CVBAND_MEM_NULL         -1
+#define CVBAND_LMEM_NULL        -2
+#define CVBAND_ILL_INPUT        -3
+#define CVBAND_MEM_FAIL         -4
+
+  /* Additional last_flag values */
+
+#define CVBAND_JACFUNC_UNRECVR  -5
+#define CVBAND_JACFUNC_RECVR    -6
+
+  /* Return values for adjoint module */
+
+#define CVBAND_ADJMEM_NULL      -101
+#define CVBAND_LMEMB_NULL       -102
+
+  /* 
+   * -----------------------------------------------------------------
+   * PART I - forward problems
+   * -----------------------------------------------------------------
+   */
+
+
+  /*
+   * -----------------------------------------------------------------
+   * Type : CVBandJacFn
+   * -----------------------------------------------------------------
+   * A band Jacobian approximation function Jac must have the
+   * prototype given below. Its parameters are:
+   *
+   * N is the length of all vector arguments.
+   *
+   * mupper is the upper half-bandwidth of the approximate banded
+   * Jacobian. This parameter is the same as the mupper parameter
+   * passed by the user to the CVBand function.
+   *
+   * mlower is the lower half-bandwidth of the approximate banded
+   * Jacobian. This parameter is the same as the mlower parameter
+   * passed by the user to the CVBand function.
+   *
+   * J is the band matrix (of type BandMat) that will be loaded
+   * by a CVBandJacFn with an approximation to the Jacobian matrix
+   * J = (df_i/dy_j) at the point (t,y).
+   * J is preset to zero, so only the nonzero elements need to be
+   * loaded. Three efficient ways to load J are:
+   *
+   * (1) (with macros - no explicit data structure references)
+   *    for (j=0; j < n; j++) {
+   *       col_j = BAND_COL(J,j);
+   *       for (i=j-mupper; i <= j+mlower; i++) {
+   *         generate J_ij = the (i,j)th Jacobian element
+   *         BAND_COL_ELEM(col_j,i,j) = J_ij;
+   *       }
+   *     }
+   *
+   * (2) (with BAND_COL macro, but without BAND_COL_ELEM macro)
+   *    for (j=0; j < n; j++) {
+   *       col_j = BAND_COL(J,j);
+   *       for (k=-mupper; k <= mlower; k++) {
+   *         generate J_ij = the (i,j)th Jacobian element, i=j+k
+   *         col_j[k] = J_ij;
+   *       }
+   *     }
+   *
+   * (3) (without macros - explicit data structure references)
+   *     offset = J->smu;
+   *     for (j=0; j < n; j++) {
+   *       col_j = ((J->data)[j])+offset;
+   *       for (k=-mupper; k <= mlower; k++) {
+   *         generate J_ij = the (i,j)th Jacobian element, i=j+k
+   *         col_j[k] = J_ij;
+   *       }
+   *     }
+   * Caution: J->smu is generally NOT the same as mupper.
+   *
+   * The BAND_ELEM(A,i,j) macro is appropriate for use in small
+   * problems in which efficiency of access is NOT a major concern.
+   *
+   * t is the current value of the independent variable.
+   *
+   * y is the current value of the dependent variable vector,
+   *      namely the predicted value of y(t).
+   *
+   * fy is the vector f(t,y).
+   *
+   * jac_data is a pointer to user data - the same as the jac_data
+   *          parameter passed to CVBand.
+   *
+   * NOTE: If the user's Jacobian routine needs other quantities,
+   *     they are accessible as follows: hcur (the current stepsize)
+   *     and ewt (the error weight vector) are accessible through
+   *     CVodeGetCurrentStep and CVodeGetErrWeights, respectively
+   *     (see cvode.h). The unit roundoff is available as
+   *     UNIT_ROUNDOFF defined in sundials_types.h
+   *
+   * tmp1, tmp2, and tmp3 are pointers to memory allocated for
+   * vectors of length N which can be used by a CVBandJacFn
+   * as temporary storage or work space.
+   *
+   * A CVBandJacFn should return 0 if successful, a positive value if 
+   * a recoverable error occurred, and a negative value if an 
+   * unrecoverable error occurred.
+   * -----------------------------------------------------------------
+   */
+
+  typedef int (*CVBandJacFn)(long int N, long int mupper, long int mlower,
+                             BandMat J, realtype t,
+                             N_Vector y, N_Vector fy, void *jac_data,
+                             N_Vector tmp1, N_Vector tmp2, N_Vector tmp3);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVBand
+   * -----------------------------------------------------------------
+   * A call to the CVBand function links the main CVODE integrator
+   * with the CVBAND linear solver.
+   *
+   * cvode_mem is the pointer to the integrator memory returned by
+   *           CVodeCreate.
+   *
+   * N is the size of the ODE system.
+   *
+   * mupper is the upper bandwidth of the band Jacobian
+   *        approximation.
+   *
+   * mlower is the lower bandwidth of the band Jacobian
+   *        approximation.
+   *
+   * The return value of CVBand is one of:
+   *    CVBAND_SUCCESS   if successful
+   *    CVBAND_MEM_NULL  if the cvode memory was NULL
+   *    CVBAND_MEM_FAIL  if there was a memory allocation failure
+   *    CVBAND_ILL_INPUT if a required vector operation is missing or
+   *                     if a bandwidth has an illegal value.
+   * -----------------------------------------------------------------
+   */
+
+  int CVBand(void *cvode_mem, long int N,
+             long int mupper, long int mlower);
+
+  /*
+   * -----------------------------------------------------------------
+   * Optional inputs to the CVBAND linear solver
+   * -----------------------------------------------------------------
+   *
+   * CVBandSetJacFn specifies the band Jacobian approximation
+   *                routine to be used. A user-supplied bjac routine
+   *                must be of type CVBandJacFn. By default, a difference
+   *                quotient routine CVBandDQJac, supplied with this
+   *                solver is used.
+   *                It also specifies a pointer to user data which is
+   *                passed to the bjac routine every time it is called.
+   *
+   * The return value of CVBandSet* is one of:
+   *    CVBAND_SUCCESS   if successful
+   *    CVBAND_MEM_NULL  if the cvode memory was NULL
+   *    CVBAND_LMEM_NULL if the cvband memory was NULL
+   * -----------------------------------------------------------------
+   */
+
+  int CVBandSetJacFn(void *cvode_mem, CVBandJacFn bjac, void *jac_data);
+
+  /*
+   * -----------------------------------------------------------------
+   * Optional outputs from the CVBAND linear solver
+   * -----------------------------------------------------------------
+   *
+   * CVBandGetWorkSpace returns the real and integer workspace used
+   *                    by CVBAND.
+   * CVBandGetNumJacEvals returns the number of calls made to the
+   *                      Jacobian evaluation routine bjac.
+   * CVBandGetNumRhsEvals returns the number of calls to the user
+   *                      f routine due to finite difference Jacobian
+   *                      evaluation.
+   * CVBandGetLastFlag returns the last error flag set by any of
+   *                   the CVBAND interface functions.
+   *
+   * The return value of CVBandGet* is one of:
+   *    CVBAND_SUCCESS   if successful
+   *    CVBAND_MEM_NULL  if the cvode memory was NULL
+   *    CVBAND_LMEM_NULL if the cvband memory was NULL
+   * -----------------------------------------------------------------
+   */
+
+  int CVBandGetWorkSpace(void *cvode_mem, long int *lenrwLS, long int *leniwLS);
+  int CVBandGetNumJacEvals(void *cvode_mem, long int *njevals);
+  int CVBandGetNumRhsEvals(void *cvode_mem, long int *nfevalsLS);
+  int CVBandGetLastFlag(void *cvode_mem, int *flag);
+
+  /*
+   * -----------------------------------------------------------------
+   * The following function returns the name of the constant 
+   * associated with a CVBAND return flag
+   * -----------------------------------------------------------------
+   */
+
+  char *CVBandGetReturnFlagName(int flag);
+
+  /* 
+   * -----------------------------------------------------------------
+   * PART II - backward problems
+   * -----------------------------------------------------------------
+   */
+
+  /*
+   * -----------------------------------------------------------------
+   * Type : CVBandJacFnB
+   * -----------------------------------------------------------------
+   * A band Jacobian approximation function JacB for the adjoint 
+   * (backward) problem must have the prototype given below. 
+   * -----------------------------------------------------------------
+   */
+
+  typedef int (*CVBandJacFnB)(long int nB, long int mupperB,
+                              long int mlowerB, BandMat JB,
+                              realtype t, N_Vector y,
+                              N_Vector yB, N_Vector fyB,
+                              void *jac_dataB, N_Vector tmp1B,
+                              N_Vector tmp2B, N_Vector tmp3B);
+  
+  /*
+   * -----------------------------------------------------------------
+   * Functions: CVBandB, CVBandSet*B
+   * -----------------------------------------------------------------
+   * CVBandB links the main CVODE integrator with the CVBAND
+   * linear solver for the backward integration.
+   * -----------------------------------------------------------------
+   */
+
+  int CVBandB(void *cvadj_mem, long int nB,
+              long int mupperB, long int mlowerB);
+  
+  int CVBandSetJacFnB(void *cvadj_mem, CVBandJacFnB bjacB, void *jac_dataB);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes_bandpre.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes_bandpre.h
new file mode 100644
index 0000000000000000000000000000000000000000..d69a6f1502dcf465c239fd1fb9629db30e7eb5de
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes_bandpre.h
@@ -0,0 +1,300 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2005, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the header file for the CVBANDPRE module, which
+ * provides a banded difference quotient Jacobian-based
+ * preconditioner and solver routines for use with CVSPGMR,
+ * CVSPBCG, or CVSPTFQMR.
+ *
+ *
+ * Part I contains type definitions and function prototypes for using
+ * CVBANDPRE on forward problems (IVP integration and/or FSA)
+ *
+ * Part II contains type definitions and function prototypes for using
+ * CVBANDPRE on adjopint (backward) problems
+ * -----------------------------------------------------------------
+ */
+
+#ifndef _CVSBANDPRE_H
+#define _CVSBANDPRE_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+  /* CVBANDPRE return values */
+
+#define CVBANDPRE_SUCCESS           0
+#define CVBANDPRE_PDATA_NULL      -11
+#define CVBANDPRE_RHSFUNC_UNRECVR -12
+
+#define CVBANDPRE_ADJMEM_NULL     -111
+#define CVBANDPRE_MEM_FAIL        -112
+
+#include <sundials/sundials_nvector.h>
+
+  /* 
+   * -----------------------------------------------------------------
+   * PART I - forward problems
+   * -----------------------------------------------------------------
+   *
+   * Summary:
+   * These routines provide a band matrix preconditioner based on
+   * difference quotients of the ODE right-hand side function f.
+   * The user supplies parameters
+   *   mu = upper half-bandwidth (number of super-diagonals)
+   *   ml = lower half-bandwidth (number of sub-diagonals)
+   * The routines generate a band matrix of bandwidth ml + mu + 1
+   * and use this to form a preconditioner for use with the Krylov
+   * linear solver in CVSP*. Although this matrix is intended to
+   * approximate the Jacobian df/dy, it may be a very crude
+   * approximation. The true Jacobian need not be banded, or its
+   * true bandwith may be larger than ml + mu + 1, as long as the
+   * banded approximation generated here is sufficiently accurate
+   * to speed convergence as a preconditioner.
+   *
+   * Usage:
+   *   The following is a summary of the usage of this module.
+   *   Details of the calls to CVodeCreate, CVodeMalloc, CVSp*,
+   *   and CVode are available in the User Guide.
+   *   To use these routines, the sequence of calls in the user
+   *   main program should be as follows:
+   *
+   *   #include <cvodes/cvodes_bandpre.h>
+   *   #include <nvector_serial.h>
+   *   ...
+   *   void *bp_data;
+   *   ...
+   *   Set y0
+   *   ...
+   *   cvode_mem = CVodeCreate(...);
+   *   ier = CVodeMalloc(...);
+   *   ...
+   *   bp_data = CVBandPrecAlloc(cvode_mem, N, mu, ml);
+   *   ...
+   *   flag = CVBPSptfqmr(cvode_mem, pretype, maxl, bp_data);
+   *     -or-
+   *   flag = CVBPSpgmr(cvode_mem, pretype, maxl, bp_data);
+   *     -or-
+   *   flag = CVBPSpbcg(cvode_mem, pretype, maxl, bp_data);
+   *   ...
+   *   flag = CVode(...);
+   *   ...
+   *   CVBandPrecFree(&bp_data);
+   *   ...
+   *   Free y0
+   *   ...
+   *   CVodeFree(cvode_mem);
+   *
+   * Notes:
+   * (1) Include this file for the CVBandPrecData type definition.
+   * (2) In the CVBandPrecAlloc call, the arguments N is the same
+   *     as in the call to CVodeMalloc.
+   * (3) In the CVBPSp* call, the user is free to specify
+   *     the input pretype and the optional input maxl. The last
+   *     argument must be the pointer returned by CVBandPrecAlloc.
+   * -----------------------------------------------------------------
+   */
+
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVBandPrecAlloc
+   * -----------------------------------------------------------------
+   * CVBandPrecAlloc allocates and initializes a CVBandPrecData
+   * structure to be passed to CVSp* (and subsequently used
+   * by CVBandPrecSetup and CVBandPrecSolve).
+   *
+   * The parameters of CVBandPrecAlloc are as follows:
+   *
+   * cvode_mem is the pointer to CVODE memory returned by CVodeCreate.
+   *
+   * N is the problem size.
+   *
+   * mu is the upper half bandwidth.
+   *
+   * ml is the lower half bandwidth.
+   *
+   * CVBandPrecAlloc returns the storage pointer of type
+   * CVBandPrecData, or NULL if the request for storage cannot be
+   * satisfied.
+   *
+   * NOTE: The band preconditioner assumes a serial implementation
+   *       of the NVECTOR package. Therefore, CVBandPrecAlloc will
+   *       first test for a compatible N_Vector internal
+   *       representation by checking for required functions.
+   * -----------------------------------------------------------------
+   */
+
+  void *CVBandPrecAlloc(void *cvode_mem, long int N,
+                        long int mu, long int ml);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVBPSptfqmr
+   * -----------------------------------------------------------------
+   * CVBPSptfqmr links the CVBANDPPRE preconditioner to the CVSPTFQMR
+   * linear solver. It performs the following actions:
+   *  1) Calls the CVSPTFQMR specification routine and attaches the
+   *     CVSPTFQMR linear solver to the integrator memory;
+   *  2) Sets the preconditioner data structure for CVSPTFQMR
+   *  3) Sets the preconditioner setup routine for CVSPTFQMR
+   *  4) Sets the preconditioner solve routine for CVSPTFQMR
+   *
+   * Its first 3 arguments are the same as for CVSptfqmr (see
+   * cvsptfqmr.h). The last argument is the pointer to the CVBANDPPRE
+   * memory block returned by CVBandPrecAlloc. Note that the user need
+   * not call CVSptfqmr.
+   *
+   * Possible return values are:
+   *    CVSPILS_SUCCESS      if successful
+   *    CVSPILS_MEM_NULL     if the cvode memory was NULL
+   *    CVSPILS_LMEM_NULL    if the cvsptfqmr memory was NULL
+   *    CVSPILS_MEM_FAIL     if there was a memory allocation failure
+   *    CVSPILS_ILL_INPUT    if a required vector operation is missing
+   *    CVBANDPRE_PDATA_NULL if the bp_data was NULL
+   * -----------------------------------------------------------------
+   */
+
+  int CVBPSptfqmr(void *cvode_mem, int pretype, int maxl, void *p_data);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVBPSpbcg
+   * -----------------------------------------------------------------
+   * CVBPSpbcg links the CVBANDPPRE preconditioner to the CVSPBCG
+   * linear solver. It performs the following actions:
+   *  1) Calls the CVSPBCG specification routine and attaches the
+   *     CVSPBCG linear solver to the integrator memory;
+   *  2) Sets the preconditioner data structure for CVSPBCG
+   *  3) Sets the preconditioner setup routine for CVSPBCG
+   *  4) Sets the preconditioner solve routine for CVSPBCG
+   *
+   * Its first 3 arguments are the same as for CVSpbcg (see
+   * cvspbcgs.h). The last argument is the pointer to the CVBANDPPRE
+   * memory block returned by CVBandPrecAlloc. Note that the user need
+   * not call CVSpbcg.
+   *
+   * Possible return values are:
+   *    CVSPILS_SUCCESS       if successful
+   *    CVSPILS_MEM_NULL      if the cvode memory was NULL
+   *    CVSPILS_LMEM_NULL     if the cvspbcg memory was NULL
+   *    CVSPILS_MEM_FAIL      if there was a memory allocation failure
+   *    CVSPILS_ILL_INPUT     if a required vector operation is missing
+   *    CVBANDPRE_PDATA_NULL  if the bp_data was NULL
+   * -----------------------------------------------------------------
+   */
+
+  int CVBPSpbcg(void *cvode_mem, int pretype, int maxl, void *p_data);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVBPSpgmr
+   * -----------------------------------------------------------------
+   * CVBPSpgmr links the CVBANDPPRE preconditioner to the CVSPGMR
+   * linear solver. It performs the following actions:
+   *  1) Calls the CVSPGMR specification routine and attaches the
+   *     CVSPGMR linear solver to the integrator memory;
+   *  2) Sets the preconditioner data structure for CVSPGMR
+   *  3) Sets the preconditioner setup routine for CVSPGMR
+   *  4) Sets the preconditioner solve routine for CVSPGMR
+   *
+   * Its first 3 arguments are the same as for CVSpgmr (see
+   * cvspgmr.h). The last argument is the pointer to the CVBANDPPRE
+   * memory block returned by CVBandPrecAlloc. Note that the user need
+   * not call CVSpgmr.
+   *
+   * Possible return values are:
+   *    CVSPILS_SUCCESS       if successful
+   *    CVSPILS_MEM_NULL      if the cvode memory was NULL
+   *    CVSPILS_LMEM_NULL     if the cvspgmr memory was NULL
+   *    CVSPILS_MEM_FAIL      if there was a memory allocation failure
+   *    CVSPILS_ILL_INPUT     if a required vector operation is missing
+   *    CVBANDPRE_PDATA_NULL  if the bp_data was NULL
+   * -----------------------------------------------------------------
+   */
+
+  int CVBPSpgmr(void *cvode_mem, int pretype, int maxl, void *p_data);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVBandPrecFree
+   * -----------------------------------------------------------------
+   * CVBandPrecFree frees the memory allocated by CVBandPrecAlloc
+   * in the argument bp_data.
+   * -----------------------------------------------------------------
+   */
+
+  void CVBandPrecFree(void **bp_data);
+
+  /*
+   * -----------------------------------------------------------------
+   * Optional output functions : CVBandPrecGet*
+   * -----------------------------------------------------------------
+   * CVBandPrecGetWorkSpace returns the real and integer work space used
+   *                        by CVBANDPRE.
+   * CVBandPrecGetNumRhsEvals returns the number of calls made from
+   *                          CVBANDPRE to the user's right-hand side
+   *                          routine f.
+   *
+   * The return value of CVBandPrecGet* is one of:
+   *    CVBANDPRE_SUCCESS    if successful
+   *    CVBANDPRE_PDATA_NULL if the bp_data memory was NULL
+   * -----------------------------------------------------------------
+   */
+
+  int CVBandPrecGetWorkSpace(void *bp_data, long int *lenrwLS, long int *leniwLS);
+  int CVBandPrecGetNumRhsEvals(void *bp_data, long int *nfevalsBP);
+
+  /*
+   * -----------------------------------------------------------------
+   * The following function returns the name of the constant 
+   * associated with a CVBANDPRE return flag
+   * -----------------------------------------------------------------
+   */
+  
+  char *CVBandPrecGetReturnFlagName(int flag);
+
+  /* 
+   * -----------------------------------------------------------------
+   * PART II - backward problems
+   * -----------------------------------------------------------------
+   */
+
+  /*
+   * -----------------------------------------------------------------
+   * Functions: CVBandPrecAllocB, CVBPSp*B
+   * -----------------------------------------------------------------
+   * Interface functions for the CVBANDPRE preconditioner to be used
+   * on the backward phase.
+   *
+   * CVBandPrecAllocB interfaces to the CVBANDPRE preconditioner
+   * for the backward integration. The pointer to the structure
+   * returned by this routine should then be used in the call to
+   * CVBPSp*B which interfaces to CVBPSPGMR/CVBPSPBCG/CVSPTFQMR.
+   * -----------------------------------------------------------------
+   */
+
+  int CVBandPrecAllocB(void *cvadj_mem, long int nB,
+                       long int muB, long int mlB);
+
+  int CVBPSptfqmrB(void *cvadj_mem, int pretypeB, int maxlB);
+  int CVBPSpbcgB(void *cvadj_mem, int pretypeB, int maxlB);
+  int CVBPSpgmrB(void *cvadj_mem, int pretypeB, int maxlB);
+
+  void CVBandPrecFreeB(void *cvadj_mem);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes_bbdpre.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes_bbdpre.h
new file mode 100644
index 0000000000000000000000000000000000000000..042281ec76fed636d0b3caffd96e6aef93b5740f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes_bbdpre.h
@@ -0,0 +1,448 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2005, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the header file for the CVBBDPRE module, for a
+ * band-block-diagonal preconditioner, i.e. a block-diagonal
+ * matrix with banded blocks, for use with CVSPGMR/CVSPBCG/CVSPTFQMR, 
+ * and the parallel implementation of the NVECTOR module.
+ *
+ *
+ * Part I contains type definitions and function prototypes for using
+ * CVBBDPRE on forward problems (IVP integration and/or FSA)
+ *
+ * Part II contains type definitions and function prototypes for using
+ * CVBBDPRE on adjopint (backward) problems
+ * -----------------------------------------------------------------
+ */
+
+#ifndef _CVSBBDPRE_H
+#define _CVSBBDPRE_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#include <sundials/sundials_nvector.h>
+
+  /* CVBBDPRE return values */
+
+#define CVBBDPRE_SUCCESS            0
+#define CVBBDPRE_PDATA_NULL       -11
+#define CVBBDPRE_FUNC_UNRECVR     -12
+
+#define CVBBDPRE_ADJMEM_NULL      -111
+#define CVBBDPRE_PDATAB_NULL      -112
+#define CVBBDPRE_MEM_FAIL         -113
+
+
+  /* 
+   * -----------------------------------------------------------------
+   * PART I - forward problems
+   * -----------------------------------------------------------------
+   *
+   * Summary:
+   *
+   * These routines provide a preconditioner matrix that is
+   * block-diagonal with banded blocks. The blocking corresponds
+   * to the distribution of the dependent variable vector y among
+   * the processors. Each preconditioner block is generated from
+   * the Jacobian of the local part (on the current processor) of a
+   * given function g(t,y) approximating f(t,y). The blocks are
+   * generated by a difference quotient scheme on each processor
+   * independently. This scheme utilizes an assumed banded
+   * structure with given half-bandwidths, mudq and mldq.
+   * However, the banded Jacobian block kept by the scheme has
+   * half-bandwiths mukeep and mlkeep, which may be smaller.
+   *
+   * The user's calling program should have the following form:
+   *
+   *   #include <cvodes/cvodes_bbdpre.h>
+   *   #include <nvector_parallel.h>
+   *   ...
+   *   void *cvode_mem;
+   *   void *bbd_data;
+   *   ...
+   *   Set y0
+   *   ...
+   *   cvode_mem = CVodeCreate(...);
+   *   ier = CVodeMalloc(...);
+   *   ...
+   *   bbd_data = CVBBDPrecAlloc(cvode_mem, Nlocal, mudq ,mldq,
+   *                             mukeep, mlkeep, dqrely, gloc, cfn);
+   *   flag = CVBBDSpgmr(cvode_mem, pretype, maxl, bbd_data);
+   *      -or-
+   *   flag = CVBBDSpbcg(cvode_mem, pretype, maxl, bbd_data);
+   *      -or-
+   *   flag = CVBBDSptfqmr(cvode_mem, pretype, maxl, bbd_data);
+   *   ...
+   *   ier = CVode(...);
+   *   ...
+   *   CVBBDPrecFree(&bbd_data);
+   *   ...                                                           
+   *   CVodeFree(...);
+   * 
+   *   Free y0
+   *
+   * The user-supplied routines required are:
+   *
+   *   f    = function defining the ODE right-hand side f(t,y).
+   *
+   *   gloc = function defining the approximation g(t,y).
+   *
+   *   cfn  = function to perform communication need for gloc.
+   *
+   * Notes:
+   *
+   * 1) This header file is included by the user for the definition
+   *    of the CVBBDData type and for needed function prototypes.
+   *
+   * 2) The CVBBDPrecAlloc call includes half-bandwiths mudq and mldq
+   *    to be used in the difference quotient calculation of the
+   *    approximate Jacobian. They need not be the true
+   *    half-bandwidths of the Jacobian of the local block of g,
+   *    when smaller values may provide a greater efficiency.
+   *    Also, the half-bandwidths mukeep and mlkeep of the retained
+   *    banded approximate Jacobian block may be even smaller,
+   *    to reduce storage and computation costs further.
+   *    For all four half-bandwidths, the values need not be the
+   *    same on every processor.
+   *
+   * 3) The actual name of the user's f function is passed to
+   *    CVodeMalloc, and the names of the user's gloc and cfn
+   *    functions are passed to CVBBDPrecAlloc.
+   *
+   * 4) The pointer to the user-defined data block f_data, which is
+   *    set through CVodeSetFdata is also available to the user in
+   *    gloc and cfn.
+   *
+   * 5) For the CVSpgmr solver, the Gram-Schmidt type gstype,
+   *    is left to the user to specify through CVSpgmrSetGStype.
+   *
+   * 6) Optional outputs specific to this module are available by
+   *    way of routines listed below. These include work space sizes
+   *    and the cumulative number of gloc calls. The costs
+   *    associated with this module also include nsetups banded LU
+   *    factorizations, nlinsetups cfn calls, and npsolves banded
+   *    backsolve calls, where nlinsetups and npsolves are
+   *    integrator/CVSPGMR/CVSPBCG/CVSPTFQMR optional outputs.
+   * -----------------------------------------------------------------
+   */
+
+  /*
+   * -----------------------------------------------------------------
+   * Type : CVLocalFn
+   * -----------------------------------------------------------------
+   * The user must supply a function g(t,y) which approximates the
+   * right-hand side function f for the system y'=f(t,y), and which
+   * is computed locally (without interprocess communication).
+   * (The case where g is mathematically identical to f is allowed.)
+   * The implementation of this function must have type CVLocalFn.
+   *
+   * This function takes as input the local vector size Nlocal, the
+   * independent variable value t, the local real dependent
+   * variable vector y, and a pointer to the user-defined data
+   * block f_data. It is to compute the local part of g(t,y) and
+   * store this in the vector g.
+   * (Allocation of memory for y and g is handled within the
+   * preconditioner module.)
+   * The f_data parameter is the same as that specified by the user
+   * through the CVodeSetFdata routine.
+   *
+   * A CVLocalFn should return 0 if successful, a positive value if 
+   * a recoverable error occurred, and a negative value if an 
+   * unrecoverable error occurred.
+   * -----------------------------------------------------------------
+   */
+
+  typedef int (*CVLocalFn)(long int Nlocal, realtype t, N_Vector y,
+                           N_Vector g, void *f_data);
+
+  /*
+   * -----------------------------------------------------------------
+   * Type : CVCommFn
+   * -----------------------------------------------------------------
+   * The user may supply a function of type CVCommFn which performs
+   * all interprocess communication necessary to evaluate the
+   * approximate right-hand side function described above.
+   *
+   * This function takes as input the local vector size Nlocal,
+   * the independent variable value t, the dependent variable
+   * vector y, and a pointer to the user-defined data block f_data.
+   * The f_data parameter is the same as that specified by the user
+   * through the CVodeSetFdata routine. The CVCommFn cfn is
+   * expected to save communicated data in space defined within the
+   * structure f_data. Note: A CVCommFn cfn does not have a return value.
+   *
+   * Each call to the CVCommFn cfn is preceded by a call to the
+   * CVRhsFn f with the same (t,y) arguments. Thus cfn can omit any
+   * communications done by f if relevant to the evaluation of g.
+   * If all necessary communication was done by f, the user can
+   * pass NULL for cfn in CVBBDPrecAlloc (see below).
+   *
+   * A CVCommFn should return 0 if successful, a positive value if 
+   * a recoverable error occurred, and a negative value if an 
+   * unrecoverable error occurred.
+   * -----------------------------------------------------------------
+   */
+
+  typedef int (*CVCommFn)(long int Nlocal, realtype t, N_Vector y,
+                          void *f_data);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVBBDPrecAlloc
+   * -----------------------------------------------------------------
+   * CVBBDPrecAlloc allocates and initializes a CVBBDData structure
+   * to be passed to CVSp* (and used by CVBBDPrecSetup and
+   * CVBBDPrecSolve).
+   *
+   * The parameters of CVBBDPrecAlloc are as follows:
+   *
+   * cvode_mem is the pointer to the integrator memory.
+   *
+   * Nlocal is the length of the local block of the vectors y etc.
+   *        on the current processor.
+   *
+   * mudq, mldq are the upper and lower half-bandwidths to be used
+   *            in the difference quotient computation of the local
+   *            Jacobian block.
+   *
+   * mukeep, mlkeep are the upper and lower half-bandwidths of the
+   *                retained banded approximation to the local Jacobian
+   *                block.
+   *
+   * dqrely is an optional input. It is the relative increment
+   *        in components of y used in the difference quotient
+   *        approximations. To specify the default, pass 0.
+   *        The default is dqrely = sqrt(unit roundoff).
+   *
+   * gloc is the name of the user-supplied function g(t,y) that
+   *      approximates f and whose local Jacobian blocks are
+   *      to form the preconditioner.
+   *
+   * cfn is the name of the user-defined function that performs
+   *     necessary interprocess communication for the
+   *     execution of gloc.
+   *
+   * CVBBDPrecAlloc returns the storage allocated (type *void),
+   * or NULL if the request for storage cannot be satisfied.
+   * -----------------------------------------------------------------
+   */
+
+  void *CVBBDPrecAlloc(void *cvode_mem, long int Nlocal, 
+                       long int mudq, long int mldq, 
+                       long int mukeep, long int mlkeep, 
+                       realtype dqrely,
+                       CVLocalFn gloc, CVCommFn cfn);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVBBDSptfqmr
+   * -----------------------------------------------------------------
+   * CVBBDSptfqmr links the CVBBDPRE preconditioner to the CVSPTFQMR
+   * linear solver. It performs the following actions:
+   *  1) Calls the CVSPTFQMR specification routine and attaches the
+   *     CVSPTFQMR linear solver to the integrator memory;
+   *  2) Sets the preconditioner data structure for CVSPTFQMR
+   *  3) Sets the preconditioner setup routine for CVSPTFQMR
+   *  4) Sets the preconditioner solve routine for CVSPTFQMR
+   *
+   * Its first 3 arguments are the same as for CVSptfqmr (see
+   * cvsptfqmr.h). The last argument is the pointer to the CVBBDPRE
+   * memory block returned by CVBBDPrecAlloc. Note that the user need
+   * not call CVSptfqmr.
+   *
+   * Possible return values are:
+   *    CVSPILS_SUCCESS     if successful
+   *    CVSPILS_MEM_NULL    if the cvode memory was NULL
+   *    CVSPILS_LMEM_NULL   if the cvspbcg memory was NULL
+   *    CVSPILS_MEM_FAIL    if there was a memory allocation failure
+   *    CVSPILS_ILL_INPUT   if a required vector operation is missing
+   *    CVBBDPRE_PDATA_NULL if the bbd_data was NULL
+   * -----------------------------------------------------------------
+   */
+
+  int CVBBDSptfqmr(void *cvode_mem, int pretype, int maxl, void *bbd_data);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVBBDSpbcg
+   * -----------------------------------------------------------------
+   * CVBBDSpbcg links the CVBBDPRE preconditioner to the CVSPBCG
+   * linear solver. It performs the following actions:
+   *  1) Calls the CVSPBCG specification routine and attaches the
+   *     CVSPBCG linear solver to the integrator memory;
+   *  2) Sets the preconditioner data structure for CVSPBCG
+   *  3) Sets the preconditioner setup routine for CVSPBCG
+   *  4) Sets the preconditioner solve routine for CVSPBCG
+   *
+   * Its first 3 arguments are the same as for CVSpbcg (see
+   * cvspbcgs.h). The last argument is the pointer to the CVBBDPRE
+   * memory block returned by CVBBDPrecAlloc. Note that the user need
+   * not call CVSpbcg.
+   *
+   * Possible return values are:
+   *    CVSPILS_SUCCESS      if successful
+   *    CVSPILS_MEM_NULL     if the cvode memory was NULL
+   *    CVSPILS_LMEM_NULL    if the cvspbcg memory was NULL
+   *    CVSPILS_MEM_FAIL     if there was a memory allocation failure
+   *    CVSPILS_ILL_INPUT    if a required vector operation is missing
+   *    CVBBDPRE_PDATA_NULL  if the bbd_data was NULL
+   * -----------------------------------------------------------------
+   */
+
+  int CVBBDSpbcg(void *cvode_mem, int pretype, int maxl, void *bbd_data);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVBBDSpgmr
+   * -----------------------------------------------------------------
+   * CVBBDSpgmr links the CVBBDPRE preconditioner to the CVSPGMR
+   * linear solver. It performs the following actions:
+   *  1) Calls the CVSPGMR specification routine and attaches the
+   *     CVSPGMR linear solver to the integrator memory;
+   *  2) Sets the preconditioner data structure for CVSPGMR
+   *  3) Sets the preconditioner setup routine for CVSPGMR
+   *  4) Sets the preconditioner solve routine for CVSPGMR
+   *
+   * Its first 3 arguments are the same as for CVSpgmr (see
+   * cvspgmr.h). The last argument is the pointer to the CVBBDPRE
+   * memory block returned by CVBBDPrecAlloc. Note that the user need
+   * not call CVSpgmr.
+   *
+   * Possible return values are:
+   *    CVSPILS_SUCCESS      if successful
+   *    CVSPILS_MEM_NULL     if the cvode memory was NULL
+   *    CVSPILS_LMEM_NULL    if the cvspgmr memory was NULL
+   *    CVSPILS_MEM_FAIL     if there was a memory allocation failure
+   *    CVSPILS_ILL_INPUT    if a required vector operation is missing
+   *    CVBBDPRE_PDATA_NULL  if the bbd_data was NULL
+   * -----------------------------------------------------------------
+   */
+
+  int CVBBDSpgmr(void *cvode_mem, int pretype, int maxl, void *bbd_data);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVBBDPrecReInit
+   * -----------------------------------------------------------------
+   * CVBBDPrecReInit re-initializes the BBDPRE module when solving a
+   * sequence of problems of the same size with CVSPGMR/CVBBDPRE,
+   * CVSPBCG/CVBBDPRE, or CVSPTFQMR/CVBBDPRE provided there is no change 
+   * in Nlocal, mukeep, or mlkeep. After solving one problem, and after 
+   * calling CVodeReInit to re-initialize the integrator for a subsequent 
+   * problem, call CVBBDPrecReInit. Then call CVSpgmrSet*, CVSpbcgSet*,
+   * or CVSptfqmrSet*  functions if necessary for any changes to CVSPGMR,
+   * CVSPBCG, or CVSPTFQMR parameters, before calling CVode.
+   *
+   * The first argument to CVBBDPrecReInit must be the pointer pdata
+   * that was returned by CVBBDPrecAlloc. All other arguments have
+   * the same names and meanings as those of CVBBDPrecAlloc.
+   *
+   * The return value of CVBBDPrecReInit is CVBBDPRE_SUCCESS, indicating
+   * success, or CVBBDPRE_PDATA_NULL if bbd_data was NULL.
+   * -----------------------------------------------------------------
+   */
+
+  int CVBBDPrecReInit(void *bbd_data, long int mudq, long int mldq,
+                      realtype dqrely, CVLocalFn gloc, CVCommFn cfn);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVBBDPrecFree
+   * -----------------------------------------------------------------
+   * CVBBDPrecFree frees the memory block bbd_data allocated by the
+   * call to CVBBDAlloc.
+   * -----------------------------------------------------------------
+   */
+
+  void CVBBDPrecFree(void **bbd_data);
+
+  /*
+   * -----------------------------------------------------------------
+   * BBDPRE optional output extraction routines
+   * -----------------------------------------------------------------
+   * CVBBDPrecGetWorkSpace returns the BBDPRE real and integer work space
+   *                       sizes.
+   * CVBBDPrecGetNumGfnEvals returns the number of calls to gfn.
+   *
+   * The return value of CVBBDPrecGet* is one of:
+   *    CVBBDPRE_SUCCESS    if successful
+   *    CVBBDPRE_PDATA_NULL if the bbd_data memory was NULL
+   * -----------------------------------------------------------------
+   */
+
+  int CVBBDPrecGetWorkSpace(void *bbd_data, long int *lenrwBBDP, 
+                            long int *leniwBBDP);
+  int CVBBDPrecGetNumGfnEvals(void *bbd_data, long int *ngevalsBBDP);
+
+  /*
+   * -----------------------------------------------------------------
+   * The following function returns the name of the constant 
+   * associated with a CVBBDPRE return flag
+   * -----------------------------------------------------------------
+   */
+  
+  char *CVBBDPrecGetReturnFlagName(int flag);
+
+  /* 
+   * -----------------------------------------------------------------
+   * PART II - backward problems
+   * -----------------------------------------------------------------
+   */
+
+  /*
+   * -----------------------------------------------------------------
+   * Types: CVLocalFnB and CVCommFnB
+   * -----------------------------------------------------------------
+   * Local approximation function and inter-process communication
+   * function for the BBD preconditioner on the backward phase.
+   * -----------------------------------------------------------------
+   */
+
+  typedef int (*CVLocalFnB)(long int NlocalB, realtype t,
+                            N_Vector y, N_Vector yB, N_Vector gB,
+                            void *f_dataB);
+  
+  typedef int (*CVCommFnB)(long int NlocalB, realtype t,
+                           N_Vector y, N_Vector yB,
+                           void *f_dataB);
+
+  /*
+   * -----------------------------------------------------------------
+   * Functions: CVBBDPrecAllocB, CVBBDSp*B, CVBBDPrecReInit
+   * -----------------------------------------------------------------
+   * Interface functions for the CVBBDPRE preconditioner to be used on
+   * the backward phase.
+   * -----------------------------------------------------------------
+   */
+
+  int CVBBDPrecAllocB(void *cvadj_mem, long int NlocalB,
+                      long int mudqB, long int mldqB,
+                      long int mukeepB, long int mlkeepB,
+                      realtype dqrelyB,
+                      CVLocalFnB glocB, CVCommFnB cfnB);
+
+  int CVBBDSptfqmrB(void *cvadj_mem, int pretypeB, int maxlB);
+  int CVBBDSpbcgB(void *cvadj_mem, int pretypeB, int maxlB);
+  int CVBBDSpgmrB(void *cvadj_mem, int pretypeB, int maxlB);
+  
+  int CVBBDPrecReInitB(void *cvadj_mem, long int mudqB, long int mldqB,
+                       realtype dqrelyB, CVLocalFnB glocB, CVCommFnB cfnB);
+
+  void CVBBDPrecFreeB(void *cvadj_mem);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes_dense.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes_dense.h
new file mode 100644
index 0000000000000000000000000000000000000000..7a4bb85e3d90b1c64a9664c9e58a8667e7067410
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes_dense.h
@@ -0,0 +1,261 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2005, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the header file for the CVODES dense linear solver, CVDENSE.
+ *
+ *
+ * Part I contains type definitions and function prototypes for using
+ * CVDENSE on forward problems (IVP integration and/or FSA)
+ *
+ * Part II contains type definitions and function prototypes for using
+ * CVDENSE on adjoint (backward) problems
+ * -----------------------------------------------------------------
+ */
+
+#ifndef _CVSDENSE_H
+#define _CVSDENSE_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#include <sundials/sundials_dense.h>
+#include <sundials/sundials_nvector.h>
+
+  /*
+   * -----------------------------------------------------------------
+   * CVDENSE solver constants
+   * -----------------------------------------------------------------
+   * CVD_MSBJ : maximum number of steps between dense Jacobian
+   *            evaluations
+   *
+   * CVD_DGMAX : maximum change in gamma between dense Jacobian
+   *             evaluations
+   * -----------------------------------------------------------------
+   */
+
+#define CVD_MSBJ  50
+#define CVD_DGMAX RCONST(0.2)
+
+  /*
+   * -----------------------------------------------------------------
+   * CVDENSE return values
+   * -----------------------------------------------------------------
+   */
+
+#define CVDENSE_SUCCESS           0
+#define CVDENSE_MEM_NULL         -1
+#define CVDENSE_LMEM_NULL        -2
+#define CVDENSE_ILL_INPUT        -3
+#define CVDENSE_MEM_FAIL         -4
+
+  /* Additional last_flag values */
+
+#define CVDENSE_JACFUNC_UNRECVR  -5
+#define CVDENSE_JACFUNC_RECVR    -6
+
+  /* Return values for the adjoint module */
+
+#define CVDENSE_ADJMEM_NULL      -101
+#define CVDENSE_LMEMB_NULL       -102
+
+  /* 
+   * -----------------------------------------------------------------
+   * PART I - forward problems
+   * -----------------------------------------------------------------
+   */
+
+  /*
+   * -----------------------------------------------------------------
+   * Type : CVDenseJacFn
+   * -----------------------------------------------------------------
+   * A dense Jacobian approximation function Jac must have the
+   * prototype given below. Its parameters are:
+   *
+   * N is the problem size.
+   *
+   * J is the dense matrix (of type DenseMat) that will be loaded
+   * by a CVDenseJacFn with an approximation to the Jacobian matrix
+   * J = (df_i/dy_j) at the point (t,y).
+   * J is preset to zero, so only the nonzero elements need to be
+   * loaded. Two efficient ways to load J are:
+   *
+   * (1) (with macros - no explicit data structure references)
+   *     for (j=0; j < n; j++) {
+   *       col_j = DENSE_COL(J,j);
+   *       for (i=0; i < n; i++) {
+   *         generate J_ij = the (i,j)th Jacobian element
+   *         col_j[i] = J_ij;
+   *       }
+   *     }
+   *
+   * (2) (without macros - explicit data structure references)
+   *     for (j=0; j < n; j++) {
+   *       col_j = (J->data)[j];
+   *       for (i=0; i < n; i++) {
+   *         generate J_ij = the (i,j)th Jacobian element
+   *         col_j[i] = J_ij;
+   *       }
+   *     }
+   *
+   * The DENSE_ELEM(A,i,j) macro is appropriate for use in small
+   * problems in which efficiency of access is NOT a major concern.
+   *
+   * t is the current value of the independent variable.
+   *
+   * y is the current value of the dependent variable vector,
+   *   namely the predicted value of y(t).
+   *
+   * fy is the vector f(t,y).
+   *
+   * jac_data is a pointer to user data - the same as the jac_data
+   *          parameter passed to CVDense.
+   *
+   * NOTE: If the user's Jacobian routine needs other quantities,
+   *       they are accessible as follows: hcur (the current stepsize)
+   *       and ewt (the error weight vector) are accessible through
+   *       CVodeGetCurrentStep and CVodeGetErrWeights, respectively
+   *       (see cvode.h). The unit roundoff is available as
+   *       UNIT_ROUNDOFF defined in sundials_types.h.
+   *
+   * tmp1, tmp2, and tmp3 are pointers to memory allocated for
+   * vectors of length N which can be used by a CVDenseJacFn
+   * as temporary storage or work space.
+   *
+   * A CVDenseJacFn should return 0 if successful, a positive value if 
+   * a recoverable error occurred, and a negative value if an 
+   * unrecoverable error occurred.
+   * -----------------------------------------------------------------
+   */
+
+  typedef int (*CVDenseJacFn)(long int N, DenseMat J, realtype t,
+                              N_Vector y, N_Vector fy, void *jac_data,
+                              N_Vector tmp1, N_Vector tmp2, N_Vector tmp3);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVDense
+   * -----------------------------------------------------------------
+   * A call to the CVDense function links the main integrator with
+   * the CVDENSE linear solver.
+   *
+   * cvode_mem is the pointer to the integrator memory returned by
+   *           CVodeCreate.
+   *
+   * N is the size of the ODE system.
+   *
+   * The return value of CVDense is one of:
+   *    CVDENSE_SUCCESS   if successful
+   *    CVDENSE_MEM_NULL  if the cvode memory was NULL
+   *    CVDENSE_MEM_FAIL  if there was a memory allocation failure
+   *    CVDENSE_ILL_INPUT if a required vector operation is missing
+   * -----------------------------------------------------------------
+   */
+
+  int CVDense(void *cvode_mem, long int N);
+
+  /*
+   * -----------------------------------------------------------------
+   * Optional inputs to the CVDENSE linear solver
+   * -----------------------------------------------------------------
+   *
+   * CVDenseSetJacFn specifies the dense Jacobian approximation
+   *                 routine to be used. A user-supplied djac routine
+   *                 must be of type CVDenseJacFn. By default, a
+   *                 difference quotient routine CVDenseDQJac, supplied
+   *                 with this solver is used.                     
+   *                 It also specifies a pointer to user data which is
+   *                 passed to the djac routine every time it is called.
+   *
+   * The return value of CVDenseSet* is one of:
+   *    CVDENSE_SUCCESS   if successful
+   *    CVDENSE_MEM_NULL  if the cvode memory was NULL
+   *    CVDENSE_LMEM_NULL if the cvdense memory was NULL
+   * -----------------------------------------------------------------
+   */
+
+  int CVDenseSetJacFn(void *cvode_mem, CVDenseJacFn djac, void *jac_data);
+
+  /*
+   * -----------------------------------------------------------------
+   * Optional outputs from the CVDENSE linear solver
+   * -----------------------------------------------------------------
+   *
+   * CVDenseGetWorkSpace returns the real and integer workspace used
+   *                     by CVDENSE.
+   * CVDenseGetNumJacEvals returns the number of calls made to the
+   *                       Jacobian evaluation routine djac.
+   * CVDenseGetNumRhsEvals returns the number of calls to the user
+   *                       f routine due to finite difference Jacobian
+   *                       evaluation.
+   * CVDenseGetLastFlag returns the last error flag set by any of
+   *                    the CVDENSE interface functions.
+   *
+   * The return value of CVDenseGet* is one of:
+   *    CVDENSE_SUCCESS   if successful
+   *    CVDENSE_MEM_NULL  if the cvode memory was NULL
+   *    CVDENSE_LMEM_NULL if the cvdense memory was NULL
+   * -----------------------------------------------------------------
+   */
+
+  int CVDenseGetWorkSpace(void *cvode_mem, long int *lenrwLS, long int *leniwLS);
+  int CVDenseGetNumJacEvals(void *cvode_mem, long int *njevals);
+  int CVDenseGetNumRhsEvals(void *cvode_mem, long int *nfevalsLS);
+  int CVDenseGetLastFlag(void *cvode_mem, int *flag);
+
+  /*
+   * -----------------------------------------------------------------
+   * The following function returns the name of the constant 
+   * associated with a CVDENSE return flag
+   * -----------------------------------------------------------------
+   */
+
+  char *CVDenseGetReturnFlagName(int flag);
+
+  /* 
+   * -----------------------------------------------------------------
+   * PART II - backward problems
+   * -----------------------------------------------------------------
+   */
+
+  /*
+   * -----------------------------------------------------------------
+   * Type: CVDenseJacFnB
+   * -----------------------------------------------------------------
+   * A dense Jacobian approximation function JacB for the adjoint
+   * (backward) problem must have the prototype given below. 
+   * -----------------------------------------------------------------
+   */
+
+  typedef int (*CVDenseJacFnB)(long int nB, DenseMat JB, realtype t,
+                               N_Vector y, N_Vector yB, N_Vector fyB,
+                               void *jac_dataB, N_Vector tmp1B,
+                               N_Vector tmp2B, N_Vector tmp3B);
+
+  /*
+   * -----------------------------------------------------------------
+   * Functions: CVDenseB, CVDenseSetJacFnB
+   * -----------------------------------------------------------------
+   * CVDenseB links the main CVODE integrator with the CVDENSE
+   * linear solver for the backward integration.
+   * -----------------------------------------------------------------
+   */
+
+  int CVDenseB(void *cvadj_mem, long int nB);
+  
+  int CVDenseSetJacFnB(void *cvadj_mem, CVDenseJacFnB djacB, void *jac_dataB);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes_diag.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes_diag.h
new file mode 100644
index 0000000000000000000000000000000000000000..527a5928d5a1013b6a174b524ab00036c0923639
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes_diag.h
@@ -0,0 +1,141 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2005, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the header file for the CVODES diagonal linear solver, 
+ * CVDIAG.
+ *
+ *
+ * Part I contains type definitions and function prototypes for using
+ * CVDIAG on forward problems (IVP integration and/or FSA)
+ *
+ * Part II contains type definitions and function prototypes for using
+ * CVDIAG on adjoint (backward) problems
+ * -----------------------------------------------------------------
+ */
+
+#ifndef _CVSDIAG_H
+#define _CVSDIAG_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#include <sundials/sundials_nvector.h>
+
+  /*
+   * -----------------------------------------------------------------
+   * CVDIAG return values
+   * -----------------------------------------------------------------
+   */
+
+#define CVDIAG_SUCCESS          0
+#define CVDIAG_MEM_NULL        -1
+#define CVDIAG_LMEM_NULL       -2
+#define CVDIAG_ILL_INPUT       -3
+#define CVDIAG_MEM_FAIL        -4
+
+  /* Additional last_flag values */
+
+#define CVDIAG_INV_FAIL        -5
+#define CVDIAG_RHSFUNC_UNRECVR -6
+#define CVDIAG_RHSFUNC_RECVR   -7
+
+  /* Return values for adjoint module */
+
+#define CVDIAG_ADJMEM_NULL     -101
+
+  /* 
+   * -----------------------------------------------------------------
+   * PART I - forward problems
+   * -----------------------------------------------------------------
+   */
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVDiag
+   * -----------------------------------------------------------------
+   * A call to the CVDiag function links the main integrator with
+   * the CVDIAG linear solver.
+   *
+   * cvode_mem is the pointer to the integrator memory returned by
+   *           CVodeCreate.
+   *
+   * The return value of CVDiag is one of:
+   *    CVDIAG_SUCCESS   if successful
+   *    CVDIAG_MEM_NULL  if the cvode memory was NULL
+   *    CVDIAG_MEM_FAIL  if there was a memory allocation failure
+   *    CVDIAG_ILL_INPUT if a required vector operation is missing
+   * -----------------------------------------------------------------
+   */
+
+  int CVDiag(void *cvode_mem);
+  
+  /*
+   * -----------------------------------------------------------------
+   * Optional outputs from the CVDIAG linear solver
+   * -----------------------------------------------------------------
+   *
+   * CVDiagGetWorkSpace returns the real and integer workspace used
+   *                    by CVDIAG.
+   * CVDiagGetNumRhsEvals returns the number of calls to the user
+   *                      f routine due to finite difference Jacobian
+   *                      evaluation.
+   *                      Note: The number of diagonal approximate
+   *                      Jacobians formed is equal to the number of
+   *                      CVDiagSetup calls. This number is available
+   *                      through CVodeGetNumLinSolvSetups.
+   * CVDiagGetLastFlag returns the last error flag set by any of
+   *                   the CVDIAG interface functions.
+   *
+   * The return value of CVDiagGet* is one of:
+   *    CVDIAG_SUCCESS   if successful
+   *    CVDIAG_MEM_NULL  if the cvode memory was NULL
+   *    CVDIAG_LMEM_NULL if the cvdiag memory was NULL
+   * -----------------------------------------------------------------
+   */
+
+  int CVDiagGetWorkSpace(void *cvode_mem, long int *lenrwLS, long int *leniwLS);
+  int CVDiagGetNumRhsEvals(void *cvode_mem, long int *nfevalsLS);
+  int CVDiagGetLastFlag(void *cvode_mem, int *flag);
+
+  /*
+   * -----------------------------------------------------------------
+   * The following function returns the name of the constant 
+   * associated with a CVDIAG return flag
+   * -----------------------------------------------------------------
+   */
+  
+  char *CVDiagGetReturnFlagName(int flag);
+
+  /* 
+   * -----------------------------------------------------------------
+   * PART II - backward problems
+   * -----------------------------------------------------------------
+   */
+
+  /*
+   * -----------------------------------------------------------------
+   * Function: CVDiagB
+   * -----------------------------------------------------------------
+   * CVDiagB links the main CVODE integrator with the CVDIAG
+   * linear solver for the backward integration.
+   * -----------------------------------------------------------------
+   */
+  
+  int CVDiagB(void *cvadj_mem);
+  
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes_spbcgs.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes_spbcgs.h
new file mode 100644
index 0000000000000000000000000000000000000000..b68d677d650356b8cb1f2debe0983c730ac77ed0
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes_spbcgs.h
@@ -0,0 +1,86 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Aaron Collier and Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2005, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the header file for the CVODES scaled preconditioned 
+ * Bi-CGSTAB linear solver, CVSPBCG.
+ *
+ * Part I contains function prototypes for using CVSPBCG on forward 
+ * problems (IVP integration and/or FSA)
+ *
+ * Part II contains function prototypes for using CVSPBCG on adjoint 
+ * (backward) problems
+ * -----------------------------------------------------------------
+ */
+
+#ifndef _CVSSPBCG_H
+#define _CVSSPBCG_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#include <cvodes/cvodes_spils.h>
+#include <sundials/sundials_spbcgs.h>
+
+  /* 
+   * -----------------------------------------------------------------
+   * PART I - forward problems
+   * -----------------------------------------------------------------
+   */
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVSpbcg
+   * -----------------------------------------------------------------
+   * A call to the CVSpbcg function links the main CVODE integrator
+   * with the CVSPBCG linear solver.
+   *
+   * cvode_mem is the pointer to the integrator memory returned by
+   *           CVodeCreate.
+   *
+   * pretype   is the type of user preconditioning to be done.
+   *           This must be one of the four enumeration constants
+   *           PREC_NONE, PREC_LEFT, PREC_RIGHT, or PREC_BOTH defined
+   *           in iterative.h. These correspond to no preconditioning,
+   *           left preconditioning only, right preconditioning
+   *           only, and both left and right preconditioning,
+   *           respectively.
+   *
+   * maxl      is the maximum Krylov dimension. This is an
+   *           optional input to the CVSPBCG solver. Pass 0 to
+   *           use the default value CVSPILS_MAXL=5.
+   *
+   * The return value of CVSpbcg is one of:
+   *    CVSPILS_SUCCESS   if successful
+   *    CVSPILS_MEM_NULL  if the cvode memory was NULL
+   *    CVSPILS_MEM_FAIL  if there was a memory allocation failure
+   *    CVSPILS_ILL_INPUT if a required vector operation is missing
+   * The above constants are defined in cvodes_spils.h
+   * -----------------------------------------------------------------
+   */
+
+  int CVSpbcg(void *cvode_mem, int pretype, int maxl);
+
+  /* 
+   * -----------------------------------------------------------------
+   * PART II - backward problems
+   * -----------------------------------------------------------------
+   */
+
+  int CVSpbcgB(void *cvadj_mem, int pretypeB, int maxlB);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes_spgmr.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes_spgmr.h
new file mode 100644
index 0000000000000000000000000000000000000000..90d45865b3f8faa0c98add2341f90a1f86d146f5
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes_spgmr.h
@@ -0,0 +1,87 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2005, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the header file for the CVODES scaled preconditioned 
+ * GMRES linear solver, CVSPGMR.
+ *
+ * Part I contains function prototypes for using CVSPGMR on forward 
+ * problems (IVP integration and/or FSA)
+ *
+ * Part II contains function prototypes for using CVSPGMR on adjoint 
+ * (backward) problems
+ * -----------------------------------------------------------------
+ */
+
+#ifndef _CVSSPGMR_H
+#define _CVSSPGMR_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#include <cvodes/cvodes_spils.h>
+#include <sundials/sundials_spgmr.h>
+
+  /* 
+   * -----------------------------------------------------------------
+   * PART I - forward problems
+   * -----------------------------------------------------------------
+   */
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVSpgmr
+   * -----------------------------------------------------------------
+   * A call to the CVSpgmr function links the main CVODE integrator
+   * with the CVSPGMR linear solver.
+   *
+   * cvode_mem is the pointer to the integrator memory returned by
+   *           CVodeCreate.
+   *
+   * pretype   is the type of user preconditioning to be done.
+   *           This must be one of the four enumeration constants
+   *           NONE, LEFT, RIGHT, or BOTH defined in iterative.h.
+   *           These correspond to no preconditioning,
+   *           left preconditioning only, right preconditioning
+   *           only, and both left and right preconditioning,
+   *           respectively.
+   *
+   * maxl      is the maximum Krylov dimension. This is an
+   *           optional input to the CVSPGMR solver. Pass 0 to
+   *           use the default value CVSPILS_MAXL=5.
+   *
+   * The return value of CVSpgmr is one of:
+   *    CVSPILS_SUCCESS   if successful
+   *    CVSPILS_MEM_NULL  if the cvode memory was NULL
+   *    CVSPILS_MEM_FAIL  if there was a memory allocation failure
+   *    CVSPILS_ILL_INPUT if a required vector operation is missing
+   * The above constants are defined in cvodes_spils.h
+   * -----------------------------------------------------------------
+   */
+
+  int CVSpgmr(void *cvode_mem, int pretype, int maxl);
+
+  /* 
+   * -----------------------------------------------------------------
+   * PART II - backward problems
+   * -----------------------------------------------------------------
+   */
+
+  int CVSpgmrB(void *cvadj_mem, int pretypeB, int maxlB);
+  
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes_spils.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes_spils.h
new file mode 100644
index 0000000000000000000000000000000000000000..93bbd7a0383596946db2eb92436065be9a0fb64e
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes_spils.h
@@ -0,0 +1,454 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2005, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the common header file for the Scaled, Preconditioned
+ * Iterative Linear Solvers in CVODE/CVODES.
+ *
+ * Part I contains type definitions and functions for using the 
+ * iterative linear solvers on forward problems 
+ * (IVP integration and/or FSA)
+ *
+ * Part II contains type definitions and functions for using the 
+ * iterative linear solvers on adjoint (backward) problems
+ * -----------------------------------------------------------------
+ */
+
+#ifndef _CVSSPILS_H
+#define _CVSSPILS_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#include <sundials/sundials_iterative.h>
+#include <sundials/sundials_nvector.h>
+
+  /*
+   * -----------------------------------------------------------------
+   * CVSPILS return values
+   * -----------------------------------------------------------------
+   */
+
+#define CVSPILS_SUCCESS          0
+#define CVSPILS_MEM_NULL        -1
+#define CVSPILS_LMEM_NULL       -2
+#define CVSPILS_ILL_INPUT       -3
+#define CVSPILS_MEM_FAIL        -4
+
+  /* Return values for the adjoint module */
+
+#define CVSPILS_ADJMEM_NULL     -101
+#define CVSPILS_LMEMB_NULL      -102
+
+  /*
+   * -----------------------------------------------------------------
+   * CVSPILS solver constants
+   * -----------------------------------------------------------------
+   * CVSPILS_MAXL   : default value for the maximum Krylov
+   *                  dimension
+   *
+   * CVSPILS_MSBPRE : maximum number of steps between
+   *                  preconditioner evaluations
+   *
+   * CVSPILS_DGMAX  : maximum change in gamma between
+   *                  preconditioner evaluations
+   *
+   * CVSPILS_DELT   : default value for factor by which the
+   *                  tolerance on the nonlinear iteration is
+   *                  multiplied to get a tolerance on the linear
+   *                  iteration
+   * -----------------------------------------------------------------
+   */
+
+#define CVSPILS_MAXL   5
+#define CVSPILS_MSBPRE 50
+#define CVSPILS_DGMAX  RCONST(0.2)
+#define CVSPILS_DELT   RCONST(0.05)
+
+  /* 
+   * -----------------------------------------------------------------
+   * PART I - forward problems
+   * -----------------------------------------------------------------
+   */
+
+  /*
+   * -----------------------------------------------------------------
+   * Type : CVSpilsPrecSetupFn
+   * -----------------------------------------------------------------
+   * The user-supplied preconditioner setup function PrecSetup and
+   * the user-supplied preconditioner solve function PrecSolve
+   * together must define left and right preconditoner matrices
+   * P1 and P2 (either of which may be trivial), such that the
+   * product P1*P2 is an approximation to the Newton matrix
+   * M = I - gamma*J.  Here J is the system Jacobian J = df/dy,
+   * and gamma is a scalar proportional to the integration step
+   * size h.  The solution of systems P z = r, with P = P1 or P2,
+   * is to be carried out by the PrecSolve function, and PrecSetup
+   * is to do any necessary setup operations.
+   *
+   * The user-supplied preconditioner setup function PrecSetup
+   * is to evaluate and preprocess any Jacobian-related data
+   * needed by the preconditioner solve function PrecSolve.
+   * This might include forming a crude approximate Jacobian,
+   * and performing an LU factorization on the resulting
+   * approximation to M.  This function will not be called in
+   * advance of every call to PrecSolve, but instead will be called
+   * only as often as necessary to achieve convergence within the
+   * Newton iteration.  If the PrecSolve function needs no
+   * preparation, the PrecSetup function can be NULL.
+   *
+   * For greater efficiency, the PrecSetup function may save
+   * Jacobian-related data and reuse it, rather than generating it
+   * from scratch.  In this case, it should use the input flag jok
+   * to decide whether to recompute the data, and set the output
+   * flag *jcurPtr accordingly.
+   *
+   * Each call to the PrecSetup function is preceded by a call to
+   * the RhsFn f with the same (t,y) arguments.  Thus the PrecSetup
+   * function can use any auxiliary data that is computed and
+   * saved by the f function and made accessible to PrecSetup.
+   *
+   * A function PrecSetup must have the prototype given below.
+   * Its parameters are as follows:
+   *
+   * t       is the current value of the independent variable.
+   *
+   * y       is the current value of the dependent variable vector,
+   *          namely the predicted value of y(t).
+   *
+   * fy      is the vector f(t,y).
+   *
+   * jok     is an input flag indicating whether Jacobian-related
+   *         data needs to be recomputed, as follows:
+   *           jok == FALSE means recompute Jacobian-related data
+   *                  from scratch.
+   *           jok == TRUE  means that Jacobian data, if saved from
+   *                  the previous PrecSetup call, can be reused
+   *                  (with the current value of gamma).
+   *         A Precset call with jok == TRUE can only occur after
+   *         a call with jok == FALSE.
+   *
+   * jcurPtr is a pointer to an output integer flag which is
+   *         to be set by PrecSetup as follows:
+   *         Set *jcurPtr = TRUE if Jacobian data was recomputed.
+   *         Set *jcurPtr = FALSE if Jacobian data was not recomputed,
+   *                        but saved data was reused.
+   *
+   * gamma   is the scalar appearing in the Newton matrix.
+   *
+   * P_data  is a pointer to user data - the same as the P_data
+   *         parameter passed to the CV*SetPreconditioner function.
+   *
+   * tmp1, tmp2, and tmp3 are pointers to memory allocated
+   *                      for N_Vectors which can be used by
+   *                      CVSpilsPrecSetupFn as temporary storage or
+   *                      work space.
+   *
+   * NOTE: If the user's preconditioner needs other quantities,
+   *       they are accessible as follows: hcur (the current stepsize)
+   *       and ewt (the error weight vector) are accessible through
+   *       CVodeGetCurrentStep and CVodeGetErrWeights, respectively).
+   *       The unit roundoff is available as UNIT_ROUNDOFF defined in
+   *       sundials_types.h.
+   *
+   * Returned value:
+   * The value to be returned by the PrecSetup function is a flag
+   * indicating whether it was successful.  This value should be
+   *   0   if successful,
+   *   > 0 for a recoverable error (step will be retried),
+   *   < 0 for an unrecoverable error (integration is halted).
+   * -----------------------------------------------------------------
+   */
+
+  typedef int (*CVSpilsPrecSetupFn)(realtype t, N_Vector y, N_Vector fy,
+                                    booleantype jok, booleantype *jcurPtr,
+                                    realtype gamma, void *P_data,
+                                    N_Vector tmp1, N_Vector tmp2,
+                                    N_Vector tmp3);
+
+  /*
+   * -----------------------------------------------------------------
+   * Type : CVSpilsPrecSolveFn
+   * -----------------------------------------------------------------
+   * The user-supplied preconditioner solve function PrecSolve
+   * is to solve a linear system P z = r in which the matrix P is
+   * one of the preconditioner matrices P1 or P2, depending on the
+   * type of preconditioning chosen.
+   *
+   * A function PrecSolve must have the prototype given below.
+   * Its parameters are as follows:
+   *
+   * t      is the current value of the independent variable.
+   *
+   * y      is the current value of the dependent variable vector.
+   *
+   * fy     is the vector f(t,y).
+   *
+   * r      is the right-hand side vector of the linear system.
+   *
+   * z      is the output vector computed by PrecSolve.
+   *
+   * gamma  is the scalar appearing in the Newton matrix.
+   *
+   * delta  is an input tolerance for use by PSolve if it uses
+   *        an iterative method in its solution.  In that case,
+   *        the residual vector Res = r - P z of the system
+   *        should be made less than delta in weighted L2 norm,
+   *        i.e., sqrt [ Sum (Res[i]*ewt[i])^2 ] < delta.
+   *        Note: the error weight vector ewt can be obtained
+   *        through a call to the routine CVodeGetErrWeights.
+   *
+   * lr     is an input flag indicating whether PrecSolve is to use
+   *        the left preconditioner P1 or right preconditioner
+   *        P2: lr = 1 means use P1, and lr = 2 means use P2.
+   *
+   * P_data is a pointer to user data - the same as the P_data
+   *        parameter passed to the CV*SetPreconditioner function.
+   *
+   * tmp    is a pointer to memory allocated for an N_Vector
+   *        which can be used by PSolve for work space.
+   *
+   * Returned value:
+   * The value to be returned by the PrecSolve function is a flag
+   * indicating whether it was successful.  This value should be
+   *   0 if successful,
+   *   positive for a recoverable error (step will be retried),
+   *   negative for an unrecoverable error (integration is halted).
+   * -----------------------------------------------------------------
+   */
+
+  typedef int (*CVSpilsPrecSolveFn)(realtype t, N_Vector y, N_Vector fy,
+                                    N_Vector r, N_Vector z,
+                                    realtype gamma, realtype delta,
+                                    int lr, void *P_data, N_Vector tmp);
+
+  /*
+   * -----------------------------------------------------------------
+   * Type : CVSpilsJacTimesVecFn
+   * -----------------------------------------------------------------
+   * The user-supplied function jtimes is to generate the product
+   * J*v for given v, where J is the Jacobian df/dy, or an
+   * approximation to it, and v is a given vector. It should return
+   * 0 if successful a positive value for a recoverable error or 
+   * a negative value for an unrecoverable failure.
+   *
+   * A function jtimes must have the prototype given below. Its
+   * parameters are as follows:
+   *
+   *   v        is the N_Vector to be multiplied by J.
+   *
+   *   Jv       is the output N_Vector containing J*v.
+   *
+   *   t        is the current value of the independent variable.
+   *
+   *   y        is the current value of the dependent variable
+   *            vector.
+   *
+   *   fy       is the vector f(t,y).
+   *
+   *   jac_data is a pointer to user Jacobian data, the same as the
+   *            jac_data parameter passed to the CV*SetJacTimesVecFn 
+   *            function.
+   *
+   *   tmp      is a pointer to memory allocated for an N_Vector
+   *            which can be used by Jtimes for work space.
+   * -----------------------------------------------------------------
+   */
+
+  typedef int (*CVSpilsJacTimesVecFn)(N_Vector v, N_Vector Jv, realtype t,
+                                      N_Vector y, N_Vector fy,
+                                      void *jac_data, N_Vector tmp);
+
+
+  /*
+   * -----------------------------------------------------------------
+   * Optional inputs to the CVSPILS linear solver
+   * -----------------------------------------------------------------
+   *
+   * CVSpilsSetPrecType resets the type of preconditioner, pretype,
+   *                from the value previously set.
+   *                This must be one of PREC_NONE, PREC_LEFT, 
+   *                PREC_RIGHT, or PREC_BOTH.
+   *
+   * CVSpilsSetGSType specifies the type of Gram-Schmidt
+   *                orthogonalization to be used. This must be one of
+   *                the two enumeration constants MODIFIED_GS or
+   *                CLASSICAL_GS defined in iterative.h. These correspond
+   *                to using modified Gram-Schmidt and classical
+   *                Gram-Schmidt, respectively.
+   *                Default value is MODIFIED_GS.
+   *
+   * CVSpilsSetMaxl resets the maximum Krylov subspace size, maxl,
+   *                from the value previously set.
+   *                An input value <= 0, gives the default value.
+   *
+   * CVSpilsSetDelt specifies the factor by which the tolerance on
+   *                the nonlinear iteration is multiplied to get a
+   *                tolerance on the linear iteration.
+   *                Default value is 0.05.
+   *
+   * CVSpilsSetPreconditioner specifies the PrecSetup and PrecSolve functions.
+   *                as well as a pointer to user preconditioner data.
+   *                This pointer is passed to PrecSetup and PrecSolve
+   *                every time these routines are called.
+   *                Default is NULL for al three arguments.
+   *
+   * CVSpilsSetJacTimesVecFn specifies the jtimes function and a pointer to
+   *                user Jacobian data. This pointer is passed to jtimes every 
+   *                time the jtimes routine is called.
+   *                Default is to use an internal finite difference
+   *                approximation routine.
+   *
+   * The return value of CVSpilsSet* is one of:
+   *    CVSPILS_SUCCESS   if successful
+   *    CVSPILS_MEM_NULL  if the cvode memory was NULL
+   *    CVSPILS_LMEM_NULL if the cvspgmr memory was NULL
+   *    CVSPILS_ILL_INPUT if an input has an illegal value
+   * -----------------------------------------------------------------
+   */
+
+  int CVSpilsSetPrecType(void *cvode_mem, int pretype);
+  int CVSpilsSetGSType(void *cvode_mem, int gstype);
+  int CVSpilsSetMaxl(void *cvode_mem, int maxl);
+  int CVSpilsSetDelt(void *cvode_mem, realtype delt);
+  int CVSpilsSetPreconditioner(void *cvode_mem, CVSpilsPrecSetupFn pset, 
+                               CVSpilsPrecSolveFn psolve, void *P_data);
+  int CVSpilsSetJacTimesVecFn(void *cvode_mem, 
+                              CVSpilsJacTimesVecFn jtimes, void *jac_data);
+
+  /*
+   * -----------------------------------------------------------------
+   * Optional outputs from the CVSPILS linear solver
+   * -----------------------------------------------------------------
+   * CVSpilsGetWorkSpace returns the real and integer workspace used
+   *                by the SPILS module.
+   *
+   * CVSpilsGetNumPrecEvals returns the number of preconditioner
+   *                 evaluations, i.e. the number of calls made
+   *                 to PrecSetup with jok==FALSE.
+   *
+   * CVSpilsGetNumPrecSolves returns the number of calls made to
+   *                 PrecSolve.
+   *
+   * CVSpilsGetNumLinIters returns the number of linear iterations.
+   *
+   * CVSpilsGetNumConvFails returns the number of linear
+   *                 convergence failures.
+   *
+   * CVSpilsGetNumJtimesEvals returns the number of calls to jtimes.
+   *
+   * CVSpilsGetNumRhsEvals returns the number of calls to the user
+   *                 f routine due to finite difference Jacobian
+   *                 times vector evaluation.
+   *
+   * CVSpilsGetLastFlag returns the last error flag set by any of
+   *                 the CVSPILS interface functions.
+   *
+   * The return value of CVSpilsGet* is one of:
+   *    CVSPILS_SUCCESS   if successful
+   *    CVSPILS_MEM_NULL  if the cvode memory was NULL
+   *    CVSPILS_LMEM_NULL if the cvspgmr memory was NULL
+   * -----------------------------------------------------------------
+   */
+
+  int CVSpilsGetWorkSpace(void *cvode_mem, long int *lenrwLS, long int *leniwLS);
+  int CVSpilsGetNumPrecEvals(void *cvode_mem, long int *npevals);
+  int CVSpilsGetNumPrecSolves(void *cvode_mem, long int *npsolves);
+  int CVSpilsGetNumLinIters(void *cvode_mem, long int *nliters);
+  int CVSpilsGetNumConvFails(void *cvode_mem, long int *nlcfails);
+  int CVSpilsGetNumJtimesEvals(void *cvode_mem, long int *njvevals);
+  int CVSpilsGetNumRhsEvals(void *cvode_mem, long int *nfevalsLS); 
+  int CVSpilsGetLastFlag(void *cvode_mem, int *flag);
+
+  /*
+   * -----------------------------------------------------------------
+   * The following function returns the name of the constant 
+   * associated with a CVSPILS return flag
+   * -----------------------------------------------------------------
+   */
+  
+  char *CVSpilsGetReturnFlagName(int flag);
+
+
+  /* 
+   * -----------------------------------------------------------------
+   * PART II - backward problems
+   * -----------------------------------------------------------------
+   */
+
+  /*
+   * -----------------------------------------------------------------
+   * Type : CVSpilsPrecSetupFnB
+   * -----------------------------------------------------------------
+   * A function PrecSetupB for the adjoint (backward) problem must have 
+   * the prototype given below.
+   * -----------------------------------------------------------------
+   */
+
+  typedef int (*CVSpilsPrecSetupFnB)(realtype t, N_Vector y,
+                                     N_Vector yB, N_Vector fyB,
+                                     booleantype jokB,
+                                     booleantype *jcurPtrB, realtype gammaB,
+                                     void *P_dataB,
+                                     N_Vector tmp1B, N_Vector tmp2B,
+                                     N_Vector tmp3B);
+
+
+  /*
+   * -----------------------------------------------------------------
+   * Type : CVSpilsPrecSolveFnB
+   * -----------------------------------------------------------------
+   * A function PrecSolveB for the adjoint (backward) problem  must 
+   * have the prototype given below.
+   * -----------------------------------------------------------------
+   */
+
+  typedef int (*CVSpilsPrecSolveFnB)(realtype t, N_Vector y,
+                                     N_Vector yB, N_Vector fyB,
+                                     N_Vector rB, N_Vector zB,
+                                     realtype gammaB, realtype deltaB,
+                                     int lrB, void *P_dataB, N_Vector tmpB);
+
+  /*
+   * -----------------------------------------------------------------
+   * Type : CVSpilsJacTimesVecFnB
+   * -----------------------------------------------------------------
+   * A function jtimesB for the adjoint (backward) problem must have 
+   * the prototype given below.
+   * -----------------------------------------------------------------
+   */
+
+  typedef int (*CVSpilsJacTimesVecFnB)(N_Vector vB, N_Vector JvB, realtype t,
+                                       N_Vector y, N_Vector yB, N_Vector fyB,
+                                       void *jac_dataB, N_Vector tmpB);
+
+  /*
+   * -----------------------------------------------------------------
+   * Functions
+   * -----------------------------------------------------------------
+   */
+
+  int CVSpilsSetPrecTypeB(void *cvadj_mem, int pretypeB);
+  int CVSpilsSetGSTypeB(void *cvadj_mem, int gstypeB);
+  int CVSpilsSetDeltB(void *cvadj_mem, realtype deltB);
+  int CVSpilsSetMaxlB(void *cvadj_mem, int maxlB);
+  int CVSpilsSetPreconditionerB(void *cvadj_mem, CVSpilsPrecSetupFnB psetB,
+                                CVSpilsPrecSolveFnB psolveB, void *P_dataB);
+  int CVSpilsSetJacTimesVecFnB(void *cvadj_mem, CVSpilsJacTimesVecFnB jtimesB,
+                               void *jac_dataB);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes_sptfqmr.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes_sptfqmr.h
new file mode 100644
index 0000000000000000000000000000000000000000..78bbb77fea668a05162b964d546ed0a910843289
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/cvodes/cvodes_sptfqmr.h
@@ -0,0 +1,87 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Aaron Collier and Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2005, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the header file for the CVODES scaled preconditioned TFQMR 
+ * linear solver, CVSPTFQMR.
+ *
+ * Part I contains function prototypes for using CVSPTFQMR on forward 
+ * problems (IVP integration and/or FSA)
+ *
+ * Part II contains function prototypes for using CVSPTFQMR on adjoint 
+ * (backward) problems
+ * -----------------------------------------------------------------
+ */
+
+#ifndef _CVSSPTFQMR_H
+#define _CVSSPTFQMR_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#include <cvodes/cvodes_spils.h>
+#include <sundials/sundials_sptfqmr.h>
+
+  /* 
+   * -----------------------------------------------------------------
+   * PART I - forward problems
+   * -----------------------------------------------------------------
+   */
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : CVSptfqmr
+   * -----------------------------------------------------------------
+   * A call to the CVSptfqmr function links the main CVODE integrator
+   * with the CVSPTFQMR linear solver.
+   *
+   * cvode_mem is the pointer to the integrator memory returned by
+   *           CVodeCreate.
+   *
+   * pretype   is the type of user preconditioning to be done.
+   *           This must be one of the four enumeration constants
+   *           PREC_NONE, PREC_LEFT, PREC_RIGHT, or PREC_BOTH defined
+   *           in iterative.h. These correspond to no preconditioning,
+   *           left preconditioning only, right preconditioning
+   *           only, and both left and right preconditioning,
+   *           respectively.
+   *
+   * maxl      is the maximum Krylov dimension. This is an
+   *           optional input to the CVSPTFQMR solver. Pass 0 to
+   *           use the default value CVSPILS_MAXL=5.
+   *
+   * The return value of CVSptfqmr is one of:
+   *    CVSPILS_SUCCESS   if successful
+   *    CVSPILS_MEM_NULL  if the cvode memory was NULL
+   *    CVSPILS_MEM_FAIL  if there was a memory allocation failure
+   *    CVSPILS_ILL_INPUT if a required vector operation is missing
+   * The above constants are defined in cvodes_spils.h
+   * -----------------------------------------------------------------
+   */
+
+  int CVSptfqmr(void *cvode_mem, int pretype, int maxl);
+
+
+  /* 
+   * -----------------------------------------------------------------
+   * PART II - backward problems
+   * -----------------------------------------------------------------
+   */
+
+  int CVSptfqmrB(void *cvadj_mem, int pretypeB, int maxlB);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/nvector/nvector_serial.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/nvector/nvector_serial.h
new file mode 100644
index 0000000000000000000000000000000000000000..2bb736831428d48ca28bb41cd5461a9a3a7b614f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/nvector/nvector_serial.h
@@ -0,0 +1,265 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Scott D. Cohen, Alan C. Hindmarsh, Radu Serban,
+ *                and Aaron Collier @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2002, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the header file for the serial implementation of the
+ * NVECTOR module.
+ *
+ * Part I contains declarations specific to the serial
+ * implementation of the supplied NVECTOR module.
+ *
+ * Part II defines accessor macros that allow the user to
+ * efficiently use the type N_Vector without making explicit
+ * references to the underlying data structure.
+ *
+ * Part III contains the prototype for the constructor N_VNew_Serial
+ * as well as implementation-specific prototypes for various useful
+ * vector operations.
+ *
+ * Notes:
+ *
+ *   - The definition of the generic N_Vector structure can be found
+ *     in the header file sundials_nvector.h.
+ *
+ *   - The definition of the type 'realtype' can be found in the
+ *     header file sundials_types.h, and it may be changed (at the 
+ *     configuration stage) according to the user's needs. 
+ *     The sundials_types.h file also contains the definition
+ *     for the type 'booleantype'.
+ *
+ *   - N_Vector arguments to arithmetic vector operations need not
+ *     be distinct. For example, the following call:
+ *
+ *       N_VLinearSum_Serial(a,x,b,y,y);
+ *
+ *     (which stores the result of the operation a*x+b*y in y)
+ *     is legal.
+ * -----------------------------------------------------------------
+ */
+
+#ifndef _NVECTOR_SERIAL_H
+#define _NVECTOR_SERIAL_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#include <sundials/sundials_nvector.h>
+
+/*
+ * -----------------------------------------------------------------
+ * PART I: SERIAL implementation of N_Vector
+ * -----------------------------------------------------------------
+ */
+
+/* serial implementation of the N_Vector 'content' structure
+   contains the length of the vector, a pointer to an array
+   of 'realtype' components, and a flag indicating ownership of
+   the data */
+
+struct _N_VectorContent_Serial {
+  long int length;
+  booleantype own_data;
+  realtype *data;
+};
+
+typedef struct _N_VectorContent_Serial *N_VectorContent_Serial;
+
+/*
+ * -----------------------------------------------------------------
+ * PART II: macros NV_CONTENT_S, NV_DATA_S, NV_OWN_DATA_S,
+ *          NV_LENGTH_S, and NV_Ith_S
+ * -----------------------------------------------------------------
+ * In the descriptions below, the following user declarations
+ * are assumed:
+ *
+ * N_Vector v;
+ * long int i;
+ *
+ * (1) NV_CONTENT_S
+ *
+ *     This routines gives access to the contents of the serial
+ *     vector N_Vector.
+ *
+ *     The assignment v_cont = NV_CONTENT_S(v) sets v_cont to be
+ *     a pointer to the serial N_Vector content structure.
+ *
+ * (2) NV_DATA_S NV_OWN_DATA_S and NV_LENGTH_S
+ *
+ *     These routines give access to the individual parts of
+ *     the content structure of a serial N_Vector.
+ *
+ *     The assignment v_data = NV_DATA_S(v) sets v_data to be
+ *     a pointer to the first component of v. The assignment
+ *     NV_DATA_S(v) = data_V sets the component array of v to
+ *     be data_v by storing the pointer data_v.
+ *
+ *     The assignment v_len = NV_LENGTH_S(v) sets v_len to be
+ *     the length of v. The call NV_LENGTH_S(v) = len_v sets
+ *     the length of v to be len_v.
+ *
+ * (3) NV_Ith_S
+ *
+ *     In the following description, the components of an
+ *     N_Vector are numbered 0..n-1, where n is the length of v.
+ *
+ *     The assignment r = NV_Ith_S(v,i) sets r to be the value of
+ *     the ith component of v. The assignment NV_Ith_S(v,i) = r
+ *     sets the value of the ith component of v to be r.
+ *
+ * Note: When looping over the components of an N_Vector v, it is
+ * more efficient to first obtain the component array via
+ * v_data = NV_DATA_S(v) and then access v_data[i] within the
+ * loop than it is to use NV_Ith_S(v,i) within the loop.
+ * -----------------------------------------------------------------
+ */
+
+#define NV_CONTENT_S(v)  ( (N_VectorContent_Serial)(v->content) )
+
+#define NV_LENGTH_S(v)   ( NV_CONTENT_S(v)->length )
+
+#define NV_OWN_DATA_S(v) ( NV_CONTENT_S(v)->own_data )
+
+#define NV_DATA_S(v)     ( NV_CONTENT_S(v)->data )
+
+#define NV_Ith_S(v,i)    ( NV_DATA_S(v)[i] )
+
+/*
+ * -----------------------------------------------------------------
+ * PART III: functions exported by nvector_serial
+ * 
+ * CONSTRUCTORS:
+ *    N_VNew_Serial
+ *    N_VNewEmpty_Serial
+ *    N_VMake_Serial
+ *    N_VCloneVectorArray_Serial
+ *    N_VCloneVectorArrayEmpty_Serial
+ * DESTRUCTORS:
+ *    N_VDestroy_Serial
+ *    N_VDestroyVectorArray_Serial
+ * OTHER:
+ *    N_VPrint_Serial
+ * -----------------------------------------------------------------
+ */
+
+/*
+ * -----------------------------------------------------------------
+ * Function : N_VNew_Serial
+ * -----------------------------------------------------------------
+ * This function creates and allocates memory for a serial vector.
+ * -----------------------------------------------------------------
+ */
+
+N_Vector N_VNew_Serial(long int vec_length);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : N_VNewEmpty_Serial
+ * -----------------------------------------------------------------
+ * This function creates a new serial N_Vector with an empty (NULL)
+ * data array.
+ * -----------------------------------------------------------------
+ */
+
+N_Vector N_VNewEmpty_Serial(long int vec_length);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : N_VMake_Serial
+ * -----------------------------------------------------------------
+ * This function creates and allocates memory for a serial vector
+ * with a user-supplied data array.
+ * -----------------------------------------------------------------
+ */
+
+N_Vector N_VMake_Serial(long int vec_length, realtype *v_data);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : N_VCloneVectorArray_Serial
+ * -----------------------------------------------------------------
+ * This function creates an array of 'count' SERIAL vectors by
+ * cloning a given vector w.
+ * -----------------------------------------------------------------
+ */
+
+N_Vector *N_VCloneVectorArray_Serial(int count, N_Vector w);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : N_VCloneVectorArrayEmpty_Serial
+ * -----------------------------------------------------------------
+ * This function creates an array of 'count' SERIAL vectors each
+ * with an empty (NULL) data array by cloning w.
+ * -----------------------------------------------------------------
+ */
+
+N_Vector *N_VCloneVectorArrayEmpty_Serial(int count, N_Vector w);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : N_VDestroyVectorArray_Serial
+ * -----------------------------------------------------------------
+ * This function frees an array of SERIAL vectors created with 
+ * N_VCloneVectorArray_Serial or N_VCloneVectorArrayEmpty_Serial.
+ * -----------------------------------------------------------------
+ */
+
+void N_VDestroyVectorArray_Serial(N_Vector *vs, int count);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : N_VPrint_Serial
+ * -----------------------------------------------------------------
+ * This function prints the content of a serial vector to stdout.
+ * -----------------------------------------------------------------
+ */
+
+void N_VPrint_Serial(N_Vector v);
+
+/*
+ * -----------------------------------------------------------------
+ * serial implementations of various useful vector operations
+ * -----------------------------------------------------------------
+ */
+
+N_Vector N_VCloneEmpty_Serial(N_Vector w);
+N_Vector N_VClone_Serial(N_Vector w);
+void N_VDestroy_Serial(N_Vector v);
+void N_VSpace_Serial(N_Vector v, long int *lrw, long int *liw);
+realtype *N_VGetArrayPointer_Serial(N_Vector v);
+void N_VSetArrayPointer_Serial(realtype *v_data, N_Vector v);
+void N_VLinearSum_Serial(realtype a, N_Vector x, realtype b, N_Vector y, N_Vector z);
+void N_VConst_Serial(realtype c, N_Vector z);
+void N_VProd_Serial(N_Vector x, N_Vector y, N_Vector z);
+void N_VDiv_Serial(N_Vector x, N_Vector y, N_Vector z);
+void N_VScale_Serial(realtype c, N_Vector x, N_Vector z);
+void N_VAbs_Serial(N_Vector x, N_Vector z);
+void N_VInv_Serial(N_Vector x, N_Vector z);
+void N_VAddConst_Serial(N_Vector x, realtype b, N_Vector z);
+realtype N_VDotProd_Serial(N_Vector x, N_Vector y);
+realtype N_VMaxNorm_Serial(N_Vector x);
+realtype N_VWrmsNorm_Serial(N_Vector x, N_Vector w);
+realtype N_VWrmsNormMask_Serial(N_Vector x, N_Vector w, N_Vector id);
+realtype N_VMin_Serial(N_Vector x);
+realtype N_VWL2Norm_Serial(N_Vector x, N_Vector w);
+realtype N_VL1Norm_Serial(N_Vector x);
+void N_VCompare_Serial(realtype c, N_Vector x, N_Vector z);
+booleantype N_VInvTest_Serial(N_Vector x, N_Vector z);
+booleantype N_VConstrMask_Serial(N_Vector c, N_Vector x, N_Vector m);
+realtype N_VMinQuotient_Serial(N_Vector num, N_Vector denom);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_band.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_band.h
new file mode 100644
index 0000000000000000000000000000000000000000..db503c76e66831465c157693110c6636e5886214
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_band.h
@@ -0,0 +1,605 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * -----------------------------------------------------------------
+ * Programmer(s): Alan C. Hindmarsh and Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2002, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the header file for a generic BAND linear solver
+ * package. There are two sets of band solver routines listed in
+ * this file: one set uses type BandMat defined below and the
+ * other set uses the type realtype ** for band matrix arguments.
+ * The two sets of band solver routines make it easy to work
+ * with two types of band matrices:
+ *
+ * (1) The BandMat type is intended for use with large
+ *     band matrices whose elements/columns may be stored in
+ *     non-contiguous memory locations or even distributed across
+ *     different process memory spaces. This type may be modified
+ *     to include such distribution information. If this is done,
+ *     then all the routines that use BandMat must be modified to
+ *     reflect the new data structure.
+ *
+ * (2) The set of routines that use realtype ** (and NOT the
+ *     BandMat type) is intended for use with small matrices
+ *     which can easily be allocated within a contiguous block of
+ *     memory for a single process.
+ *
+ * Routines that work with the type BandMat begin with "Band".
+ * The BandAllocMat function allocates a band matrix for use in
+ * the other matrix routines listed in this file. Matrix storage
+ * details are given in the documentation for the type BandMat.
+ * The BandAllocPiv function allocates memory for pivot
+ * information. The storage allocated by BandAllocMat and
+ * BandAllocPiv is deallocated by the routines BandFreeMat and
+ * BandFreePiv, respectively. The BandGBTRF and BandGBTRS
+ * routines perform the actual solution of a band linear system.
+ *
+ * Routines that work with realtype ** begin with "band" (except
+ * for the factor and solve routines which are called bandGBTRF and
+ * bandGBTRS, respectively). The underlying matrix storage is
+ * described in the documentation for bandalloc.
+ * -----------------------------------------------------------------
+ */
+
+#ifndef _BAND_H
+#define _BAND_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#include <sundials/sundials_types.h>
+
+/*
+ * -----------------------------------------------------------------
+ * Type: BandMat
+ * -----------------------------------------------------------------
+ * The type BandMat is the type of a large (possibly distributed)
+ * band matrix. It is defined to be a pointer to a structure
+ * with the following fields:
+ *
+ * size is the number of columns (== number of rows)
+ *
+ * mu   is the upper bandwidth, 0 <= mu <= size-1
+ *
+ * ml   is the lower bandwidth, 0 <= ml <= size-1
+ *
+ * smu  is the storage upper bandwidth, mu <= smu <= size-1.
+ *      The BandGBTRF routine writes the LU factors
+ *      into the storage for A. The upper triangular factor U,
+ *      however, may have an upper bandwidth as big as
+ *      MIN(size-1,mu+ml) because of partial pivoting. The smu
+ *      field holds the upper bandwidth allocated for A.
+ *
+ * data is a two dimensional array used for component storage.
+ *      The elements of a band matrix of type BandMat are
+ *      stored columnwise (i.e. columns are stored one on top
+ *      of the other in memory). Only elements within the
+ *      specified bandwidths are stored.
+ *
+ * If we number rows and columns in the band matrix starting
+ * from 0, then
+ *
+ * data[0] is a pointer to (smu+ml+1)*size contiguous locations
+ *         which hold the elements within the band of A
+ *
+ * data[j] is a pointer to the uppermost element within the band
+ *         in the jth column. This pointer may be treated as
+ *         an array indexed from smu-mu (to access the
+ *         uppermost element within the band in the jth
+ *         column) to smu+ml (to access the lowest element
+ *         within the band in the jth column). (Indices from 0
+ *         to smu-mu-1 give access to extra storage elements
+ *         required by BandGBTRF.)
+ *
+ * data[j][i-j+smu] is the (i,j)th element, j-mu <= i <= j+ml.
+ *
+ * The macros below allow a user to access individual matrix
+ * elements without writing out explicit data structure
+ * references and without knowing too much about the underlying
+ * element storage. The only storage assumption needed is that
+ * elements are stored columnwise and that a pointer into the jth
+ * column of elements can be obtained via the BAND_COL macro. The
+ * BAND_COL_ELEM macro selects an element from a column which has
+ * already been isolated via BAND_COL. BAND_COL_ELEM allows the
+ * user to avoid the translation from the matrix location (i,j)
+ * to the index in the array returned by BAND_COL at which the
+ * (i,j)th element is stored. See the documentation for BAND_COL
+ * and BAND_COL_ELEM for usage details. Users should use these
+ * macros whenever possible.
+ * -----------------------------------------------------------------
+ */
+
+typedef struct _BandMat {
+  long int size;
+  long int mu, ml, smu;
+  realtype **data;
+} *BandMat;
+
+/* BandMat accessor macros */
+
+/*
+ * -----------------------------------------------------------------
+ * Macro : BAND_ELEM
+ * -----------------------------------------------------------------
+ * Usage : BAND_ELEM(A,i,j) = a_ij;  OR
+ *         a_ij = BAND_ELEM(A,i,j);
+ * -----------------------------------------------------------------
+ * BAND_ELEM(A,i,j) references the (i,j)th element of the
+ * N by N band matrix A, where 0 <= i,j <= N-1. The location
+ * (i,j) should further satisfy j-(A->mu) <= i <= j+(A->ml).
+ * -----------------------------------------------------------------
+ */
+
+#define BAND_ELEM(A,i,j) ((A->data)[j][(i)-(j)+(A->smu)])
+
+/*
+ * -----------------------------------------------------------------
+ * Macro : BAND_COL
+ * -----------------------------------------------------------------
+ * Usage : col_j = BAND_COL(A,j);
+ * -----------------------------------------------------------------
+ * BAND_COL(A,j) references the diagonal element of the jth
+ * column of the N by N band matrix A, 0 <= j <= N-1. The type of
+ * the expression BAND_COL(A,j) is realtype *. The pointer
+ * returned by the call BAND_COL(A,j) can be treated as an array
+ * which is indexed from -(A->mu) to (A->ml).
+ * -----------------------------------------------------------------
+ */
+
+#define BAND_COL(A,j) (((A->data)[j])+(A->smu))
+
+/*
+ * -----------------------------------------------------------------
+ * Macro : BAND_COL_ELEM
+ * -----------------------------------------------------------------
+ * Usage : col_j = BAND_COL(A,j);
+ *         BAND_COL_ELEM(col_j,i,j) = a_ij;  OR
+ *         a_ij = BAND_COL_ELEM(col_j,i,j);
+ * -----------------------------------------------------------------
+ * This macro references the (i,j)th entry of the band matrix A
+ * when used in conjunction with BAND_COL as shown above. The
+ * index (i,j) should satisfy j-(A->mu) <= i <= j+(A->ml).
+ * -----------------------------------------------------------------
+ */
+
+#define BAND_COL_ELEM(col_j,i,j) (col_j[(i)-(j)])
+
+/* Functions that use the BandMat representation for a band matrix */
+
+/*
+ * -----------------------------------------------------------------
+ * Function : BandAllocMat
+ * -----------------------------------------------------------------
+ * Usage : A = BandAllocMat(N, mu, ml, smu);
+ *         if (A == NULL) ... memory request failed
+ * -----------------------------------------------------------------
+ * BandAllocMat allocates memory for an N by N band matrix with
+ * upper bandwidth mu, lower bandwidth ml, and storage upper
+ * bandwidth smu. Pass smu as follows depending on whether A will
+ * be factored by BandGBTRF:
+ *
+ * (1) Pass smu = mu if A will not be factored.
+ *
+ * (2) Pass smu = MIN(N-1,mu+ml) if A will be factored.
+ *
+ * BandAllocMat returns the storage allocated (type BandMat) or
+ * NULL if the request for matrix storage cannot be satisfied.
+ * See the documentation for the type BandMat for matrix storage
+ * details.
+ * -----------------------------------------------------------------
+ */
+
+BandMat BandAllocMat(long int N, long int mu, long int ml, 
+                     long int smu);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : BandAllocPiv
+ * -----------------------------------------------------------------
+ * Usage : p = BandAllocPiv(N);
+ *         if (p == NULL) ... memory request failed
+ * -----------------------------------------------------------------
+ * BandAllocPiv allocates memory for pivot information to be
+ * filled in by the BandGBTRF routine during the factorization
+ * of an N by N band matrix. The underlying type for pivot
+ * information is an array of N integers and this routine returns
+ * the pointer to the memory it allocates. If the request for
+ * pivot storage cannot be satisfied, BandAllocPiv returns NULL.
+ * -----------------------------------------------------------------
+ */
+
+long int *BandAllocPiv(long int N);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : BandGBTRF
+ * -----------------------------------------------------------------
+ * Usage : ier = BandGBTRF(A, p);
+ *         if (ier != 0) ... A is singular
+ * -----------------------------------------------------------------
+ * BandGBTRF performs the LU factorization of the N by N band
+ * matrix A. This is done using standard Gaussian elimination
+ * with partial pivoting.
+ *
+ * A successful LU factorization leaves the "matrix" A and the
+ * pivot array p with the following information:
+ *
+ * (1) p[k] contains the row number of the pivot element chosen
+ *     at the beginning of elimination step k, k=0, 1, ..., N-1.
+ *
+ * (2) If the unique LU factorization of A is given by PA = LU,
+ *     where P is a permutation matrix, L is a lower triangular
+ *     matrix with all 1's on the diagonal, and U is an upper
+ *     triangular matrix, then the upper triangular part of A
+ *     (including its diagonal) contains U and the strictly lower
+ *     triangular part of A contains the multipliers, I-L.
+ *
+ * BandGBTRF returns 0 if successful. Otherwise it encountered
+ * a zero diagonal element during the factorization. In this case
+ * it returns the column index (numbered from one) at which
+ * it encountered the zero.
+ *
+ * Important Note: A must be allocated to accommodate the increase
+ * in upper bandwidth that occurs during factorization. If
+ * mathematically, A is a band matrix with upper bandwidth mu and
+ * lower bandwidth ml, then the upper triangular factor U can
+ * have upper bandwidth as big as smu = MIN(n-1,mu+ml). The lower
+ * triangular factor L has lower bandwidth ml. Allocate A with
+ * call A = BandAllocMat(N,mu,ml,smu), where mu, ml, and smu are
+ * as defined above. The user does not have to zero the "extra"
+ * storage allocated for the purpose of factorization. This will
+ * handled by the BandGBTRF routine.
+ * -----------------------------------------------------------------
+ */
+
+long int BandGBTRF(BandMat A, long int *p);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : BandGBTRS
+ * -----------------------------------------------------------------
+ * Usage : BandGBTRS(A, p, b);
+ * -----------------------------------------------------------------
+ * BandGBTRS solves the N-dimensional system A x = b using
+ * the LU factorization in A and the pivot information in p
+ * computed in BandGBTRF. The solution x is returned in b. This
+ * routine cannot fail if the corresponding call to BandGBTRF
+ * did not fail.
+ * -----------------------------------------------------------------
+ */
+
+void BandGBTRS(BandMat A, long int *p, realtype *b);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : BandZero
+ * -----------------------------------------------------------------
+ * Usage : BandZero(A);
+ * -----------------------------------------------------------------
+ * A(i,j) <- 0.0,    j-(A->mu) <= i <= j+(A->ml).
+ * -----------------------------------------------------------------
+ */
+
+void BandZero(BandMat A);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : BandCopy
+ * -----------------------------------------------------------------
+ * Usage : BandCopy(A, B, copymu, copyml);
+ * -----------------------------------------------------------------
+ * BandCopy copies the submatrix with upper and lower bandwidths
+ * copymu, copyml of the N by N band matrix A into the N by N
+ * band matrix B.
+ * -----------------------------------------------------------------
+ */
+
+void BandCopy(BandMat A, BandMat B, long int copymu, long int copyml);
+
+/*
+ * -----------------------------------------------------------------
+ * Function: BandScale
+ * -----------------------------------------------------------------
+ * Usage : BandScale(c, A);
+ * -----------------------------------------------------------------
+ * A(i,j) <- c*A(i,j),   j-(A->mu) <= i <= j+(A->ml).
+ * -----------------------------------------------------------------
+ */
+
+void BandScale(realtype c, BandMat A);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : BandAddI
+ * -----------------------------------------------------------------
+ * Usage : BandAddI(A);
+ * -----------------------------------------------------------------
+ * A(j,j) <- A(j,j)+1.0,   0 <= j <= (A->size)-1.
+ * -----------------------------------------------------------------
+ */
+
+void BandAddI(BandMat A);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : BandFreeMat
+ * -----------------------------------------------------------------
+ * Usage : BandFreeMat(A);
+ * -----------------------------------------------------------------
+ * BandFreeMat frees the memory allocated by BandAllocMat for
+ * the band matrix A.
+ * -----------------------------------------------------------------
+ */
+
+void BandFreeMat(BandMat A);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : BandFreePiv
+ * -----------------------------------------------------------------
+ * Usage : BandFreePiv(p);
+ * -----------------------------------------------------------------
+ * BandFreePiv frees the memory allocated by BandAllocPiv for
+ * the pivot information array p.
+ * -----------------------------------------------------------------
+ */
+
+void BandFreePiv(long int *p);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : BandPrint
+ * -----------------------------------------------------------------
+ * Usage : BandPrint(A);
+ * -----------------------------------------------------------------
+ * This routine prints the N by N band matrix A (upper and lower
+ * bandwidths A->mu and A->ml, respectively) to standard output
+ * as it would normally appear on paper. It is intended as a
+ * debugging tool with small values of N. The elements are
+ * printed using the %g/lg/Lg option. A blank line is printed
+ * before and after the matrix.
+ * -----------------------------------------------------------------
+ */
+
+void BandPrint(BandMat A);
+
+/* Functions that use the realtype ** representation for a band matrix */
+
+/*
+ * -----------------------------------------------------------------
+ * Function : bandalloc
+ * -----------------------------------------------------------------
+ * Usage : realtype **a;
+ *         a = bandalloc(n, smu, ml);
+ *         if (a == NULL) ... memory request failed
+ * -----------------------------------------------------------------
+ * bandalloc(n, smu, ml) allocates storage for an n by n band
+ * matrix A with storage upper bandwidth smu and lower bandwidth
+ * ml. It returns a pointer to the newly allocated storage if
+ * successful. If the memory request cannot be satisfied, then
+ * bandalloc returns NULL. If, mathematically, A has upper and
+ * lower bandwidths mu and ml, respectively, then the value
+ * passed to bandalloc for smu may need to be greater than mu.
+ * The bandGBTRF routine writes the LU factors into the storage
+ * (named "a" in the above usage documentation) for A (thus destroying
+ * the original elements of A). The upper triangular factor U,
+ * however, may have a larger upper bandwidth than the upper
+ * bandwidth mu of A. Thus some "extra" storage for A must be
+ * allocated if A is to be factored by bandGBTRF. Pass smu as follows:
+ *
+ * (1) Pass smu = mu if A will not be factored.
+ *
+ * (2) Pass smu = MIN(n-1,mu+ml) if A will be factored.
+ *
+ * The underlying type of the band matrix returned is realtype**.
+ * If we allocate a band matrix A in realtype **a by
+ * a = bandalloc(n,smu,ml), then a[0] is a pointer to
+ * n * (smu + ml + 1) contiguous storage locations and a[j] is a
+ * pointer to the uppermost element in the storage for the jth
+ * column. The expression a[j][i-j+smu] references the (i,j)th
+ * element of A, where 0 <= i,j <= n-1 and j-mu <= i <= j+ml.
+ * (The elements a[j][0], a[j][1], ..., a[j][smu-mu-1] are used
+ * by bandGBTRF and bandGBTRS.)
+ * -----------------------------------------------------------------
+ */
+
+realtype **bandalloc(long int n, long int smu, long int ml);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : bandallocpiv
+ * -----------------------------------------------------------------
+ * Usage : long int *pivot;
+ *         pivot = bandallocpiv(n);
+ *         if (pivot == NULL) ... memory request failed
+ * -----------------------------------------------------------------
+ * bandallocpiv(n) allocates an array of n integers. It returns a
+ * pointer to the first element in the array if successful. It
+ * returns NULL if the memory request could not be satisfied.
+ * -----------------------------------------------------------------
+ */
+
+long int *bandallocpiv(long int n);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : bandGBTRF
+ * -----------------------------------------------------------------
+ * Usage : long int ier;
+ *         ier = bandGBTRF(a,n,mu,ml,smu,p);
+ *         if (ier > 0) ... zero element encountered during
+ *                          the factorization
+ * -----------------------------------------------------------------
+ * bandGBTRF(a,n,mu,ml,smu,p) factors the n by n band matrix A 
+ * (upper and lower bandwidths mu and ml, storage upper bandwidth smu)
+ * stored in "a". It overwrites the elements of A with the LU
+ * factors and it keeps track of the pivot rows chosen in the
+ * pivot array p.
+ *
+ * A successful LU factorization leaves a and pivot array p with
+ * the following information:
+ *
+ * (1) p[k] contains the row number of the pivot element chosen
+ *     at the beginning of elimination step k, k=0, 1, ..., n-1.
+ *
+ * (2) If the unique LU factorization of A is given by PA = LU,
+ *     where P is a permutation matrix, L is a lower triangular
+ *     matrix with all 1's on the diagonal, and U is an upper
+ *     triangular matrix, then the upper triangular part of A
+ *     (including its diagonal) contains U and the strictly lower
+ *     triangular part of A contains the multipliers, I-L.
+ *
+ * bandGBTRF returns 0 if successful. Otherwise it encountered a zero
+ * diagonal element during the factorization. In this case it
+ * returns the column index (numbered from one) at which it
+ * encountered the zero.
+ *
+ * IMPORTANT NOTE: Suppose A is a band matrix with upper
+ * bandwidth mu and lower bandwidth ml, then the upper triangular
+ * factor U can have upper bandwidth as big as MIN(n-1,mu+ml)
+ * because of partial pivoting. The lower triangular factor L has
+ * lower bandwidth ml. Thus, if A is to be factored and
+ * backsolved using bandGBTRF and bandGBTRS, then it should be allocated
+ * as a = bandalloc(n,smu,ml), where smu = MIN(n-1,mu+ml). The
+ * call to bandGBTRF is ier = bandGBTRF(a,n,mu,ml,smu,p). The
+ * corresponding call to bandGBTRS is bandGBTRS(a,n,smu,ml,p,b). The user 
+ * does not need to zero the "extra" storage allocated for the 
+ * purpose of factorization. This is handled by the bandGBTRF routine. 
+ * If A is not going to be factored and backsolved, then it can be
+ * allocated as a = bandalloc(n,smu,ml). In either case, all
+ * routines in this section use the parameter name smu for a
+ * parameter which must be the "storage upper bandwidth" which
+ * was passed to bandalloc.
+ * -----------------------------------------------------------------
+ */
+
+long int bandGBTRF(realtype **a, long int n, long int mu, long int ml, 
+                   long int smu, long int *p);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : bandGBTRS
+ * -----------------------------------------------------------------
+ * Usage : realtype *b;
+ *         ier = bandGBTRF(a,n,mu,ml,smu,p);
+ *         if (ier == 0) bandGBTRS(a,n,smu,ml,p,b);
+ * -----------------------------------------------------------------
+ * bandGBTRS(a,n,smu,ml,p,b) solves the n by n linear system
+ * Ax = b, where A is band matrix stored in "a" with storage
+ * upper bandwidth smu and lower bandwidth ml. It assumes that A
+ * has been LU factored and the pivot array p has been set by a
+ * successful call bandGBTRF(a,n,mu,ml,smu,p). The solution x is
+ * written into the b array.
+ * -----------------------------------------------------------------
+ */
+
+void bandGBTRS(realtype **a, long int n, long int smu, 
+               long int ml, long int *p, realtype *b);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : bandzero
+ * -----------------------------------------------------------------
+ * Usage : bandzero(a,n,mu,ml,smu);
+ * -----------------------------------------------------------------
+ * a(i,j) <- 0.0,   0 <= i,j <= n-1, j-mu <= i <= j+ml.
+ * -----------------------------------------------------------------
+ */
+
+void bandzero(realtype **a, long int n, long int mu, 
+              long int ml, long int smu);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : bandcopy
+ * -----------------------------------------------------------------
+ * Usage : bandcopy(a,b,n,a_smu,b_smu,copymu,copyml);
+ * -----------------------------------------------------------------
+ * b(i,j) <- a(i,j), 0 <= i,j <= n-1, j-copymu <= i <= j+copyml.
+ * -----------------------------------------------------------------
+ */
+
+void bandcopy(realtype **a, realtype **b, long int n, 
+              long int a_smu, long int b_smu,
+              long int copymu, long int copyml);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : bandscale
+ * -----------------------------------------------------------------
+ * Usage : bandscale(c,a,n,mu,ml);
+ * -----------------------------------------------------------------
+ * a(i,j) <- c*a(i,j),   0 <= i,j <= n-1, j-mu <= i <= j+ml.
+ * -----------------------------------------------------------------
+ */
+
+void bandscale(realtype c, realtype **a, long int n, 
+               long int mu, long int ml, long int smu);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : bandaddI
+ * -----------------------------------------------------------------
+ * Usage : bandaddI(a,n,smu);
+ * -----------------------------------------------------------------
+ * a(j,j) <- a(j,j)+1.0,   0 <= j <= n-1.
+ * -----------------------------------------------------------------
+ */
+
+void bandaddI(realtype **a, long int n, long int smu);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : bandfreepiv
+ * -----------------------------------------------------------------
+ * Usage : bandfreepiv(p);
+ * -----------------------------------------------------------------
+ * bandfreepiv(p) frees the pivot array p allocated by
+ * bandallocpiv.
+ * -----------------------------------------------------------------
+ */
+
+void bandfreepiv(long int *p);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : bandfree
+ * -----------------------------------------------------------------
+ * Usage : bandfree(a);
+ * -----------------------------------------------------------------
+ * bandfree(a) frees the band matrix a allocated by bandalloc.
+ * -----------------------------------------------------------------
+ */
+
+void bandfree(realtype **a);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : bandprint
+ * -----------------------------------------------------------------
+ * Usage : bandprint(a,n,mu,ml,smu);
+ * -----------------------------------------------------------------
+ * bandprint(a,n,mu,ml,smu) prints the n by n band matrix stored
+ * in a (with upper bandwidth mu and lower bandwidth ml) to
+ * standard output as it would normally appear on paper. It is
+ * intended as a debugging tool with small values of n. The
+ * elements are printed using the %g/lg/Lg option. A blank line
+ * is printed before and after the matrix.
+ * -----------------------------------------------------------------
+ */
+
+void bandprint(realtype **a, long int n, long int mu, long int ml, 
+               long int smu);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_config.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_config.h
new file mode 100644
index 0000000000000000000000000000000000000000..518483b0fa13b104f37d7926882549dbe0f6fe61
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_config.h
@@ -0,0 +1,2 @@
+#define SUNDIALS_DOUBLE_PRECISION
+#define SUNDIALS_USE_GENERIC_MATH
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_dense.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_dense.h
new file mode 100644
index 0000000000000000000000000000000000000000..a5d975b3fe4b5fca6a8784be5528a970bff711ea
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_dense.h
@@ -0,0 +1,313 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * -----------------------------------------------------------------
+ * Programmer: Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2006, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the header file for a generic package of DENSE matrix
+ * operations.  The routines listed in this file all use type
+ * DenseMat, defined below, for M by N matrices.
+ * These routines in turn call routines in the smalldense module,
+ * which use the type realtype** for matrices. This separation allows
+ * for possible modifications in which matrices of type DenseMat
+ * may not be stored contiguously, while small matrices can still
+ * be treated with the routines in smalldense.
+ *
+ * Routines that work with the type DenseMat begin with "Dense".
+ * The DenseAllocMat function allocates a dense matrix for use in
+ * the other DenseMat routines listed in this file. Matrix
+ * storage details are given in the documentation for the type
+ * DenseMat. The DenseAllocPiv function allocates memory for
+ * pivot information. The storage allocated by DenseAllocMat and
+ * DenseAllocPiv is deallocated by the routines DenseFreeMat and
+ * DenseFreePiv, respectively. The DenseGETRF and DenseGETRS
+ * routines perform the actual solution of a dense linear system.
+ *
+ * Routines that work with realtype** begin with "den". 
+ * The underlying matrix storage is described in the documentation 
+ * for denalloc in smalldense.h
+ * -----------------------------------------------------------------
+ */
+
+#ifndef _DENSE_H
+#define _DENSE_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#include <sundials/sundials_types.h>
+#include <sundials/sundials_smalldense.h>
+
+  /*
+   * ==================================================================
+   * Type definitions
+   * ==================================================================
+   */
+
+  /*
+   * -----------------------------------------------------------------
+   * Type : DenseMat
+   * -----------------------------------------------------------------
+   * The type DenseMat is defined to be a pointer to a structure
+   * with sizes (M and N) and a data field. The M and N fields 
+   * indicates the number of rows and columns, respectively of a dense 
+   * matrix, while the data field is a two dimensional array used for 
+   * component storage. The elements of a dense matrix are stored 
+   * columnwise (i.e columns are stored one on top of the other in 
+   * memory). If A is of type DenseMat, then the (i,j)th element 
+   * of A (with 0 <= i < M and 0 <= j < N) is given by the expression 
+   * (A->data)[j][i] or by the expression (A->data)[0][j*n+i]. 
+   * The macros below allow a user to access efficiently individual
+   * matrix elements without writing out explicit data structure
+   * references and without knowing too much about the underlying
+   * element storage. The only storage assumption needed is that
+   * elements are stored columnwise and that a pointer to the jth
+   * column of elements can be obtained via the DENSE_COL macro.
+   * Users should use these macros whenever possible.
+   * -----------------------------------------------------------------
+   */
+
+  typedef struct _DenseMat {
+    long int M;
+    long int N;
+    realtype **data;
+  } *DenseMat;
+
+  /*
+   * ==================================================================
+   * Data accessor macros
+   * ==================================================================
+   */
+
+  /*
+   * -----------------------------------------------------------------
+   * Macro : DENSE_ELEM
+   * -----------------------------------------------------------------
+   * Usage : DENSE_ELEM(A,i,j) = a_ij;  OR
+   *         a_ij = DENSE_ELEM(A,i,j);
+   * -----------------------------------------------------------------
+   * DENSE_ELEM(A,i,j) references the (i,j)th element of the M by N
+   * DenseMat A, 0 <= i < M ; 0 <= j < N.
+   * -----------------------------------------------------------------
+   */
+
+#define DENSE_ELEM(A,i,j) ((A->data)[j][i])
+
+  /*
+   * -----------------------------------------------------------------
+   * Macro : DENSE_COL
+   * -----------------------------------------------------------------
+   * Usage : col_j = DENSE_COL(A,j);
+   * -----------------------------------------------------------------
+   * DENSE_COL(A,j) references the jth column of the M by N
+   * DenseMat A, 0 <= j < N. The type of the expression DENSE_COL(A,j) 
+   * is (realtype *). After the assignment in the usage above, col_j 
+   * may be treated as an array indexed from 0 to M-1. 
+   * The (i,j)-th element of A is thus referenced by col_j[i].
+   * -----------------------------------------------------------------
+   */
+
+#define DENSE_COL(A,j) ((A->data)[j])
+
+  /*
+   * ==================================================================
+   * Function prototypes
+   * ==================================================================
+   */
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : DenseAllocMat
+   * -----------------------------------------------------------------
+   * Usage : A = DenseAllocMat(M, N);
+   *         if (A == NULL) ... memory request failed
+   * -----------------------------------------------------------------
+   * DenseAllocMat allocates memory for an M by N dense matrix and
+   * returns the storage allocated (type DenseMat). DenseAllocMat
+   * returns NULL if the request for matrix storage cannot be
+   * satisfied. See the above documentation for the type DenseMat
+   * for matrix storage details.
+   * -----------------------------------------------------------------
+   */
+
+  DenseMat DenseAllocMat(long int M, long int N);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : DenseAllocPiv
+   * -----------------------------------------------------------------
+   * Usage : p = DenseAllocPiv(N);
+   *         if (p == NULL) ... memory request failed
+   * -----------------------------------------------------------------
+   * DenseAllocPiv allocates memory for pivot information to be
+   * filled in by the DenseGETRF routine during the factorization
+   * of an N by N dense matrix. The underlying type for pivot
+   * information is an array of N integers and this routine returns
+   * the pointer to the memory it allocates. If the request for
+   * pivot storage cannot be satisfied, DenseAllocPiv returns NULL.
+   * -----------------------------------------------------------------
+   */
+
+  long int *DenseAllocPiv(long int N);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : DenseGETRF
+   * -----------------------------------------------------------------
+   * Usage : ier = DenseGETRF(A, p);
+   *         if (ier != 0) ... A is singular
+   * -----------------------------------------------------------------
+   * DenseGETRF performs the LU factorization of the M by N dense
+   * matrix A. This is done using standard Gaussian elimination
+   * with partial (row) pivoting. Note that this applies only
+   * to matrices with M >= N and full column rank.
+   *
+   * A successful LU factorization leaves the matrix A and the
+   * pivot array p with the following information:
+   *
+   * (1) p[k] contains the row number of the pivot element chosen
+   *     at the beginning of elimination step k, k=0, 1, ..., N-1.
+   *
+   * (2) If the unique LU factorization of A is given by PA = LU,
+   *     where P is a permutation matrix, L is a lower trapezoidal
+   *     matrix with all 1's on the diagonal, and U is an upper
+   *     triangular matrix, then the upper triangular part of A
+   *     (including its diagonal) contains U and the strictly lower
+   *     trapezoidal part of A contains the multipliers, I-L.
+   *
+   * For square matrices (M=N), L is unit lower triangular.
+   *
+   * DenseGETRF returns 0 if successful. Otherwise it encountered
+   * a zero diagonal element during the factorization. In this case
+   * it returns the column index (numbered from one) at which
+   * it encountered the zero.
+   * -----------------------------------------------------------------
+   */
+
+  long int DenseGETRF(DenseMat A, long int *p);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : DenseGETRS
+   * -----------------------------------------------------------------
+   * Usage : DenseGETRS(A, p, b);
+   * -----------------------------------------------------------------
+   * DenseGETRS solves the N-dimensional system A x = b using
+   * the LU factorization in A and the pivot information in p
+   * computed in DenseGETRF. The solution x is returned in b. This
+   * routine cannot fail if the corresponding call to DenseGETRF
+   * did not fail.
+   * DenseGETRS does NOT check for a square matrix!
+   * -----------------------------------------------------------------
+   */
+
+  void DenseGETRS(DenseMat A, long int *p, realtype *b);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : DenseZero
+   * -----------------------------------------------------------------
+   * Usage : DenseZero(A);
+   * -----------------------------------------------------------------
+   * DenseZero sets all the elements of the M by N matrix A to 0.0.
+   * -----------------------------------------------------------------
+   */
+
+  void DenseZero(DenseMat A);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : DenseCopy
+   * -----------------------------------------------------------------
+   * Usage : DenseCopy(A, B);
+   * -----------------------------------------------------------------
+   * DenseCopy copies the contents of the M by N matrix A into the
+   * M by N matrix B.
+   * -----------------------------------------------------------------
+   */
+
+  void DenseCopy(DenseMat A, DenseMat B);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function: DenseScale
+   * -----------------------------------------------------------------
+   * Usage : DenseScale(c, A);
+   * -----------------------------------------------------------------
+   * DenseScale scales the elements of the M by N matrix A by the
+   * constant c and stores the result back in A.
+   * -----------------------------------------------------------------
+   */
+
+  void DenseScale(realtype c, DenseMat A);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : DenseAddI
+   * -----------------------------------------------------------------
+   * Usage : DenseAddI(A);
+   * -----------------------------------------------------------------
+   * DenseAddI adds 1.0 to the main diagonal (A_ii, i=1,2,...,N-1) of
+   * the M by N matrix A (M >= N) and stores the result back in A.
+   * DenseAddI is typically used with square matrices.
+   * DenseAddI does not check for M >= N and therefore a segmentation
+   * fault will occur if M < N!
+   * -----------------------------------------------------------------
+   */
+
+  void DenseAddI(DenseMat A);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : DenseFreeMat
+   * -----------------------------------------------------------------
+   * Usage : DenseFreeMat(A);
+   * -----------------------------------------------------------------
+   * DenseFreeMat frees the memory allocated by DenseAllocMat for
+   * the M by N matrix A.
+   * -----------------------------------------------------------------
+   */
+
+  void DenseFreeMat(DenseMat A);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : DenseFreePiv
+   * -----------------------------------------------------------------
+   * Usage : DenseFreePiv(p);
+   * -----------------------------------------------------------------
+   * DenseFreePiv frees the memory allocated by DenseAllocPiv for
+   * the pivot information array p.
+   * -----------------------------------------------------------------
+   */
+
+  void DenseFreePiv(long int *p);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : DensePrint
+   * -----------------------------------------------------------------
+   * Usage : DensePrint(A);
+   * -----------------------------------------------------------------
+   * This routine prints the M by N dense matrix A to standard output
+   * as it would normally appear on paper. It is intended as a 
+   * debugging tool with small values of M and N. The elements are
+   * printed using the %g/%lg/%Lg option. A blank line is printed
+   * before and after the matrix.
+   * -----------------------------------------------------------------
+   */
+
+  void DensePrint(DenseMat A);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_fnvector.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_fnvector.h
new file mode 100644
index 0000000000000000000000000000000000000000..335337fc985164b28b5e280c0c96377fa31fa76d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_fnvector.h
@@ -0,0 +1,41 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Radu Serban and Aaron Collier @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2002, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This file (companion of nvector.h) contains definitions 
+ * needed for the initialization of vector operations in Fortran.
+ * -----------------------------------------------------------------
+ */
+
+
+#ifndef _FNVECTOR_H
+#define _FNVECTOR_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#ifndef _SUNDIALS_CONFIG_H
+#define _SUNDIALS_CONFIG_H
+#include <sundials/sundials_config.h>
+#endif
+
+/* SUNDIALS solver IDs */
+
+#define FCMIX_CVODE   1
+#define FCMIX_IDA     2
+#define FCMIX_KINSOL  3
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_iterative.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_iterative.h
new file mode 100644
index 0000000000000000000000000000000000000000..0ed0b5c0f6e45dad2e6d9a98dabc263f6bf571cb
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_iterative.h
@@ -0,0 +1,242 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Scott D. Cohen and Alan C. Hindmarsh @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2002, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This header file contains declarations intended for use by
+ * generic iterative solvers of Ax = b. The enumeration gives
+ * symbolic names for the type  of preconditioning to be used.
+ * The function type declarations give the prototypes for the
+ * functions to be called within an iterative linear solver, that
+ * are responsible for
+ *    multiplying A by a given vector v (ATimesFn), and
+ *    solving the preconditioner equation Pz = r (PSolveFn).
+ * -----------------------------------------------------------------
+ */
+
+#ifndef _ITERATIVE_H
+#define _ITERATIVE_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#include <sundials/sundials_nvector.h>
+
+
+/*
+ * -----------------------------------------------------------------
+ * enum : types of preconditioning                                
+ * -----------------------------------------------------------------
+ * PREC_NONE  : The iterative linear solver should not use             
+ *              preconditioning.                                       
+ *                                                                
+ * PREC_LEFT  : The iterative linear solver uses preconditioning on    
+ *              the left only.                                         
+ *                                                                
+ * PREC_RIGHT : The iterative linear solver uses preconditioning on    
+ *              the right only.                                        
+ *                                                                
+ * PREC_BOTH  : The iterative linear solver uses preconditioning on    
+ *              both the left and the right.                           
+ * -----------------------------------------------------------------
+ */
+
+enum { PREC_NONE, PREC_LEFT, PREC_RIGHT, PREC_BOTH };
+
+/*
+ * -----------------------------------------------------------------
+ * enum : types of Gram-Schmidt routines                          
+ * -----------------------------------------------------------------
+ * MODIFIED_GS  : The iterative solver uses the modified          
+ *                Gram-Schmidt routine ModifiedGS listed in this  
+ *                file.                                           
+ *                                                                
+ * CLASSICAL_GS : The iterative solver uses the classical         
+ *                Gram-Schmidt routine ClassicalGS listed in this 
+ *                file.                                           
+ * -----------------------------------------------------------------
+ */
+
+enum { MODIFIED_GS = 1, CLASSICAL_GS = 2 };
+
+/*
+ * -----------------------------------------------------------------
+ * Type: ATimesFn                                                 
+ * -----------------------------------------------------------------
+ * An ATimesFn multiplies Av and stores the result in z. The      
+ * caller is responsible for allocating memory for the z vector.  
+ * The parameter A_data is a pointer to any information about A   
+ * which the function needs in order to do its job. The vector v  
+ * is unchanged. An ATimesFn returns 0 if successful and a        
+ * non-zero value if unsuccessful.                                
+ * -----------------------------------------------------------------
+ */
+
+typedef int (*ATimesFn)(void *A_data, N_Vector v, N_Vector z);
+
+/*
+ * -----------------------------------------------------------------
+ * Type: PSolveFn                                                 
+ * -----------------------------------------------------------------
+ * A PSolveFn solves the preconditioner equation Pz = r for the   
+ * vector z. The caller is responsible for allocating memory for  
+ * the z vector. The parameter P_data is a pointer to any         
+ * information about P which the function needs in order to do    
+ * its job. The parameter lr is input, and indicates whether P    
+ * is to be taken as the left preconditioner or the right         
+ * preconditioner: lr = 1 for left and lr = 2 for right.          
+ * If preconditioning is on one side only, lr can be ignored.     
+ * The vector r is unchanged.                                     
+ * A PSolveFn returns 0 if successful and a non-zero value if     
+ * unsuccessful.  On a failure, a negative return value indicates 
+ * an unrecoverable condition, while a positive value indicates   
+ * a recoverable one, in which the calling routine may reattempt  
+ * the solution after updating preconditioner data.               
+ * -----------------------------------------------------------------
+ */
+
+typedef int (*PSolveFn)(void *P_data, N_Vector r, N_Vector z, int lr);
+
+/*
+ * -----------------------------------------------------------------
+ * Function: ModifiedGS                                           
+ * -----------------------------------------------------------------
+ * ModifiedGS performs a modified Gram-Schmidt orthogonalization  
+ * of the N_Vector v[k] against the p unit N_Vectors at           
+ * v[k-1], v[k-2], ..., v[k-p].                                   
+ *                                                                
+ * v is an array of (k+1) N_Vectors v[i], i=0, 1, ..., k.         
+ * v[k-1], v[k-2], ..., v[k-p] are assumed to have L2-norm        
+ * equal to 1.                                                    
+ *                                                                
+ * h is the output k by k Hessenberg matrix of inner products.    
+ * This matrix must be allocated row-wise so that the (i,j)th     
+ * entry is h[i][j]. The inner products (v[i],v[k]),              
+ * i=i0, i0+1, ..., k-1, are stored at h[i][k-1]. Here            
+ * i0=MAX(0,k-p).                                                 
+ *                                                                
+ * k is the index of the vector in the v array that needs to be   
+ * orthogonalized against previous vectors in the v array.        
+ *                                                                
+ * p is the number of previous vectors in the v array against     
+ * which v[k] is to be orthogonalized.                            
+ *                                                                
+ * new_vk_norm is a pointer to memory allocated by the caller to  
+ * hold the Euclidean norm of the orthogonalized vector v[k].     
+ *                                                                
+ * If (k-p) < 0, then ModifiedGS uses p=k. The orthogonalized     
+ * v[k] is NOT normalized and is stored over the old v[k]. Once   
+ * the orthogonalization has been performed, the Euclidean norm   
+ * of v[k] is stored in (*new_vk_norm).                           
+ *                                                                
+ * ModifiedGS returns 0 to indicate success. It cannot fail.      
+ * -----------------------------------------------------------------
+ */                                                                
+
+int ModifiedGS(N_Vector *v, realtype **h, int k, int p, 
+               realtype *new_vk_norm);
+
+/*
+ * -----------------------------------------------------------------
+ * Function: ClassicalGS                                          
+ * -----------------------------------------------------------------
+ * ClassicalGS performs a classical Gram-Schmidt                  
+ * orthogonalization of the N_Vector v[k] against the p unit      
+ * N_Vectors at v[k-1], v[k-2], ..., v[k-p]. The parameters v, h, 
+ * k, p, and new_vk_norm are as described in the documentation    
+ * for ModifiedGS.                                                
+ *                                                                
+ * temp is an N_Vector which can be used as workspace by the      
+ * ClassicalGS routine.                                           
+ *                                                                
+ * s is a length k array of realtype which can be used as         
+ * workspace by the ClassicalGS routine.                          
+ *
+ * ClassicalGS returns 0 to indicate success. It cannot fail.     
+ * -----------------------------------------------------------------
+ */
+
+int ClassicalGS(N_Vector *v, realtype **h, int k, int p, 
+                realtype *new_vk_norm, N_Vector temp, realtype *s);
+
+/*
+ * -----------------------------------------------------------------
+ * Function: QRfact                                               
+ * -----------------------------------------------------------------
+ * QRfact performs a QR factorization of the Hessenberg matrix H. 
+ *                                                                
+ * n is the problem size; the matrix H is (n+1) by n.             
+ *                                                                
+ * h is the (n+1) by n Hessenberg matrix H to be factored. It is  
+ * stored row-wise.                                               
+ *                                                                
+ * q is an array of length 2*n containing the Givens rotations    
+ * computed by this function. A Givens rotation has the form:     
+ * | c  -s |                                                      
+ * | s   c |.                                                     
+ * The components of the Givens rotations are stored in q as      
+ * (c, s, c, s, ..., c, s).                                       
+ *                                                                
+ * job is a control flag. If job==0, then a new QR factorization  
+ * is performed. If job!=0, then it is assumed that the first     
+ * n-1 columns of h have already been factored and only the last  
+ * column needs to be updated.                                    
+ *                                                                
+ * QRfact returns 0 if successful. If a zero is encountered on    
+ * the diagonal of the triangular factor R, then QRfact returns   
+ * the equation number of the zero entry, where the equations are 
+ * numbered from 1, not 0. If QRsol is subsequently called in     
+ * this situation, it will return an error because it could not   
+ * divide by the zero diagonal entry.                             
+ * -----------------------------------------------------------------
+ */                                                                
+
+int QRfact(int n, realtype **h, realtype *q, int job);
+
+/*                                                                
+ * -----------------------------------------------------------------
+ * Function: QRsol                                                
+ * -----------------------------------------------------------------
+ * QRsol solves the linear least squares problem                  
+ *                                                                
+ * min (b - H*x, b - H*x), x in R^n,                              
+ *                                                                
+ * where H is a Hessenberg matrix, and b is in R^(n+1).           
+ * It uses the QR factors of H computed by QRfact.                
+ *                                                                
+ * n is the problem size; the matrix H is (n+1) by n.             
+ *                                                                
+ * h is a matrix (computed by QRfact) containing the upper        
+ * triangular factor R of the original Hessenberg matrix H.       
+ *                                                                
+ * q is an array of length 2*n (computed by QRfact) containing    
+ * the Givens rotations used to factor H.                         
+ *                                                                
+ * b is the (n+1)-vector appearing in the least squares problem   
+ * above.                                                         
+ *                                                                
+ * On return, b contains the solution x of the least squares      
+ * problem, if QRsol was successful.                              
+ *                                                                
+ * QRsol returns a 0 if successful.  Otherwise, a zero was        
+ * encountered on the diagonal of the triangular factor R.        
+ * In this case, QRsol returns the equation number (numbered      
+ * from 1, not 0) of the zero entry.                              
+ * -----------------------------------------------------------------
+ */                                                                
+
+int QRsol(int n, realtype **h, realtype *q, realtype *b);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_math.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_math.h
new file mode 100644
index 0000000000000000000000000000000000000000..34c2f5ba56e4b1ef26cd5ef4448dce15b73a7c82
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_math.h
@@ -0,0 +1,139 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * -----------------------------------------------------------------
+ * Programmer(s): Scott D. Cohen, Alan C. Hindmarsh and
+ *                Aaron Collier @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2002, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the header file for a simple C-language math library. The
+ * routines listed here work with the type realtype as defined in
+ * the header file sundials_types.h.
+ * -----------------------------------------------------------------
+ */
+
+#ifndef _SUNDIALSMATH_H
+#define _SUNDIALSMATH_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#include <sundials/sundials_types.h>
+
+/*
+ * -----------------------------------------------------------------
+ * Macros : MIN and MAX
+ * -----------------------------------------------------------------
+ * MIN(A,B) returns the minimum of A and B
+ *
+ * MAX(A,B) returns the maximum of A and B
+ *
+ * SQR(A) returns A^2
+ * -----------------------------------------------------------------
+ */
+
+#ifndef MIN
+#define MIN(A, B) ((A) < (B) ? (A) : (B))
+#endif
+
+#ifndef MAX
+#define MAX(A, B) ((A) > (B) ? (A) : (B))
+#endif
+
+#ifndef SQR
+#define SQR(A) ((A)*(A))
+#endif
+
+#ifndef ABS
+#define ABS RAbs
+#endif
+
+#ifndef SQRT
+#define SQRT RSqrt
+#endif
+
+#ifndef EXP
+#define EXP RExp
+#endif
+
+/*
+ * -----------------------------------------------------------------
+ * Function : RPowerI
+ * -----------------------------------------------------------------
+ * Usage : int exponent;
+ *         realtype base, ans;
+ *         ans = RPowerI(base,exponent);
+ * -----------------------------------------------------------------
+ * RPowerI returns the value of base^exponent, where base is of type
+ * realtype and exponent is of type int.
+ * -----------------------------------------------------------------
+ */
+
+realtype RPowerI(realtype base, int exponent);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : RPowerR
+ * -----------------------------------------------------------------
+ * Usage : realtype base, exponent, ans;
+ *         ans = RPowerR(base,exponent);
+ * -----------------------------------------------------------------
+ * RPowerR returns the value of base^exponent, where both base and
+ * exponent are of type realtype. If base < ZERO, then RPowerR
+ * returns ZERO.
+ * -----------------------------------------------------------------
+ */
+
+realtype RPowerR(realtype base, realtype exponent);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : RSqrt
+ * -----------------------------------------------------------------
+ * Usage : realtype sqrt_x;
+ *         sqrt_x = RSqrt(x);
+ * -----------------------------------------------------------------
+ * RSqrt(x) returns the square root of x. If x < ZERO, then RSqrt
+ * returns ZERO.
+ * -----------------------------------------------------------------
+ */
+
+realtype RSqrt(realtype x);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : RAbs (a.k.a. ABS)
+ * -----------------------------------------------------------------
+ * Usage : realtype abs_x;
+ *         abs_x = RAbs(x);
+ * -----------------------------------------------------------------
+ * RAbs(x) returns the absolute value of x.
+ * -----------------------------------------------------------------
+ */
+
+realtype RAbs(realtype x);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : RExp (a.k.a. EXP)
+ * -----------------------------------------------------------------
+ * Usage : realtype exp_x;
+ *         exp_x = RExp(x);
+ * -----------------------------------------------------------------
+ * RExp(x) returns e^x (base-e exponential function).
+ * -----------------------------------------------------------------
+ */
+
+realtype RExp(realtype x);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_nvector.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_nvector.h
new file mode 100644
index 0000000000000000000000000000000000000000..fcf685008f7f39c78c64af44f83a97cf61d79c34
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_nvector.h
@@ -0,0 +1,373 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Radu Serban and Aaron Collier @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2002, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the header file for a generic NVECTOR package.
+ * It defines the N_Vector structure (_generic_N_Vector) which
+ * contains the following fields:
+ *   - an implementation-dependent 'content' field which contains
+ *     the description and actual data of the vector
+ *   - an 'ops' filed which contains a structure listing operations
+ *     acting on such vectors
+ *
+ * Part I of this file contains type declarations for the
+ * _generic_N_Vector and _generic_N_Vector_Ops structures, as well
+ * as references to pointers to such structures (N_Vector).
+ *
+ * Part II of this file contains the prototypes for the vector
+ * functions which operate on N_Vector.
+ *
+ * At a minimum, a particular implementation of an NVECTOR must
+ * do the following:
+ *  - specify the 'content' field of N_Vector,
+ *  - implement the operations on those N_Vectors,
+ *  - provide a constructor routine for new vectors
+ *
+ * Additionally, an NVECTOR implementation may provide the following:
+ *  - macros to access the underlying N_Vector data
+ *  - a constructor for an array of N_Vectors
+ *  - a constructor for an empty N_Vector (i.e., a new N_Vector with
+ *    a NULL data pointer).
+ *  - a routine to print the content of an N_Vector
+ * -----------------------------------------------------------------
+ */
+
+#ifndef _NVECTOR_H
+#define _NVECTOR_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#include <sundials/sundials_types.h>
+
+/*
+ * -----------------------------------------------------------------
+ * Generic definition of N_Vector
+ * -----------------------------------------------------------------
+ */
+
+/* Forward reference for pointer to N_Vector_Ops object */
+typedef struct _generic_N_Vector_Ops *N_Vector_Ops;
+
+/* Forward reference for pointer to N_Vector object */
+typedef struct _generic_N_Vector *N_Vector;
+
+/* Define array of N_Vectors */
+typedef N_Vector *N_Vector_S;
+
+/* Structure containing function pointers to vector operations  */  
+struct _generic_N_Vector_Ops {
+  N_Vector    (*nvclone)(N_Vector);
+  N_Vector    (*nvcloneempty)(N_Vector);
+  void        (*nvdestroy)(N_Vector);
+  void        (*nvspace)(N_Vector, long int *, long int *);
+  realtype*   (*nvgetarraypointer)(N_Vector);
+  void        (*nvsetarraypointer)(realtype *, N_Vector);
+  void        (*nvlinearsum)(realtype, N_Vector, realtype, N_Vector, N_Vector); 
+  void        (*nvconst)(realtype, N_Vector);
+  void        (*nvprod)(N_Vector, N_Vector, N_Vector);
+  void        (*nvdiv)(N_Vector, N_Vector, N_Vector);
+  void        (*nvscale)(realtype, N_Vector, N_Vector);
+  void        (*nvabs)(N_Vector, N_Vector);
+  void        (*nvinv)(N_Vector, N_Vector);
+  void        (*nvaddconst)(N_Vector, realtype, N_Vector);
+  realtype    (*nvdotprod)(N_Vector, N_Vector);
+  realtype    (*nvmaxnorm)(N_Vector);
+  realtype    (*nvwrmsnorm)(N_Vector, N_Vector);
+  realtype    (*nvwrmsnormmask)(N_Vector, N_Vector, N_Vector);
+  realtype    (*nvmin)(N_Vector);
+  realtype    (*nvwl2norm)(N_Vector, N_Vector);
+  realtype    (*nvl1norm)(N_Vector);
+  void        (*nvcompare)(realtype, N_Vector, N_Vector);
+  booleantype (*nvinvtest)(N_Vector, N_Vector);
+  booleantype (*nvconstrmask)(N_Vector, N_Vector, N_Vector);
+  realtype    (*nvminquotient)(N_Vector, N_Vector);
+};
+
+/*
+ * -----------------------------------------------------------------
+ * A vector is a structure with an implementation-dependent
+ * 'content' field, and a pointer to a structure of vector
+ * operations corresponding to that implementation.
+ * -----------------------------------------------------------------
+ */
+
+struct _generic_N_Vector {
+  void *content;
+  struct _generic_N_Vector_Ops *ops;
+};
+  
+/*
+ * -----------------------------------------------------------------
+ * Functions exported by NVECTOR module
+ * -----------------------------------------------------------------
+ */
+
+/*
+ * -----------------------------------------------------------------
+ * N_VClone
+ *   Creates a new vector of the same type as an existing vector.
+ *   It does not copy the vector, but rather allocates storage for
+ *   the new vector.
+ *
+ * N_VCloneEmpty
+ *   Creates a new vector of the same type as an existing vector,
+ *   but does not allocate storage.
+ *
+ * N_VDestroy
+ *   Destroys a vector created with N_VClone.
+ *
+ * N_VSpace
+ *   Returns space requirements for one N_Vector (type 'realtype' in
+ *   lrw and type 'long int' in liw).
+ *
+ * N_VGetArrayPointer
+ *   Returns a pointer to the data component of the given N_Vector.
+ *   NOTE: This function assumes that the internal data is stored
+ *   as a contiguous 'realtype' array. This routine is only used in
+ *   the solver-specific interfaces to the dense and banded linear
+ *   solvers, as well as the interfaces to  the banded preconditioners
+ *   distributed with SUNDIALS.
+ *   
+ * N_VSetArrayPointer
+ *   Overwrites the data field in the given N_Vector with a user-supplied
+ *   array of type 'realtype'.
+ *   NOTE: This function assumes that the internal data is stored
+ *   as a contiguous 'realtype' array. This routine is only used in
+ *   the interfaces to the dense linear solver.
+ *
+ * N_VLinearSum
+ *   Performs the operation z = a*x + b*y
+ *
+ * N_VConst
+ *   Performs the operation z[i] = c for i = 0, 1, ..., N-1
+ *
+ * N_VProd
+ *   Performs the operation z[i] = x[i]*y[i] for i = 0, 1, ..., N-1
+ *
+ * N_VDiv
+ *   Performs the operation z[i] = x[i]/y[i] for i = 0, 1, ..., N-1
+ *
+ * N_VScale
+ *   Performs the operation z = c*x
+ *
+ * N_VAbs
+ *   Performs the operation z[i] = |x[i]| for i = 0, 1, ..., N-1
+ *
+ * N_VInv
+ *   Performs the operation z[i] = 1/x[i] for i = 0, 1, ..., N-1
+ *   This routine does not check for division by 0. It should be
+ *   called only with an N_Vector x which is guaranteed to have
+ *   all non-zero components.
+ *
+ * N_VAddConst
+ *   Performs the operation z[i] = x[i] + b   for i = 0, 1, ..., N-1
+ *
+ * N_VDotProd
+ *   Returns the dot product of two vectors:
+ *         sum (i = 0 to N-1) {x[i]*y[i]}
+ *
+ * N_VMaxNorm
+ *   Returns the maximum norm of x:
+ *         max (i = 0 to N-1) ABS(x[i])
+ *
+ * N_VWrmsNorm
+ *   Returns the weighted root mean square norm of x with weight 
+ *   vector w:
+ *         sqrt [(sum (i = 0 to N-1) {(x[i]*w[i])^2})/N]
+ *
+ * N_VWrmsNormMask
+ *   Returns the weighted root mean square norm of x with weight
+ *   vector w, masked by the elements of id:
+ *         sqrt [(sum (i = 0 to N-1) {(x[i]*w[i]*msk[i])^2})/N]
+ *   where msk[i] = 1.0 if id[i] > 0 and
+ *         msk[i] = 0.0 if id[i] < 0
+ *
+ * N_VMin
+ *   Returns the smallest element of x:
+ *         min (i = 0 to N-1) x[i]
+ *
+ * N_VWL2Norm
+ *   Returns the weighted Euclidean L2 norm of x with weight 
+ *   vector w:
+ *         sqrt [(sum (i = 0 to N-1) {(x[i]*w[i])^2})]
+ *
+ * N_VL1Norm
+ *   Returns the L1 norm of x:
+ *         sum (i = 0 to N-1) {ABS(x[i])}
+ *
+ * N_VCompare
+ *   Performs the operation
+ *          z[i] = 1.0 if ABS(x[i]) >= c   i = 0, 1, ..., N-1
+ *                 0.0 otherwise
+ *
+ * N_VInvTest
+ *   Performs the operation z[i] = 1/x[i] with a test for 
+ *   x[i] == 0.0 before inverting x[i].
+ *   This routine returns TRUE if all components of x are non-zero 
+ *   (successful inversion) and returns FALSE otherwise.
+ *
+ * N_VConstrMask
+ *   Performs the operation : 
+ *       m[i] = 1.0 if constraint test fails for x[i]
+ *       m[i] = 0.0 if constraint test passes for x[i]
+ *   where the constraint tests are as follows:
+ *      If c[i] = +2.0, then x[i] must be >  0.0.
+ *      If c[i] = +1.0, then x[i] must be >= 0.0.
+ *      If c[i] = -1.0, then x[i] must be <= 0.0.
+ *      If c[i] = -2.0, then x[i] must be <  0.0.
+ *   This routine returns a boolean FALSE if any element failed
+ *   the constraint test, TRUE if all passed. It also sets a
+ *   mask vector m, with elements equal to 1.0 where the
+ *   corresponding constraint test failed, and equal to 0.0
+ *   where the constraint test passed.
+ *   This routine is specialized in that it is used only for
+ *   constraint checking.
+ *
+ * N_VMinQuotient
+ *   Performs the operation : 
+ *       minq  = min ( num[i]/denom[i]) over all i such that   
+ *       denom[i] != 0.
+ *   This routine returns the minimum of the quotients obtained
+ *   by term-wise dividing num[i] by denom[i]. A zero element
+ *   in denom will be skipped. If no such quotients are found,
+ *   then the large value BIG_REAL is returned.
+ *
+ * -----------------------------------------------------------------
+ *
+ * The following table lists the vector functions used by
+ * different modules in SUNDIALS. The symbols in the table
+ * have the following meaning:
+ * S    -  called by the solver;
+ * D    -  called by the dense linear solver module
+ * B    -  called by the band linear solver module
+ * Di   -  called by the diagonal linear solver module
+ * I    -  called by the iterative linear solver module
+ * BP   -  called by the band preconditioner module
+ * BBDP -  called by the band-block diagonal preconditioner module
+ * F    -  called by the Fortran-to-C interface
+ *
+ *                  ------------------------------------------------
+ *                                         MODULES                  
+ * NVECTOR          ------------------------------------------------
+ * FUNCTIONS          CVODE/CVODES          IDA             KINSOL    
+ * -----------------------------------------------------------------
+ * N_VClone           S Di I                S I BBDP        S I BBDP
+ * -----------------------------------------------------------------
+ * N_VCloneEmpty      F                     F               F
+ * -----------------------------------------------------------------
+ * N_VDestroy         S Di I                S I BBDP        S I BBDP
+ * -----------------------------------------------------------------
+ * N_VSpace           S                     S               S         
+ * -----------------------------------------------------------------
+ * N_VGetArrayPointer D B BP BBDP F         D B BBDP        BBDP F     
+ * -----------------------------------------------------------------
+ * N_VSetArrayPointer D F                   D               F
+ * -----------------------------------------------------------------
+ * N_VLinearSum       S D Di I              S D I           S I       
+ * -----------------------------------------------------------------
+ * N_VConst           S I                   S I             I       
+ * -----------------------------------------------------------------
+ * N_VProd            S Di I                S I             S I       
+ * -----------------------------------------------------------------
+ * N_VDiv             S Di I                S I             S I
+ * -----------------------------------------------------------------
+ * N_VScale           S D B Di I BP BBDP    S D B I BBDP    S I BBDP  
+ * -----------------------------------------------------------------
+ * N_VAbs             S                     S               S         
+ * -----------------------------------------------------------------
+ * N_VInv             S Di                  S               S         
+ * -----------------------------------------------------------------
+ * N_VAddConst        S Di                  S                        
+ * -----------------------------------------------------------------
+ * N_VDotProd         I                     I               I         
+ * -----------------------------------------------------------------
+ * N_VMaxNorm         S                     S               S         
+ * -----------------------------------------------------------------
+ * N_VWrmsNorm        S D B I BP BBDP       S                         
+ * -----------------------------------------------------------------
+ * N_VWrmsNormMask                          S                         
+ * -----------------------------------------------------------------
+ * N_VMin             S                     S               S         
+ * -----------------------------------------------------------------
+ * N_VWL2Norm                                               S I       
+ * -----------------------------------------------------------------
+ * N_VL1Norm                                                I
+ * -----------------------------------------------------------------
+ * N_VCompare         Di                    S                         
+ * -----------------------------------------------------------------
+ * N_VInvTest         Di                                              
+ * -----------------------------------------------------------------
+ * N_VConstrMask                            S               S         
+ * -----------------------------------------------------------------
+ * N_VMinQuotient                           S               S         
+ * -----------------------------------------------------------------
+ */
+  
+N_Vector N_VClone(N_Vector w);
+N_Vector N_VCloneEmpty(N_Vector w);
+void N_VDestroy(N_Vector v);
+void N_VSpace(N_Vector v, long int *lrw, long int *liw);
+realtype *N_VGetArrayPointer(N_Vector v);
+void N_VSetArrayPointer(realtype *v_data, N_Vector v);
+void N_VLinearSum(realtype a, N_Vector x, realtype b, N_Vector y, N_Vector z);
+void N_VConst(realtype c, N_Vector z);
+void N_VProd(N_Vector x, N_Vector y, N_Vector z);
+void N_VDiv(N_Vector x, N_Vector y, N_Vector z);
+void N_VScale(realtype c, N_Vector x, N_Vector z);
+void N_VAbs(N_Vector x, N_Vector z);
+void N_VInv(N_Vector x, N_Vector z);
+void N_VAddConst(N_Vector x, realtype b, N_Vector z);
+realtype N_VDotProd(N_Vector x, N_Vector y);
+realtype N_VMaxNorm(N_Vector x);
+realtype N_VWrmsNorm(N_Vector x, N_Vector w);
+realtype N_VWrmsNormMask(N_Vector x, N_Vector w, N_Vector id);
+realtype N_VMin(N_Vector x);
+realtype N_VWL2Norm(N_Vector x, N_Vector w);
+realtype N_VL1Norm(N_Vector x);
+void N_VCompare(realtype c, N_Vector x, N_Vector z);
+booleantype N_VInvTest(N_Vector x, N_Vector z);
+booleantype N_VConstrMask(N_Vector c, N_Vector x, N_Vector m);
+realtype N_VMinQuotient(N_Vector num, N_Vector denom);
+
+/*
+ * -----------------------------------------------------------------
+ * Additional functions exported by NVECTOR module
+ * -----------------------------------------------------------------
+ */
+
+/*
+ * -----------------------------------------------------------------
+ * N_VCloneEmptyVectorArray
+ *   Creates (by cloning 'w') an array of 'count' empty N_Vectors 
+ *
+ * N_VCloneVectorArray
+ *   Creates (by cloning 'w') an array of 'count' N_Vectors 
+ *
+ * N_VDestroyVectorArray
+ *   Frees memory for an array of 'count' N_Vectors that was
+ *   created by a call to N_VCloneVectorArray
+ *
+ * These functions are used by the SPGMR iterative linear solver 
+ * module and by the CVODES and IDAS solvers.
+ * -----------------------------------------------------------------
+ */
+
+N_Vector *N_VCloneEmptyVectorArray(int count, N_Vector w);
+N_Vector *N_VCloneVectorArray(int count, N_Vector w);
+void N_VDestroyVectorArray(N_Vector *vs, int count);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_smalldense.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_smalldense.h
new file mode 100644
index 0000000000000000000000000000000000000000..fbfd4d87a23fc83fdfebd0c059a6cfc4fe4b9ef2
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_smalldense.h
@@ -0,0 +1,222 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * -----------------------------------------------------------------
+ * Programmer: Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2006, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the header file for a generic DENSE linear solver
+ * package, intended for small m by n dense matrices, with m<=n.
+ * These routines use the type realtype** for dense matrix arguments.
+ * -----------------------------------------------------------------
+ */
+
+#ifndef _SMALLDENSE_H
+#define _SMALLDENSE_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#include <sundials/sundials_types.h>
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : denalloc
+   * -----------------------------------------------------------------
+   * Usage : realtype **a;
+   *         a = denalloc(m, n);
+   *         if (a == NULL) ... memory request failed
+   * -----------------------------------------------------------------
+   * denalloc(m, n) allocates storage for an m by n dense matrix.
+   * It returns a pointer to the newly allocated storage if successful. 
+   * If the memory request cannot be satisfied, then denalloc returns 
+   * NULL. The underlying type of the dense matrix returned is a double
+   * pointer to realtype. If we allocate a dense matrix a by 
+   * a = denalloc(m, n), then a[j][i] references the (i,j)-th element 
+   * of the matrix a, 0 <= i < m, 0 <= j < n,  and a[j] is a pointer 
+   * to the first element in the jth column of a. The location a[0] 
+   * contains a pointer to m*n contiguous locations which contain the 
+   * elements of a.
+   * -----------------------------------------------------------------
+   */
+
+  realtype **denalloc(long int m, long int n);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : denallocpiv
+   * -----------------------------------------------------------------
+   * Usage : long int *pivot;
+   *         pivot = denallocpiv(n);
+   *         if (pivot == NULL) ... memory request failed
+   * -----------------------------------------------------------------
+   * denallocpiv(n) allocates an array of n long int. It returns
+   * a pointer to the first element in the array if successful.
+   * It returns NULL if the memory request could not be satisfied.
+   * -----------------------------------------------------------------
+   */
+
+  long int *denallocpiv(long int n);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : denGETRF
+   * -----------------------------------------------------------------
+   * Usage : long int ier;
+   *         ier = denGETRF(a,m,n,p);
+   *         if (ier > 0) ... zero element encountered during
+   *                          the factorization
+   * -----------------------------------------------------------------
+   * denGETRF(a,m,n,p) factors the m by n dense matrix a, m>=n.
+   * It overwrites the elements of a with its LU factors and keeps 
+   * track of the pivot rows chosen in the pivot array p.
+   *
+   * A successful LU factorization leaves the matrix a and the
+   * pivot array p with the following information:
+   *
+   * (1) p[k] contains the row number of the pivot element chosen
+   *     at the beginning of elimination step k, k=0, 1, ..., n-1.
+   *
+   * (2) If the unique LU factorization of a is given by Pa = LU,
+   *     where P is a permutation matrix, L is a lower trapezoidal
+   *     matrix with all 1.0 on the diagonal, and U is an upper
+   *     triangular matrix, then the upper triangular part of a
+   *     (including its diagonal) contains U and the strictly lower
+   *     trapezoidal part of a contains the multipliers, I-L.
+   *
+   * Note that for square matrices (m=n), L is unit lower triangular.
+   *
+   * denGETRF returns 0 if successful. Otherwise it encountered a
+   * zero diagonal element during the factorization. In this case
+   * it returns the column index (numbered from one) at which it
+   * encountered the zero.
+   * -----------------------------------------------------------------
+   */
+
+  long int denGETRF(realtype **a, long int m, long int n, long int *p);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : denGETRS
+   * -----------------------------------------------------------------
+   * Usage : realtype *b;
+   *         ier = denGETRF(a,n,n,p);
+   *         if (ier == 0) denGETRS(a,n,p,b);
+   * -----------------------------------------------------------------
+   * denGETRS(a,n,p,b) solves the n by n linear system a*x = b.
+   * It assumes that a has been LU factored and the pivot array p has
+   * been set by a successful call to denGETRF(a,n,n,p). 
+   * denGETRS does not check whether a is square!
+   * The solution x is written into the b array.
+   * -----------------------------------------------------------------
+   */
+
+  void denGETRS(realtype **a, long int n, long int *p, realtype *b);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : denzero
+   * -----------------------------------------------------------------
+   * Usage : denzero(a,m,n);
+   * -----------------------------------------------------------------
+   * denzero(a,m,n) sets all the elements of the m by n dense matrix
+   * a to be 0.0.
+   * -----------------------------------------------------------------
+   */
+
+  void denzero(realtype **a, long int m, long int n);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : dencopy
+   * -----------------------------------------------------------------
+   * Usage : dencopy(a,b,m,n);
+   * -----------------------------------------------------------------
+   * dencopy(a,b,n) copies the m by n dense matrix a into the
+   * m by n dense matrix b.
+   * -----------------------------------------------------------------
+   */
+
+  void dencopy(realtype **a, realtype **b, long int m, long int n);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : denscale
+   * -----------------------------------------------------------------
+   * Usage : denscale(c,a,m,n);
+   * -----------------------------------------------------------------
+   * denscale(c,a,m,n) scales every element in the m by n dense
+   * matrix a by c.
+   * -----------------------------------------------------------------
+   */
+
+  void denscale(realtype c, realtype **a, long int m, long int n);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : denaddI
+   * -----------------------------------------------------------------
+   * Usage : denaddI(a,n);
+   * -----------------------------------------------------------------
+   * denaddI(a,n) increments the diagonal elements of the dense 
+   * m by n matrix a by 1.0. (a_ii <= a_ii + 1, i=1,2,..n-1.)
+   * denaddI is typically used with square matrices.
+   * denaddI does NOT check for m >= n! Therefore, a segmentation 
+   * fault will occur if m<n!
+   * -----------------------------------------------------------------
+   */
+
+  void denaddI(realtype **a, long int n);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : denfreepiv
+   * -----------------------------------------------------------------
+   * Usage : denfreepiv(p);
+   * -----------------------------------------------------------------
+   * denfreepiv(p) frees the pivot array p allocated by
+   * denallocpiv.
+   * -----------------------------------------------------------------
+   */
+
+  void denfreepiv(long int *p);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : denfree
+   * -----------------------------------------------------------------
+   * Usage : denfree(a);
+   * -----------------------------------------------------------------
+   * denfree(a) frees the dense matrix a allocated by denalloc.
+   * -----------------------------------------------------------------
+   */
+
+  void denfree(realtype **a);
+
+  /*
+   * -----------------------------------------------------------------
+   * Function : denprint
+   * -----------------------------------------------------------------
+   * Usage : denprint(a,m,n);
+   * -----------------------------------------------------------------
+   * denprint(a,m,n) prints the m by n dense matrix a to standard
+   * output as it would normally appear on paper. It is intended as
+   * a debugging tool with small values of m and n. The elements are
+   * printed using the %g/%lg/%Lg option. A blank line is printed
+   * before and after the matrix.
+   * -----------------------------------------------------------------
+   */
+
+  void denprint(realtype **a, long int m, long int n);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_spbcgs.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_spbcgs.h
new file mode 100644
index 0000000000000000000000000000000000000000..652a76414cc91b408c4ca18e2fc597fb55b8f158
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_spbcgs.h
@@ -0,0 +1,199 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * -----------------------------------------------------------------
+ * Programmer(s): Peter Brown and Aaron Collier @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2004, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the header file for the implementation of the scaled,
+ * preconditioned Bi-CGSTAB (SPBCG) iterative linear solver.
+ * -----------------------------------------------------------------
+ */
+
+#ifndef _SPBCG_H
+#define _SPBCG_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#include <sundials/sundials_iterative.h>
+
+/*
+ * -----------------------------------------------------------------
+ * Types: struct SpbcgMemRec and struct *SpbcgMem
+ * -----------------------------------------------------------------
+ * A variable declaration of type struct *SpbcgMem denotes a pointer
+ * to a data structure of type struct SpbcgMemRec. The SpbcgMemRec
+ * structure contains numerous fields that must be accessed by the
+ * SPBCG linear solver module.
+ *
+ *  l_max  maximum Krylov subspace dimension that SpbcgSolve will
+ *         be permitted to use
+ *
+ *  r  vector (type N_Vector) which holds the scaled, preconditioned
+ *     linear system residual
+ *
+ *  r_star  vector (type N_Vector) which holds the initial scaled,
+ *          preconditioned linear system residual
+ *
+ *  p, q, u and Ap  vectors (type N_Vector) used for workspace by
+ *                  the SPBCG algorithm
+ *
+ *  vtemp  scratch vector (type N_Vector) used as temporary vector
+ *         storage
+ * -----------------------------------------------------------------
+ */
+
+typedef struct {
+
+  int l_max;
+
+  N_Vector r_star;
+  N_Vector r;
+  N_Vector p;
+  N_Vector q;
+  N_Vector u;
+  N_Vector Ap;
+  N_Vector vtemp;
+
+} SpbcgMemRec, *SpbcgMem;
+
+/*
+ * -----------------------------------------------------------------
+ * Function : SpbcgMalloc
+ * -----------------------------------------------------------------
+ * SpbcgMalloc allocates additional memory needed by the SPBCG
+ * linear solver module.
+ *
+ *  l_max  maximum Krylov subspace dimension that SpbcgSolve will
+ *         be permitted to use
+ *
+ *  vec_tmpl  implementation-specific template vector (type N_Vector)
+ *            (created using either N_VNew_Serial or N_VNew_Parallel)
+ *
+ * If successful, SpbcgMalloc returns a non-NULL memory pointer. If
+ * an error occurs, then a NULL pointer is returned.
+ * -----------------------------------------------------------------
+ */
+
+SpbcgMem SpbcgMalloc(int l_max, N_Vector vec_tmpl);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : SpbcgSolve
+ * -----------------------------------------------------------------
+ * SpbcgSolve solves the linear system Ax = b by means of a scaled
+ * preconditioned Bi-CGSTAB (SPBCG) iterative method.
+ *
+ *  mem  pointer to an internal memory block allocated during a
+ *       prior call to SpbcgMalloc
+ *
+ *  A_data  pointer to a data structure containing information
+ *          about the coefficient matrix A (passed to user-supplied
+ *          function referenced by atimes (function pointer))
+ *
+ *  x  vector (type N_Vector) containing initial guess x_0 upon
+ *     entry, but which upon return contains an approximate solution
+ *     of the linear system Ax = b (solution only valid if return
+ *     value is either SPBCG_SUCCESS or SPBCG_RES_REDUCED)
+ *
+ *  b  vector (type N_Vector) set to the right-hand side vector b
+ *     of the linear system (undisturbed by function)
+ *
+ *  pretype  variable (type int) indicating the type of
+ *           preconditioning to be used (see sundials_iterative.h)
+ *
+ *  delta  tolerance on the L2 norm of the scaled, preconditioned
+ *         residual (if return value == SPBCG_SUCCESS, then
+ *         ||sb*P1_inv*(b-Ax)||_L2 <= delta)
+ *
+ *  P_data  pointer to a data structure containing preconditioner
+ *          information (passed to user-supplied function referenced
+ *          by psolve (function pointer))
+ *
+ *  sx  vector (type N_Vector) containing positive scaling factors
+ *      for x (pass sx == NULL if scaling NOT required)
+ *
+ *  sb  vector (type N_Vector) containing positive scaling factors
+ *      for b (pass sb == NULL if scaling NOT required)
+ *
+ *  atimes  user-supplied routine responsible for computing the
+ *          matrix-vector product Ax (see sundials_iterative.h)
+ *
+ *  psolve  user-supplied routine responsible for solving the
+ *          preconditioned linear system Pz = r (ignored if
+ *          pretype == PREC_NONE) (see sundials_iterative.h)
+ *
+ *  res_norm  pointer (type realtype*) to the L2 norm of the
+ *            scaled, preconditioned residual (if return value
+ *            is either SPBCG_SUCCESS or SPBCG_RES_REDUCED, then
+ *            *res_norm = ||sb*P1_inv*(b-Ax)||_L2, where x is
+ *            the computed approximate solution, sb is the diagonal
+ *            scaling matrix for the right-hand side b, and P1_inv
+ *            is the inverse of the left-preconditioner matrix)
+ *
+ *  nli  pointer (type int*) to the total number of linear
+ *       iterations performed
+ *
+ *  nps  pointer (type int*) to the total number of calls made
+ *       to the psolve routine
+ * -----------------------------------------------------------------
+ */
+
+int SpbcgSolve(SpbcgMem mem, void *A_data, N_Vector x, N_Vector b,
+               int pretype, realtype delta, void *P_data, N_Vector sx,
+               N_Vector sb, ATimesFn atimes, PSolveFn psolve,
+               realtype *res_norm, int *nli, int *nps);
+
+/* Return values for SpbcgSolve */
+
+#define SPBCG_SUCCESS            0  /* SPBCG algorithm converged          */
+#define SPBCG_RES_REDUCED        1  /* SPBCG did NOT converge, but the
+				       residual was reduced               */
+#define SPBCG_CONV_FAIL          2  /* SPBCG algorithm failed to converge */
+#define SPBCG_PSOLVE_FAIL_REC    3  /* psolve failed recoverably          */
+#define SPBCG_ATIMES_FAIL_REC    4  /* atimes failed recoverably          */
+#define SPBCG_PSET_FAIL_REC      5  /* pset faild recoverably             */
+
+#define SPBCG_MEM_NULL          -1  /* mem argument is NULL               */
+#define SPBCG_ATIMES_FAIL_UNREC -2  /* atimes returned failure flag       */
+#define SPBCG_PSOLVE_FAIL_UNREC -3  /* psolve failed unrecoverably        */
+#define SPBCG_PSET_FAIL_UNREC   -4  /* pset failed unrecoverably          */
+
+/*
+ * -----------------------------------------------------------------
+ * Function : SpbcgFree
+ * -----------------------------------------------------------------
+ * SpbcgFree frees the memory allocated by a call to SpbcgMalloc.
+ * It is illegal to use the pointer mem after a call to SpbcgFree.
+ * -----------------------------------------------------------------
+ */
+
+void SpbcgFree(SpbcgMem mem);
+
+/*
+ * -----------------------------------------------------------------
+ * Macro : SPBCG_VTEMP
+ * -----------------------------------------------------------------
+ * This macro provides access to the vector r in the
+ * memory block of the SPBCG module. The argument mem is the
+ * memory pointer returned by SpbcgMalloc, of type SpbcgMem,
+ * and the macro value is of type N_Vector.
+ *
+ * Note: Only used by IDA (r contains P_inverse F if nli_inc == 0).
+ * -----------------------------------------------------------------
+ */
+
+#define SPBCG_VTEMP(mem) (mem->r)
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_spgmr.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_spgmr.h
new file mode 100644
index 0000000000000000000000000000000000000000..cd9b00f37ec2f634e152eead941175c6f668149d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_spgmr.h
@@ -0,0 +1,296 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Scott D. Cohen, Alan C. Hindmarsh and
+ *                Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2002, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the header file for the implementation of SPGMR Krylov
+ * iterative linear solver.  The SPGMR algorithm is based on the
+ * Scaled Preconditioned GMRES (Generalized Minimal Residual)
+ * method.
+ *
+ * The SPGMR algorithm solves a linear system A x = b.
+ * Preconditioning is allowed on the left, right, or both.
+ * Scaling is allowed on both sides, and restarts are also allowed.
+ * We denote the preconditioner and scaling matrices as follows:
+ *   P1 = left preconditioner
+ *   P2 = right preconditioner
+ *   S1 = diagonal matrix of scale factors for P1-inverse b
+ *   S2 = diagonal matrix of scale factors for P2 x
+ * The matrices A, P1, and P2 are not required explicitly; only
+ * routines that provide A, P1-inverse, and P2-inverse as
+ * operators are required.
+ *
+ * In this notation, SPGMR applies the underlying GMRES method to
+ * the equivalent transformed system
+ *   Abar xbar = bbar , where
+ *   Abar = S1 (P1-inverse) A (P2-inverse) (S2-inverse) ,
+ *   bbar = S1 (P1-inverse) b , and   xbar = S2 P2 x .
+ *
+ * The scaling matrices must be chosen so that vectors S1
+ * P1-inverse b and S2 P2 x have dimensionless components.
+ * If preconditioning is done on the left only (P2 = I), by a
+ * matrix P, then S2 must be a scaling for x, while S1 is a
+ * scaling for P-inverse b, and so may also be taken as a scaling
+ * for x.  Similarly, if preconditioning is done on the right only
+ * (P1 = I, P2 = P), then S1 must be a scaling for b, while S2 is
+ * a scaling for P x, and may also be taken as a scaling for b.
+ *
+ * The stopping test for the SPGMR iterations is on the L2 norm of
+ * the scaled preconditioned residual:
+ *      || bbar - Abar xbar ||_2  <  delta
+ * with an input test constant delta.
+ *
+ * The usage of this SPGMR solver involves supplying two routines
+ * and making three calls.  The user-supplied routines are
+ *    atimes (A_data, x, y) to compute y = A x, given x,
+ * and
+ *    psolve (P_data, x, y, lr)
+ *                to solve P1 x = y or P2 x = y for x, given y.
+ * The three user calls are:
+ *    mem  = SpgmrMalloc(lmax, vec_tmpl);
+ *           to initialize memory,
+ *    flag = SpgmrSolve(mem,A_data,x,b,...,
+ *                      P_data,s1,s2,atimes,psolve,...);
+ *           to solve the system, and
+ *    SpgmrFree(mem);
+ *           to free the memory created by SpgmrMalloc.
+ * Complete details for specifying atimes and psolve and for the
+ * usage calls are given in the paragraphs below and in iterative.h.
+ * -----------------------------------------------------------------
+ */
+
+#ifndef _SPGMR_H
+#define _SPGMR_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#include <sundials/sundials_iterative.h>
+
+/*
+ * -----------------------------------------------------------------
+ * Types: SpgmrMemRec, SpgmrMem
+ * -----------------------------------------------------------------
+ * SpgmrMem is a pointer to an SpgmrMemRec which contains
+ * the memory needed by SpgmrSolve. The SpgmrMalloc routine
+ * returns a pointer of type SpgmrMem which should then be passed
+ * in subsequent calls to SpgmrSolve. The SpgmrFree routine frees
+ * the memory allocated by SpgmrMalloc.
+ *
+ * l_max is the maximum Krylov dimension that SpgmrSolve will be
+ * permitted to use.
+ *
+ * V is the array of Krylov basis vectors v_1, ..., v_(l_max+1),
+ * stored in V[0], ..., V[l_max], where l_max is the second
+ * parameter to SpgmrMalloc. Each v_i is a vector of type
+ * N_Vector.
+ *
+ * Hes is the (l_max+1) x l_max Hessenberg matrix. It is stored
+ * row-wise so that the (i,j)th element is given by Hes[i][j].
+ *
+ * givens is a length 2*l_max array which represents the
+ * Givens rotation matrices that arise in the algorithm. The
+ * Givens rotation matrices F_0, F_1, ..., F_j, where F_i is
+ *
+ *             1
+ *               1
+ *                 c_i  -s_i      <--- row i
+ *                 s_i   c_i
+ *                           1
+ *                             1
+ *
+ * are represented in the givens vector as
+ * givens[0]=c_0, givens[1]=s_0, givens[2]=c_1, givens[3]=s_1,
+ * ..., givens[2j]=c_j, givens[2j+1]=s_j.
+ *
+ * xcor is a vector (type N_Vector) which holds the scaled,
+ * preconditioned correction to the initial guess.
+ *
+ * yg is a length (l_max+1) array of realtype used to hold "short"
+ * vectors (e.g. y and g).
+ *
+ * vtemp is a vector (type N_Vector) used as temporary vector
+ * storage during calculations.
+ * -----------------------------------------------------------------
+ */
+  
+typedef struct _SpgmrMemRec {
+
+  int l_max;
+
+  N_Vector *V;
+  realtype **Hes;
+  realtype *givens;
+  N_Vector xcor;
+  realtype *yg;
+  N_Vector vtemp;
+
+} SpgmrMemRec, *SpgmrMem;
+
+/*
+ * -----------------------------------------------------------------
+ * Function : SpgmrMalloc
+ * -----------------------------------------------------------------
+ * SpgmrMalloc allocates the memory used by SpgmrSolve. It
+ * returns a pointer of type SpgmrMem which the user of the
+ * SPGMR package should pass to SpgmrSolve. The parameter l_max
+ * is the maximum Krylov dimension that SpgmrSolve will be
+ * permitted to use. The parameter vec_tmpl is a pointer to an
+ * N_Vector used as a template to create new vectors by duplication.
+ * This routine returns NULL if there is a memory request failure.
+ * -----------------------------------------------------------------
+ */
+
+SpgmrMem SpgmrMalloc(int l_max, N_Vector vec_tmpl);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : SpgmrSolve
+ * -----------------------------------------------------------------
+ * SpgmrSolve solves the linear system Ax = b using the SPGMR
+ * method. The return values are given by the symbolic constants
+ * below. The first SpgmrSolve parameter is a pointer to memory
+ * allocated by a prior call to SpgmrMalloc.
+ *
+ * mem is the pointer returned by SpgmrMalloc to the structure
+ * containing the memory needed by SpgmrSolve.
+ *
+ * A_data is a pointer to information about the coefficient
+ * matrix A. This pointer is passed to the user-supplied function
+ * atimes.
+ *
+ * x is the initial guess x_0 upon entry and the solution
+ * N_Vector upon exit with return value SPGMR_SUCCESS or
+ * SPGMR_RES_REDUCED. For all other return values, the output x
+ * is undefined.
+ *
+ * b is the right hand side N_Vector. It is undisturbed by this
+ * function.
+ *
+ * pretype is the type of preconditioning to be used. Its
+ * legal possible values are enumerated in iterativ.h. These
+ * values are PREC_NONE=0, PREC_LEFT=1, PREC_RIGHT=2, and
+ * PREC_BOTH=3.
+ *
+ * gstype is the type of Gram-Schmidt orthogonalization to be
+ * used. Its legal values are enumerated in iterativ.h. These
+ * values are MODIFIED_GS=0 and CLASSICAL_GS=1.
+ *
+ * delta is the tolerance on the L2 norm of the scaled,
+ * preconditioned residual. On return with value SPGMR_SUCCESS,
+ * this residual satisfies || s1 P1_inv (b - Ax) ||_2 <= delta.
+ *
+ * max_restarts is the maximum number of times the algorithm is
+ * allowed to restart.
+ *
+ * P_data is a pointer to preconditioner information. This
+ * pointer is passed to the user-supplied function psolve.
+ *
+ * s1 is an N_Vector of positive scale factors for P1-inv b, where
+ * P1 is the left preconditioner. (Not tested for positivity.)
+ * Pass NULL if no scaling on P1-inv b is required.
+ *
+ * s2 is an N_Vector of positive scale factors for P2 x, where
+ * P2 is the right preconditioner. (Not tested for positivity.)
+ * Pass NULL if no scaling on P2 x is required.
+ *
+ * atimes is the user-supplied function which performs the
+ * operation of multiplying A by a given vector. Its description
+ * is given in iterative.h.
+ *
+ * psolve is the user-supplied function which solves a
+ * preconditioner system Pz = r, where P is P1 or P2. Its full
+ * description is  given in iterativ.h. The psolve function will
+ * not be called if pretype is NONE; in that case, the user
+ * should pass NULL for psolve.
+ *
+ * res_norm is a pointer to the L2 norm of the scaled,
+ * preconditioned residual. On return with value SPGMR_SUCCESS or
+ * SPGMR_RES_REDUCED, (*res_norm) contains the value
+ * || s1 P1_inv (b - Ax) ||_2 for the computed solution x.
+ * For all other return values, (*res_norm) is undefined. The
+ * caller is responsible for allocating the memory (*res_norm)
+ * to be filled in by SpgmrSolve.
+ *
+ * nli is a pointer to the number of linear iterations done in
+ * the execution of SpgmrSolve. The caller is responsible for
+ * allocating the memory (*nli) to be filled in by SpgmrSolve.
+ *
+ * nps is a pointer to the number of calls made to psolve during
+ * the execution of SpgmrSolve. The caller is responsible for
+ * allocating the memory (*nps) to be filled in by SpgmrSolve.
+ *
+ * Note: Repeated calls can be made to SpgmrSolve with varying
+ * input arguments. If, however, the problem size N or the
+ * maximum Krylov dimension l_max changes, then a call to
+ * SpgmrMalloc must be made to obtain new memory for SpgmrSolve
+ * to use.
+ * -----------------------------------------------------------------
+ */                                                                
+     
+int SpgmrSolve(SpgmrMem mem, void *A_data, N_Vector x, N_Vector b,
+               int pretype, int gstype, realtype delta, 
+               int max_restarts, void *P_data, N_Vector s1, 
+               N_Vector s2, ATimesFn atimes, PSolveFn psolve, 
+               realtype *res_norm, int *nli, int *nps);
+
+
+/* Return values for SpgmrSolve */
+
+#define SPGMR_SUCCESS            0  /* Converged                     */
+#define SPGMR_RES_REDUCED        1  /* Did not converge, but reduced
+                                       norm of residual              */
+#define SPGMR_CONV_FAIL          2  /* Failed to converge            */
+#define SPGMR_QRFACT_FAIL        3  /* QRfact found singular matrix  */
+#define SPGMR_PSOLVE_FAIL_REC    4  /* psolve failed recoverably     */
+#define SPGMR_ATIMES_FAIL_REC    5  /* atimes failed recoverably     */
+#define SPGMR_PSET_FAIL_REC      6  /* pset faild recoverably        */
+
+#define SPGMR_MEM_NULL          -1  /* mem argument is NULL          */
+#define SPGMR_ATIMES_FAIL_UNREC -2  /* atimes returned failure flag  */
+#define SPGMR_PSOLVE_FAIL_UNREC -3  /* psolve failed unrecoverably   */
+#define SPGMR_GS_FAIL           -4  /* Gram-Schmidt routine faiuled  */        
+#define SPGMR_QRSOL_FAIL        -5  /* QRsol found singular R        */
+#define SPGMR_PSET_FAIL_UNREC   -6  /* pset failed unrecoverably     */
+
+/*
+ * -----------------------------------------------------------------
+ * Function : SpgmrFree
+ * -----------------------------------------------------------------
+ * SpgmrMalloc frees the memory allocated by SpgmrMalloc. It is
+ * illegal to use the pointer mem after a call to SpgmrFree.
+ * -----------------------------------------------------------------
+ */                                                                
+
+void SpgmrFree(SpgmrMem mem);
+
+/*
+ * -----------------------------------------------------------------
+ * Macro: SPGMR_VTEMP
+ * -----------------------------------------------------------------
+ * This macro provides access to the work vector vtemp in the
+ * memory block of the SPGMR module.  The argument mem is the
+ * memory pointer returned by SpgmrMalloc, of type SpgmrMem,
+ * and the macro value is of type N_Vector.
+ * On a return from SpgmrSolve with *nli = 0, this vector
+ * contains the scaled preconditioned initial residual,
+ * s1 * P1_inverse * (b - A x_0).
+ * -----------------------------------------------------------------
+ */
+
+#define SPGMR_VTEMP(mem) (mem->vtemp)
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_sptfqmr.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_sptfqmr.h
new file mode 100644
index 0000000000000000000000000000000000000000..fa52e026ed34a29d41369bac29f388e62d8584cb
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_sptfqmr.h
@@ -0,0 +1,254 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * -----------------------------------------------------------------
+ * Programmer(s): Aaron Collier @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2005, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the header file for the implementation of the scaled
+ * preconditioned Transpose-Free Quasi-Minimal Residual (SPTFQMR)
+ * linear solver.
+ *
+ * The SPTFQMR algorithm solves a linear system of the form Ax = b.
+ * Preconditioning is allowed on the left (PREC_LEFT), right
+ * (PREC_RIGHT), or both (PREC_BOTH).  Scaling is allowed on both
+ * sides.  We denote the preconditioner and scaling matrices as
+ * follows:
+ *   P1 = left preconditioner
+ *   P2 = right preconditioner
+ *   S1 = diagonal matrix of scale factors for P1-inverse b
+ *   S2 = diagonal matrix of scale factors for P2 x
+ * The matrices A, P1, and P2 are not required explicitly; only
+ * routines that provide A, P1-inverse, and P2-inverse as operators
+ * are required.
+ *
+ * In this notation, SPTFQMR applies the underlying TFQMR method to
+ * the equivalent transformed system:
+ *   Abar xbar = bbar, where
+ *   Abar = S1 (P1-inverse) A (P2-inverse) (S2-inverse),
+ *   bbar = S1 (P1-inverse) b, and
+ *   xbar = S2 P2 x.
+ *
+ * The scaling matrices must be chosen so that vectors
+ * S1 P1-inverse b and S2 P2 x have dimensionless components.  If
+ * preconditioning is done on the left only (P2 = I), by a matrix P,
+ * then S2 must be a scaling for x, while S1 is a scaling for
+ * P-inverse b, and so may also be taken as a scaling for x.
+ * Similarly, if preconditioning is done on the right only (P1 = I,
+ * P2 = P), then S1 must be a scaling for b, while S2 is a scaling
+ * for P x, and may also be taken as a scaling for b.
+ *
+ * The stopping test for the SPTFQMR iterations is on the L2-norm of
+ * the scaled preconditioned residual:
+ *   || bbar - Abar xbar ||_2 < delta
+ * with an input test constant delta.
+ *
+ * The usage of this SPTFQMR solver involves supplying two routines
+ * and making three calls.  The user-supplied routines are:
+ *   atimes(A_data, x, y) to compute y = A x, given x,
+ * and
+ *   psolve(P_data, x, y, lr) to solve P1 x = y or P2 x = y for x,
+ *                            given y.
+ * The three user calls are:
+ *   mem  = SptfqmrMalloc(lmax, vec_tmpl);
+ *          to initialize memory
+ *   flag = SptfqmrSolve(mem, A_data, x, b, pretype, delta, P_data,
+ *                       sx, sb, atimes, psolve, res_norm, nli, nps);
+ *          to solve the system, and
+ *   SptfqmrFree(mem);
+ *          to free the memory allocated by SptfqmrMalloc().
+ * Complete details for specifying atimes() and psolve() and for the
+ * usage calls are given in the paragraphs below and in the header
+ * file sundials_iterative.h.
+ * -----------------------------------------------------------------
+ */
+
+#ifndef _SPTFQMR_H
+#define _SPTFQMR_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#include <sundials/sundials_iterative.h>
+
+/*
+ * -----------------------------------------------------------------
+ * Types: struct SptfqmrMemRec and struct *SptfqmrMem
+ * -----------------------------------------------------------------
+ * A variable declaration of type struct *SptfqmrMem denotes a pointer
+ * to a data structure of type struct SptfqmrMemRec. The SptfqmrMemRec
+ * structure contains numerous fields that must be accessed by the
+ * SPTFQMR linear solver module.
+ *
+ *  l_max  maximum Krylov subspace dimension that SptfqmrSolve will
+ *         be permitted to use
+ *
+ *  r_star  vector (type N_Vector) which holds the initial scaled,
+ *          preconditioned linear system residual
+ *
+ *  q/d/v/p/u/r  vectors (type N_Vector) used for workspace by
+ *               the SPTFQMR algorithm
+ *
+ *  vtemp1/vtemp2/vtemp3  scratch vectors (type N_Vector) used as
+ *                        temporary storage
+ * -----------------------------------------------------------------
+ */
+
+typedef struct {
+
+  int l_max;
+
+  N_Vector r_star;
+  N_Vector q;
+  N_Vector d;
+  N_Vector v;
+  N_Vector p;
+  N_Vector *r;
+  N_Vector u;
+  N_Vector vtemp1;
+  N_Vector vtemp2;
+  N_Vector vtemp3;
+
+} SptfqmrMemRec, *SptfqmrMem;
+
+/*
+ * -----------------------------------------------------------------
+ * Function : SptfqmrMalloc
+ * -----------------------------------------------------------------
+ * SptfqmrMalloc allocates additional memory needed by the SPTFQMR
+ * linear solver module.
+ *
+ *  l_max  maximum Krylov subspace dimension that SptfqmrSolve will
+ *         be permitted to use
+ *
+ *  vec_tmpl  implementation-specific template vector (type N_Vector)
+ *            (created using either N_VNew_Serial or N_VNew_Parallel)
+ *
+ * If successful, SptfqmrMalloc returns a non-NULL memory pointer. If
+ * an error occurs, then a NULL pointer is returned.
+ * -----------------------------------------------------------------
+ */
+
+SptfqmrMem SptfqmrMalloc(int l_max, N_Vector vec_tmpl);
+
+/*
+ * -----------------------------------------------------------------
+ * Function : SptfqmrSolve
+ * -----------------------------------------------------------------
+ * SptfqmrSolve solves the linear system Ax = b by means of a scaled
+ * preconditioned Transpose-Free Quasi-Minimal Residual (SPTFQMR)
+ * method.
+ *
+ *  mem  pointer to an internal memory block allocated during a
+ *       prior call to SptfqmrMalloc
+ *
+ *  A_data  pointer to a data structure containing information
+ *          about the coefficient matrix A (passed to user-supplied
+ *          function referenced by atimes (function pointer))
+ *
+ *  x  vector (type N_Vector) containing initial guess x_0 upon
+ *     entry, but which upon return contains an approximate solution
+ *     of the linear system Ax = b (solution only valid if return
+ *     value is either SPTFQMR_SUCCESS or SPTFQMR_RES_REDUCED)
+ *
+ *  b  vector (type N_Vector) set to the right-hand side vector b
+ *     of the linear system (undisturbed by function)
+ *
+ *  pretype  variable (type int) indicating the type of
+ *           preconditioning to be used (see sundials_iterative.h)
+ *
+ *  delta  tolerance on the L2 norm of the scaled, preconditioned
+ *         residual (if return value == SPTFQMR_SUCCESS, then
+ *         ||sb*P1_inv*(b-Ax)||_L2 <= delta)
+ *
+ *  P_data  pointer to a data structure containing preconditioner
+ *          information (passed to user-supplied function referenced
+ *          by psolve (function pointer))
+ *
+ *  sx  vector (type N_Vector) containing positive scaling factors
+ *      for x (pass sx == NULL if scaling NOT required)
+ *
+ *  sb  vector (type N_Vector) containing positive scaling factors
+ *      for b (pass sb == NULL if scaling NOT required)
+ *
+ *  atimes  user-supplied routine responsible for computing the
+ *          matrix-vector product Ax (see sundials_iterative.h)
+ *
+ *  psolve  user-supplied routine responsible for solving the
+ *          preconditioned linear system Pz = r (ignored if
+ *          pretype == PREC_NONE) (see sundials_iterative.h)
+ *
+ *  res_norm  pointer (type realtype*) to the L2 norm of the
+ *            scaled, preconditioned residual (if return value
+ *            is either SPTFQMR_SUCCESS or SPTFQMR_RES_REDUCED, then
+ *            *res_norm = ||sb*P1_inv*(b-Ax)||_L2, where x is
+ *            the computed approximate solution, sb is the diagonal
+ *            scaling matrix for the right-hand side b, and P1_inv
+ *            is the inverse of the left-preconditioner matrix)
+ *
+ *  nli  pointer (type int*) to the total number of linear
+ *       iterations performed
+ *
+ *  nps  pointer (type int*) to the total number of calls made
+ *       to the psolve routine
+ * -----------------------------------------------------------------
+ */
+
+int SptfqmrSolve(SptfqmrMem mem, void *A_data, N_Vector x, N_Vector b,
+		 int pretype, realtype delta, void *P_data, N_Vector sx,
+		 N_Vector sb, ATimesFn atimes, PSolveFn psolve,
+		 realtype *res_norm, int *nli, int *nps);
+
+/* Return values for SptfqmrSolve */
+
+#define SPTFQMR_SUCCESS            0  /* SPTFQMR algorithm converged          */
+#define SPTFQMR_RES_REDUCED        1  /* SPTFQMR did NOT converge, but the
+				         residual was reduced                 */
+#define SPTFQMR_CONV_FAIL          2  /* SPTFQMR algorithm failed to converge */
+#define SPTFQMR_PSOLVE_FAIL_REC    3  /* psolve failed recoverably            */
+#define SPTFQMR_ATIMES_FAIL_REC    4  /* atimes failed recoverably            */
+#define SPTFQMR_PSET_FAIL_REC      5  /* pset faild recoverably               */
+
+#define SPTFQMR_MEM_NULL          -1  /* mem argument is NULL                 */
+#define SPTFQMR_ATIMES_FAIL_UNREC -2  /* atimes returned failure flag         */
+#define SPTFQMR_PSOLVE_FAIL_UNREC -3  /* psolve failed unrecoverably          */
+#define SPTFQMR_PSET_FAIL_UNREC   -4  /* pset failed unrecoverably            */
+
+/*
+ * -----------------------------------------------------------------
+ * Function : SptfqmrFree
+ * -----------------------------------------------------------------
+ * SptfqmrFree frees the memory allocated by a call to SptfqmrMalloc.
+ * It is illegal to use the pointer mem after a call to SptfqmrFree.
+ * -----------------------------------------------------------------
+ */
+
+void SptfqmrFree(SptfqmrMem mem);
+
+/*
+ * -----------------------------------------------------------------
+ * Macro : SPTFQMR_VTEMP
+ * -----------------------------------------------------------------
+ * This macro provides access to the work vector vtemp1 in the
+ * memory block of the SPTFQMR module. The argument mem is the
+ * memory pointer returned by SptfqmrMalloc, of type SptfqmrMem,
+ * and the macro value is of type N_Vector.
+ *
+ * Note: Only used by IDA (vtemp1 contains P_inverse F if
+ *       nli_inc == 0).
+ * -----------------------------------------------------------------
+ */
+
+#define SPTFQMR_VTEMP(mem) (mem->vtemp1)
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_types.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_types.h
new file mode 100644
index 0000000000000000000000000000000000000000..0e3f26dde30328eae3ecec6ebb8a2470d46c4364
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/include_SUNDIALS_CVODES_25/sundials/sundials_types.h
@@ -0,0 +1,114 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Scott Cohen, Alan Hindmarsh, Radu Serban, and
+ *                Aaron Collier @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2002, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ *------------------------------------------------------------------
+ * This header file exports two types: realtype and booleantype,
+ * as well as the constants TRUE and FALSE.
+ *
+ * Users should include the header file sundials_types.h in every
+ * program file and use the exported name realtype instead of
+ * float, double or long double.
+ *
+ * The constants SUNDIALS_SINGLE_PRECISION, SUNDIALS_DOUBLE_PRECISION
+ * and SUNDIALS_LONG_DOUBLE_PRECISION indicate the underlying data
+ * type of realtype. It is set at the configuration stage.
+ *
+ * The legal types for realtype are float, double and long double.
+ *
+ * The macro RCONST gives the user a convenient way to define
+ * real-valued constants. To use the constant 1.0, for example,
+ * the user should write the following:
+ *
+ *   #define ONE RCONST(1.0)
+ *
+ * If realtype is defined as a double, then RCONST(1.0) expands
+ * to 1.0. If realtype is defined as a float, then RCONST(1.0)
+ * expands to 1.0F. If realtype is defined as a long double,
+ * then RCONST(1.0) expands to 1.0L. There is never a need to
+ * explicitly cast 1.0 to (realtype).
+ *------------------------------------------------------------------
+ */
+  
+#ifndef _SUNDIALSTYPES_H
+#define _SUNDIALSTYPES_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#ifndef _SUNDIALS_CONFIG_H
+#define _SUNDIALS_CONFIG_H
+#include <sundials/sundials_config.h>
+#endif
+
+#include <float.h>
+  
+#if defined(SUNDIALS_SINGLE_PRECISION)
+
+typedef float realtype;
+#define RCONST(x) x##F
+#define BIG_REAL FLT_MAX
+#define SMALL_REAL FLT_MIN
+#define UNIT_ROUNDOFF FLT_EPSILON
+
+#elif defined(SUNDIALS_DOUBLE_PRECISION)
+
+typedef double realtype;
+#define RCONST(x) x
+#define BIG_REAL DBL_MAX
+#define SMALL_REAL DBL_MIN
+#define UNIT_ROUNDOFF DBL_EPSILON
+
+#elif defined(SUNDIALS_EXTENDED_PRECISION)
+
+typedef long double realtype;
+#define RCONST(x) x##L
+#define BIG_REAL LDBL_MAX
+#define SMALL_REAL LDBL_MIN
+#define UNIT_ROUNDOFF LDBL_EPSILON
+
+#endif
+
+/*
+ *------------------------------------------------------------------
+ * Type : booleantype
+ *------------------------------------------------------------------
+ * Constants : FALSE and TRUE
+ *------------------------------------------------------------------
+ * ANSI C does not have a built-in boolean data type. Below is the
+ * definition for a new type called booleantype. The advantage of
+ * using the name booleantype (instead of int) is an increase in
+ * code readability. It also allows the programmer to make a
+ * distinction between int and boolean data. Variables of type
+ * booleantype are intended to have only the two values FALSE and
+ * TRUE which are defined below to be equal to 0 and 1,
+ * respectively.
+ *------------------------------------------------------------------
+ */
+
+#ifndef booleantype
+#define booleantype int
+#endif
+
+#ifndef FALSE
+#define FALSE 0
+#endif
+
+#ifndef TRUE
+#define TRUE 1
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/kineticformulas.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/kineticformulas.h
new file mode 100644
index 0000000000000000000000000000000000000000..c4bc94146bccd779f88fbb2a6ec01d843ee350b2
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/kineticformulas.h
@@ -0,0 +1,194 @@
+/*
+ * kineticformulas.h: Include file for specification of useful kinetic formulas
+ *
+ * Information:
+ * ============
+ * SBPD Package - Systems Biology Parameter Determination Package
+ * Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+ */
+
+double kin_mass_action_irr(double k, double substrate)
+{
+    return k*substrate;    
+}
+
+double kin_mass_action_rev(double k1, double substrate, double k2, double product)
+{
+    return k1*substrate - k2*product;    
+}
+
+double kin_degradation(double kdeg, double substrate)
+{
+    return kdeg*substrate;    
+}
+
+double kin_michaelis_menten_irr(double V, double substrate, double Km)
+{
+    return V*substrate / ( Km + substrate );    
+}
+
+double kin_hill_cooperativity_irr(double V, double substrate, double h, double Shalve)
+{
+    return V*pow(substrate,h) / (pow(Shalve,h) + pow(substrate,h));    
+}
+
+double kin_mixed_inihib_irr(double V, double substrate, double Km, double inhibitor, double Kis, double Kic)
+{
+    return V*substrate / ( Km*(1+inhibitor/Kis) + substrate*(1+inhibitor/Kic) );    
+}
+
+double kin_noncomp_inihib_irr(double V, double substrate, double Km, double inhibitor, double Ki)
+{
+    return V*substrate / ( (Km+substrate)*(1+inhibitor/Ki) );
+}
+
+double kin_uncomp_inihib_irr(double V, double substrate, double Km, double inhibitor, double Ki)
+{
+    return V*substrate / ( Km + substrate*(1+inhibitor/Ki) );
+}
+
+double kin_comp_inihib_irr(double V, double substrate, double Km, double inhibitor, double Ki)
+{
+    return V*substrate / ( Km*(1+inhibitor/Ki) + substrate );
+}
+
+double kin_substrate_inihib_irr(double V, double substrate, double Km, double Ki)
+{
+    return V*substrate / ( Km + substrate + Km*pow((substrate/Ki),2.0) );
+}
+
+double kin_allosteric_inihib_mwc_irr(double V, double substrate, double Ks, double n, double L, double inhibitor, double Ki)
+{
+    return V*substrate*pow((Ks+substrate),(n-1.0)) / ( L*pow((Ks*(1+inhibitor/Ki)),n) + pow((Ks+substrate),n) );
+}
+
+double kin_allosteric_inihib_empirical_rev(double Vf, double substrate, double Kms, double Vr, double product, double Kmp, double inhibitor, double Ki, double n)
+{
+    return (Vf*substrate/Kms - Vr*product/Kmp) / (1 + substrate/Kms + product/Kmp + pow((inhibitor/Ki),n));
+}
+
+double kin_catalytic_activation_irr(double V, double substrate, double activator, double Kms, double Ka)
+{
+    return V*substrate*activator / ( (Kms + substrate)*(Ka+activator) );
+}
+
+double kin_catalytic_activation_rev(double Vf, double substrate, double Kms, double Vr, double product, double Kmp, double activator, double Ka)
+{
+    return ( Vf*substrate/Kms - Vr*product/Kmp )*activator / ( (1+substrate/Kms+product/Kmp)*(Ka+activator) );
+}
+
+double kin_comp_inihib_rev(double Vf, double substrate, double Kms, double Vr, double product, double Kmp, double inhibitor, double Ki)
+{
+    return (Vf*substrate/Kms - Vr*product/Kmp) / ( 1+substrate/Kms+product/Kmp+inhibitor/Ki );
+}
+
+double kin_constantflux(double v)
+{
+    return v;
+}
+
+double kin_hyperbolic_modifier_irr(double V,double substrate,double b,double modifier,double a,double Kd,double Km)
+{
+    return V*substrate*(1+b*modifier/(a*Kd)) / ( Km*(1+modifier/Kd) + substrate*(1+modifier/(a*Kd)) );
+}
+
+double kin_hyperbolic_modifier_rev(double Vf,double substrate,double Kms,double Vr,double product,double Kmp,double b,double modifier,double a,double Kd)
+{
+    return (Vf*substrate/Kms - Vr*product/Kmp)*(1+b*modifier/(a*Kd)) / ( 1+modifier/Kd+(substrate/Kms+product/Kmp)*(1+modifier/(a*Kd)) );
+}
+
+double kin_hill_rev(double Vf,double substrate,double Shalve,double product,double Keq,double Phalve,double h)
+{
+    return Vf*substrate/Shalve*(1-product/(substrate*Keq))*pow((substrate/Shalve+product/Phalve),(h-1.0)) / ( 1+pow((substrate/Shalve + product/Phalve),h) );
+}
+
+double kin_iso_uni_uni_rev(double Vf,double substrate,double product,double Keq,double Kii,double Kms,double Kmp)
+{
+    return Vf*(substrate-product/Keq) / ( substrate*(1+product/Kii) + Kms*(1+product/Kmp) );
+}
+
+double kin_mixed_activation_irr(double V,double substrate,double activator,double Kms,double Kas,double Kac)
+{
+    return V*substrate*activator / ( Kms*(Kas+activator) + substrate*(Kac+activator) );
+}
+
+double kin_mixed_activation_rev(double Vf,double substrate,double Kms,double Vr,double product,double Kmp,double activator,double Kas,double Kac)
+{
+    return (Vf*substrate/Kms - Vr*product/Kmp)*activator / ( Kas+activator+(substrate/Kms+product/Kmp)*(Kac+activator) );
+}
+
+double kin_mixed_inihib_rev(double Vf,double substrate,double Kms,double Vr,double product,double Kmp,double inhibitor,double Kis,double Kic)
+{
+    return (Vf*substrate/Kms - Vr*product/Kmp) / ( 1+inhibitor/Kis+(substrate/Kms+product/Kmp)*(1+inhibitor/Kic) );
+}
+
+double kin_noncomp_inihib_rev(double Vf,double substrate,double Kms,double Vr,double product,double Kmp,double inhibitor,double Ki)
+{
+    return (Vf*substrate/Kms-Vr*product/Kmp) / ( (1+substrate/Kms+product/Kmp)*(1+inhibitor/Ki) );
+}
+
+double kin_ordered_bi_bi_rev(double Vf,double substratea,double substrateb,double productp,double productq,double Keq,double Kip,double Kma,double Kmb,double Kia,double Vr,double Kmq,double Kmp,double Kib)
+{
+    return Vf*(substratea*substrateb-productp*productq/Keq) / (substratea*substrateb*(1+productp/Kip) + Kma*substrateb + Kmb*(substratea+Kia)+Vf/(Vr*Keq)*(Kmq*productp*(1+substratea/Kia) + productq*(Kmp*(1+Kia*substrateb/(Kma*Kmb))+productp*(1+substrateb/Kib))) );
+}
+
+double kin_ordered_bi_uni_rev(double Vf,double substratea,double substrateb,double product,double Keq,double Kma,double Kmb,double Vr,double Kmp,double Kia)
+{
+    return Vf*(substratea*substrateb-product/Keq) / ( substratea*substrateb+Kma*substrateb+Kmb*substratea+Vf/(Vr*Keq)*(Kmp+product*(1+substratea/Kia)) );
+}
+
+double kin_ordered_uni_bi_rev(double Vf,double substrate,double productp,double productq,double Keq,double Kms,double Kip,double Vr,double Kmq,double Kmp)
+{
+    return Vf*(substrate-productp*productq/Keq) / ( Kms+substrate*(1+productp/Kip)+Vf/(Vr*Keq)*(Kmq*productp+Kmp*productq+productp*productq) );
+}
+
+double kin_michaelis_menten_rev(double Vf,double substrate,double Kms,double Vr,double product,double Kmp)
+{
+    return (Vf*substrate/Kms+Vr*product/Kmp) / ( 1+substrate/Kms+product/Kmp );
+}
+
+double kin_substrate_inihib_rev(double Vf,double substrate,double Kms,double Vr,double product,double Kmp,double Ki)
+{
+    return (Vf*substrate/Kms-Vr*product/Kmp) / ( 1+substrate/Kms+product/Kmp+pow((substrate/Ki),2.0) );
+}
+
+double kin_uncomp_inihib_rev(double Vf,double substrate,double Kms,double Vr,double product,double Kmp,double inhibitor,double Ki)
+{
+    return ( Vf*substrate/Kms-Vr*product/Kmp ) / ( 1+(substrate/Kms+product/Kmp)*(1+inhibitor/Ki) );
+}
+
+double kin_uni_uni_rev(double Vf,double substrate,double product,double Keq,double Kms,double Kmp)
+{
+    return Vf*( substrate-product/Keq ) / ( substrate+Kms*(1+product/Kmp) );
+}
+
+double kin_specific_activation_irr(double V,double substrate,double activator,double Kms,double Ka)
+{
+    return V*substrate*activator/( Kms*Ka+(Kms+substrate)*activator );
+}
+
+double kin_specific_activation_rev(double Vf,double substrate,double Kms,double Vr,double product,double Kmp,double activator,double Ka)
+{
+    return ( Vf*substrate/Kms-Vr*product/Kmp )*activator / ( Ka+(1+substrate/Kms+product/Kmp)*activator );
+}
+
+double kin_substrate_activation_irr(double V,double substrate,double Ksa,double Ksc)
+{
+    return V*pow((substrate/Ksa),2.0) / ( 1+substrate/Ksc+substrate/Ksa+pow((substrate/Ksa),2.0) );
+}
+
+double kin_ping_pong_bi_bi_rev(double Vf,double substratea,double substrateb,double productp,double productq,double Keq,double Kiq,double Kma,double Kmb,double Vr,double Kmq,double Kia,double Kmp)
+{
+    return Vf*( substratea*substrateb-productp*productq/Keq ) / (substratea*substrateb*(1+productq/Kiq)+Kma*substrateb+Kmb*substratea+Vf/(Vr*Keq)*(Kmq*productp*(1+substratea/Kia)+productq*(Kmp+productp)));
+}
+
+double kin_hill_1_modifier_rev(double Vf,double substrate,double Shalve,double product,double Keq,double Phalve,double h,double modifier,double Mhalve,double alpha)
+{
+    return Vf*substrate/Shalve*(1-product/(substrate*Keq))*pow((substrate/Shalve+product/Phalve),(h-1.0)) / ( (1+pow((modifier/Mhalve),h))/(1+alpha*pow((modifier/Mhalve),h))+pow((substrate/Shalve + product/Phalve),h) );
+}
+
+double kin_hill_2_modifiers_rev(double Vf,double substrate,double Shalve,double product,double Keq,double Phalve,double h,double modifierA,double MAhalve,double modifierB,double MBhalve,double alphaA,double alphaB,double alphaAB)
+{
+    return Vf*substrate/Shalve*(1-product/(substrate*Keq))*pow((substrate/Shalve+product/Phalve),(h-1.0)) / ( (1+pow((modifierA/MAhalve),h) + 1+pow((modifierB/MBhalve),h)) / ( 1+alphaA*pow((modifierA/MAhalve),h)+alphaB*pow((modifierB/MBhalve),h)+alphaA*alphaB*alphaAB*pow((modifierA/MAhalve),h)*pow((modifierB/MBhalve),h) ) + pow((substrate/Shalve + product/Phalve),h) );
+}
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/mexmathaddon.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/mexmathaddon.h
new file mode 100644
index 0000000000000000000000000000000000000000..9f781153aada50d5355e4a9295571ff0e9e49d7b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/mexmathaddon.h
@@ -0,0 +1,279 @@
+/*
+ * mexmathaddon.h: Include file for automatically generated MEX model files.
+ *
+ * Information:
+ * ============
+ * SBPD Package - Systems Biology Parameter Determination Package
+ * Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+ */
+
+#define pi 3.141592653589793
+
+#ifdef __LCC__
+double max(double a, double b)
+{
+    if (a<b) return b;
+    else return a;
+}
+
+double min(double a, double b)
+{
+    if (a>b) return b;
+    else return a;
+}
+#endif
+
+#ifdef __GNUC__
+double max(double a, double b)
+{
+    return fmax(a,b);
+}
+
+double min(double a, double b)
+{
+    return fmin(a,b);
+}
+#endif
+
+
+
+double minSB(int nargs, ...)
+{
+    int k;
+    double minimum;
+    double checkmin;
+    va_list vararg;
+    va_start(vararg, nargs);
+    minimum = va_arg(vararg, double);
+    for (k=1; k<nargs; k++ ) {
+        checkmin = va_arg(vararg, double);
+        if (checkmin < minimum) {
+            minimum = checkmin;
+        }
+    }
+    va_end (vararg);
+    return minimum;
+}
+
+double maxSB(int nargs, ...)
+{
+    int k;
+    double maximum;
+    double checkmax;
+    va_list vararg;
+    va_start(vararg, nargs);
+    maximum = va_arg(vararg, double);
+    for (k=1; k<nargs; k++ ) {
+        checkmax = va_arg(vararg, double);
+        if (checkmax > maximum) {
+            maximum = checkmax;
+        }
+    }
+    va_end (vararg);
+    return maximum;
+}
+
+double indexmaxSB(int nargs, ...)
+{
+    int k;
+    double maximum;
+    double indexmaximum;
+    double checkmax;
+    va_list vararg;
+    va_start(vararg, nargs);
+    maximum = va_arg(vararg, double);
+    indexmaximum = 1;
+    for (k=1; k<nargs; k++ ) {
+        checkmax = va_arg(vararg, double);
+        if (checkmax > maximum) {
+            maximum = checkmax;
+            indexmaximum = (double)k+1;
+        }
+    }
+    va_end (vararg);
+    return indexmaximum;
+}
+
+double sign(double a)
+{
+    if (a<0) return -1;
+    else if (a==0) return 0;
+    else if (a>0) return 1;
+    else return a;
+}
+
+double absSB(double a)
+{
+    if (a < 0) return -a;
+    else return a;
+}
+
+double mod(double a, double b)
+{
+    if (b == 0) return a;
+    else if (a == b) return 0;
+    return sign(b)*absSB(a-floor(a/b)*b);
+}
+
+double nthrootSB(double a, double n)
+{
+    return pow(a,1.0/n);
+}
+
+double andSB(int nargs, ...)
+{
+    int k;
+    va_list vararg;
+    va_start(vararg, nargs);
+    for (k=0; k<nargs; k++ ) {
+        if (va_arg(vararg, double) == 0) {
+            va_end (vararg);
+            return 0;
+        }
+    }
+    va_end (vararg);
+    return 1;
+}
+
+double orSB(int nargs, ...)
+{
+    int k;
+    va_list vararg;
+    va_start(vararg, nargs);
+    for (k=0; k<nargs; k++ ) {
+        if (va_arg(vararg, double) != 0) {
+            va_end (vararg);
+            return 1;
+        }
+    }
+    va_end (vararg);
+    return 0;
+}
+
+double piecewiseSB(int nargs, ...)
+{
+    int k, oddnumber;
+    double *data;
+    double returnvalue;
+    va_list vararg;
+    va_start(vararg, nargs);
+    /* Read in all variable input arguments in double array */
+    data = (double *)mxCalloc(nargs,sizeof(double));
+    for (k=0; k<nargs; k++ ) {
+        data[k] = va_arg(vararg, double);
+    }
+    /* 
+       Determine result
+       Check if odd or even number of input arguments
+     */
+    oddnumber = nargs % 2;
+    for (k=0;k<nargs-oddnumber;k+=2) {
+        if (data[k+1] != 0) {
+            returnvalue = data[k];
+            mxFree(data); /* free temporary array */
+            return returnvalue;
+        }
+    }
+    if (oddnumber != 0) {
+            returnvalue = data[nargs-1];
+            mxFree(data); /* free temporary array */
+            return returnvalue;
+    }
+    else {
+        mexErrMsgTxt("A piecewise statement is wrongly defined - missing (but needed) default value.");
+        mxFree(data); /* free temporary array */
+        return 0; /* statement never reached */
+    }
+}
+
+double piecewiseT0SB(int nargs, ...) /* does the same as the piecewiseSB function but does not lead to added events in the simulation model */
+{
+    int k, oddnumber;
+    double *data;
+    double returnvalue;
+    va_list vararg;
+    va_start(vararg, nargs);
+    /* Read in all variable input arguments in double array */
+    data = (double *)mxCalloc(nargs,sizeof(double));
+    for (k=0; k<nargs; k++ ) {
+        data[k] = va_arg(vararg, double);
+    }
+    /* 
+       Determine result
+       Check if odd or even number of input arguments
+     */
+    oddnumber = nargs % 2;
+    for (k=0;k<nargs-oddnumber;k+=2) {
+        if (data[k+1] != 0) {
+            returnvalue = data[k];
+            mxFree(data); /* free temporary array */
+            return returnvalue;
+        }
+    }
+    if (oddnumber != 0) {
+            returnvalue = data[nargs-1];
+            mxFree(data); /* free temporary array */
+            return returnvalue;
+    }
+    else {
+        mexErrMsgTxt("A piecewise statement is wrongly defined - missing (but needed) default value.");
+        mxFree(data); /* free temporary array */
+        return 0; /* statement never reached */
+    }
+}
+
+
+double piecewiseSmoothSB(double t,double y0,double y1,double alpha) 
+{
+
+return (y0+y1*exp(alpha*t))/(1+exp(alpha*t));
+
+}
+        
+
+double gt(double a, double b)
+{
+    if (a > b) return 1;
+    else return 0;
+}
+
+double ge(double a, double b)
+{
+    if (a >= b) return 1;
+    else return 0;
+}
+
+double lt(double a, double b)
+{
+    if (a < b) return 1;
+    else return 0;
+}
+
+double le(double a, double b)
+{
+    if (a <= b) return 1;
+    else return 0;
+}
+
+double eq(double a, double b)
+{
+    if (a*b < 0) return 0;
+    else if ( absSB(a-b) < 10.0*mxGetEps() ) return 1;
+    else return 0;
+}
+
+/* THIS FUNCTION IS NOT NEEDED ANYMORE ... in SBPDmakeMEXmodel the relevant parts have been commented out 
+ * and in SBPDsimulate a check has been included that gives an error is a model contains a delaySB function.
+ *
+double delaySB(double input, double tau, double time, char *queuename)
+{
+    mxArray *callArg[4];
+    mxArray *outArg[1];
+    callArg[0] = mxCreateDoubleScalar(input);
+    callArg[1] = mxCreateDoubleScalar(tau);
+    callArg[2] = mxCreateDoubleScalar(time);
+    callArg[3] = mxCreateString(queuename);
+    mexCallMATLAB(1, outArg, 4, callArg, "delaySB");
+    return mxGetScalar(outArg[0]);
+}
+*/
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/mexsplineaddon.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/mexsplineaddon.h
new file mode 100644
index 0000000000000000000000000000000000000000..ce7bfda5212b4b89c4f4533a7744135bac94e317
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/mexsplineaddon.h
@@ -0,0 +1,1895 @@
+/*
+ * mexsplineaddon.h: contains the function interpcseSB, interpcsexSB and '
+ *      the function interpcsSB
+ *      Cubic spline interpolation with (and without) endpoints for use 
+ *      by the CVODE integrator in the SBPD package
+ *
+ * The interpcsSB is a function for cubic spline interpolation, but without the 
+ * possibility of defining slopes at the endpoints.
+ * 
+ * The interpcseSB function allows to define slopes at the endpoints. The 
+ * spline coefficients are only calculated once and then only evaluated (faster)
+ * 
+ * the interpcsexSB function determines the spline coefficients each time, allowing to 
+ * implement time dependent spline functions (slower).
+ *
+ */
+
+/* interpcseSB and interpcsexSB FUNCTIONS:
+ * Original C-code for spline interpolation taken from:
+ *   http://www.mech.uq.edu.au/staff/jacobs/nm_lib/cmathsrc/spline.c
+ *
+ * The syntax of this MEX function (to be used via CVODE interface) is as follows:
+ *
+ * yy = interpcseSB(nargs,n,x1,x2,...,xn,y1,y2,...,yn,xx)
+ * yy = interpcseSB(nargs,n,e1,e2,x1,x2,...,xn,y1,y2,...,yn,xx)
+ *
+ * nargs:  number of arguments
+ * n:      number of points in the x and y vectors
+ * xi:     x-values 
+ * yi:     y-values
+ * xx:     x-value at which to evaluate the spline function (do NOT allow multiple)
+ * e1,e2:  endpoint derivatives (if specified, both need to be given)
+ * yy:     interpolated value
+ */
+
+/*
+ *========================================================================
+ * Initialization of the spline related functions
+ *========================================================================
+ */
+void spline (int n, int e1, int e2, double s1, double s2, double x[], double y[], double b[], double c[], double d[], int *flag);
+double seval (int n, double xx, double x[], double y[], double b[], double c[], double d[], int *last);
+double deriv (int n, double xx, double x[], double b[], double c[], double d[], int *last);
+
+/*
+ *========================================================================
+ * Declare variables for the interpcseSB function
+ *========================================================================
+ */
+#define MAX_INTERPCSESB 10000    /* defined maximum number of interpcseSB functions in the model */
+int*    interpcseSB_check = NULL; /* is initialized each new integration start to NULL ... required */
+double* xvec[MAX_INTERPCSESB];
+double* yvec[MAX_INTERPCSESB];
+double* bvec[MAX_INTERPCSESB];
+double* cvec[MAX_INTERPCSESB];
+double* dvec[MAX_INTERPCSESB];
+
+int*    interpcseSlopeSB_check = NULL; /* is initialized each new integration start to NULL ... required */
+double* xvecslope[MAX_INTERPCSESB];
+double* yvecslope[MAX_INTERPCSESB];
+double* bvecslope[MAX_INTERPCSESB];
+double* cvecslope[MAX_INTERPCSESB];
+double* dvecslope[MAX_INTERPCSESB];
+
+/*
+ *========================================================================
+ * INTERFACE FUNCTION for interpcseSB ... 
+ *========================================================================
+ */
+double interpcseSB(int nargs, ...)
+{
+    /*************************************************************/
+    /* Define the variables needed for the spline function calls */
+    /*************************************************************/
+    int    index_pw; /* index of the interpcseSB function */
+    int    n;
+    double *x;
+    double *y;
+    double xx;
+    double s1,s2;
+    int    e1,e2;
+    double *b;
+    double *c;
+    double *d;
+    int    flag;
+    int    last;
+    int    k;
+    double yy;
+    int    newCall;
+    double b2,c2,d2,x0,x1,y0,y1;
+    
+    /***************************************/
+    /* Handle the variable input arguments */
+    /***************************************/
+    /* Initialize the va_list */
+    va_list vararg;
+    va_start(vararg, nargs);
+    /* Get the index of the current interpcseSB function */
+    index_pw = (int) va_arg(vararg, double);
+    /* Get the number of the x and y axis nodes for interpolation */
+    n = (int) va_arg(vararg, double);
+    /* Get the xx value at which to interpolate */
+    xx = va_arg(vararg, double);
+    
+    /* Check if too many interpcseSB functions in the model (unlikely) */
+    if (index_pw >= MAX_INTERPCSESB) {
+        mexErrMsgTxt("interpcseSB_CVODE: To many calls to interpcseSB in the model.");
+    }
+    
+    /* Check if memory already obtained for handling the different calls */
+    if (interpcseSB_check == NULL) interpcseSB_check = (int *) mxCalloc(MAX_INTERPCSESB, sizeof(int));
+    
+    /* Check if new call or subsequent call */
+    if (interpcseSB_check[index_pw] == 69) {
+        newCall = 0;
+    } else {
+        newCall = 1;
+        interpcseSB_check[index_pw] = 69;
+    }
+
+    if (newCall == 1 || n == 2) {
+        /* First call to this function ... get the information */
+        /* Check if the number of input argument is plausible and define slopes */
+        if (nargs == 3+2*n) {
+            /* Plausible, but no slopes defined */
+            e1 = 0; s1 = 0; /* set s1 to 0 but it is not used */
+            e2 = 0; s2 = 0; /* set s2 to 0 but it is not used */
+        } else if (nargs == 3+2*n+2) {
+            /* Plausible, slopes are defined */
+            e1 = 1; s1 = va_arg(vararg, double);
+            e2 = 1; s2 = va_arg(vararg, double);
+        } else {
+            mexErrMsgTxt("interpcseSB_CVODE: Incorrect number of input arguments (increase MAX_INTERPCSESB in mexsplineaddon.h).");
+        }
+        
+        /***********/
+        /* If n==2 */
+        /***********/
+        if (n == 2) {
+            if (e1 == 0 || e2 == 0) mexErrMsgTxt("interpcseSB: n=2 requires the definition of slopes.");
+            x0 = va_arg(vararg, double);
+            x1 = va_arg(vararg, double);
+            y0 = va_arg(vararg, double);
+            y1 = va_arg(vararg, double);
+            /* End the variable input handling */
+            va_end (vararg);
+            b2 = s1;
+            c2 = -(-3.0*y1+3.0*y0+(s2+2.0*s1)*x1+(-s2-2.0*s1)*x0)/(pow(x1, 2.0)-2.0*x0*x1+pow(x0, 2.0));
+            d2 = (-2.0*y1+2.0*y0+(s2+s1)*x1+(-s2-s1)*x0)/(pow(x1, 3.0)-3.0*x0*pow(x1, 2.0)+3.0*pow(x0, 2.0)*x1-pow(x0, 3.0));
+            yy = y0 + b2*(xx-x0) + c2*pow(xx-x0, 2.0) + d2*pow(xx-x0, 3.0);   
+        } else {
+            /***********/
+            /* If n!=2 */
+            /***********/
+            /* Allocate memory for x and y */
+            x  = (double *) mxCalloc(n, sizeof(double));
+            y  = (double *) mxCalloc(n, sizeof(double));
+            /* Parse input arguments into x and y */
+            for (k=0;k<n;k++) x[k] = va_arg(vararg, double);
+            for (k=0;k<n;k++) y[k] = va_arg(vararg, double);
+            /* End the variable input handling */
+            va_end (vararg);
+        
+            /*****************************/
+            /* Allocate memory for b,c,d */
+            /*****************************/
+            b  = (double *) mxCalloc(n, sizeof(double));
+            c  = (double *) mxCalloc(n, sizeof(double));
+            d  = (double *) mxCalloc(n, sizeof(double));
+            
+            /****************************/
+            /* Call the spline function */
+            /****************************/
+            spline(n, e1, e2, s1, s2, x, y, b, c, d, &flag);
+            
+            /*********************************/
+            /* Save b,c,d,x,y for next calls */
+            /*********************************/
+            xvec[index_pw] = x;
+            yvec[index_pw] = y;
+            bvec[index_pw] = b;
+            cvec[index_pw] = c;
+            dvec[index_pw] = d;
+            
+            /***************************************/
+            /* Call the spline evaluation function */
+            /***************************************/
+            yy = seval (n, xx, x, y, b, c, d, &last);            
+        }
+    } else {
+        /* get x,y,b,c,d pointers */
+        x = xvec[index_pw];
+        y = yvec[index_pw];
+        b = bvec[index_pw];
+        c = cvec[index_pw];
+        d = dvec[index_pw];
+        /***************************************/
+        /* Call the spline evaluation function */
+        /***************************************/
+        yy = seval(n, xx, x, y, b, c, d, &last);
+    }
+    
+    /*********************************/
+    /* Return the interpolated value */
+    /*********************************/
+    return yy;
+}
+
+
+/*
+ *========================================================================
+ * INTERFACE FUNCTION for interpcseSB ... 
+ *========================================================================
+ */
+double interpcseSlopeSB(int nargs, ...)
+{
+    /*************************************************************/
+    /* Define the variables needed for the spline function calls */
+    /*************************************************************/
+    int    index_pw; /* index of the interpcseSlopeSB function */
+    int    n;
+    double *x;
+    double *y;
+    double xx;
+    double s1,s2;
+    int    e1,e2;
+    double *b;
+    double *c;
+    double *d;
+    int    flag;
+    int    last;
+    int    k;
+    double yy;
+    int    newCall;
+    double b2,c2,d2,x0,x1,y0,y1;
+    
+    /***************************************/
+    /* Handle the variable input arguments */
+    /***************************************/
+    /* Initialize the va_list */
+    va_list vararg;
+    va_start(vararg, nargs);
+    /* Get the index of the current interpcseSlopeSB function */
+    index_pw = (int) va_arg(vararg, double);
+    /* Get the number of the x and y axis nodes for interpolation */
+    n = (int) va_arg(vararg, double);
+    /* Get the xx value at which to interpolate */
+    xx = va_arg(vararg, double);
+    
+    /* Check if too many interpcseSlopeSB functions in the model (unlikely) */
+    if (index_pw >= MAX_INTERPCSESB) {
+        mexErrMsgTxt("interpcseSlopeSB_CVODE: To many calls to interpcseSB in the model.");
+    }
+    
+    /* Check if memory already obtained for handling the different calls */
+    if (interpcseSlopeSB_check == NULL) interpcseSlopeSB_check = (int *) mxCalloc(MAX_INTERPCSESB, sizeof(int));
+    
+    /* Check if new call or subsequent call */
+    if (interpcseSlopeSB_check[index_pw] == 69) {
+        newCall = 0;
+    } else {
+        newCall = 1;
+        interpcseSlopeSB_check[index_pw] = 69;
+    }
+
+    if (newCall == 1 || n == 2) {
+        /* First call to this function ... get the information */
+        /* Check if the number of input argument is plausible and define slopes */
+        if (nargs == 3+2*n) {
+            /* Plausible, but no slopes defined */
+            e1 = 0; s1 = 0; /* set s1 to 0 but it is not used */
+            e2 = 0; s2 = 0; /* set s2 to 0 but it is not used */
+        } else if (nargs == 3+2*n+2) {
+            /* Plausible, slopes are defined */
+            e1 = 1; s1 = va_arg(vararg, double);
+            e2 = 1; s2 = va_arg(vararg, double);
+        } else {
+            mexErrMsgTxt("interpcseSlopeSB_CVODE: Incorrect number of input arguments (increase MAX_INTERPCSESB in mexsplineaddon.h).");
+        }
+        
+        /***********/
+        /* If n==2 */
+        /***********/
+        if (n == 2) {
+            if (e1 == 0 || e2 == 0) mexErrMsgTxt("interpcseSlopeSB_CVODE: n=2 requires the definition of slopes.");
+            x0 = va_arg(vararg, double);
+            x1 = va_arg(vararg, double);
+            y0 = va_arg(vararg, double);
+            y1 = va_arg(vararg, double);
+            /* End the variable input handling */
+            va_end (vararg);
+            b2 = s1;
+            c2 = -(-3.0*y1+3.0*y0+(s2+2.0*s1)*x1+(-s2-2.0*s1)*x0)/(pow(x1, 2.0)-2.0*x0*x1+pow(x0, 2.0));
+            d2 = (-2.0*y1+2.0*y0+(s2+s1)*x1+(-s2-s1)*x0)/(pow(x1, 3.0)-3.0*x0*pow(x1, 2.0)+3.0*pow(x0, 2.0)*x1-pow(x0, 3.0));
+            yy = b2 + 2.0*c2*(xx-x0) + 3.0*d2*pow(xx-x0, 2.0);   
+        } else {
+            /***********/
+            /* If n!=2 */
+            /***********/
+            /* Allocate memory for x and y */
+            x  = (double *) mxCalloc(n, sizeof(double));
+            y  = (double *) mxCalloc(n, sizeof(double));
+            /* Parse input arguments into x and y */
+            for (k=0;k<n;k++) x[k] = va_arg(vararg, double);
+            for (k=0;k<n;k++) y[k] = va_arg(vararg, double);
+            /* End the variable input handling */
+            va_end (vararg);
+        
+            /*****************************/
+            /* Allocate memory for b,c,d */
+            /*****************************/
+            b  = (double *) mxCalloc(n, sizeof(double));
+            c  = (double *) mxCalloc(n, sizeof(double));
+            d  = (double *) mxCalloc(n, sizeof(double));
+            
+            /****************************/
+            /* Call the spline function */
+            /****************************/
+            spline(n, e1, e2, s1, s2, x, y, b, c, d, &flag);
+            
+            /*********************************/
+            /* Save b,c,d,x,y for next calls */
+            /*********************************/
+            xvecslope[index_pw] = x;
+            yvecslope[index_pw] = y;
+            bvecslope[index_pw] = b;
+            cvecslope[index_pw] = c;
+            dvecslope[index_pw] = d;
+            
+            /***************************************/
+            /* Call the spline evaluation function */
+            /***************************************/
+            yy = deriv(n, xx, x, b, c, d, &last);            
+        }
+    } else {
+        /* get x,y,b,c,d pointers */
+        x = xvecslope[index_pw];
+        y = yvecslope[index_pw];
+        b = bvecslope[index_pw];
+        c = cvecslope[index_pw];
+        d = dvecslope[index_pw];
+        /***************************************/
+        /* Call the spline evaluation function */
+        /***************************************/
+        yy = deriv(n, xx, x, b, c, d, &last);
+    }
+    
+    /*********************************/
+    /* Return the interpolated value */
+    /*********************************/
+    return yy;
+}
+
+/*
+ *========================================================================
+ * INTERFACE FUNCTION for interpcsexSB ... 
+ *========================================================================
+ */
+double interpcsexSB(int nargs, ...)
+{
+    /*************************************************************/
+    /* Define the variables needed for the spline function calls */
+    /*************************************************************/
+    int    n;
+    double *x;
+    double *y;
+    double xx;
+    double s1,s2;
+    int    e1,e2;
+    double *b;
+    double *c;
+    double *d;
+    int    flag;
+    int    last;
+    int    k;
+    double yy;
+    double b2, c2, d2;
+    double x0,x1,y0,y1;
+    
+    /***************************************/
+    /* Handle the variable input arguments */
+    /***************************************/
+    /* Initialize the va_list */
+    va_list vararg;
+    va_start(vararg, nargs);
+    /* Get the number of the x and y axis nodes for interpolation */
+    n = (int) va_arg(vararg, double);
+    /* Check if the number of input argument is plausible and define slopes */
+    if (nargs == 1+2*n+1) {
+        /* Plausible, but no slopes defined */
+        e1 = 0; s1 = 0; /* set s1 to 0 but it is not used */
+        e2 = 0; s2 = 0; /* set s2 to 0 but it is not used */
+    } else if (nargs == 1+2*n+1+2) {
+        /* Plausible, slopes are defined */
+        e1 = 1; s1 = va_arg(vararg, double);
+        e2 = 1; s2 = va_arg(vararg, double);
+    } else {
+        mexErrMsgTxt("interpcseSB_CVODE: Incorrect number of input arguments.");
+    }
+    
+    /***********/
+    /* If n==2 */
+    /***********/
+    if (n==2) {        
+        if (e1 == 0 || e2 == 0) mexErrMsgTxt("interpcseSB: n=2 requires the definition of slopes.");
+        x0 = va_arg(vararg, double);
+        x1 = va_arg(vararg, double);
+        y0 = va_arg(vararg, double);
+        y1 = va_arg(vararg, double);
+
+        /* Get the xx value at which to interpolate */
+        xx = va_arg(vararg, double);
+        /* End the variable input handling */
+        va_end(vararg);
+
+        b2 = s1;
+        c2 = -(-3.0*y1+3.0*y0+(s2+2.0*s1)*x1+(-s2-2.0*s1)*x0)/(pow(x1,2.0)-2.0*x0*x1+pow(x0,2.0));
+        d2 = (-2.0*y1+2.0*y0+(s2+s1)*x1+(-s2-s1)*x0)/(pow(x1,3.0)-3.0*x0*pow(x1,2.0)+3.0*pow(x0,2.0)*x1-pow(x0,3.0));
+        yy = y0 + b2*(xx-x0) + c2*pow(xx-x0,2.0) + d2*pow(xx-x0,3.0);
+    } else {
+        /***********/
+        /* If n!=2 */
+        /***********/
+        /* Allocate memory for x and y */
+        x  = (double *) mxCalloc(n, sizeof(double));
+        y  = (double *) mxCalloc(n, sizeof(double));
+        /* Parse input arguments into x and y */
+        for (k=0;k<n;k++) x[k] = va_arg(vararg, double);
+        for (k=0;k<n;k++) y[k] = va_arg(vararg, double);
+        
+        /* Get the xx value at which to interpolate */
+        xx = va_arg(vararg, double);
+        /* End the variable input handling */
+        va_end(vararg);
+        
+        /*****************************/
+        /* Allocate memory for b,c,d */
+        /*****************************/
+        b  = (double *) mxCalloc(n, sizeof(double));
+        c  = (double *) mxCalloc(n, sizeof(double));
+        d  = (double *) mxCalloc(n, sizeof(double));
+        
+        /****************************/
+        /* Call the spline function */
+        /****************************/
+        spline(n, e1, e2, s1, s2, x, y, b, c, d, &flag);
+        
+        /***************************************/
+        /* Call the spline evaluation function */
+        /***************************************/
+        yy = seval(n, xx, x, y, b, c, d, &last);
+        
+        /***************/
+        /* Free memory */
+        /***************/
+        mxFree(x);
+        mxFree(y);
+        mxFree(b);
+        mxFree(c);
+        mxFree(d);
+    }
+    
+    /*********************************/
+    /* Return the interpolated value */
+    /*********************************/
+    return yy;
+}
+
+
+/*
+ *========================================================================
+ * INTERFACE FUNCTION for interpcsexSlopeSB ... 
+ *========================================================================
+ */
+double interpcsexSlopeSB(int nargs, ...)
+{
+    /*************************************************************/
+    /* Define the variables needed for the spline function calls */
+    /*************************************************************/
+    int    n;
+    double *x;
+    double *y;
+    double xx;
+    double s1,s2;
+    int    e1,e2;
+    double *b;
+    double *c;
+    double *d;
+    int    flag;
+    int    last;
+    int    k;
+    double yy;
+    double b2, c2, d2;
+    double x0,x1,y0,y1;
+    
+    /***************************************/
+    /* Handle the variable input arguments */
+    /***************************************/
+    /* Initialize the va_list */
+    va_list vararg;
+    va_start(vararg, nargs);
+    /* Get the number of the x and y axis nodes for interpolation */
+    n = (int) va_arg(vararg, double);
+    /* Check if the number of input argument is plausible and define slopes */
+    if (nargs == 1+2*n+1) {
+        /* Plausible, but no slopes defined */
+        e1 = 0; s1 = 0; /* set s1 to 0 but it is not used */
+        e2 = 0; s2 = 0; /* set s2 to 0 but it is not used */
+    } else if (nargs == 1+2*n+1+2) {
+        /* Plausible, slopes are defined */
+        e1 = 1; s1 = va_arg(vararg, double);
+        e2 = 1; s2 = va_arg(vararg, double);
+    } else {
+        mexErrMsgTxt("interpcsexSlopeSB_CVODE: Incorrect number of input arguments.");
+    }
+    
+    /***********/
+    /* If n==2 */
+    /***********/
+    if (n==2) {        
+        if (e1 == 0 || e2 == 0) mexErrMsgTxt("interpcsexSlopeSB: n=2 requires the definition of slopes.");
+        x0 = va_arg(vararg, double);
+        x1 = va_arg(vararg, double);
+        y0 = va_arg(vararg, double);
+        y1 = va_arg(vararg, double);
+
+        /* Get the xx value at which to interpolate */
+        xx = va_arg(vararg, double);
+        /* End the variable input handling */
+        va_end(vararg);
+
+        b2 = s1;
+        c2 = -(-3.0*y1+3.0*y0+(s2+2.0*s1)*x1+(-s2-2.0*s1)*x0)/(pow(x1,2.0)-2.0*x0*x1+pow(x0,2.0));
+        d2 = (-2.0*y1+2.0*y0+(s2+s1)*x1+(-s2-s1)*x0)/(pow(x1,3.0)-3.0*x0*pow(x1,2.0)+3.0*pow(x0,2.0)*x1-pow(x0,3.0));
+        yy = b2 + 2.0*c2*(xx-x0) + 3.0*d2*pow(xx-x0,2.0);
+    } else {
+        /***********/
+        /* If n!=2 */
+        /***********/
+        /* Allocate memory for x and y */
+        x  = (double *) mxCalloc(n, sizeof(double));
+        y  = (double *) mxCalloc(n, sizeof(double));
+        /* Parse input arguments into x and y */
+        for (k=0;k<n;k++) x[k] = va_arg(vararg, double);
+        for (k=0;k<n;k++) y[k] = va_arg(vararg, double);
+        
+        /* Get the xx value at which to interpolate */
+        xx = va_arg(vararg, double);
+        /* End the variable input handling */
+        va_end(vararg);
+        
+        /*****************************/
+        /* Allocate memory for b,c,d */
+        /*****************************/
+        b  = (double *) mxCalloc(n, sizeof(double));
+        c  = (double *) mxCalloc(n, sizeof(double));
+        d  = (double *) mxCalloc(n, sizeof(double));
+        
+        /****************************/
+        /* Call the spline function */
+        /****************************/
+        spline(n, e1, e2, s1, s2, x, y, b, c, d, &flag);
+        
+        /***************************************/
+        /* Call the spline evaluation function */
+        /***************************************/
+        yy = deriv(n, xx, x, b, c, d, &last);
+        
+        /***************/
+        /* Free memory */
+        /***************/
+        mxFree(x);
+        mxFree(y);
+        mxFree(b);
+        mxFree(c);
+        mxFree(d);
+    }
+    
+    /*********************************/
+    /* Return the interpolated value */
+    /*********************************/
+    return yy;
+}
+
+/*=========================================================================
+   Cubic spline coefficients
+   -------------------------
+   Evaluate the coefficients b[i], c[i], d[i], i = 0, 1, .. n-1 for
+   a cubic interpolating spline
+
+   S(xx) = Y[i] + b[i] * w + c[i] * w**2 + d[i] * w**3
+   where w = xx - x[i]
+   and   x[i] <= xx <= x[i+1]
+
+   The n supplied data points are x[i], y[i], i = 0 ... n-1.
+
+   Input :
+   -------
+   n       : The number of data points or knots (n >= 2)
+   end1,
+   end2    : = 1 to specify the slopes at the end points
+             = 0 to obtain the default conditions
+   slope1,
+   slope2  : the slopes at the end points x[0] and x[n-1]
+             respectively
+   x[]     : the abscissas of the knots in strictly
+             increasing order
+   y[]     : the ordinates of the knots
+
+   Output :
+   --------
+   b, c, d : arrays of spline coefficients as defined above
+             (See note 2 for a definition.)
+   iflag   : status flag
+            = 0 normal return
+            = 1 less than two data points; cannot interpolate
+            = 2 x[] are not in ascending order
+
+   This C code written by ...  Peter & Nigel,
+   ----------------------      Design Software,
+                               42 Gubberley St,
+                               Kenmore, 4069,
+                               Australia.
+
+   Version ... 1.1, 30 September 1987
+   -------     2.0, 6 April 1989    (start with zero subscript)
+                                     remove ndim from parameter list
+               2.1, 28 April 1989   (check on x[])
+               2.2, 10 Oct   1989   change number order of matrix
+
+   Notes ...
+   -----
+   (1) The accompanying function seval() may be used to evaluate the
+       spline while deriv will provide the first derivative.
+   (2) Using p to denote differentiation
+       y[i] = S(X[i])
+       b[i] = Sp(X[i])
+       c[i] = Spp(X[i])/2
+       d[i] = Sppp(X[i])/6  ( Derivative from the right )
+   (3) Since the zero elements of the arrays ARE NOW used here,
+       all arrays to be passed from the main program should be
+       dimensioned at least [n].  These routines will use elements
+       [0 .. n-1].
+   (4) Adapted from the text
+       Forsythe, G.E., Malcolm, M.A. and Moler, C.B. (1977)
+       "Computer Methods for Mathematical Computations"
+       Prentice Hall
+   (5) Note that although there are only n-1 polynomial segments,
+       n elements are requird in b, c, d.  The elements b[n-1],
+       c[n-1] and d[n-1] are set to continue the last segment
+       past x[n-1].
+=========================================================================*/
+void spline (int n, int end1, int end2,
+            double slope1, double slope2,
+            double x[], double y[],
+            double b[], double c[], double d[],
+            int *iflag)
+{  /* begin procedure spline() */
+
+int    nm1, ib, i;
+double t;
+int    ascend;
+
+nm1    = n - 1;
+*iflag = 0;
+
+if (n < 2)
+  {  /* no possible interpolation */
+  *iflag = 1;
+  return;
+  }
+
+ascend = 1;
+for (i = 1; i < n; ++i) if (x[i] <= x[i-1]) ascend = 0;
+if (!ascend)
+   {
+   *iflag = 2;
+   return;
+   }
+
+if (n >= 3)
+   {    /* ---- At least quadratic ---- */
+
+   /* ---- Set up the symmetric tri-diagonal system
+           b = diagonal
+           d = offdiagonal
+           c = right-hand-side  */
+   d[0] = x[1] - x[0];
+   c[1] = (y[1] - y[0]) / d[0];
+   for (i = 1; i < nm1; ++i)
+      {
+      d[i]   = x[i+1] - x[i];
+      b[i]   = 2.0 * (d[i-1] + d[i]);
+      c[i+1] = (y[i+1] - y[i]) / d[i];
+      c[i]   = c[i+1] - c[i];
+      }
+
+   /* ---- Default End conditions
+           Third derivatives at x[0] and x[n-1] obtained
+           from divided differences  */
+   b[0]   = -d[0];
+   b[nm1] = -d[n-2];
+   c[0]   = 0.0;
+   c[nm1] = 0.0;
+   if (n != 3)
+      {
+      c[0]   = c[2] / (x[3] - x[1]) - c[1] / (x[2] - x[0]);
+      c[nm1] = c[n-2] / (x[nm1] - x[n-3]) - c[n-3] / (x[n-2] - x[n-4]);
+      c[0]   = c[0] * d[0] * d[0] / (x[3] - x[0]);
+      c[nm1] = -c[nm1] * d[n-2] * d[n-2] / (x[nm1] - x[n-4]);
+      }
+
+   /* Alternative end conditions -- known slopes */
+   if (end1 == 1)
+      {
+      b[0] = 2.0 * (x[1] - x[0]);
+      c[0] = (y[1] - y[0]) / (x[1] - x[0]) - slope1;
+      }
+   if (end2 == 1)
+      {
+      b[nm1] = 2.0 * (x[nm1] - x[n-2]);
+      c[nm1] = slope2 - (y[nm1] - y[n-2]) / (x[nm1] - x[n-2]);
+      }
+
+   /* Forward elimination */
+   for (i = 1; i < n; ++i)
+     {
+     t    = d[i-1] / b[i-1];
+     b[i] = b[i] - t * d[i-1];
+     c[i] = c[i] - t * c[i-1];
+     }
+
+   /* Back substitution */
+   c[nm1] = c[nm1] / b[nm1];
+   for (ib = 0; ib < nm1; ++ib)
+      {
+      i    = n - ib - 2;
+      c[i] = (c[i] - d[i] * c[i+1]) / b[i];
+      }
+
+   /* c[i] is now the sigma[i] of the text */
+
+   /* Compute the polynomial coefficients */
+   b[nm1] = (y[nm1] - y[n-2]) / d[n-2] + d[n-2] * (c[n-2] + 2.0 * c[nm1]);
+   for (i = 0; i < nm1; ++i)
+      {
+      b[i] = (y[i+1] - y[i]) / d[i] - d[i] * (c[i+1] + 2.0 * c[i]);
+      d[i] = (c[i+1] - c[i]) / d[i];
+      c[i] = 3.0 * c[i];
+      }
+   c[nm1] = 3.0 * c[nm1];
+   d[nm1] = d[n-2];
+
+   }  /* at least quadratic */
+
+else  /* if n >= 3 */
+   {  /* linear segment only  */
+   b[0] = (y[1] - y[0]) / (x[1] - x[0]);
+   c[0] = 0.0;
+   d[0] = 0.0;
+   b[1] = b[0];
+   c[1] = 0.0;
+   d[1] = 0.0;
+   }
+}  /* end of spline() */
+
+
+/*-------------------------------------------------------------------*/
+/*-----------------------------------------------------------------*/
+/*-----------------------------------------------------------------*/
+double seval (int n, double u,
+              double x[], double y[],
+              double b[], double c[], double d[],
+              int *last)
+/*-----------------------------------------------------------------*/
+/*Purpose ...
+  -------
+  Evaluate the cubic spline function
+
+  S(xx) = y[i] + b[i] * w + c[i] * w**2 + d[i] * w**3
+  where w = u - x[i]
+  and   x[i] <= u <= x[i+1]
+  Note that Horner's rule is used.
+  If u < x[0]   then i = 0 is used.
+  If u > x[n-1] then i = n-1 is used.
+
+  Input :
+  -------
+  n       : The number of data points or knots (n >= 2)
+  u       : the abscissa at which the spline is to be evaluated
+  Last    : the segment that was last used to evaluate U
+  x[]     : the abscissas of the knots in strictly increasing order
+  y[]     : the ordinates of the knots
+  b, c, d : arrays of spline coefficients computed by spline().
+
+  Output :
+  --------
+  seval   : the value of the spline function at u
+  Last    : the segment in which u lies
+
+  Notes ...
+  -----
+  (1) If u is not in the same interval as the previous call then a
+      binary search is performed to determine the proper interval.
+
+*/
+/*-------------------------------------------------------------------*/
+{  /* begin function seval() */
+
+int    i, j, k;
+double w;
+
+i = *last;
+if (i >= n-1) i = 0;
+if (i < 0)  i = 0;
+
+if ((x[i] > u) || (x[i+1] < u))
+  {  /* ---- perform a binary search ---- */
+  i = 0;
+  j = n;
+  do
+    {
+    k = (i + j) / 2;         /* split the domain to search */
+    if (u < x[k])  j = k;    /* move the upper bound */
+    if (u >= x[k]) i = k;    /* move the lower bound */
+    }                        /* there are no more segments to search */
+  while (j > i+1);
+  }
+*last = i;
+
+/* ---- Evaluate the spline ---- */
+w = u - x[i];
+w = y[i] + w * (b[i] + w * (c[i] + w * d[i]));
+return (w);
+}
+/*-------------------------------------------------------------------*/
+
+/*-------------------------------------------------------------------*/
+/*-----------------------------------------------------------------*/
+/*-----------------------------------------------------------------*/
+double deriv (int n, double u,
+              double x[],
+              double b[], double c[], double d[],
+              int *last)
+/*-----------------------------------------------------------------*/
+/* Purpose ...
+   -------
+   Evaluate the derivative of the cubic spline function
+
+   S(x) = B[i] + 2.0 * C[i] * w + 3.0 * D[i] * w**2
+   where w = u - X[i]
+   and   X[i] <= u <= X[i+1]
+   Note that Horner's rule is used.
+   If U < X[0] then i = 0 is used.
+   If U > X[n-1] then i = n-1 is used.
+
+   Input :
+   -------
+   n       : The number of data points or knots (n >= 2)
+   u       : the abscissa at which the derivative is to be evaluated
+   last    : the segment that was last used
+   x       : the abscissas of the knots in strictly increasing order
+   b, c, d : arrays of spline coefficients computed by spline()
+
+   Output :
+   --------
+   deriv : the value of the derivative of the spline
+           function at u
+   last  : the segment in which u lies
+
+   Notes ...
+   -----
+   (1) If u is not in the same interval as the previous call then a
+       binary search is performed to determine the proper interval.
+
+*/
+/*-------------------------------------------------------------------*/
+{  /* begin function deriv() */
+
+int    i, j, k;
+double w;
+
+i = *last;
+if (i >= n-1) i = 0;
+if (i < 0) i = 0;
+
+if ((x[i] > u) || (x[i+1] < u))
+  {  /* ---- perform a binary search ---- */
+  i = 0;
+  j = n;
+  do
+    {
+    k = (i + j) / 2;          /* split the domain to search */
+    if (u < x[k])  j = k;     /* move the upper bound */
+    if (u >= x[k]) i = k;     /* move the lower bound */
+    }                         /* there are no more segments to search */
+  while (j > i+1);
+  }
+*last = i;
+
+/* ---- Evaluate the derivative ---- */
+w = u - x[i];
+w = b[i] + w * (2.0 * c[i] + w * 3.0 * d[i]);
+return (w);
+
+} /* end of deriv() */
+/*-------------------------------------------------------------------*/
+
+
+
+
+
+
+
+
+
+
+
+
+
+/*************************************************************/
+/*************************************************************/
+/*************************************************************/
+/*************************************************************/
+/*************************************************************/
+/* interpcsSB function ... MEX version for CVODE use in SBPD */
+/*************************************************************/
+
+void spline_pchip_set( int n, double x[], double f[], double d[] );
+void spline_pchip_val( int n, double x[], double f[], double d[],  int ne, double xe, double *feptr );
+int i4_max( int i1, int i2 );
+int chfev( double x1, double x2, double f1, double f2, double d1, double d2, int ne, double xe, double *feptr, int next[] );
+double r8_min( double x, double y );
+double r8_max( double x, double y );
+double pchst( double arg1, double arg2 );
+
+
+/****************************************************************************/
+
+double interpcsSB(int nargs, int n, double xe, ...)
+
+/****************************************************************************
+
+  Purpose:
+
+    interpcsSB is the calling function to evaluate a piecewise cubic spline 
+    function and calculte the Hermite interpolant.
+
+
+  Modified:
+
+    1 October 2007
+
+  Author:
+
+    Basti Bergdahl,
+    Department of Applied Microbiology,
+    Lund Insitute of Technology.
+
+  Calling syntax:
+
+    interpcsSB(NARGS, N, XE, X1,...,XN,F1,...,FN)
+
+  Parameters:
+
+    Input, int NARGS, the total number of input arguments (not counting NARGS itself).
+    The number should be even, otherwise an error will occure.
+
+    Input, int N, the number of data points (rows in the table).  N must be at least 2.
+
+    Input, double XE, point at which the function is to be evaluated.
+
+    Input, double X1,...,XN, the strictly increasing independent variable values.
+
+    Input, double F1,...,FN, dependent variable values to be interpolated.  This
+    routine is designed for monotonic data, but it will work for any F-array.
+    It will force extrema at points where monotonicity switches direction.
+
+    Output, double FE, the value of the cubic Hermite function at XE.
+*/
+{
+    va_list vararg;
+    int k, oddnumber;
+    int ne = 1;
+    double *data, *x, *f, *d, *feptr;
+    double fe;
+
+    /* Check if table data has been given */
+    if (nargs == 2)
+    {
+        mexErrMsgTxt("interpcsSB error: Input incorrect. No data for the table has been supplied.");
+        return 0;
+    }
+
+    /* Check if odd or even number of input arguments */
+    oddnumber = nargs % 2;
+    if (oddnumber != 0)
+    {
+        mexErrMsgTxt("interpcsSB error: Input incorrect. The number of inputs should be even.");
+        return 0;
+    }
+
+    /* If number of input arguments in odd, check if
+     * the X and Y vectors are of the same size */
+    if ((nargs-2)/2 != n)
+    {
+        mexErrMsgTxt("interpcsSB error: Input incorrect. The X and Y vectors are either of different lengths or");
+        mexErrMsgTxt("an incorrect number for the data points has been given.");
+        return 0;
+    }
+
+    /* Read in all variable input arguments in double array */    
+    va_start(vararg, xe);
+    data = (double *)mxCalloc((n*2),sizeof(double));
+    for (k=0; k<nargs-2; k++ )
+    {
+        data[k] = va_arg(vararg, double);
+    }
+
+    /* Create the X and Y arrays making up the table */
+    x = (double *)mxCalloc(n,sizeof(double));
+    f = (double *)mxCalloc(n,sizeof(double));
+    for (k=0; k<n; k++)
+    {
+        x[k] = data[k];
+        f[k] = data[k+n];
+    }
+    mxFree(data); /* free temporary array */
+
+    /* handle off limit values */
+    if (xe < x[0]) return(f[0]);
+    if (xe > x[n-1]) return(f[n-1]);
+    
+    /* Calculate the derivatives for the piecewise cubic Hermite interpolant */
+    d = (double *)mxCalloc(n,sizeof(double));
+    spline_pchip_set(n, x, f, d);
+
+    /* Evaluate the cubic Hermite function at x */    
+    feptr = &fe;
+    spline_pchip_val(n, x, f, d, ne, xe, feptr);
+
+    return(fe);
+}
+
+
+
+/****************************************************************************/
+
+void spline_pchip_set( int n, double x[], double f[], double d[] )
+
+/****************************************************************************
+
+  Purpose:
+
+    SPLINE_PCHIP_SET sets derivatives for a piecewise cubic Hermite interpolant.
+
+  Discussion:
+
+    This routine computes what would normally be called a Hermite
+    interpolant.  However, the user is only required to supply function
+    values, not derivative values as well.  This routine computes
+    "suitable" derivative values, so that the resulting Hermite interpolant
+    has desirable shape and monotonicity properties.
+
+    The interpolant will have an extremum at each point where
+    monotonicity switches direction.
+
+    The resulting piecewise cubic Hermite function may be evaluated
+    by SPLINE_PCHIP_VAL..
+
+    This routine was originally called "PCHIM".
+
+  Modified:
+
+    14 August 2005
+
+  Author:
+
+    Fred Fritsch,
+    Mathematics and Statistics Division,
+    Lawrence Livermore National Laboratory.
+
+    C++ translation by John Burkardt.
+
+  Reference:
+
+    Fred Fritsch, Ralph Carlson,
+    Monotone Piecewise Cubic Interpolation,
+    SIAM Journal on Numerical Analysis,
+    Volume 17, Number 2, April 1980, pages 238-246.
+
+    Fred Fritsch, Judy Butland,
+    A Method for Constructing Local Monotone Piecewise
+    Cubic Interpolants,
+    SIAM Journal on Scientific and Statistical Computing,
+    Volume 5, Number 2, 1984, pages 300-304.
+
+  Parameters:
+
+    Input, int N, the number of data points.  N must be at least 2.
+
+    Input, double X[N], the strictly increasing independent
+    variable values.
+
+    Input, double F[N], dependent variable values to be interpolated.  This
+    routine is designed for monotonic data, but it will work for any F-array.
+    It will force extrema at points where monotonicity switches direction.
+
+    Output, double D[N], the derivative values at the
+    data points.  If the data are monotonic, these values will determine
+    a monotone cubic Hermite function.
+*/
+{
+  double del1;
+  double del2;
+  double dmax;
+  double dmin;
+  double drat1;
+  double drat2;
+  double dsave;
+  double h1;
+  double h2;
+  double hsum;
+  double hsumt3;
+  int i;
+  int ierr;
+  int nless1;
+  double temp;
+  double w1;
+  double w2;
+
+  /*  Check the arguments. */
+
+  if ( n < 2 )
+  {
+    ierr = -1;
+    mexErrMsgTxt("\n");
+    mexErrMsgTxt("SPLINE_PCHIP_SET - Fatal error!\n");
+    mexErrMsgTxt("  Number of data points less than 2.\n");
+    exit ( ierr );
+  }
+
+  for ( i = 1; i < n; i++ )
+  {
+    if ( x[i] <= x[i-1] )
+    {
+      ierr = -3;
+      mexErrMsgTxt("\n");
+      mexErrMsgTxt("SPLINE_PCHIP_SET - Fatal error!\n");
+      mexErrMsgTxt("  X array not strictly increasing.\n");
+      exit ( ierr );
+    }
+  }
+
+  ierr = 0;
+  nless1 = n - 1;
+  h1 = x[1] - x[0];
+  del1 = ( f[1] - f[0] ) / h1;
+  dsave = del1;
+
+/*  Special case N=2, use linear interpolation. */
+
+  if ( n == 2 )
+  {
+    d[0] = del1;
+    d[n-1] = del1;
+    return;
+  }
+
+/*  Normal case, 3 <= N. */
+
+  h2 = x[2] - x[1];
+  del2 = ( f[2] - f[1] ) / h2;
+
+/*  Set D(1) via non-centered three point formula, adjusted to be
+    shape preserving. */
+
+  hsum = h1 + h2;
+  w1 = ( h1 + hsum ) / hsum;
+  w2 = -h1 / hsum;
+  d[0] = w1 * del1 + w2 * del2;
+
+  if ( pchst ( d[0], del1 ) <= 0.0 )
+  {
+    d[0] = 0.0;
+  }
+
+/*  Need do this check only if monotonicity switches. */
+
+  else if ( pchst ( del1, del2 ) < 0.0 )
+  {
+     dmax = 3.0 * del1;
+
+     if ( fabs ( dmax ) < fabs ( d[0] ) )
+     {
+       d[0] = dmax;
+     }
+
+  }
+
+/*  Loop through interior points. */
+
+  for ( i = 2; i <= nless1; i++ )
+  {
+    if ( 2 < i )
+    {
+      h1 = h2;
+      h2 = x[i] - x[i-1];
+      hsum = h1 + h2;
+      del1 = del2;
+      del2 = ( f[i] - f[i-1] ) / h2;
+    }
+
+/*  Set D(I)=0 unless data are strictly monotonic. */
+
+    d[i-1] = 0.0;
+
+    temp = pchst ( del1, del2 );
+
+    if ( temp < 0.0 )
+    {
+      ierr = ierr + 1;
+      dsave = del2;
+    }
+
+/*  Count number of changes in direction of monotonicity. */
+
+    else if ( temp == 0.0 )
+    {
+      if ( del2 != 0.0 )
+      {
+        if ( pchst ( dsave, del2 ) < 0.0 )
+        {
+          ierr = ierr + 1;
+        }
+        dsave = del2;
+      }
+    }
+
+/*  Use Brodlie modification of Butland formula. */
+
+    else
+    {
+      hsumt3 = 3.0 * hsum;
+      w1 = ( hsum + h1 ) / hsumt3;
+      w2 = ( hsum + h2 ) / hsumt3;
+      dmax = r8_max ( fabs ( del1 ), fabs ( del2 ) );
+      dmin = r8_min ( fabs ( del1 ), fabs ( del2 ) );
+      drat1 = del1 / dmax;
+      drat2 = del2 / dmax;
+      d[i-1] = dmin / ( w1 * drat1 + w2 * drat2 );
+    }
+  }
+
+/*  Set D(N) via non-centered three point formula, adjusted to be
+    shape preserving. */
+
+  w1 = -h2 / hsum;
+  w2 = ( h2 + hsum ) / hsum;
+  d[n-1] = w1 * del1 + w2 * del2;
+
+  if ( pchst ( d[n-1], del2 ) <= 0.0 )
+  {
+    d[n-1] = 0.0;
+  }
+  else if ( pchst ( del1, del2 ) < 0.0 )
+  {
+
+/*  Need do this check only if monotonicity switches. */
+
+    dmax = 3.0 * del2;
+
+    if ( fabs ( dmax ) < abs ( d[n-1] ) )
+    {
+      d[n-1] = dmax;
+    }
+
+  }
+  return;
+}
+
+/****************************************************************************/
+
+void spline_pchip_val( int n, double x[], double f[], double d[],
+  int ne, double xe, double *feptr )
+
+/****************************************************************************
+
+  Purpose:
+
+    SPLINE_PCHIP_VAL evaluates a piecewise cubic Hermite function.
+
+  Description:
+
+    This routine may be used by itself for Hermite interpolation, or as an
+    evaluator for SPLINE_PCHIP_SET.
+
+    This routine evaluates the cubic Hermite function at the points XE.
+
+    Most of the coding between the call to CHFEV and the end of
+    the IR loop could be eliminated if it were permissible to
+    assume that XE is ordered relative to X.
+
+    CHFEV does not assume that X1 is less than X2.  Thus, it would
+    be possible to write a version of SPLINE_PCHIP_VAL that assumes a strictly
+    decreasing X array by simply running the IR loop backwards
+    and reversing the order of appropriate tests.
+
+    The present code has a minor bug, which I have decided is not
+    worth the effort that would be required to fix it.
+    If XE contains points in [X(N-1),X(N)], followed by points less than
+    X(N-1), followed by points greater than X(N), the extrapolation points
+    will be counted (at least) twice in the total returned in IERR.
+
+    The evaluation will be most efficient if the elements of XE are
+    increasing relative to X; that is, for all J <= K,
+      X(I) <= XE(J)
+    implies
+      X(I) <= XE(K).
+
+    If any of the XE are outside the interval [X(1),X(N)],
+    values are extrapolated from the nearest extreme cubic,
+    and a warning error is returned.
+
+    This routine was originally named "PCHFE".
+
+  Modified:
+
+    14 August 2005
+
+  Author:
+
+    Fred Fritsch,
+    Mathematics and Statistics Division,
+    Lawrence Livermore National Laboratory.
+
+    C++ translation by John Burkardt.
+
+  Reference:
+
+    Fred Fritsch, Ralph Carlson,
+    Monotone Piecewise Cubic Interpolation,
+    SIAM Journal on Numerical Analysis,
+    Volume 17, Number 2, April 1980, pages 238-246.
+
+  Parameters:
+
+    Input, int N, the number of data points.  N must be at least 2.
+
+    Input, double X[N], the strictly increasing independent
+    variable values.
+
+    Input, double F[N], the function values.
+
+    Input, double D[N], the derivative values.
+
+    Input, int NE, the number of evaluation points.
+
+    Input, double XE, point at which the function is to
+    be evaluated.
+
+    Output, double FE, the value of the cubic Hermite
+    function at XE.
+*/
+{
+  int i;
+  int ierc;
+  int ierr;
+  int ir;
+  int j;
+  int j_first;
+  int j_new;
+  int j_save;
+  int next[2];
+  int nj;
+
+/*  Check arguments. */
+
+  if ( n < 2 )
+  {
+    ierr = -1;
+    mexErrMsgTxt("\n");
+    mexErrMsgTxt("SPLINE_PCHIP_VAL - Fatal error!\n");
+    mexErrMsgTxt("Number of data points less than 2.\n");
+    exit ( ierr );
+  }
+
+  for ( i = 1; i < n; i++ )
+  {
+    if ( x[i] <= x[i-1] )
+    {
+      ierr = -3;
+      mexErrMsgTxt("\n");
+      mexErrMsgTxt("SPLINE_PCHIP_VAL - Fatal error!\n");
+      mexErrMsgTxt("X array not strictly increasing.\n");
+      exit ( ierr );
+    }
+  }
+
+  if ( ne < 1 )
+  {
+    ierr = -4;
+    mexErrMsgTxt("\n");
+    mexErrMsgTxt("SPLINE_PCHIP_VAL - Fatal error!\n");
+    mexErrMsgTxt("Number of evaluation points less than 1.\n");
+    return;
+  }
+
+  ierr = 0;
+
+/*  Loop over intervals.
+  The interval index is IL = IR-1.
+  The interval is X(IL) <= X < X(IR).
+*/
+  j_first = 1;
+  ir = 2;
+
+  for ( ; ; )
+  {
+/*
+  Skip out of the loop if have processed all evaluation points.
+*/
+    if ( ne < j_first )
+    {
+      break;
+    }
+/*
+  Locate all points in the interval.
+*/
+    j_save = ne + 1;
+
+    for ( j = j_first; j <= ne; j++ )
+    {
+      if ( x[ir-1] <= xe )
+      {
+        j_save = j;
+        if ( ir == n )
+        {
+          j_save = ne + 1;
+        }
+        break;
+      }
+    }
+/*
+  Have located first point beyond interval.
+*/
+    j = j_save;
+
+    nj = j - j_first;
+/*
+  Skip evaluation if no points in interval.
+*/
+    if ( nj != 0 )
+    {
+/*
+  Evaluate cubic at XE(J_FIRST:J-1).
+*/
+      ierc = chfev ( x[ir-2], x[ir-1], f[ir-2], f[ir-1], d[ir-2], d[ir-1],
+        nj, xe, feptr, next );
+
+      if ( ierc < 0 )
+      {
+        ierr = -5;
+        mexErrMsgTxt("\n");
+        mexErrMsgTxt("SPLINE_PCHIP_VAL - Fatal error!\n");
+        mexErrMsgTxt("Error return from CHFEV.\n");
+        exit ( ierr );
+      }
+/*
+  In the current set of XE points, there are NEXT(2) to the right of X(IR).
+*/
+      if ( next[1] != 0 )
+      {
+        if ( ir < n )
+        {
+          ierr = -5;
+          mexErrMsgTxt("\n");
+          mexErrMsgTxt("SPLINE_PCHIP_VAL - Fatal error!\n");
+          mexErrMsgTxt("IR < N.\n");
+          exit ( ierr );
+        }
+/*
+  These are actually extrapolation points.
+*/
+        ierr = ierr + next[1];
+
+      }
+/*
+  In the current set of XE points, there are NEXT(1) to the left of X(IR-1).
+*/
+      if ( next[0] != 0 )
+      {
+/*
+  These are actually extrapolation points.
+*/
+        if ( ir <= 2 )
+        {
+          ierr = ierr + next[0];
+        }
+        else
+        {
+          j_new = -1;
+
+          for ( i = j_first; i <= j-1; i++ )
+          {
+            if ( xe < x[ir-2] )
+            {
+              j_new = i;
+              break;
+            }
+          }
+
+          if ( j_new == -1 )
+          {
+            ierr = -5;
+            mexErrMsgTxt("\n");
+            mexErrMsgTxt("SPLINE_PCHIP_VAL - Fatal error!\n");
+            mexErrMsgTxt("  Could not bracket the data point.\n");
+            exit ( ierr );
+          }
+/*
+  Reset J.  This will be the new J_FIRST.
+*/
+          j = j_new;
+/*
+  Now find out how far to back up in the X array.
+*/
+          for ( i = 1; i <= ir-1; i++ )
+          {
+            if ( xe < x[i-1] )
+            {
+              break;
+            }
+          }
+/*
+  At this point, either XE(J) < X(1) or X(i-1) <= XE(J) < X(I) .
+
+  Reset IR, recognizing that it will be incremented before cycling.
+*/
+          ir = i4_max ( 1, i-1 );
+        }
+      }
+
+      j_first = j;
+    }
+
+    ir = ir + 1;
+
+    if ( n < ir )
+    {
+      break;
+    }
+
+  }
+
+  return;
+}
+
+/****************************************************************************/
+
+int chfev( double x1, double x2, double f1, double f2, double d1, double d2,
+  int ne, double xe, double *feptr, int next[] )
+
+/****************************************************************************
+
+  Purpose:
+
+    CHFEV evaluates a cubic polynomial given in Hermite form.
+
+  Discussion:
+
+    This routine evaluates a cubic polynomial given in Hermite form at an
+    array of points.  While designed for use by SPLINE_PCHIP_VAL, it may
+    be useful directly as an evaluator for a piecewise cubic
+    Hermite function in applications, such as graphing, where
+    the interval is known in advance.
+
+    The cubic polynomial is determined by function values
+    F1, F2 and derivatives D1, D2 on the interval [X1,X2].
+
+  Modified:
+
+    12 August 2005
+
+  Author:
+
+    Fred Fritsch,
+    Mathematics and Statistics Division,
+    Lawrence Livermore National Laboratory.
+
+    C++ translation by John Burkardt.
+
+  Reference:
+
+    Fred Fritsch, Ralph Carlson,
+    Monotone Piecewise Cubic Interpolation,
+    SIAM Journal on Numerical Analysis,
+    Volume 17, Number 2, April 1980, pages 238-246.
+
+    David Kahaner, Cleve Moler, Steven Nash,
+    Numerical Methods and Software,
+    Prentice Hall, 1989,
+    ISBN: 0-13-627258-4,
+    LC: TA345.K34.
+
+  Parameters:
+
+    Input, double X1, X2, the endpoints of the interval of
+    definition of the cubic.  X1 and X2 must be distinct.
+
+    Input, double F1, F2, the values of the function at X1 and
+    X2, respectively.
+
+    Input, double D1, D2, the derivative values at X1 and
+    X2, respectively.
+
+    Input, int NE, the number of evaluation points.
+
+    Input, double XE, the point at which the function is to
+    be evaluated.  If the value of XE is outside the interval
+    [X1,X2], a warning error is returned in NEXT.
+
+    Output, double FE, the value of the cubic function
+    at the point XE.
+
+    Output, int NEXT[2], indicates the number of extrapolation points:
+    NEXT[0] = number of evaluation points to the left of interval.
+    NEXT[1] = number of evaluation points to the right of interval.
+
+    Output, int CHFEV, error flag.
+    0, no errors.
+    -1, NE < 1.
+    -2, X1 == X2.
+*/
+{
+  double c2;
+  double c3;
+  double del1;
+  double del2;
+  double delta;
+  double h;
+  int ierr;
+  double x;
+  double fe;
+  double xma;
+  double xmi;
+
+  if ( ne < 1 )
+  {
+    ierr = -1;
+    mexErrMsgTxt("\n");
+    mexErrMsgTxt("CHFEV - Fatal error!\n");
+    mexErrMsgTxt("  Number of evaluation points is less than 1.\n");
+    printf("  NE = %d\n", ne);
+    return ierr;
+  }
+
+  h = x2 - x1;
+
+  if ( h == 0.0 )
+  {
+    ierr = -2;
+    mexErrMsgTxt("\n");
+    mexErrMsgTxt("CHFEV - Fatal error!\n");
+    mexErrMsgTxt("  The interval [X1,X2] is of zero length.\n");
+    return ierr;
+  }
+/*
+  Initialize.
+*/
+  ierr = 0;
+  next[0] = 0;
+  next[1] = 0;
+  xmi = r8_min ( 0.0, h );
+  xma = r8_max ( 0.0, h );
+/*
+  Compute cubic coefficients expanded about X1.
+*/
+  delta = ( f2 - f1 ) / h;
+  del1 = ( d1 - delta ) / h;
+  del2 = ( d2 - delta ) / h;
+  c2 = -( del1 + del1 + del2 );
+  c3 = ( del1 + del2 ) / h;
+    x = xe - x1;
+    fe = f1 + x * ( d1 + x * ( c2 + x * c3 ) );
+    *feptr = fe;
+/*
+  Count the extrapolation points.
+*/
+    if ( x < xmi )
+    {
+      next[0] = next[0] + 1;
+    }
+
+    if ( xma < x )
+    {
+      next[1] = next[1] + 1;
+    }
+
+
+  return 0;
+}
+
+/****************************************************************************/
+
+double pchst( double arg1, double arg2 )
+
+/****************************************************************************
+
+  Purpose:
+
+    PCHST: PCHIP sign-testing routine.
+
+  Discussion:
+
+    This routine essentially computes the sign of ARG1 * ARG2.
+
+    The object is to do this without multiplying ARG1 * ARG2, to avoid
+    possible over/underflow problems.
+
+  Modified:
+
+    12 August 2005
+
+  Author:
+
+    Fred Fritsch,
+    Mathematics and Statistics Division,
+    Lawrence Livermore National Laboratory.
+
+    C++ translation by John Burkardt.
+
+  Reference:
+
+    Fred Fritsch, Ralph Carlson,
+    Monotone Piecewise Cubic Interpolation,
+    SIAM Journal on Numerical Analysis,
+    Volume 17, Number 2, April 1980, pages 238-246.
+
+  Parameters:
+
+    Input, double ARG1, ARG2, two values to check.
+
+    Output, double PCHST,
+    -1.0, if ARG1 and ARG2 are of opposite sign.
+     0.0, if either argument is zero.
+    +1.0, if ARG1 and ARG2 are of the same sign.
+*/
+{
+  double value;
+
+  if ( arg1 == 0.0 )
+  {
+    value = 0.0;
+  }
+  else if ( arg1 < 0.0 )
+  {
+    if ( arg2 < 0.0 )
+    {
+      value = 1.0;
+    }
+    else if ( arg2 == 0.0 )
+    {
+      value = 0.0;
+    }
+    else if ( 0.0 < arg2 )
+    {
+      value = -1.0;
+    }
+  }
+  else if ( 0.0 < arg1 )
+  {
+    if ( arg2 < 0.0 )
+    {
+      value = -1.0;
+    }
+    else if ( arg2 == 0.0 )
+    {
+      value = 0.0;
+    }
+    else if ( 0.0 < arg2 )
+    {
+      value = 1.0;
+    }
+  }
+
+  return(value);
+}
+
+/****************************************************************************/
+
+double r8_max( double x, double y )
+
+/****************************************************************************
+
+  Purpose:
+
+    R8_MAX returns the maximum of two R8's.
+
+  Modified:
+
+    10 January 2002
+
+  Author:
+
+    John Burkardt
+
+  Parameters:
+
+    Input, double X, Y, the quantities to compare.
+
+    Output, double R8_MAX, the maximum of X and Y.
+*/
+{
+  if ( y < x )
+  {
+    return(x);
+  }
+  else
+  {
+    return(y);
+  }
+}
+/****************************************************************************/
+
+double r8_min( double x, double y )
+
+/****************************************************************************
+
+  Purpose:
+
+    R8_MIN returns the minimum of two R8's.
+
+  Modified:
+
+    09 May 2003
+
+  Author:
+
+    John Burkardt
+
+  Parameters:
+
+    Input, double X, Y, the quantities to compare.
+
+    Output, double R8_MIN, the minimum of X and Y.
+*/
+{
+  if ( y < x )
+  {
+    return(y);
+  }
+  else
+  {
+    return(x);
+  }
+}
+
+
+/****************************************************************************/
+
+int i4_max ( int i1, int i2 )
+
+/****************************************************************************
+
+  Purpose:
+
+    I4_MAX returns the maximum of two I4's.
+
+  Modified:
+
+    13 October 1998
+
+  Author:
+
+    John Burkardt
+
+  Parameters:
+
+    Input, int I1, I2, are two integers to be compared.
+
+    Output, int I4_MAX, the larger of I1 and I2.
+
+*/
+{
+  if ( i2 < i1 )
+  {
+    return(i1);
+  }
+  else
+  {
+    return(i2);
+  }
+
+}
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodea.c b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodea.c
new file mode 100644
index 0000000000000000000000000000000000000000..e5f0260d817b83ee0ead438a675ca2a789e01dca
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodea.c
@@ -0,0 +1,1805 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2006, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the implementation file for the CVODEA adjoint integrator.
+ * -----------------------------------------------------------------
+ */
+
+/* 
+ * =================================================================
+ * IMPORTED HEADER FILES
+ * =================================================================
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "cvodes_impl.h"
+
+#include <sundials/sundials_math.h>
+#include <sundials/sundials_types.h>
+
+/* 
+ * =================================================================
+ * MACRO DEFINITIONS
+ * =================================================================
+ */
+
+#define loop for(;;)
+
+/* 
+ * =================================================================
+ * CVODEA PRIVATE CONSTANTS
+ * =================================================================
+ */
+
+#define ZERO        RCONST(0.0)        /* real 0.0   */
+#define ONE         RCONST(1.0)        /* real 1.0   */
+#define TWO         RCONST(2.0)        /* real 2.0   */
+#define HUNDRED     RCONST(100.0)      /* real 100.0 */
+#define FUZZ_FACTOR RCONST(1000000.0)  /* fuzz factor for CVadjGetY */
+
+/* 
+ * =================================================================
+ * PRIVATE FUNCTION PROTOTYPES
+ * =================================================================
+ */
+
+static booleantype CVAallocVectors(CVadjMem ca_mem);
+static void CVAfreeVectors(CVadjMem ca_mem);
+
+static CkpntMem CVAckpntInit(CVodeMem cv_mem);
+static CkpntMem CVAckpntNew(CVodeMem cv_mem);
+static void CVAckpntDelete(CkpntMem *ck_memPtr);
+
+static int  CVAdataStore(CVadjMem ca_mem, CkpntMem ck_mem);
+static int  CVAckpntGet(CVodeMem cv_mem, CkpntMem ck_mem); 
+
+static int CVAfindIndex(CVadjMem ca_mem, realtype t, 
+                        long int *indx, booleantype *newpoint);
+
+static booleantype CVAhermiteMalloc(CVadjMem ca_mem, long int steps);
+static void CVAhermiteFree(DtpntMem *dt_mem, long int steps);
+static int CVAhermiteGetY(CVadjMem ca_mem, realtype t, N_Vector y);
+static int CVAhermiteStorePnt(CVodeMem cv_mem, DtpntMem d);
+
+static booleantype CVApolynomialMalloc(CVadjMem ca_mem, long int steps);
+static void CVApolynomialFree(DtpntMem *dt_mem, long int steps);
+static int CVApolynomialGetY(CVadjMem ca_mem, realtype t, N_Vector y);
+static int CVApolynomialStorePnt(CVodeMem cv_mem, DtpntMem d);
+
+/* Wrappers */
+
+static int CVArhs(realtype t, N_Vector yB, 
+                  N_Vector yBdot, void *cvadj_mem);
+
+static int CVArhsQ(realtype t, N_Vector yB, 
+                   N_Vector qBdot, void *cvadj_mem);
+
+/* 
+ * =================================================================
+ * EXPORTED FUNCTIONS IMPLEMENTATION
+ * =================================================================
+ */
+
+/* 
+ * -----------------------------------------------------------------
+ * Readibility Constants
+ * -----------------------------------------------------------------
+ */
+
+#define uround      (ca_mem->ca_uround)
+#define tinitial    (ca_mem->ca_tinitial)
+#define tfinal      (ca_mem->ca_tfinal)
+#define nckpnts     (ca_mem->ca_nckpnts)
+#define nsteps      (ca_mem->ca_nsteps)
+#define ckpntData   (ca_mem->ca_ckpntData)
+#define newData     (ca_mem->ca_newData)
+#define np          (ca_mem->ca_np)
+#define ytmp        (ca_mem->ca_ytmp)
+#define f_B         (ca_mem->ca_fB)
+#define f_data_B    (ca_mem->ca_f_dataB)
+#define fQ_B        (ca_mem->ca_fQB)
+#define fQ_data_B   (ca_mem->ca_fQ_dataB)
+#define t_for_quad  (ca_mem->ca_t_for_quad)
+#define Y0          (ca_mem->ca_Y0)
+#define Y1          (ca_mem->ca_Y1)
+#define Y           (ca_mem->ca_Y)
+#define T           (ca_mem->ca_T)
+#define interpType  (ca_mem->ca_interpType)
+#define getY        (ca_mem->ca_getY)
+#define storePnt    (ca_mem->ca_storePnt)
+#define lfreeB      (ca_mem->ca_lfreeB)
+
+#define zn         (cv_mem->cv_zn)
+#define nst        (cv_mem->cv_nst)
+#define q          (cv_mem->cv_q)
+#define qu         (cv_mem->cv_qu)
+#define qprime     (cv_mem->cv_qprime)
+#define qwait      (cv_mem->cv_qwait)
+#define L          (cv_mem->cv_L)
+#define gammap     (cv_mem->cv_gammap)
+#define h          (cv_mem->cv_h)
+#define hprime     (cv_mem->cv_hprime)
+#define hscale     (cv_mem->cv_hscale)
+#define eta        (cv_mem->cv_eta)
+#define etamax     (cv_mem->cv_etamax)
+#define tn         (cv_mem->cv_tn)
+#define tretlast   (cv_mem->cv_tretlast)
+#define tau        (cv_mem->cv_tau)
+#define tq         (cv_mem->cv_tq)
+#define l          (cv_mem->cv_l)
+#define saved_tq5  (cv_mem->cv_saved_tq5)
+#define forceSetup (cv_mem->cv_forceSetup)
+#define f          (cv_mem->cv_f)
+#define lmm        (cv_mem->cv_lmm)
+#define iter       (cv_mem->cv_iter)
+#define itol       (cv_mem->cv_itol)
+#define reltol     (cv_mem->cv_reltol)
+#define Sabstol    (cv_mem->cv_Sabstol)
+#define Vabstol    (cv_mem->cv_Vabstol)
+#define efun       (cv_mem->cv_efun)
+#define f_data     (cv_mem->cv_f_data)
+#define errfp      (cv_mem->cv_errfp)
+#define h0u        (cv_mem->cv_h0u)
+#define quadr      (cv_mem->cv_quadr)
+#define errconQ    (cv_mem->cv_errconQ)
+#define znQ        (cv_mem->cv_znQ)
+#define itolQ      (cv_mem->cv_itolQ)
+#define reltolQ    (cv_mem->cv_reltolQ)
+#define SabstolQ   (cv_mem->cv_SabstolQ)
+#define VabstolQ   (cv_mem->cv_VabstolQ)
+#define fQ         (cv_mem->cv_fQ)
+#define tempv      (cv_mem->cv_tempv)
+#define tempvQ     (cv_mem->cv_tempvQ)
+
+#define t0_        (ck_mem->ck_t0)
+#define t1_        (ck_mem->ck_t1)
+#define zn_        (ck_mem->ck_zn)
+#define znQ_       (ck_mem->ck_znQ)
+#define quadr_     (ck_mem->ck_quadr)
+#define zqm_       (ck_mem->ck_zqm)
+#define nst_       (ck_mem->ck_nst)
+#define tretlast_  (ck_mem->ck_tretlast)
+#define q_         (ck_mem->ck_q)
+#define qprime_    (ck_mem->ck_qprime)
+#define qwait_     (ck_mem->ck_qwait)
+#define L_         (ck_mem->ck_L)
+#define gammap_    (ck_mem->ck_gammap)
+#define h_         (ck_mem->ck_h)
+#define hprime_    (ck_mem->ck_hprime)
+#define hscale_    (ck_mem->ck_hscale)
+#define eta_       (ck_mem->ck_eta)
+#define etamax_    (ck_mem->ck_etamax)
+#define tau_       (ck_mem->ck_tau)
+#define tq_        (ck_mem->ck_tq)
+#define l_         (ck_mem->ck_l)
+#define saved_tq5_ (ck_mem->ck_saved_tq5)
+#define next_      (ck_mem->ck_next)
+
+/*
+ * CVadjMalloc
+ *
+ * This routine allocates space for the global CVODEA memory
+ * structure.
+ */
+
+void *CVadjMalloc(void *cvode_mem, long int steps, int interp)
+{
+  CVadjMem ca_mem;
+  CVodeMem cv_mem;
+  booleantype allocOK;
+  long int i, ii;
+
+  /* Check arguments */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, 0, "CVODEA", "CVadjMalloc", MSGAM_NULL_CVMEM);
+    return(NULL);
+  }
+  cv_mem = (CVodeMem)cvode_mem;
+
+  if (steps <= 0) {
+    CVProcessError(NULL, 0, "CVODEA", "CVadjMalloc", MSGAM_BAD_STEPS);
+    return(NULL);
+  }
+
+  if ( (interp != CV_HERMITE) && (interp != CV_POLYNOMIAL) ) {
+    CVProcessError(NULL, 0, "CVODEA", "CVadjMalloc", MSGAM_BAD_INTERP);
+    return(NULL);
+  } 
+
+  /* Allocate memory block */
+  ca_mem = NULL;
+  ca_mem = (CVadjMem) malloc(sizeof(struct CVadjMemRec));
+  if (ca_mem == NULL) {
+    CVProcessError(NULL, 0, "CVODEA", "CVadjMalloc", MSGAM_MEM_FAIL);
+    return(NULL);
+  }
+
+  /* Attach CVODES memory for forward runs */
+  ca_mem->cv_mem = cv_mem;
+
+  /* Set interpType */
+  interpType = interp;
+
+  /* Allocate memory for workspace vectors */
+  allocOK = CVAallocVectors(ca_mem);
+  if (!allocOK) {
+    free(ca_mem); ca_mem = NULL;
+    CVProcessError(NULL, 0, "CVODEA", "CVadjMalloc", MSGAM_MEM_FAIL);
+    return(NULL);
+  }
+
+  /* Initialize Check Points linked list */
+  ca_mem->ck_mem = NULL;
+  ca_mem->ck_mem = CVAckpntInit(cv_mem);
+  if (ca_mem->ck_mem == NULL) {
+    CVAfreeVectors(ca_mem);
+    free(ca_mem); ca_mem = NULL;
+    CVProcessError(NULL, 0, "CVODEA", "CVadjMalloc", MSGAM_MEM_FAIL);
+    return(NULL);
+  }
+
+  /* Allocate space for the array of Data Point structures */
+  
+  ca_mem->dt_mem = NULL;
+  ca_mem->dt_mem = (DtpntMem *) malloc((steps+1)*sizeof(struct DtpntMemRec *));
+  if (ca_mem->dt_mem == NULL) {
+    while (ca_mem->ck_mem != NULL) CVAckpntDelete(&(ca_mem->ck_mem));
+    CVAfreeVectors(ca_mem);
+    free(ca_mem); ca_mem = NULL;
+    CVProcessError(NULL, 0, "CVODEA", "CVadjMalloc", MSGAM_MEM_FAIL);
+    return(NULL);
+  }
+
+  for (i=0; i<=steps; i++) { 
+    ca_mem->dt_mem[i] = NULL;
+    ca_mem->dt_mem[i] = (DtpntMem) malloc(sizeof(struct DtpntMemRec));
+    if (ca_mem->dt_mem[i] == NULL) {
+      for(ii=0; ii<i; ii++) {free(ca_mem->dt_mem[ii]); ca_mem->dt_mem[ii] = NULL;}
+      free(ca_mem->dt_mem); ca_mem->dt_mem = NULL;
+      while (ca_mem->ck_mem != NULL) CVAckpntDelete(&(ca_mem->ck_mem));
+      CVAfreeVectors(ca_mem);
+      free(ca_mem); ca_mem = NULL;
+      CVProcessError(NULL, 0, "CVODEA", "CVadjMalloc", MSGAM_MEM_FAIL);
+      return(NULL);
+    }
+  }
+
+  switch (interpType) {
+
+  case CV_HERMITE:
+    /* Allocate Data Points memory */
+    allocOK = CVAhermiteMalloc(ca_mem, steps);
+    if (!allocOK) {
+      for(i=0; i<=steps; i++) {free(ca_mem->dt_mem[i]); ca_mem->dt_mem[i] = NULL;}
+      free(ca_mem->dt_mem); ca_mem->dt_mem = NULL;
+      while (ca_mem->ck_mem != NULL) CVAckpntDelete(&(ca_mem->ck_mem));
+      CVAfreeVectors(ca_mem);
+      free(ca_mem); ca_mem = NULL;
+      CVProcessError(NULL, 0, "CVODEA", "CVadjMalloc", MSGAM_MEM_FAIL);
+      return(NULL);
+    }
+    /* Attach interpolation functions getY and storePnt */
+    getY = CVAhermiteGetY;
+    storePnt = CVAhermiteStorePnt;
+    /* Rename zn[0] and zn[1] for use in interpolation */
+    Y0 = zn[0];
+    Y1 = zn[1];
+    break;
+  case CV_POLYNOMIAL:
+    /* Allocate Data Points memory */
+    allocOK = CVApolynomialMalloc(ca_mem, steps);
+    if (!allocOK) {
+      for(i=0; i<=steps; i++) {free(ca_mem->dt_mem[i]); ca_mem->dt_mem[i] = NULL;}
+      free(ca_mem->dt_mem); ca_mem->dt_mem = NULL;
+      while (ca_mem->ck_mem != NULL) CVAckpntDelete(&(ca_mem->ck_mem));
+      CVAfreeVectors(ca_mem);
+      free(ca_mem); ca_mem = NULL;
+      CVProcessError(NULL, 0, "CVODEA", "CVadjMalloc", MSGAM_MEM_FAIL);
+      return(NULL);
+    }
+    /* Attach interpolation functions getY and storePnt */
+    getY = CVApolynomialGetY;
+    storePnt = CVApolynomialStorePnt;
+    /* Rename zn for use in interpolation */
+    for (i=0;i<L_MAX;i++) Y[i] = zn[i];
+    break;
+  }
+
+  /* Other entries in ca_mem */
+  uround   = cv_mem->cv_uround;
+  nsteps   = steps;
+  tinitial = tn; 
+
+  /* Initialize nckpnts to ZERO */
+  nckpnts = 0;
+
+  /* Initialize backward cvode memory to NULL */
+  ca_mem->cvb_mem = NULL;
+
+  ca_mem->ca_lmemB = NULL;
+  ca_mem->ca_lfreeB = NULL;
+  ca_mem->ca_pmemB = NULL;
+  
+  ca_mem->ca_f_dataB = NULL;
+  ca_mem->ca_fQ_dataB = NULL;
+
+  return((void *)ca_mem);
+} 
+
+/* 
+ * CVadjSetInterpType
+ *
+ * Changes the interpolation type.
+ * Possible return values: CV_SUCCESS, CV_ADJMEM_NULL, CV_ILL_INPUT, CV_MEM_FAIL
+ */
+
+int CVadjSetInterpType(void *cvadj_mem, int interp)
+{
+  CVadjMem ca_mem;
+  CVodeMem cv_mem;
+  booleantype allocOK;
+  long int i;
+  
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CV_ADJMEM_NULL, "CVODEA", "CVadjSetInterpType", MSGAM_NULL_CAMEM);
+    return(CV_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  cv_mem = ca_mem->cv_mem;
+
+  if ( (interp != CV_HERMITE) && (interp != CV_POLYNOMIAL) ) {
+    CVProcessError(NULL, CV_ILL_INPUT, "CVODEA", "CVadjSetInterpType", MSGAM_BAD_INTERP);
+    return(CV_ILL_INPUT);
+  } 
+
+  if (interp == interpType) return(CV_SUCCESS);
+
+  interpType = interp;
+
+
+  switch (interpType) {
+
+  case CV_HERMITE:
+    /* Delete Data Points memory */
+    CVApolynomialFree(ca_mem->dt_mem, nsteps);
+    /* Allocate Data Points memory */
+    allocOK = CVAhermiteMalloc(ca_mem, nsteps);
+    if (!allocOK) {
+      CVProcessError(NULL, CV_MEM_FAIL, "CVODEA", "CVadjSetInterpType", MSGAM_MEM_FAIL);
+      return(CV_MEM_FAIL);
+    }
+    /* Attach interpolation functions getY and storePnt */
+    getY = CVAhermiteGetY;
+    storePnt = CVAhermiteStorePnt;
+    /* Rename zn[0] and zn[1] for use in interpolation */
+    Y0 = zn[0];
+    Y1 = zn[1];
+    break;
+  case CV_POLYNOMIAL:
+    /* Delete Data Points memory */
+    CVAhermiteFree(ca_mem->dt_mem, nsteps);
+    /* Allocate Data Points memory */
+    allocOK = CVApolynomialMalloc(ca_mem, nsteps);
+    if (!allocOK) {
+      CVProcessError(NULL, CV_MEM_FAIL, "CVODEA", "CVadjSetInterpType", MSGAM_MEM_FAIL);
+      return(CV_MEM_FAIL);
+    }
+    /* Attach interpolation functions getY and storePnt */
+    getY = CVApolynomialGetY;
+    storePnt = CVApolynomialStorePnt;
+    /* Rename zn for use in interpolation */
+    for (i=0;i<L_MAX;i++) Y[i] = zn[i];
+    break;
+  }
+
+  return(CV_SUCCESS);
+
+}
+
+/*
+ * CVadjFree
+ *
+ * This routine frees the memory allocated by CVadjMalloc.
+ */
+
+void CVadjFree(void **cvadj_mem)
+{
+  void *cvode_bmem;
+  CVadjMem ca_mem;
+  long int i;
+
+  if (*cvadj_mem == NULL) return;
+
+  ca_mem = (CVadjMem) (*cvadj_mem);
+
+  /* Delete check points one by one */
+  while (ca_mem->ck_mem != NULL) CVAckpntDelete(&(ca_mem->ck_mem));
+
+  /* Free vectors at each data point */
+  switch (interpType) {
+  case CV_HERMITE:
+    CVAhermiteFree(ca_mem->dt_mem, nsteps);
+    break;
+  case CV_POLYNOMIAL:
+    CVApolynomialFree(ca_mem->dt_mem, nsteps);
+    break;
+  }
+  for(i=0; i<=nsteps; i++) {free(ca_mem->dt_mem[i]); ca_mem->dt_mem[i] = NULL;}
+  free(ca_mem->dt_mem); ca_mem->dt_mem = NULL;
+
+  /* Free workspace vectors in ca_mem */
+  CVAfreeVectors(ca_mem);
+
+  /* Free memory allocated by the linear solver */
+  if (lfreeB != NULL) lfreeB(ca_mem);
+
+  /* Free CVODES memory for backward run */
+  cvode_bmem = (void *)ca_mem->cvb_mem;
+  CVodeFree(&cvode_bmem);
+
+  /* Free CVODEA memory */
+  free(*cvadj_mem);
+  *cvadj_mem = NULL;
+}
+
+/*
+ * CVodeF
+ *
+ * This routine integrates to tout and returns solution into yout.
+ * In the same time, it stores check point data every 'steps' steps. 
+ * 
+ * CVodeF can be called repeatedly by the user.
+ *
+ * ncheckPtr points to the number of check points stored so far.
+ */
+
+int CVodeF(void *cvadj_mem, realtype tout, N_Vector yout, 
+           realtype *tret, int itask, int *ncheckPtr)
+{
+  CVadjMem ca_mem;
+  CVodeMem cv_mem;
+  CkpntMem tmp;
+  DtpntMem *dt_mem;
+  int cv_itask, flag;
+  booleantype iret;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CV_ADJMEM_NULL, "CVODEA", "CVodeF", MSGAM_NULL_CAMEM);
+    return(CV_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  cv_mem = ca_mem->cv_mem;
+  dt_mem = ca_mem->dt_mem;
+
+  iret = TRUE;
+  cv_itask = CV_ONE_STEP;
+
+  /* Interpret itask */
+  switch (itask) {
+  case CV_NORMAL:
+    iret = FALSE;
+    cv_itask = CV_ONE_STEP;
+    break;
+  case CV_ONE_STEP:
+    iret = TRUE;
+    cv_itask = CV_ONE_STEP;
+    break;
+  case CV_NORMAL_TSTOP:
+    iret = FALSE;
+    cv_itask = CV_ONE_STEP_TSTOP;
+    break;
+  case CV_ONE_STEP_TSTOP:
+    iret = TRUE;
+    cv_itask = CV_ONE_STEP_TSTOP;
+    break;
+  }
+
+  /* On the first step, load dt_mem[0].
+     On subsequent steps, test if taking a new step is necessary. */
+  if ( nst == 0) {
+
+    dt_mem[0]->t = ca_mem->ck_mem->ck_t0;
+    storePnt(cv_mem, dt_mem[0]);
+
+  } else if ( (tn - tout)*h >= ZERO ) {
+
+    /* If tout was passed, return interpolated solution. 
+       No changes to ck_mem or dt_mem are needed. */
+    *tret = tout;
+    flag = CVodeGetDky(cv_mem, tout, 0, yout);
+    *ncheckPtr = nckpnts;
+    newData = TRUE;
+    ckpntData = ca_mem->ck_mem;
+    np = nst % nsteps + 1;
+    return(flag);
+
+  }
+
+  /* Integrate to tout (in CV_ONE_STEP mode) while loading check points */
+  loop {
+
+    /* Perform one step of the integration */
+
+    flag = CVode(cv_mem, tout, yout, tret, cv_itask);
+    if (flag < 0) break;
+
+    /* Test if a new check point is needed */
+
+    if ( nst % nsteps == 0 ) {
+
+      ca_mem->ck_mem->ck_t1 = *tret;
+
+      /* Create a new check point, load it, and append it to the list */
+      tmp = CVAckpntNew(cv_mem);
+      if (tmp == NULL) {
+        CVProcessError(cv_mem, CV_MEM_FAIL, "CVODEA", "CVodeF", MSGAM_MEM_FAIL);
+        flag = CV_MEM_FAIL;
+        break;
+      }
+      tmp->ck_next = ca_mem->ck_mem;
+      ca_mem->ck_mem = tmp;
+      nckpnts++;
+      forceSetup = TRUE;
+      
+      /* Reset i=0 and load dt_mem[0] */
+      dt_mem[0]->t = ca_mem->ck_mem->ck_t0;
+      storePnt(cv_mem, dt_mem[0]);
+
+    } else {
+      
+      /* Load next point in dt_mem */
+      dt_mem[nst%nsteps]->t = *tret;
+      storePnt(cv_mem, dt_mem[nst%nsteps]);
+
+    }
+
+    /* Set t1 field of the current ckeck point structure
+       for the case in which there will be no future
+       check points */
+    ca_mem->ck_mem->ck_t1 = *tret;
+
+    /* tfinal is now set to *tret */
+    tfinal = *tret;
+
+    /* Return if in CV_ONE_STEP mode */
+    if (iret) break;
+
+    /* Return if tout reached */
+    if ( (*tret - tout)*h >= ZERO ) {
+      *tret = tout;
+      CVodeGetDky(cv_mem, tout, 0, yout);
+      break;
+    }
+
+  } /* end of loop() */
+
+  /* Get ncheck from ca_mem */ 
+  *ncheckPtr = nckpnts;
+
+  /* Data is available for the last interval */
+  newData = TRUE;
+  ckpntData = ca_mem->ck_mem;
+  np = nst % nsteps + 1;
+
+  return(flag);
+}
+
+/*
+ * CVodeCreateB, CVodeMallocB, and CVodeReInitB
+ *
+ * Wrappers for the backward phase around the corresponding 
+ * CVODES functions
+ */
+
+int CVodeCreateB(void *cvadj_mem, int lmmB, int iterB)
+{
+  CVadjMem ca_mem;
+  void *cvode_mem;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CV_ADJMEM_NULL, "CVODEA", "CVodeCreateB", MSGAM_NULL_CAMEM);
+    return(CV_ADJMEM_NULL);
+  }
+
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  cvode_mem = CVodeCreate(lmmB, iterB);
+
+  if (cvode_mem == NULL)
+    return(CV_MEM_FAIL);
+
+  ca_mem->cvb_mem = (CVodeMem) cvode_mem;
+
+  return(CV_SUCCESS);
+
+}
+
+int CVodeMallocB(void *cvadj_mem, CVRhsFnB fB, 
+                 realtype tB0, N_Vector yB0,
+                 int itolB, realtype reltolB, void *abstolB)
+{
+  CVadjMem ca_mem;
+  CVodeMem cv_mem;
+  int sign, flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CV_ADJMEM_NULL, "CVODEA", "CVodeMallocB", MSGAM_NULL_CAMEM);
+    return(CV_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  cv_mem = ca_mem->cvb_mem;
+
+  flag = CVodeMalloc(cv_mem, CVArhs, tB0, yB0,
+                     itolB, reltolB, abstolB);
+  if (flag != CV_SUCCESS) return(flag);
+
+  sign = (tfinal - tinitial > ZERO) ? 1 : -1;
+  if ( (sign*(tB0-tinitial) < ZERO) || (sign*(tfinal-tB0) < ZERO) ) {
+    CVProcessError(cv_mem, CV_BAD_TB0, "CVODEA", "CVodeMallocB", MSGAM_BAD_TB0);
+    return(CV_BAD_TB0);
+  }
+
+  f_B = fB;
+
+  CVodeSetMaxHnilWarns(cv_mem, -1);
+  CVodeSetFdata(cv_mem, cvadj_mem);
+
+  return(CV_SUCCESS);
+
+}
+
+int CVodeReInitB(void *cvadj_mem, CVRhsFnB fB, 
+                 realtype tB0, N_Vector yB0, 
+                 int itolB, realtype reltolB, void *abstolB)
+{
+  CVadjMem ca_mem;
+  CVodeMem cv_mem;
+  int sign, flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CV_ADJMEM_NULL, "CVODEA", "CVodeReInitB", MSGAM_NULL_CAMEM);
+    return(CV_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  cv_mem = ca_mem->cvb_mem;
+
+  flag = CVodeReInit(cv_mem, CVArhs, tB0, yB0,
+                     itolB, reltolB, abstolB);
+
+  if (flag != CV_SUCCESS) return(flag);
+
+  sign = (tfinal - tinitial > ZERO) ? 1 : -1;
+  if ( (sign*(tB0-tinitial) < ZERO) || (sign*(tfinal-tB0) < ZERO) ) {
+    CVProcessError(cv_mem, CV_BAD_TB0, "CVODEA", "CVodeReInitB", MSGAM_BAD_TB0);
+    return(CV_BAD_TB0);
+  }
+  
+  f_B  = fB;
+
+  CVodeSetMaxHnilWarns(cv_mem, -1);
+  CVodeSetFdata(cv_mem, cvadj_mem);
+
+  return(CV_SUCCESS);
+
+}
+
+/*
+ * CVodeQuadMallocB, and CVodeQuadReInitB
+ *
+ * Wrappers for the backward phase around the corresponding 
+ * CVODES functions
+ */
+
+int CVodeQuadMallocB(void *cvadj_mem, CVQuadRhsFnB fQB, N_Vector yQB0)
+{
+  CVadjMem ca_mem;
+  void *cvode_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CV_ADJMEM_NULL, "CVODEA", "CVodeQuadMallocB", MSGAM_NULL_CAMEM);
+    return(CV_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  fQ_B = fQB;
+
+  cvode_mem = (void *) ca_mem->cvb_mem;
+
+  flag = CVodeQuadMalloc(cvode_mem, CVArhsQ, yQB0);
+  if (flag != CV_SUCCESS) return(flag);
+
+  flag = CVodeSetQuadFdata(cvode_mem, cvadj_mem);
+
+  return(flag);
+
+}
+
+int CVodeQuadReInitB(void *cvadj_mem, CVQuadRhsFnB fQB, N_Vector yQB0)
+{
+  CVadjMem ca_mem;
+  void *cvode_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CV_ADJMEM_NULL, "CVODEA", "CVodeQuadReInitB", MSGAM_NULL_CAMEM);
+    return(CV_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  fQ_B = fQB;
+
+  cvode_mem = (void *) ca_mem->cvb_mem;
+
+  flag = CVodeQuadReInit(cvode_mem, CVArhsQ, yQB0);
+
+  return(flag);
+
+}
+
+/*
+ * CVodeB
+ *
+ * This routine performs the backward integration towards tBout. 
+ * When necessary, it performs a forward integration between two 
+ * consecutive check points to update interpolation data.
+ * itask can be CV_NORMAL or CV_ONE_STEP only.
+ *
+ * On a successful return, CVodeB returns either CV_SUCCESS
+ * (in ONE_STEP mode or if tBout was reached in NORMAL mode)
+ * unless the return time happens to be a checkpoint, in which
+ * case it returns CV_TSTOP_RETURN)
+ */
+
+int CVodeB(void *cvadj_mem, realtype tBout, N_Vector yBout, 
+           realtype *tBret, int itaskB)
+{
+  CVadjMem ca_mem;
+  CkpntMem ck_mem;
+  CVodeMem cvb_mem;
+  int sign, flag, cv_itask;
+  realtype tBn, hB, troundoff;
+  
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CV_ADJMEM_NULL, "CVODEA", "CVodeB", MSGAM_NULL_CAMEM);
+    return(CV_ADJMEM_NULL);
+  }
+  ca_mem  = (CVadjMem) cvadj_mem;
+
+  cvb_mem = ca_mem->cvb_mem;
+  if (cvb_mem == NULL) {
+    CVProcessError(NULL, CV_BCKMEM_NULL, "CVODEA", "CVodeB", MSGAM_NULL_CVMEM);
+    return(CV_BCKMEM_NULL);
+  }
+
+  if (itaskB == CV_NORMAL)
+    cv_itask = CV_NORMAL_TSTOP;
+  else if (itaskB == CV_ONE_STEP)
+    cv_itask = CV_ONE_STEP_TSTOP;
+  else {
+    CVProcessError(cvb_mem, CV_BAD_ITASK, "CVODEA", "CVodeB", MSGAM_BAD_ITASKB);
+    return(CV_BAD_ITASK);
+  }
+
+  ck_mem = ca_mem->ck_mem;
+
+  sign = (tfinal - tinitial > ZERO) ? 1 : -1;
+
+  if ( (sign*(tBout-tinitial) < ZERO) || (sign*(tfinal-tBout) < ZERO) ) {
+    CVProcessError(cvb_mem, CV_BAD_TBOUT, "CVODEA", "CVodeB", MSGAM_BAD_TBOUT);
+    return(CV_BAD_TBOUT);
+  }
+
+  /* Move ck_mem pointer to the checkpoint appropriate for
+     tBn (the current time reached by CVODES) */
+  tBn = cvb_mem->cv_tn;
+  troundoff = HUNDRED*uround*(ABS(tBn) + ABS(hB));
+  while ( sign*(tBn - t0_) <= troundoff ) {
+    if (next_ == NULL) break;
+    ck_mem = next_;
+  }
+
+  loop {
+
+    /* Store interpolation data if not available 
+       This is the 2nd forward integration pass */
+    if (ck_mem != ckpntData) {
+      flag = CVAdataStore(ca_mem, ck_mem);
+      if (flag != CV_SUCCESS) break;
+    }
+
+    /* Backward integration */
+    CVodeSetStopTime((void *)cvb_mem, t0_);
+    flag = CVode(cvb_mem, tBout, yBout, tBret, cv_itask);
+
+    /* If an error occured, return now */
+    if (flag < 0) break;
+
+    /* Set the time at which CVodeGetQuadB will evaluate any quadratures */
+    t_for_quad = *tBret;
+
+    /* If in CV_ONE_STEP mode, return now (flag=CV_SUCCESS or flag=CV_TSTOP_RETURN) */
+    if (itaskB == CV_ONE_STEP) break;
+
+    /* If succesfully reached tBout, return now */
+    if ( sign*(*tBret - tBout) <= ZERO) break;
+
+    /* Move check point in linked list to next one */
+    ck_mem = next_;
+
+  } 
+
+  return(flag);
+}
+
+/* 
+ * =================================================================
+ * PRIVATE FUNCTIONS
+ * =================================================================
+ */
+
+/*
+ * CVAallocVectors
+ *
+ * Allocate memory for adjoint workspace N_Vectors
+ */
+
+static booleantype CVAallocVectors(CVadjMem ca_mem)
+{
+  CVodeMem cv_mem;
+
+  cv_mem = ca_mem->cv_mem;
+
+  ytmp = NULL;
+  ytmp = N_VClone(tempv);
+  if (ytmp == NULL) {
+    return(FALSE);
+  }
+
+  return(TRUE);
+
+}
+
+/*
+ * CVAfreeVectors
+ * 
+ * Free memory allocated by CVAallocVectors
+ */
+
+static void CVAfreeVectors(CVadjMem ca_mem)
+{
+  N_VDestroy(ytmp);
+}
+
+
+/*
+ * CVAckpntInit
+ *
+ * This routine initializes the check point linked list with 
+ * information from the initial time.
+ */
+
+static CkpntMem CVAckpntInit(CVodeMem cv_mem)
+{
+  CkpntMem ck_mem;
+
+  /* Allocate space for ckdata */
+  ck_mem = NULL;
+  ck_mem = (CkpntMem) malloc(sizeof(struct CkpntMemRec));
+  if (ck_mem == NULL) return(NULL);
+
+  zn_[0] = NULL;
+  zn_[0] = N_VClone(tempv);
+  if (zn_[0] == NULL) {
+    free(ck_mem); ck_mem = NULL;
+    return(NULL);
+  }
+  
+  zn_[1] = NULL;
+  zn_[1] = N_VClone(tempv);
+  if (zn_[1] == NULL) {
+    N_VDestroy(zn_[0]);
+    free(ck_mem); ck_mem = NULL;
+    return(NULL);
+  }
+
+  /* zn_[qmax] was not allocated */
+  zqm_ = 0;
+
+  /* Load ckdata from cv_mem */
+  N_VScale(ONE, zn[0], zn_[0]);
+  t0_    = tn;
+  nst_   = 0;
+  q_     = 1;
+  h_     = 0.0;
+  
+  /* Do we need to carry quadratures */
+  quadr_ = quadr && errconQ;
+
+  if (quadr_) {
+    znQ_[0] = NULL;
+    znQ_[0] = N_VClone(tempvQ);
+    if (znQ_[0] == NULL) {
+      N_VDestroy(zn_[0]);
+      N_VDestroy(zn_[1]);
+      free(ck_mem); ck_mem = NULL;
+      return(NULL);
+    }
+    N_VScale(ONE, znQ[0], znQ_[0]);
+  }
+
+  /* Next in list */
+  next_  = NULL;
+
+  return(ck_mem);
+}
+
+/*
+ * CVAckpntNew
+ *
+ * This routine allocates space for a new check point and sets 
+ * its data from current values in cv_mem.
+ */
+
+static CkpntMem CVAckpntNew(CVodeMem cv_mem)
+{
+  CkpntMem ck_mem;
+  int j, jj;
+  int qmax; 
+
+  /* Allocate space for ckdata */
+  ck_mem = NULL;
+  ck_mem = (CkpntMem) malloc(sizeof(struct CkpntMemRec));
+  if (ck_mem == NULL) return(NULL);
+
+  /* Test if we need to allocate space for the last zn.
+     NOTE: zn(qmax) may be needed for a hot restart, if an order
+     increase is deemed necessary at the first step after a check 
+     point */
+  qmax = cv_mem->cv_qmax;
+  zqm_ = (q < qmax) ? qmax : 0;
+
+  for (j=0; j<=q; j++) {
+    zn_[j] = NULL;
+    zn_[j] = N_VClone(tempv);
+    if (zn_[j] == NULL) {
+      for (jj=0; jj<j; jj++) N_VDestroy(zn_[jj]);
+      free(ck_mem); ck_mem = NULL;
+      return(NULL);
+    }
+  }
+
+  if (q < qmax) {
+    zn_[qmax] = NULL;
+    zn_[qmax] = N_VClone(tempv);
+    if (zn_[qmax] == NULL) {
+      for (j=0; j<=q; j++) N_VDestroy(zn_[j]);
+      free(ck_mem); ck_mem = NULL;
+      return(NULL);
+    }
+  }
+
+  /* Test if we need to carry quadratures */
+  quadr_ = quadr && errconQ;
+
+  if (quadr_) {
+
+    for (j=0; j<=q; j++) {
+      znQ_[j] = NULL;
+      znQ_[j] = N_VClone(tempvQ);
+      if(znQ_[j] == NULL) {
+        for (jj=0; jj<j; jj++) N_VDestroy(znQ_[jj]);
+        if (q < qmax) N_VDestroy(zn_[qmax]);
+        for (j=0; j<=q; j++) N_VDestroy(zn_[j]);
+        free(ck_mem); ck_mem = NULL;
+        return(NULL);
+      }
+    }
+
+    if ( q < qmax) {
+      znQ_[qmax] = NULL;
+      znQ_[qmax] = N_VClone(tempvQ);
+      if (znQ_[qmax] == NULL) {
+        for (j=0; j<=q; j++) N_VDestroy(znQ_[j]);
+        N_VDestroy(zn_[qmax]);
+        for (j=0; j<=q; j++) N_VDestroy(zn_[j]);
+        free(ck_mem); ck_mem = NULL;
+        return(NULL);
+      }
+    }
+  }
+
+  /* Load check point data from cv_mem */
+
+  for (j=0; j<=q; j++) N_VScale(ONE, zn[j], zn_[j]);
+  if ( q < qmax ) N_VScale(ONE, zn[qmax], zn_[qmax]);
+
+  if(quadr_) {
+    for (j=0; j<=q; j++) N_VScale(ONE, znQ[j], znQ_[j]);
+    if ( q < qmax ) N_VScale(ONE, znQ[qmax], znQ_[qmax]);
+  }
+
+  for (j=0; j<=L_MAX; j++)     tau_[j] = tau[j];
+  for (j=0; j<=NUM_TESTS; j++) tq_[j] = tq[j];
+  for (j=0; j<=q; j++)         l_[j] = l[j];
+  nst_       = nst;
+  tretlast_  = tretlast;
+  q_         = q;
+  qprime_    = qprime;
+  qwait_     = qwait;
+  L_         = L;
+  gammap_    = gammap;
+  h_         = h;
+  hprime_    = hprime;
+  hscale_    = hscale;
+  eta_       = eta;
+  etamax_    = etamax;
+  t0_        = tn;
+  saved_tq5_ = saved_tq5;
+
+  return(ck_mem);
+}
+
+/*
+ * CVAckpntDelete
+ *
+ * This routine deletes the first check point in list.
+ */
+
+static void CVAckpntDelete(CkpntMem *ck_memPtr)
+{
+  CkpntMem tmp;
+  int j;
+
+  if (*ck_memPtr != NULL) {
+
+    /* store head of list */
+    tmp = *ck_memPtr;
+
+    /* move head of list */
+    *ck_memPtr = (*ck_memPtr)->ck_next;
+
+    /* free N_Vectors in tmp */
+    for (j=0;j<=tmp->ck_q;j++) N_VDestroy(tmp->ck_zn[j]);
+    if (tmp->ck_zqm != 0) N_VDestroy(tmp->ck_zn[tmp->ck_zqm]);
+
+    /* free N_Vectors for quadratures in tmp 
+       Note that at the check point at t_initial, only znQ_[0] 
+       was allocated*/
+    if(tmp->ck_quadr) {
+      if(tmp->ck_next != NULL) {
+        for (j=0;j<=tmp->ck_q;j++) N_VDestroy(tmp->ck_znQ[j]);
+        if (tmp->ck_zqm != 0) N_VDestroy(tmp->ck_znQ[tmp->ck_zqm]);
+      } else {
+        N_VDestroy(tmp->ck_znQ[0]);
+      }
+    }
+
+    free(tmp); tmp = NULL;
+
+  }
+}
+
+/*
+ * CVAdataStore
+ *
+ * This routine integrates the forward model starting at the check
+ * point ck_mem and stores y and yprime at all intermediate steps.
+ *
+ * Return values:
+ * CV_SUCCESS
+ * CV_REIFWD_FAIL
+ * CV_FWD_FAIL
+ */
+
+static int CVAdataStore(CVadjMem ca_mem, CkpntMem ck_mem)
+{
+  CVodeMem cv_mem;
+  DtpntMem *dt_mem;
+  realtype t;
+  long int i;
+  int flag;
+
+  cv_mem = ca_mem->cv_mem;
+  dt_mem = ca_mem->dt_mem;
+
+  /* Initialize cv_mem with data from ck_mem */
+  flag = CVAckpntGet(cv_mem, ck_mem);
+  if (flag != CV_SUCCESS)
+    return(CV_REIFWD_FAIL);
+
+  /* Set first structure in dt_mem[0] */
+  dt_mem[0]->t = t0_;
+  storePnt(cv_mem, dt_mem[0]);
+
+  /* Run CVode to set following structures in dt_mem[i] */
+
+  i = 1;
+  do {
+    flag = CVode(cv_mem, t1_, ytmp, &t, CV_ONE_STEP);
+    if (flag < 0) 
+      return(CV_FWD_FAIL);
+    dt_mem[i]->t = t;
+    storePnt(cv_mem, dt_mem[i]);
+    i++;
+  } while (t<t1_);
+
+
+  newData = TRUE;       /* New data is now available    */
+  ckpntData = ck_mem;   /* starting at this check point */
+  np = i;               /* and we have this many points */
+
+  return(CV_SUCCESS);
+}
+
+/*
+ * CVAckpntGet
+ *
+ * This routine prepares CVODES for a hot restart from
+ * the check point ck_mem
+ */
+
+static int CVAckpntGet(CVodeMem cv_mem, CkpntMem ck_mem) 
+{
+  int j;
+  int flag;
+  int qmax;
+  void *abstol;
+
+  abstol = NULL;
+
+  if (next_ == NULL) {
+
+    /* In this case, we just call the reinitialization routine,
+       but make sure we use the same initial stepsize as on 
+       the first run. */
+
+    CVodeSetInitStep(cv_mem, h0u);
+
+    switch (itol) {
+    case CV_SS:
+      abstol = (void *) &Sabstol;
+      break;
+    case CV_SV:
+      abstol = (void *)Vabstol;
+      break;
+    case CV_EE:
+      abstol = (void *)efun;
+      break;
+    }
+    flag = CVodeReInit(cv_mem, f, t0_, zn_[0], itol, reltol, abstol);
+    if (flag != CV_SUCCESS) return(flag);
+
+    if(quadr_) {
+      flag = CVodeQuadReInit(cv_mem, fQ, znQ_[0]);
+      if (flag != CV_SUCCESS) return(flag);
+    }
+
+  } else {
+    
+    qmax = cv_mem->cv_qmax;
+
+    /* Copy parameters from check point data structure */
+    nst       = nst_;
+    tretlast  = tretlast_;
+    q         = q_;
+    qprime    = qprime_;
+    qwait     = qwait_;
+    L         = L_;
+    gammap    = gammap_;
+    h         = h_;
+    hprime    = hprime_;
+    hscale    = hscale_;
+    eta       = eta_;
+    etamax    = etamax_;
+    tn        = t0_;
+    saved_tq5 = saved_tq5_;
+    
+    /* Copy the arrays from check point data structure */
+    for (j=0; j<=q; j++) N_VScale(ONE, zn_[j], zn[j]);
+    if ( q < qmax ) N_VScale(ONE, zn_[qmax], zn[qmax]);
+    if(quadr_) {
+      for (j=0; j<=q; j++) N_VScale(ONE, znQ_[j], znQ[j]);
+      if ( q < qmax ) N_VScale(ONE, znQ_[qmax], znQ[qmax]);
+    }
+    for (j=0; j<=L_MAX; j++)     tau[j] = tau_[j];
+    for (j=0; j<=NUM_TESTS; j++) tq[j] = tq_[j];
+    for (j=0; j<=q; j++)         l[j] = l_[j];
+    
+    /* Force a call to setup */
+    forceSetup = TRUE;
+
+  }
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * -----------------------------------------------------------------
+ * Functions for interpolation
+ * -----------------------------------------------------------------
+ */
+
+/*
+ * CVAfindIndex
+ *
+ * Finds the index in the array of data point strctures such that
+ *     dt_mem[indx-1].t <= t < dt_mem[indx].t
+ * If indx is changed from the previous invocation, then newpoint = TRUE
+ *
+ * If t is beyond the leftmost limit, but close enough, indx=0.
+ *
+ * Returns CV_SUCCESS if successful and CV_GETY_BADT if unable to
+ * find indx (t is too far beyond limits).
+ */
+
+static int CVAfindIndex(CVadjMem ca_mem, realtype t, 
+                        long int *indx, booleantype *newpoint)
+{
+  static long int ilast;
+  DtpntMem *dt_mem;
+  int sign;
+  booleantype to_left, to_right;
+
+  dt_mem = ca_mem->dt_mem;
+
+  *newpoint = FALSE;
+
+  /* Find the direction of integration */
+  sign = (tfinal - tinitial > ZERO) ? 1 : -1;
+
+  /* If this is the first time we use new data */
+  if (newData) {
+    ilast     = np-1;
+    *newpoint = TRUE;
+    newData   = FALSE;
+  }
+
+  /* Search for indx starting from ilast */
+  to_left  = ( sign*(t - dt_mem[ilast-1]->t) < ZERO);
+  to_right = ( sign*(t - dt_mem[ilast]->t)   > ZERO);
+
+  if ( to_left ) {
+    /* look for a new indx to the left */
+
+    *newpoint = TRUE;
+    
+    *indx = ilast;
+    loop {
+      if ( *indx == 0 ) break;
+      if ( sign*(t - dt_mem[*indx-1]->t) <= ZERO ) (*indx)--;
+      else                                         break;
+    }
+
+    if ( *indx == 0 )
+      ilast = 1;
+    else
+      ilast = *indx;
+
+    if ( *indx == 0 ) {
+      /* t is beyond leftmost limit. Is it too far? */  
+      if ( ABS(t - dt_mem[0]->t) > FUZZ_FACTOR * uround ) return(CV_GETY_BADT);
+    }
+
+  } else if ( to_right ) {
+    /* look for a new indx to the right */
+
+    *newpoint = TRUE;
+
+    *indx = ilast;
+    loop {
+      if ( sign*(t - dt_mem[*indx]->t) > ZERO) (*indx)++;
+      else                                     break;
+    }
+
+    ilast = *indx;
+
+
+  } else {
+    /* ilast is still OK */
+
+    *indx = ilast;
+
+  }
+
+  return(CV_SUCCESS);
+
+
+}
+
+/*
+ * CVadjGetY
+ *
+ * This routine returns the interpolated forward solution at time t.
+ * The user must allocate space for y.
+ */
+
+int CVadjGetY(void *cvadj_mem, realtype t, N_Vector y)
+{
+  int flag;
+  CVadjMem ca_mem;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CV_ADJMEM_NULL, "CVODEA", "CVadjGetY", MSGAM_NULL_CAMEM);
+    return(CV_ADJMEM_NULL);
+  }
+  ca_mem  = (CVadjMem) cvadj_mem;
+  
+  flag = getY(ca_mem, t, y);
+
+  return(flag);
+}
+
+/* 
+ * -----------------------------------------------------------------
+ * Functions specific to cubic Hermite interpolation
+ * -----------------------------------------------------------------
+ */
+
+/*
+ * CVAhermiteMalloc
+ *
+ * This routine allocates memory for storing information at all
+ * intermediate points between two consecutive check points. 
+ * This data is then used to interpolate the forward solution 
+ * at any other time.
+ */
+
+static booleantype CVAhermiteMalloc(CVadjMem ca_mem, long int steps)
+{
+  CVodeMem cv_mem;
+  DtpntMem *dt_mem;
+  HermiteDataMem content;
+  long int i, ii=0;
+  booleantype allocOK;
+
+  allocOK = TRUE;
+
+  dt_mem = ca_mem->dt_mem;
+  cv_mem = ca_mem->cv_mem;
+
+  for (i=0; i<=steps; i++) {
+
+    content = NULL;
+    content = (HermiteDataMem) malloc(sizeof(struct HermiteDataMemRec));
+    if (content == NULL) {
+      ii = i;
+      allocOK = FALSE;
+      break;
+    }
+
+    content->y = NULL;
+    content->y = N_VClone(tempv);
+    if (content->y == NULL) {
+      free(content); content = NULL;
+      ii = i;
+      allocOK = FALSE;
+      break;
+    }
+
+    content->yd = NULL;
+    content->yd = N_VClone(tempv);
+    if (content->yd == NULL) {
+      N_VDestroy(content->y);
+      free(content); content = NULL;
+      ii = i;
+      allocOK = FALSE;
+      break;
+    }
+    
+    dt_mem[i]->content = content;
+
+  } 
+
+  if (!allocOK) {
+    for (i=0; i<ii; i++) {
+      content = (HermiteDataMem) (dt_mem[i]->content);
+      N_VDestroy(content->y);
+      N_VDestroy(content->yd);
+      free(dt_mem[i]->content); dt_mem[i]->content = NULL;
+    }
+  }
+
+  return(allocOK);
+}
+
+/*
+ * CVAhermiteFree
+ *
+ * This routine frees the memory allocated for data storage.
+ */
+
+static void CVAhermiteFree(DtpntMem *dt_mem, long int steps)
+{
+  long int i;
+  HermiteDataMem content;
+
+  for (i=0; i<=steps; i++) {
+    content = (HermiteDataMem) (dt_mem[i]->content);
+    N_VDestroy(content->y);
+    N_VDestroy(content->yd);
+    free(dt_mem[i]->content); dt_mem[i]->content = NULL;
+  }
+}
+
+/*
+ * CVAhermiteStorePnt ( -> storePnt )
+ *
+ * This routine stores a new point (y,yd) in the structure d for use
+ * in the cubic Hermite interpolation.
+ * Note that the time is already stored.
+ */
+
+static int CVAhermiteStorePnt(CVodeMem cv_mem, DtpntMem d)
+{
+  int retval;
+  HermiteDataMem content;
+
+  content = (HermiteDataMem) d->content;
+
+  N_VScale(ONE, zn[0], content->y);
+  
+  if (nst == 0)
+    retval = f(tn, content->y, content->yd, f_data);
+  else
+    N_VScale(ONE/h, zn[1], content->yd);
+
+  return(0);
+}
+
+/*
+ * CVAhermiteGetY ( -> getY )
+ *
+ * This routine uses cubic piece-wise Hermite interpolation for 
+ * the forward solution vector. 
+ * It is typically called by the wrapper routines before calling
+ * user provided routines (fB, djacB, bjacB, jtimesB, psolB) but
+ * can be directly called by the user through CVadjGetY
+ */
+
+static int CVAhermiteGetY(CVadjMem ca_mem, realtype t, N_Vector y)
+{
+  DtpntMem *dt_mem;
+  HermiteDataMem content0, content1;
+  realtype t0, t1, delta, factor;
+  N_Vector y0, yd0, y1, yd1;
+  int flag;
+  long int indx;
+  booleantype newpoint;
+
+  dt_mem = ca_mem->dt_mem;
+  
+  /* Get the index in dt_mem */
+
+  flag = CVAfindIndex(ca_mem, t, &indx, &newpoint);
+  if (flag != CV_SUCCESS) return(flag);
+
+  /* If we are beyond the left limit but close enough,
+     then return y at the left limit. */
+
+  if (indx == 0) {
+    content0 = (HermiteDataMem) (dt_mem[0]->content);
+    N_VScale(ONE, content0->y, y);
+    return(CV_SUCCESS);
+  }
+
+  /* Extract stuff from the appropriate data points */
+
+  t0 = dt_mem[indx-1]->t;
+  t1 = dt_mem[indx]->t;
+  delta = t1 - t0;
+
+  content0 = (HermiteDataMem) (dt_mem[indx-1]->content);
+  y0  = content0->y;
+  yd0 = content0->yd;
+
+  if (newpoint) {
+    
+    /* Recompute Y0 and Y1 */
+
+    content1 = (HermiteDataMem) (dt_mem[indx]->content);
+    y1  = content1->y;
+    yd1 = content1->yd;
+
+    N_VLinearSum(ONE, y1, -ONE, y0, Y0);
+    N_VLinearSum(ONE, yd1,  ONE, yd0, Y1);
+    N_VLinearSum(delta, Y1, -TWO, Y0, Y1);
+    N_VLinearSum(ONE, Y0, -delta, yd0, Y0);
+
+  }
+
+  /* Perform the actual interpolation. */
+
+  factor = t - t0;
+  N_VLinearSum(ONE, y0, factor, yd0, y);
+
+  factor = factor/delta;
+  factor = factor*factor;
+  N_VLinearSum(ONE, y, factor, Y0, y);
+
+  factor = factor*(t-t1)/delta;
+  N_VLinearSum(ONE, y, factor, Y1, y);
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * -----------------------------------------------------------------
+ * Functions specific to Polynomial interpolation
+ * -----------------------------------------------------------------
+ */
+
+/*
+ * CVApolynomialMalloc
+ *
+ * This routine allocates memory for storing information at all
+ * intermediate points between two consecutive check points. 
+ * This data is then used to interpolate the forward solution 
+ * at any other time.
+ */
+
+static booleantype CVApolynomialMalloc(CVadjMem ca_mem, long int steps)
+{
+  CVodeMem cv_mem;
+  DtpntMem *dt_mem;
+  PolynomialDataMem content;
+  long int i, ii=0;
+  booleantype allocOK;
+
+  allocOK = TRUE;
+
+  dt_mem = ca_mem->dt_mem;
+  cv_mem = ca_mem->cv_mem;
+
+  for (i=0; i<=steps; i++) {
+    content = NULL;
+    content = (PolynomialDataMem) malloc(sizeof(struct PolynomialDataMemRec));
+    if (content == NULL) {
+      ii = i;
+      allocOK = FALSE;
+      break;
+    }
+
+    content->y = NULL;
+    content->y = N_VClone(tempv);
+    if (content->y == NULL) {
+      free(content); content = NULL;
+      ii = i;
+      allocOK = FALSE;
+      break;
+    }
+
+    dt_mem[i]->content = content;
+  } 
+
+  if (!allocOK) {
+    for (i=0; i<ii; i++) {
+      content = (PolynomialDataMem) (dt_mem[i]->content);
+      N_VDestroy(content->y);
+      free(dt_mem[i]->content); dt_mem[i]->content = NULL;
+    }
+  }
+
+  return(allocOK);
+
+}
+
+/*
+ * CVApolynomialFree
+ *
+ * This routine frees the memeory allocated for data storage.
+ */
+
+static void CVApolynomialFree(DtpntMem *dt_mem, long int steps)
+{
+  long int i;
+  PolynomialDataMem content;
+
+  for (i=0; i<=steps; i++) {
+    content = (PolynomialDataMem) (dt_mem[i]->content);
+    N_VDestroy(content->y);
+    free(dt_mem[i]->content); dt_mem[i]->content = NULL;
+  }
+}
+
+/*
+ * CVApolynomialStorePnt ( -> storePnt )
+ *
+ * This routine stores a new point y in the structure d for use
+ * in the Polynomial interpolation.
+ * Note that the time is already stored.
+ */
+
+static int CVApolynomialStorePnt(CVodeMem cv_mem, DtpntMem d)
+{
+  PolynomialDataMem content;
+
+  content = (PolynomialDataMem) d->content;
+
+  N_VScale(ONE, zn[0], content->y);
+  content->order = qu;
+
+  return(0);
+}
+
+/*
+ * CVApolynomialGetY ( -> getY )
+ *
+ * This routine uses polynomial interpolation for the forward solution vector. 
+ * It is typically called by the wrapper routines before calling
+ * user provided routines (fB, djacB, bjacB, jtimesB, psolB)) but
+ * can be directly called by the user through CVadjGetY.
+ */
+
+static int CVApolynomialGetY(CVadjMem ca_mem, realtype t, N_Vector y)
+{
+  DtpntMem *dt_mem;
+  PolynomialDataMem content;
+  int flag, dir, order, i, j;
+  long int indx, base;
+  booleantype newpoint;
+  realtype dt, factor;
+
+  dt_mem = ca_mem->dt_mem;
+  
+  /* Get the index in dt_mem */
+
+  flag = CVAfindIndex(ca_mem, t, &indx, &newpoint);
+  if (flag != CV_SUCCESS) return(flag);
+
+  /* If we are beyond the left limit but close enough,
+     then return y at the left limit. */
+
+  if (indx == 0) {
+    content = (PolynomialDataMem) (dt_mem[0]->content);
+    N_VScale(ONE, content->y, y);
+    return(CV_SUCCESS);
+  }
+
+  /* Scaling factor */
+
+  dt = ABS(dt_mem[indx]->t - dt_mem[indx-1]->t);
+
+  /* Find the direction of the forward integration */
+
+  dir = (tfinal - tinitial > ZERO) ? 1 : -1;
+
+  /* Establish the base point depending on the integration direction.
+     Modify the base if there are not enough points for the current order */
+
+  if (dir == 1) {
+    base = indx;
+    content = (PolynomialDataMem) (dt_mem[base]->content);
+    order = content->order;
+    if(indx < order) base += order-indx;
+  } else {
+    base = indx-1;
+    content = (PolynomialDataMem) (dt_mem[base]->content);
+    order = content->order;
+    if (np-indx > order) base -= indx+order-np;
+  }
+
+  /* Recompute Y (divided differences for Newton polynomial) if needed */
+
+  if (newpoint) {
+
+    /* Store 0-th order DD */
+    if (dir == 1) {
+      for(j=0;j<=order;j++) {
+        T[j] = dt_mem[base-j]->t;
+        content = (PolynomialDataMem) (dt_mem[base-j]->content);
+        N_VScale(ONE, content->y, Y[j]);
+      }
+    } else {
+      for(j=0;j<=order;j++) {
+        T[j] = dt_mem[base-1+j]->t;
+        content = (PolynomialDataMem) (dt_mem[base-1+j]->content);
+        N_VScale(ONE, content->y, Y[j]);
+      }
+    }
+
+    /* Compute higher-order DD */
+    for(i=1;i<=order;i++) {
+      for(j=order;j>=i;j--) {
+        factor = dt/(T[j]-T[j-i]);
+        N_VLinearSum(factor, Y[j], -factor, Y[j-1], Y[j]);
+      }
+    }
+  }
+
+  /* Perform the actual interpolation using nested multiplications */
+
+  N_VScale(ONE, Y[order], y);
+  for (i=order-1; i>=0; i--) {
+    factor = (t-T[i])/dt;
+    N_VLinearSum(factor, y, ONE, Y[i], y);
+  }
+
+  return(CV_SUCCESS);
+
+}
+
+/* 
+ * =================================================================
+ * WRAPPERS FOR ADJOINT SYSTEM
+ * =================================================================
+ */
+/*
+ * CVArhs
+ *
+ * This routine interfaces to the CVRhsFnB routine provided by
+ * the user.
+ * NOTE: f_data actually contains cvadj_mem
+ */
+
+static int CVArhs(realtype t, N_Vector yB, 
+                  N_Vector yBdot, void *cvadj_mem)
+{
+  CVadjMem ca_mem;
+  CVodeMem cv_mem;
+  int flag, retval;
+
+  ca_mem = (CVadjMem) cvadj_mem;
+  cv_mem = ca_mem->cvb_mem;
+
+  /* Forward solution from interpolation */
+  flag = getY(ca_mem, t, ytmp);
+  if (flag != CV_SUCCESS) {
+    CVProcessError(cv_mem, -1, "CVODEA", "CVArhs", MSGAM_BAD_T);
+    return(-1);
+  }
+
+  /* Call user's adjoint RHS routine */
+  retval = f_B(t, ytmp, yB, yBdot, f_data_B);
+
+  return(retval);
+}
+
+/*
+ * CVArhsQ
+ *
+ * This routine interfaces to the CVQuadRhsFnB routine provided by
+ * the user.
+ * NOTE: fQ_data actually contains cvadj_mem
+ */
+
+static int CVArhsQ(realtype t, N_Vector yB, 
+                   N_Vector qBdot, void *cvadj_mem)
+{
+  CVadjMem ca_mem;
+  CVodeMem cv_mem;
+  int flag, retval;
+
+  ca_mem = (CVadjMem) cvadj_mem;
+  cv_mem = ca_mem->cvb_mem;
+
+  /* Forward solution from interpolation */
+  flag = getY(ca_mem, t, ytmp);
+  if (flag != CV_SUCCESS) {
+    CVProcessError(cv_mem, -1, "CVODEA", "CVArhsQ", MSGAM_BAD_T);
+    return(-1);
+  }
+
+  /* Call user's adjoint RHS routine */
+  retval = fQ_B(t, ytmp, yB, qBdot, fQ_data_B);
+
+  return(retval);
+}
+
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodea_io.c b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodea_io.c
new file mode 100644
index 0000000000000000000000000000000000000000..1aec134c2a097bf16c7fe014cc6baa0fd044eb8d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodea_io.c
@@ -0,0 +1,538 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * -----------------------------------------------------------------
+ * Programmer: Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2006, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the implementation file for the optional input and output
+ * functions for the adjoint module in the CVODES solver.
+ * -----------------------------------------------------------------
+ */
+
+/* 
+ * =================================================================
+ * IMPORTED HEADER FILES
+ * =================================================================
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "cvodes_impl.h"
+#include <sundials/sundials_types.h>
+
+/* 
+ * =================================================================
+ * CVODEA PRIVATE CONSTANTS
+ * =================================================================
+ */
+
+#define ONE         RCONST(1.0) 
+
+/* 
+ * =================================================================
+ * EXPORTED FUNCTIONS IMPLEMENTATION
+ * =================================================================
+ */
+
+/* 
+ * -----------------------------------------------------------------
+ * Readibility Constants
+ * -----------------------------------------------------------------
+ */
+
+#define interpType  (ca_mem->ca_interpType)
+#define f_data_B    (ca_mem->ca_f_dataB)
+#define fQ_data_B   (ca_mem->ca_fQ_dataB)
+#define t_for_quad  (ca_mem->ca_t_for_quad)
+#define ckpntData   (ca_mem->ca_ckpntData)
+
+#define t0_         (ck_mem->ck_t0)
+#define t1_         (ck_mem->ck_t1)
+#define nst_        (ck_mem->ck_nst)
+#define q_          (ck_mem->ck_q)
+#define h_          (ck_mem->ck_h)
+#define next_       (ck_mem->ck_next)
+
+/* 
+ * -----------------------------------------------------------------
+ * Optional input functions for backward integration
+ * -----------------------------------------------------------------
+ */
+
+/*
+ * CVodeSet***B
+ *
+ * Wrappers for the backward phase around the corresponding 
+ * CVODES optional input functions
+ */
+
+int CVodeSetErrHandlerFnB(void *cvadj_mem, CVErrHandlerFn ehfunB, void *eh_dataB)
+{
+  CVadjMem ca_mem;
+  void *cvode_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CV_ADJMEM_NULL, "CVODEA", "CVodeSetErrHandlerB", MSGAM_NULL_CAMEM);
+    return(CV_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+  cvode_mem = (void *)ca_mem->cvb_mem;
+
+  flag = CVodeSetErrHandlerFn(cvode_mem, ehfunB, eh_dataB);
+
+  return(flag);
+}
+
+int CVodeSetErrFileB(void *cvadj_mem, FILE *errfpB)
+{
+  CVadjMem ca_mem;
+  void *cvode_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CV_ADJMEM_NULL, "CVODEA", "CVodeSetErrFileB", MSGAM_NULL_CAMEM);
+    return(CV_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+  cvode_mem = (void *)ca_mem->cvb_mem;
+
+  flag = CVodeSetErrFile(cvode_mem, errfpB);
+
+  return(flag);
+}
+
+int CVodeSetIterTypeB(void *cvadj_mem, int iterB)
+{
+  CVadjMem ca_mem;
+  void *cvode_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CV_ADJMEM_NULL, "CVODEA", "CVodeSetIterTypeB", MSGAM_NULL_CAMEM);
+    return(CV_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+  cvode_mem = (void *)ca_mem->cvb_mem;
+
+  flag = CVodeSetIterType(cvode_mem, iterB);
+  
+  return(flag);
+}
+
+int CVodeSetFdataB(void *cvadj_mem, void *f_dataB)
+{
+  CVadjMem ca_mem;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CV_ADJMEM_NULL, "CVODEA", "CVodeSetFdataB", MSGAM_NULL_CAMEM);
+    return(CV_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  f_data_B = f_dataB;
+
+  return(CV_SUCCESS);
+}
+
+int CVodeSetMaxOrdB(void *cvadj_mem, int maxordB)
+{
+  CVadjMem ca_mem;
+  void *cvode_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CV_ADJMEM_NULL, "CVODEA", "CVodeSetMaxOrdB", MSGAM_NULL_CAMEM);
+    return(CV_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+  cvode_mem = (void *)ca_mem->cvb_mem;
+
+  flag = CVodeSetMaxOrd(cvode_mem, maxordB);
+
+  return(flag);
+}
+
+
+int CVodeSetMaxNumStepsB(void *cvadj_mem, long int mxstepsB)
+{
+  CVadjMem ca_mem;
+  void *cvode_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CV_ADJMEM_NULL, "CVODEA", "CVodeSetMaxNumStepsB", MSGAM_NULL_CAMEM);
+    return(CV_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+  cvode_mem = (void *)ca_mem->cvb_mem;
+
+  flag = CVodeSetMaxNumSteps(cvode_mem, mxstepsB);
+
+  return(flag);
+}
+
+int CVodeSetStabLimDetB(void *cvadj_mem, booleantype stldetB)
+{
+  CVadjMem ca_mem;
+  void *cvode_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CV_ADJMEM_NULL, "CVODEA", "CVodeSetStabLimDetB", MSGAM_NULL_CAMEM);
+    return(CV_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+  cvode_mem = (void *)ca_mem->cvb_mem;
+
+  flag = CVodeSetStabLimDet(cvode_mem, stldetB);
+
+  return(flag);
+}
+
+int CVodeSetInitStepB(void *cvadj_mem, realtype hinB)
+{
+  CVadjMem ca_mem;
+  void *cvode_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CV_ADJMEM_NULL, "CVODEA", "CVodeSetInitStepB", MSGAM_NULL_CAMEM);
+    return(CV_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+  cvode_mem = (void *)ca_mem->cvb_mem;
+
+  flag = CVodeSetInitStep(cvode_mem, hinB);
+
+  return(flag);
+}
+
+int CVodeSetMinStepB(void *cvadj_mem, realtype hminB)
+{
+  CVadjMem ca_mem;
+  void *cvode_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CV_ADJMEM_NULL, "CVODEA", "CVodeSetMinStepB", MSGAM_NULL_CAMEM);
+    return(CV_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+  cvode_mem = (void *)ca_mem->cvb_mem;
+
+  flag = CVodeSetMinStep(cvode_mem, hminB);
+
+  return(flag);
+}
+
+int CVodeSetMaxStepB(void *cvadj_mem, realtype hmaxB)
+{
+  CVadjMem ca_mem;
+  void *cvode_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CV_ADJMEM_NULL, "CVODEA", "CVodeSetMaxStepB", MSGAM_NULL_CAMEM);
+    return(CV_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+  cvode_mem = (void *)ca_mem->cvb_mem;
+
+  flag = CVodeSetMaxStep(cvode_mem, hmaxB);
+
+  return(flag);
+}
+
+/*
+ * CVodeSetQuad*B
+ *
+ * Wrappers for the backward phase around the corresponding 
+ * CVODES quadrature optional input functions
+ */
+
+int CVodeSetQuadFdataB(void *cvadj_mem, void *fQ_dataB)
+{
+  CVadjMem ca_mem;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CV_ADJMEM_NULL, "CVODEA", "CVodeSetQuadFdataB", MSGAM_NULL_CAMEM);
+    return(CV_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  fQ_data_B = fQ_dataB;
+
+  return(CV_SUCCESS);
+}
+
+int CVodeSetQuadErrConB(void *cvadj_mem, booleantype errconQB,
+                        int itolQB, realtype reltolQB, void *abstolQB)
+{
+  CVadjMem ca_mem;
+  void *cvode_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CV_ADJMEM_NULL, "CVODEA", "CVodeSetQuadErrConB", MSGAM_NULL_CAMEM);
+    return(CV_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  cvode_mem = (void *)ca_mem->cvb_mem;
+
+  flag = CVodeSetQuadErrCon(cvode_mem, errconQB, itolQB, reltolQB, abstolQB);
+
+  return(flag);
+}
+
+/* 
+ * -----------------------------------------------------------------
+ * Optional output functions for backward integration
+ * -----------------------------------------------------------------
+ */
+
+/*
+ * CVodeGetQuadB
+ */
+
+int CVodeGetQuadB(void *cvadj_mem, N_Vector qB)
+{
+  CVadjMem ca_mem;
+  void *cvode_mem;
+  int flag;
+  
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CV_ADJMEM_NULL, "CVODEA", "CVodeGetQuadB", MSGAM_NULL_CAMEM);
+    return(CV_ADJMEM_NULL);
+  }
+  ca_mem  = (CVadjMem) cvadj_mem;
+  cvode_mem = (void *) ca_mem->cvb_mem;
+  
+  flag = CVodeGetQuad(cvode_mem, t_for_quad, qB);
+
+  return(flag);
+}
+
+/*
+ * CVadjGetCVodeBmem
+ *
+ * CVadjGetCVodeBmem returns a (void *) pointer to the CVODES     
+ * memory allocated for the backward problem. This pointer can    
+ * then be used to call any of the CVodeGet* CVODES routines to  
+ * extract optional output for the backward integration phase.
+ */
+
+void *CVadjGetCVodeBmem(void *cvadj_mem)
+{
+  CVadjMem ca_mem;
+  void *cvode_mem;
+  
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, 0, "CVODEA", "CVadjGetCVodeBmem", MSGAM_NULL_CAMEM);
+    return(NULL);
+  }
+  ca_mem  = (CVadjMem) cvadj_mem;
+  cvode_mem = (void *) ca_mem->cvb_mem;
+
+  return(cvode_mem);
+}
+
+/*
+ * CVadjGetReturnFlagName
+ *
+ * The following function returns the name of the constant 
+ * associated with a CVODEA-specific return flag
+ */
+
+char *CVadjGetReturnFlagName(int flag)
+{
+  char *name;
+
+  name = (char *)malloc(30*sizeof(char));
+
+  switch(flag) {
+  case CV_SUCCESS:
+    sprintf(name,"CV_SUCCESS");
+    break;
+  case CV_ADJMEM_NULL:
+    sprintf(name,"CV_ADJMEM_NULL");
+    break;
+  case CV_BAD_TB0:
+    sprintf(name,"CV_BAD_TB0");
+    break;
+  case CV_BCKMEM_NULL:
+    sprintf(name,"CV_BCKMEM_NULL");
+    break;
+  case CV_REIFWD_FAIL:
+    sprintf(name,"CV_REIFWD_FAIL");
+    break;
+  case CV_FWD_FAIL:
+    sprintf(name,"CV_FWD_FAIL");
+    break;
+  case CV_BAD_ITASK:
+    sprintf(name,"CV_BAD_ITASK");
+    break;
+  case CV_BAD_TBOUT:
+    sprintf(name,"CV_BAD_TBOUT");
+    break;
+  case CV_GETY_BADT:
+    sprintf(name,"CV_GETY_BADT");
+    break;
+  default:
+    sprintf(name,"NONE");
+  }
+
+  return(name);
+}
+
+/*
+ * CVadjGetCheckPointsInfo
+ *
+ * This routine loads an array of nckpnts structures of type CVadjCheckPointRec.
+ * The user must allocate space for ckpnt.
+ */
+
+int CVadjGetCheckPointsInfo(void *cvadj_mem, CVadjCheckPointRec *ckpnt)
+{
+  CVadjMem ca_mem;
+  CkpntMem ck_mem;
+  int i;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CV_ADJMEM_NULL, "CVODEA", "CVadjGetCheckPointsInfo", MSGAM_NULL_CAMEM);
+    return(CV_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+  ck_mem = ca_mem->ck_mem;
+  i = 0;
+
+  while (ck_mem != NULL) {
+
+    ckpnt[i].my_addr = (void *) ck_mem;
+    ckpnt[i].next_addr = (void *) next_;
+    ckpnt[i].t0 = t0_;
+    ckpnt[i].t1 = t1_;
+    ckpnt[i].nstep = nst_;
+    ckpnt[i].order = q_;
+    ckpnt[i].step = h_;
+
+    ck_mem = next_;
+    i++;
+
+  }
+
+  return(CV_SUCCESS);
+
+}
+
+/*
+ * CVadjGetDataPointHermite
+ *
+ * This routine returns the solution stored in the data structure
+ * at the 'which' data point. Cubic Hermite interpolation.
+ */
+
+int CVadjGetDataPointHermite(void *cvadj_mem, long int which, 
+                             realtype *t, N_Vector y, N_Vector yd)
+{
+  CVadjMem ca_mem;
+  DtpntMem *dt_mem;
+  HermiteDataMem content;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CV_ADJMEM_NULL, "CVODEA", "CVadjGetDataPointHermite", MSGAM_NULL_CAMEM);
+    return(CV_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+  dt_mem = ca_mem->dt_mem;
+
+  if (interpType != CV_HERMITE) {
+    CVProcessError(NULL, CV_ILL_INPUT, "CVODEA", "CVadjGetDataPointHermite", MSGAM_WRONG_INTERP);
+    return(CV_ILL_INPUT);
+  }
+
+  *t = dt_mem[which]->t;
+
+  content = (HermiteDataMem) (dt_mem[which]->content);
+
+  if (y != NULL)
+    N_VScale(ONE, content->y, y);
+
+  if (yd != NULL)
+    N_VScale(ONE, content->yd, yd);
+
+  return(CV_SUCCESS);
+}
+
+/*
+ * CVadjGetDataPointPolynomial
+ *
+ * This routine returns the solution stored in the data structure
+ * at the 'which' data point. Polynomial interpolation.
+ */
+
+int CVadjGetDataPointPolynomial(void *cvadj_mem, long int which, 
+                                realtype *t, int *order, N_Vector y)
+{
+  CVadjMem ca_mem;
+  DtpntMem *dt_mem;
+  PolynomialDataMem content;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CV_ADJMEM_NULL, "CVODEA", "CVadjGetDataPointPolynomial", MSGAM_NULL_CAMEM);
+    return(CV_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+  dt_mem = ca_mem->dt_mem;
+
+  if (interpType != CV_POLYNOMIAL) {
+    CVProcessError(NULL, CV_ILL_INPUT, "CVODEA", "CVadjGetDataPointPolynomial", MSGAM_WRONG_INTERP);
+    return(CV_ILL_INPUT);
+  }
+
+  *t = dt_mem[which]->t;
+
+  content = (PolynomialDataMem) (dt_mem[which]->content);
+
+  if (y != NULL)
+    N_VScale(ONE, content->y, y);
+
+  *order = content->order;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * -----------------------------------------------------------------
+ * UNDOCUMENTED development user-callable functions
+ * -----------------------------------------------------------------
+ */
+
+/*
+ * CVadjGetCurrentCheckPoint
+ *
+ * Returns the address of the 'active' check point.
+ */
+
+int CVadjGetCurrentCheckPoint(void *cvadj_mem, void **addr)
+{
+  CVadjMem ca_mem;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CV_ADJMEM_NULL, "CVODEA", "CVadjGetCurrentCheckPoint", MSGAM_NULL_CAMEM);
+    return(CV_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  *addr = (void *) ckpntData;
+
+  return(CV_SUCCESS);
+}
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes.c b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes.c
new file mode 100644
index 0000000000000000000000000000000000000000..2925a6171140f5b0a9f8bada7c9dd7d0e856a9a5
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes.c
@@ -0,0 +1,7242 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Alan C. Hindmarsh and Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2006, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the implementation file for the main CVODES integrator
+ * with sensitivity analysis capabilities.
+ * -----------------------------------------------------------------
+ * 
+ * EXPORTED FUNCTIONS
+ * ------------------
+ *
+ *   Creation, allocation and re-initialization functions
+ *      CVodeCreate
+ *      CVodeMalloc 
+ *      CVodeReInit
+ *      CVodeRootInit      
+ *      CVodeQuadMalloc
+ *      CVodeQuadReInit   
+ *      CVodeSensMalloc
+ *      CVodeSensReInit             
+ *      CVodeSensToggleOff
+ *
+ *   Main solver function
+ *      CVode
+ *
+ *   Interpolated output and extraction functions
+ *      CVodeGetDky
+ *      CVodeGetQuad             
+ *      CVodeGetQuadDky
+ *      CVodeGetSens             
+ *      CVodeGetSens1
+ *      CVodeGetSensDky         
+ *      CVodeGetSensDky1
+ *
+ *   Deallocation functions
+ *      CVodeFree              
+ *      CVodeQuadFree
+ *      CVodeSensFree  
+ *
+ * PRIVATE FUNCTIONS
+ * -----------------
+ *
+ *      CVCheckNvector
+ *
+ *   Memory allocation/deallocation
+ *      CVAllocVectors         
+ *      CVFreeVectors
+ *      CVQuadAllocVectors      
+ *      CVQuadFreeVectors
+ *      CVSensAllocVectors     
+ *      CVSensFreeVectors
+ *
+ *   Initial stepsize calculation
+ *      CVHin                 
+ *      CVUpperBoundH0
+ *      CVYddNorm     
+ *
+ *   Initial setup
+ *      CVInitialSetup
+ *      CVEwtSet           
+ *      CVEwtSetSS
+ *      CVEwtSetSV         
+ *      CVQuadEwtSet
+ *      CVQuadEwtSetSS     
+ *      CVQuadEwtSetSV
+ *      CVSensEwtSet      
+ *      CVSensEwtSetEE
+ *      CVSensEwtSetSS    
+ *      CVSensEwtSetSV
+ *
+ *   Main CVStep function
+ *      CVStep
+ *
+ *   Functions called at beginning of step
+ *      CVAdjustParams
+ *      CVAdjustOrder    
+ *      CVAdjustAdams
+ *      CVAdjustBDF       
+ *      CVIncreaseBDF
+ *      CVDecreaseBDF     
+ *      CVRescale
+ *      CVPredict         
+ *      CVSet
+ *      CVSetAdams        
+ *      CVAdamsStart
+ *      CVAdamsFinish      
+ *      CVAltSum
+ *      CVSetBDF           
+ *      CVSetTqBDF
+ *
+ *   Nonlinear solver functions
+ *      CVNls              
+ *      CVNlsFunctional
+ *      CVNlsNewton        
+ *      CVNewtonIteration
+ *      CVQuadNls           
+ *      CVStgrNls
+ *      CVStgrNlsFunctional     
+ *      CVStgrNlsNewton
+ *      CVStgrNewtonIteration    
+ *      CVStgr1Nls
+ *      CVStgr1NlsFunctional    
+ *      CVStgr1NlsNewton
+ *      CVStgr1NewtonIteration   
+ *      CVHandleNFlag
+ *      CVRestore             
+ *
+ *   Error Test
+ *      CVDoErrorTest
+ *
+ *   Functions called after a successful step
+ *      CVCompleteStep      
+ *      CVPrepareNextStep
+ *      CVSetEta          
+ *      CVComputeEtaqm1
+ *      CVComputeEtaqp1   
+ *      CVChooseEta
+ *
+ *   Function to handle failures
+ *      CVHandleFailure   
+ *
+ *   Functions for BDF Stability Limit Detection  
+ *      CVBDFStab
+ *      CVsldet   
+ *
+ *   Functions for rootfinding
+ *      CVRcheck1
+ *      CVRcheck2         
+ *      CVRcheck3
+ *      CVRootfind  
+ *
+ *   Functions for combined norms
+ *      CVQuadUpdateNorm
+ *      CVQuadUpdateDsm     
+ *      CVSensNorm
+ *      CVSensUpdateNorm    
+ *      CVStgrUpdateDsm
+ *
+ *   Wrappers for sensitivity RHS
+ *      CVSensRhs           
+ *      CVSensRhs1
+ *
+ *   Internal DQ approximations for sensitivity RHS
+ *      CVSensRhsDQ         
+ *      CVSensRhs1DQ
+ *
+ *   Error message handling functions
+ *      CVProcessError      
+ *      CVErrHandler
+ *
+ * -----------------------------------------------------------------
+ */
+
+/* 
+ * =================================================================
+ * IMPORTED HEADER FILES
+ * =================================================================
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+
+#include "cvodes_impl.h"
+#include <sundials/sundials_math.h>
+#include <sundials/sundials_types.h>
+
+/* 
+ * =================================================================
+ * MACRO DEFINITIONS
+ * =================================================================
+ */
+
+/* Macro: loop */
+#define loop for(;;)
+
+/* 
+ * =================================================================
+ * CVODES PRIVATE CONSTANTS
+ * =================================================================
+ */
+
+#define ZERO   RCONST(0.0)
+#define TINY   RCONST(1.0e-10)
+#define TENTH  RCONST(0.1)
+#define POINT2 RCONST(0.2)
+#define FOURTH RCONST(0.25)
+#define HALF   RCONST(0.5)
+#define ONE    RCONST(1.0)
+#define TWO    RCONST(2.0)
+#define THREE  RCONST(3.0)
+#define FOUR   RCONST(4.0)
+#define FIVE   RCONST(5.0)
+#define TWELVE RCONST(12.0)
+#define HUN    RCONST(100.0)
+
+/* 
+ * =================================================================
+ * CVODES ROUTINE-SPECIFIC CONSTANTS
+ * =================================================================
+ */
+
+/* 
+ * Control constants for lower-level functions used by CVStep 
+ * ----------------------------------------------------------
+ *
+ * CVHin return values:
+ *    CV_SUCCESS,
+ *    CV_RHSFUNC_FAIL,  CV_RPTD_RHSFUNC_ERR,
+ *    CV_QRHSFUNC_FAIL, CV_RPTD_QRHSFUNC_ERR,
+ *    CV_SRHSFUNC_FAIL, CV_RPTD_SRHSFUNC_ERR,
+ *    CV_TOO_CLOSE
+ *
+ * CVStep control constants:
+ *    DO_ERROR_TEST
+ *    PREDICT_AGAIN
+ *
+ * CVStep return values: 
+ *    CV_SUCCESS,
+ *    CV_CONV_FAILURE,      CV_ERR_FAILURE,
+ *    CV_LSETUP_FAIL,       CV_LSOLVE_FAIL, 
+ *    CV_RTFUNC_FAIL,
+ *    CV_RHSFUNC_FAIL,      CV_QRHSFUNC_FAIL,      CV_SRHSFUNC_FAIL,
+ *    CV_FIRST_RHSFUNC_ERR, CV_FIRST_QRHSFUNC_ERR, CV_FIRST_SRHSFUNC_ERR
+ *    CV_UNREC_RHSFUNC_ERR, CV_UNREC_QRHSFUNC_ERR, CV_UNREC_SRHSFUNC_ERR,
+ *    CV_REPTD_RHSFUNC_ERR, CV_REPTD_QRHSFUNC_ERR, CV_REPTD_SRHSFUNC_ERR 
+ *
+ * CVNls input nflag values:
+ *    FIRST_CALL
+ *    PREV_CONV_FAIL
+ *    PREV_ERR_FAIL
+ *    
+ * CVNls return values: 
+ *    CV_SUCCESS,
+ *    CV_LSETUP_FAIL,  CV_LSOLVE_FAIL, 
+ *    CV_RHSFUNC_FAIL, CV_SRHSFUNC_FAIL,
+ *    CONV_FAIL, 
+ *    RHSFUNC_RECVR,   SRHSFUNC_RECVR
+ * 
+ * CVNewtonIteration return values:
+ *    CV_SUCCESS, 
+ *    CV_LSOLVE_FAIL, 
+ *    CV_RHSFUNC_FAIL, CV_SRHSFUNC_FAIL,
+ *    CONV_FAIL,       TRY_AGAIN
+ *    RHSFUNC_RECVR,   SRHSFUNC_RECVR
+ *
+ */
+
+#define DO_ERROR_TEST    +2
+#define PREDICT_AGAIN    +3
+
+#define CONV_FAIL        +4 
+#define TRY_AGAIN        +5
+
+#define FIRST_CALL       +6
+#define PREV_CONV_FAIL   +7
+#define PREV_ERR_FAIL    +8
+
+#define RHSFUNC_RECVR    +9
+
+#define QRHSFUNC_RECVR   +11
+#define SRHSFUNC_RECVR   +12
+
+/*
+ * Control constants for lower-level rootfinding functions
+ * -------------------------------------------------------
+ *
+ * CVRcheck1 return values:
+ *    CV_SUCCESS,
+ *    CV_RTFUNC_FAIL,
+ *    INITROOT
+ * CVRcheck2 return values:
+ *    CV_SUCCESS,
+ *    CV_RTFUNC_FAIL,
+ *    CLOSERT,
+ *    RTFOUND
+ * CVRcheck3 return values:
+ *    CV_SUCCESS,
+ *    CV_RTFUNC_FAIL,
+ *    RTFOUND
+ * CVRootFind return values:
+ *    CV_SUCCESS,
+ *    CV_RTFUNC_FAIL,
+ *    RTFOUND
+ */
+
+#define RTFOUND          +1
+#define INITROOT         +2
+#define CLOSERT          +3
+
+/*
+ * Control constants for sensitivity DQ
+ * ------------------------------------
+ */
+
+#define CENTERED1        +1
+#define CENTERED2        +2
+#define FORWARD1         +3
+#define FORWARD2         +4
+
+
+/*
+ * Algorithmic constants
+ * ---------------------
+ *
+ * CVodeGetDky and CVStep
+ *
+ *    FUZZ_FACTOR fuzz factor used to estimate infinitesimal time intervals
+ *
+ * CVHin
+ *
+ *    HLB_FACTOR  factor for upper bound on initial step size
+ *    HUB_FACTOR  factor for lower bound on initial step size
+ *    H_BIAS      bias factor in selection of intial step size
+ *    MAX_ITERS   maximum attempts to compute the initial step size
+ *
+ * CVodeCreate 
+ *
+ *   CORTES       constant in nonlinear iteration convergence test
+ *
+ * CVStep
+ *
+ *    THRESH      if eta < THRESH reject a change in step size or order
+ *    ETAMX1      -+
+ *    ETAMX2       |
+ *    ETAMX3       |-> bounds for eta (step size change)
+ *    ETAMXF       |
+ *    ETAMIN       |
+ *    ETACF       -+
+ *    ADDON       safety factor in computing eta
+ *    BIAS1       -+
+ *    BIAS2        |-> bias factors in eta selection
+ *    BIAS3       -+
+ *    ONEPSM      (1+epsilon) used in testing if the step size is below its bound
+ *
+ *    SMALL_NST   nst > SMALL_NST => use ETAMX3 
+ *    MXNCF       max no. of convergence failures during one step try
+ *    MXNEF       max no. of error test failures during one step try
+ *    MXNEF1      max no. of error test failures before forcing a reduction of order
+ *    SMALL_NEF   if an error failure occurs and SMALL_NEF <= nef <= MXNEF1, then
+ *                reset eta =  MIN(eta, ETAMXF)
+ *    LONG_WAIT   number of steps to wait before considering an order change when
+ *                q==1 and MXNEF1 error test failures have occurred
+ *
+ * CVNls
+ *    
+ *    NLS_MAXCOR  maximum no. of corrector iterations for the nonlinear solver
+ *    CRDOWN      constant used in the estimation of the convergence rate (crate)
+ *                of the iterates for the nonlinear equation
+ *    DGMAX       iter == CV_NEWTON, |gamma/gammap-1| > DGMAX => call lsetup
+ *    RDIV        declare divergence if ratio del/delp > RDIV
+ *    MSBP        max no. of steps between lsetup calls
+ *    
+ */
+
+
+#define FUZZ_FACTOR RCONST(100.0)
+
+#define HLB_FACTOR RCONST(100.0)
+#define HUB_FACTOR RCONST(0.1)
+#define H_BIAS     HALF
+#define MAX_ITERS  4
+
+#define CORTES RCONST(0.1)
+
+#define THRESH RCONST(1.5)
+#define ETAMX1 RCONST(10000.0) 
+#define ETAMX2 RCONST(10.0)
+#define ETAMX3 RCONST(10.0)
+#define ETAMXF RCONST(0.2)
+#define ETAMIN RCONST(0.1)
+#define ETACF  RCONST(0.25)
+#define ADDON  RCONST(0.000001)
+#define BIAS1  RCONST(6.0)
+#define BIAS2  RCONST(6.0)
+#define BIAS3  RCONST(10.0)
+#define ONEPSM RCONST(1.000001)
+
+#define SMALL_NST    10
+#define MXNCF        10
+#define MXNEF         7
+#define MXNEF1        3
+#define SMALL_NEF     2
+#define LONG_WAIT    10
+
+#define NLS_MAXCOR 3
+#define CRDOWN RCONST(0.3)
+#define DGMAX  RCONST(0.3)
+
+#define RDIV      TWO
+#define MSBP       20
+
+/* 
+ * =================================================================
+ * PRIVATE FUNCTION PROTOTYPES
+ * =================================================================
+ */
+
+static booleantype CVCheckNvector(N_Vector tmpl);
+
+/* Memory allocation/deallocation */
+
+static booleantype CVAllocVectors(CVodeMem cv_mem, N_Vector tmpl, int tol);
+static void CVFreeVectors(CVodeMem cv_mem);
+
+static booleantype CVQuadAllocVectors(CVodeMem cv_mem, N_Vector tmpl);
+static void CVQuadFreeVectors(CVodeMem cv_mem);
+
+static booleantype CVSensAllocVectors(CVodeMem cv_mem, N_Vector tmpl);
+static void CVSensFreeVectors(CVodeMem cv_mem);
+
+/* Initial stepsize calculation */
+
+static int CVHin(CVodeMem cv_mem, realtype tout);
+static realtype CVUpperBoundH0(CVodeMem cv_mem, realtype tdist);
+static int CVYddNorm(CVodeMem cv_mem, realtype hg, realtype *yddnrm);
+
+/* Initial setup */
+
+static int CVInitialSetup(CVodeMem cv_mem);
+
+static int CVEwtSetSS(CVodeMem cv_mem, N_Vector ycur, N_Vector weight);
+static int CVEwtSetSV(CVodeMem cv_mem, N_Vector ycur, N_Vector weight);
+
+static int CVQuadEwtSet(CVodeMem cv_mem, N_Vector qcur, N_Vector weightQ);
+static int CVQuadEwtSetSS(CVodeMem cv_mem, N_Vector qcur, N_Vector weightQ);
+static int CVQuadEwtSetSV(CVodeMem cv_mem, N_Vector qcur, N_Vector weightQ);
+
+static int CVSensEwtSet(CVodeMem cv_mem, N_Vector *yScur, N_Vector *weightS);
+static int CVSensEwtSetEE(CVodeMem cv_mem, N_Vector *yScur, N_Vector *weightS);
+static int CVSensEwtSetSS(CVodeMem cv_mem, N_Vector *yScur, N_Vector *weightS);
+static int CVSensEwtSetSV(CVodeMem cv_mem, N_Vector *yScur, N_Vector *weightS);
+
+/* Main CVStep function */
+
+static int CVStep(CVodeMem cv_mem);
+
+/* Function called at beginning of step */
+
+static void CVAdjustParams(CVodeMem cv_mem);
+static void CVAdjustOrder(CVodeMem cv_mem, int deltaq);
+static void CVAdjustAdams(CVodeMem cv_mem, int deltaq);
+static void CVAdjustBDF(CVodeMem cv_mem, int deltaq);
+static void CVIncreaseBDF(CVodeMem cv_mem);
+static void CVDecreaseBDF(CVodeMem cv_mem);
+static void CVRescale(CVodeMem cv_mem);
+static void CVPredict(CVodeMem cv_mem);
+static void CVSet(CVodeMem cv_mem);
+static void CVSetAdams(CVodeMem cv_mem);
+static realtype CVAdamsStart(CVodeMem cv_mem, realtype m[]);
+static void CVAdamsFinish(CVodeMem cv_mem, realtype m[], realtype M[], realtype hsum);
+static realtype CVAltSum(int iend, realtype a[], int k);
+static void CVSetBDF(CVodeMem cv_mem);
+static void CVSetTqBDF(CVodeMem cv_mem, realtype hsum, realtype alpha0,
+                       realtype alpha0_hat, realtype xi_inv, realtype xistar_inv);
+
+/* Nonlinear solver functions */
+
+static int CVNls(CVodeMem cv_mem, int nflag);
+static int CVNlsFunctional(CVodeMem cv_mem);
+static int CVNlsNewton(CVodeMem cv_mem, int nflag);
+static int CVNewtonIteration(CVodeMem cv_mem);
+
+static int CVQuadNls(CVodeMem cv_mem);
+
+static int CVStgrNls(CVodeMem cv_mem);
+static int CVStgrNlsFunctional(CVodeMem cv_mem);
+static int CVStgrNlsNewton(CVodeMem cv_mem);
+static int CVStgrNewtonIteration(CVodeMem cv_mem);
+
+static int CVStgr1Nls(CVodeMem cv_mem, int is);
+static int CVStgr1NlsFunctional(CVodeMem cv_mem, int is);
+static int CVStgr1NlsNewton(CVodeMem cv_mem, int is);
+static int CVStgr1NewtonIteration(CVodeMem cv_mem, int is);
+
+static int CVHandleNFlag(CVodeMem cv_mem, int *nflagPtr, realtype saved_t,
+                         int *ncfPtr, long int *ncfnPtr);
+
+static void CVRestore(CVodeMem cv_mem, realtype saved_t);
+
+/* Error Test */
+
+static int CVDoErrorTest(CVodeMem cv_mem, int *nflagPtr, realtype saved_t, 
+                         realtype acor_nrm,
+                         int *nefPtr, long int *netfPtr, realtype *dsmPtr);
+
+/* Function called after a successful step */
+
+static void CVCompleteStep(CVodeMem cv_mem);
+static void CVPrepareNextStep(CVodeMem cv_mem, realtype dsm);
+static void CVSetEta(CVodeMem cv_mem);
+static realtype CVComputeEtaqm1(CVodeMem cv_mem);
+static realtype CVComputeEtaqp1(CVodeMem cv_mem);
+static void CVChooseEta(CVodeMem cv_mem);
+
+/* Function to handle failures */
+
+static int CVHandleFailure(CVodeMem cv_mem,int flag);
+
+/* Functions for BDF Stability Limit Detection */
+
+static void CVBDFStab(CVodeMem cv_mem);
+static int CVsldet(CVodeMem cv_mem);
+
+/* Functions for rootfinding */
+
+static int CVRcheck1(CVodeMem cv_mem);
+static int CVRcheck2(CVodeMem cv_mem);
+static int CVRcheck3(CVodeMem cv_mem);
+static int CVRootfind(CVodeMem cv_mem);
+
+/* Function for combined norms */
+
+static realtype CVQuadUpdateNorm(CVodeMem cv_mem, realtype old_nrm,
+                                 N_Vector xQ, N_Vector wQ);
+static realtype CVQuadUpdateDsm(CVodeMem cv_mem, realtype old_dsm, 
+                                realtype dsmQ);
+static realtype CVSensNorm(CVodeMem cv_mem, N_Vector *xS, N_Vector *wS);
+static realtype CVSensUpdateNorm(CVodeMem cv_mem, realtype old_nrm,
+                                 N_Vector *xS, N_Vector *wS);
+static realtype CVStgrUpdateDsm(CVodeMem cv_mem, realtype old_dsm, 
+                                realtype dsmS);
+
+/* Wrappers for sensitivity RHS */
+
+static int CVSensRhs(CVodeMem cv_mem, realtype time, 
+                     N_Vector ycur, N_Vector fcur, 
+                     N_Vector *yScur, N_Vector *fScur,
+                     N_Vector temp1, N_Vector temp2);
+static int CVSensRhs1(CVodeMem cv_mem, realtype time, 
+                      N_Vector ycur, N_Vector fcur, 
+                      int is, N_Vector yScur, N_Vector fScur,
+                      N_Vector temp1, N_Vector temp2);
+
+/* 
+ * =================================================================
+ * EXPORTED FUNCTIONS IMPLEMENTATION
+ * =================================================================
+ */
+
+/* 
+ * -----------------------------------------------------------------
+ * Creation, allocation and re-initialization functions
+ * -----------------------------------------------------------------
+ */
+
+/* 
+ * CVodeCreate
+ *
+ * CVodeCreate creates an internal memory block for a problem to 
+ * be solved by CVODES.
+ * If successful, CVodeCreate returns a pointer to the problem memory. 
+ * This pointer should be passed to CVodeMalloc.  
+ * If an initialization error occurs, CVodeCreate prints an error 
+ * message to standard err and returns NULL. 
+ */
+
+void *CVodeCreate(int lmm, int iter)
+{
+  int maxord;
+  CVodeMem cv_mem;
+
+  /* Test inputs */
+
+  if ((lmm != CV_ADAMS) && (lmm != CV_BDF)) {
+    CVProcessError(NULL, 0, "CVODES", "CVodeCreate", MSGCV_BAD_LMM);
+    return(NULL);
+  }
+  
+  if ((iter != CV_FUNCTIONAL) && (iter != CV_NEWTON)) {
+    CVProcessError(NULL, 0, "CVODES", "CVodeCreate", MSGCV_BAD_ITER);
+    return(NULL);
+  }
+
+  cv_mem = NULL;
+  cv_mem = (CVodeMem) malloc(sizeof(struct CVodeMemRec));
+  if (cv_mem == NULL) {
+    CVProcessError(NULL, 0, "CVODES", "CVodeCreate", MSGCV_CVMEM_FAIL);
+    return(NULL);
+  }
+
+  maxord = (lmm == CV_ADAMS) ? ADAMS_Q_MAX : BDF_Q_MAX;
+
+  /* copy input parameters into cv_mem */
+  cv_mem->cv_lmm  = lmm;
+  cv_mem->cv_iter = iter;
+
+  /* Set uround */
+  cv_mem->cv_uround = UNIT_ROUNDOFF;
+
+  /* Set default values for integrator optional inputs */
+  cv_mem->cv_f        = NULL;
+  cv_mem->cv_f_data   = NULL;
+  cv_mem->cv_efun     = NULL;
+  cv_mem->cv_e_data   = NULL;
+  cv_mem->cv_ehfun    = CVErrHandler;
+  cv_mem->cv_eh_data  = (void *) cv_mem;
+  cv_mem->cv_errfp    = stderr;
+  cv_mem->cv_qmax     = maxord;
+  cv_mem->cv_mxstep   = MXSTEP_DEFAULT;
+  cv_mem->cv_mxhnil   = MXHNIL_DEFAULT;
+  cv_mem->cv_sldeton  = FALSE;
+  cv_mem->cv_hin      = ZERO;
+  cv_mem->cv_hmin     = HMIN_DEFAULT;
+  cv_mem->cv_hmax_inv = HMAX_INV_DEFAULT;
+  cv_mem->cv_tstopset = FALSE;
+  cv_mem->cv_maxcor   = NLS_MAXCOR;
+  cv_mem->cv_maxnef   = MXNEF;
+  cv_mem->cv_maxncf   = MXNCF;
+  cv_mem->cv_nlscoef  = CORTES;
+
+  /* Initialize root finding variables */
+
+  cv_mem->cv_glo    = NULL;
+  cv_mem->cv_ghi    = NULL;
+  cv_mem->cv_grout  = NULL;
+  cv_mem->cv_iroots = NULL;
+  cv_mem->cv_gfun   = NULL;
+  cv_mem->cv_g_data = NULL;
+  cv_mem->cv_nrtfn  = 0;  
+
+  /* Set default values for quad. optional inputs */
+  cv_mem->cv_quadr    = FALSE;
+  cv_mem->cv_fQ       = NULL;
+  cv_mem->cv_fQ_data  = NULL;
+  cv_mem->cv_errconQ  = FALSE;
+
+  /* Set default values for sensi. optional inputs */
+  cv_mem->cv_sensi        = FALSE;
+  cv_mem->cv_fS_data      = (void *)cv_mem;
+  cv_mem->cv_fS           = CVSensRhsDQ;
+  cv_mem->cv_fS1          = CVSensRhs1DQ;
+  cv_mem->cv_fSDQ         = TRUE;
+  cv_mem->cv_ifS          = CV_ONESENS;
+  cv_mem->cv_DQtype       = CV_CENTERED;
+  cv_mem->cv_DQrhomax     = ZERO;
+  cv_mem->cv_p            = NULL;
+  cv_mem->cv_pbar         = NULL;
+  cv_mem->cv_plist        = NULL;
+  cv_mem->cv_errconS      = FALSE;
+  cv_mem->cv_maxcorS      = NLS_MAXCOR;
+  cv_mem->cv_ncfS1        = NULL;
+  cv_mem->cv_ncfnS1       = NULL;
+  cv_mem->cv_nniS1        = NULL;
+  cv_mem->cv_itolS        = CV_EE;
+
+  /* Set the saved values for qmax_alloc */
+
+  cv_mem->cv_qmax_alloc  = maxord;
+  cv_mem->cv_qmax_allocQ = maxord;
+  cv_mem->cv_qmax_allocS = maxord;
+
+  /* Initialize lrw and liw */
+
+  cv_mem->cv_lrw = 65 + 2*L_MAX + NUM_TESTS;
+  cv_mem->cv_liw = 52;
+
+  /* No mallocs have been done yet */
+
+  cv_mem->cv_VabstolMallocDone  = FALSE;
+  cv_mem->cv_MallocDone         = FALSE;
+
+  cv_mem->cv_VabstolQMallocDone = FALSE;
+  cv_mem->cv_quadMallocDone     = FALSE;
+
+  cv_mem->cv_VabstolSMallocDone = FALSE;
+  cv_mem->cv_SabstolSMallocDone = FALSE;
+  cv_mem->cv_sensMallocDone     = FALSE;
+
+  /* Return pointer to CVODES memory block */
+
+  return((void *)cv_mem);
+}
+
+/*-----------------------------------------------------------------*/
+
+#define iter (cv_mem->cv_iter)  
+#define lmm  (cv_mem->cv_lmm) 
+#define lrw  (cv_mem->cv_lrw)
+#define liw  (cv_mem->cv_liw)
+
+/*-----------------------------------------------------------------*/
+
+/*
+ * CVodeMalloc
+ * 
+ * CVodeMalloc allocates and initializes memory for a problem. All 
+ * problem inputs are checked for errors. If any error occurs during 
+ * initialization, it is reported to the file whose file pointer is 
+ * errfp and an error flag is returned. Otherwise, it returns CV_SUCCESS
+ */
+
+int CVodeMalloc(void *cvode_mem, CVRhsFn f, realtype t0, N_Vector y0, 
+                int itol, realtype reltol, void *abstol)
+{
+  CVodeMem cv_mem;
+  booleantype nvectorOK, allocOK, neg_abstol;
+  long int lrw1, liw1;
+  int i,k;
+
+  /* Check cvode_mem */
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeMalloc", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  /* Check for legal input parameters */
+
+  if (y0==NULL) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeMalloc", MSGCV_NULL_Y0);
+    return(CV_ILL_INPUT);
+  }
+
+  if ((itol != CV_SS) && (itol != CV_SV) && (itol != CV_WF)) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeMalloc", MSGCV_BAD_ITOL);
+    return(CV_ILL_INPUT);
+  }
+
+  if (f == NULL) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeMalloc", MSGCV_NULL_F);
+    return(CV_ILL_INPUT);
+  }
+
+  /* Test if all required vector operations are implemented */
+
+  nvectorOK = CVCheckNvector(y0);
+  if(!nvectorOK) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeMalloc", MSGCV_BAD_NVECTOR);
+    return(CV_ILL_INPUT);
+  }
+
+  /* Test tolerances */
+
+  if (itol != CV_WF) {
+
+    if (abstol == NULL) {
+      CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeMalloc", MSGCV_NULL_ABSTOL);
+      return(CV_ILL_INPUT);
+    }
+
+    if (reltol < ZERO) {
+      CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeMalloc", MSGCV_BAD_RELTOL);
+      return(CV_ILL_INPUT);
+    }
+
+    if (itol == CV_SS)
+      neg_abstol = (*((realtype *)abstol) < ZERO);
+    else
+      neg_abstol = (N_VMin((N_Vector)abstol) < ZERO);
+
+    if (neg_abstol) {
+      CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeMalloc", MSGCV_BAD_ABSTOL);
+      return(CV_ILL_INPUT);
+    }
+
+  }
+
+  /* Set space requirements for one N_Vector */
+
+  if (y0->ops->nvspace != NULL) {
+    N_VSpace(y0, &lrw1, &liw1);
+  } else {
+    lrw1 = 0;
+    liw1 = 0;
+  }
+  cv_mem->cv_lrw1 = lrw1;
+  cv_mem->cv_liw1 = liw1;
+
+  /* Allocate the vectors (using y0 as a template) */
+
+  allocOK = CVAllocVectors(cv_mem, y0, itol);
+  if (!allocOK) {
+    CVProcessError(cv_mem, CV_MEM_FAIL, "CVODES", "CVodeMalloc", MSGCV_MEM_FAIL);
+    return(CV_MEM_FAIL);
+  }
+
+  /* Copy tolerances into memory */
+
+  cv_mem->cv_itol   = itol;
+  cv_mem->cv_reltol = reltol;      
+
+  if (itol == CV_SS)
+    cv_mem->cv_Sabstol = *((realtype *)abstol);
+  else if (itol == CV_SV)
+    N_VScale(ONE, (N_Vector)abstol, cv_mem->cv_Vabstol);
+
+  /* All error checking is complete at this point */
+
+  /* Copy the input parameters into CVODES state */
+
+  cv_mem->cv_f  = f;
+  cv_mem->cv_tn = t0;
+
+  /* Set step parameters */
+
+  cv_mem->cv_q      = 1;
+  cv_mem->cv_L      = 2;
+  cv_mem->cv_qwait  = cv_mem->cv_L;
+  cv_mem->cv_etamax = ETAMX1;
+
+  cv_mem->cv_qu     = 0;
+  cv_mem->cv_hu     = ZERO;
+  cv_mem->cv_tolsf  = ONE;
+
+  /* Set the linear solver addresses to NULL.
+     (We check != NULL later, in CVode, if using CV_NEWTON.) */
+
+  cv_mem->cv_linit  = NULL;
+  cv_mem->cv_lsetup = NULL;
+  cv_mem->cv_lsolve = NULL;
+  cv_mem->cv_lfree  = NULL;
+  cv_mem->cv_lmem   = NULL;
+
+  /* Set forceSetup to FALSE */
+
+  cv_mem->cv_forceSetup = FALSE;
+
+  /* Initialize zn[0] in the history array */
+
+  N_VScale(ONE, y0, cv_mem->cv_zn[0]);
+
+  /* Initialize all the counters */
+
+  cv_mem->cv_nst     = 0;
+  cv_mem->cv_nfe     = 0;
+  cv_mem->cv_ncfn    = 0;
+  cv_mem->cv_netf    = 0;
+  cv_mem->cv_nni     = 0;
+  cv_mem->cv_nsetups = 0;
+  cv_mem->cv_nhnil   = 0;
+  cv_mem->cv_nstlp   = 0;
+  cv_mem->cv_nscon   = 0;
+  cv_mem->cv_nge     = 0;
+
+  /* Initialize other integrator optional outputs */
+
+  cv_mem->cv_h0u      = ZERO;
+  cv_mem->cv_next_h   = ZERO;
+  cv_mem->cv_next_q   = 0;
+
+  /* Initialize Stablilty Limit Detection data */
+  /* NOTE: We do this even if stab lim det was not
+     turned on yet. This way, the user can turn it
+     on at any time */
+
+  cv_mem->cv_nor = 0;
+  for (i = 1; i <= 5; i++)
+    for (k = 1; k <= 3; k++) 
+      cv_mem->cv_ssdat[i-1][k-1] = ZERO;
+
+  /* Problem has been successfully initialized */
+
+  cv_mem->cv_MallocDone = TRUE;
+
+  return(CV_SUCCESS);
+}
+
+/*-----------------------------------------------------------------*/
+
+#define lrw1 (cv_mem->cv_lrw1)
+#define liw1 (cv_mem->cv_liw1)
+
+/*-----------------------------------------------------------------*/
+
+/*
+ * CVodeReInit
+ *
+ * CVodeReInit re-initializes CVODES's memory for a problem, assuming
+ * it has already been allocated in a prior CVodeMalloc call.
+ * All problem specification inputs are checked for errors.
+ * If any error occurs during initialization, it is reported to the
+ * file whose file pointer is errfp.
+ * The return value is CV_SUCCESS = 0 if no errors occurred, or
+ * a negative value otherwise.
+ */
+
+int CVodeReInit(void *cvode_mem, CVRhsFn f, realtype t0, N_Vector y0, 
+                int itol, realtype reltol, void *abstol)
+{
+  CVodeMem cv_mem;
+  booleantype neg_abstol;
+  int i,k;
+ 
+  /* Check cvode_mem */
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeReInit", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  /* Check if cvode_mem was allocated */
+
+  if (cv_mem->cv_MallocDone == FALSE) {
+    CVProcessError(cv_mem, CV_NO_MALLOC, "CVODES", "CVodeReInit", MSGCV_NO_MALLOC);
+    return(CV_NO_MALLOC);
+  }
+
+  /* Check for legal input parameters */
+
+  if (y0 == NULL) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeReInit", MSGCV_NULL_Y0);
+    return(CV_ILL_INPUT);
+  }
+  
+  if ((itol != CV_SS) && (itol != CV_SV) && (itol != CV_WF)) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeReInit", MSGCV_BAD_ITOL);
+    return(CV_ILL_INPUT);
+  }
+
+  if (f == NULL) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeReInit", MSGCV_NULL_F);
+    return(CV_ILL_INPUT);
+  }
+
+  /* Test tolerances */
+   
+  if (itol != CV_WF) {
+    
+    if (abstol == NULL) {
+      CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeReInit", MSGCV_NULL_ABSTOL);
+      return(CV_ILL_INPUT);
+    }
+
+    if (reltol < ZERO) {
+      CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeReInit", MSGCV_BAD_RELTOL);
+      return(CV_ILL_INPUT);
+    }
+
+    if (itol == CV_SS)
+      neg_abstol = (*((realtype *)abstol) < ZERO);
+    else
+      neg_abstol = (N_VMin((N_Vector)abstol) < ZERO);
+
+    if (neg_abstol) {
+      CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeReInit", MSGCV_BAD_ABSTOL);
+      return(CV_ILL_INPUT);
+    }
+
+  }
+
+  /* Copy tolerances into memory */
+
+  if ( (itol != CV_SV) && (cv_mem->cv_VabstolMallocDone) ) {
+    N_VDestroy(cv_mem->cv_Vabstol);
+    lrw -= lrw1;
+    liw -= liw1;
+    cv_mem->cv_VabstolMallocDone = FALSE;
+  }
+
+  if ( (itol == CV_SV) && !(cv_mem->cv_VabstolMallocDone) ) {
+    cv_mem->cv_Vabstol = NULL;
+    cv_mem->cv_Vabstol = N_VClone(y0);
+    lrw += lrw1;
+    liw += liw1;
+    cv_mem->cv_VabstolMallocDone = TRUE;
+  }
+
+  cv_mem->cv_itol   = itol;
+  cv_mem->cv_reltol = reltol;
+
+  if (itol == CV_SS)
+    cv_mem->cv_Sabstol = *((realtype *)abstol);
+  else if (itol == CV_SV)
+    N_VScale(ONE, (N_Vector)abstol, cv_mem->cv_Vabstol);
+
+  /* All error checking is complete at this point */
+  
+  /* Copy the input parameters into CVODES state */
+
+  cv_mem->cv_f = f;
+  cv_mem->cv_tn = t0;
+
+  /* Set step parameters */
+
+  cv_mem->cv_q      = 1;
+  cv_mem->cv_L      = 2;
+  cv_mem->cv_qwait  = cv_mem->cv_L;
+  cv_mem->cv_etamax = ETAMX1;
+
+  cv_mem->cv_qu     = 0;
+  cv_mem->cv_hu     = ZERO;
+  cv_mem->cv_tolsf  = ONE;
+
+  /* Set forceSetup to FALSE */
+
+  cv_mem->cv_forceSetup = FALSE;
+
+  /* Initialize zn[0] in the history array */
+
+  N_VScale(ONE, y0, cv_mem->cv_zn[0]);
+ 
+  /* Initialize all the counters */
+
+  cv_mem->cv_nst     = 0;
+  cv_mem->cv_nfe     = 0;
+  cv_mem->cv_ncfn    = 0;
+  cv_mem->cv_netf    = 0;
+  cv_mem->cv_nni     = 0;
+  cv_mem->cv_nsetups = 0;
+  cv_mem->cv_nhnil   = 0;
+  cv_mem->cv_nstlp   = 0;
+  cv_mem->cv_nscon   = 0;
+  cv_mem->cv_nge     = 0;
+
+  /* Initialize other integrator optional outputs */
+
+  cv_mem->cv_h0u      = ZERO;
+  cv_mem->cv_next_h   = ZERO;
+  cv_mem->cv_next_q   = 0;
+
+  /* Initialize Stablilty Limit Detection data */
+
+  cv_mem->cv_nor = 0;
+  for (i = 1; i <= 5; i++)
+    for (k = 1; k <= 3; k++) 
+      cv_mem->cv_ssdat[i-1][k-1] = ZERO;
+  
+  /* Problem has been successfully re-initialized */
+
+  return(CV_SUCCESS);
+}
+
+/*-----------------------------------------------------------------*/
+
+#define gfun   (cv_mem->cv_gfun)
+#define g_data (cv_mem->cv_g_data) 
+#define glo    (cv_mem->cv_glo)
+#define ghi    (cv_mem->cv_ghi)
+#define grout  (cv_mem->cv_grout)
+#define iroots (cv_mem->cv_iroots)
+
+/*-----------------------------------------------------------------*/
+
+/*
+ * CVodeRootInit
+ *
+ * CVodeRootInit initializes a rootfinding problem to be solved
+ * during the integration of the ODE system.  It loads the root
+ * function pointer and the number of root functions, and allocates
+ * workspace memory.  The return value is CV_SUCCESS = 0 if no errors
+ * occurred, or a negative value otherwise.
+ */
+
+int CVodeRootInit(void *cvode_mem, int nrtfn, CVRootFn g, void *gdata)
+{
+  CVodeMem cv_mem;
+  int nrt;
+
+  /* Check cvode_mem */
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeRootInit", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  nrt = (nrtfn < 0) ? 0 : nrtfn;
+
+  /* If rerunning CVodeRootInit() with a different number of root
+     functions (changing number of gfun components), then free
+     currently held memory resources */
+  if ((nrt != cv_mem->cv_nrtfn) && (cv_mem->cv_nrtfn > 0)) {
+    free(glo); glo = NULL;
+    free(ghi); ghi = NULL;
+    free(grout); grout = NULL;
+    free(iroots); iroots = NULL;
+
+    lrw -= 3* (cv_mem->cv_nrtfn);
+    liw -= cv_mem->cv_nrtfn;
+
+  }
+
+  /* If CVodeRootInit() was called with nrtfn == 0, then set cv_nrtfn to
+     zero and cv_gfun to NULL before returning */
+  if (nrt == 0) {
+    cv_mem->cv_nrtfn = nrt;
+    gfun = NULL;
+    g_data = NULL;
+    return(CV_SUCCESS);
+  }
+
+  /* Store user's data pointer */
+  g_data = gdata;
+
+  /* If rerunning CVodeRootInit() with the same number of root functions
+     (not changing number of gfun components), then check if the root
+     function argument has changed */
+  /* If g != NULL then return as currently reserved memory resources
+     will suffice */
+  if (nrt == cv_mem->cv_nrtfn) {
+    if (g != gfun) {
+      if (g == NULL) {
+	free(glo); glo = NULL;
+	free(ghi); ghi = NULL;
+	free(grout); grout = NULL;
+	free(iroots); iroots = NULL;
+        
+        lrw -= 3*nrt;
+        liw -= nrt;
+
+        CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeRootInit", MSGCV_NULL_G);
+	return(CV_ILL_INPUT);
+      }
+      else {
+	gfun = g;
+	return(CV_SUCCESS);
+      }
+    }
+    else return(CV_SUCCESS);
+  }
+
+  /* Set variable values in CVode memory block */
+  cv_mem->cv_nrtfn = nrt;
+  if (g == NULL) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeRootInit", MSGCV_NULL_G);
+    return(CV_ILL_INPUT);
+  }
+  else gfun = g;
+
+  /* Allocate necessary memory and return */
+  glo = NULL;
+  glo = (realtype *) malloc(nrt*sizeof(realtype));
+  if (glo == NULL) {
+    CVProcessError(cv_mem, CV_MEM_FAIL, "CVODES", "CVodeRootInit", MSGCV_MEM_FAIL);
+    return(CV_MEM_FAIL);
+  }
+    
+  ghi = NULL;
+  ghi = (realtype *) malloc(nrt*sizeof(realtype));
+  if (ghi == NULL) {
+    free(glo); glo = NULL;
+    CVProcessError(cv_mem, CV_MEM_FAIL, "CVODES", "CVodeRootInit", MSGCV_MEM_FAIL);
+    return(CV_MEM_FAIL);
+  }
+    
+  grout = NULL;
+  grout = (realtype *) malloc(nrt*sizeof(realtype));
+  if (grout == NULL) {
+    free(glo); glo = NULL;
+    free(ghi); ghi = NULL;
+    CVProcessError(cv_mem, CV_MEM_FAIL, "CVODES", "CVodeRootInit", MSGCV_MEM_FAIL);
+    return(CV_MEM_FAIL);
+  }
+
+  iroots = NULL;
+  iroots = (int *) malloc(nrt*sizeof(int));
+  if (iroots == NULL) {
+    free(glo); glo = NULL;
+    free(ghi); ghi = NULL;
+    free(grout); grout = NULL;
+    CVProcessError(cv_mem, CV_MEM_FAIL, "CVODES", "CVodeRootInit", MSGCV_MEM_FAIL);
+    return(CV_MEM_FAIL);
+  }
+
+  lrw += 3*nrt;
+  liw += nrt;
+
+  return(CV_SUCCESS);
+}
+
+/*
+ * CVodeQuadMalloc
+ *
+ * CVodeQuadMalloc allocates and initializes quadrature related 
+ * memory for a problem. All problem specification inputs are 
+ * checked for errors. If any error occurs during initialization, 
+ * it is reported to the file whose file pointer is errfp. 
+ * The return value is CV_SUCCESS = 0 if no errors occurred, or
+ * a negative value otherwise.
+ */
+
+int CVodeQuadMalloc(void *cvode_mem, CVQuadRhsFn fQ, N_Vector yQ0)
+{
+  CVodeMem cv_mem;
+  booleantype allocOK;
+  long int lrw1Q, liw1Q;
+
+  /* Check cvode_mem */
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeQuadMalloc", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  /* Set space requirements for one N_Vector */
+  N_VSpace(yQ0, &lrw1Q, &liw1Q);
+  cv_mem->cv_lrw1Q = lrw1Q;
+  cv_mem->cv_liw1Q = liw1Q;
+
+  /* Allocate the vectors (using yQ0 as a template) */
+  allocOK = CVQuadAllocVectors(cv_mem, yQ0);
+  if (!allocOK) {
+    CVProcessError(cv_mem, CV_MEM_FAIL, "CVODES", "CVodeQuadMalloc", MSGCV_MEM_FAIL);
+    return(CV_MEM_FAIL);
+  }
+
+  /* Initialize znQ[0] in the history array */
+  N_VScale(ONE, yQ0, cv_mem->cv_znQ[0]);
+
+  /* Copy the input parameters into CVODES state */
+  cv_mem->cv_fQ = fQ;
+
+  /* Initialize counters */
+  cv_mem->cv_nfQe  = 0;
+  cv_mem->cv_netfQ = 0;
+
+  /* Quadrature integration turned ON */
+  cv_mem->cv_quadr = TRUE;
+  cv_mem->cv_quadMallocDone = TRUE;
+
+  /* Quadrature initialization was successfull */
+  return(CV_SUCCESS);
+}
+
+/*-----------------------------------------------------------------*/
+
+#define lrw1Q (cv_mem->cv_lrw1Q)
+#define liw1Q (cv_mem->cv_liw1Q)
+
+/*-----------------------------------------------------------------*/
+
+/*
+ * CVodeQuadReInit
+ *
+ * CVodeQuadReInit re-initializes CVODES's quadrature related memory 
+ * for a problem, assuming it has already been allocated in prior 
+ * calls to CVodeMalloc and CVodeQuadMalloc. 
+ * All problem specification inputs are checked for errors.
+ * If any error occurs during initialization, it is reported to the
+ * file whose file pointer is errfp.
+ * The return value is CV_SUCCESS = 0 if no errors occurred, or
+ * a negative value otherwise.
+ */
+
+int CVodeQuadReInit(void *cvode_mem, CVQuadRhsFn fQ, N_Vector yQ0)
+{
+  CVodeMem cv_mem;
+
+  /* Check cvode_mem */
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeQuadReInit", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  /* Ckeck if quadrature was initialized? */
+  if (cv_mem->cv_quadMallocDone == FALSE) {
+    CVProcessError(cv_mem, CV_NO_QUAD, "CVODES", "CVodeQuadReInit", MSGCV_NO_QUAD);
+    return(CV_NO_QUAD);
+  }
+
+  /* Initialize znQ[0] in the history array */
+  N_VScale(ONE, yQ0, cv_mem->cv_znQ[0]);
+
+  /* Copy the input parameters into CVODES state */
+  cv_mem->cv_fQ = fQ;
+
+  /* Initialize counters */
+  cv_mem->cv_nfQe  = 0;
+  cv_mem->cv_netfQ = 0;
+
+  /* Quadrature integration turned ON */
+  cv_mem->cv_quadr = TRUE;
+
+  /* Quadrature re-initialization was successfull */
+  return(CV_SUCCESS);
+}
+
+/*-----------------------------------------------------------------*/
+
+#define ifS          (cv_mem->cv_ifS)
+#define fSDQ         (cv_mem->cv_fSDQ)
+#define stgr1alloc   (cv_mem->cv_stgr1alloc)
+#define nniS1        (cv_mem->cv_nniS1)
+#define ncfnS1       (cv_mem->cv_ncfnS1)
+#define ncfS1        (cv_mem->cv_ncfS1)
+
+/*-----------------------------------------------------------------*/
+
+/*
+ * CVodeSenMalloc
+ *
+ * CVodeSensMalloc allocates and initializes sensitivity related 
+ * memory for a problem. All problem specification inputs are 
+ * checked for errors. If any error occurs during initialization, 
+ * it is reported to the file whose file pointer is errfp. 
+ * The return value is CV_SUCCESS = 0 if no errors occurred, or
+ * a negative value otherwise.
+ */
+
+int CVodeSensMalloc(void *cvode_mem, int Ns, int ism, N_Vector *yS0)
+{
+  CVodeMem    cv_mem;
+  booleantype allocOK;
+  int is;
+  
+  /* Check cvode_mem */
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSensMalloc", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  /* Check if Ns is legal */
+  if (Ns<=0) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSensMalloc", MSGCV_BAD_NS);
+    return(CV_ILL_INPUT);
+  }
+  cv_mem->cv_Ns = Ns;
+
+  /* Check if ism is legal */
+  if ((ism!=CV_SIMULTANEOUS) && (ism!=CV_STAGGERED) && (ism!=CV_STAGGERED1)) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSensMalloc", MSGCV_BAD_ISM);
+    return(CV_ILL_INPUT);
+  }
+  cv_mem->cv_ism = ism;
+   
+  /* Check if yS0 is non-null */
+  if (yS0 == NULL) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSensMalloc", MSGCV_NULL_YS0);
+    return(CV_ILL_INPUT);
+  }
+
+  /* Allocate ncfS1, ncfnS1, and nniS1 if needed */
+  if (ism == CV_STAGGERED1) {
+    stgr1alloc = TRUE;
+    ncfS1 = NULL;
+    ncfS1 = (int*)malloc(Ns*sizeof(int));
+    ncfnS1 = NULL;
+    ncfnS1 = (long int*)malloc(Ns*sizeof(long int));
+    nniS1 = NULL;
+    nniS1 = (long int*)malloc(Ns*sizeof(long int));
+    if ( (ncfS1 == NULL) || (ncfnS1 == NULL) || (nniS1 == NULL) ) {
+      CVProcessError(cv_mem, CV_MEM_FAIL, "CVODES", "CVodeSensMalloc", MSGCV_MEM_FAIL);
+      return(CV_MEM_FAIL);
+    }
+  } else {
+    stgr1alloc = FALSE;
+  }
+
+  /* Allocate the vectors (using yS0[0] as a template) */
+  allocOK = CVSensAllocVectors(cv_mem, yS0[0]);
+  if (!allocOK) {
+    if (stgr1alloc) {
+      free(ncfS1); ncfS1 = NULL;
+      free(ncfnS1); ncfnS1 = NULL;
+      free(nniS1); nniS1 = NULL;
+    }
+    CVProcessError(cv_mem, CV_MEM_FAIL, "CVODES", "CVodeSensMalloc", MSGCV_MEM_FAIL);
+    return(CV_MEM_FAIL);
+  }
+  
+  /*---------------------------------------------- 
+    All error checking is complete at this point 
+    -----------------------------------------------*/
+
+  /* Initialize znS[0] in the history array */
+  for (is=0; is<Ns; is++) 
+    N_VScale(ONE, yS0[is], cv_mem->cv_znS[0][is]);
+
+  /* Initialize all sensitivity related counters */
+  cv_mem->cv_nfSe     = 0;
+  cv_mem->cv_nfeS     = 0;
+  cv_mem->cv_ncfnS    = 0;
+  cv_mem->cv_netfS    = 0;
+  cv_mem->cv_nniS     = 0;
+  cv_mem->cv_nsetupsS = 0;
+  if (ism==CV_STAGGERED1)
+    for (is=0; is<Ns; is++) {
+      ncfnS1[is] = 0;
+      nniS1[is] = 0;
+    }
+
+  /* Set default values for plist and pbar */
+  for (is=0; is<Ns; is++) {
+    cv_mem->cv_plist[is] = is;
+    cv_mem->cv_pbar[is] = ONE;
+  }
+
+  /* Sensitivities will be computed */
+  cv_mem->cv_sensi = TRUE;
+  cv_mem->cv_sensMallocDone = TRUE;
+
+  /* Sensitivity initialization was successfull */
+  return(CV_SUCCESS);
+}
+
+/*-----------------------------------------------------------------*/
+
+#define Ns (cv_mem->cv_Ns)
+
+/*-----------------------------------------------------------------*/
+
+/*
+ * CVodeSensReInit
+ *
+ * CVodeSensReInit re-initializes CVODES's sensitivity related memory 
+ * for a problem, assuming it has already been allocated in prior 
+ * calls to CVodeMalloc and CVodeSensMalloc. 
+ * All problem specification inputs are checked for errors.
+ * The number of sensitivities Ns is assumed to be unchanged since
+ * the previous call to CVodeSensMalloc.
+ * If any error occurs during initialization, it is reported to the
+ * file whose file pointer is errfp.
+ * The return value is CV_SUCCESS = 0 if no errors occurred, or
+ * a negative value otherwise.
+ */ 
+
+int CVodeSensReInit(void *cvode_mem, int ism, N_Vector *yS0)
+{
+  CVodeMem    cv_mem;
+  int is;  
+
+  /* Check cvode_mem */
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSensReInit", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  /* Was sensitivity initialized? */
+  if (cv_mem->cv_sensMallocDone == FALSE) {
+    CVProcessError(cv_mem, CV_NO_SENS, "CVODES", "CVodeSensReInit", MSGCV_NO_SENSI);
+    return(CV_NO_SENS);
+  } 
+
+  /* Check if ism is legal */
+  if ((ism!=CV_SIMULTANEOUS) && (ism!=CV_STAGGERED) && (ism!=CV_STAGGERED1)) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSensReInit", MSGCV_BAD_ISM);
+    return(CV_ILL_INPUT);
+  }
+  cv_mem->cv_ism = ism;
+  
+  /* Check if yS0 is non-null */
+  if (yS0 == NULL) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSensReInit", MSGCV_NULL_YS0);
+    return(CV_ILL_INPUT);
+  }  
+  
+  /* Allocate ncfS1, ncfnS1, and nniS1 if needed */
+  if ( (ism==CV_STAGGERED1) && (stgr1alloc==FALSE) ) {
+    stgr1alloc = TRUE;
+    ncfS1 = NULL;
+    ncfS1 = (int*)malloc(Ns*sizeof(int));
+    ncfnS1 = NULL;
+    ncfnS1 = (long int*)malloc(Ns*sizeof(long int));
+    nniS1 = NULL;
+    nniS1 = (long int*)malloc(Ns*sizeof(long int));
+    if ( (ncfS1==NULL) || (ncfnS1==NULL) || (nniS1==NULL) ) {
+      CVProcessError(cv_mem, CV_MEM_FAIL, "CVODES", "CVodeSensReInit", MSGCV_MEM_FAIL);
+      return(CV_MEM_FAIL);
+    }
+  }
+
+  /*---------------------------------------------- 
+    All error checking is complete at this point 
+    -----------------------------------------------*/
+
+  /* Initialize znS[0] in the history array */
+  for (is=0; is<Ns; is++) 
+    N_VScale(ONE, yS0[is], cv_mem->cv_znS[0][is]);
+
+  /* Initialize all sensitivity related counters */
+  cv_mem->cv_nfSe     = 0;
+  cv_mem->cv_nfeS     = 0;
+  cv_mem->cv_ncfnS    = 0;
+  cv_mem->cv_netfS    = 0;
+  cv_mem->cv_nniS     = 0;
+  cv_mem->cv_nsetupsS = 0;
+  if (ism==CV_STAGGERED1)
+    for (is=0; is<Ns; is++) {
+      ncfnS1[is] = 0;
+      nniS1[is] = 0;
+    }
+
+  /* Problem has been successfully re-initialized */
+  cv_mem->cv_sensi = TRUE;
+  return(CV_SUCCESS);
+}
+
+/*
+ * CVodeSensToggleOff
+ *
+ * CVodeSensToggleOff deactivates sensitivity calculations.
+ * It does NOT deallocate sensitivity-related memory.
+ */
+
+int CVodeSensToggleOff(void *cvode_mem)
+{
+  CVodeMem cv_mem;
+
+  /* Check cvode_mem */
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSensToggleOff", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  /* Disable sensitivities */
+  cv_mem->cv_sensi = FALSE;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * -----------------------------------------------------------------
+ * Readibility Constants
+ * -----------------------------------------------------------------
+ */
+
+#define f              (cv_mem->cv_f)      
+#define f_data         (cv_mem->cv_f_data) 
+#define efun           (cv_mem->cv_efun)
+#define e_data         (cv_mem->cv_e_data) 
+#define qmax           (cv_mem->cv_qmax)
+#define mxstep         (cv_mem->cv_mxstep)
+#define mxhnil         (cv_mem->cv_mxhnil)
+#define sldeton        (cv_mem->cv_sldeton)
+#define hin            (cv_mem->cv_hin)
+#define hmin           (cv_mem->cv_hmin)
+#define hmax_inv       (cv_mem->cv_hmax_inv)
+#define istop          (cv_mem->cv_istop)
+#define tstop          (cv_mem->cv_tstop)
+#define tstopset       (cv_mem->cv_tstopset)
+#define maxnef         (cv_mem->cv_maxnef)
+#define maxncf         (cv_mem->cv_maxncf)
+#define maxcor         (cv_mem->cv_maxcor)
+#define nlscoef        (cv_mem->cv_nlscoef)
+#define itol           (cv_mem->cv_itol)         
+#define reltol         (cv_mem->cv_reltol)       
+#define Sabstol        (cv_mem->cv_Sabstol) 
+#define Vabstol        (cv_mem->cv_Vabstol) 
+
+#define fQ             (cv_mem->cv_fQ)
+#define fQ_data        (cv_mem->cv_fQ_data)
+#define errconQ        (cv_mem->cv_errconQ)
+#define itolQ          (cv_mem->cv_itolQ)
+#define reltolQ        (cv_mem->cv_reltolQ)
+#define SabstolQ       (cv_mem->cv_SabstolQ)
+#define VabstolQ       (cv_mem->cv_VabstolQ)
+
+#define fS             (cv_mem->cv_fS)
+#define fS1            (cv_mem->cv_fS1)
+#define fS_data        (cv_mem->cv_fS_data)
+#define DQtype         (cv_mem->cv_DQtype)
+#define DQrhomax       (cv_mem->cv_DQrhomax)
+#define pbar           (cv_mem->cv_pbar)
+#define errconS        (cv_mem->cv_errconS)
+#define maxcorS        (cv_mem->cv_maxcorS)
+#define itolS          (cv_mem->cv_itolS)
+#define reltolS        (cv_mem->cv_reltolS)
+#define SabstolS       (cv_mem->cv_SabstolS)
+#define VabstolS       (cv_mem->cv_VabstolS)
+#define ism            (cv_mem->cv_ism)
+#define p              (cv_mem->cv_p)
+#define plist          (cv_mem->cv_plist)
+
+#define uround         (cv_mem->cv_uround)  
+#define zn             (cv_mem->cv_zn) 
+#define ewt            (cv_mem->cv_ewt)  
+#define y              (cv_mem->cv_y)
+#define acor           (cv_mem->cv_acor)
+#define tempv          (cv_mem->cv_tempv)
+#define ftemp          (cv_mem->cv_ftemp) 
+#define q              (cv_mem->cv_q)
+#define qprime         (cv_mem->cv_qprime)
+#define next_q         (cv_mem->cv_next_q)
+#define qwait          (cv_mem->cv_qwait)
+#define L              (cv_mem->cv_L)
+#define h              (cv_mem->cv_h)
+#define hprime         (cv_mem->cv_hprime)
+#define next_h         (cv_mem->cv_next_h)
+#define eta            (cv_mem->cv_eta) 
+#define etaqm1         (cv_mem->cv_etaqm1) 
+#define etaq           (cv_mem->cv_etaq) 
+#define etaqp1         (cv_mem->cv_etaqp1) 
+#define nscon          (cv_mem->cv_nscon)
+#define hscale         (cv_mem->cv_hscale)
+#define tn             (cv_mem->cv_tn)
+#define tau            (cv_mem->cv_tau)
+#define tq             (cv_mem->cv_tq)
+#define l              (cv_mem->cv_l)
+#define rl1            (cv_mem->cv_rl1)
+#define gamma          (cv_mem->cv_gamma) 
+#define gammap         (cv_mem->cv_gammap) 
+#define gamrat         (cv_mem->cv_gamrat)
+#define crate          (cv_mem->cv_crate)
+#define acnrm          (cv_mem->cv_acnrm)
+#define mnewt          (cv_mem->cv_mnewt)
+#define etamax         (cv_mem->cv_etamax)
+#define nst            (cv_mem->cv_nst)
+#define nfe            (cv_mem->cv_nfe)
+#define ncfn           (cv_mem->cv_ncfn)
+#define netf           (cv_mem->cv_netf)
+#define nni            (cv_mem->cv_nni)
+#define nsetups        (cv_mem->cv_nsetups)
+#define nhnil          (cv_mem->cv_nhnil)
+#define linit          (cv_mem->cv_linit)
+#define lsetup         (cv_mem->cv_lsetup)
+#define lsolve         (cv_mem->cv_lsolve) 
+#define lfree          (cv_mem->cv_lfree) 
+#define lmem           (cv_mem->cv_lmem) 
+#define qu             (cv_mem->cv_qu)          
+#define nstlp          (cv_mem->cv_nstlp)  
+#define h0u            (cv_mem->cv_h0u)
+#define hu             (cv_mem->cv_hu)         
+#define saved_tq5      (cv_mem->cv_saved_tq5)  
+#define indx_acor      (cv_mem->cv_indx_acor)
+#define jcur           (cv_mem->cv_jcur)         
+#define tolsf          (cv_mem->cv_tolsf)      
+#define setupNonNull   (cv_mem->cv_setupNonNull) 
+#define forceSetup     (cv_mem->cv_forceSetup)
+#define nor            (cv_mem->cv_nor)
+#define ssdat          (cv_mem->cv_ssdat)
+
+#define nrtfn          (cv_mem->cv_nrtfn)
+#define tlo            (cv_mem->cv_tlo)
+#define thi            (cv_mem->cv_thi)
+#define tretlast       (cv_mem->cv_tretlast)
+#define toutc          (cv_mem->cv_toutc)
+#define trout          (cv_mem->cv_trout)
+#define ttol           (cv_mem->cv_ttol)
+#define taskc          (cv_mem->cv_taskc)
+#define irfnd          (cv_mem->cv_irfnd)
+#define nge            (cv_mem->cv_nge)
+
+#define sensi          (cv_mem->cv_sensi)
+#define znS            (cv_mem->cv_znS)
+#define ewtS           (cv_mem->cv_ewtS)
+#define acorS          (cv_mem->cv_acorS)
+#define yS             (cv_mem->cv_yS)
+#define tempvS         (cv_mem->cv_tempvS)
+#define ftempS         (cv_mem->cv_ftempS)
+#define crateS         (cv_mem->cv_crateS)
+#define acnrmS         (cv_mem->cv_acnrmS)
+#define nfSe           (cv_mem->cv_nfSe)
+#define nfeS           (cv_mem->cv_nfeS)
+#define nniS           (cv_mem->cv_nniS)
+#define ncfnS          (cv_mem->cv_ncfnS)
+#define netfS          (cv_mem->cv_netfS)
+#define nsetupsS       (cv_mem->cv_nsetupsS)
+#define stgr1alloc     (cv_mem->cv_stgr1alloc)
+#define sensMallocDone (cv_mem->cv_sensMallocDone)
+
+#define quadr          (cv_mem->cv_quadr)
+#define znQ            (cv_mem->cv_znQ)
+#define ewtQ           (cv_mem->cv_ewtQ)
+#define acorQ          (cv_mem->cv_acorQ)
+#define yQ             (cv_mem->cv_yQ)
+#define tempvQ         (cv_mem->cv_tempvQ)
+#define acnrmQ         (cv_mem->cv_acnrmQ)
+#define nfQe           (cv_mem->cv_nfQe)
+#define netfQ          (cv_mem->cv_netfQ)
+#define quadMallocDone (cv_mem->cv_quadMallocDone)
+
+/* 
+ * -----------------------------------------------------------------
+ * Main solver function
+ * -----------------------------------------------------------------
+ */
+
+/*
+ * CVode
+ *
+ * This routine is the main driver of the CVODES package. 
+ *
+ * It integrates over a time interval defined by the user, by calling
+ * CVStep to do internal time steps.
+ *
+ * The first time that CVode is called for a successfully initialized
+ * problem, it computes a tentative initial step size h.
+ *
+ * CVode supports four modes, specified by itask: CV_NORMAL, CV_ONE_STEP,
+ * CV_NORMAL_TSTOP, and CV_ONE_STEP_TSTOP.
+ * In the CV_NORMAL mode, the solver steps until it reaches or passes tout
+ * and then interpolates to obtain y(tout).
+ * In the CV_ONE_STEP mode, it takes one internal step and returns.
+ * CV_NORMAL_TSTOP and CV_ONE_STEP_TSTOP are similar to CV_NORMAL and CV_ONE_STEP,
+ * respectively, but the integration never proceeds past tstop (which
+ * must have been defined through a call to CVodeSetStopTime).
+ */
+
+int CVode(void *cvode_mem, realtype tout, N_Vector yout, 
+          realtype *tret, int itask)
+{
+  CVodeMem cv_mem;
+  long int nstloc; 
+  int retval, hflag, kflag, istate, is, ier, task, irfndp;
+  realtype troundoff, rh, nrm;
+
+  /*
+   * -------------------------------------
+   * 1. Check and process inputs
+   * -------------------------------------
+   */
+
+  /* Check if cvode_mem exists */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVode", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  /* Check if cvode_mem was allocated */
+  if (cv_mem->cv_MallocDone == FALSE) {
+    CVProcessError(cv_mem, CV_NO_MALLOC, "CVODES", "CVode", MSGCV_NO_MALLOC);
+    return(CV_NO_MALLOC);
+  }
+  
+  /* Check for yout != NULL */
+  if ((y = yout) == NULL) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVode", MSGCV_YOUT_NULL);
+    return(CV_ILL_INPUT);
+  }
+  
+  /* Check for tret != NULL */
+  if (tret == NULL) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVode", MSGCV_TRET_NULL);
+    return(CV_ILL_INPUT);
+  }
+
+  /* Check for valid itask */
+  if ((itask != CV_NORMAL)       && 
+      (itask != CV_ONE_STEP)     &&
+      (itask != CV_NORMAL_TSTOP) &&
+      (itask != CV_ONE_STEP_TSTOP) ) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVode", MSGCV_BAD_ITASK);
+    return(CV_ILL_INPUT);
+  }
+
+  /* Split itask into task and istop */
+  if ((itask == CV_NORMAL_TSTOP) || (itask == CV_ONE_STEP_TSTOP)) {
+    if ( tstopset == FALSE ) {
+      CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVode", MSGCV_NO_TSTOP);
+      return(CV_ILL_INPUT);
+    }
+    istop = TRUE;
+  } else {
+    istop = FALSE;
+  }
+  if ((itask == CV_NORMAL) || (itask == CV_NORMAL_TSTOP)) {
+    task = CV_NORMAL; toutc = tout;
+  } else {
+    task = CV_ONE_STEP;
+  }
+  taskc = task;
+
+
+  /* Sensitivity-specific tests */
+
+  if (sensi && fSDQ) {
+
+    /* If using internal DQ function for sensitivity RHS */
+
+    /* Set internal DQ functions */
+    fS  = CVSensRhsDQ;
+    fS1 = CVSensRhs1DQ;
+
+    /* Make sure we have the right 'user data' */
+    fS_data = cvode_mem;
+    
+    /* Test if we have the problem parameters */
+    if(p == NULL) {
+      CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVode", MSGCV_NULL_P);
+      return(CV_ILL_INPUT);
+    }
+
+    /* Set ifS to CV_ONESENS so that any method can be used */
+    ifS = CV_ONESENS;
+    
+  }
+
+  /*
+   * ----------------------------------------
+   * 2. Initializations performed only at
+   *    the first step (nst=0):
+   *    - initial setup
+   *    - initialize Nordsieck history array
+   *    - compute initial step size
+   *    - check for approach to tstop
+   *    - check for approach to a root
+   * ----------------------------------------
+   */
+
+  if (nst == 0) {
+
+    /* Check inputs for corectness */
+
+    ier = CVInitialSetup(cv_mem);
+    if (ier!= CV_SUCCESS) return(ier);
+
+    /* 
+       Call f at (t0,y0), set zn[1] = y'(t0). 
+       If computing any quadratures, call fQ at (t0,y0), set znQ[1] = yQ'(t0)
+       If computing sensitivities, call fS at (t0,y0,yS0), set znS[1][is] = yS'(t0), is=1,...,Ns.
+    */
+
+    retval = f(tn, zn[0], zn[1], f_data); 
+    nfe++;
+    if (retval < 0) {
+      CVProcessError(cv_mem, CV_RHSFUNC_FAIL, "CVODES", "CVode", MSGCV_RHSFUNC_FAILED, tn);
+      return(CV_RHSFUNC_FAIL);
+    }
+    if (retval > 0) {
+      CVProcessError(cv_mem, CV_FIRST_RHSFUNC_ERR, "CVODES", "CVode", MSGCV_RHSFUNC_FIRST);
+      return(CV_FIRST_RHSFUNC_ERR);
+    }
+
+    if (quadr) {
+      retval = fQ(tn, zn[0], znQ[1], fQ_data);
+      nfQe++;
+      if (retval < 0) {
+        CVProcessError(cv_mem, CV_QRHSFUNC_FAIL, "CVODES", "CVode", MSGCV_QRHSFUNC_FAILED, tn);
+        return(CV_QRHSFUNC_FAIL);
+      }
+      if (retval > 0) {
+        CVProcessError(cv_mem, CV_FIRST_QRHSFUNC_ERR, "CVODES", "CVode", MSGCV_QRHSFUNC_FIRST);
+        return(CV_FIRST_QRHSFUNC_ERR);
+      }
+    }
+
+    if (sensi) {
+      retval = CVSensRhs(cv_mem, tn, zn[0], zn[1], znS[0], znS[1], tempv, ftemp);
+      if (retval < 0) {
+        CVProcessError(cv_mem, CV_SRHSFUNC_FAIL, "CVODES", "CVSensRhs", MSGCV_SRHSFUNC_FAILED, tn);
+        return(CV_SRHSFUNC_FAIL);
+      } 
+      if (retval > 0) {
+        CVProcessError(cv_mem, CV_FIRST_SRHSFUNC_ERR, "CVODES", "CVSensRhs", MSGCV_SRHSFUNC_FIRST);
+        return(CV_FIRST_SRHSFUNC_ERR);
+      }
+    }
+
+    /* Set initial h (from H0 or CVHin). */
+    
+    h = hin;
+    if ( (h != ZERO) && ((tout-tn)*h < ZERO) ) {
+      CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVode", MSGCV_BAD_H0);
+      return(CV_ILL_INPUT);
+    }
+    if (h == ZERO) {
+      hflag = CVHin(cv_mem, tout);
+      if (hflag != CV_SUCCESS) {
+        istate = CVHandleFailure(cv_mem, hflag);
+        return(istate);
+      }
+    }
+    rh = ABS(h)*hmax_inv;
+    if (rh > ONE) h /= rh;
+    if (ABS(h) < hmin) h *= hmin/ABS(h);
+
+    /* Check for approach to tstop */
+
+    if (istop) {
+      if ( (tstop - tn)*h < ZERO ) {
+        CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVode", MSGCV_BAD_TSTOP, tn);
+        return(CV_ILL_INPUT);
+      }
+      if ( (tn + h - tstop)*h > ZERO ) 
+        h = (tstop - tn)*(ONE-FOUR*uround);
+    }
+
+    /* 
+       Scale zn[1] by h.
+       If computing any quadratures, scale znQ[1] by h.
+       If computing sensitivities,  scale znS[1][is] by h. 
+    */
+
+    hscale = h;
+    h0u    = h;
+    hprime = h;
+
+    N_VScale(h, zn[1], zn[1]);
+    
+    if (sensi)
+      for (is=0; is<Ns; is++) 
+        N_VScale(h, znS[1][is], znS[1][is]);
+    
+    if (quadr)
+      N_VScale(h, znQ[1], znQ[1]);
+
+    /* Check for zeros of root function g at and near t0. */
+
+    if (nrtfn > 0) {
+
+      retval = CVRcheck1(cv_mem);
+
+      if (retval == INITROOT) {
+        CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVRcheck1", MSGCV_BAD_INIT_ROOT);
+        return(CV_ILL_INPUT);
+      } else if (retval == CV_RTFUNC_FAIL) {
+        CVProcessError(cv_mem, CV_RTFUNC_FAIL, "CVODES", "CVRcheck1", MSGCV_RTFUNC_FAILED, tn);
+        return(CV_RTFUNC_FAIL);
+      }
+
+    }
+
+  } /* end first call block */
+
+  /*
+   * ------------------------------------------------------
+   * 3. At following steps, perform stop tests:
+   *    - check for root in last step
+   *    - check if we passed tstop
+   *    - check if we passed tout (NORMAL mode)
+   *    - check if current tn was returned (ONE_STEP mode)
+   *    - check if we are close to tstop
+   *      (adjust step size if needed)
+   * -------------------------------------------------------
+   */
+
+  if (nst > 0) {
+
+    /* Estimate an infinitesimal time interval to be used as
+       a roundoff for time quantities (based on current time 
+       and step size) */
+    troundoff = FUZZ_FACTOR*uround*(ABS(tn) + ABS(h));
+
+    /* First check for a root in the last step taken, other than the
+       last root found, if any.  If task = CV_ONE_STEP and y(tn) was not
+       returned because of an intervening root, return y(tn) now.     */
+    if (nrtfn > 0) {
+      
+      irfndp = irfnd;
+      
+      retval = CVRcheck2(cv_mem);
+
+      if (retval == CLOSERT) {
+        CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVRcheck2", MSGCV_CLOSE_ROOTS, tlo);
+        return(CV_ILL_INPUT);
+      } else if (retval == CV_RTFUNC_FAIL) {
+        CVProcessError(cv_mem, CV_RTFUNC_FAIL, "CVODES", "CVRcheck2", MSGCV_RTFUNC_FAILED, tlo);
+        return(CV_RTFUNC_FAIL);
+      } else if (retval == RTFOUND) {
+        tretlast = *tret = tlo;
+        return(CV_ROOT_RETURN);
+      }
+      
+      /* If tn is distinct from tretlast (within roundoff),
+         check remaining interval for roots */
+      if ( ABS(tn - tretlast) > troundoff ) {
+
+        retval = CVRcheck3(cv_mem);
+
+        if (retval == CV_SUCCESS) {     /* no root found */
+          irfnd = 0;
+          if ((irfndp == 1) && (task == CV_ONE_STEP)) {
+            tretlast = *tret = tn;
+            N_VScale(ONE, zn[0], yout);
+            return(CV_SUCCESS);
+          }
+        } else if (retval == RTFOUND) {  /* a new root was found */
+          irfnd = 1;
+          tretlast = *tret = tlo;
+          return(CV_ROOT_RETURN);
+        } else if (retval == CV_RTFUNC_FAIL) {  /* g failed */
+          CVProcessError(cv_mem, CV_RTFUNC_FAIL, "CVODES", "CVRcheck3", MSGCV_RTFUNC_FAILED, tlo);
+          return(CV_RTFUNC_FAIL);
+        }
+
+      }
+      
+    } /* end of root stop check */
+    
+    /* Test for tn past tstop */
+    if ( istop && ((tstop - tn)*h < ZERO) ) {
+      CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVode", MSGCV_BAD_TSTOP, tn);
+      return(CV_ILL_INPUT);
+    }
+    
+    /* In CV_NORMAL mode, test if tout was reached */
+    if ( (task == CV_NORMAL) && ((tn-tout)*h >= ZERO) ) {
+      tretlast = *tret = tout;
+      ier =  CVodeGetDky(cv_mem, tout, 0, yout);
+      if (ier != CV_SUCCESS) {
+        CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVode", MSGCV_BAD_TOUT, tout);
+        return(CV_ILL_INPUT);
+      }
+      return(CV_SUCCESS);
+    }
+    
+    /* In CV_ONE_STEP mode, test if tn was returned */
+    if ( task == CV_ONE_STEP && ABS(tn - tretlast) > troundoff ) {
+      tretlast = *tret = tn;
+      N_VScale(ONE, zn[0], yout);
+      return(CV_SUCCESS);
+    }
+    
+    /* Test for tn at tstop or near tstop */
+    if ( istop ) {
+      
+      if ( ABS(tn - tstop) <= troundoff ) {
+        ier =  CVodeGetDky(cv_mem, tstop, 0, yout);
+        if (ier != CV_SUCCESS) {
+          CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVode", MSGCV_BAD_TSTOP, tn);
+          return(CV_ILL_INPUT);
+        }
+        tretlast = *tret = tstop;
+        return(CV_TSTOP_RETURN);
+      }
+      
+      /* If next step would overtake tstop, adjust stepsize */
+      if ( (tn + hprime - tstop)*h > ZERO ) {
+        hprime = (tstop - tn)*(ONE-FOUR*uround);
+        eta = hprime/h;
+      }
+      
+    } /* end of istop tests block */
+    
+  } /* end stopping tests block at nst>0 */  
+  
+  /*
+   * --------------------------------------------------
+   * 4. Looping point for internal steps
+   *
+   *    4.1. check for errors (too many steps, too much
+   *         accuracy requested, step size too small)
+   *    4.2. take a new step (call CVStep)
+   *    4.3. stop on error 
+   *    4.4. perform stop tests:
+   *         - check for root in last step
+   *         - check if tout was passed
+   *         - check if close to tstop
+   *         - check if in ONE_STEP mode (must return)
+   * --------------------------------------------------
+   */  
+  
+  nstloc = 0;
+  loop {
+   
+    next_h = h;
+    next_q = q;
+    
+    /* Reset and check ewt, ewtQ, ewtS */   
+    if (nst > 0) {
+
+      ier = efun(zn[0], ewt, e_data);
+      if(ier != 0) {
+        if (itol == CV_WF) CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVode", MSGCV_EWT_NOW_FAIL, tn);
+        else               CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVode", MSGCV_EWT_NOW_BAD, tn);
+        istate = CV_ILL_INPUT;
+        tretlast = *tret = tn;
+        N_VScale(ONE, zn[0], yout);
+        break;
+      }
+
+      if (quadr && errconQ) {
+        ier = CVQuadEwtSet(cv_mem, znQ[0], ewtQ);
+        if(ier != 0) {
+          CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVode", MSGCV_EWTQ_NOW_BAD, tn);
+          istate = CV_ILL_INPUT;
+          tretlast = *tret = tn;
+          N_VScale(ONE, zn[0], yout);
+          break;
+        }
+      }
+
+      if (sensi) {
+        ier = CVSensEwtSet(cv_mem, znS[0], ewtS);
+        if (ier != 0) {
+          CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVode", MSGCV_EWTS_NOW_BAD, tn);
+          istate = CV_ILL_INPUT;
+          tretlast = *tret = tn;
+          N_VScale(ONE, zn[0], yout);
+          break;
+        }
+      }
+
+    }
+
+    /* Check for too many steps */
+    if (nstloc >= mxstep) {
+      CVProcessError(cv_mem, CV_TOO_MUCH_WORK, "CVODES", "CVode", MSGCV_MAX_STEPS, tn);
+      istate = CV_TOO_MUCH_WORK;
+      tretlast = *tret = tn;
+      N_VScale(ONE, zn[0], yout);
+      break;
+    }
+
+    /* Check for too much accuracy requested */
+    nrm = N_VWrmsNorm(zn[0], ewt);
+    if (quadr && errconQ) {
+      nrm = CVQuadUpdateNorm(cv_mem, nrm, znQ[0], ewtQ); 
+    }
+    if (sensi && errconS) {
+      nrm = CVSensUpdateNorm(cv_mem, nrm, znS[0], ewtS);
+    }
+    tolsf = uround * nrm;
+    if (tolsf > ONE) {
+      CVProcessError(cv_mem, CV_TOO_MUCH_ACC, "CVODES", "CVode", MSGCV_TOO_MUCH_ACC, tn);
+      istate = CV_TOO_MUCH_ACC;
+      tretlast = *tret = tn;
+      N_VScale(ONE, zn[0], yout);
+      tolsf *= TWO;
+      break;
+    } else {
+      tolsf = ONE;
+    }
+    
+    /* Check for h below roundoff level in tn */
+    if (tn + h == tn) {
+      nhnil++;
+      if (nhnil <= mxhnil) 
+        CVProcessError(cv_mem, CV_WARNING, "CVODES", "CVode", MSGCV_HNIL, tn, h);
+      if (nhnil == mxhnil) 
+        CVProcessError(cv_mem, CV_WARNING, "CVODES", "CVode", MSGCV_HNIL_DONE);
+    }
+
+    /* Call CVStep to take a step */
+    kflag = CVStep(cv_mem);
+
+    /* Process failed step cases, and exit loop */
+    if (kflag != CV_SUCCESS) {
+      istate = CVHandleFailure(cv_mem, kflag);
+      tretlast = *tret = tn;
+      N_VScale(ONE, zn[0], yout);
+      break;
+    }
+    
+    nstloc++;
+
+    /* Check for root in last step taken. */    
+    if (nrtfn > 0) {
+      
+      retval = CVRcheck3(cv_mem);
+      
+      if (retval == RTFOUND) {  /* A new root was found */
+        irfnd = 1;
+        istate = CV_ROOT_RETURN;
+        tretlast = *tret = tlo;
+        break;
+      } else if (retval == CV_RTFUNC_FAIL) { /* g failed */
+        CVProcessError(cv_mem, CV_RTFUNC_FAIL, "CVODES", "CVRcheck3", MSGCV_RTFUNC_FAILED, tlo);
+        istate = CV_RTFUNC_FAIL;
+        break;
+      }
+
+    }
+
+    /* In NORMAL mode, check if tout reached */
+    if ( (task == CV_NORMAL) &&  (tn-tout)*h >= ZERO ) {
+      istate = CV_SUCCESS;
+      tretlast = *tret = tout;
+      (void) CVodeGetDky(cv_mem, tout, 0, yout);
+      next_q = qprime;
+      next_h = hprime;
+      break;
+    }
+
+    /* Check if tn is at tstop or near tstop */
+    if ( istop ) {
+
+      troundoff = FUZZ_FACTOR*uround*(ABS(tn) + ABS(h));
+      if ( ABS(tn - tstop) <= troundoff) {
+        (void) CVodeGetDky(cv_mem, tstop, 0, yout);
+        tretlast = *tret = tstop;
+        istate = CV_TSTOP_RETURN;
+        break;
+      }
+
+      if ( (tn + hprime - tstop)*h > ZERO ) {
+        hprime = (tstop - tn)*(ONE-FOUR*uround);
+        eta = hprime/h;
+      }
+
+    }
+
+    /* In ONE_STEP mode, copy y and exit loop */
+    if (task == CV_ONE_STEP) {
+      istate = CV_SUCCESS;
+      tretlast = *tret = tn;
+      N_VScale(ONE, zn[0], yout);
+      next_q = qprime;
+      next_h = hprime;
+      break;
+    }
+
+  } /* end looping for internal steps */
+  
+  /* Load optional output */
+  if (sensi && (ism==CV_STAGGERED1)) { 
+    nniS  = 0;
+    ncfnS = 0;
+    for (is=0; is<Ns; is++) {
+      nniS  += nniS1[is];
+      ncfnS += ncfnS1[is];
+    }
+  }
+  
+  return(istate);
+
+}
+
+/* 
+ * -----------------------------------------------------------------
+ * Interpolated output and extraction functions
+ * -----------------------------------------------------------------
+ */
+
+/*
+ * CVodeGetDky
+ *
+ * This routine computes the k-th derivative of the interpolating
+ * polynomial at the time t and stores the result in the vector dky.
+ * The formula is:
+ *         q 
+ *  dky = SUM c(j,k) * (t - tn)^(j-k) * h^(-j) * zn[j] , 
+ *        j=k 
+ * where c(j,k) = j*(j-1)*...*(j-k+1), q is the current order, and
+ * zn[j] is the j-th column of the Nordsieck history array.
+ *
+ * This function is called by CVode with k = 0 and t = tout, but
+ * may also be called directly by the user.
+ */
+
+int CVodeGetDky(void *cvode_mem, realtype t, int k, N_Vector dky)
+{
+  realtype s, c, r;
+  realtype tfuzz, tp, tn1;
+  int i, j;
+  CVodeMem cv_mem;
+  
+  /* Check all inputs for legality */
+ 
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetDky", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (dky == NULL) {
+    CVProcessError(cv_mem, CV_BAD_DKY, "CVODES", "CVodeGetDky", MSGCV_NULL_DKY);
+    return(CV_BAD_DKY);
+  }
+
+  if ((k < 0) || (k > q)) {
+    CVProcessError(cv_mem, CV_BAD_K, "CVODES", "CVodeGetDky", MSGCV_BAD_K);
+    return(CV_BAD_K);
+  }
+  
+  /* Allow for some slack */
+  tfuzz = FUZZ_FACTOR * uround * (ABS(tn) + ABS(hu));
+  if (hu < ZERO) tfuzz = -tfuzz;
+  tp = tn - hu - tfuzz;
+  tn1 = tn + tfuzz;
+  if ((t-tp)*(t-tn1) > ZERO) {
+    CVProcessError(cv_mem, CV_BAD_T, "CVODES", "CVodeGetDky", MSGCV_BAD_T, t, tn-hu, tn);
+    return(CV_BAD_T);
+  }
+
+  /* Sum the differentiated interpolating polynomial */
+
+  s = (t - tn) / h;
+  for (j=q; j >= k; j--) {
+    c = ONE;
+    for (i=j; i >= j-k+1; i--) c *= i;
+    if (j == q) {
+      N_VScale(c, zn[q], dky);
+    } else {
+      N_VLinearSum(c, zn[j], s, dky, dky);
+    }
+  }
+  if (k == 0) return(CV_SUCCESS);
+  r = RPowerI(h,-k);
+  N_VScale(r, dky, dky);
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeGetQuad
+ *
+ * This routine extracts quadrature solution into yQout.
+ * This is just a wrapper that calls CVodeGetQuadDky with k=0                    
+ */
+ 
+int CVodeGetQuad(void *cvode_mem, realtype t, N_Vector yQout)
+{
+  return(CVodeGetQuadDky(cvode_mem,t,0,yQout));
+}
+
+/*
+ * CVodeGetQuadDky
+ *
+ * CVodeQuadDky computes the kth derivative of the yQ function at
+ * time t, where tn-hu <= t <= tn, tn denotes the current         
+ * internal time reached, and hu is the last internal step size   
+ * successfully used by the solver. The user may request 
+ * k=0, 1, ..., qu, where qu is the current order. 
+ * The derivative vector is returned in dky. This vector 
+ * must be allocated by the caller. It is only legal to call this         
+ * function after a successful return from CVode with quadrature
+ * computation enabled.
+ */
+
+int CVodeGetQuadDky(void *cvode_mem, realtype t, int k, N_Vector dkyQ)
+{ 
+  realtype s, c, r;
+  realtype tfuzz, tp, tn1;
+  int i, j;
+  CVodeMem cv_mem;
+  
+  /* Check all inputs for legality */
+  
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetQuadDky", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;  
+
+  if(quadr != TRUE) {
+    CVProcessError(cv_mem, CV_NO_QUAD, "CVODES", "CVodeGetQuadDky", MSGCV_NO_QUAD);
+    return(CV_NO_QUAD);
+  }
+
+  if (dkyQ == NULL) {
+    CVProcessError(cv_mem, CV_BAD_DKY, "CVODES", "CVodeGetQuadDky", MSGCV_NULL_DKY);
+    return(CV_BAD_DKY);
+  }
+  
+  if ((k < 0) || (k > q)) {
+    CVProcessError(cv_mem, CV_BAD_K, "CVODES", "CVodeGetQuadDky", MSGCV_BAD_K);
+    return(CV_BAD_K);
+  }
+  
+  /* Allow for some slack */
+  tfuzz = FUZZ_FACTOR * uround * (ABS(tn) + ABS(hu));
+  if (hu < ZERO) tfuzz = -tfuzz;
+  tp = tn - hu - tfuzz;
+  tn1 = tn + tfuzz;
+  if ((t-tp)*(t-tn1) > ZERO) {
+    CVProcessError(cv_mem, CV_BAD_T, "CVODES", "CVodeGetQuadDky", MSGCV_BAD_T);
+    return(CV_BAD_T);
+  }
+  
+  /* Sum the differentiated interpolating polynomial */
+  
+  s = (t - tn) / h;
+  for (j=q; j >= k; j--) {
+    c = ONE;
+    for (i=j; i >= j-k+1; i--) c *= i;
+    if (j == q) {
+      N_VScale(c, znQ[q], dkyQ);
+    } else {
+      N_VLinearSum(c, znQ[j], s, dkyQ, dkyQ);
+    }
+  }
+  if (k == 0) return(CV_SUCCESS);
+  r = RPowerI(h,-k);
+  N_VScale(r, dkyQ, dkyQ);
+  return(CV_SUCCESS);
+  
+}
+
+/* 
+ * CVodeGetSens
+ *
+ * This routine extracts sensitivity solution into ySout.
+ * This is just a wrapper that calls CVodeSensDky with k=0                    
+ */
+ 
+int CVodeGetSens(void *cvode_mem, realtype t, N_Vector *ySout)
+{
+  return(CVodeGetSensDky(cvode_mem,t,0,ySout));
+}
+    
+/* 
+ * CVodeGetSens1
+ *
+ * This routine extracts the is-th sensitivity solution into ySout.
+ * This is just a wrapper that calls CVodeSensDky1 with k=0                    
+ */
+ 
+int CVodeGetSens1(void *cvode_mem, realtype t, int is, N_Vector ySout)
+{
+  return(CVodeGetSensDky1(cvode_mem,t,0,is,ySout));
+}
+    
+/*
+ * CVodeGetSensDky
+ *
+ * If the user calls directly CVodeSensDky then s must be allocated
+ * prior to this call. When CVodeSensDky is called by 
+ * CVodeGetSens, only ier=CV_SUCCESS, ier=CV_NO_SENS, or 
+ * ier=CV_BAD_T are possible.
+ */
+
+int CVodeGetSensDky(void *cvode_mem, realtype t, int k, N_Vector *dkyS)
+{
+  int ier=CV_SUCCESS;
+  int is;
+  CVodeMem cv_mem;
+  
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetSensDky", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;  
+  
+  if (dkyS == NULL) {
+    CVProcessError(cv_mem, CV_BAD_DKY, "CVODES", "CVodeGetSensDky", MSGCV_NULL_DKYA);
+    return(CV_BAD_DKY);
+  }
+  
+  for (is=0; is<Ns; is++) {
+    ier = CVodeGetSensDky1(cvode_mem,t,k,is,dkyS[is]);
+    if (ier!=CV_SUCCESS) break;
+  }
+  
+  return(ier);
+}
+    
+/*
+ * CVodeGetSensDky1
+ *
+ * CVodeSensDky1 computes the kth derivative of the yS[is] function at
+ * time t, where tn-hu <= t <= tn, tn denotes the current         
+ * internal time reached, and hu is the last internal step size   
+ * successfully used by the solver. The user may request 
+ * is=0, 1, ..., Ns-1 and k=0, 1, ..., qu, where qu is the current
+ * order. The derivative vector is returned in dky. This vector 
+ * must be allocated by the caller. It is only legal to call this         
+ * function after a successful return from CVode with sensitivity 
+ * computation enabled.
+ */
+
+int CVodeGetSensDky1(void *cvode_mem, realtype t, int k, int is, N_Vector dkyS)
+{ 
+  realtype s, c, r;
+  realtype tfuzz, tp, tn1;
+  int i, j;
+  CVodeMem cv_mem;
+  
+  /* Check all inputs for legality */
+  
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetSensDky1", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;  
+  
+  if(sensi != TRUE) {
+    CVProcessError(cv_mem, CV_NO_SENS, "CVODES", "CVodeGetSensDky1", MSGCV_NO_SENSI);
+    return(CV_NO_SENS);
+  }
+
+  if (dkyS == NULL) {
+    CVProcessError(cv_mem, CV_BAD_DKY, "CVODES", "CVodeGetSensDky1", MSGCV_NULL_DKY);
+    return(CV_BAD_DKY);
+  }
+  
+  if ((k < 0) || (k > q)) {
+    CVProcessError(cv_mem, CV_BAD_K, "CVODES", "CVodeGetSensDky1", MSGCV_BAD_K);
+    return(CV_BAD_K);
+  }
+  
+  if ((is < 0) || (is > Ns-1)) {
+    CVProcessError(cv_mem, CV_BAD_IS, "CVODES", "CVodeGetSensDky1", MSGCV_BAD_IS);
+    return(CV_BAD_IS);
+  }
+  
+  /* Allow for some slack */
+  tfuzz = FUZZ_FACTOR * uround * (ABS(tn) + ABS(hu));
+  if (hu < ZERO) tfuzz = -tfuzz;
+  tp = tn - hu - tfuzz;
+  tn1 = tn + tfuzz;
+  if ((t-tp)*(t-tn1) > ZERO) {
+    CVProcessError(cv_mem, CV_BAD_T, "CVODES", "CVodeGetSensDky1", MSGCV_BAD_T);
+    return(CV_BAD_T);
+  }
+  
+  /* Sum the differentiated interpolating polynomial */
+  
+  s = (t - tn) / h;
+  for (j=q; j >= k; j--) {
+    c = ONE;
+    for (i=j; i >= j-k+1; i--) c *= i;
+    if (j == q) {
+      N_VScale(c, znS[q][is], dkyS);
+    } else {
+      N_VLinearSum(c, znS[j][is], s, dkyS, dkyS);
+    }
+  }
+  if (k == 0) return(CV_SUCCESS);
+  r = RPowerI(h,-k);
+  N_VScale(r, dkyS, dkyS);
+  return(CV_SUCCESS);
+  
+}
+
+/* 
+ * -----------------------------------------------------------------
+ * Deallocation functions
+ * -----------------------------------------------------------------
+ */
+
+/*
+ * CVodeFree
+ *
+ * This routine frees the problem memory allocated by CVodeMalloc.
+ * Such memory includes all the vectors allocated by CVAllocVectors,
+ * and the memory lmem for the linear solver (deallocated by a call
+ * to lfree), as well as (if Ns!=0) all memory allocated for 
+ * sensitivity computations by CVodeSensMalloc.
+ */
+
+void CVodeFree(void **cvode_mem)
+{
+  CVodeMem cv_mem;
+
+  if (*cvode_mem == NULL) return;
+
+  cv_mem = (CVodeMem) (*cvode_mem);
+  
+  CVFreeVectors(cv_mem);
+
+  CVodeQuadFree(cv_mem);
+
+  CVodeSensFree(cv_mem);
+
+  if (iter == CV_NEWTON && lfree != NULL) lfree(cv_mem);
+
+  if (nrtfn > 0) {
+    free(glo); glo = NULL; 
+    free(ghi);  ghi = NULL;
+    free(grout);  grout = NULL;
+    free(iroots); iroots = NULL;
+  }
+
+  free(*cvode_mem);
+  *cvode_mem = NULL;
+}
+
+/*
+ * CVodeQuadFree
+ *
+ * CVodeQuadFree frees the problem memory in cvode_mem allocated
+ * for quadrature integration. Its only argument is the pointer
+ * cvode_mem returned by CVodeCreate. 
+ */
+
+void CVodeQuadFree(void *cvode_mem)
+{
+  CVodeMem cv_mem;
+  
+  if (cvode_mem == NULL) return;
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if(quadMallocDone) {
+    CVQuadFreeVectors(cv_mem);
+    quadMallocDone = FALSE;
+    quadr = FALSE;
+  }
+}
+
+/*
+ * CVodeSensFree
+ *
+ * CVodeSensFree frees the problem memory in cvode_mem allocated
+ * for sensitivity analysis. Its only argument is the pointer
+ * cvode_mem returned by CVodeCreate. 
+ */
+
+void CVodeSensFree(void *cvode_mem)
+{
+  CVodeMem cv_mem;
+  
+  if (cvode_mem == NULL) return;
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if(sensMallocDone) {
+    if (stgr1alloc) {
+      free(ncfS1); ncfS1 = NULL;
+      free(ncfnS1); ncfnS1 = NULL;
+      free(nniS1); nniS1 = NULL;
+      stgr1alloc = FALSE;
+    }
+    CVSensFreeVectors(cv_mem);
+    sensMallocDone = FALSE;
+    sensi = FALSE;
+  }
+}
+
+/* 
+ * =================================================================
+ * PRIVATE FUNCTIONS
+ * =================================================================
+ */
+
+/*
+ * CVCheckNvector
+ * This routine checks if all required vector operations are present.
+ * If any of them is missing it returns FALSE.
+ */
+
+static booleantype CVCheckNvector(N_Vector tmpl)
+{
+  if((tmpl->ops->nvclone     == NULL) ||
+     (tmpl->ops->nvdestroy   == NULL) ||
+     (tmpl->ops->nvlinearsum == NULL) ||
+     (tmpl->ops->nvconst     == NULL) ||
+     (tmpl->ops->nvprod      == NULL) ||
+     (tmpl->ops->nvdiv       == NULL) ||
+     (tmpl->ops->nvscale     == NULL) ||
+     (tmpl->ops->nvabs       == NULL) ||
+     (tmpl->ops->nvinv       == NULL) ||
+     (tmpl->ops->nvaddconst  == NULL) ||
+     (tmpl->ops->nvmaxnorm   == NULL) ||
+     (tmpl->ops->nvwrmsnorm  == NULL) ||
+     (tmpl->ops->nvmin       == NULL))
+    return(FALSE);
+  else
+    return(TRUE);
+}
+
+/* 
+ * -----------------------------------------------------------------
+ * Memory allocation/deallocation
+ * -----------------------------------------------------------------
+ */
+
+/*
+ * CVAllocVectors
+ *
+ * This routine allocates the CVODES vectors ewt, acor, tempv, ftemp, and
+ * zn[0], ..., zn[maxord]. If itol=CV_SV, it also allocates space for Vabstol.
+ * If all memory allocations are successful, CVAllocVectors returns TRUE. 
+ * Otherwise all allocated memory is freed and CVAllocVectors returns FALSE.
+ * This routine also sets the optional outputs lrw and liw, which are
+ * (respectively) the lengths of the real and integer work spaces
+ * allocated here.
+ */
+
+static booleantype CVAllocVectors(CVodeMem cv_mem, N_Vector tmpl, int tol)
+{
+  int i, j;
+
+  /* Allocate ewt, acor, tempv, ftemp */
+  
+  ewt = NULL;
+  ewt = N_VClone(tmpl);
+  if (ewt == NULL) return(FALSE);
+
+  acor = NULL;
+  acor = N_VClone(tmpl);
+  if (acor == NULL) {
+    N_VDestroy(ewt);
+    return(FALSE);
+  }
+
+  tempv = NULL;
+  tempv = N_VClone(tmpl);
+  if (tempv == NULL) {
+    N_VDestroy(ewt);
+    N_VDestroy(acor);
+    return(FALSE);
+  }
+
+  ftemp = NULL;
+  ftemp = N_VClone(tmpl);
+  if (ftemp == NULL) {
+    N_VDestroy(tempv);
+    N_VDestroy(ewt);
+    N_VDestroy(acor);
+    return(FALSE);
+  }
+
+  /* Allocate zn[0] ... zn[qmax] */
+
+  for (j=0; j <= qmax; j++) {
+    zn[j] = NULL;
+    zn[j] = N_VClone(tmpl);
+    if (zn[j] == NULL) {
+      N_VDestroy(ewt);
+      N_VDestroy(acor);
+      N_VDestroy(tempv);
+      N_VDestroy(ftemp);
+      for (i=0; i < j; i++) N_VDestroy(zn[i]);
+      return(FALSE);
+    }
+  }
+
+  /* Update solver workspace lengths  */
+  lrw += (qmax + 5)*lrw1;
+  liw += (qmax + 5)*liw1;
+
+  if (tol == CV_SV) {
+    Vabstol = NULL;
+    Vabstol = N_VClone(tmpl);
+    if (Vabstol == NULL) {
+      N_VDestroy(ewt);
+      N_VDestroy(acor);
+      N_VDestroy(tempv);
+      N_VDestroy(ftemp);
+      for (i=0; i <= qmax; i++) N_VDestroy(zn[i]);
+      return(FALSE);
+    }
+    lrw += lrw1;
+    liw += liw1;
+    cv_mem->cv_VabstolMallocDone = TRUE;
+  }  
+
+  /* Store the value of qmax used here */
+  cv_mem->cv_qmax_alloc = qmax;
+
+  return(TRUE);
+}
+
+/*  
+ * CVFreeVectors
+ *
+ * This routine frees the CVODES vectors allocated in CVAllocVectors.
+ */
+
+static void CVFreeVectors(CVodeMem cv_mem)
+{
+  int j, maxord;
+  
+  maxord = cv_mem->cv_qmax_alloc;
+
+  N_VDestroy(ewt);
+  N_VDestroy(acor);
+  N_VDestroy(tempv);
+  N_VDestroy(ftemp);
+  for (j=0; j <= maxord; j++) 
+    N_VDestroy(zn[j]);
+
+  lrw -= (maxord + 5)*lrw1;
+  liw -= (maxord + 5)*liw1;
+
+  if (cv_mem->cv_VabstolMallocDone) {
+    N_VDestroy(Vabstol);
+    lrw -= lrw1;
+    liw -= liw1;
+  }
+}
+
+/*
+ * CVodeQuadAllocVectors
+ *
+ * NOTE: Space for ewtQ is allocated even when errconQ=FALSE, 
+ * although in this case, ewtQ is never used. The reason for this
+ * decision is to allow the user to re-initialize the quadrature
+ * computation with errconQ=TRUE, after an initialization with
+ * errconQ=FALSE, without new memory allocation within 
+ * CVodeQuadReInit.
+ */
+
+static booleantype CVQuadAllocVectors(CVodeMem cv_mem, N_Vector tmpl) 
+{
+  int i, j;
+
+  /* Allocate ewtQ */
+  ewtQ = NULL;
+  ewtQ = N_VClone(tmpl);
+  if (ewtQ == NULL) {
+    return(FALSE);
+  }
+  
+  /* Allocate acorQ */
+  acorQ = NULL;
+  acorQ = N_VClone(tmpl);
+  if (acorQ == NULL) {
+    N_VDestroy(ewtQ);
+    return(FALSE);
+  }
+
+  /* Allocate yQ */
+  yQ = NULL;
+  yQ = N_VClone(tmpl);
+  if (yQ == NULL) {
+    N_VDestroy(ewtQ);
+    N_VDestroy(acorQ);
+    return(FALSE);
+  }
+
+  /* Allocate tempvQ */
+  tempvQ = NULL;
+  tempvQ = N_VClone(tmpl);
+  if (tempvQ == NULL) {
+    N_VDestroy(ewtQ);
+    N_VDestroy(acorQ);
+    N_VDestroy(yQ);
+    return(FALSE);
+  }
+
+  /* Allocate zQn[0] ... zQn[maxord] */
+
+  for (j=0; j <= qmax; j++) {
+    znQ[j] = NULL;
+    znQ[j] = N_VClone(tmpl);
+    if (znQ[j] == NULL) {
+      N_VDestroy(ewtQ);
+      N_VDestroy(acorQ);
+      N_VDestroy(yQ);
+      N_VDestroy(tempvQ);
+      for (i=0; i < j; i++) N_VDestroy(znQ[i]);
+      return(FALSE);
+    }
+  }
+
+  /* Store the value of qmax used here */
+  cv_mem->cv_qmax_allocQ = qmax;
+
+  /* Update solver workspace lengths */
+  lrw += (qmax + 5)*lrw1Q;
+  liw += (qmax + 5)*liw1Q;
+
+  return(TRUE);
+}
+
+/*
+ * CVQuadFreeVectors
+ *
+ * This routine frees the CVODES vectors allocated in CVQuadAllocVectors.
+ */
+
+static void CVQuadFreeVectors(CVodeMem cv_mem)
+{
+  int j, maxord;
+  
+  maxord = cv_mem->cv_qmax_allocQ;
+
+  N_VDestroy(ewtQ);
+  N_VDestroy(acorQ);
+  N_VDestroy(yQ);
+  N_VDestroy(tempvQ);
+  
+  for (j=0; j<=maxord; j++) N_VDestroy(znQ[j]);
+
+  lrw -= (maxord + 5)*lrw1Q;
+  liw -= (maxord + 5)*liw1Q;
+
+  if (cv_mem->cv_VabstolQMallocDone) {
+    N_VDestroy(VabstolQ);
+    lrw -= lrw1Q;
+    liw -= liw1Q;
+  }
+
+  cv_mem->cv_VabstolQMallocDone = FALSE;
+}
+
+/*
+ * CVSensAllocVectors
+ *
+ * Create (through duplication) N_Vectors used for sensitivity analysis, 
+ * using the N_Vector 'tmpl' as a template.
+ */
+
+static booleantype CVSensAllocVectors(CVodeMem cv_mem, N_Vector tmpl) 
+{
+  int i, j;
+  
+  /* Allocate yS */
+  yS = NULL;
+  yS = N_VCloneVectorArray(Ns, tmpl);
+  if (yS == NULL) {
+    return(FALSE);
+  }
+
+  /* Allocate ewtS */
+  ewtS = NULL;
+  ewtS = N_VCloneVectorArray(Ns, tmpl);
+  if (ewtS == NULL) {
+    N_VDestroyVectorArray(yS, Ns);
+    return(FALSE);
+  }
+  
+  /* Allocate acorS */
+  acorS = NULL;
+  acorS = N_VCloneVectorArray(Ns, tmpl);
+  if (acorS == NULL) {
+    N_VDestroyVectorArray(yS, Ns);
+    N_VDestroyVectorArray(ewtS, Ns);
+    return(FALSE);
+  }
+  
+  /* Allocate tempvS */
+  tempvS = NULL;
+  tempvS = N_VCloneVectorArray(Ns, tmpl);
+  if (tempvS == NULL) {
+    N_VDestroyVectorArray(yS, Ns);
+    N_VDestroyVectorArray(ewtS, Ns);
+    N_VDestroyVectorArray(acorS, Ns);
+    return(FALSE);
+  }
+    
+  /* Allocate ftempS */
+  ftempS = NULL;
+  ftempS = N_VCloneVectorArray(Ns, tmpl);
+  if (ftempS == NULL) {
+    N_VDestroyVectorArray(yS, Ns);
+    N_VDestroyVectorArray(ewtS, Ns);
+    N_VDestroyVectorArray(acorS, Ns);
+    N_VDestroyVectorArray(tempvS, Ns);
+    return(FALSE);
+  }
+  
+  /* Allocate znS */
+  for (j=0; j<=qmax; j++) {
+    znS[j] = NULL;
+    znS[j] = N_VCloneVectorArray(Ns, tmpl);
+    if (znS[j] == NULL) {
+      N_VDestroyVectorArray(yS, Ns);
+      N_VDestroyVectorArray(ewtS, Ns);
+      N_VDestroyVectorArray(acorS, Ns);
+      N_VDestroyVectorArray(tempvS, Ns);
+      N_VDestroyVectorArray(ftempS, Ns);
+      for (i=0; i<j; i++) N_VDestroyVectorArray(znS[i], Ns);
+      return(FALSE);
+    }
+  }
+  
+  /* Allocate space for pbar and plist */
+  pbar = NULL;
+  pbar = (realtype *)malloc(Ns*sizeof(realtype));
+  if (pbar == NULL) {
+    N_VDestroyVectorArray(yS, Ns);
+    N_VDestroyVectorArray(ewtS, Ns);
+    N_VDestroyVectorArray(acorS, Ns);
+    N_VDestroyVectorArray(tempvS, Ns);
+    N_VDestroyVectorArray(ftempS, Ns);
+    for (i=0; i<=qmax; i++) N_VDestroyVectorArray(znS[i], Ns);
+    return(FALSE);
+  }
+
+  plist = NULL;
+  plist = (int *)malloc(Ns*sizeof(int));
+  if (plist == NULL) {
+    N_VDestroyVectorArray(yS, Ns);
+    N_VDestroyVectorArray(ewtS, Ns);
+    N_VDestroyVectorArray(acorS, Ns);
+    N_VDestroyVectorArray(tempvS, Ns);
+    N_VDestroyVectorArray(ftempS, Ns);
+    for (i=0; i<=qmax; i++) N_VDestroyVectorArray(znS[i], Ns);
+    free(pbar); pbar = NULL;
+    return(FALSE);
+  }
+
+  /* Update solver workspace lengths */
+  lrw += (qmax + 6)*Ns*lrw1 + Ns;
+  liw += (qmax + 6)*Ns*liw1 + Ns;
+  
+  /* Store the value of qmax used here */
+  cv_mem->cv_qmax_allocS = qmax;
+
+  return(TRUE);
+}
+
+/*
+ * CVSensFreeVectors
+ *
+ * This routine frees the CVODES vectors allocated in CVSensAllocVectors.
+ */
+
+static void CVSensFreeVectors(CVodeMem cv_mem) 
+{
+  int j, maxord;
+  
+  maxord = cv_mem->cv_qmax_allocS;
+
+  N_VDestroyVectorArray(yS, Ns);
+  N_VDestroyVectorArray(ewtS, Ns);
+  N_VDestroyVectorArray(acorS, Ns);
+  N_VDestroyVectorArray(tempvS, Ns);
+  N_VDestroyVectorArray(ftempS, Ns);
+  
+  for (j=0; j<=maxord; j++) N_VDestroyVectorArray(znS[j], Ns);  
+
+  free(pbar); pbar = NULL;
+  free(plist); plist = NULL;
+
+  lrw -= (maxord + 6)*Ns*lrw1 + Ns;
+  liw -= (maxord + 6)*Ns*liw1 + Ns;
+
+  if (cv_mem->cv_VabstolSMallocDone) {
+    N_VDestroyVectorArray(VabstolS, Ns);
+    lrw -= Ns*lrw1;
+    liw -= Ns*liw1;
+  }
+  if (cv_mem->cv_SabstolSMallocDone) {
+    free(SabstolS); SabstolS = NULL;
+    lrw -= Ns;
+  }
+  cv_mem->cv_VabstolSMallocDone = FALSE;
+  cv_mem->cv_SabstolSMallocDone = FALSE;
+}
+
+/* 
+ * -----------------------------------------------------------------
+ * Initial stepsize calculation
+ * -----------------------------------------------------------------
+ */
+
+/*
+ * CVHin
+ *
+ * This routine computes a tentative initial step size h0. 
+ * If tout is too close to tn (= t0), then CVHin returns CV_TOO_CLOSE
+ * and h remains uninitialized. 
+ * If any RHS function fails unrecoverably, CVHin returns CV_*RHSFUNC_FAIL.
+ * If any RHS function fails recoverably too many times and recovery is
+ * not possible, CVHin returns CV_REPTD_*RHSFUNC_ERR.
+ * Otherwise, CVHin sets h to the chosen value h0 and returns CV_SUCCESS.
+ *
+ * The algorithm used seeks to find h0 as a solution of
+ *       (WRMS norm of (h0^2 ydd / 2)) = 1, 
+ * where ydd = estimated second derivative of y. Here, y includes
+ * all variables considered in the error test.
+ *
+ * We start with an initial estimate equal to the geometric mean of the
+ * lower and upper bounds on the step size.
+ *
+ * Loop up to MAX_ITERS times to find h0.
+ * Stop if new and previous values differ by a factor < 2.
+ * Stop if hnew/hg > 2 after one iteration, as this probably means
+ * that the ydd value is bad because of cancellation error.        
+ *  
+ * For each new proposed hg, we allow MAX_ITERS attempts to
+ * resolve a possible recoverable failure from f() by reducing
+ * the proposed stepsize by a factor of 0.2. If a legal stepsize
+ * still cannot be found, fall back on a previous value if possible,
+ * or else return CV_REPTD_RHSFUNC_ERR.
+ *
+ * Finally, we apply a bias (0.5) and verify that h0 is within bounds.
+ */
+
+static int CVHin(CVodeMem cv_mem, realtype tout)
+{
+  int retval, sign, count1, count2;
+  realtype tdiff, tdist, tround, hlb, hub;
+  realtype hg, hgs, hs, hnew, hrat, h0, yddnrm;
+  booleantype hgOK, hnewOK;
+
+  /* If tout is too close to tn, give up */
+  
+  if ((tdiff = tout-tn) == ZERO) return(CV_TOO_CLOSE);
+  
+  sign = (tdiff > ZERO) ? 1 : -1;
+  tdist = ABS(tdiff);
+  tround = uround * MAX(ABS(tn), ABS(tout));
+
+  if (tdist < TWO*tround) return(CV_TOO_CLOSE);
+  
+  /* 
+     Set lower and upper bounds on h0, and take geometric mean 
+     as first trial value.
+     Exit with this value if the bounds cross each other.
+  */
+
+  hlb = HLB_FACTOR * tround;
+  hub = CVUpperBoundH0(cv_mem, tdist);
+
+  hg  = RSqrt(hlb*hub);
+
+  if (hub < hlb) {
+    if (sign == -1) h = -hg;
+    else            h =  hg;
+    return(CV_SUCCESS);
+  }
+  
+  /* Outer loop */
+
+  hnewOK = FALSE;
+  hs = hg;         /* safeguard against 'uninitialized variable' warning */
+
+  for(count1 = 1; count1 <= MAX_ITERS; count1++) {
+
+    /* Attempts to estimate ydd */
+
+    hgOK = FALSE;
+
+    for (count2 = 1; count2 <= MAX_ITERS; count2++) {
+      hgs = hg*sign;
+      retval = CVYddNorm(cv_mem, hgs, &yddnrm);
+      /* If a RHS function failed unrecoverably, give up */
+      if (retval < 0) return(retval);
+      /* If successful, we can use ydd */
+      if (retval == CV_SUCCESS) {hgOK = TRUE; break;}
+      /* A RHS function failed recoverably; cut step size and test it again */
+      hg *= POINT2;
+    }
+
+    /* If a RHS function failed recoverably MAX_ITERS times */
+
+    if (!hgOK) {
+      /* Exit if this is the first or second pass. No recovery possible */
+      if (count1 <= 2) 
+        if (retval == RHSFUNC_RECVR)  return(CV_REPTD_RHSFUNC_ERR);
+        if (retval == QRHSFUNC_RECVR) return(CV_REPTD_QRHSFUNC_ERR);
+        if (retval == SRHSFUNC_RECVR) return(CV_REPTD_SRHSFUNC_ERR);
+      /* We have a fall-back option. The value hs is a previous hnew which
+         passed through f(). Use it and break */
+      hnew = hs;
+      break;
+    }
+
+    /* The proposed step size is feasible. Save it. */
+    hs = hg;
+
+    /* If the stopping criteria was met, or if this is the last pass, stop */
+    if ( (hnewOK) || (count1 == MAX_ITERS))  {hnew = hg; break;}
+
+    /* Propose new step size */
+    hnew = (yddnrm*hub*hub > TWO) ? RSqrt(TWO/yddnrm) : RSqrt(hg*hub);
+    hrat = hnew/hg;
+    
+    /* Accept hnew if it does not differ from hg by more than a factor of 2 */
+    if ((hrat > HALF) && (hrat < TWO)) {
+      hnewOK = TRUE;
+    }
+
+    /* After one pass, if ydd seems to be bad, use fall-back value. */
+    if ((count1 > 1) && (hrat > TWO)) {
+      hnew = hg;
+      hnewOK = TRUE;
+    }
+
+    /* Send this value back through f() */
+    hg = hnew;
+
+  }
+
+  /* Apply bounds, bias factor, and attach sign */
+
+  h0 = H_BIAS*hnew;
+  if (h0 < hlb) h0 = hlb;
+  if (h0 > hub) h0 = hub;
+  if (sign == -1) h0 = -h0;
+  h = h0;
+
+  return(CV_SUCCESS);
+}
+
+/*
+ * CVUpperBoundH0
+ *
+ * This routine sets an upper bound on abs(h0) based on
+ * tdist = tn - t0 and the values of y[i]/y'[i].
+ */
+
+static realtype CVUpperBoundH0(CVodeMem cv_mem, realtype tdist)
+{
+  realtype hub_inv, hubQ_inv, hubS_inv, hub;
+  N_Vector temp1, temp2;
+  N_Vector tempQ1, tempQ2;
+  N_Vector *tempS1;
+  int is;
+
+  /* 
+   * Bound based on |y|/|y'| -- allow at most an increase of
+   * HUB_FACTOR in y0 (based on a forward Euler step). The weight 
+   * factor is used as a safeguard against zero components in y0. 
+   */
+
+  temp1 = tempv;
+  temp2 = acor;
+
+  N_VAbs(zn[0], temp2);
+  efun(zn[0], temp1, e_data);
+  N_VInv(temp1, temp1);
+  N_VLinearSum(HUB_FACTOR, temp2, ONE, temp1, temp1);
+
+  N_VAbs(zn[1], temp2);
+
+  N_VDiv(temp2, temp1, temp1);
+  hub_inv = N_VMaxNorm(temp1);
+
+  /* Bound based on |yQ|/|yQ'| */
+  
+  if (quadr && errconQ) {
+
+    tempQ1 = tempvQ;
+    tempQ2 = acorQ;
+
+    N_VAbs(znQ[0], tempQ2);
+    CVQuadEwtSet(cv_mem, znQ[0], tempQ1);
+    N_VInv(tempQ1, tempQ1);
+    N_VLinearSum(HUB_FACTOR, tempQ2, ONE, tempQ1, tempQ1);
+    
+    N_VAbs(znQ[1], tempQ2);
+    
+    N_VDiv(tempQ2, tempQ1, tempQ1);
+    hubQ_inv = N_VMaxNorm(tempQ1);
+
+    if (hubQ_inv > hub_inv) hub_inv = hubQ_inv;
+
+  }
+
+  /* Bound based on |yS|/|yS'| */
+
+  if (sensi && errconS) {
+
+    tempS1 = acorS;
+    CVSensEwtSet(cv_mem, znS[0], tempS1);
+
+    for (is=0; is<Ns; is++) {
+
+      N_VAbs(znS[0][is], temp2);
+      N_VInv(tempS1[is], temp1);
+      N_VLinearSum(HUB_FACTOR, temp2, ONE, temp1, temp1);
+      
+      N_VAbs(znS[1][is], temp2);
+      
+      N_VDiv(temp2, temp1, temp1);
+      hubS_inv = N_VMaxNorm(temp1);
+
+      if (hubS_inv > hub_inv) hub_inv = hubS_inv;
+
+    }
+
+  }
+
+  /*
+   * bound based on tdist -- allow at most a step of magnitude
+   * HUB_FACTOR * tdist
+   */
+  
+  hub = HUB_FACTOR*tdist;
+
+  /* Use the smaler of the two */
+
+  if (hub*hub_inv > ONE) hub = ONE/hub_inv;
+
+  return(hub);
+}
+
+/*
+ * CVYddNorm
+ *
+ * This routine computes an estimate of the second derivative of Y
+ * using a difference quotient, and returns its WRMS norm.
+ *
+ * Y contains all variables included in the error test. 
+ */
+
+static int CVYddNorm(CVodeMem cv_mem, realtype hg, realtype *yddnrm)
+{
+  int retval, is;
+  N_Vector wrk1, wrk2;
+  
+  /* y     <- h*y'(t) + y(t) */
+  
+  N_VLinearSum(hg, zn[1], ONE, zn[0], y);
+  
+  if (sensi && errconS) 
+    for (is=0; is<Ns; is++)
+      N_VLinearSum(hg, znS[1][is], ONE, znS[0][is], yS[is]);
+  
+  /* tempv <- f(t+h, h*y'(t)+y(t)) */
+
+  retval = f(tn+hg, y, tempv, f_data);
+  nfe++;
+  if (retval < 0) return(CV_RHSFUNC_FAIL);
+  if (retval > 0) return(RHSFUNC_RECVR);
+
+  if (quadr && errconQ) {
+    retval = fQ(tn+hg, y, tempvQ, fQ_data);
+    nfQe++;
+    if (retval < 0) return(CV_QRHSFUNC_FAIL);
+    if (retval > 0) return(QRHSFUNC_RECVR);
+  }
+
+  if (sensi && errconS) {
+    wrk1 = ftemp;
+    wrk2 = acor;
+    retval = CVSensRhs(cv_mem, tn+hg, y, tempv, yS, tempvS, wrk1, wrk2);
+    if (retval < 0) return(CV_SRHSFUNC_FAIL);
+    if (retval > 0) return(SRHSFUNC_RECVR);
+  }  
+
+  /* tempv <- f(t+h, h*y'(t)+y(t)) - y'(t) */
+  /* tempv <- ydd */
+  
+  N_VLinearSum(ONE, tempv, -ONE, zn[1], tempv);
+  N_VScale(ONE/hg, tempv, tempv);
+  
+  if (quadr && errconQ) {
+    N_VLinearSum(ONE, tempvQ, -ONE, znQ[1], tempvQ);
+    N_VScale(ONE/hg, tempvQ, tempvQ);
+  }
+
+  if (sensi && errconS)
+    for (is=0; is<Ns; is++) {
+      N_VLinearSum(ONE, tempvS[is], -ONE, znS[1][is], tempvS[is]);
+      N_VScale(ONE/hg, tempvS[is], tempvS[is]);
+    }
+
+  /* Estimate ||y''|| */
+  
+  *yddnrm = N_VWrmsNorm(tempv, ewt);
+  if (quadr && errconQ) {
+    *yddnrm = CVQuadUpdateNorm(cv_mem, *yddnrm, tempvQ, ewtQ);
+  }
+  if (sensi && errconS) {
+    *yddnrm = CVSensUpdateNorm(cv_mem, *yddnrm, tempvS, ewtS);
+  }
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * -----------------------------------------------------------------
+ * Initial setup
+ * -----------------------------------------------------------------
+ */
+
+/*  
+ * CVInitialSetup
+ *
+ * This routine performs input consistency checks at the first step.
+ * If needed, it also checks the linear solver module and calls the
+ * linear solver initialization routine.
+ */
+
+static int CVInitialSetup(CVodeMem cv_mem)
+{
+  int ier;
+
+  /* Did the user provide efun? */
+
+  if (itol != CV_WF) {
+    efun = CVEwtSet;
+    e_data = (void *)cv_mem;
+  } else {
+    if (efun == NULL) {
+      CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVInitialSetup", MSGCV_NO_EFUN);
+      return(CV_ILL_INPUT);
+    }
+  }
+
+  ier = efun(zn[0], ewt, e_data);
+  if (ier != 0) {
+
+    if (itol == CV_WF) 
+      CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVInitialSetup", MSGCV_EWT_FAIL);
+    else
+      CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVInitialSetup", MSGCV_BAD_EWT);
+
+    return(CV_ILL_INPUT);
+  }
+  
+  /* Quadrature initial setup */
+
+  if (quadr && errconQ) {
+
+    /* Load ewtQ */
+    ier = CVQuadEwtSet(cv_mem, znQ[0], ewtQ);
+    if (ier != 0) {
+      CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVInitialSetup", MSGCV_BAD_EWTQ);
+      return(CV_ILL_INPUT);
+    }
+
+  }
+
+  if (!quadr) errconQ = FALSE;
+
+  /* Forward sensitivity initial setup */
+
+  if (sensi) {
+
+    /* Check if ism and ifS agree */
+    if ((ism==CV_STAGGERED1) && (ifS==CV_ALLSENS)) {
+      CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVInitialSetup", MSGCV_BAD_ISM_IFS);
+      return(CV_ILL_INPUT);
+    }    
+
+    /* Load ewtS */
+    ier = CVSensEwtSet(cv_mem, znS[0], ewtS);
+    if (ier != 0) {
+      CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVInitialSetup", MSGCV_BAD_EWTS);
+      return(CV_ILL_INPUT);
+    }
+
+  }
+
+  /* Check if lsolve function exists (if needed)
+     and call linit function (if it exists) */
+
+  if (iter == CV_NEWTON) {
+    if (lsolve == NULL) {
+      CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVInitialSetup", MSGCV_LSOLVE_NULL);
+      return(CV_ILL_INPUT);
+    }
+    if (linit != NULL) {
+      ier = linit(cv_mem);
+      if (ier != 0) {
+        CVProcessError(cv_mem, CV_LINIT_FAIL, "CVODES", "CVInitialSetup", MSGCV_LINIT_FAIL);
+        return(CV_LINIT_FAIL);
+      }
+    }
+  }
+    
+  return(CV_SUCCESS);
+}
+
+/*
+ * CVEwtSet
+ *
+ * This routine is responsible for setting the error weight vector ewt,
+ * according to tol_type, as follows:
+ *
+ * (1) ewt[i] = 1 / (reltol * ABS(ycur[i]) + *abstol), i=0,...,neq-1
+ *     if tol_type = CV_SS
+ * (2) ewt[i] = 1 / (reltol * ABS(ycur[i]) + abstol[i]), i=0,...,neq-1
+ *     if tol_type = CV_SV
+ *
+ * CVEwtSet returns 0 if ewt is successfully set as above to a
+ * positive vector and -1 otherwise. In the latter case, ewt is
+ * considered undefined.
+ *
+ * All the real work is done in the routines CVEwtSetSS, CVEwtSetSV.
+ */
+
+int CVEwtSet(N_Vector ycur, N_Vector weight, void *data)
+{
+  CVodeMem cv_mem;
+  int flag = 0;
+
+  /* data points to cv_mem here */
+
+  cv_mem = (CVodeMem) data;
+
+  switch(itol) {
+  case CV_SS: 
+    flag = CVEwtSetSS(cv_mem, ycur, weight);
+    break;
+  case CV_SV: 
+    flag = CVEwtSetSV(cv_mem, ycur, weight);
+    break;
+  }
+
+  return(flag);
+}
+
+/*
+ * CVEwtSetSS
+ *
+ * This routine sets ewt as decribed above in the case tol_type = CV_SS.
+ * It tests for non-positive components before inverting. CVEwtSetSS
+ * returns 0 if ewt is successfully set to a positive vector
+ * and -1 otherwise. In the latter case, ewt is considered undefined.
+ */
+
+static int CVEwtSetSS(CVodeMem cv_mem, N_Vector ycur, N_Vector weight)
+{
+  N_VAbs(ycur, tempv);
+  N_VScale(reltol, tempv, tempv);
+  N_VAddConst(tempv, Sabstol, tempv);
+  if (N_VMin(tempv) <= ZERO) return(-1);
+  N_VInv(tempv, weight);
+
+  return(0);
+}
+
+/*
+ * CVEwtSetSV
+ *
+ * This routine sets ewt as decribed above in the case tol_type = CV_SV.
+ * It tests for non-positive components before inverting. CVEwtSetSV
+ * returns 0 if ewt is successfully set to a positive vector
+ * and -1 otherwise. In the latter case, ewt is considered undefined.
+ */
+
+static int CVEwtSetSV(CVodeMem cv_mem, N_Vector ycur, N_Vector weight)
+{
+  N_VAbs(ycur, tempv);
+  N_VLinearSum(reltol, tempv, ONE, Vabstol, tempv);
+  if (N_VMin(tempv) <= ZERO) return(-1);
+  N_VInv(tempv, weight);
+  return(0);
+}
+
+/*
+ * CVQuadEwtSet
+ *
+ */
+
+static int CVQuadEwtSet(CVodeMem cv_mem, N_Vector qcur, N_Vector weightQ)
+{
+  int flag=0;
+
+  switch (itolQ) {
+  case CV_SS: 
+    flag = CVQuadEwtSetSS(cv_mem, qcur, weightQ);
+    break;
+  case CV_SV: 
+    flag = CVQuadEwtSetSV(cv_mem, qcur, weightQ);
+    break;
+  }
+
+  return(flag);
+
+}
+
+/*
+ * CVQuadEwtSetSS
+ *
+ */
+
+static int CVQuadEwtSetSS(CVodeMem cv_mem, N_Vector qcur, N_Vector weightQ)
+{
+  N_VAbs(qcur, tempvQ);
+  N_VScale(reltolQ, tempvQ, tempvQ);
+  N_VAddConst(tempvQ, SabstolQ, tempvQ);
+  if (N_VMin(tempvQ) <= ZERO) return(-1);
+  N_VInv(tempvQ, weightQ);
+
+  return(0);
+}
+
+/*
+ * CVQuadEwtSetSV
+ *
+ */
+
+static int CVQuadEwtSetSV(CVodeMem cv_mem, N_Vector qcur, N_Vector weightQ)
+{
+  N_VAbs(qcur, tempvQ);
+  N_VLinearSum(reltolQ, tempvQ, ONE, VabstolQ, tempvQ);
+  if (N_VMin(tempvQ) <= ZERO) return(-1);
+  N_VInv(tempvQ, weightQ);
+
+  return(0);
+}
+
+/*
+ * CVSensEwtSet
+ *
+ */
+
+static int CVSensEwtSet(CVodeMem cv_mem, N_Vector *yScur, N_Vector *weightS)
+{
+  int flag=0;
+
+  switch (itolS) {
+  case CV_EE:
+    flag = CVSensEwtSetEE(cv_mem, yScur, weightS);
+    break;
+  case CV_SS: 
+    flag = CVSensEwtSetSS(cv_mem, yScur, weightS);
+    break;
+  case CV_SV: 
+    flag = CVSensEwtSetSV(cv_mem, yScur, weightS);
+    break;
+  }
+
+  return(flag);
+
+}
+
+/*
+ * CVSensEwtSetEE
+ *
+ * In this case, the error weight vector for the i-th sensitivity is set to
+ *
+ * ewtS_i = pbar_i * efun(pbar_i*yS_i)
+ *
+ * In other words, the scaled sensitivity pbar_i * yS_i has the same error
+ * weight vector calculation as the solution vector.
+ *
+ */
+
+static int CVSensEwtSetEE(CVodeMem cv_mem, N_Vector *yScur, N_Vector *weightS)
+{
+  int is;
+  N_Vector pyS;
+  int flag;
+
+  /* Use tempvS[0] as temporary storage for the scaled sensitivity */
+  pyS = tempvS[0];
+
+  for (is=0; is<Ns; is++) {
+    N_VScale(pbar[is], yScur[is], pyS);
+    flag = efun(pyS, weightS[is], e_data);
+    if (flag != 0) return(-1);
+    N_VScale(pbar[is], weightS[is], weightS[is]);
+  }
+
+  return(0);
+}
+
+/*
+ * CVSensEwtSetSS
+ *
+ */
+
+static int CVSensEwtSetSS(CVodeMem cv_mem, N_Vector *yScur, N_Vector *weightS)
+{
+  int is;
+  
+  for (is=0; is<Ns; is++) {
+    N_VAbs(yScur[is], tempv);
+    N_VScale(reltolS, tempv, tempv);
+    N_VAddConst(tempv, SabstolS[is], tempv);
+    if (N_VMin(tempv) <= ZERO) return(-1);
+    N_VInv(tempv, weightS[is]);
+  }
+  return(0);
+}
+
+/*
+ * CVSensEwtSetSV
+ *
+ */
+
+static int CVSensEwtSetSV(CVodeMem cv_mem, N_Vector *yScur, N_Vector *weightS)
+{
+  int is;
+  
+  for (is=0; is<Ns; is++) {
+    N_VAbs(yScur[is], tempv);
+    N_VLinearSum(reltolS, tempv, ONE, VabstolS[is], tempv);
+    if (N_VMin(tempv) <= ZERO) return(-1);
+    N_VInv(tempv, weightS[is]);
+  }
+
+  return(0);
+}
+
+/* 
+ * -----------------------------------------------------------------
+ * Main CVStep function
+ * -----------------------------------------------------------------
+ */
+
+/* 
+ * CVStep
+ *
+ * This routine performs one internal cvode step, from tn to tn + h.
+ * It calls other routines to do all the work.
+ *
+ * The main operations done here are as follows:
+ * - preliminary adjustments if a new step size was chosen;
+ * - prediction of the Nordsieck history array zn at tn + h;
+ * - setting of multistep method coefficients and test quantities;
+ * - solution of the nonlinear system;
+ * - testing the local error;
+ * - updating zn and other state data if successful;
+ * - resetting stepsize and order for the next step.
+ * - if SLDET is on, check for stability, reduce order if necessary.
+ * On a failure in the nonlinear system solution or error test, the
+ * step may be reattempted, depending on the nature of the failure.
+ */
+
+static int CVStep(CVodeMem cv_mem)
+{
+  realtype saved_t, dsm, dsmS, dsmQ;
+  booleantype do_sensi_stg, do_sensi_stg1;
+  int ncf, nef, ncfS, nefS, nefQ;
+  int nflag, kflag, eflag;
+  int retval, is;
+
+  /* Are we computing sensitivities with a staggered approach? */
+
+  do_sensi_stg  = (sensi && (ism==CV_STAGGERED));
+  do_sensi_stg1 = (sensi && (ism==CV_STAGGERED1));
+
+  /* Initialize local counters for convergence and error test failures */
+
+  ncf  = nef  = 0;
+  nefQ = 0;
+  ncfS = nefS = 0;
+  if (do_sensi_stg1)
+    for (is=0; is<Ns; is++) ncfS1[is] = 0;
+
+  /* If needed, adjust method parameters */
+
+  if ((nst > 0) && (hprime != h)) CVAdjustParams(cv_mem);
+
+  /* Looping point for attempts to take a step */
+
+  saved_t = tn;
+  nflag = FIRST_CALL;
+
+  loop {  
+
+    CVPredict(cv_mem);  
+    CVSet(cv_mem);
+
+    /* ------ Correct state variables ------ */
+    
+    nflag = CVNls(cv_mem, nflag);
+    kflag = CVHandleNFlag(cv_mem, &nflag, saved_t, &ncf, &ncfn);
+
+    /* Go back in loop if we need to predict again (nflag=PREV_CONV_FAIL) */
+    if (kflag == PREDICT_AGAIN) continue;
+
+    /* Return if nonlinear solve failed and recovery not possible. */
+    if (kflag != DO_ERROR_TEST) return(kflag);
+
+    /* Perform error test (nflag=CV_SUCCESS) */
+    eflag = CVDoErrorTest(cv_mem, &nflag, saved_t, acnrm, &nef, &netf, &dsm);
+
+    /* Go back in loop if we need to predict again (nflag=PREV_ERR_FAIL) */
+    if (eflag == TRY_AGAIN) continue;
+
+    /* Return if error test failed and recovery not possible. */
+    if (eflag != CV_SUCCESS) return(eflag);
+
+    /* Error test passed (eflag=CV_SUCCESS, nflag=CV_SUCCESS), go on */
+
+    /* ------ Correct the quadrature variables ------ */
+
+    if (quadr) {
+
+      ncf = nef = 0; /* reset counters for states */
+
+      nflag = CVQuadNls(cv_mem);
+      kflag = CVHandleNFlag(cv_mem, &nflag, saved_t, &ncf, &ncfn);
+
+      if (kflag == PREDICT_AGAIN) continue;
+      if (kflag != DO_ERROR_TEST) return(kflag);
+
+      /* Error test on quadratures */
+      if (errconQ) {
+        acnrmQ = N_VWrmsNorm(acorQ, ewtQ);
+        eflag = CVDoErrorTest(cv_mem, &nflag, saved_t, acnrmQ, &nefQ, &netfQ, &dsmQ);
+
+        if (eflag == TRY_AGAIN)  continue;
+        if (eflag != CV_SUCCESS) return(eflag);
+
+        /* update 'dsm' with 'dsmQ' (to be used in CVPrepareNextStep) */
+        dsm = CVQuadUpdateDsm(cv_mem, dsm, dsmQ);
+      }
+
+    }
+
+    /* ------ Correct the sensitivity variables (STAGGERED or STAGGERED1) ------- */
+
+    if (do_sensi_stg || do_sensi_stg1) {
+
+      ncf = nef = 0;        /* reset counters for states     */
+      if (quadr) nefQ = 0;  /* reset counter for quadratures */
+
+      /* Evaluate f at converged y, needed for future evaluations of sens. RHS 
+         If f() fails recoverably, treat it as a convergence failure and 
+         attempt the step again */
+
+      retval = f(tn, y, ftemp, f_data);
+      nfe++;
+      if (retval < 0) return(CV_RHSFUNC_FAIL);
+      if (retval > 0) {
+        nflag = PREV_CONV_FAIL;
+        continue;
+      }
+
+      if (do_sensi_stg) {
+        /* Nonlinear solve for sensitivities (all-at-once) */
+        nflag = CVStgrNls(cv_mem);
+        kflag = CVHandleNFlag(cv_mem, &nflag, saved_t, &ncfS, &ncfnS);
+      } else {
+        /* Nonlinear solve for sensitivities (one-by-one) */
+        for (is=0; is<Ns; is++) { 
+          nflag = CVStgr1Nls(cv_mem, is); 
+          kflag = CVHandleNFlag(cv_mem, &nflag, saved_t, &ncfS1[is], &ncfnS1[is]);
+          if (kflag != DO_ERROR_TEST) break; 
+        }
+      }
+
+      if (kflag == PREDICT_AGAIN) continue;
+      if (kflag != DO_ERROR_TEST) return(kflag);
+
+      /* Error test on sensitivities */
+      if (errconS) {
+
+        if (do_sensi_stg1) acnrmS = CVSensNorm(cv_mem, acorS, ewtS);
+
+        eflag = CVDoErrorTest(cv_mem, &nflag, saved_t, acnrmS, &nefS, &netfS, &dsmS);
+
+        if (eflag == TRY_AGAIN)  continue;
+        if (eflag != CV_SUCCESS) return(eflag);
+
+        /* update 'dsm' with 'dsmS' (to be used in CVPrepareNextStep) */
+        dsm = CVStgrUpdateDsm(cv_mem, dsm, dsmS);
+      }
+
+    }
+
+    /* Everything went fine; exit loop */ 
+    break;
+
+  }
+
+  /* Nonlinear system solve and error test were both successful.
+     Update data, and consider change of step and/or order.       */
+
+  CVCompleteStep(cv_mem); 
+
+  CVPrepareNextStep(cv_mem, dsm); 
+
+  /* If Stablilty Limit Detection is turned on, call stability limit
+     detection routine for possible order reduction. */
+
+  if (sldeton) CVBDFStab(cv_mem);
+
+  etamax = (nst <= SMALL_NST) ? ETAMX2 : ETAMX3;
+
+  /*  Finally, we rescale the acor array to be the 
+      estimated local error vector. */
+
+  N_VScale(ONE/tq[2], acor, acor);
+
+  if (quadr)
+    N_VScale(ONE/tq[2], acorQ, acorQ);
+
+  if (sensi)
+    for (is=0; is<Ns; is++)
+      N_VScale(ONE/tq[2], acorS[is], acorS[is]);
+
+  return(CV_SUCCESS);
+      
+}
+
+/* 
+ * -----------------------------------------------------------------
+ * Function called at beginning of step
+ * -----------------------------------------------------------------
+ */
+
+/*
+ * CVAdjustParams
+ *
+ * This routine is called when a change in step size was decided upon,
+ * and it handles the required adjustments to the history array zn.
+ * If there is to be a change in order, we call CVAdjustOrder and reset
+ * q, L = q+1, and qwait.  Then in any case, we call CVRescale, which
+ * resets h and rescales the Nordsieck array.
+ */
+
+static void CVAdjustParams(CVodeMem cv_mem)
+{
+  if (qprime != q) {
+    CVAdjustOrder(cv_mem, qprime-q);
+    q = qprime;
+    L = q+1;
+    qwait = L;
+  }
+  CVRescale(cv_mem);
+}
+
+/*
+ * CVAdjustOrder
+ *
+ * This routine is a high level routine which handles an order
+ * change by an amount deltaq (= +1 or -1). If a decrease in order
+ * is requested and q==2, then the routine returns immediately.
+ * Otherwise CVAdjustAdams or CVAdjustBDF is called to handle the
+ * order change (depending on the value of lmm).
+ */
+
+static void CVAdjustOrder(CVodeMem cv_mem, int deltaq)
+{
+  if ((q==2) && (deltaq != 1)) return;
+  
+  switch(lmm){
+  case CV_ADAMS: 
+    CVAdjustAdams(cv_mem, deltaq);
+    break;
+  case CV_BDF:   
+    CVAdjustBDF(cv_mem, deltaq);
+    break;
+  }
+}
+
+/*
+ * CVAdjustAdams
+ *
+ * This routine adjusts the history array on a change of order q by
+ * deltaq, in the case that lmm == CV_ADAMS.
+ */
+
+static void CVAdjustAdams(CVodeMem cv_mem, int deltaq)
+{
+  int i, j;
+  int is;
+  realtype xi, hsum;
+
+  /* On an order increase, set new column of zn to zero and return */
+  
+  if (deltaq==1) {
+    N_VConst(ZERO, zn[L]);
+    if (quadr)
+      N_VConst(ZERO, znQ[L]);
+    if (sensi)
+      for (is=0; is<Ns; is++)
+        N_VConst(ZERO, znS[L][is]);
+    return;
+  }
+
+  /*
+   * On an order decrease, each zn[j] is adjusted by a multiple of zn[q].
+   * The coeffs. in the adjustment are the coeffs. of the polynomial:
+   *        x
+   * q * INT { u * ( u + xi_1 ) * ... * ( u + xi_{q-2} ) } du 
+   *        0
+   * where xi_j = [t_n - t_(n-j)]/h => xi_0 = 0
+   */
+
+  for (i=0; i <= qmax; i++) l[i] = ZERO;
+  l[1] = ONE;
+  hsum = ZERO;
+  for (j=1; j <= q-2; j++) {
+    hsum += tau[j];
+    xi = hsum / hscale;
+    for (i=j+1; i >= 1; i--) l[i] = l[i]*xi + l[i-1];
+  }
+  
+  for (j=1; j <= q-2; j++) l[j+1] = q * (l[j] / (j+1));
+  
+  for (j=2; j < q; j++)
+    N_VLinearSum(-l[j], zn[q], ONE, zn[j], zn[j]);
+
+  if (quadr)
+    for (j=2; j < q; j++)
+      N_VLinearSum(-l[j], znQ[q], ONE, znQ[j], znQ[j]);
+
+  if (sensi)
+    for (is=0; is<Ns; is++)
+      for (j=2; j < q; j++)
+        N_VLinearSum(-l[j], znS[q][is], ONE, znS[j][is], znS[j][is]);
+
+}
+
+/*
+ * CVAdjustBDF
+ *
+ * This is a high level routine which handles adjustments to the
+ * history array on a change of order by deltaq in the case that 
+ * lmm == CV_BDF.  CVAdjustBDF calls CVIncreaseBDF if deltaq = +1 and 
+ * CVDecreaseBDF if deltaq = -1 to do the actual work.
+ */
+
+static void CVAdjustBDF(CVodeMem cv_mem, int deltaq)
+{
+  switch(deltaq) {
+  case 1: 
+    CVIncreaseBDF(cv_mem);
+    return;
+  case -1: 
+    CVDecreaseBDF(cv_mem);
+    return;
+  }
+}
+
+/*
+ * CVIncreaseBDF
+ *
+ * This routine adjusts the history array on an increase in the 
+ * order q in the case that lmm == CV_BDF.  
+ * A new column zn[q+1] is set equal to a multiple of the saved 
+ * vector (= acor) in zn[indx_acor].  Then each zn[j] is adjusted by
+ * a multiple of zn[q+1].  The coefficients in the adjustment are the 
+ * coefficients of the polynomial x*x*(x+xi_1)*...*(x+xi_j),
+ * where xi_j = [t_n - t_(n-j)]/h.
+ */
+
+static void CVIncreaseBDF(CVodeMem cv_mem)
+{
+  realtype alpha0, alpha1, prod, xi, xiold, hsum, A1;
+  int i, j;
+  int is;
+
+  for (i=0; i <= qmax; i++) l[i] = ZERO;
+  l[2] = alpha1 = prod = xiold = ONE;
+  alpha0 = -ONE;
+  hsum = hscale;
+  if (q > 1) {
+    for (j=1; j < q; j++) {
+      hsum += tau[j+1];
+      xi = hsum / hscale;
+      prod *= xi;
+      alpha0 -= ONE / (j+1);
+      alpha1 += ONE / xi;
+      for (i=j+2; i >= 2; i--) l[i] = l[i]*xiold + l[i-1];
+      xiold = xi;
+    }
+  }
+  A1 = (-alpha0 - alpha1) / prod;
+
+  /* 
+     zn[indx_acor] contains the value Delta_n = y_n - y_n(0) 
+     This value was stored there at the previous successful
+     step (in CVCompleteStep) 
+     
+     A1 contains dbar = (1/xi* - 1/xi_q)/prod(xi_j)
+  */
+  
+  N_VScale(A1, zn[indx_acor], zn[L]);
+  for (j=2; j <= q; j++)
+    N_VLinearSum(l[j], zn[L], ONE, zn[j], zn[j]);
+
+  if (quadr) {
+    N_VScale(A1, znQ[indx_acor], znQ[L]);
+    for (j=2; j <= q; j++)
+      N_VLinearSum(l[j], znQ[L], ONE, znQ[j], znQ[j]);
+  }
+
+  if (sensi) {
+    for (is=0; is<Ns; is++) {
+      N_VScale(A1, znS[indx_acor][is], znS[L][is]);
+      for (j=2; j <= q; j++)
+        N_VLinearSum(l[j], znS[L][is], ONE, znS[j][is], znS[j][is]);
+    }
+  }
+
+}
+
+/*
+ * CVDecreaseBDF
+ *
+ * This routine adjusts the history array on a decrease in the 
+ * order q in the case that lmm == CV_BDF.  
+ * Each zn[j] is adjusted by a multiple of zn[q].  The coefficients
+ * in the adjustment are the coefficients of the polynomial
+ *   x*x*(x+xi_1)*...*(x+xi_j), where xi_j = [t_n - t_(n-j)]/h.
+ */
+
+static void CVDecreaseBDF(CVodeMem cv_mem)
+{
+  realtype hsum, xi;
+  int i, j;
+  int is;
+  
+  for (i=0; i <= qmax; i++) l[i] = ZERO;
+  l[2] = ONE;
+  hsum = ZERO;
+  for (j=1; j <= q-2; j++) {
+    hsum += tau[j];
+    xi = hsum /hscale;
+    for (i=j+2; i >= 2; i--) l[i] = l[i]*xi + l[i-1];
+  }
+  
+  for (j=2; j < q; j++)
+    N_VLinearSum(-l[j], zn[q], ONE, zn[j], zn[j]);
+
+  if (quadr) {
+    for (j=2; j < q; j++)
+      N_VLinearSum(-l[j], znQ[q], ONE, znQ[j], znQ[j]);
+  }
+
+  if (sensi) {
+    for (is=0; is<Ns; is++) 
+      for (j=2; j < q; j++)
+        N_VLinearSum(-l[j], znS[q][is], ONE, znS[j][is], znS[j][is]);
+  }
+}
+
+/*
+ * CVRescale
+ *
+ * This routine rescales the Nordsieck array by multiplying the
+ * jth column zn[j] by eta^j, j = 1, ..., q.  Then the value of
+ * h is rescaled by eta, and hscale is reset to h.
+ */
+
+static void CVRescale(CVodeMem cv_mem)
+{
+  int j;
+  int is;
+  realtype factor;
+
+  factor = eta;
+  for (j=1; j <= q; j++) {
+
+    N_VScale(factor, zn[j], zn[j]);
+
+    if (quadr)
+      N_VScale(factor, znQ[j], znQ[j]);
+
+    if (sensi)
+      for (is=0; is<Ns; is++)
+        N_VScale(factor, znS[j][is], znS[j][is]);
+
+    factor *= eta;
+
+  }
+  h = hscale * eta;
+  next_h = h;
+  hscale = h;
+  nscon = 0;
+}
+
+/*
+ * CVPredict
+ *
+ * This routine advances tn by the tentative step size h, and computes
+ * the predicted array z_n(0), which is overwritten on zn.  The
+ * prediction of zn is done by repeated additions.
+ * In TSTOP mode, it is possible for tn + h to be past tstop by roundoff,
+ * and in that case, we reset tn (after incrementing by h) to tstop.
+ */
+
+static void CVPredict(CVodeMem cv_mem)
+{
+  int j, k;
+  int is;
+
+  tn += h;
+  if (istop) {
+    if ((tn - tstop)*h > ZERO) tn = tstop;
+  }
+
+  for (k = 1; k <= q; k++)
+    for (j = q; j >= k; j--) 
+      N_VLinearSum(ONE, zn[j-1], ONE, zn[j], zn[j-1]); 
+
+  if (quadr) {
+    for (k = 1; k <= q; k++)
+      for (j = q; j >= k; j--) 
+        N_VLinearSum(ONE, znQ[j-1], ONE, znQ[j], znQ[j-1]);
+  }
+
+  if (sensi) {
+    for (is=0; is<Ns; is++) {
+      for (k = 1; k <= q; k++)
+        for (j = q; j >= k; j--) 
+          N_VLinearSum(ONE, znS[j-1][is], ONE, znS[j][is], znS[j-1][is]);
+    }
+  }
+}
+
+/*
+ * CVSet
+ *
+ * This routine is a high level routine which calls CVSetAdams or
+ * CVSetBDF to set the polynomial l, the test quantity array tq, 
+ * and the related variables  rl1, gamma, and gamrat.
+ */
+
+static void CVSet(CVodeMem cv_mem)
+{
+  switch(lmm) {
+  case CV_ADAMS: 
+    CVSetAdams(cv_mem);
+    break;
+  case CV_BDF: 
+    CVSetBDF(cv_mem);
+    break;
+  }
+  rl1 = ONE / l[1];
+  gamma = h * rl1;
+  if (nst == 0) gammap = gamma;
+  gamrat = (nst > 0) ? gamma / gammap : ONE;  /* protect x / x != 1.0 */
+}
+
+/*
+ * CVSetAdams
+ *
+ * This routine handles the computation of l and tq for the
+ * case lmm == CV_ADAMS.
+ *
+ * The components of the array l are the coefficients of a
+ * polynomial Lambda(x) = l_0 + l_1 x + ... + l_q x^q, given by
+ *                          q-1
+ * (d/dx) Lambda(x) = c * PRODUCT (1 + x / xi_i) , where
+ *                          i=1
+ *  Lambda(-1) = 0, Lambda(0) = 1, and c is a normalization factor.
+ * Here xi_i = [t_n - t_(n-i)] / h.
+ *
+ * The array tq is set to test quantities used in the convergence
+ * test, the error test, and the selection of h at a new order.
+ */
+
+static void CVSetAdams(CVodeMem cv_mem)
+{
+  realtype m[L_MAX], M[3], hsum;
+  
+  if (q == 1) {
+    l[0] = l[1] = tq[1] = tq[5] = ONE;
+    tq[2] = TWO;
+    tq[3] = TWELVE;
+    tq[4] = nlscoef * tq[2];       /* = 0.1 * tq[2] */
+    return;
+  }
+  
+  hsum = CVAdamsStart(cv_mem, m);
+  
+  M[0] = CVAltSum(q-1, m, 1);
+  M[1] = CVAltSum(q-1, m, 2);
+  
+  CVAdamsFinish(cv_mem, m, M, hsum);
+}
+
+/*
+ * CVAdamsStart
+ *
+ * This routine generates in m[] the coefficients of the product
+ * polynomial needed for the Adams l and tq coefficients for q > 1.
+ */
+
+static realtype CVAdamsStart(CVodeMem cv_mem, realtype m[])
+{
+  realtype hsum, xi_inv, sum;
+  int i, j;
+  
+  hsum = h;
+  m[0] = ONE;
+  for (i=1; i <= q; i++) m[i] = ZERO;
+  for (j=1; j < q; j++) {
+    if ((j==q-1) && (qwait == 1)) {
+      sum = CVAltSum(q-2, m, 2);
+      tq[1] = m[q-2] / (q * sum);
+    }
+    xi_inv = h / hsum;
+    for (i=j; i >= 1; i--) m[i] += m[i-1] * xi_inv;
+    hsum += tau[j];
+    /* The m[i] are coefficients of product(1 to j) (1 + x/xi_i) */
+  }
+  return(hsum);
+}
+
+/*
+ * CVAdamsFinish
+ *
+ * This routine completes the calculation of the Adams l and tq.
+ */
+
+static void CVAdamsFinish(CVodeMem cv_mem, realtype m[], realtype M[], realtype hsum)
+{
+  int i;
+  realtype M0_inv, xi, xi_inv;
+  
+  M0_inv = ONE / M[0];
+  
+  l[0] = ONE;
+  for (i=1; i <= q; i++) l[i] = M0_inv * (m[i-1] / i);
+  xi = hsum / h;
+  xi_inv = ONE / xi;
+  
+  tq[2] = xi * M[0] / M[1];
+  tq[5] = xi / l[q];
+
+  if (qwait == 1) {
+    for (i=q; i >= 1; i--) m[i] += m[i-1] * xi_inv;
+    M[2] = CVAltSum(q, m, 2);
+    tq[3] = L * M[0] / M[2];
+  }
+
+  tq[4] = nlscoef * tq[2];
+}
+
+/*  
+ * CVAltSum
+ *
+ * CVAltSum returns the value of the alternating sum
+ *   sum (i= 0 ... iend) [ (-1)^i * (a[i] / (i + k)) ].
+ * If iend < 0 then CVAltSum returns 0.
+ * This operation is needed to compute the integral, from -1 to 0,
+ * of a polynomial x^(k-1) M(x) given the coefficients of M(x).
+ */
+
+static realtype CVAltSum(int iend, realtype a[], int k)
+{
+  int i, sign;
+  realtype sum;
+  
+  if (iend < 0) return(ZERO);
+  
+  sum = ZERO;
+  sign = 1;
+  for (i=0; i <= iend; i++) {
+    sum += sign * (a[i] / (i+k));
+    sign = -sign;
+  }
+  return(sum);
+}
+
+/*
+ * CVSetBDF
+ *
+ * This routine computes the coefficients l and tq in the case
+ * lmm == CV_BDF.  CVSetBDF calls CVSetTqBDF to set the test
+ * quantity array tq. 
+ * 
+ * The components of the array l are the coefficients of a
+ * polynomial Lambda(x) = l_0 + l_1 x + ... + l_q x^q, given by
+ *                                 q-1
+ * Lambda(x) = (1 + x / xi*_q) * PRODUCT (1 + x / xi_i) , where
+ *                                 i=1
+ *  xi_i = [t_n - t_(n-i)] / h.
+ *
+ * The array tq is set to test quantities used in the convergence
+ * test, the error test, and the selection of h at a new order.
+ */
+
+static void CVSetBDF(CVodeMem cv_mem)
+{
+  realtype alpha0, alpha0_hat, xi_inv, xistar_inv, hsum;
+  int i,j;
+  
+  l[0] = l[1] = xi_inv = xistar_inv = ONE;
+  for (i=2; i <= q; i++) l[i] = ZERO;
+  alpha0 = alpha0_hat = -ONE;
+  hsum = h;
+  if (q > 1) {
+    for (j=2; j < q; j++) {
+      hsum += tau[j-1];
+      xi_inv = h / hsum;
+      alpha0 -= ONE / j;
+      for (i=j; i >= 1; i--) l[i] += l[i-1]*xi_inv;
+      /* The l[i] are coefficients of product(1 to j) (1 + x/xi_i) */
+    }
+    
+    /* j = q */
+    alpha0 -= ONE / q;
+    xistar_inv = -l[1] - alpha0;
+    hsum += tau[q-1];
+    xi_inv = h / hsum;
+    alpha0_hat = -l[1] - xi_inv;
+    for (i=q; i >= 1; i--) l[i] += l[i-1]*xistar_inv;
+  }
+
+  CVSetTqBDF(cv_mem, hsum, alpha0, alpha0_hat, xi_inv, xistar_inv);
+}
+
+/*
+ * CVSetTqBDF
+ *
+ * This routine sets the test quantity array tq in the case
+ * lmm == CV_BDF.
+ */
+
+static void CVSetTqBDF(CVodeMem cv_mem, realtype hsum, realtype alpha0,
+                       realtype alpha0_hat, realtype xi_inv, realtype xistar_inv)
+{
+  realtype A1, A2, A3, A4, A5, A6;
+  realtype C, CPrime, CPrimePrime;
+  
+  A1 = ONE - alpha0_hat + alpha0;
+  A2 = ONE + q * A1;
+  tq[2] = ABS(alpha0 * (A2 / A1));
+  tq[5] = ABS((A2) / (l[q] * xi_inv/xistar_inv));
+  if (qwait == 1) {
+    C = xistar_inv / l[q];
+    A3 = alpha0 + ONE / q;
+    A4 = alpha0_hat + xi_inv;
+    CPrime = A3 / (ONE - A4 + A3);
+    tq[1] = ABS(CPrime / C);
+    hsum += tau[q];
+    xi_inv = h / hsum;
+    A5 = alpha0 - (ONE / (q+1));
+    A6 = alpha0_hat - xi_inv;
+    CPrimePrime = A2 / (ONE - A6 + A5);
+    tq[3] = ABS(CPrimePrime * xi_inv * (q+2) * A5);
+  }
+  tq[4] = nlscoef * tq[2];
+}
+
+/* 
+ * -----------------------------------------------------------------
+ * Nonlinear solver functions
+ * -----------------------------------------------------------------
+ */
+
+/*
+ * CVNls
+ *
+ * This routine attempts to solve the nonlinear system associated
+ * with a single implicit step of the linear multistep method.
+ * Depending on iter, it calls CVNlsFunctional or CVNlsNewton
+ * to do the work.
+ */
+
+static int CVNls(CVodeMem cv_mem, int nflag)
+{
+  int flag=CV_SUCCESS;
+
+  switch(iter) {
+  case CV_FUNCTIONAL: 
+    flag = CVNlsFunctional(cv_mem);
+    break;
+  case CV_NEWTON: 
+    flag = CVNlsNewton(cv_mem, nflag);
+    break;
+  }
+  
+  return(flag);
+
+}
+
+/*
+ * CVNlsFunctional
+ *
+ * This routine attempts to solve the nonlinear system using 
+ * functional iteration (no matrices involved).
+ * 
+ * This routine also handles the functional iteration of the
+ * combined system (states + sensitivities) when sensitivities are 
+ * computed using the CV_SIMULTANEOUS approach.
+ *
+ * Possible return values are:
+ *
+ *   CV_SUCCESS       ---> continue with error test
+ *
+ *   CV_RHSFUNC_FAIL  -+   
+ *   CV_SRHSFUNC_FAIL -+-> halt the integration 
+ *
+ *   CONV_FAIL        -+
+ *   RHSFUNC_RECVR     |-> predict again or stop if too many
+ *   SRHSFUNC_RECVR   -+
+ *
+ */
+
+static int CVNlsFunctional(CVodeMem cv_mem)
+{
+  int m;
+  realtype del, delS, Del, Delp, dcon;
+  int retval, is;
+  booleantype do_sensi_sim;
+  N_Vector wrk1, wrk2;
+
+  /* Are we computing sensitivities with the CV_SIMULTANEOUS approach? */
+  do_sensi_sim = (sensi && (ism==CV_SIMULTANEOUS));
+
+  /* Initialize counter and evaluate f at predicted y */
+  crate = ONE;
+  m = 0;
+
+  /* Initialize delS and Delp to avoid compiler warning message */
+  delS = Delp = ZERO;
+
+  retval = f(tn, zn[0], tempv, f_data);
+  nfe++;
+  if (retval < 0) return(CV_RHSFUNC_FAIL);
+  if (retval > 0) return(RHSFUNC_RECVR);
+
+  if (do_sensi_sim) {
+    wrk1 = ftemp;
+    wrk2 = ftempS[0];
+    retval = CVSensRhs(cv_mem, tn, zn[0], tempv, znS[0], tempvS, wrk1, wrk2);
+    if (retval < 0) return(CV_SRHSFUNC_FAIL);
+    if (retval > 0) return(SRHSFUNC_RECVR);
+  }
+
+  /* Initialize correction to zero */
+
+  N_VConst(ZERO, acor);
+  if (do_sensi_sim) {
+    for (is=0; is<Ns; is++)
+      N_VConst(ZERO,acorS[is]);
+  }
+
+  /* Loop until convergence; accumulate corrections in acor */
+
+  loop {
+
+    nni++;
+
+    /* Correct y directly from the last f value */
+
+    N_VLinearSum(h, tempv, -ONE, zn[1], tempv);
+    N_VScale(rl1, tempv, tempv);
+    N_VLinearSum(ONE, zn[0], ONE, tempv, y);
+
+    if (do_sensi_sim)
+      for (is=0; is<Ns; is++) {
+        N_VLinearSum(h, tempvS[is], -ONE, znS[1][is], tempvS[is]);
+        N_VScale(rl1, tempvS[is], tempvS[is]);
+        N_VLinearSum(ONE, znS[0][is], ONE, tempvS[is], yS[is]);
+      }
+    
+    /* Get WRMS norm of current correction to use in convergence test */
+
+    N_VLinearSum(ONE, tempv, -ONE, acor, acor);
+    if (do_sensi_sim)
+      for (is=0; is<Ns; is++)
+        N_VLinearSum(ONE, tempvS[is], -ONE, acorS[is], acorS[is]);
+
+    del = N_VWrmsNorm(acor, ewt);
+    if (do_sensi_sim)
+      delS = CVSensUpdateNorm(cv_mem, del, acorS, ewtS);
+
+    N_VScale(ONE, tempv, acor);
+    if (do_sensi_sim) 
+      for (is=0; is<Ns; is++)
+        N_VScale(ONE, tempvS[is], acorS[is]);
+    
+    /* Test for convergence.  If m > 0, an estimate of the convergence
+       rate constant is stored in crate, and used in the test. 
+
+       Recall that, even when errconS=FALSE, all variables are used in the
+       convergence test. Hence, we use Del (and not del). However, acnrm
+       is used in the error test and thus it has different forms
+       depending on errconS (and this explains why we have to carry around
+       del and delS)
+    */
+    
+    Del = (do_sensi_sim) ? delS : del;
+    if (m > 0) crate = MAX(CRDOWN * crate, Del / Delp);
+    dcon = Del * MIN(ONE, crate) / tq[4];
+
+    if (dcon <= ONE) {
+      if (m == 0)
+        if (do_sensi_sim && errconS) acnrm = delS;
+        else                         acnrm = del;
+      else {
+        acnrm = N_VWrmsNorm(acor, ewt);
+        if (do_sensi_sim && errconS)
+          acnrm = CVSensUpdateNorm(cv_mem, acnrm, acorS, ewtS);
+      }
+      return(CV_SUCCESS);  /* Convergence achieved */
+    }
+
+    /* Stop at maxcor iterations or if iter. seems to be diverging */
+
+    m++;
+    if ((m==maxcor) || ((m >= 2) && (Del > RDIV * Delp))) return(CONV_FAIL);
+
+    /* Save norm of correction, evaluate f, and loop again */
+
+    Delp = Del;
+
+    retval = f(tn, y, tempv, f_data);
+    nfe++;
+    if (retval < 0) return(CV_RHSFUNC_FAIL);
+    if (retval > 0) return(RHSFUNC_RECVR);
+
+    if (do_sensi_sim) {
+      wrk1 = ftemp;
+      wrk2 = ftempS[0];
+      retval = CVSensRhs(cv_mem, tn, y, tempv, yS, tempvS, wrk1, wrk2);
+      if (retval < 0) return(CV_SRHSFUNC_FAIL);
+      if (retval > 0) return(SRHSFUNC_RECVR);
+    }      
+
+  } /* end loop */
+
+}
+
+/*
+ * CVNlsNewton
+ *
+ * This routine handles the Newton iteration. It calls lsetup if 
+ * indicated, calls CVNewtonIteration to perform the iteration, and 
+ * retries a failed attempt at Newton iteration if that is indicated.
+ * See return values at top of this file.
+ *
+ * This routine also handles the Newton iteration of the combined 
+ * system when sensitivities are computed using the CV_SIMULTANEOUS
+ * approach. Since in that case we use a quasi-Newton on the 
+ * combined system (by approximating the Jacobian matrix by its
+ * block diagonal) and thus only solve linear systems with 
+ * multiple right hand sides (all sharing the same coefficient
+ * matrix - whatever iteration matrix we decide on) we set-up
+ * the linear solver to handle N equations at a time.
+ *
+ * Possible return values:
+ *
+ *   CV_SUCCESS       ---> continue with error test
+ *
+ *   CV_RHSFUNC_FAIL  -+  
+ *   CV_LSETUP_FAIL    |
+ *   CV_LSOLVE_FAIL    |-> halt the integration 
+ *   CV_SRHSFUNC_FAIL -+
+ *
+ *   CONV_FAIL        -+
+ *   RHSFUNC_RECVR     |-> predict again or stop if too many
+ *   SRHSFUNC_RECVR   -+
+ *
+ */
+
+static int CVNlsNewton(CVodeMem cv_mem, int nflag)
+{
+  N_Vector vtemp1, vtemp2, vtemp3, wrk1, wrk2;
+  int convfail, ier;
+  booleantype callSetup, do_sensi_sim;
+  int retval, is;
+  
+  /* Are we computing sensitivities with the CV_SIMULTANEOUS approach? */
+  do_sensi_sim = (sensi && (ism==CV_SIMULTANEOUS));
+
+  vtemp1 = acor;  /* rename acor as vtemp1 for readability  */
+  vtemp2 = y;     /* rename y as vtemp2 for readability     */
+  vtemp3 = tempv; /* rename tempv as vtemp3 for readability */
+  
+  /* Set flag convfail, input to lsetup for its evaluation decision */
+  convfail = ((nflag == FIRST_CALL) || (nflag == PREV_ERR_FAIL)) ?
+    CV_NO_FAILURES : CV_FAIL_OTHER;
+
+  /* Decide whether or not to call setup routine (if one exists) */
+  if (setupNonNull) {      
+    callSetup = (nflag == PREV_CONV_FAIL) || (nflag == PREV_ERR_FAIL) ||
+      (nst == 0) || (nst >= nstlp + MSBP) || (ABS(gamrat-ONE) > DGMAX);
+
+    /* Decide whether to force a call to setup */
+    if (forceSetup) {
+      callSetup = TRUE;
+      convfail = CV_FAIL_OTHER;
+    }
+
+  } else {  
+    crate = ONE;
+    crateS = ONE;  /* if NO lsetup all conv. rates are set to ONE */
+    callSetup = FALSE;
+  }
+  
+  /* Looping point for the solution of the nonlinear system.
+     Evaluate f at the predicted y, call lsetup if indicated, and
+     call CVNewtonIteration for the Newton iteration itself.      */
+
+  loop {
+
+    retval = f(tn, zn[0], ftemp, f_data);
+    nfe++; 
+    if (retval < 0) return(CV_RHSFUNC_FAIL);
+    if (retval > 0) return(RHSFUNC_RECVR);
+
+    if (do_sensi_sim) {
+      wrk1 = tempv;
+      wrk2 = tempvS[0];
+      retval = CVSensRhs(cv_mem, tn, zn[0], ftemp, znS[0], ftempS, wrk1, wrk2);
+      if (retval < 0) return(CV_SRHSFUNC_FAIL);
+      if (retval > 0) return(SRHSFUNC_RECVR);
+    }
+
+    if (callSetup) {
+      ier = lsetup(cv_mem, convfail, zn[0], ftemp, &jcur, 
+                   vtemp1, vtemp2, vtemp3);
+      nsetups++;
+      callSetup = FALSE;
+      forceSetup = FALSE;
+      gamrat = ONE; 
+      gammap = gamma;
+      crate = ONE;
+      crateS = ONE; /* after lsetup all conv. rates are reset to ONE */
+      nstlp = nst;
+      /* Return if lsetup failed */
+      if (ier < 0) return(CV_LSETUP_FAIL);
+      if (ier > 0) return(CONV_FAIL);
+    }
+
+    /* Set acor to zero and load prediction into y vector */
+    N_VConst(ZERO, acor);
+    N_VScale(ONE, zn[0], y);
+
+    if (do_sensi_sim)
+      for (is=0; is<Ns; is++) {
+        N_VConst(ZERO, acorS[is]);
+        N_VScale(ONE, znS[0][is], yS[is]);
+      }
+
+    /* Do the Newton iteration */
+    ier = CVNewtonIteration(cv_mem);
+
+    /* If there is a convergence failure and the Jacobian-related 
+       data appears not to be current, loop again with a call to lsetup
+       in which convfail=CV_FAIL_BAD_J.  Otherwise return.                 */
+    if (ier != TRY_AGAIN) return(ier);
+    
+    callSetup = TRUE;
+    convfail = CV_FAIL_BAD_J;
+  }
+}
+
+/*
+ * CVNewtonIteration
+ *
+ * This routine performs the Newton iteration. If the iteration succeeds,
+ * it returns the value CV_SUCCESS. If not, it may signal the CVNlsNewton 
+ * routine to call lsetup again and reattempt the iteration, by
+ * returning the value TRY_AGAIN. (In this case, CVNlsNewton must set 
+ * convfail to CV_FAIL_BAD_J before calling setup again). 
+ * Otherwise, this routine returns one of the appropriate values 
+ * CV_LSOLVE_FAIL, CV_RHSFUNC_FAIL, CV_SRHSFUNC_FAIL, CONV_FAIL,
+ * RHSFUNC_RECVR, or SRHSFUNC_RECVR back to CVNlsNewton.
+ *
+ * If sensitivities are computed using the CV_SIMULTANEOUS approach, this
+ * routine performs a quasi-Newton on the combined nonlinear system.
+ * The iteration matrix of the combined system is block diagonal with
+ * each block being the iteration matrix of the original system. Thus
+ * we solve linear systems with the same matrix but different right
+ * hand sides.
+ */
+
+static int CVNewtonIteration(CVodeMem cv_mem)
+{
+  int m;
+  realtype del, delS, Del, Delp, dcon;
+  N_Vector b, *bS=NULL, wrk1, wrk2;
+  booleantype do_sensi_sim;
+  int retval, is;
+  
+  /* Are we computing sensitivities with the CV_SIMULTANEOUS approach? */
+  do_sensi_sim = (sensi && (ism==CV_SIMULTANEOUS));
+
+  mnewt = m = 0;
+
+  /* Initialize delS and Delp to avoid compiler warning message */
+  delS = Delp = ZERO;
+
+  /* At this point, ftemp  <- f(t_n, y_n(0))
+     ftempS <- fS(t_n, y_n(0), s_n(0))
+     acor   <- 0
+     acorS  <- 0
+     y      <- y_n(0)
+     yS     <- yS_n(0)                 */
+
+  /* Looping point for Newton iteration */
+  loop {
+    
+    /* Evaluate the residual of the nonlinear system */
+    N_VLinearSum(rl1, zn[1], ONE, acor, tempv);
+    N_VLinearSum(gamma, ftemp, -ONE, tempv, tempv);
+
+    /* Call the lsolve function */
+    b = tempv;
+
+    retval = lsolve(cv_mem, b, ewt, y, ftemp); 
+    nni++;
+
+    if (retval < 0) return(CV_LSOLVE_FAIL);
+    
+    /* If lsolve had a recoverable failure and Jacobian data is
+       not current, signal to try the solution again            */
+    if (retval > 0) { 
+      if ((!jcur) && (setupNonNull)) return(TRY_AGAIN);
+      else                           return(CONV_FAIL);
+    }
+
+    /* Solve the sensitivity linear systems and do the same 
+       tests on the return value of lsolve. */
+ 
+    if (do_sensi_sim) {
+
+      for (is=0; is<Ns; is++) {
+        N_VLinearSum(rl1, znS[1][is], ONE, acorS[is], tempvS[is]);
+        N_VLinearSum(gamma, ftempS[is], -ONE, tempvS[is], tempvS[is]);
+      }
+      bS = tempvS;
+      for (is=0; is<Ns; is++) {
+        retval = lsolve(cv_mem, bS[is], ewtS[is], y, ftemp);
+        if (retval < 0) return(CV_LSOLVE_FAIL);
+        if (retval > 0) { 
+          if ((!jcur) && (setupNonNull)) return(TRY_AGAIN);
+          else                           return(CONV_FAIL);
+        }
+      }
+    }
+    
+    /* Get WRMS norm of correction; add correction to acor and y */
+
+    del = N_VWrmsNorm(b, ewt);
+    N_VLinearSum(ONE, acor, ONE, b, acor);
+    N_VLinearSum(ONE, zn[0], ONE, acor, y);
+
+    if (do_sensi_sim) {
+      delS = CVSensUpdateNorm(cv_mem, del, bS, ewtS);
+      for (is=0; is<Ns; is++) {
+        N_VLinearSum(ONE, acorS[is], ONE, bS[is], acorS[is]);
+        N_VLinearSum(ONE, znS[0][is], ONE, acorS[is], yS[is]);
+      }
+    }
+
+    /* Test for convergence.  If m > 0, an estimate of the convergence
+       rate constant is stored in crate, and used in the test.        */
+
+    Del = (do_sensi_sim) ? delS : del;
+    if (m > 0) crate = MAX(CRDOWN * crate, Del/Delp);
+    dcon = Del * MIN(ONE, crate) / tq[4];
+    
+    if (dcon <= ONE) {
+      if (m == 0)
+        if (do_sensi_sim && errconS) acnrm = delS;
+        else                         acnrm = del;
+      else {
+        acnrm = N_VWrmsNorm(acor, ewt);
+        if (do_sensi_sim && errconS)
+          acnrm = CVSensUpdateNorm(cv_mem, acnrm, acorS, ewtS);
+      }
+      jcur = FALSE;
+      return(CV_SUCCESS);  /* Convergence achieved */
+    }
+
+    mnewt = ++m;
+    
+    /* Stop at maxcor iterations or if iter. seems to be diverging.
+       If still not converged and Jacobian data is not current, 
+       signal to try the solution again                            */
+    if ((m == maxcor) || ((m >= 2) && (Del > RDIV * Delp))) {
+      if ((!jcur) && (setupNonNull)) return(TRY_AGAIN);
+      else                           return(CONV_FAIL);
+    }
+    
+    /* Save norm of correction, evaluate f, and loop again */
+    Delp = Del;
+    retval = f(tn, y, ftemp, f_data);
+    nfe++;
+    if (retval < 0) return(CV_RHSFUNC_FAIL);
+    if (retval > 0) {
+      if ((!jcur) && (setupNonNull)) return(TRY_AGAIN);
+      else                           return(RHSFUNC_RECVR);
+    }
+
+    if (do_sensi_sim) {
+      wrk1 = tempv;
+      wrk2 = tempvS[0];
+      retval = CVSensRhs(cv_mem, tn, y, ftemp, yS, ftempS, wrk1, wrk2);
+      if (retval < 0) return(CV_SRHSFUNC_FAIL);
+      if (retval > 0) {
+        if ((!jcur) && (setupNonNull)) return(TRY_AGAIN);
+        else                           return(SRHSFUNC_RECVR);
+      }
+    }
+
+  } /* end loop */
+
+}
+
+/*
+ * CVQuadNls
+ * 
+ * This routine solves for the quadrature variables at the new step.
+ * It does not solve a nonlinear system, but rather updates the
+ * quadrature variables. The name for this function is just for 
+ * uniformity purposes.
+ *
+ * Possible return values (interpreted by CVHandleNFlag)
+ *
+ *   CV_SUCCESS       -> continue with error test
+ *   CV_QRHSFUNC_FAIL -> halt the integration 
+ *   QRHSFUNC_RECVR   -> predict again or stop if too many
+ *   
+ */
+
+static int CVQuadNls(CVodeMem cv_mem)
+{
+  int retval;
+
+  /* Save quadrature correction in acorQ */
+  retval = fQ(tn, y, acorQ, fQ_data);
+  nfQe++;
+  if (retval < 0) return(CV_QRHSFUNC_FAIL);
+  if (retval > 0) return(QRHSFUNC_RECVR);
+
+  N_VLinearSum(h, acorQ, -ONE, znQ[1], acorQ);
+  N_VScale(rl1, acorQ, acorQ);
+
+  /* Apply correction to quadrature variables */
+  N_VLinearSum(ONE, znQ[0], ONE, acorQ, yQ);
+
+  return(CV_SUCCESS);
+}
+
+/*
+ * CVStgrNls
+ *
+ * This is a high-level routine that attempts to solve the 
+ * sensitivity linear systems using nonlinear iterations (CV_FUNCTIONAL
+ * or CV_NEWTON - depending on the value of iter) once the states y_n
+ * were obtained and passed the error test.
+ */
+
+static int CVStgrNls(CVodeMem cv_mem)
+{
+  int flag=CV_SUCCESS;
+
+  switch(iter) {
+  case CV_FUNCTIONAL: 
+    flag = CVStgrNlsFunctional(cv_mem);
+    break;
+  case CV_NEWTON:     
+    flag = CVStgrNlsNewton(cv_mem);
+    break;
+  }
+
+  return(flag);
+
+}
+
+/*
+ * CVStgrNlsfunctional
+ *
+ * This routine attempts to solve the sensitivity linear systems 
+ * using functional iteration (no matrices involved).
+ *
+ * Possible return values:
+ *  CV_SUCCESS,
+ *  CV_SRHSFUNC_FAIL,
+ *  CONV_FAIL, SRHSFUNC_RECVR
+ */
+
+static int CVStgrNlsFunctional(CVodeMem cv_mem)
+{
+  int m;
+  int retval, is;
+  realtype Del, Delp, dcon;
+  N_Vector wrk1, wrk2;
+
+  /* Initialize estimated conv. rate and counter */
+  crateS = ONE;
+  m = 0;
+
+  /* Initialize Delp to avoid compiler warning message */
+  Delp = ZERO;
+
+  /* Evaluate fS at predicted yS but with converged y (and corresponding f) */
+  wrk1 = tempv;
+  wrk2 = ftempS[0];
+  retval = CVSensRhs(cv_mem, tn, y, ftemp, znS[0], tempvS, wrk1, wrk2);
+  if (retval < 0) return(CV_SRHSFUNC_FAIL);
+  if (retval > 0) return(SRHSFUNC_RECVR);
+
+  /* Initialize correction to zero */
+  for (is=0; is<Ns; is++)
+    N_VConst(ZERO,acorS[is]);
+
+  /* Loop until convergence; accumulate corrections in acorS */
+
+  loop {
+    
+    nniS++;
+    
+    /* Correct yS from last fS value */
+    for (is=0; is<Ns; is++) {
+      N_VLinearSum(h, tempvS[is], -ONE, znS[1][is], tempvS[is]);
+      N_VScale(rl1, tempvS[is], tempvS[is]);
+      N_VLinearSum(ONE, znS[0][is], ONE, tempvS[is], yS[is]);
+    }
+    /* Get norm of current correction to use in convergence test */
+    for (is=0; is<Ns; is++)
+      N_VLinearSum(ONE, tempvS[is], -ONE, acorS[is], acorS[is]);
+    Del = CVSensNorm(cv_mem, acorS, ewtS);
+    for (is=0; is<Ns; is++)
+      N_VScale(ONE, tempvS[is], acorS[is]);
+
+    /* Test for convergence.  If m > 0, an estimate of the convergence
+       rate constant is stored in crateS, and used in the test. 
+       acnrmS contains the norm of the corrections (yS_n-yS_n(0)) and
+       will be used in the error test (if errconS==TRUE)              */
+    if (m > 0) crateS = MAX(CRDOWN * crateS, Del / Delp);
+    dcon = Del * MIN(ONE, crateS) / tq[4];
+    
+    if (dcon <= ONE) {
+      if (errconS)
+        acnrmS = (m==0)? Del : CVSensNorm(cv_mem, acorS, ewtS);
+      return(CV_SUCCESS);  /* Convergence achieved */
+    }
+
+    /* Stop at maxcor iterations or if iter. seems to be diverging */
+    m++;
+    if ((m==maxcorS) || ((m >= 2) && (Del > RDIV * Delp))) return(CONV_FAIL);
+
+    /* Save norm of correction, evaluate f, and loop again */
+    Delp = Del;
+
+    wrk1 = tempv;
+    wrk2 = ftempS[0];
+    retval = CVSensRhs(cv_mem, tn, y, ftemp, yS, tempvS, wrk1, wrk2);
+    if (retval < 0) return(CV_SRHSFUNC_FAIL);
+    if (retval > 0) return(SRHSFUNC_RECVR);
+
+  } /* end loop */
+  
+}
+
+/*
+ * CVStgrNlsNewton
+ *
+ * This routine attempts to solve the sensitivity linear systems using 
+ * Newton iteration. It calls CVStgrNlsNewton to perform the actual 
+ * iteration. If the Newton iteration fails with out-of-date Jacobian 
+ * data (ier=TRY_AGAIN), it calls lsetup and retries the Newton iteration. 
+ * This second try is unlikely to happen when using a Krylov linear solver.
+ *
+ * Possible return values:
+ *
+ *   CV_SUCCESS
+ *
+ *   CV_LSOLVE_FAIL   -+
+ *   CV_LSETUP_FAIL    |
+ *   CV_SRHSFUNC_FAIL -+
+ *
+ *   CONV_FAIL        -+
+ *   SRHSFUNC_RECVR   -+
+ */
+
+static int CVStgrNlsNewton(CVodeMem cv_mem)
+{
+  int retval, is;
+  int convfail, ier;
+  N_Vector vtemp1, vtemp2, vtemp3, wrk1, wrk2;
+
+  loop {
+
+    /* Set acorS to zero and load prediction into yS vector */
+    for (is=0; is<Ns; is++) {
+      N_VConst(ZERO, acorS[is]);
+      N_VScale(ONE, znS[0][is], yS[is]);
+    }
+ 
+    /* Evaluate fS at predicted yS but with converged y (and corresponding f) */
+    wrk1 = tempv;
+    wrk2 = tempvS[0];
+    retval = CVSensRhs(cv_mem, tn, y, ftemp, yS, ftempS, wrk1, wrk2);
+    if (retval < 0) return(CV_SRHSFUNC_FAIL);
+    if (retval > 0) return(SRHSFUNC_RECVR);
+
+    /* Do the Newton iteration */
+    ier = CVStgrNewtonIteration(cv_mem);
+
+    /* If the solve was successful (ier=CV_SUCCESS) or if an error 
+       that cannot be fixed by a call to lsetup occured
+       (ier = CV_LSOLVE_FAIL or CONV_FAIL) return */
+    if (ier != TRY_AGAIN) return(ier);
+
+    /* There was a convergence failure and the Jacobian-related data
+       appears not to be current. Call lsetup with convfail=CV_FAIL_BAD_J
+       and then loop again */
+    convfail = CV_FAIL_BAD_J;
+
+    /* Rename some vectors for readibility */
+    vtemp1 = tempv;
+    vtemp2 = yS[0];
+    vtemp3 = ftempS[0];
+
+    /* Call linear solver setup at converged y */
+    ier = lsetup(cv_mem, convfail, y, ftemp, &jcur, 
+                 vtemp1, vtemp2, vtemp3);
+    nsetups++;
+    nsetupsS++;
+    gamrat = ONE;
+    gammap = gamma;
+    crate = ONE;
+    crateS = ONE; /* after lsetup all conv. rates are reset to ONE */
+    nstlp = nst;
+
+    /* Return if lsetup failed */
+    if (ier < 0) return(CV_LSETUP_FAIL);
+    if (ier > 0) return(CONV_FAIL);
+
+  } /* end loop */
+
+}
+
+/*
+ * CVstgrNewtonIteration
+ *
+ * This routine performs the Newton iteration for all sensitivities. 
+ * If the iteration succeeds, it returns the value CV_SUCCESS. 
+ * If not, it may signal the CVStgrNlsNewton routine to call lsetup and 
+ * reattempt the iteration, by returning the value TRY_AGAIN. (In this case, 
+ * CVStgrNlsNewton must set convfail to CV_FAIL_BAD_J before calling setup again). 
+ * Otherwise, this routine returns one of the appropriate values 
+ * CV_LSOLVE_FAIL or CONV_FAIL back to CVStgrNlsNewton.
+ */
+
+static int CVStgrNewtonIteration(CVodeMem cv_mem)
+{
+  int m, retval;
+  realtype Del, Delp, dcon;
+  N_Vector *bS, wrk1, wrk2;
+  int is;
+
+  m = 0;
+
+  /* Initialize Delp to avoid compiler warning message */
+  Delp = ZERO;
+
+  /* ftemp  <- f(t_n, y_n)
+     y      <- y_n
+     ftempS <- fS(t_n, y_n(0), s_n(0))
+     acorS  <- 0
+     yS     <- yS_n(0)                   */
+
+  loop {
+
+    /* Evaluate the residual of the nonlinear systems */
+    for (is=0; is<Ns; is++) {
+      N_VLinearSum(rl1, znS[1][is], ONE, acorS[is], tempvS[is]);
+      N_VLinearSum(gamma, ftempS[is], -ONE, tempvS[is], tempvS[is]);
+    }
+
+    /* Call the lsolve function */
+    bS = tempvS;
+    nniS++;
+    for (is=0; is<Ns; is++) {
+
+      retval = lsolve(cv_mem, bS[is], ewtS[is], y, ftemp);
+
+      /* Unrecoverable error in lsolve */
+      if (retval < 0) return(CV_LSOLVE_FAIL);
+
+      /* Recoverable error in lsolve and Jacobian data not current */
+      if (retval > 0) { 
+        if ((!jcur) && (setupNonNull)) return(TRY_AGAIN);
+        else                           return(CONV_FAIL);
+      }
+
+    }
+ 
+    /* Get norm of correction; add correction to acorS and yS */
+    Del = CVSensNorm(cv_mem, bS, ewtS);
+    for (is=0; is<Ns; is++) {
+      N_VLinearSum(ONE, acorS[is], ONE, bS[is], acorS[is]);
+      N_VLinearSum(ONE, znS[0][is], ONE, acorS[is], yS[is]);
+    }
+
+    /* Test for convergence.  If m > 0, an estimate of the convergence
+       rate constant is stored in crateS, and used in the test.        */
+    if (m > 0) crateS = MAX(CRDOWN * crateS, Del/Delp);
+    dcon = Del * MIN(ONE, crateS) / tq[4];
+    if (dcon <= ONE) {
+      if (errconS)
+        acnrmS = (m==0) ? Del : CVSensNorm(cv_mem, acorS, ewtS);
+      jcur = FALSE;
+      return(CV_SUCCESS);  /* Convergence achieved */
+    }
+
+    m++;
+
+    /* Stop at maxcor iterations or if iter. seems to be diverging.
+       If still not converged and Jacobian data is not current, 
+       signal to try the solution again                            */
+    if ((m == maxcorS) || ((m >= 2) && (Del > RDIV * Delp))) {
+      if ((!jcur) && (setupNonNull)) return(TRY_AGAIN);
+      else                           return(CONV_FAIL);
+    }
+    
+    /* Save norm of correction, evaluate fS, and loop again */
+    Delp = Del;
+    
+    wrk1 = tempv;
+    wrk2 = tempvS[0];
+    retval = CVSensRhs(cv_mem, tn, y, ftemp, yS, ftempS, wrk1, wrk2);
+    if (retval < 0) return(CV_SRHSFUNC_FAIL);
+    if (retval > 0) {
+      if ((!jcur) && (setupNonNull)) return(TRY_AGAIN);
+      else                           return(SRHSFUNC_RECVR);
+    }
+
+  } /* end loop */
+
+}
+
+/*
+ * CVStgr1Nls
+ *
+ * This is a high-level routine that attempts to solve the i-th 
+ * sensitivity linear system using nonlinear iterations (CV_FUNCTIONAL
+ * or CV_NEWTON - depending on the value of iter) once the states y_n
+ * were obtained and passed the error test.
+ */
+
+static int CVStgr1Nls(CVodeMem cv_mem, int is)
+{
+  int flag=CV_SUCCESS;
+
+  switch(iter) {
+  case CV_FUNCTIONAL: 
+    flag = CVStgr1NlsFunctional(cv_mem,is);
+    break;
+  case CV_NEWTON:     
+    flag = CVStgr1NlsNewton(cv_mem,is);
+    break;
+  }
+
+  return(flag);
+
+}
+
+/*
+ * CVStgr1NlsFunctional
+ *
+ * This routine attempts to solve the i-th sensitivity linear system
+ * using functional iteration (no matrices involved).
+ *
+ * Possible return values:
+ *   CV_SUCCESS,
+ *   CV_SRHSFUNC_FAIL,
+ *   CONV_FAIL, SRHSFUNC_RECVR
+ */
+
+static int CVStgr1NlsFunctional(CVodeMem cv_mem, int is)
+{
+  int retval, m;
+  realtype Del, Delp, dcon;
+  N_Vector wrk1, wrk2;
+
+  /* Initialize estimated conv. rate and counter */
+  crateS = ONE;
+  m = 0;
+
+  /* Initialize Delp to avoid compiler warning message */
+  Delp = ZERO;
+
+  /* Evaluate fS at predicted yS but with converged y (and corresponding f) */
+  wrk1 = tempv;
+  wrk2 = ftempS[0];
+  retval = CVSensRhs1(cv_mem, tn, y, ftemp, is, znS[0][is], tempvS[is], wrk1, wrk2);
+  if (retval < 0) return(CV_SRHSFUNC_FAIL);
+  if (retval > 0) return(SRHSFUNC_RECVR);
+
+  /* Initialize correction to zero */
+  N_VConst(ZERO,acorS[is]);
+
+  /* Loop until convergence; accumulate corrections in acorS */
+
+  loop {
+
+    nniS1[is]++;
+
+    /* Correct yS from last fS value */
+    N_VLinearSum(h, tempvS[is], -ONE, znS[1][is], tempvS[is]);
+    N_VScale(rl1, tempvS[is], tempvS[is]);
+    N_VLinearSum(ONE, znS[0][is], ONE, tempvS[is], yS[is]);
+
+    /* Get WRMS norm of current correction to use in convergence test */
+    N_VLinearSum(ONE, tempvS[is], -ONE, acorS[is], acorS[is]);
+    Del = N_VWrmsNorm(acorS[is], ewtS[is]);
+    N_VScale(ONE, tempvS[is], acorS[is]);
+
+    /* Test for convergence.  If m > 0, an estimate of the convergence
+       rate constant is stored in crateS, and used in the test. */
+
+    if (m > 0) crateS = MAX(CRDOWN * crateS, Del / Delp);
+    dcon = Del * MIN(ONE, crateS) / tq[4];
+
+    if (dcon <= ONE) {
+      return(CV_SUCCESS);  /* Convergence achieved */
+    }
+
+    /* Stop at maxcor iterations or if iter. seems to be diverging */
+    m++;
+    if ((m==maxcorS) || ((m >= 2) && (Del > RDIV * Delp))) return(CONV_FAIL);
+
+    /* Save norm of correction, evaluate f, and loop again */
+    Delp = Del;
+
+    wrk1 = tempv;
+    wrk2 = ftempS[0];
+
+    retval = CVSensRhs1(cv_mem, tn, y, ftemp, is, yS[is], tempvS[is], wrk1, wrk2);
+    if (retval < 0) return(CV_SRHSFUNC_FAIL);
+    if (retval > 0) return(SRHSFUNC_RECVR);
+
+  } /* end loop */
+  
+}
+
+/*
+ * CVStgr1NlsNewton
+ *
+ * This routine attempts to solve the i-th sensitivity linear system 
+ * using Newton iteration. It calls CVStgr1NlsNewton to perform the 
+ * actual iteration. If the Newton iteration fails with out-of-date 
+ * Jacobian data (ier=TRY_AGAIN), it calls lsetup and retries the 
+ * Newton iteration. This second try is unlikely to happen when 
+ * using a Krylov linear solver.
+ *
+ * Possible return values:
+ *
+ *   CV_SUCCESS
+ *
+ *   CV_LSOLVE_FAIL
+ *   CV_LSETUP_FAIL
+ *   CV_SRHSFUNC_FAIL
+ *
+ *   CONV_FAIL
+ *   SRHSFUNC_RECVR
+ */
+
+static int CVStgr1NlsNewton(CVodeMem cv_mem, int is)
+{
+  int convfail, retval, ier;
+  N_Vector vtemp1, vtemp2, vtemp3, wrk1, wrk2;
+
+  loop {
+
+    /* Set acorS to zero and load prediction into yS vector */
+    N_VConst(ZERO, acorS[is]);
+    N_VScale(ONE, znS[0][is], yS[is]);
+ 
+    /* Evaluate fS at predicted yS but with converged y (and corresponding f) */
+    wrk1 = tempv;
+    wrk2 = tempvS[0];
+    retval = CVSensRhs1(cv_mem, tn, y, ftemp, is, yS[is], ftempS[is], wrk1, wrk2);
+    if (retval < 0) return(CV_SRHSFUNC_FAIL);
+    if (retval > 0) return(SRHSFUNC_RECVR);
+  
+    /* Do the Newton iteration */
+    ier = CVStgr1NewtonIteration(cv_mem, is);
+
+    /* If the solve was successful (ier=CV_SUCCESS) or if an error 
+       that cannot be fixed by a call to lsetup occured
+       (ier = CV_LSOLVE_FAIL or CONV_FAIL) return */
+    if (ier != TRY_AGAIN) return(ier);
+
+    /* There was a convergence failure and the Jacobian-related data
+       appears not to be current. Call lsetup with convfail=CV_FAIL_BAD_J
+       and then loop again */
+    convfail = CV_FAIL_BAD_J;
+
+    /* Rename some vectors for readibility */
+    vtemp1 = tempv;
+    vtemp2 = yS[0];
+    vtemp3 = ftempS[0];
+
+    /* Call linear solver setup at converged y */
+    ier = lsetup(cv_mem, convfail, y, ftemp, &jcur, 
+                 vtemp1, vtemp2, vtemp3);
+    nsetups++;
+    nsetupsS++;
+    gamrat = ONE;
+    crate = ONE;
+    crateS = ONE; /* after lsetup all conv. rates are reset to ONE */
+    gammap = gamma;
+    nstlp = nst;
+
+    /* Return if lsetup failed */
+    if (ier < 0) return(CV_LSETUP_FAIL);
+    if (ier > 0) return(CONV_FAIL);
+
+  } /* end loop */
+
+}
+
+/*
+ * CVStgr1NewtonIteration
+ *
+ * This routine performs the Newton iteration for the i-th sensitivity. 
+ * If the iteration succeeds, it returns the value CV_SUCCESS. 
+ * If not, it may signal the CVStgr1NlsNewton routine to call lsetup 
+ * and reattempt the iteration, by returning the value TRY_AGAIN. 
+ * (In this case, CVStgr1NlsNewton must set convfail to CV_FAIL_BAD_J 
+ * before calling setup again). Otherwise, this routine returns one 
+ * of the appropriate values CV_LSOLVE_FAIL or CONV_FAIL back to 
+ * CVStgr1NlsNewton.
+ */
+
+static int CVStgr1NewtonIteration(CVodeMem cv_mem, int is)
+{
+  int m, retval;
+  realtype Del, Delp, dcon;
+  N_Vector *bS, wrk1, wrk2;
+
+  m = 0;
+
+  /* Initialize Delp to avoid compiler warning message */
+  Delp = ZERO;
+
+  /* ftemp      <- f(t_n, y_n)
+     y          <- y_n
+     ftempS[is] <- fS(is, t_n, y_n(0), s_n(0))
+     acorS[is]  <- 0
+     yS[is]     <- yS_n(0)[is]                 */
+
+  loop {
+
+    /* Evaluate the residual of the nonlinear systems */
+    N_VLinearSum(rl1, znS[1][is], ONE, acorS[is], tempvS[is]);
+    N_VLinearSum(gamma, ftempS[is], -ONE, tempvS[is], tempvS[is]);
+
+    /* Call the lsolve function */
+    bS = tempvS;
+
+    nniS1[is]++;
+
+    retval = lsolve(cv_mem, bS[is], ewtS[is], y, ftemp);
+
+    /* Unrecoverable error in lsolve */
+    if (retval < 0) return(CV_LSOLVE_FAIL);
+
+    /* Recoverable error in lsolve and Jacobian data not current */
+    if (retval > 0) { 
+      if ((!jcur) && (setupNonNull)) return(TRY_AGAIN);
+      else                           return(CONV_FAIL);
+    }
+
+    /* Get norm of correction; add correction to acorS and yS */
+    Del = N_VWrmsNorm(bS[is], ewtS[is]);
+    N_VLinearSum(ONE, acorS[is], ONE, bS[is], acorS[is]);
+    N_VLinearSum(ONE, znS[0][is], ONE, acorS[is], yS[is]);
+
+    /* Test for convergence.  If m > 0, an estimate of the convergence
+       rate constant is stored in crateS, and used in the test.        */
+    if (m > 0) crateS = MAX(CRDOWN * crateS, Del/Delp);
+    dcon = Del * MIN(ONE, crateS) / tq[4];
+    if (dcon <= ONE) {
+      jcur = FALSE;
+      return(CV_SUCCESS);  /* Convergence achieved */
+    }
+
+    m++;
+
+    /* Stop at maxcor iterations or if iter. seems to be diverging.
+       If still not converged and Jacobian data is not current, 
+       signal to try the solution again                            */
+    if ((m == maxcorS) || ((m >= 2) && (Del > RDIV * Delp))) {
+      if ((!jcur) && (setupNonNull)) return(TRY_AGAIN);
+      else                           return(CONV_FAIL);
+    }
+
+    /* Save norm of correction, evaluate fS, and loop again */
+    Delp = Del;
+
+    wrk1 = tempv;
+    wrk2 = tempvS[0];
+    retval = CVSensRhs1(cv_mem, tn, y, ftemp, is, yS[is], ftempS[is], wrk1, wrk2);
+    if (retval < 0) return(CV_SRHSFUNC_FAIL);
+    if (retval > 0) {
+      if ((!jcur) && (setupNonNull)) return(TRY_AGAIN);
+      else                           return(SRHSFUNC_RECVR);
+    }
+
+  } /* end loop */
+
+}
+
+/*
+ * CVHandleNFlag
+ *
+ * This routine takes action on the return value nflag = *nflagPtr
+ * returned by CVNls, as follows:
+ *
+ * If CVNls succeeded in solving the nonlinear system, then
+ * CVHandleNFlag returns the constant DO_ERROR_TEST, which tells CVStep
+ * to perform the error test.
+ *
+ * If the nonlinear system was not solved successfully, then ncfn and
+ * ncf = *ncfPtr are incremented and Nordsieck array zn is restored.
+ *
+ * If the solution of the nonlinear system failed due to an
+ * unrecoverable failure by setup, we return the value CV_LSETUP_FAIL.
+ * 
+ * If it failed due to an unrecoverable failure in solve, then we return
+ * the value CV_LSOLVE_FAIL.
+ *
+ * If it failed due to an unrecoverable failure in rhs, then we return
+ * the value CV_RHSFUNC_FAIL.
+ *
+ * If it failed due to an unrecoverable failure in quad rhs, then we return
+ * the value CV_QRHSFUNC_FAIL.
+ *
+ * If it failed due to an unrecoverable failure in sensi rhs, then we return
+ * the value CV_SRHSFUNC_FAIL.
+ *
+ * Otherwise, a recoverable failure occurred when solving the 
+ * nonlinear system (CVNls returned nflag = CONV_FAIL, RHSFUNC_RECVR, or
+ * SRHSFUNC_RECVR). 
+ * In this case, if ncf is now equal to maxncf or |h| = hmin, 
+ * we return the value CV_CONV_FAILURE (if nflag=CONV_FAIL), or
+ * CV_REPTD_RHSFUNC_ERR (if nflag=RHSFUNC_RECVR), or CV_REPTD_SRHSFUNC_ERR
+ * (if nflag=SRHSFUNC_RECVR).
+ * If not, we set *nflagPtr = PREV_CONV_FAIL and return the value
+ * PREDICT_AGAIN, telling CVStep to reattempt the step.
+ *
+ */
+
+static int CVHandleNFlag(CVodeMem cv_mem, int *nflagPtr, realtype saved_t,
+                         int *ncfPtr, long int *ncfnPtr)
+{
+  int nflag;
+  
+  nflag = *nflagPtr;
+  
+  if (nflag == CV_SUCCESS) return(DO_ERROR_TEST);
+
+  /* The nonlinear soln. failed; increment ncfn and restore zn */
+  (*ncfnPtr)++;
+  CVRestore(cv_mem, saved_t);
+  
+  /* Return if lsetup, lsolve, or some rhs failed unrecoverably */
+  if (nflag == CV_LSETUP_FAIL)   return(CV_LSETUP_FAIL);
+  if (nflag == CV_LSOLVE_FAIL)   return(CV_LSOLVE_FAIL);
+  if (nflag == CV_RHSFUNC_FAIL)  return(CV_RHSFUNC_FAIL);
+  if (nflag == CV_QRHSFUNC_FAIL) return(CV_QRHSFUNC_FAIL);
+  if (nflag == CV_SRHSFUNC_FAIL) return(CV_SRHSFUNC_FAIL);
+
+  /* At this point, nflag = CONV_FAIL, RHSFUNC_RECVR, or SRHSFUNC_RECVR; 
+     increment ncf */
+  
+  (*ncfPtr)++;
+  etamax = ONE;
+
+  /* If we had maxncf failures or |h| = hmin, 
+     return CV_CONV_FAILURE, CV_REPTD_RHSFUNC_ERR, 
+     CV_REPTD_QRHSFUNC_ERR, or CV_REPTD_SRHSFUNC_ERR */
+
+  if ((ABS(h) <= hmin*ONEPSM) || (*ncfPtr == maxncf)) {
+    if (nflag == CONV_FAIL)      return(CV_CONV_FAILURE);
+    if (nflag == RHSFUNC_RECVR)  return(CV_REPTD_RHSFUNC_ERR);    
+    if (nflag == QRHSFUNC_RECVR) return(CV_REPTD_QRHSFUNC_ERR);    
+    if (nflag == SRHSFUNC_RECVR) return(CV_REPTD_SRHSFUNC_ERR);    
+  }
+
+  /* Reduce step size; return to reattempt the step */
+
+  eta = MAX(ETACF, hmin / ABS(h));
+  *nflagPtr = PREV_CONV_FAIL;
+  CVRescale(cv_mem);
+
+  return(PREDICT_AGAIN);
+}
+
+/*
+ * CVRestore
+ *
+ * This routine restores the value of tn to saved_t and undoes the
+ * prediction.  After execution of CVRestore, the Nordsieck array zn has
+ * the same values as before the call to CVPredict.
+ */
+
+static void CVRestore(CVodeMem cv_mem, realtype saved_t)
+{
+  int j, k;
+  int is;
+
+  tn = saved_t;
+  for (k = 1; k <= q; k++)
+    for (j = q; j >= k; j--)
+      N_VLinearSum(ONE, zn[j-1], -ONE, zn[j], zn[j-1]);
+
+  if (quadr) {
+    for (k = 1; k <= q; k++)
+      for (j = q; j >= k; j--)
+        N_VLinearSum(ONE, znQ[j-1], -ONE, znQ[j], znQ[j-1]);
+  }
+
+  if (sensi) {
+    for (is=0; is<Ns; is++) {
+      for (k = 1; k <= q; k++)
+        for (j = q; j >= k; j--)
+          N_VLinearSum(ONE, znS[j-1][is], -ONE, znS[j][is], znS[j-1][is]);
+    }
+  }
+}
+
+/* 
+ * -----------------------------------------------------------------
+ * Error Test
+ * -----------------------------------------------------------------
+ */
+
+/*
+ * CVDoErrorTest
+ *
+ * This routine performs the local error test, for the state, quadrature, 
+ * or sensitivity variables. Its last three arguments change depending
+ * on which variables the error test is to be performed on.
+ * 
+ * The weighted local error norm dsm is loaded into *dsmPtr, and 
+ * the test dsm ?<= 1 is made.
+ *
+ * If the test passes, CVDoErrorTest returns CV_SUCCESS. 
+ *
+ * If the test fails, we undo the step just taken (call CVRestore) and 
+ *
+ *   - if maxnef error test failures have occurred or if ABS(h) = hmin,
+ *     we return CV_ERR_FAILURE.
+ *
+ *   - if more than MXNEF1 error test failures have occurred, an order
+ *     reduction is forced. If already at order 1, restart by reloading 
+ *     zn from scratch (also znQ and znS if appropriate).
+ *     If f() fails, we return CV_RHSFUNC_FAIL or CV_UNREC_RHSFUNC_ERR;
+ *     if fQ() fails, we return CV_QRHSFUNC_FAIL or CV_UNREC_QRHSFUNC_ERR;
+ *     if CVSensRhs() fails, we return CV_SRHSFUNC_FAIL or CV_UNREC_SRHSFUNC_ERR;
+ *     (no recovery is possible at this stage).
+ *
+ *   - otherwise, set *nflagPtr to PREV_ERR_FAIL, and return TRY_AGAIN. 
+ *
+ */
+
+static int CVDoErrorTest(CVodeMem cv_mem, int *nflagPtr, realtype saved_t, 
+                         realtype acor_nrm,
+                         int *nefPtr, long int *netfPtr, realtype *dsmPtr)
+{
+  realtype dsm;
+  int retval, is;
+  N_Vector wrk1, wrk2;
+
+  dsm = acor_nrm / tq[2];
+
+  /* If est. local error norm dsm passes test, return CV_SUCCESS */  
+  *dsmPtr = dsm; 
+  if (dsm <= ONE) return(CV_SUCCESS);
+  
+  /* Test failed; increment counters, set nflag, and restore zn array */
+  (*nefPtr)++;
+  (*netfPtr)++;
+  *nflagPtr = PREV_ERR_FAIL;
+  CVRestore(cv_mem, saved_t);
+
+  /* At maxnef failures or |h| = hmin, return CV_ERR_FAILURE */
+  if ((ABS(h) <= hmin*ONEPSM) || (*nefPtr == maxnef)) return(CV_ERR_FAILURE);
+
+  /* Set etamax = 1 to prevent step size increase at end of this step */
+  etamax = ONE;
+
+  /* Set h ratio eta from dsm, rescale, and return for retry of step */
+  if (*nefPtr <= MXNEF1) {
+    eta = ONE / (RPowerR(BIAS2*dsm,ONE/L) + ADDON);
+    eta = MAX(ETAMIN, MAX(eta, hmin / ABS(h)));
+    if (*nefPtr >= SMALL_NEF) eta = MIN(eta, ETAMXF);
+    CVRescale(cv_mem);
+    return(TRY_AGAIN);
+  }
+  
+  /* After MXNEF1 failures, force an order reduction and retry step */
+  if (q > 1) {
+    eta = MAX(ETAMIN, hmin / ABS(h));
+    CVAdjustOrder(cv_mem,-1);
+    L = q;
+    q--;
+    qwait = L;
+    CVRescale(cv_mem);
+    return(TRY_AGAIN);
+  }
+
+  /* If already at order 1, restart: reload zn, znQ, znS from scratch */
+  eta = MAX(ETAMIN, hmin / ABS(h));
+  h *= eta;
+  next_h = h;
+  hscale = h;
+  qwait = LONG_WAIT;
+  nscon = 0;
+
+  retval = f(tn, zn[0], tempv, f_data);
+  nfe++;
+  if (retval < 0) return(CV_RHSFUNC_FAIL);
+  if (retval > 0) return(CV_UNREC_RHSFUNC_ERR);
+
+  N_VScale(h, tempv, zn[1]);
+
+  if (quadr) {
+
+    retval = fQ(tn, zn[0], tempvQ, fQ_data);
+    nfQe++;
+    if (retval < 0) return(CV_QRHSFUNC_FAIL);
+    if (retval > 0) return(CV_UNREC_QRHSFUNC_ERR);
+
+    N_VScale(h, tempvQ, znQ[1]);
+
+  }
+
+  if (sensi) {
+
+    wrk1 = ftemp;
+    wrk2 = ftempS[0];
+
+    retval = CVSensRhs(cv_mem, tn, zn[0], tempv, znS[0], tempvS, wrk1, wrk2);
+    if (retval < 0) return(CV_SRHSFUNC_FAIL);
+    if (retval > 0) return(CV_UNREC_SRHSFUNC_ERR);
+
+    for (is=0; is<Ns; is++) 
+      N_VScale(h, tempvS[is], znS[1][is]);
+
+  }
+  
+  return(TRY_AGAIN);
+}
+
+/* 
+ * -----------------------------------------------------------------
+ * Functions called after a successful step
+ * -----------------------------------------------------------------
+ */
+
+/*
+ * CVCompleteStep
+ *
+ * This routine performs various update operations when the solution
+ * to the nonlinear system has passed the local error test. 
+ * We increment the step counter nst, record the values hu and qu,
+ * update the tau array, and apply the corrections to the zn array.
+ * The tau[i] are the last q values of h, with tau[1] the most recent.
+ * The counter qwait is decremented, and if qwait == 1 (and q < qmax)
+ * we save acor and tq[5] for a possible order increase.
+ */
+
+static void CVCompleteStep(CVodeMem cv_mem)
+{
+  int i, j;
+  int is;
+  
+  nst++;
+  nscon++;
+  hu = h;
+  qu = q;
+
+  for (i=q; i >= 2; i--)  tau[i] = tau[i-1];
+  if ((q==1) && (nst > 1)) tau[2] = tau[1];
+  tau[1] = h;
+
+  /* Apply correction to column j of zn: l_j * Delta_n */
+
+  for (j=0; j <= q; j++) 
+    N_VLinearSum(l[j], acor, ONE, zn[j], zn[j]);
+
+  if (quadr) {
+    for (j=0; j <= q; j++) 
+      N_VLinearSum(l[j], acorQ, ONE, znQ[j], znQ[j]);
+  }
+
+  if (sensi) {
+    for (is=0; is<Ns; is++)
+      for (j=0; j <= q; j++) 
+        N_VLinearSum(l[j], acorS[is], ONE, znS[j][is], znS[j][is]);
+  }
+
+  /* If necessary, store Delta_n in zn[qmax] to be used in order increase
+  
+  This actually will be Delta_{n-1} in the ELTE at q+1 since it happens at
+  the next to last step of order q before a possible one at order q+1
+  */
+
+  qwait--;
+  if ((qwait == 1) && (q != qmax)) {
+    
+    N_VScale(ONE, acor, zn[qmax]);
+    
+    if (quadr)
+      N_VScale(ONE, acorQ, znQ[qmax]);
+
+    if (sensi)
+      for (is=0; is<Ns; is++)
+        N_VScale(ONE, acorS[is], znS[qmax][is]);
+    
+    saved_tq5 = tq[5];
+    indx_acor = qmax;
+  }
+
+}
+
+/*
+ * CVprepareNextStep
+ *
+ * This routine handles the setting of stepsize and order for the
+ * next step -- hprime and qprime.  Along with hprime, it sets the
+ * ratio eta = hprime/h.  It also updates other state variables 
+ * related to a change of step size or order. 
+ */
+
+static void CVPrepareNextStep(CVodeMem cv_mem, realtype dsm)
+{
+  /* If etamax = 1, defer step size or order changes */
+  if (etamax == ONE) {
+    qwait = MAX(qwait, 2);
+    qprime = q;
+    hprime = h;
+    eta = ONE;
+    return;
+  }
+
+  /* etaq is the ratio of new to old h at the current order */  
+  etaq = ONE /(RPowerR(BIAS2*dsm,ONE/L) + ADDON);
+  
+  /* If no order change, adjust eta and acor in CVSetEta and return */
+  if (qwait != 0) {
+    eta = etaq;
+    qprime = q;
+    CVSetEta(cv_mem);
+    return;
+  }
+  
+  /* If qwait = 0, consider an order change.   etaqm1 and etaqp1 are 
+     the ratios of new to old h at orders q-1 and q+1, respectively.
+     CVChooseEta selects the largest; CVSetEta adjusts eta and acor */
+  qwait = 2;
+  etaqm1 = CVComputeEtaqm1(cv_mem);
+  etaqp1 = CVComputeEtaqp1(cv_mem);  
+  CVChooseEta(cv_mem); 
+  CVSetEta(cv_mem);
+}
+
+/*
+ * CVsetEta
+ *
+ * This routine adjusts the value of eta according to the various
+ * heuristic limits and the optional input hmax.  It also resets
+ * etamax to be the estimated local error vector.
+ */
+
+static void CVSetEta(CVodeMem cv_mem)
+{
+
+  /* If eta below the threshhold THRESH, reject a change of step size */
+  if (eta < THRESH) {
+    eta = ONE;
+    hprime = h;
+  } else {
+    /* Limit eta by etamax and hmax, then set hprime */
+    eta = MIN(eta, etamax);
+    eta /= MAX(ONE, ABS(h)*hmax_inv*eta);
+    hprime = h * eta;
+    if (qprime < q) nscon = 0;
+  }
+
+  /* Reset etamx for the next step size change, and scale acor */
+}
+
+/*
+ * CVComputeEtaqm1
+ *
+ * This routine computes and returns the value of etaqm1 for a
+ * possible decrease in order by 1.
+ */
+
+static realtype CVComputeEtaqm1(CVodeMem cv_mem)
+{
+  realtype ddn;
+  
+  etaqm1 = ZERO;
+
+  if (q > 1) {
+
+    ddn = N_VWrmsNorm(zn[q], ewt);
+
+    if ( quadr && errconQ) {
+      ddn = CVQuadUpdateNorm(cv_mem, ddn, znQ[q], ewtQ);
+    }
+
+    if ( sensi && errconS ) {
+      ddn = CVSensUpdateNorm(cv_mem, ddn, znS[q], ewtS);
+    }
+
+    ddn = ddn/tq[1];
+
+    etaqm1 = ONE/(RPowerR(BIAS1*ddn, ONE/q) + ADDON);
+
+  }
+
+  return(etaqm1);
+}
+
+/*
+ * CVComputeEtaqp1
+ *
+ * This routine computes and returns the value of etaqp1 for a
+ * possible increase in order by 1.
+ */
+
+static realtype CVComputeEtaqp1(CVodeMem cv_mem)
+{
+  realtype dup, cquot;
+  int is;
+  
+  etaqp1 = ZERO;
+
+  if (q != qmax) {
+
+    cquot = (tq[5] / saved_tq5) * RPowerI(h/tau[2], L);
+
+    N_VLinearSum(-cquot, zn[qmax], ONE, acor, tempv);
+
+    dup = N_VWrmsNorm(tempv, ewt);
+
+    if ( quadr && errconQ ) {
+      N_VLinearSum(-cquot, znQ[qmax], ONE, acorQ, tempvQ);
+      dup = CVQuadUpdateNorm(cv_mem, dup, tempvQ, ewtQ);
+    }
+
+    if ( sensi && errconS ) {
+      for (is=0; is<Ns; is++) 
+        N_VLinearSum(-cquot, znS[qmax][is], ONE, acorS[is], tempvS[is]);
+      dup = CVSensUpdateNorm(cv_mem, dup, tempvS, ewtS);
+    }
+
+    dup = dup / tq[3];
+
+    etaqp1 = ONE / (RPowerR(BIAS3*dup, ONE/(L+1)) + ADDON);
+
+  }
+
+  return(etaqp1);
+}
+
+/*
+ * CVChooseEta
+ * Given etaqm1, etaq, etaqp1 (the values of eta for qprime =
+ * q - 1, q, or q + 1, respectively), this routine chooses the 
+ * maximum eta value, sets eta to that value, and sets qprime to the
+ * corresponding value of q.  If there is a tie, the preference
+ * order is to (1) keep the same order, then (2) decrease the order,
+ * and finally (3) increase the order.  If the maximum eta value
+ * is below the threshhold THRESH, the order is kept unchanged and
+ * eta is set to 1.
+ */
+
+static void CVChooseEta(CVodeMem cv_mem)
+{
+  realtype etam;
+  int is;
+  
+  etam = MAX(etaqm1, MAX(etaq, etaqp1));
+  
+  if (etam < THRESH) {
+    eta = ONE;
+    qprime = q;
+    return;
+  }
+
+  if (etam == etaq) {
+
+    eta = etaq;
+    qprime = q;
+
+  } else if (etam == etaqm1) {
+
+    eta = etaqm1;
+    qprime = q - 1;
+
+  } else {
+
+    eta = etaqp1;
+    qprime = q + 1;
+
+    if (lmm == CV_BDF) {
+
+      /* 
+       * Store Delta_n in zn[qmax] to be used in order increase 
+       *
+       * This happens at the last step of order q before an increase
+       * to order q+1, so it represents Delta_n in the ELTE at q+1
+       */
+      
+      N_VScale(ONE, acor, zn[qmax]);
+      
+      if (quadr && errconQ)
+        N_VScale(ONE, acorQ, znQ[qmax]);
+      
+      if (sensi && errconS)
+        for (is=0; is<Ns; is++)
+          N_VScale(ONE, acorS[is], znS[qmax][is]);
+    }
+
+  }
+
+}
+
+/* 
+ * -----------------------------------------------------------------
+ * Function to handle failures
+ * -----------------------------------------------------------------
+ */
+
+/*
+ * CVHandleFailure
+ *
+ * This routine prints error messages for all cases of failure by
+ * CVHin or CVStep. 
+ * It returns to CVode the value that CVode is to return to the user.
+ */
+
+static int CVHandleFailure(CVodeMem cv_mem, int flag)
+{
+
+  /* Set vector of  absolute weighted local errors */
+  /*
+  N_VProd(acor, ewt, tempv);
+  N_VAbs(tempv, tempv);
+  */  
+
+  /* Depending on flag, print error message and return error flag */
+  switch (flag) {
+  case CV_ERR_FAILURE:  
+    CVProcessError(cv_mem, CV_ERR_FAILURE, "CVODES", "CVode", MSGCV_ERR_FAILS, tn, h);
+    break;
+  case CV_CONV_FAILURE: 
+    CVProcessError(cv_mem, CV_CONV_FAILURE, "CVODES", "CVode", MSGCV_CONV_FAILS, tn, h);
+    break;
+  case CV_LSETUP_FAIL:  
+    CVProcessError(cv_mem, CV_LSETUP_FAIL, "CVODES", "CVode", MSGCV_SETUP_FAILED, tn);
+    break;
+  case CV_LSOLVE_FAIL:  
+    CVProcessError(cv_mem, CV_LSOLVE_FAIL, "CVODES", "CVode", MSGCV_SOLVE_FAILED, tn);
+    break;
+  case CV_RHSFUNC_FAIL:
+    CVProcessError(cv_mem, CV_RHSFUNC_FAIL, "CVODES", "CVode", MSGCV_RHSFUNC_FAILED, tn);
+    break;
+  case CV_UNREC_RHSFUNC_ERR:
+    CVProcessError(cv_mem, CV_UNREC_RHSFUNC_ERR, "CVODES", "CVode", MSGCV_RHSFUNC_UNREC, tn);
+    break;
+  case CV_REPTD_RHSFUNC_ERR:
+    CVProcessError(cv_mem, CV_REPTD_RHSFUNC_ERR, "CVODES", "CVode", MSGCV_RHSFUNC_REPTD, tn);
+    break;
+  case CV_RTFUNC_FAIL:    
+    CVProcessError(cv_mem, CV_RTFUNC_FAIL, "CVODES", "CVode", MSGCV_RTFUNC_FAILED, tn);
+    break;
+  case CV_QRHSFUNC_FAIL:
+    CVProcessError(cv_mem, CV_QRHSFUNC_FAIL, "CVODES", "CVode", MSGCV_QRHSFUNC_FAILED, tn);
+    break;
+  case CV_UNREC_QRHSFUNC_ERR:
+    CVProcessError(cv_mem, CV_UNREC_QRHSFUNC_ERR, "CVODES", "CVode", MSGCV_QRHSFUNC_UNREC, tn);
+    break;
+  case CV_REPTD_QRHSFUNC_ERR:
+    CVProcessError(cv_mem, CV_REPTD_QRHSFUNC_ERR, "CVODES", "CVode", MSGCV_QRHSFUNC_REPTD, tn);
+    break;
+  case CV_SRHSFUNC_FAIL:
+    CVProcessError(cv_mem, CV_SRHSFUNC_FAIL, "CVODES", "CVode", MSGCV_SRHSFUNC_FAILED, tn);
+    break;
+  case CV_UNREC_SRHSFUNC_ERR:
+    CVProcessError(cv_mem, CV_UNREC_SRHSFUNC_ERR, "CVODES", "CVode", MSGCV_SRHSFUNC_UNREC, tn);
+    break;
+  case CV_REPTD_SRHSFUNC_ERR:
+    CVProcessError(cv_mem, CV_REPTD_SRHSFUNC_ERR, "CVODES", "CVode", MSGCV_SRHSFUNC_REPTD, tn);
+    break;
+  case CV_TOO_CLOSE:
+    CVProcessError(cv_mem, CV_TOO_CLOSE, "CVODES", "CVode", MSGCV_TOO_CLOSE);
+  default:
+    return(CV_SUCCESS);
+  }
+
+  return(flag);
+
+}
+
+/* 
+ * -----------------------------------------------------------------
+ * Functions for BDF Stability Limit Detection   
+ * -----------------------------------------------------------------
+ */
+
+/*
+ * CVBDFStab
+ *
+ * This routine handles the BDF Stability Limit Detection Algorithm
+ * STALD.  It is called if lmm = CV_BDF and the SLDET option is on.
+ * If the order is 3 or more, the required norm data is saved.
+ * If a decision to reduce order has not already been made, and
+ * enough data has been saved, CVsldet is called.  If it signals
+ * a stability limit violation, the order is reduced, and the step
+ * size is reset accordingly.
+ */
+
+static void CVBDFStab(CVodeMem cv_mem)
+{
+  int i,k, ldflag, factorial;
+  realtype sq, sqm1, sqm2;
+      
+  /* If order is 3 or greater, then save scaled derivative data,
+     push old data down in i, then add current values to top.    */
+
+  if (q >= 3) {
+    for (k = 1; k <= 3; k++)
+      for (i = 5; i >= 2; i--) 
+        ssdat[i][k] = ssdat[i-1][k]; 
+    factorial = 1;
+    for (i = 1; i <= q-1; i++) factorial *= i;
+    sq = factorial*q*(q+1)*acnrm/tq[5];
+    sqm1 = factorial*q*N_VWrmsNorm(zn[q], ewt);
+    sqm2 = factorial*N_VWrmsNorm(zn[q-1], ewt);
+    ssdat[1][1] = sqm2*sqm2;
+    ssdat[1][2] = sqm1*sqm1;
+    ssdat[1][3] = sq*sq;
+  }  
+
+  if (qprime >= q) {
+
+    /* If order is 3 or greater, and enough ssdat has been saved,
+       nscon >= q+5, then call stability limit detection routine.  */
+
+    if ( (q >= 3) && (nscon >= q+5) ) {
+      ldflag = CVsldet(cv_mem);
+      if (ldflag > 3) {
+        /* A stability limit violation is indicated by
+           a return flag of 4, 5, or 6.
+           Reduce new order.                     */
+        qprime = q-1;
+        eta = etaqm1; 
+        eta = MIN(eta,etamax);
+        eta = eta/MAX(ONE,ABS(h)*hmax_inv*eta);
+        hprime = h*eta;
+        nor = nor + 1;
+      }
+    }
+  }
+  else {
+    /* Otherwise, let order increase happen, and 
+       reset stability limit counter, nscon.     */
+    nscon = 0;
+  }
+}
+
+/*
+ * CVsldet
+ *
+ * This routine detects stability limitation using stored scaled 
+ * derivatives data. CVsldet returns the magnitude of the
+ * dominate characteristic root, rr. The presents of a stability
+ * limit is indicated by rr > "something a little less then 1.0",  
+ * and a positive kflag. This routine should only be called if
+ * order is greater than or equal to 3, and data has been collected
+ * for 5 time steps. 
+ * 
+ * Returned values:
+ *    kflag = 1 -> Found stable characteristic root, normal matrix case
+ *    kflag = 2 -> Found stable characteristic root, quartic solution
+ *    kflag = 3 -> Found stable characteristic root, quartic solution,
+ *                 with Newton correction
+ *    kflag = 4 -> Found stability violation, normal matrix case
+ *    kflag = 5 -> Found stability violation, quartic solution
+ *    kflag = 6 -> Found stability violation, quartic solution,
+ *                 with Newton correction
+ *
+ *    kflag < 0 -> No stability limitation, 
+ *                 or could not compute limitation.
+ *
+ *    kflag = -1 -> Min/max ratio of ssdat too small.
+ *    kflag = -2 -> For normal matrix case, vmax > vrrt2*vrrt2
+ *    kflag = -3 -> For normal matrix case, The three ratios
+ *                  are inconsistent.
+ *    kflag = -4 -> Small coefficient prevents elimination of quartics.  
+ *    kflag = -5 -> R value from quartics not consistent.
+ *    kflag = -6 -> No corrected root passes test on qk values
+ *    kflag = -7 -> Trouble solving for sigsq.
+ *    kflag = -8 -> Trouble solving for B, or R via B.
+ *    kflag = -9 -> R via sigsq[k] disagrees with R from data.
+ */
+
+static int CVsldet(CVodeMem cv_mem)
+{
+  int i, k, j, it, kmin=0, kflag=0;
+  realtype rat[5][4], rav[4], qkr[4], sigsq[4], smax[4], ssmax[4];
+  realtype drr[4], rrc[4],sqmx[4], qjk[4][4], vrat[5], qc[6][4], qco[6][4];
+  realtype rr, rrcut, vrrtol, vrrt2, sqtol, rrtol;
+  realtype smink, smaxk, sumrat, sumrsq, vmin, vmax, drrmax, adrr;
+  realtype tem, sqmax, saqk, qp, s, sqmaxk, saqj, sqmin;
+  realtype rsa, rsb, rsc, rsd, rd1a, rd1b, rd1c;
+  realtype rd2a, rd2b, rd3a, cest1, corr1; 
+  realtype ratp, ratm, qfac1, qfac2, bb, rrb;
+
+  /* The following are cutoffs and tolerances used by this routine */
+
+  rrcut  = RCONST(0.98);
+  vrrtol = RCONST(1.0e-4);
+  vrrt2  = RCONST(5.0e-4);
+  sqtol  = RCONST(1.0e-3);
+  rrtol  = RCONST(1.0e-2);
+
+  rr = ZERO;
+
+  /*  Index k corresponds to the degree of the interpolating polynomial. */
+  /*      k = 1 -> q-1          */
+  /*      k = 2 -> q            */
+  /*      k = 3 -> q+1          */
+
+  /*  Index i is a backward-in-time index, i = 1 -> current time, */
+  /*      i = 2 -> previous step, etc    */
+
+  /* get maxima, minima, and variances, and form quartic coefficients  */
+
+  for (k=1; k<=3; k++) {
+    smink = ssdat[1][k];
+    smaxk = ZERO;
+    
+    for (i=1; i<=5; i++) {
+      smink = MIN(smink,ssdat[i][k]);
+      smaxk = MAX(smaxk,ssdat[i][k]);
+    }
+    
+    if (smink < TINY*smaxk) {
+      kflag = -1;  
+      return(kflag);
+    }
+    smax[k] = smaxk;
+    ssmax[k] = smaxk*smaxk;
+    
+    sumrat = ZERO;
+    sumrsq = ZERO;
+    for (i=1; i<=4; i++) {
+      rat[i][k] = ssdat[i][k]/ssdat[i+1][k];
+      sumrat = sumrat + rat[i][k];
+      sumrsq = sumrsq + rat[i][k]*rat[i][k];
+    } 
+    rav[k] = FOURTH*sumrat;
+    vrat[k] = ABS(FOURTH*sumrsq - rav[k]*rav[k]);
+      
+    qc[5][k] = ssdat[1][k]*ssdat[3][k] - ssdat[2][k]*ssdat[2][k];
+    qc[4][k] = ssdat[2][k]*ssdat[3][k] - ssdat[1][k]*ssdat[4][k];
+    qc[3][k] = ZERO;
+    qc[2][k] = ssdat[2][k]*ssdat[5][k] - ssdat[3][k]*ssdat[4][k];
+    qc[1][k] = ssdat[4][k]*ssdat[4][k] - ssdat[3][k]*ssdat[5][k];
+    
+    for (i=1; i<=5; i++) {
+      qco[i][k] = qc[i][k];
+    }
+  }                            /* End of k loop */
+  
+  /* Isolate normal or nearly-normal matrix case. Three quartic will
+     have common or nearly-common roots in this case. 
+     Return a kflag = 1 if this procedure works. If three root 
+     differ more than vrrt2, return error kflag = -3.    */
+  
+  vmin = MIN(vrat[1],MIN(vrat[2],vrat[3]));
+  vmax = MAX(vrat[1],MAX(vrat[2],vrat[3]));
+  
+  if (vmin < vrrtol*vrrtol) {
+
+    if (vmax > vrrt2*vrrt2) {
+      kflag = -2;  
+      return(kflag);
+    } else {
+      rr = (rav[1] + rav[2] + rav[3])/THREE;
+      drrmax = ZERO;
+      for (k = 1;k<=3;k++) {
+        adrr = ABS(rav[k] - rr);
+        drrmax = MAX(drrmax, adrr);
+      }
+      if (drrmax > vrrt2)
+        kflag = -3;    
+      kflag = 1;
+      /*  can compute charactistic root, drop to next section   */
+    }
+
+  } else {
+      
+    /* use the quartics to get rr. */
+      
+    if (ABS(qco[1][1]) < TINY*ssmax[1]) {
+      kflag = -4;    
+      return(kflag);
+    }
+      
+    tem = qco[1][2]/qco[1][1];
+    for (i=2; i<=5; i++) {
+      qco[i][2] = qco[i][2] - tem*qco[i][1];
+    }
+      
+    qco[1][2] = ZERO;
+    tem = qco[1][3]/qco[1][1];
+    for (i=2; i<=5; i++) {
+      qco[i][3] = qco[i][3] - tem*qco[i][1];
+    }
+    qco[1][3] = ZERO;
+      
+    if (ABS(qco[2][2]) < TINY*ssmax[2]) {
+      kflag = -4;    
+      return(kflag);
+    }
+      
+    tem = qco[2][3]/qco[2][2];
+    for (i=3; i<=5; i++) {
+      qco[i][3] = qco[i][3] - tem*qco[i][2];
+    }
+      
+    if (ABS(qco[4][3]) < TINY*ssmax[3]) {
+      kflag = -4;    
+      return(kflag);
+    }
+      
+    rr = -qco[5][3]/qco[4][3];
+      
+    if (rr < TINY || rr > HUN) {
+      kflag = -5;   
+      return(kflag);
+    }
+      
+    for (k=1; k<=3; k++) {
+      qkr[k] = qc[5][k] + rr*(qc[4][k] + rr*rr*(qc[2][k] + rr*qc[1][k]));
+    }  
+      
+    sqmax = ZERO;
+    for (k=1; k<=3; k++) {
+      saqk = ABS(qkr[k])/ssmax[k];
+      if (saqk > sqmax) sqmax = saqk;
+    } 
+      
+    if (sqmax < sqtol) {
+      kflag = 2;
+        
+      /*  can compute charactistic root, drop to "given rr,etc"   */
+        
+    } else {
+          
+      /* do Newton corrections to improve rr.  */
+        
+      for (it=1; it<=3; it++) {
+        for (k=1; k<=3; k++) {
+          qp = qc[4][k] + rr*rr*(THREE*qc[2][k] + rr*FOUR*qc[1][k]);
+          drr[k] = ZERO;
+          if (ABS(qp) > TINY*ssmax[k]) drr[k] = -qkr[k]/qp;
+          rrc[k] = rr + drr[k];
+        } 
+          
+        for (k=1; k<=3; k++) {
+          s = rrc[k];
+          sqmaxk = ZERO;
+          for (j=1; j<=3; j++) {
+            qjk[j][k] = qc[5][j] + s*(qc[4][j] + 
+                                      s*s*(qc[2][j] + s*qc[1][j]));
+            saqj = ABS(qjk[j][k])/ssmax[j];
+            if (saqj > sqmaxk) sqmaxk = saqj;
+          } 
+          sqmx[k] = sqmaxk;
+        } 
+              
+        sqmin = sqmx[1] + ONE;
+        for (k=1; k<=3; k++) {
+          if (sqmx[k] < sqmin) {
+            kmin = k;
+            sqmin = sqmx[k];
+          }
+        } 
+        rr = rrc[kmin];
+              
+        if (sqmin < sqtol) {
+          kflag = 3;
+          /*  can compute charactistic root   */
+          /*  break out of Newton correction loop and drop to "given rr,etc" */ 
+          break;
+        } else {
+          for (j=1; j<=3; j++) {
+            qkr[j] = qjk[j][kmin];
+          }
+        }     
+      } /*  end of Newton correction loop  */ 
+          
+      if (sqmin > sqtol) {
+        kflag = -6;
+        return(kflag);
+      }
+    } /*  end of if (sqmax < sqtol) else   */
+  } /*  end of if (vmin < vrrtol*vrrtol) else, quartics to get rr. */
+  
+  /* given rr, find sigsq[k] and verify rr.  */
+  /* All positive kflag drop to this section  */
+  
+  for (k=1; k<=3; k++) {
+    rsa = ssdat[1][k];
+    rsb = ssdat[2][k]*rr;
+    rsc = ssdat[3][k]*rr*rr;
+    rsd = ssdat[4][k]*rr*rr*rr;
+    rd1a = rsa - rsb;
+    rd1b = rsb - rsc;
+    rd1c = rsc - rsd;
+    rd2a = rd1a - rd1b;
+    rd2b = rd1b - rd1c;
+    rd3a = rd2a - rd2b;
+    
+    if (ABS(rd1b) < TINY*smax[k]) {
+      kflag = -7;
+      return(kflag);
+    }
+    
+    cest1 = -rd3a/rd1b;
+    if (cest1 < TINY || cest1 > FOUR) {
+      kflag = -7;
+      return(kflag);
+    }
+    corr1 = (rd2b/cest1)/(rr*rr);
+    sigsq[k] = ssdat[3][k] + corr1;
+  }
+  
+  if (sigsq[2] < TINY) {
+    kflag = -8;
+    return(kflag);
+  }
+  
+  ratp = sigsq[3]/sigsq[2];
+  ratm = sigsq[1]/sigsq[2];
+  qfac1 = FOURTH*(q*q - ONE);
+  qfac2 = TWO/(q - ONE);
+  bb = ratp*ratm - ONE - qfac1*ratp;
+  tem = ONE - qfac2*bb;
+  
+  if (ABS(tem) < TINY) {
+    kflag = -8;
+    return(kflag);
+  }
+  
+  rrb = ONE/tem;
+  
+  if (ABS(rrb - rr) > rrtol) {
+    kflag = -9;
+    return(kflag);
+  }
+  
+  /* Check to see if rr is above cutoff rrcut  */
+  if (rr > rrcut) {
+    if (kflag == 1) kflag = 4;
+    if (kflag == 2) kflag = 5;
+    if (kflag == 3) kflag = 6;
+  }
+  
+  /* All positive kflag returned at this point  */
+  
+  return(kflag);
+  
+}
+
+/* 
+ * -----------------------------------------------------------------
+ * Functions for rootfinding
+ * -----------------------------------------------------------------
+ */
+
+/* 
+ * CVRcheck1
+ *
+ * This routine completes the initialization of rootfinding memory
+ * information, and checks whether g has a zero both at and very near
+ * the initial point of the IVP.
+ *
+ * This routine returns an int equal to:
+ *  INITROOT = -1 if a close pair of zeros was found, and
+ *  CV_SUCCESS     =  0 otherwise.
+ */
+
+static int CVRcheck1(CVodeMem cv_mem)
+{
+  int i, retval;
+  realtype smallh, hratio;
+  booleantype zroot;
+
+  for (i = 0; i < nrtfn; i++) iroots[i] = 0;
+  tlo = tn;
+  ttol = (ABS(tn) + ABS(h))*uround*HUN;
+
+  /* Evaluate g at initial t and check for zero values. */
+  retval = gfun(tlo, zn[0], glo, g_data);
+  nge = 1;
+  if (retval != 0) return(CV_RTFUNC_FAIL);
+  
+  zroot = FALSE;
+  for (i = 0; i < nrtfn; i++) {
+    if (ABS(glo[i]) == ZERO) zroot = TRUE;
+  }
+  if (!zroot) return(CV_SUCCESS);
+
+  /* Some g_i is zero at t0; look at g at t0+(small increment). */
+  hratio = MAX(ttol/ABS(h), TENTH);
+  smallh = hratio*h;
+  tlo += smallh;
+  N_VLinearSum(ONE, zn[0], hratio, zn[1], y);
+  retval = gfun(tlo, y, glo, g_data);
+  nge++;
+  if (retval != 0) return(CV_RTFUNC_FAIL);
+
+  zroot = FALSE;
+  for (i = 0; i < nrtfn; i++) {
+    if (ABS(glo[i]) == ZERO) {
+      zroot = TRUE;
+      iroots[i] = 1;
+    }
+  }
+  if (zroot) return(INITROOT);
+  return(CV_SUCCESS);
+
+}
+
+/*
+ * CVRcheck2
+ *
+ * This routine checks for exact zeros of g at the last root found,
+ * if the last return was a root.  It then checks for a close
+ * pair of zeros (an error condition), and for a new root at a
+ * nearby point.  The left endpoint (tlo) of the search interval
+ * is adjusted if necessary to assure that all g_i are nonzero
+ * there, before returning to do a root search in the interval.
+ *
+ * On entry, tlo = tretlast is the last value of tret returned by
+ * CVode.  This may be the previous tn, the previous tout value, or
+ * the last root location.
+ *
+ * This routine returns an int equal to:
+ *      CLOSERT = -2 if a close pair of zeros was found,
+ *      RTFOUND =  1 if a new zero of g was found near tlo, or
+ *      CV_SUCCESS    =  0 otherwise.
+ */
+
+static int CVRcheck2(CVodeMem cv_mem)
+{
+  int i, retval;
+  realtype smallh, hratio;
+  booleantype zroot;
+
+  if (irfnd == 0) return(CV_SUCCESS);
+
+  (void) CVodeGetDky(cv_mem, tlo, 0, y);
+  retval = gfun(tlo, y, glo, g_data);
+  nge++;
+  if (retval != 0) return(CV_RTFUNC_FAIL);
+
+  zroot = FALSE;
+  for (i = 0; i < nrtfn; i++) iroots[i] = 0;
+  for (i = 0; i < nrtfn; i++) {
+    if (ABS(glo[i]) == ZERO) {
+      zroot = TRUE;
+      iroots[i] = 1;
+    }
+  }
+  if (!zroot) return(CV_SUCCESS);
+
+  /* One or more g_i has a zero at tlo.  Check g at tlo+smallh. */
+  ttol = (ABS(tn) + ABS(h))*uround*HUN;
+  smallh = (h > ZERO) ? ttol : -ttol;
+  tlo += smallh;
+  if ( (tlo - tn)*h >= ZERO) {
+    hratio = smallh/h;
+    N_VLinearSum(ONE, y, hratio, zn[1], y);
+  } else {
+    (void) CVodeGetDky(cv_mem, tlo, 0, y);
+  }
+  retval = gfun(tlo, y, glo, g_data);
+  nge++;
+  if (retval != 0) return(CV_RTFUNC_FAIL);
+
+  zroot = FALSE;
+  for (i = 0; i < nrtfn; i++) {
+    if (ABS(glo[i]) == ZERO) {
+      if (iroots[i] == 1) return(CLOSERT);
+      zroot = TRUE;
+      iroots[i] = 1;
+    }
+  }
+  if (zroot) return(RTFOUND);
+  return(CV_SUCCESS);
+
+}
+
+/*
+ * CVRcheck3
+ *
+ * This routine interfaces to CVRootfind to look for a root of g
+ * between tlo and either tn or tout, whichever comes first.
+ * Only roots beyond tlo in the direction of integration are sought.
+ *
+ * This routine returns an int equal to:
+ *      RTFOUND =  1 if a root of g was found, or
+ *      CV_SUCCESS    =  0 otherwise.
+ */
+
+static int CVRcheck3(CVodeMem cv_mem)
+{
+  int i, retval, ier;
+
+  /* Set thi = tn or tout, whichever comes first; set y = y(thi). */
+  if (taskc == CV_ONE_STEP) {
+    thi = tn;
+    N_VScale(ONE, zn[0], y);
+  }
+  if (taskc == CV_NORMAL) {
+    if ( (toutc - tn)*h >= ZERO) {
+      thi = tn; 
+      N_VScale(ONE, zn[0], y);
+    } else {
+      thi = toutc;
+      (void) CVodeGetDky(cv_mem, thi, 0, y);
+    }
+  }
+
+  /* Set ghi = g(thi) and call CVRootfind to search (tlo,thi) for roots. */
+  retval = gfun(thi, y, ghi, g_data);
+  nge++;
+  if (retval != 0) return(CV_RTFUNC_FAIL);
+
+  ttol = (ABS(tn) + ABS(h))*uround*HUN;
+  ier = CVRootfind(cv_mem);
+  tlo = trout;
+  for (i = 0; i < nrtfn; i++) glo[i] = grout[i];
+
+  /* If no root found, return CV_SUCCESS. */  
+  if (ier == CV_SUCCESS) return(CV_SUCCESS);
+
+  /* If a root was found, interpolate to get y(trout) and return.  */
+  (void) CVodeGetDky(cv_mem, trout, 0, y);
+  return(RTFOUND);
+
+}
+
+/*
+ * CVRootFind
+ *
+ * This routine solves for a root of g(t) between tlo and thi, if
+ * one exists.  Only roots of odd multiplicity (i.e. with a change
+ * of sign in one of the g_i), or exact zeros, are found.
+ * Here the sign of tlo - thi is arbitrary, but if multiple roots
+ * are found, the one closest to tlo is returned.
+ *
+ * The method used is the Illinois algorithm, a modified secant method.
+ * Reference: Kathie L. Hiebert and Lawrence F. Shampine, Implicitly
+ * Defined Output Points for Solutions of ODEs, Sandia National
+ * Laboratory Report SAND80-0180, February 1980.
+ *
+ * This routine uses the following parameters for communication:
+ *
+ * nrtfn    = number of functions g_i, or number of components of
+ *            the vector-valued function g(t).  Input only.
+ *
+ * gfun     = user-defined function for g(t).  Its form is
+ *            (void) gfun(t, y, gt, g_data)
+ *
+ * nge      = cumulative counter for gfun calls.
+ *
+ * ttol     = a convergence tolerance for trout.  Input only.
+ *            When a root at trout is found, it is located only to
+ *            within a tolerance of ttol.  Typically, ttol should
+ *            be set to a value on the order of
+ *               100 * UROUND * max (ABS(tlo), ABS(thi))
+ *            where UROUND is the unit roundoff of the machine.
+ *
+ * tlo, thi = endpoints of the interval in which roots are sought.
+ *            On input, and must be distinct, but tlo - thi may
+ *            be of either sign.  The direction of integration is
+ *            assumed to be from tlo to thi.  On return, tlo and thi
+ *            are the endpoints of the final relevant interval.
+ *
+ * glo, ghi = arrays of length nrtfn containing the vectors g(tlo)
+ *            and g(thi) respectively.  Input and output.  On input,
+ *            none of the glo[i] should be zero.
+ *
+ * trout    = root location, if a root was found, or thi if not.
+ *            Output only.  If a root was found other than an exact
+ *            zero of g, trout is the endpoint thi of the final
+ *            interval bracketing the root, with size at most ttol.
+ *
+ * grout    = array of length nrtfn containing g(trout) on return.
+ *
+ * iroots   = int array of length nrtfn with root information.
+ *            Output only.  If a root was found, iroots indicates
+ *            which components g_i have a root at trout.  For
+ *            i = 0, ..., nrtfn-1, iroots[i] = 1 if g_i has a root
+ *            and iroots[i] = 0 otherwise.
+ *
+ * This routine returns an int equal to:
+ *      RTFOUND =  1 if a root of g was found, or
+ *      CV_SUCCESS    =  0 otherwise.
+ */
+
+static int CVRootfind(CVodeMem cv_mem)
+{
+  realtype alpha, tmid, gfrac, maxfrac, fracint, fracsub;
+  int i, retval, imax, side, sideprev;
+  booleantype zroot, sgnchg;
+
+  imax = 0;
+
+  /* First check for change in sign in ghi or for a zero in ghi. */
+  maxfrac = ZERO;
+  zroot = FALSE;
+  sgnchg = FALSE;
+  for (i = 0;  i < nrtfn; i++) {
+    if (ABS(ghi[i]) == ZERO) {
+      zroot = TRUE;
+    } else {
+      if (glo[i]*ghi[i] < ZERO) {
+        gfrac = ABS(ghi[i]/(ghi[i] - glo[i]));
+        if (gfrac > maxfrac) {
+          sgnchg = TRUE;
+          maxfrac = gfrac;
+          imax = i;
+        }
+      }
+    }
+  }
+
+  /* If no sign change was found, reset trout and grout.  Then return
+     CV_SUCCESS if no zero was found, or set iroots and return RTFOUND.  */ 
+  if (!sgnchg) {
+    trout = thi;
+    for (i = 0; i < nrtfn; i++) grout[i] = ghi[i];
+    if (!zroot) return(CV_SUCCESS);
+    for (i = 0; i < nrtfn; i++) {
+      iroots[i] = 0;
+      if (ABS(ghi[i]) == ZERO) iroots[i] = 1;
+    }
+    return(RTFOUND);
+  }
+
+  /* Initialize alpha to avoid compiler warning */
+
+  alpha = ONE;
+
+  /* A sign change was found.  Loop to locate nearest root. */
+
+  side = 0;  sideprev = -1;
+  loop {                                    /* Looping point */
+
+    /* Set weight alpha.
+       On the first two passes, set alpha = 1.  Thereafter, reset alpha
+       according to the side (low vs high) of the subinterval in which
+       the sign change was found in the previous two passes.
+       If the sides were opposite, set alpha = 1.
+       If the sides were the same, then double alpha (if high side),
+       or halve alpha (if low side).
+       The next guess tmid is the secant method value if alpha = 1, but
+       is closer to tlo if alpha < 1, and closer to thi if alpha > 1.    */
+
+    if (sideprev == side) {
+      alpha = (side == 2) ? alpha*TWO : alpha*HALF;
+    } else {
+      alpha = ONE;
+    }
+
+    /* Set next root approximation tmid and get g(tmid).
+       If tmid is too close to tlo or thi, adjust it inward,
+       by a fractional distance that is between 0.1 and 0.5.  */
+    tmid = thi - (thi - tlo)*ghi[imax]/(ghi[imax] - alpha*glo[imax]);
+    if (ABS(tmid - tlo) < HALF*ttol) {
+      fracint = ABS(thi - tlo)/ttol;
+      fracsub = (fracint > FIVE) ? TENTH : HALF/fracint;
+      tmid = tlo + fracsub*(thi - tlo);
+    }
+    if (ABS(thi - tmid) < HALF*ttol) {
+      fracint = ABS(thi - tlo)/ttol;
+      fracsub = (fracint > FIVE) ? TENTH : HALF/fracint;
+      tmid = thi - fracsub*(thi - tlo);
+    }
+
+    (void) CVodeGetDky(cv_mem, tmid, 0, y);
+    retval = gfun(tmid, y, grout, g_data);
+    nge++;
+    if (retval != 0) return(CV_RTFUNC_FAIL);
+
+    /* Check to see in which subinterval g changes sign, and reset imax.
+       Set side = 1 if sign change is on low side, or 2 if on high side.  */  
+    maxfrac = ZERO;
+    zroot = FALSE;
+    sgnchg = FALSE;
+    sideprev = side;
+    for (i = 0;  i < nrtfn; i++) {
+      if (ABS(grout[i]) == ZERO) {
+        zroot = TRUE;
+      } else {
+        if (glo[i]*grout[i] < ZERO) {
+          gfrac = ABS(grout[i]/(grout[i] - glo[i]));
+          if (gfrac > maxfrac) {
+            sgnchg = TRUE;
+            maxfrac = gfrac;
+            imax = i;
+          }
+        }
+      }
+    }
+    if (sgnchg) {
+      /* Sign change found in (tlo,tmid); replace thi with tmid. */
+      thi = tmid;
+      for (i = 0; i < nrtfn; i++) ghi[i] = grout[i];
+      side = 1;
+      /* Stop at root thi if converged; otherwise loop. */
+      if (ABS(thi - tlo) <= ttol) break;
+      continue;  /* Return to looping point. */
+    }
+
+    if (zroot) {
+      /* No sign change in (tlo,tmid), but g = 0 at tmid; return root tmid. */
+      thi = tmid;
+      for (i = 0; i < nrtfn; i++) ghi[i] = grout[i];
+      break;
+    }
+
+    /* No sign change in (tlo,tmid), and no zero at tmid.
+       Sign change must be in (tmid,thi).  Replace tlo with tmid. */
+    tlo = tmid;
+    for (i = 0; i < nrtfn; i++) glo[i] = grout[i];
+    side = 2;
+    /* Stop at root thi if converged; otherwise loop back. */
+    if (ABS(thi - tlo) <= ttol) break;
+
+  } /* End of root-search loop */
+
+  /* Reset trout and grout, set iroots, and return RTFOUND. */
+  trout = thi;
+  for (i = 0; i < nrtfn; i++) {
+    grout[i] = ghi[i];
+    iroots[i] = 0;
+    if (ABS(ghi[i]) == ZERO) iroots[i] = 1;
+    if (glo[i]*ghi[i] < ZERO) iroots[i] = 1;
+  }
+  return(RTFOUND);
+}
+
+/* 
+ * -----------------------------------------------------------------
+ * Functions for combined norms
+ * -----------------------------------------------------------------
+ */
+
+/*
+ * CVQuadUpdateNorm
+ *
+ * Updates the norm old_nrm to account for all quadratures.
+ */
+
+static realtype CVQuadUpdateNorm(CVodeMem cv_mem, realtype old_nrm,
+                                 N_Vector xQ, N_Vector wQ)
+{
+  realtype qnrm;
+
+  qnrm = N_VWrmsNorm(xQ, wQ);
+  if (old_nrm > qnrm) return(old_nrm);
+  else                return(qnrm);
+}
+
+/*
+ * CVQuadUpdateDsm
+ *
+ *  Usage    : dms = CVQuadUpdateDsm(cv_mem, dsm, dsmQ);
+ *
+ * This routine updates the local error norm dsm with quadrature
+ * related information. Used only if quadratures are computed
+ * with FULL error control.
+ *
+ * Returns the maximum over the wheighted local error norms.
+ */
+
+static realtype CVQuadUpdateDsm(CVodeMem cv_mem, realtype old_dsm, 
+                                realtype dsmQ)
+{
+  if ( old_dsm > dsmQ ) return(old_dsm);
+  else                  return(dsmQ);
+}
+
+/*
+ * CVSensNorm
+ *
+ * This routine returns the maximum over the weighted root mean 
+ * square norm of xS with weight vectors wS:
+ *
+ *  max { wrms(xS[0],wS[0]) ... wrms(xS[Ns-1],wS[Ns-1]) }    
+ *
+ * Called by CVSensUpdateNorm or directly in the CV_STAGGERED approach 
+ * during the NLS solution and before the error test.
+ */
+
+static realtype CVSensNorm(CVodeMem cv_mem, N_Vector *xS, N_Vector *wS)
+{
+  int is;
+  realtype nrm, snrm;
+
+  nrm = N_VWrmsNorm(xS[0],wS[0]);
+  for (is=1; is<Ns; is++) {
+    snrm = N_VWrmsNorm(xS[is],wS[is]);
+    if ( snrm > nrm ) nrm = snrm;
+  }
+
+  return(nrm);
+
+}
+
+/*
+ * CVSensUpdateNorm
+ *
+ * Updates the norm old_nrm to account for all sensitivities.
+ */
+
+static realtype CVSensUpdateNorm(CVodeMem cv_mem, realtype old_nrm,
+                                 N_Vector *xS, N_Vector *wS)
+{
+  realtype snrm;
+  
+  snrm = CVSensNorm(cv_mem, xS, wS);
+  if (old_nrm > snrm) return(old_nrm);
+  else                return(snrm);
+}
+
+/*
+ * CVStgrUpdateNorm
+ *
+ *  Usage    : dms = CVStgrUpdateDsm(cv_mem, old_dsm, dsmS);
+ *
+ * This routine updates the local error norm old_dsm with sensitivity 
+ * related information. Used only in the CV_STAGGERED or CV_STAGGERED1 
+ * approach with FULL error control.This value is consistent with 
+ * the one computed in CVDoErrorTest when ism=CV_SIMULTANEOUS and 
+ * errconS=TRUE.
+ *
+ * Returns the maximum over the wheighted local error norms.
+ */
+
+static realtype CVStgrUpdateDsm(CVodeMem cv_mem, realtype old_dsm, 
+                                realtype dsmS)
+{
+  if ( old_dsm > dsmS ) return(old_dsm);
+  else                  return(dsmS);
+}
+
+/* 
+ * -----------------------------------------------------------------
+ * Wrappers for sensitivity RHS
+ * -----------------------------------------------------------------
+ */
+
+/*
+ * CVSensRhs
+ *
+ * CVSensRhs is a high level routine that returns right hand side 
+ * of sensitivity equations. Depending on the 'ifS' flag, it either 
+ * calls directly the fS routine (ifS=CV_ALLSENS) or (if ifS=CV_ONESENS) 
+ * calls the fS1 routine in a loop over all sensitivities.
+ *
+ * CVSensRhs is called:
+ *  (*) by CVode at the first step
+ *  (*) by CVYddNorm if errcon=TRUE
+ *  (*) by CVNlsFunctional, CVNlsNewton, and CVNewtonIteration
+ *      if ism=CV_SIMULTANEOUS
+ *  (*) by CVDoErrorTest when restarting from scratch
+ *  (*) in the corrector loop if ism=CV_STAGGERED
+ *  (*) by CVStgrDoErrorTest when restarting from scratch 
+ *
+ * The return value is that of the sensitivity RHS function fS,
+ *
+ */
+
+static int CVSensRhs(CVodeMem cv_mem, realtype time, 
+                     N_Vector ycur, N_Vector fcur, 
+                     N_Vector *yScur, N_Vector *fScur,
+                     N_Vector temp1, N_Vector temp2)
+{
+  int retval=0, is;
+
+  if (ifS==CV_ALLSENS) {
+    retval = fS(Ns, time, ycur, fcur, yScur, fScur, 
+                fS_data, temp1, temp2);
+    nfSe++;
+  } else {
+    for (is=0; is<Ns; is++) {
+      retval = fS1(Ns, time, ycur, fcur, is, yScur[is], fScur[is], 
+                   fS_data, temp1, temp2);
+      nfSe++;
+      if (retval != 0) break;
+    }
+  }
+
+  return(retval);
+}
+
+/*
+ * CVSensRhs1
+ *
+ * CVSensRhs1 is a high level routine that returns right hand side 
+ * of the is-th sensitivity equation. 
+ *
+ * CVSensRhs1 is called only during the CV_STAGGERED1 corrector loop
+ * (ifS must be CV_ONESENS, otherwise CVodeSensMalloc would have 
+ * issued an error message).
+ *
+ * The return value is that of the sensitivity RHS function fS1,
+ */
+
+static int CVSensRhs1(CVodeMem cv_mem, realtype time, 
+                      N_Vector ycur, N_Vector fcur, 
+                      int is, N_Vector yScur, N_Vector fScur,
+                      N_Vector temp1, N_Vector temp2)
+{
+  int retval;
+
+  retval = fS1(Ns, time, ycur, fcur, is, yScur, fScur, 
+               fS_data, temp1, temp2);
+  nfSe++;
+
+  return(retval);
+}
+
+/* 
+ * -----------------------------------------------------------------
+ * Internal DQ approximations for sensitivity RHS
+ * -----------------------------------------------------------------
+ */
+
+/* Undefine Readibility Constants */
+
+#undef Ns
+#undef y
+#undef yS
+#undef fS_data
+#undef ftemp
+
+/*
+ * CVSensRhsDQ   - internal CVSensRhsFn
+ *
+ * CVSensRhsDQ computes right hand side of all sensitivity equations
+ * by finite differences
+ */
+
+int CVSensRhsDQ(int Ns, realtype t, 
+                N_Vector y, N_Vector ydot, 
+                N_Vector *yS, N_Vector *ySdot, 
+                void *fS_data,  
+                N_Vector ytemp, N_Vector ftemp)
+{
+  int is, retval;
+  
+  for (is=0; is<Ns; is++) {
+    retval = CVSensRhs1DQ(Ns, t, y, ydot, is, yS[is], ySdot[is],
+                          fS_data, ytemp, ftemp);
+    if (retval!=0) return(retval);
+  }
+
+  return(0);
+}
+
+/*
+ * CVSensRhs1DQ   - internal CVSensRhs1Fn
+ *
+ * CVSensRhs1DQ computes the right hand side of the is-th sensitivity 
+ * equation by finite differences
+ *
+ * CVSensRhs1DQ returns 0 if successful. Otherwise it returns the 
+ * non-zero return value from f().
+ */
+
+int CVSensRhs1DQ(int Ns, realtype t, 
+                 N_Vector y, N_Vector ydot, 
+                 int is, N_Vector yS, N_Vector ySdot, 
+                 void *fS_data,
+                 N_Vector ytemp, N_Vector ftemp)
+{
+  CVodeMem cv_mem;
+  int retval, method;
+  int nfel = 0, which;
+  realtype psave, pbari;
+  realtype delta , rdelta;
+  realtype Deltap, rDeltap, r2Deltap;
+  realtype Deltay, rDeltay, r2Deltay;
+  realtype Delta , rDelta , r2Delta ;
+  realtype norms, ratio;
+  
+  /* fS_data points to cv_mem */
+  cv_mem = (CVodeMem) fS_data;
+
+  delta = RSqrt(MAX(reltol, uround));
+  rdelta = ONE/delta;
+  
+  pbari = pbar[is];
+
+  which = plist[is];
+
+  psave = p[which];
+  
+  Deltap  = pbari * delta;
+  rDeltap = ONE/Deltap;
+  norms   = N_VWrmsNorm(yS, ewt) * pbari;
+  rDeltay = MAX(norms, rdelta) / pbari;
+  Deltay  = ONE/rDeltay;
+  
+  if (DQrhomax == ZERO) {
+    /* No switching */
+    method = (DQtype==CV_CENTERED) ? CENTERED1 : FORWARD1;
+  } else {
+    /* switch between simultaneous/separate DQ */
+    ratio = Deltay * rDeltap;
+    if ( MAX(ONE/ratio, ratio) <= DQrhomax ) 
+      method = (DQtype==CV_CENTERED) ? CENTERED1 : FORWARD1;
+    else
+      method = (DQtype==CV_CENTERED) ? CENTERED2 : FORWARD2;
+  }
+
+  switch(method) {
+    
+  case CENTERED1:
+    
+    Delta = MIN(Deltay, Deltap);
+    r2Delta = HALF/Delta;
+    
+    N_VLinearSum(ONE,y,Delta,yS,ytemp);
+    p[which] = psave + Delta;
+
+    retval = f(t, ytemp, ySdot, f_data);
+    nfel++;
+    if (retval != 0) return(retval);
+    
+    N_VLinearSum(ONE,y,-Delta,yS,ytemp);
+    p[which] = psave - Delta;
+
+    retval = f(t, ytemp, ftemp, f_data);
+    nfel++;
+    if (retval != 0) return(retval);
+
+    N_VLinearSum(r2Delta,ySdot,-r2Delta,ftemp,ySdot);
+    
+    break;
+    
+  case CENTERED2:
+    
+    r2Deltap = HALF/Deltap;
+    r2Deltay = HALF/Deltay;
+    
+    N_VLinearSum(ONE,y,Deltay,yS,ytemp);
+
+    retval = f(t, ytemp, ySdot, f_data);
+    nfel++;
+    if (retval != 0) return(retval);
+
+    N_VLinearSum(ONE,y,-Deltay,yS,ytemp);
+
+    retval = f(t, ytemp, ftemp, f_data);
+    nfel++;
+    if (retval != 0) return(retval);
+
+    N_VLinearSum(r2Deltay, ySdot, -r2Deltay, ftemp, ySdot);
+    
+    p[which] = psave + Deltap;
+    retval = f(t, y, ytemp, f_data);
+    nfel++;
+    if (retval != 0) return(retval);
+
+    p[which] = psave - Deltap;
+    retval = f(t, y, ftemp, f_data);
+    nfel++;
+    if (retval != 0) return(retval);
+
+    N_VLinearSum(r2Deltap,ytemp,-r2Deltap,ftemp,ftemp);
+    
+    N_VLinearSum(ONE,ySdot,ONE,ftemp,ySdot);
+    
+    break;
+    
+  case FORWARD1:
+    
+    Delta = MIN(Deltay, Deltap);
+    rDelta = ONE/Delta;
+    
+    N_VLinearSum(ONE,y,Delta,yS,ytemp);
+    p[which] = psave + Delta;
+
+    retval = f(t, ytemp, ySdot, f_data);
+    nfel++;
+    if (retval != 0) return(retval);
+    
+    N_VLinearSum(rDelta,ySdot,-rDelta,ydot,ySdot);
+    
+    break;
+    
+  case FORWARD2:
+    
+    N_VLinearSum(ONE,y,Deltay,yS,ytemp);
+
+    retval = f(t, ytemp, ySdot, f_data);
+    nfel++;
+    if (retval != 0) return(retval);
+
+    N_VLinearSum(rDeltay, ySdot, -rDeltay, ydot, ySdot);
+    
+    p[which] = psave + Deltap;
+    retval = f(t, y, ytemp, f_data);
+    nfel++;
+    if (retval != 0) return(retval);
+
+    N_VLinearSum(rDeltap,ytemp,-rDeltap,ydot,ftemp);
+      
+    N_VLinearSum(ONE,ySdot,ONE,ftemp,ySdot);
+    
+    break;
+    
+  }
+  
+  p[which] = psave;
+  
+  /* Increment counter nfeS */
+  nfeS += nfel;
+  
+  return(0);
+}
+
+/* 
+ * -----------------------------------------------------------------
+ * Error message handling functions
+ * -----------------------------------------------------------------
+ */
+
+/* 
+ * CVProcessError is a high level error handling function
+ * - if cv_mem==NULL it prints the error message to stderr
+ * - otherwise, it sets-up and calls the error hadling function 
+ *   pointed to by cv_ehfun
+ */
+
+#define ehfun    (cv_mem->cv_ehfun)
+#define eh_data  (cv_mem->cv_eh_data)
+
+void CVProcessError(CVodeMem cv_mem, 
+                    int error_code, const char *module, const char *fname, 
+                    const char *msgfmt, ...)
+{
+  va_list ap;
+  char msg[256];
+
+  /* Initialize the argument pointer variable 
+     (msgfmt is the last required argument to CVProcessError) */
+
+  va_start(ap, msgfmt);
+
+  if (cv_mem == NULL) {    /* We write to stderr */
+
+#ifndef NO_FPRINTF_OUTPUT
+    fprintf(stderr, "\n[%s ERROR]  %s\n  ", module, fname);
+    fprintf(stderr, msgfmt);
+    fprintf(stderr, "\n\n");
+#endif
+
+  } else {                 /* We can call ehfun */
+
+    /* Compose the message */
+
+    vsprintf(msg, msgfmt, ap);
+
+    /* Call ehfun */
+
+    ehfun(error_code, module, fname, msg, eh_data);
+
+  }
+
+  /* Finalize argument processing */
+  
+  va_end(ap);
+
+  return;
+
+}
+
+/* 
+ * CVErrHandler is the default error handling function.
+ * It sends the error message to the stream pointed to by cv_errfp 
+ */
+
+#define errfp    (cv_mem->cv_errfp)
+
+void CVErrHandler(int error_code, const char *module,
+                  const char *function, char *msg, void *data)
+{
+  CVodeMem cv_mem;
+  char err_type[10];
+
+  /* data points to cv_mem here */
+
+  cv_mem = (CVodeMem) data;
+
+  if (error_code == CV_WARNING)
+    sprintf(err_type,"WARNING");
+  else
+    sprintf(err_type,"ERROR");
+
+#ifndef NO_FPRINTF_OUTPUT
+  if (errfp!=NULL) {
+    fprintf(errfp,"\n[%s %s]  %s\n",module,err_type,function);
+    fprintf(errfp,"  %s\n\n",msg);
+  }
+#endif
+
+  return;
+}
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_band.c b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_band.c
new file mode 100644
index 0000000000000000000000000000000000000000..c53cb786c8adcc5656403738c082a381dc6ebb02
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_band.c
@@ -0,0 +1,805 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2005, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the implementation file for the CVBAND linear solver.
+ * -----------------------------------------------------------------
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "cvodes_band_impl.h"
+#include "cvodes_impl.h"
+
+#include <sundials/sundials_math.h>
+
+/* Other Constants */
+
+#define MIN_INC_MULT RCONST(1000.0)
+#define ZERO         RCONST(0.0)
+#define ONE          RCONST(1.0)
+#define TWO          RCONST(2.0)
+
+/* CVBAND linit, lsetup, lsolve, and lfree routines */
+
+static int CVBandInit(CVodeMem cv_mem);
+
+static int CVBandSetup(CVodeMem cv_mem, int convfail, N_Vector ypred,
+                       N_Vector fpred, booleantype *jcurPtr, N_Vector vtemp1,
+                       N_Vector vtemp2, N_Vector vtemp3);
+
+static int CVBandSolve(CVodeMem cv_mem, N_Vector b, N_Vector weight,
+                       N_Vector ycur, N_Vector fcur);
+
+static void CVBandFree(CVodeMem cv_mem);
+
+/* CVBAND lfreeB function */
+
+static void CVBandFreeB(CVadjMem ca_mem);
+
+/* Wrapper function for adjoint code */
+
+static int CVAbandJac(long int nB, long int mupperB, 
+                      long int mlowerB, BandMat JB, realtype t, 
+                      N_Vector yB, N_Vector fyB, void *cvadj_mem, 
+                      N_Vector tmp1B, N_Vector tmp2B, N_Vector tmp3B);
+
+/* CVBAND DQJac routine */
+
+static int CVBandDQJac(long int n, long int mupper, long int mlower,
+                       BandMat J, realtype t,
+                       N_Vector y, N_Vector fy, void *jac_data,
+                       N_Vector tmp1, N_Vector tmp2, N_Vector tmp3);
+
+
+/* 
+ * ================================================================
+ *
+ *                   PART I - forward problems
+ *
+ * ================================================================
+ */
+
+
+/* Readability Replacements */
+
+#define lmm       (cv_mem->cv_lmm)
+#define f         (cv_mem->cv_f)
+#define f_data    (cv_mem->cv_f_data)
+#define uround    (cv_mem->cv_uround)
+#define nst       (cv_mem->cv_nst)
+#define tn        (cv_mem->cv_tn)
+#define h         (cv_mem->cv_h)
+#define gamma     (cv_mem->cv_gamma)
+#define gammap    (cv_mem->cv_gammap)
+#define gamrat    (cv_mem->cv_gamrat)
+#define ewt       (cv_mem->cv_ewt)
+#define nfe       (cv_mem->cv_nfe)
+#define linit     (cv_mem->cv_linit)
+#define lsetup    (cv_mem->cv_lsetup)
+#define lsolve    (cv_mem->cv_lsolve)
+#define lfree     (cv_mem->cv_lfree)
+#define lmem      (cv_mem->cv_lmem)
+#define vec_tmpl      (cv_mem->cv_tempv)
+#define setupNonNull  (cv_mem->cv_setupNonNull)
+
+#define n          (cvband_mem->b_n)
+#define jac        (cvband_mem->b_jac)
+#define M          (cvband_mem->b_M)
+#define mu         (cvband_mem->b_mu)
+#define ml         (cvband_mem->b_ml)
+#define storage_mu (cvband_mem->b_storage_mu)
+#define pivots     (cvband_mem->b_pivots)
+#define savedJ     (cvband_mem->b_savedJ)
+#define nstlj      (cvband_mem->b_nstlj)
+#define nje        (cvband_mem->b_nje)
+#define nfeB       (cvband_mem->b_nfeB)
+#define J_data     (cvband_mem->b_J_data)
+#define last_flag  (cvband_mem->b_last_flag)
+
+
+/*
+ * -----------------------------------------------------------------
+ * CVBand
+ * -----------------------------------------------------------------
+ * This routine initializes the memory record and sets various function
+ * fields specific to the band linear solver module.  CVBand first calls
+ * the existing lfree routine if this is not NULL.  It then sets the
+ * cv_linit, cv_lsetup, cv_lsolve, and cv_lfree fields in (*cvode_mem)
+ * to be CVBandInit, CVBandSetup, CVBandSolve, and CVBandFree,
+ * respectively.  It allocates memory for a structure of type
+ * CVBandMemRec and sets the cv_lmem field in (*cvode_mem) to the
+ * address of this structure.  It sets setupNonNull in (*cvode_mem) to be
+ * TRUE, b_mu to be mupper, b_ml to be mlower, and the b_jac field to be 
+ * CVBandDQJac.
+ * Finally, it allocates memory for M, savedJ, and pivot.  The CVBand
+ * return value is SUCCESS = 0, LMEM_FAIL = -1, or LIN_ILL_INPUT = -2.
+ *
+ * NOTE: The band linear solver assumes a serial implementation
+ *       of the NVECTOR package. Therefore, CVBand will first 
+ *       test for compatible a compatible N_Vector internal
+ *       representation by checking that the function 
+ *       N_VGetArrayPointer exists.
+ * -----------------------------------------------------------------
+ */
+                  
+int CVBand(void *cvode_mem, long int N,
+           long int mupper, long int mlower)
+{
+  CVodeMem cv_mem;
+  CVBandMem cvband_mem;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVBAND_MEM_NULL, "CVBAND", "CVBand", MSGB_CVMEM_NULL);
+    return(CVBAND_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  /* Test if the NVECTOR package is compatible with the BAND solver */
+  if (vec_tmpl->ops->nvgetarraypointer == NULL) {
+    CVProcessError(cv_mem, CVBAND_ILL_INPUT, "CVBAND", "CVBand", MSGB_BAD_NVECTOR);
+    return(CVBAND_ILL_INPUT);
+  }
+
+  if (lfree != NULL) lfree(cv_mem);
+
+  /* Set four main function fields in cv_mem */  
+  linit  = CVBandInit;
+  lsetup = CVBandSetup;
+  lsolve = CVBandSolve;
+  lfree  = CVBandFree;
+  
+  /* Get memory for CVBandMemRec */
+  cvband_mem = NULL;
+  cvband_mem = (CVBandMem) malloc(sizeof(CVBandMemRec));
+  if (cvband_mem == NULL) {
+    CVProcessError(cv_mem, CVBAND_MEM_FAIL, "CVBAND", "CVBand", MSGB_MEM_FAIL);
+    return(CVBAND_MEM_FAIL);
+  }
+  
+  /* Set default Jacobian routine and Jacobian data */
+  jac = CVBandDQJac;
+  J_data = cvode_mem;
+  last_flag = CVBAND_SUCCESS;
+
+  setupNonNull = TRUE;
+  
+  /* Load problem dimension */
+  n = N;
+
+  /* Load half-bandwiths in cvband_mem */
+  ml = mlower;
+  mu = mupper;
+
+  /* Test ml and mu for legality */
+  if ((ml < 0) || (mu < 0) || (ml >= N) || (mu >= N)) {
+    CVProcessError(cv_mem, CVBAND_ILL_INPUT, "CVBAND", "CVBand", MSGB_BAD_SIZES);
+    return(CVBAND_ILL_INPUT);
+  }
+
+  /* Set extended upper half-bandwith for M (required for pivoting) */
+  storage_mu = MIN(N-1, mu + ml);
+
+  /* Allocate memory for M, savedJ, and pivot arrays */
+  M = NULL;
+  M = BandAllocMat(N, mu, ml, storage_mu);
+  if (M == NULL) {
+    CVProcessError(cv_mem, CVBAND_MEM_FAIL, "CVBAND", "CVBand", MSGB_MEM_FAIL);
+    free(cvband_mem); cvband_mem = NULL;
+    return(CVBAND_MEM_FAIL);
+  }
+  savedJ = NULL;
+  savedJ = BandAllocMat(N, mu, ml, mu);
+  if (savedJ == NULL) {
+    CVProcessError(cv_mem, CVBAND_MEM_FAIL, "CVBAND", "CVBand", MSGB_MEM_FAIL);
+    BandFreeMat(M);
+    free(cvband_mem); cvband_mem = NULL;
+    return(CVBAND_MEM_FAIL);
+  }
+  pivots = NULL;
+  pivots = BandAllocPiv(N);
+  if (pivots == NULL) {
+    CVProcessError(cv_mem, CVBAND_MEM_FAIL, "CVBAND", "CVBand", MSGB_MEM_FAIL);
+    BandFreeMat(M);
+    BandFreeMat(savedJ);
+    free(cvband_mem); cvband_mem = NULL;
+    return(CVBAND_MEM_FAIL);
+  }
+
+  /* Attach linear solver memory to integrator memory */
+  lmem = cvband_mem;
+
+  return(CVBAND_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVBandSetJacFn
+ * -----------------------------------------------------------------
+ */
+
+int CVBandSetJacFn(void *cvode_mem, CVBandJacFn bjac, void *jac_data)
+{
+  CVodeMem cv_mem;
+  CVBandMem cvband_mem;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVBAND_MEM_NULL, "CVBAND", "CVBandSetJacFn", MSGB_CVMEM_NULL);
+    return(CVBAND_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (lmem == NULL) {
+    CVProcessError(cv_mem, CVBAND_LMEM_NULL, "CVBAND", "CVBandSetJacFn", MSGB_LMEM_NULL);
+    return(CVBAND_LMEM_NULL);
+  }
+  cvband_mem = (CVBandMem) lmem;
+
+  jac = bjac;
+  if (bjac != NULL) J_data = jac_data;
+
+  return(CVBAND_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVBandGetWorkSpace
+ * -----------------------------------------------------------------
+ */
+
+int CVBandGetWorkSpace(void *cvode_mem, long int *lenrwLS, long int *leniwLS)
+{
+  CVodeMem cv_mem;
+  CVBandMem cvband_mem;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVBAND_MEM_NULL, "CVBAND", "CVBandGetWorkSpace", MSGB_CVMEM_NULL);
+    return(CVBAND_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (lmem == NULL) {
+    CVProcessError(cv_mem, CVBAND_LMEM_NULL, "CVBAND", "CVBandGetWorkSpace", MSGB_LMEM_NULL);
+    return(CVBAND_LMEM_NULL);
+  }
+  cvband_mem = (CVBandMem) lmem;
+
+  *lenrwLS = n*(storage_mu + mu + 2*ml + 2);
+  *leniwLS = n;
+
+  return(CVBAND_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVBandGetNumJacEvals
+ * -----------------------------------------------------------------
+ */
+
+int CVBandGetNumJacEvals(void *cvode_mem, long int *njevals)
+{
+  CVodeMem cv_mem;
+  CVBandMem cvband_mem;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVBAND_MEM_NULL, "CVBAND", "CVBandGetNumJacEvals", MSGB_CVMEM_NULL);
+    return(CVBAND_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (lmem == NULL) {
+    CVProcessError(cv_mem, CVBAND_LMEM_NULL, "CVBAND", "CVBandGetNumJacEvals", MSGB_LMEM_NULL);
+    return(CVBAND_LMEM_NULL);
+  }
+  cvband_mem = (CVBandMem) lmem;
+
+  *njevals = nje;
+
+  return(CVBAND_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVBandGetNumRhsEvals
+ * -----------------------------------------------------------------
+ */
+
+int CVBandGetNumRhsEvals(void *cvode_mem, long int *nfevalsLS)
+{
+  CVodeMem cv_mem;
+  CVBandMem cvband_mem;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVBAND_MEM_NULL, "CVBAND", "CVBandGetNumRhsEvals", MSGB_CVMEM_NULL);
+    return(CVBAND_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (lmem == NULL) {
+    CVProcessError(cv_mem, CVBAND_LMEM_NULL, "CVBAND", "CVBandGetNumRhsEvals", MSGB_LMEM_NULL);
+    return(CVBAND_LMEM_NULL);
+  }
+  cvband_mem = (CVBandMem) lmem;
+
+  *nfevalsLS = nfeB;
+
+  return(CVBAND_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVBandGetLastFlag
+ * -----------------------------------------------------------------
+ */
+
+int CVBandGetLastFlag(void *cvode_mem, int *flag)
+{
+  CVodeMem cv_mem;
+  CVBandMem cvband_mem;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVBAND_MEM_NULL, "CVBAND", "CVBandGetLastFlag", MSGB_CVMEM_NULL);
+    return(CVBAND_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (lmem == NULL) {
+    CVProcessError(cv_mem, CVBAND_LMEM_NULL, "CVBAND", "CVBandGetLastFlag", MSGB_LMEM_NULL);
+    return(CVBAND_LMEM_NULL);
+  }
+  cvband_mem = (CVBandMem) lmem;
+
+  *flag = last_flag;
+
+  return(CVBAND_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVBandGetReturnFlagName
+ * -----------------------------------------------------------------
+ */
+
+char *CVBandGetReturnFlagName(int flag)
+{
+  char *name;
+
+  name = (char *)malloc(30*sizeof(char));
+
+  switch(flag) {
+  case CVBAND_SUCCESS:
+    sprintf(name,"CVBAND_SUCCESS");
+    break;  
+  case CVBAND_MEM_NULL:
+    sprintf(name,"CVBAND_MEM_NULL");
+    break;
+  case CVBAND_LMEM_NULL:
+    sprintf(name,"CVBAND_LMEM_NULL");
+    break;
+  case CVBAND_ILL_INPUT:
+    sprintf(name,"CVBAND_ILL_INPUT");
+    break;
+  case CVBAND_MEM_FAIL:
+    sprintf(name,"CVBAND_MEM_FAIL");
+    break;
+  case CVBAND_JACFUNC_UNRECVR:
+    sprintf(name,"CVBAND_JACFUNC_UNRECVR");
+    break;
+  case CVBAND_JACFUNC_RECVR:
+    sprintf(name,"CVBAND_JACFUNC_RECVR");
+    break;
+  case CVBAND_ADJMEM_NULL:
+    sprintf(name,"CVBAND_ADJMEM_NULL");
+    break;
+  case CVBAND_LMEMB_NULL:
+    sprintf(name,"CVBAND_LMEMB_NULL");
+    break;
+  default:
+    sprintf(name,"NONE");
+  }
+
+  return(name);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVBandInit
+ * -----------------------------------------------------------------
+ * This routine does remaining initializations specific to the band
+ * linear solver.
+ * -----------------------------------------------------------------
+ */
+
+static int CVBandInit(CVodeMem cv_mem)
+{
+  CVBandMem cvband_mem;
+
+  cvband_mem = (CVBandMem) lmem;
+
+  nje   = 0;
+  nfeB  = 0;
+  nstlj = 0;
+
+  if (jac == NULL) {
+    jac = CVBandDQJac;
+    J_data = cv_mem;
+  }
+
+  last_flag = CVBAND_SUCCESS;
+  return(0);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVBandSetup
+ * -----------------------------------------------------------------
+ * This routine does the setup operations for the band linear solver.
+ * It makes a decision whether or not to call the Jacobian evaluation
+ * routine based on various state variables, and if not it uses the 
+ * saved copy.  In any case, it constructs the Newton matrix 
+ * M = I - gamma*J, updates counters, and calls the band LU 
+ * factorization routine.
+ * -----------------------------------------------------------------
+ */
+
+static int CVBandSetup(CVodeMem cv_mem, int convfail, N_Vector ypred,
+                       N_Vector fpred, booleantype *jcurPtr, N_Vector vtemp1,
+                       N_Vector vtemp2, N_Vector vtemp3)
+{
+  booleantype jbad, jok;
+  realtype dgamma;
+  long int ier;
+  CVBandMem cvband_mem;
+  int retval;
+
+  cvband_mem = (CVBandMem) lmem;
+
+  /* Use nst, gamma/gammap, and convfail to set J eval. flag jok */
+
+  dgamma = ABS((gamma/gammap) - ONE);
+  jbad = (nst == 0) || (nst > nstlj + CVB_MSBJ) ||
+         ((convfail == CV_FAIL_BAD_J) && (dgamma < CVB_DGMAX)) ||
+         (convfail == CV_FAIL_OTHER);
+  jok = !jbad;
+  
+  if (jok) {
+
+    /* If jok = TRUE, use saved copy of J */
+    *jcurPtr = FALSE;
+    BandCopy(savedJ, M, mu, ml);
+
+  } else {
+
+    /* If jok = FALSE, call jac routine for new J value */
+    nje++;
+    nstlj = nst;
+    *jcurPtr = TRUE;
+    BandZero(M); 
+
+    retval = jac(n, mu, ml, M, tn, ypred, fpred, J_data, vtemp1, vtemp2, vtemp3);
+    if (retval < 0) {
+      CVProcessError(cv_mem, CVBAND_JACFUNC_UNRECVR, "CVBAND", "CVBandSetup", MSGB_JACFUNC_FAILED);
+      last_flag = CVBAND_JACFUNC_UNRECVR;
+      return(-1);
+    }
+    if (retval > 0) {
+      last_flag = CVBAND_JACFUNC_RECVR;
+      return(1);
+    }
+
+    BandCopy(M, savedJ, mu, ml);
+
+  }
+  
+  /* Scale and add I to get M = I - gamma*J */
+  BandScale(-gamma, M);
+  BandAddI(M);
+
+  /* Do LU factorization of M */
+  ier = BandGBTRF(M, pivots);
+
+  /* Return 0 if the LU was complete; otherwise return 1 */
+  if (ier > 0) {
+    last_flag = ier;
+    return(1);
+  }
+  last_flag = CVBAND_SUCCESS;
+  return(0);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVBandSolve
+ * -----------------------------------------------------------------
+ * This routine handles the solve operation for the band linear solver
+ * by calling the band backsolve routine.  The return value is 0.
+ * -----------------------------------------------------------------
+ */
+
+static int CVBandSolve(CVodeMem cv_mem, N_Vector b, N_Vector weight,
+                       N_Vector ycur, N_Vector fcur)
+{
+  CVBandMem cvband_mem;
+  realtype *bd;
+
+  cvband_mem = (CVBandMem) lmem;
+
+  bd = N_VGetArrayPointer(b);
+
+  BandGBTRS(M, pivots, bd);
+
+  /* If CV_BDF, scale the correction to account for change in gamma */
+  if ((lmm == CV_BDF) && (gamrat != ONE)) {
+    N_VScale(TWO/(ONE + gamrat), b, b);
+  }
+
+  last_flag = CVBAND_SUCCESS;
+  return(0);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVBandFree
+ * -----------------------------------------------------------------
+ * This routine frees memory specific to the band linear solver.
+ * -----------------------------------------------------------------
+ */
+
+static void CVBandFree(CVodeMem cv_mem)
+{
+  CVBandMem cvband_mem;
+
+  cvband_mem = (CVBandMem) lmem;
+
+  BandFreeMat(M);
+  BandFreeMat(savedJ);
+  BandFreePiv(pivots);
+  free(cvband_mem); cvband_mem = NULL;
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVBandDQJac
+ * -----------------------------------------------------------------
+ * This routine generates a banded difference quotient approximation to
+ * the Jacobian of f(t,y).  It assumes that a band matrix of type
+ * BandMat is stored column-wise, and that elements within each column
+ * are contiguous. This makes it possible to get the address of a column
+ * of J via the macro BAND_COL and to write a simple for loop to set
+ * each of the elements of a column in succession.
+ * -----------------------------------------------------------------
+ */
+
+static int CVBandDQJac(long int N, long int mupper, long int mlower,
+                       BandMat J, realtype t,
+                       N_Vector y, N_Vector fy, void *jac_data,
+                       N_Vector tmp1, N_Vector tmp2, N_Vector tmp3)
+{
+  N_Vector ftemp, ytemp;
+  realtype fnorm, minInc, inc, inc_inv, srur;
+  realtype *col_j, *ewt_data, *fy_data, *ftemp_data, *y_data, *ytemp_data;
+  long int group, i, j, width, ngroups, i1, i2;
+  int retval = 0;
+
+  CVodeMem cv_mem;
+  CVBandMem cvband_mem;
+
+  /* jac_dat points to cvode_mem */
+  cv_mem = (CVodeMem) jac_data;
+  cvband_mem = (CVBandMem) lmem;
+
+  /* Rename work vectors for use as temporary values of y and f */
+  ftemp = tmp1;
+  ytemp = tmp2;
+
+  /* Obtain pointers to the data for ewt, fy, ftemp, y, ytemp */
+  ewt_data   = N_VGetArrayPointer(ewt);
+  fy_data    = N_VGetArrayPointer(fy);
+  ftemp_data = N_VGetArrayPointer(ftemp);
+  y_data     = N_VGetArrayPointer(y);
+  ytemp_data = N_VGetArrayPointer(ytemp);
+
+  /* Load ytemp with y = predicted y vector */
+  N_VScale(ONE, y, ytemp);
+
+  /* Set minimum increment based on uround and norm of f */
+  srur = RSqrt(uround);
+  fnorm = N_VWrmsNorm(fy, ewt);
+  minInc = (fnorm != ZERO) ?
+           (MIN_INC_MULT * ABS(h) * uround * N * fnorm) : ONE;
+
+  /* Set bandwidth and number of column groups for band differencing */
+  width = mlower + mupper + 1;
+  ngroups = MIN(width, N);
+  
+  for (group=1; group <= ngroups; group++) {
+    
+    /* Increment all y_j in group */
+    for(j=group-1; j < N; j+=width) {
+      inc = MAX(srur*ABS(y_data[j]), minInc/ewt_data[j]);
+      ytemp_data[j] += inc;
+    }
+
+    /* Evaluate f with incremented y */
+
+    retval = f(tn, ytemp, ftemp, f_data);
+    nfeB++;
+    if (retval != 0) break;
+
+    /* Restore ytemp, then form and load difference quotients */
+    for (j=group-1; j < N; j+=width) {
+      ytemp_data[j] = y_data[j];
+      col_j = BAND_COL(J,j);
+      inc = MAX(srur*ABS(y_data[j]), minInc/ewt_data[j]);
+      inc_inv = ONE/inc;
+      i1 = MAX(0, j-mupper);
+      i2 = MIN(j+mlower, N-1);
+      for (i=i1; i <= i2; i++)
+        BAND_COL_ELEM(col_j,i,j) =
+          inc_inv * (ftemp_data[i] - fy_data[i]);
+    }
+  }
+  
+  return(retval);
+}
+
+
+/* 
+ * ================================================================
+ *
+ *                   PART II - backward problems
+ *
+ * ================================================================
+ */
+
+
+/* Additional readability replacements */
+
+#define ytmp        (ca_mem->ca_ytmp)
+#define getY        (ca_mem->ca_getY)
+#define lmemB       (ca_mem->ca_lmemB)
+#define lfreeB      (ca_mem->ca_lfreeB)
+
+#define bjac_B      (cvbandB_mem->b_bjacB)
+#define jac_data_B  (cvbandB_mem->b_jac_dataB)
+
+/*
+ * CVBandB and CVBandSet*B
+ *
+ * Wrappers for the backward phase around the corresponding 
+ * CVODES functions
+ */
+
+int CVBandB(void *cvadj_mem, long int nB, 
+            long int mupperB, long int mlowerB)
+{
+  CVadjMem ca_mem;
+  CVBandMemB cvbandB_mem;
+  CVodeMem cvB_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CVBAND_ADJMEM_NULL, "CVBAND", "CVBandB", MSGB_CAMEM_NULL);
+    return(CVBAND_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  cvB_mem = ca_mem->cvb_mem;
+
+  /* Get memory for CVBandMemRecB */
+  cvbandB_mem = (CVBandMemB) malloc(sizeof(CVBandMemRecB));
+  if (cvbandB_mem == NULL) {
+    CVProcessError(cvB_mem, CVBAND_MEM_FAIL, "CVBAND", "CVBandB", MSGB_MEM_FAIL);
+    return(CVBAND_MEM_FAIL);
+  }
+
+  bjac_B = NULL;
+  jac_data_B = NULL;
+
+  /* attach lmemB and lfreeB */
+  lmemB = cvbandB_mem;
+  lfreeB = CVBandFreeB;
+
+  flag = CVBand(cvB_mem, nB, mupperB, mlowerB);
+
+  if (flag != CVBAND_SUCCESS) {
+    free(cvbandB_mem);
+    cvbandB_mem = NULL;
+  }
+
+  return(flag);
+}
+
+int CVBandSetJacFnB(void *cvadj_mem, CVBandJacFnB bjacB, void *jac_dataB)
+{
+  CVadjMem ca_mem;
+  CVBandMemB cvbandB_mem;
+  CVodeMem cvB_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CVBAND_ADJMEM_NULL, "CVBAND", "CVBandSetJacFnB", MSGB_CAMEM_NULL);
+    return(CVBAND_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  cvB_mem = ca_mem->cvb_mem;
+
+  if (lmemB == NULL) {
+    CVProcessError(cvB_mem, CVBAND_LMEMB_NULL, "CVBAND", "CVBandSetJacFnB", MSGB_LMEMB_NULL);
+    return(CVBAND_LMEMB_NULL);
+  }
+  cvbandB_mem = (CVBandMemB) lmemB;
+
+  bjac_B     = bjacB;
+  jac_data_B = jac_dataB;
+
+  flag = CVBandSetJacFn(cvB_mem, CVAbandJac, cvadj_mem);
+
+  return(flag);
+}
+
+/*
+ * CVBandFreeB 
+ */
+
+static void CVBandFreeB(CVadjMem ca_mem)
+{
+  CVBandMemB cvbandB_mem;
+
+  cvbandB_mem = (CVBandMemB) lmemB;
+
+  free(cvbandB_mem);
+}
+
+/*
+ * CVAbandJac
+ *
+ * This routine interfaces to the CVBandJacFnB routine provided 
+ * by the user.
+ * NOTE: jac_data actually contains cvadj_mem
+ */
+
+static int CVAbandJac(long int nB, long int mupperB, 
+                      long int mlowerB, BandMat JB, realtype t, 
+                      N_Vector yB, N_Vector fyB, void *cvadj_mem, 
+                      N_Vector tmp1B, N_Vector tmp2B, N_Vector tmp3B)
+{
+  CVadjMem ca_mem;
+  CVodeMem cvB_mem;
+  CVBandMemB cvbandB_mem;
+  int retval, flag;
+
+  ca_mem = (CVadjMem) cvadj_mem;
+  cvB_mem = ca_mem->cvb_mem;
+  cvbandB_mem = (CVBandMemB) lmemB;
+
+  /* Forward solution from interpolation */
+  flag = getY(ca_mem, t, ytmp);
+  if (flag != CV_SUCCESS) {
+    CVProcessError(cvB_mem, -1, "CVBAND", "CVAbandJac", MSGB_BAD_T);
+    return(-1);
+  }
+
+  /* Call user's adjoint band bjacB routine */
+  retval = bjac_B(nB, mupperB, mlowerB, JB, t, ytmp, yB, fyB, jac_data_B,
+                  tmp1B, tmp2B, tmp3B);
+
+  return(retval);
+}
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_band_impl.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_band_impl.h
new file mode 100644
index 0000000000000000000000000000000000000000..e6c2f93177f6a5ac3ff39aa83381eb3a075d465d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_band_impl.h
@@ -0,0 +1,106 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2005, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * Implementation header file for the band linear solver, CVBAND.
+ * -----------------------------------------------------------------
+ */
+
+#ifndef _CVSBAND_IMPL_H
+#define _CVSBAND_IMPL_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#include <cvodes/cvodes_band.h>
+
+  /*
+   * -----------------------------------------------------------------
+   * Types: CVBandMemRec, CVBandMem                                
+   * -----------------------------------------------------------------
+   * The type CVBandMem is pointer to a CVBandMemRec.
+   * This structure contains CVBand solver-specific data.                
+   *
+   * CVBand attaches such a structure to the lmem field of CVodeMem
+   * -----------------------------------------------------------------
+   */                                                                
+
+  typedef struct {
+
+    long int b_n;           /* N = problem dimension                    */
+
+    CVBandJacFn b_jac;      /* jac = Jacobian routine to be called      */
+
+    long int b_ml;          /* b_ml = lower bandwidth of savedJ         */
+  
+    long int b_mu;          /* b_mu = upper bandwidth of savedJ         */ 
+  
+    long int b_storage_mu;  /* upper bandwith of M = MIN(N-1,b_mu+b_ml) */
+  
+    BandMat b_M;            /* M = I - gamma J, gamma = h / l1          */
+  
+    long int *b_pivots;     /* pivots = pivot array for PM = LU         */
+  
+    BandMat b_savedJ;       /* savedJ = old Jacobian                    */
+  
+    long int b_nstlj;       /* nstlj = nst at last Jacobian eval.       */
+  
+    long int b_nje;         /* nje = no. of calls to jac                */
+  
+    long int b_nfeB;        /* nfeB = no. of calls to f due to difference
+                               quotient band Jacobian approximation     */
+
+    void *b_J_data;         /* J_data is passed to jac                  */
+
+    int b_last_flag;        /* last error return flag                   */
+  
+  } CVBandMemRec, *CVBandMem;
+
+
+  /*
+   * -----------------------------------------------------------------
+   * Types : CVBandMemRecB, CVBandMemB       
+   * -----------------------------------------------------------------
+   * CVBandB attaches such a structure to the lmemB filed of CVadjMem
+   * -----------------------------------------------------------------
+   */
+
+  typedef struct {
+
+    CVBandJacFnB b_bjacB;
+    void *b_jac_dataB;
+
+  } CVBandMemRecB, *CVBandMemB;
+
+
+  /*
+   * -----------------------------------------------------------------
+   * Error Messages 
+   * -----------------------------------------------------------------
+   */
+
+#define MSGB_CVMEM_NULL "Integrator memory is NULL."
+#define MSGB_MEM_FAIL "A memory request failed."
+#define MSGB_BAD_SIZES "Illegal bandwidth parameter(s). Must have 0 <=  ml, mu <= N-1."
+#define MSGB_BAD_NVECTOR "A required vector operation is not implemented."
+#define MSGB_LMEM_NULL "CVBAND memory is NULL."
+#define MSGB_JACFUNC_FAILED "The Jacobian routine failed in an unrecoverable manner."
+
+#define MSGB_CAMEM_NULL "cvadj_mem = NULL illegal."
+#define MSGB_LMEMB_NULL "CVBAND memory is NULL for the backward integration."
+#define MSGB_BAD_T "Bad t for interpolation."
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_bandpre.c b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_bandpre.c
new file mode 100644
index 0000000000000000000000000000000000000000..737a36bc055992aca66a2167f4f7bb1dfb8fd6e5
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_bandpre.c
@@ -0,0 +1,647 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Radu Serban and Aaron Collier @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2005, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This file contains implementations of the banded difference
+ * quotient Jacobian-based preconditioner and solver routines for
+ * use with the CVSPILS linear solvers.
+ * -----------------------------------------------------------------
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "cvodes_impl.h"
+#include "cvodes_bandpre_impl.h"
+
+#include <cvodes/cvodes_sptfqmr.h>
+#include <cvodes/cvodes_spbcgs.h>
+#include <cvodes/cvodes_spgmr.h>
+
+#include <sundials/sundials_math.h>
+
+#define MIN_INC_MULT RCONST(1000.0)
+#define ZERO         RCONST(0.0)
+#define ONE          RCONST(1.0)
+
+/* Prototypes of CVBandPrecSetup and CVBandPrecSolve */
+  
+static int CVBandPrecSetup(realtype t, N_Vector y, N_Vector fy, 
+                           booleantype jok, booleantype *jcurPtr, 
+                           realtype gamma, void *bp_data,
+                           N_Vector tmp1, N_Vector tmp2, N_Vector tmp3);
+
+static int CVBandPrecSolve(realtype t, N_Vector y, N_Vector fy, 
+                           N_Vector r, N_Vector z, 
+                           realtype gamma, realtype delta,
+                           int lr, void *bp_data, N_Vector tmp);
+
+/* Prototype for difference quotient Jacobian calculation routine */
+
+static int CVBandPDQJac(CVBandPrecData pdata, 
+                        realtype t, N_Vector y, N_Vector fy, 
+                        N_Vector ftemp, N_Vector ytemp);
+
+/* 
+ * ================================================================
+ *
+ *                   PART I - forward problems
+ *
+ * ================================================================
+ */
+
+/* Redability replacements */
+
+#define vec_tmpl (cv_mem->cv_tempv)
+
+/*
+ * -----------------------------------------------------------------
+ * Malloc, Free, and Get Functions
+ * NOTE: The band linear solver assumes a serial implementation
+ *       of the NVECTOR package. Therefore, CVBandPrecAlloc will
+ *       first test for a compatible N_Vector internal representation
+ *       by checking that the function N_VGetArrayPointer exists.
+ * -----------------------------------------------------------------
+ */
+
+void *CVBandPrecAlloc(void *cvode_mem, long int N, 
+                      long int mu, long int ml)
+{
+  CVodeMem cv_mem;
+  CVBandPrecData pdata;
+  long int mup, mlp, storagemu;
+
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, 0, "CVBANDPRE", "CVBandPrecAlloc", MSGBP_CVMEM_NULL);
+    return(NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  /* Test if the NVECTOR package is compatible with the BAND preconditioner */
+  if(vec_tmpl->ops->nvgetarraypointer == NULL) {
+    CVProcessError(cv_mem, 0, "CVBANDPRE", "CVBandPrecAlloc", MSGBP_BAD_NVECTOR);
+    return(NULL);
+  }
+
+  pdata = NULL;
+  pdata = (CVBandPrecData) malloc(sizeof *pdata);  /* Allocate data memory */
+  if (pdata == NULL) {
+    CVProcessError(cv_mem, 0, "CVBANDPRE", "CVBandPrecAlloc", MSGBP_MEM_FAIL);
+    return(NULL);
+  }
+
+  /* Load pointers and bandwidths into pdata block. */
+  pdata->cvode_mem = cvode_mem;
+  pdata->N = N;
+  pdata->mu = mup = MIN(N-1, MAX(0,mu));
+  pdata->ml = mlp = MIN(N-1, MAX(0,ml));
+
+  /* Initialize nfeBP counter */
+  pdata->nfeBP = 0;
+
+  /* Allocate memory for saved banded Jacobian approximation. */
+  pdata->savedJ = NULL;
+  pdata->savedJ = BandAllocMat(N, mup, mlp, mup);
+  if (pdata->savedJ == NULL) {
+    free(pdata); pdata = NULL;
+    CVProcessError(cv_mem, 0, "CVBANDPRE", "CVBandPrecAlloc", MSGBP_MEM_FAIL);
+    return(NULL);
+  }
+
+  /* Allocate memory for banded preconditioner. */
+  storagemu = MIN(N-1, mup+mlp);
+  pdata->savedP = NULL;
+  pdata->savedP = BandAllocMat(N, mup, mlp, storagemu);
+  if (pdata->savedP == NULL) {
+    BandFreeMat(pdata->savedJ);
+    free(pdata); pdata = NULL;
+    CVProcessError(cv_mem, 0, "CVBANDPRE", "CVBandPrecAlloc", MSGBP_MEM_FAIL);
+    return(NULL);
+  }
+
+  /* Allocate memory for pivot array. */
+  pdata->pivots = NULL;
+  pdata->pivots = BandAllocPiv(N);
+  if (pdata->savedJ == NULL) {
+    BandFreeMat(pdata->savedP);
+    BandFreeMat(pdata->savedJ);
+    free(pdata); pdata = NULL;
+    CVProcessError(cv_mem, 0, "CVBANDPRE", "CVBandPrecAlloc", MSGBP_MEM_FAIL);
+    return(NULL);
+  }
+
+  return((void *) pdata);
+}
+
+int CVBPSptfqmr(void *cvode_mem, int pretype, int maxl, void *p_data)
+{
+  CVodeMem cv_mem;
+  int flag;
+
+  flag = CVSptfqmr(cvode_mem, pretype, maxl);
+  if(flag != CVSPILS_SUCCESS) return(flag);
+  
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if ( p_data == NULL ) {
+    CVProcessError(cv_mem, CVBANDPRE_PDATA_NULL, "CVBANDPRE", "CVBPSptfqmr", MSGBP_PDATA_NULL);
+    return(CVBANDPRE_PDATA_NULL);
+  } 
+
+  flag = CVSpilsSetPreconditioner(cvode_mem, CVBandPrecSetup, CVBandPrecSolve, p_data);
+  if(flag != CVSPILS_SUCCESS) return(flag);
+
+  return(CVSPILS_SUCCESS);
+}
+
+int CVBPSpbcg(void *cvode_mem, int pretype, int maxl, void *p_data)
+{
+  CVodeMem cv_mem;
+  int flag;
+
+  flag = CVSpbcg(cvode_mem, pretype, maxl);
+  if(flag != CVSPILS_SUCCESS) return(flag);
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if ( p_data == NULL ) {
+    CVProcessError(cv_mem, CVBANDPRE_PDATA_NULL, "CVBANDPRE", "CVBPSpbcg", MSGBP_PDATA_NULL);
+    return(CVBANDPRE_PDATA_NULL);
+  } 
+
+  flag = CVSpilsSetPreconditioner(cvode_mem, CVBandPrecSetup, CVBandPrecSolve, p_data);
+  if(flag != CVSPILS_SUCCESS) return(flag);
+
+  return(CVSPILS_SUCCESS);
+}
+
+int CVBPSpgmr(void *cvode_mem, int pretype, int maxl, void *p_data)
+{
+  CVodeMem cv_mem;
+  int flag;
+
+  flag = CVSpgmr(cvode_mem, pretype, maxl);
+  if(flag != CVSPILS_SUCCESS) return(flag);
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if ( p_data == NULL ) {
+    CVProcessError(cv_mem, CVBANDPRE_PDATA_NULL, "CVBANDPRE", "CVBPSpgmr", MSGBP_PDATA_NULL);
+    return(CVBANDPRE_PDATA_NULL);
+  }
+
+  flag = CVSpilsSetPreconditioner(cvode_mem, CVBandPrecSetup, CVBandPrecSolve, p_data);
+  if(flag != CVSPILS_SUCCESS) return(flag);
+
+  return(CVSPILS_SUCCESS);
+}
+
+void CVBandPrecFree(void **bp_data)
+{
+  CVBandPrecData pdata;
+
+  if (*bp_data == NULL) return;
+
+  pdata = (CVBandPrecData) (*bp_data);
+  BandFreeMat(pdata->savedJ);
+  BandFreeMat(pdata->savedP);
+  BandFreePiv(pdata->pivots);
+
+  free(*bp_data);
+  *bp_data = NULL;
+
+}
+
+int CVBandPrecGetWorkSpace(void *bp_data, long int *lenrwBP, long int *leniwBP)
+{
+  CVBandPrecData pdata;
+  long int N, ml, mu, smu;
+
+  if ( bp_data == NULL ) {
+    CVProcessError(NULL, CVBANDPRE_PDATA_NULL, "CVBANDPRE", "CVBandPrecGetWorkSpace", MSGBP_PDATA_NULL);
+    return(CVBANDPRE_PDATA_NULL);
+  } 
+
+  pdata = (CVBandPrecData) bp_data;
+
+  N   = pdata->N;
+  mu  = pdata->mu;
+  ml  = pdata->ml;
+  smu = MIN( N-1, mu + ml);
+
+  *leniwBP = pdata->N;
+  *lenrwBP = N * ( 2*ml + smu + mu + 2 );
+
+  return(CVBANDPRE_SUCCESS);
+}
+
+int CVBandPrecGetNumRhsEvals(void *bp_data, long int *nfevalsBP)
+{
+  CVBandPrecData pdata;
+
+  if (bp_data == NULL) {
+    CVProcessError(NULL, CVBANDPRE_PDATA_NULL, "CVBANDPRE", "CVBandPrecGetNumRhsEvals", MSGBP_PDATA_NULL);
+    return(CVBANDPRE_PDATA_NULL);
+  } 
+
+  pdata = (CVBandPrecData) bp_data;
+
+  *nfevalsBP = pdata->nfeBP;
+
+  return(CVBANDPRE_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVBandPrecGetReturnFlagName
+ * -----------------------------------------------------------------
+ */
+
+char *CVBandPrecGetReturnFlagName(int flag)
+{
+  char *name;
+
+  name = (char *)malloc(30*sizeof(char));
+
+  switch(flag) {
+  case CVBANDPRE_SUCCESS:
+    sprintf(name,"CVBANDPRE_SUCCESS");
+    break;    
+  case CVBANDPRE_PDATA_NULL:
+    sprintf(name,"CVBANDPRE_PDATA_NULL");
+    break;
+  case CVBANDPRE_RHSFUNC_UNRECVR:
+    sprintf(name,"CVBANDPRE_RHSFUNC_UNRECVR");
+    break;
+  case CVBANDPRE_ADJMEM_NULL:
+    sprintf(name,"CVBANDPRE_ADJMEM_NULL");
+    break;
+  case CVBANDPRE_MEM_FAIL:
+    sprintf(name,"CVBANDPRE_MEM_FAIL");
+    break;
+  default:
+    sprintf(name,"NONE");
+  }
+
+  return(name);
+}
+
+/* Readability Replacements */
+
+#define N      (pdata->N)
+#define mu     (pdata->mu)
+#define ml     (pdata->ml)
+#define pivots (pdata->pivots)
+#define savedJ (pdata->savedJ)
+#define savedP (pdata->savedP)
+#define nfeBP  (pdata->nfeBP)
+
+/*
+ * -----------------------------------------------------------------
+ * CVBandPrecSetup
+ * -----------------------------------------------------------------
+ * Together CVBandPrecSetup and CVBandPrecSolve use a banded
+ * difference quotient Jacobian to create a preconditioner.
+ * CVBandPrecSetup calculates a new J, if necessary, then
+ * calculates P = I - gamma*J, and does an LU factorization of P.
+ *
+ * The parameters of CVBandPrecSetup are as follows:
+ *
+ * t       is the current value of the independent variable.
+ *
+ * y       is the current value of the dependent variable vector,
+ *         namely the predicted value of y(t).
+ *
+ * fy      is the vector f(t,y).
+ *
+ * jok     is an input flag indicating whether Jacobian-related
+ *         data needs to be recomputed, as follows:
+ *           jok == FALSE means recompute Jacobian-related data
+ *                  from scratch.
+ *           jok == TRUE means that Jacobian data from the
+ *                  previous PrecSetup call will be reused
+ *                  (with the current value of gamma).
+ *         A CVBandPrecSetup call with jok == TRUE should only
+ *         occur after a call with jok == FALSE.
+ *
+ * *jcurPtr is a pointer to an output integer flag which is
+ *          set by CVBandPrecond as follows:
+ *            *jcurPtr = TRUE if Jacobian data was recomputed.
+ *            *jcurPtr = FALSE if Jacobian data was not recomputed,
+ *                       but saved data was reused.
+ *
+ * gamma   is the scalar appearing in the Newton matrix.
+ *
+ * bp_data is a pointer to preconditoner data - the same as the
+ *         bp_data parameter passed to CVSp*.
+ *
+ * tmp1, tmp2, and tmp3 are pointers to memory allocated
+ *           for vectors of length N for work space. This
+ *           routine uses only tmp1 and tmp2.
+ *
+ * The value to be returned by the CVBandPrecSetup function is
+ *   0  if successful, or
+ *   1  if the band factorization failed.
+ * -----------------------------------------------------------------
+ */
+
+static int CVBandPrecSetup(realtype t, N_Vector y, N_Vector fy, 
+                           booleantype jok, booleantype *jcurPtr, 
+                           realtype gamma, void *bp_data,
+                           N_Vector tmp1, N_Vector tmp2, N_Vector tmp3)
+{
+  long int ier;
+  CVBandPrecData pdata;
+  CVodeMem cv_mem;
+  int retval;
+
+  /* Assume matrix and pivots have already been allocated. */
+  pdata = (CVBandPrecData) bp_data;
+
+  cv_mem = (CVodeMem) pdata->cvode_mem;
+
+  if (jok) {
+
+    /* If jok = TRUE, use saved copy of J. */
+    *jcurPtr = FALSE;
+    BandCopy(savedJ, savedP, mu, ml);
+
+  } else {
+
+    /* If jok = FALSE, call CVBandPDQJac for new J value. */
+    *jcurPtr = TRUE;
+    BandZero(savedJ);
+
+    retval = CVBandPDQJac(pdata, t, y, fy, tmp1, tmp2);
+    if (retval < 0) {
+      CVProcessError(cv_mem, CVBANDPRE_RHSFUNC_UNRECVR, "CVBANDPRE", "CVBandPrecSetup", MSGBP_RHSFUNC_FAILED);
+      return(-1);
+    }
+    if (retval > 0) {
+      return(1);
+    }
+
+    BandCopy(savedJ, savedP, mu, ml);
+
+  }
+  
+  /* Scale and add I to get savedP = I - gamma*J. */
+  BandScale(-gamma, savedP);
+  BandAddI(savedP);
+ 
+  /* Do LU factorization of matrix. */
+  ier = BandGBTRF(savedP, pivots);
+ 
+  /* Return 0 if the LU was complete; otherwise return 1. */
+  if (ier > 0) return(1);
+  return(0);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVBandPrecSolve
+ * -----------------------------------------------------------------
+ * CVBandPrecSolve solves a linear system P z = r, where P is the
+ * matrix computed by CVBandPrecond.
+ *
+ * The parameters of CVBandPrecSolve used here are as follows:
+ *
+ * r       is the right-hand side vector of the linear system.
+ *
+ * bp_data is a pointer to preconditioner data - the same as the
+ *         bp_data parameter passed to CVSp*.
+ *
+ * z       is the output vector computed by CVBandPrecSolve.
+ *
+ * The value returned by the CVBandPrecSolve function is always 0,
+ * indicating success.
+ * -----------------------------------------------------------------
+ */ 
+
+static int CVBandPrecSolve(realtype t, N_Vector y, N_Vector fy, 
+                           N_Vector r, N_Vector z, 
+                           realtype gamma, realtype delta,
+                           int lr, void *bp_data, N_Vector tmp)
+{
+  CVBandPrecData pdata;
+  realtype *zd;
+
+  /* Assume matrix and pivots have already been allocated. */
+  pdata = (CVBandPrecData) bp_data;
+
+  /* Copy r to z. */
+  N_VScale(ONE, r, z);
+
+  /* Do band backsolve on the vector z. */
+  zd = N_VGetArrayPointer(z);
+
+  BandGBTRS(savedP, pivots, zd);
+
+  return(0);
+}
+
+#define ewt    (cv_mem->cv_ewt)
+#define uround (cv_mem->cv_uround)
+#define h      (cv_mem->cv_h)
+#define f      (cv_mem->cv_f)
+#define f_data (cv_mem->cv_f_data)
+
+/*
+ * -----------------------------------------------------------------
+ * CVBandPDQJac
+ * -----------------------------------------------------------------
+ * This routine generates a banded difference quotient approximation to
+ * the Jacobian of f(t,y). It assumes that a band matrix of type
+ * BandMat is stored column-wise, and that elements within each column
+ * are contiguous. This makes it possible to get the address of a column
+ * of J via the macro BAND_COL and to write a simple for loop to set
+ * each of the elements of a column in succession.
+ * -----------------------------------------------------------------
+ */
+
+static int CVBandPDQJac(CVBandPrecData pdata, 
+                        realtype t, N_Vector y, N_Vector fy, 
+                        N_Vector ftemp, N_Vector ytemp)
+{
+  CVodeMem cv_mem;
+  realtype fnorm, minInc, inc, inc_inv, srur;
+  long int group, i, j, width, ngroups, i1, i2;
+  realtype *col_j, *ewt_data, *fy_data, *ftemp_data, *y_data, *ytemp_data;
+  int retval;
+
+  cv_mem = (CVodeMem) pdata->cvode_mem;
+
+  /* Obtain pointers to the data for ewt, fy, ftemp, y, ytemp. */
+  ewt_data   = N_VGetArrayPointer(ewt);
+  fy_data    = N_VGetArrayPointer(fy);
+  ftemp_data = N_VGetArrayPointer(ftemp);
+  y_data     = N_VGetArrayPointer(y);
+  ytemp_data = N_VGetArrayPointer(ytemp);
+
+  /* Load ytemp with y = predicted y vector. */
+  N_VScale(ONE, y, ytemp);
+
+  /* Set minimum increment based on uround and norm of f. */
+  srur = RSqrt(uround);
+  fnorm = N_VWrmsNorm(fy, ewt);
+  minInc = (fnorm != ZERO) ?
+           (MIN_INC_MULT * ABS(h) * uround * N * fnorm) : ONE;
+
+  /* Set bandwidth and number of column groups for band differencing. */
+  width = ml + mu + 1;
+  ngroups = MIN(width, N);
+  
+  for (group = 1; group <= ngroups; group++) {
+    
+    /* Increment all y_j in group. */
+    for(j = group-1; j < N; j += width) {
+      inc = MAX(srur*ABS(y_data[j]), minInc/ewt_data[j]);
+      ytemp_data[j] += inc;
+    }
+
+    /* Evaluate f with incremented y. */
+
+    retval = f(t, ytemp, ftemp, f_data);
+    nfeBP++;
+    if (retval != 0) return(retval);
+
+    /* Restore ytemp, then form and load difference quotients. */
+    for (j = group-1; j < N; j += width) {
+      ytemp_data[j] = y_data[j];
+      col_j = BAND_COL(savedJ,j);
+      inc = MAX(srur*ABS(y_data[j]), minInc/ewt_data[j]);
+      inc_inv = ONE/inc;
+      i1 = MAX(0, j-mu);
+      i2 = MIN(j+ml, N-1);
+      for (i=i1; i <= i2; i++)
+        BAND_COL_ELEM(col_j,i,j) =
+          inc_inv * (ftemp_data[i] - fy_data[i]);
+    }
+  }
+
+  return(0);
+}
+
+/* 
+ * ================================================================
+ *
+ *                   PART II - backward problems
+ *
+ * ================================================================
+ */
+
+/* Additional readability replacements */
+
+#define bp_data_B   (ca_mem->ca_pmemB)
+
+/*
+ * CVBandPrecAllocB, CVBPSp*B
+ *
+ * Wrappers for the backward phase around the corresponding 
+ * CVODES functions
+ */
+
+int CVBandPrecAllocB(void *cvadj_mem, long int nB, 
+                     long int muB, long int mlB)
+{
+  CVadjMem ca_mem;
+  CVodeMem cvB_mem;
+  void *bp_dataB;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CVBANDPRE_ADJMEM_NULL, "CVBANDPRE", "CVBandPrecAlloc", MSGBP_CAMEM_NULL);
+    return(CVBANDPRE_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  cvB_mem = ca_mem->cvb_mem;
+
+  bp_dataB = CVBandPrecAlloc(cvB_mem, nB, muB, mlB);
+  if (bp_dataB == NULL) {
+    CVProcessError(cvB_mem, CVBANDPRE_MEM_FAIL, "CVBANDPRE", "CVBandPrecAlloc", MSGBP_MEM_FAIL);
+    return(CVBANDPRE_MEM_FAIL);
+  }
+
+  bp_data_B = bp_dataB;
+
+  return(CVBANDPRE_SUCCESS);
+
+}
+
+int CVBPSptfqmrB(void *cvadj_mem, int pretypeB, int maxlB)
+{
+  CVadjMem ca_mem;
+  CVodeMem cvB_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CVBANDPRE_ADJMEM_NULL, "CVBANDPRE", "CVBPSptfqmrAlloc", MSGBP_CAMEM_NULL);
+    return(CVBANDPRE_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  cvB_mem = ca_mem->cvb_mem;
+  
+  flag = CVBPSptfqmr(cvB_mem, pretypeB, maxlB, bp_data_B);
+
+  return(flag);
+}
+
+int CVBPSpbcgB(void *cvadj_mem, int pretypeB, int maxlB)
+{
+  CVadjMem ca_mem;
+  CVodeMem cvB_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CVBANDPRE_ADJMEM_NULL, "CVBANDPRE", "CVBPSptbcgAlloc", MSGBP_CAMEM_NULL);
+    return(CVBANDPRE_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  cvB_mem = ca_mem->cvb_mem;
+  
+  flag = CVBPSpbcg(cvB_mem, pretypeB, maxlB, bp_data_B);
+
+  return(flag);
+}
+
+int CVBPSpgmrB(void *cvadj_mem, int pretypeB, int maxlB)
+{
+  CVadjMem ca_mem;
+  CVodeMem cvB_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CVBANDPRE_ADJMEM_NULL, "CVBANDPRE", "CVBPSpgmrAlloc", MSGBP_CAMEM_NULL);
+    return(CVBANDPRE_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  cvB_mem = ca_mem->cvb_mem;
+  
+  flag = CVBPSpgmr(cvB_mem, pretypeB, maxlB, bp_data_B);
+
+  return(flag);
+}
+
+
+void CVBandPrecFreeB(void *cvadj_mem)
+{
+  CVadjMem ca_mem;
+
+  if (cvadj_mem == NULL) return;
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  CVBandPrecFree(&bp_data_B);
+}
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_bandpre_impl.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_bandpre_impl.h
new file mode 100644
index 0000000000000000000000000000000000000000..8cfed9b0436a2d49a6cace9f1fded05f4191ba64
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_bandpre_impl.h
@@ -0,0 +1,74 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2005, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * Implementation header file for the CVBANDPRE module.
+ * -----------------------------------------------------------------
+ */
+
+#ifndef _CVSBANDPRE_IMPL_H
+#define _CVSBANDPRE_IMPL_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#include <cvodes/cvodes_bandpre.h>
+#include <sundials/sundials_band.h>
+
+  /*
+   * -----------------------------------------------------------------
+   * Type: CVBandPrecData
+   * -----------------------------------------------------------------
+   */
+
+  typedef struct {
+
+    /* Data set by user in CVBandPrecAlloc */
+
+    long int N;
+    long int ml, mu;
+
+    /* Data set by CVBandPrecSetup */
+
+    BandMat savedJ;
+    BandMat savedP;
+    long int *pivots;
+
+    /* Rhs calls */
+
+    long int nfeBP;
+
+    /* Pointer to cvode_mem */
+
+    void *cvode_mem;
+
+  } *CVBandPrecData;
+
+  /*
+   * -----------------------------------------------------------------
+   * CVBANDPRE error messages
+   * -----------------------------------------------------------------
+   */
+
+#define MSGBP_CVMEM_NULL "Integrator memory is NULL."
+#define MSGBP_MEM_FAIL "A memory request failed."
+#define MSGBP_BAD_NVECTOR "A required vector operation is not implemented."
+#define MSGBP_PDATA_NULL "CVBANDPRE memory is NULL."
+#define MSGBP_RHSFUNC_FAILED "The right-hand side routine failed in an unrecoverable manner."
+
+#define MSGBP_CAMEM_NULL "cvadj_mem = NULL illegal."
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_bbdpre.c b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_bbdpre.c
new file mode 100644
index 0000000000000000000000000000000000000000..cb1f705d9754232887411ff6495924641f001372
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_bbdpre.c
@@ -0,0 +1,883 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Radu Serban and Aaron Collier @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2005, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This file contains implementations of routines for a
+ * band-block-diagonal preconditioner, i.e. a block-diagonal
+ * matrix with banded blocks, for use with CVODE, a CVSPILS linear
+ * solver, and the parallel implementation of NVECTOR.
+ * -----------------------------------------------------------------
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "cvodes_impl.h"
+#include "cvodes_bbdpre_impl.h"
+
+#include <cvodes/cvodes_sptfqmr.h>
+#include <cvodes/cvodes_spbcgs.h>
+#include <cvodes/cvodes_spgmr.h>
+
+#include <sundials/sundials_math.h>
+
+#define MIN_INC_MULT RCONST(1000.0)
+#define ZERO         RCONST(0.0)
+#define ONE          RCONST(1.0)
+
+/* Prototypes of functions CVBBDPrecSetup and CVBBDPrecSolve */
+
+static int CVBBDPrecSetup(realtype t, N_Vector y, N_Vector fy, 
+                          booleantype jok, booleantype *jcurPtr, 
+                          realtype gamma, void *bbd_data, 
+                          N_Vector tmp1, N_Vector tmp2, N_Vector tmp3);
+
+static int CVBBDPrecSolve(realtype t, N_Vector y, N_Vector fy, 
+                          N_Vector r, N_Vector z, 
+                          realtype gamma, realtype delta,
+                          int lr, void *bbd_data, N_Vector tmp);
+
+/* Wrapper functions for adjoint code */
+
+static int CVAgloc(long int NlocalB, realtype t, N_Vector yB, N_Vector gB, 
+                   void *cvadj_mem);
+
+static int CVAcfn(long int NlocalB, realtype t, N_Vector yB,
+                  void *cvadj_mem);
+
+/* Prototype for difference quotient Jacobian calculation routine */
+
+static int CVBBDDQJac(CVBBDPrecData pdata, realtype t, 
+                      N_Vector y, N_Vector gy, 
+                      N_Vector ytemp, N_Vector gtemp);
+
+
+/* 
+ * ================================================================
+ *
+ *                   PART I - forward problems
+ *
+ * ================================================================
+ */
+
+/* Redability replacements */
+
+#define uround   (cv_mem->cv_uround)
+#define vec_tmpl (cv_mem->cv_tempv)
+
+/*
+ * -----------------------------------------------------------------
+ * User-Callable Functions: malloc, reinit and free
+ * -----------------------------------------------------------------
+ */
+
+void *CVBBDPrecAlloc(void *cvode_mem, long int Nlocal, 
+                     long int mudq, long int mldq,
+                     long int mukeep, long int mlkeep, 
+                     realtype dqrely, 
+                     CVLocalFn gloc, CVCommFn cfn)
+{
+  CVodeMem cv_mem;
+  CVBBDPrecData pdata;
+  long int muk, mlk, storage_mu;
+
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, 0, "CVBBDPRE", "CVBBDPrecAlloc", MSGBBDP_CVMEM_NULL);
+    return(NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  /* Test if the NVECTOR package is compatible with the BLOCK BAND preconditioner */
+  if(vec_tmpl->ops->nvgetarraypointer == NULL) {
+    CVProcessError(cv_mem, 0, "CVBBDPRE", "CVBBDPrecAlloc", MSGBBDP_BAD_NVECTOR);
+    return(NULL);
+  }
+
+  /* Allocate data memory */
+  pdata = NULL;
+  pdata = (CVBBDPrecData) malloc(sizeof *pdata);  
+  if (pdata == NULL) {
+    CVProcessError(cv_mem, 0, "CVBBDPRE", "CVBBDPrecAlloc", MSGBBDP_MEM_FAIL);
+    return(NULL);
+  }
+
+  /* Set pointers to gloc and cfn; load half-bandwidths */
+  pdata->cvode_mem = cvode_mem;
+  pdata->gloc = gloc;
+  pdata->cfn = cfn;
+  pdata->mudq = MIN(Nlocal-1, MAX(0,mudq));
+  pdata->mldq = MIN(Nlocal-1, MAX(0,mldq));
+  muk = MIN(Nlocal-1, MAX(0,mukeep));
+  mlk = MIN(Nlocal-1, MAX(0,mlkeep));
+  pdata->mukeep = muk;
+  pdata->mlkeep = mlk;
+
+  /* Allocate memory for saved Jacobian */
+  pdata->savedJ = BandAllocMat(Nlocal, muk, mlk, muk);
+  if (pdata->savedJ == NULL) { 
+    free(pdata); pdata = NULL; 
+    CVProcessError(cv_mem, 0, "CVBBDPRE", "CVBBDPrecAlloc", MSGBBDP_MEM_FAIL);
+    return(NULL); 
+  }
+
+  /* Allocate memory for preconditioner matrix */
+  storage_mu = MIN(Nlocal-1, muk + mlk);
+  pdata->savedP = NULL;
+  pdata->savedP = BandAllocMat(Nlocal, muk, mlk, storage_mu);
+  if (pdata->savedP == NULL) {
+    BandFreeMat(pdata->savedJ);
+    free(pdata); pdata = NULL;
+    CVProcessError(cv_mem, 0, "CVBBDPRE", "CVBBDPrecAlloc", MSGBBDP_MEM_FAIL);
+    return(NULL);
+  }
+  /* Allocate memory for pivots */
+  pdata->pivots = NULL;
+  pdata->pivots = BandAllocPiv(Nlocal);
+  if (pdata->savedJ == NULL) {
+    BandFreeMat(pdata->savedP);
+    BandFreeMat(pdata->savedJ);
+    free(pdata); pdata = NULL;
+    CVProcessError(cv_mem, 0, "CVBBDPRE", "CVBBDPrecAlloc", MSGBBDP_MEM_FAIL);
+    return(NULL);
+  }
+
+  /* Set pdata->dqrely based on input dqrely (0 implies default). */
+  pdata->dqrely = (dqrely > ZERO) ? dqrely : RSqrt(uround);
+
+  /* Store Nlocal to be used in CVBBDPrecSetup */
+  pdata->n_local = Nlocal;
+
+  /* Set work space sizes and initialize nge */
+  pdata->rpwsize = Nlocal*(muk + 2*mlk + storage_mu + 2);
+  pdata->ipwsize = Nlocal;
+  pdata->nge = 0;
+
+  return((void *)pdata);
+}
+
+int CVBBDSptfqmr(void *cvode_mem, int pretype, int maxl, void *bbd_data)
+{
+  CVodeMem cv_mem;
+  int flag;
+
+  flag = CVSptfqmr(cvode_mem, pretype, maxl);
+  if(flag != CVSPILS_SUCCESS) return(flag);
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (bbd_data == NULL) {
+    CVProcessError(cv_mem, CVBBDPRE_PDATA_NULL, "CVBBDPRE", "CVBBDSptfqmr", MSGBBDP_PDATA_NULL);
+    return(CVBBDPRE_PDATA_NULL);
+  } 
+
+  flag = CVSpilsSetPreconditioner(cvode_mem, CVBBDPrecSetup, CVBBDPrecSolve, bbd_data);
+  if(flag != CVSPILS_SUCCESS) return(flag);
+
+  return(CVSPILS_SUCCESS);
+}
+
+int CVBBDSpbcg(void *cvode_mem, int pretype, int maxl, void *bbd_data)
+{
+  CVodeMem cv_mem;
+  int flag;
+
+  flag = CVSpbcg(cvode_mem, pretype, maxl);
+  if(flag != CVSPILS_SUCCESS) return(flag);
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (bbd_data == NULL) {
+    CVProcessError(cv_mem, CVBBDPRE_PDATA_NULL, "CVBBDPRE", "CVBBDSpbcg", MSGBBDP_PDATA_NULL);
+    return(CVBBDPRE_PDATA_NULL);
+  } 
+
+  flag = CVSpilsSetPreconditioner(cvode_mem, CVBBDPrecSetup, CVBBDPrecSolve, bbd_data);
+  if(flag != CVSPILS_SUCCESS) return(flag);
+
+  return(CVSPILS_SUCCESS);
+}
+
+int CVBBDSpgmr(void *cvode_mem, int pretype, int maxl, void *bbd_data)
+{
+  CVodeMem cv_mem;
+  int flag;
+
+  flag = CVSpgmr(cvode_mem, pretype, maxl);
+  if(flag != CVSPILS_SUCCESS) return(flag);
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (bbd_data == NULL) {
+    CVProcessError(cv_mem, CVBBDPRE_PDATA_NULL, "CVBBDPRE", "CVBBDSpgmr", MSGBBDP_PDATA_NULL);
+    return(CVBBDPRE_PDATA_NULL);
+  } 
+
+  flag = CVSpilsSetPreconditioner(cvode_mem, CVBBDPrecSetup, CVBBDPrecSolve, bbd_data);
+  if(flag != CVSPILS_SUCCESS) return(flag);
+
+  return(CVSPILS_SUCCESS);
+}
+
+int CVBBDPrecReInit(void *bbd_data, 
+                    long int mudq, long int mldq, 
+                    realtype dqrely, 
+                    CVLocalFn gloc, CVCommFn cfn)
+{
+  CVBBDPrecData pdata;
+  CVodeMem cv_mem;
+  long int Nlocal;
+
+  if (bbd_data == NULL) {
+    CVProcessError(NULL, CVBBDPRE_PDATA_NULL, "CVBBDPRE", "CVBBDPrecReInit", MSGBBDP_PDATA_NULL);
+    return(CVBBDPRE_PDATA_NULL);
+  } 
+
+  pdata  = (CVBBDPrecData) bbd_data;
+  cv_mem = (CVodeMem) pdata->cvode_mem;
+
+  /* Set pointers to gloc and cfn; load half-bandwidths */
+  pdata->gloc = gloc;
+  pdata->cfn = cfn;
+  Nlocal = pdata->n_local;
+  pdata->mudq = MIN(Nlocal-1, MAX(0,mudq));
+  pdata->mldq = MIN(Nlocal-1, MAX(0,mldq));
+
+  /* Set pdata->dqrely based on input dqrely (0 implies default). */
+  pdata->dqrely = (dqrely > ZERO) ? dqrely : RSqrt(uround);
+
+  /* Re-initialize nge */
+  pdata->nge = 0;
+
+  return(CVBBDPRE_SUCCESS);
+}
+
+void CVBBDPrecFree(void **bbd_data)
+{
+  CVBBDPrecData pdata;
+  
+  if (*bbd_data == NULL) return;
+
+  pdata = (CVBBDPrecData) (*bbd_data);
+  BandFreeMat(pdata->savedJ);
+  BandFreeMat(pdata->savedP);
+  BandFreePiv(pdata->pivots);
+
+  free(*bbd_data);
+  *bbd_data = NULL;
+
+}
+
+int CVBBDPrecGetWorkSpace(void *bbd_data, long int *lenrwBBDP, long int *leniwBBDP)
+{
+  CVBBDPrecData pdata;
+
+  if (bbd_data == NULL) {
+    CVProcessError(NULL, CVBBDPRE_PDATA_NULL, "CVBBDPRE", "CVBBDPrecGetWorkSpace", MSGBBDP_PDATA_NULL);    
+    return(CVBBDPRE_PDATA_NULL);
+  } 
+
+  pdata = (CVBBDPrecData) bbd_data;
+
+  *lenrwBBDP = pdata->rpwsize;
+  *leniwBBDP = pdata->ipwsize;
+
+  return(CVBBDPRE_SUCCESS);
+}
+
+int CVBBDPrecGetNumGfnEvals(void *bbd_data, long int *ngevalsBBDP)
+{
+  CVBBDPrecData pdata;
+
+  if (bbd_data == NULL) {
+    CVProcessError(NULL, CVBBDPRE_PDATA_NULL, "CVBBDPRE", "CVBBDPrecGetNumGfnEvals", MSGBBDP_PDATA_NULL);
+    return(CVBBDPRE_PDATA_NULL);
+  } 
+
+  pdata = (CVBBDPrecData) bbd_data;
+
+  *ngevalsBBDP = pdata->nge;
+
+  return(CVBBDPRE_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVBBDPrecGetReturnFlagName
+ * -----------------------------------------------------------------
+ */
+
+char *CVBBDPrecGetReturnFlagName(int flag)
+{
+  char *name;
+
+  name = (char *)malloc(30*sizeof(char));
+
+  switch(flag) {
+  case CVBBDPRE_SUCCESS:
+    sprintf(name,"CVBBDPRE_SUCCESS");
+    break; 
+  case CVBBDPRE_PDATA_NULL:
+    sprintf(name,"CVBBDPRE_PDATA_NULL");
+    break;
+  case CVBBDPRE_FUNC_UNRECVR:
+    sprintf(name,"CVBBDPRE_FUNC_UNRECVR");
+    break;
+  case CVBBDPRE_ADJMEM_NULL:
+    sprintf(name,"CVBBDPRE_ADJMEM_NULL");
+    break;
+  case CVBBDPRE_PDATAB_NULL:
+    sprintf(name,"CVBBDPRE_PDATAB_NULL");
+    break;
+  case CVBBDPRE_MEM_FAIL:
+    sprintf(name,"CVBBDPRE_MEM_FAIL");
+    break;
+  default:
+    sprintf(name,"NONE");
+  }
+
+  return(name);
+}
+
+/* Readability Replacements */
+
+#define Nlocal (pdata->n_local)
+#define mudq   (pdata->mudq)
+#define mldq   (pdata->mldq)
+#define mukeep (pdata->mukeep)
+#define mlkeep (pdata->mlkeep)
+#define dqrely (pdata->dqrely)
+#define gloc   (pdata->gloc)
+#define cfn    (pdata->cfn)
+#define savedJ (pdata->savedJ)
+#define savedP (pdata->savedP)
+#define pivots (pdata->pivots)
+#define nge    (pdata->nge)
+
+/*
+ * -----------------------------------------------------------------
+ * Function : CVBBDPrecSetup                                      
+ * -----------------------------------------------------------------
+ * CVBBDPrecSetup generates and factors a banded block of the
+ * preconditioner matrix on each processor, via calls to the
+ * user-supplied gloc and cfn functions. It uses difference
+ * quotient approximations to the Jacobian elements.
+ *
+ * CVBBDPrecSetup calculates a new J,if necessary, then calculates
+ * P = I - gamma*J, and does an LU factorization of P.
+ *
+ * The parameters of CVBBDPrecSetup used here are as follows:
+ *
+ * t       is the current value of the independent variable.
+ *
+ * y       is the current value of the dependent variable vector,
+ *         namely the predicted value of y(t).
+ *
+ * fy      is the vector f(t,y).
+ *
+ * jok     is an input flag indicating whether Jacobian-related
+ *         data needs to be recomputed, as follows:
+ *           jok == FALSE means recompute Jacobian-related data
+ *                  from scratch.
+ *           jok == TRUE  means that Jacobian data from the
+ *                  previous CVBBDPrecon call can be reused
+ *                  (with the current value of gamma).
+ *         A CVBBDPrecon call with jok == TRUE should only occur
+ *         after a call with jok == FALSE.
+ *
+ * jcurPtr is a pointer to an output integer flag which is
+ *         set by CVBBDPrecon as follows:
+ *           *jcurPtr = TRUE if Jacobian data was recomputed.
+ *           *jcurPtr = FALSE if Jacobian data was not recomputed,
+ *                      but saved data was reused.
+ *
+ * gamma   is the scalar appearing in the Newton matrix.
+ *
+ * bbd_data  is a pointer to user data - the same as the P_data
+ *           parameter passed to CVSp*. For CVBBDPrecon,
+ *           this should be of type CVBBDData.
+ *
+ * tmp1, tmp2, and tmp3 are pointers to memory allocated
+ *           for NVectors which are be used by CVBBDPrecSetup
+ *           as temporary storage or work space.
+ *
+ * Return value:
+ * The value returned by this CVBBDPrecSetup function is the int
+ *   0  if successful,
+ *   1  for a recoverable error (step will be retried).
+ * -----------------------------------------------------------------
+ */
+
+static int CVBBDPrecSetup(realtype t, N_Vector y, N_Vector fy, 
+                          booleantype jok, booleantype *jcurPtr, 
+                          realtype gamma, void *bbd_data, 
+                          N_Vector tmp1, N_Vector tmp2, N_Vector tmp3)
+{
+  long int ier;
+  CVBBDPrecData pdata;
+  CVodeMem cv_mem;
+  int retval;
+
+  pdata = (CVBBDPrecData) bbd_data;
+
+  cv_mem = (CVodeMem) pdata->cvode_mem;
+
+  if (jok) {
+
+    /* If jok = TRUE, use saved copy of J */
+    *jcurPtr = FALSE;
+    BandCopy(savedJ, savedP, mukeep, mlkeep);
+
+  } else {
+
+    /* Otherwise call CVBBDDQJac for new J value */
+    *jcurPtr = TRUE;
+    BandZero(savedJ);
+
+    retval = CVBBDDQJac(pdata, t, y, tmp1, tmp2, tmp3);
+    if (retval < 0) {
+      CVProcessError(cv_mem, CVBBDPRE_FUNC_UNRECVR, "CVBBDPRE", "CVBBDPrecSetup", MSGBBDP_FUNC_FAILED);
+      return(-1);
+    }
+    if (retval > 0) {
+      return(1);
+    }
+
+    BandCopy(savedJ, savedP, mukeep, mlkeep);
+
+  }
+  
+  /* Scale and add I to get P = I - gamma*J */
+  BandScale(-gamma, savedP);
+  BandAddI(savedP);
+ 
+  /* Do LU factorization of P in place */
+  ier = BandGBTRF(savedP, pivots);
+ 
+  /* Return 0 if the LU was complete; otherwise return 1 */
+  if (ier > 0) return(1);
+  return(0);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * Function : CVBBDPrecSolve
+ * -----------------------------------------------------------------
+ * CVBBDPrecSolve solves a linear system P z = r, with the
+ * band-block-diagonal preconditioner matrix P generated and
+ * factored by CVBBDPrecSetup.
+ *
+ * The parameters of CVBBDPrecSolve used here are as follows:
+ *
+ * r      is the right-hand side vector of the linear system.
+ *
+ * bbd_data is a pointer to the preconditioner data returned by
+ *          CVBBDPrecAlloc.
+ *
+ * z      is the output vector computed by CVBBDPrecSolve.
+ *
+ * The value returned by the CVBBDPrecSolve function is always 0,
+ * indicating success.
+ * -----------------------------------------------------------------
+ */
+
+static int CVBBDPrecSolve(realtype t, N_Vector y, N_Vector fy, 
+                          N_Vector r, N_Vector z, 
+                          realtype gamma, realtype delta,
+                          int lr, void *bbd_data, N_Vector tmp)
+{
+  CVBBDPrecData pdata;
+  realtype *zd;
+
+  pdata = (CVBBDPrecData) bbd_data;
+
+  /* Copy r to z, then do backsolve and return */
+  N_VScale(ONE, r, z);
+  
+  zd = N_VGetArrayPointer(z);
+
+  BandGBTRS(savedP, pivots, zd);
+
+  return(0);
+}
+
+#define ewt    (cv_mem->cv_ewt)
+#define h      (cv_mem->cv_h)
+#define f_data (cv_mem->cv_f_data)
+
+/*
+ * -----------------------------------------------------------------
+ * Function : CVBBDDQJac
+ * -----------------------------------------------------------------
+ * This routine generates a banded difference quotient approximation
+ * to the local block of the Jacobian of g(t,y). It assumes that a
+ * band matrix of type BandMat is stored columnwise, and that elements
+ * within each column are contiguous. All matrix elements are generated
+ * as difference quotients, by way of calls to the user routine gloc.
+ * By virtue of the band structure, the number of these calls is
+ * bandwidth + 1, where bandwidth = mldq + mudq + 1.
+ * But the band matrix kept has bandwidth = mlkeep + mukeep + 1.
+ * This routine also assumes that the local elements of a vector are
+ * stored contiguously.
+ * -----------------------------------------------------------------
+ */
+
+static int CVBBDDQJac(CVBBDPrecData pdata, realtype t, 
+                      N_Vector y, N_Vector gy, 
+                      N_Vector ytemp, N_Vector gtemp)
+{
+  CVodeMem cv_mem;
+  realtype gnorm, minInc, inc, inc_inv;
+  long int group, i, j, width, ngroups, i1, i2;
+  realtype *y_data, *ewt_data, *gy_data, *gtemp_data, *ytemp_data, *col_j;
+  int retval;
+
+  cv_mem = (CVodeMem) pdata->cvode_mem;
+
+  /* Load ytemp with y = predicted solution vector */
+  N_VScale(ONE, y, ytemp);
+
+  /* Call cfn and gloc to get base value of g(t,y) */
+  if (cfn != NULL) {
+    retval = cfn(Nlocal, t, y, f_data);
+    if (retval != 0) return(retval);
+  }
+
+  retval = gloc(Nlocal, t, ytemp, gy, f_data);
+  nge++;
+  if (retval != 0) return(retval);
+
+  /* Obtain pointers to the data for various vectors */
+  y_data     =  N_VGetArrayPointer(y);
+  gy_data    =  N_VGetArrayPointer(gy);
+  ewt_data   =  N_VGetArrayPointer(ewt);
+  ytemp_data =  N_VGetArrayPointer(ytemp);
+  gtemp_data =  N_VGetArrayPointer(gtemp);
+
+  /* Set minimum increment based on uround and norm of g */
+  gnorm = N_VWrmsNorm(gy, ewt);
+  minInc = (gnorm != ZERO) ?
+           (MIN_INC_MULT * ABS(h) * uround * Nlocal * gnorm) : ONE;
+
+  /* Set bandwidth and number of column groups for band differencing */
+  width = mldq + mudq + 1;
+  ngroups = MIN(width, Nlocal);
+
+  /* Loop over groups */  
+  for (group=1; group <= ngroups; group++) {
+    
+    /* Increment all y_j in group */
+    for(j=group-1; j < Nlocal; j+=width) {
+      inc = MAX(dqrely*ABS(y_data[j]), minInc/ewt_data[j]);
+      ytemp_data[j] += inc;
+    }
+
+    /* Evaluate g with incremented y */
+    retval = gloc(Nlocal, t, ytemp, gtemp, f_data);
+    nge++;
+    if (retval != 0) return(retval);
+
+    /* Restore ytemp, then form and load difference quotients */
+    for (j=group-1; j < Nlocal; j+=width) {
+      ytemp_data[j] = y_data[j];
+      col_j = BAND_COL(savedJ,j);
+      inc = MAX(dqrely*ABS(y_data[j]), minInc/ewt_data[j]);
+      inc_inv = ONE/inc;
+      i1 = MAX(0, j-mukeep);
+      i2 = MIN(j+mlkeep, Nlocal-1);
+      for (i=i1; i <= i2; i++)
+        BAND_COL_ELEM(col_j,i,j) =
+          inc_inv * (gtemp_data[i] - gy_data[i]);
+    }
+  }
+
+  return(0);
+}
+
+
+/* 
+ * ================================================================
+ *
+ *                   PART II - backward problems
+ *
+ * ================================================================
+ */
+
+
+/* Additional readability replacements */
+
+#define ytmp        (ca_mem->ca_ytmp)
+#define f_data_B    (ca_mem->ca_f_dataB)
+#define getY        (ca_mem->ca_getY)
+#define pmemB       (ca_mem->ca_pmemB)
+
+#define bbd_data_B  (cvbbdB_mem->bbd_dataB)
+#define gloc_B      (cvbbdB_mem->glocB)
+#define cfn_B       (cvbbdB_mem->cfnB)
+
+
+/*
+ * CVBBDPrecAllocB, CVBPSp*B
+ *
+ * Wrappers for the backward phase around the corresponding 
+ * CVODES functions
+ */
+
+int CVBBDPrecAllocB(void *cvadj_mem, long int NlocalB, 
+                    long int mudqB, long int mldqB, 
+                    long int mukeepB, long int mlkeepB, 
+                    realtype dqrelyB,
+                    CVLocalFnB glocB, CVCommFnB cfnB)
+{
+  CVadjMem ca_mem;
+  CVBBDPrecDataB cvbbdB_mem;
+  CVodeMem cvB_mem;
+  void *bbd_dataB;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CVBBDPRE_ADJMEM_NULL, "CVBBDPRE", "CVBBDPrecAllocB", MSGBBDP_CAMEM_NULL);
+    return(CVBBDPRE_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  cvB_mem = ca_mem->cvb_mem;
+
+  /* Get memory for CVBBDPrecDataB */
+  cvbbdB_mem = NULL;
+  cvbbdB_mem = (CVBBDPrecDataB) malloc(sizeof(* cvbbdB_mem));
+  if (cvbbdB_mem == NULL) {
+    CVProcessError(cvB_mem, CVBBDPRE_MEM_FAIL, "CVBBDPRE", "CVBBDPrecAllocB", MSGBBDP_MEM_FAIL);
+    return(CVBBDPRE_MEM_FAIL);
+  }
+
+  gloc_B = glocB;
+  cfn_B  = cfnB;
+
+  bbd_dataB = CVBBDPrecAlloc(cvB_mem, NlocalB, 
+                             mudqB, mldqB,
+                             mukeepB, mlkeepB, 
+                             dqrelyB, 
+                             CVAgloc, CVAcfn);
+  if (bbd_dataB == NULL) {
+    free(cvbbdB_mem); cvbbdB_mem = NULL;
+
+    return(CVBBDPRE_MEM_FAIL);
+  }
+
+  bbd_data_B = bbd_dataB;
+
+  /* attach pmemB */
+  pmemB = cvbbdB_mem;
+
+  return(CVBBDPRE_SUCCESS);
+
+}
+
+int CVBBDSptfqmrB(void *cvadj_mem, int pretypeB, int maxlB)
+{
+
+  CVadjMem ca_mem;
+  CVBBDPrecDataB cvbbdB_mem;
+  CVodeMem cvB_mem;
+  int flag;
+  
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CVBBDPRE_ADJMEM_NULL, "CVBBDPRE", "CVBBDSptfqmrB", MSGBBDP_CAMEM_NULL);
+    return(CVBBDPRE_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+  
+  cvB_mem = ca_mem->cvb_mem;
+  
+  if (pmemB == NULL) {
+    CVProcessError(cvB_mem, CVBBDPRE_PDATAB_NULL, "CVBBDPRE", "CVBBDSptfqmrB", MSGBBDP_PDATAB_NULL);
+    return(CVBBDPRE_PDATAB_NULL);
+  }
+  cvbbdB_mem = (CVBBDPrecDataB) pmemB;
+
+  flag = CVBBDSptfqmr(cvB_mem, pretypeB, maxlB, bbd_data_B);
+
+  return(flag);
+
+}
+
+int CVBBDSpbcgB(void *cvadj_mem, int pretypeB, int maxlB)
+{
+
+  CVadjMem ca_mem;
+  CVBBDPrecDataB cvbbdB_mem;
+  CVodeMem cvB_mem;
+  int flag;
+  
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CVBBDPRE_ADJMEM_NULL, "CVBBDPRE", "CVBBDSpbcgB", MSGBBDP_CAMEM_NULL);
+    return(CVBBDPRE_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+  
+  cvB_mem = ca_mem->cvb_mem;
+  
+  if (pmemB == NULL) {
+    CVProcessError(cvB_mem, CVBBDPRE_PDATAB_NULL, "CVBBDPRE", "CVBBDSpbcgB", MSGBBDP_PDATAB_NULL);
+    return(CVBBDPRE_PDATAB_NULL);
+  }
+  cvbbdB_mem = (CVBBDPrecDataB) pmemB;
+
+  flag = CVBBDSpbcg(cvB_mem, pretypeB, maxlB, bbd_data_B);
+
+  return(flag);
+
+}
+
+int CVBBDSpgmrB(void *cvadj_mem, int pretypeB, int maxlB)
+{
+
+  CVadjMem ca_mem;
+  CVBBDPrecDataB cvbbdB_mem;
+  CVodeMem cvB_mem;
+  int flag;
+  
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CVBBDPRE_ADJMEM_NULL, "CVBBDPRE", "CVBBDSpgmrB", MSGBBDP_CAMEM_NULL);
+    return(CV_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+  
+  cvB_mem = ca_mem->cvb_mem;
+  
+  if (pmemB == NULL) {
+    CVProcessError(cvB_mem, CVBBDPRE_PDATAB_NULL, "CVBBDPRE", "CVBBDSpgmrB", MSGBBDP_PDATAB_NULL);
+    return(CVBBDPRE_PDATAB_NULL);
+  }
+  cvbbdB_mem = (CVBBDPrecDataB) pmemB;
+
+  flag = CVBBDSpgmr(cvB_mem, pretypeB, maxlB, bbd_data_B);
+
+  return(flag);
+
+}
+
+int CVBBDPrecReInitB(void *cvadj_mem, long int mudqB, long int mldqB,
+                     realtype dqrelyB, CVLocalFnB glocB, CVCommFnB cfnB)
+{
+  CVadjMem ca_mem;
+  CVodeMem cvB_mem;
+  CVBBDPrecDataB cvbbdB_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CVBBDPRE_ADJMEM_NULL, "CVBBDPRE", "CVBBDPrecReInitB", MSGBBDP_CAMEM_NULL);
+    return(CVBBDPRE_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+  
+  cvB_mem = ca_mem->cvb_mem;
+
+  if (pmemB == NULL) {
+    CVProcessError(cvB_mem, CVBBDPRE_PDATAB_NULL, "CVBBDPRE", "CVBBDPrecReInitB", MSGBBDP_PDATAB_NULL);
+    return(CVBBDPRE_PDATAB_NULL);
+  }
+  cvbbdB_mem = (CVBBDPrecDataB) pmemB;
+
+  gloc_B = glocB;
+  cfn_B  = cfnB;
+
+  flag = CVBBDPrecReInit(bbd_data_B, mudqB, mldqB,
+                         dqrelyB, CVAgloc, CVAcfn);
+
+  return(flag);
+}
+
+
+void CVBBDPrecFreeB(void *cvadj_mem)
+{
+  CVadjMem ca_mem;
+  CVBBDPrecDataB cvbbdB_mem;
+
+  if (cvadj_mem == NULL) return;
+  ca_mem = (CVadjMem) cvadj_mem;
+  
+  if (pmemB == NULL) return;
+  cvbbdB_mem = (CVBBDPrecDataB) pmemB;
+
+  CVBBDPrecFree(&bbd_data_B);
+  
+  free(pmemB); pmemB = NULL;
+}
+
+
+/*
+ * CVAgloc
+ *
+ * This routine interfaces to the CVLocalFnB routine 
+ * provided by the user.
+ * NOTE: f_data actually contains cvadj_mem
+ */
+
+static int CVAgloc(long int NlocalB, realtype t, N_Vector yB, N_Vector gB, 
+                   void *cvadj_mem)
+{
+  CVadjMem ca_mem;
+  CVodeMem cvB_mem;
+  CVBBDPrecDataB cvbbdB_mem;
+  int retval, flag;
+
+  ca_mem = (CVadjMem) cvadj_mem;
+  cvB_mem = ca_mem->cvb_mem;
+  cvbbdB_mem = (CVBBDPrecDataB) pmemB;
+
+  /* Forward solution from interpolation */
+  flag = getY(ca_mem, t, ytmp);
+  if (flag != CV_SUCCESS) {
+    CVProcessError(cvB_mem, -1, "CVBBDPRE", "CVAgloc", MSGBBDP_BAD_T);
+    return(-1);
+  } 
+
+  /* Call user's adjoint glocB routine */
+  retval = gloc_B(NlocalB, t, ytmp, yB, gB, f_data_B);
+
+  return(retval);
+}
+
+/*
+ * CVAcfn
+ *
+ * This routine interfaces to the CVCommFnB routine 
+ * provided by the user.
+ * NOTE: f_data actually contains cvadj_mem
+ */
+
+static int CVAcfn(long int NlocalB, realtype t, N_Vector yB,
+                  void *cvadj_mem)
+{
+  CVadjMem ca_mem;
+  CVodeMem cvB_mem;
+  CVBBDPrecDataB cvbbdB_mem;
+  int retval, flag;
+
+  ca_mem = (CVadjMem) cvadj_mem;
+  cvB_mem = ca_mem->cvb_mem;
+  cvbbdB_mem = (CVBBDPrecDataB) pmemB;
+
+  if (cfn_B == NULL) return(0);
+
+  /* Forward solution from interpolation */
+  flag = getY(ca_mem, t, ytmp);
+  if (flag != CV_SUCCESS) {
+    CVProcessError(cvB_mem, -1, "CVBBDPRE", "CVAcfn", MSGBBDP_BAD_T);
+    return(-1);
+  } 
+
+  /* Call user's adjoint cfnB routine */
+  retval = cfn_B(NlocalB, t, ytmp, yB, f_data_B);
+
+  return(retval);
+}
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_bbdpre_impl.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_bbdpre_impl.h
new file mode 100644
index 0000000000000000000000000000000000000000..028cd29da0fa3ea178d1e516042354c0e9207e07
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_bbdpre_impl.h
@@ -0,0 +1,103 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2005, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * Implementation header file for the CVBBDPRE module.
+ * -----------------------------------------------------------------
+ */
+
+#ifndef _CVSBBDPRE_IMPL_H
+#define _CVSBBDPRE_IMPL_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#include <cvodes/cvodes_bbdpre.h>
+#include <sundials/sundials_band.h>
+
+  /*
+   * -----------------------------------------------------------------
+   * Type: CVBBDPrecData
+   * -----------------------------------------------------------------
+   */
+
+  typedef struct {
+
+    /* passed by user to CVBBDPrecAlloc and used by PrecSetup/PrecSolve */
+
+    long int mudq, mldq, mukeep, mlkeep;
+    realtype dqrely;
+    CVLocalFn gloc;
+    CVCommFn cfn;
+
+    /* set by CVBBDPrecSetup and used by CVBBDPrecSolve */
+
+    BandMat savedJ;
+    BandMat savedP;
+    long int *pivots;
+
+    /* set by CVBBDPrecAlloc and used by CVBBDPrecSetup */
+
+    long int n_local;
+
+    /* available for optional output */
+
+    long int rpwsize;
+    long int ipwsize;
+    long int nge;
+
+    /* pointer to cvode_mem */
+
+    void *cvode_mem;
+
+  } *CVBBDPrecData;
+
+
+  /*
+   * -----------------------------------------------------------------
+   * Type: CVBBDPrecDataB
+   * -----------------------------------------------------------------
+   */
+
+  typedef struct {
+
+    /* BBD user functions (glocB and cfnB) for backward run */
+    CVLocalFnB glocB;
+    CVCommFnB  cfnB;
+    
+    /* BBD prec data */
+    void *bbd_dataB;
+
+  } *CVBBDPrecDataB;
+
+  /*
+   * -----------------------------------------------------------------
+   * CVBBDPRE error messages
+   * -----------------------------------------------------------------
+   */
+
+#define MSGBBDP_CVMEM_NULL  "Integrator memory is NULL."
+#define MSGBBDP_MEM_FAIL    "A memory request failed."
+#define MSGBBDP_BAD_NVECTOR "A required vector operation is not implemented."
+#define MSGBBDP_PDATA_NULL  "CVBBDPRE memory is NULL."
+#define MSGBBDP_FUNC_FAILED "The gloc or cfn routine failed in an unrecoverable manner."
+
+#define MSGBBDP_CAMEM_NULL  "cvadj_mem = NULL illegal."
+#define MSGBBDP_PDATAB_NULL "CVBBDPRE memory is NULL for the backward integration."
+#define MSGBBDP_BAD_T       "Bad t for interpolation."
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_dense.c b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_dense.c
new file mode 100644
index 0000000000000000000000000000000000000000..98ff34aca0be8a67d7c6614b313985a721bc1de8
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_dense.c
@@ -0,0 +1,778 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2005, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the implementation file for the CVDENSE linear solver.
+ * -----------------------------------------------------------------
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "cvodes_dense_impl.h"
+#include "cvodes_impl.h"
+
+#include <sundials/sundials_math.h>
+
+/* Other Constants */
+
+#define MIN_INC_MULT RCONST(1000.0)
+#define ZERO         RCONST(0.0)
+#define ONE          RCONST(1.0)
+#define TWO          RCONST(2.0)
+
+/* CVDENSE linit, lsetup, lsolve, and lfree routines */
+ 
+static int CVDenseInit(CVodeMem cv_mem);
+
+static int CVDenseSetup(CVodeMem cv_mem, int convfail, N_Vector ypred,
+                        N_Vector fpred, booleantype *jcurPtr, 
+                        N_Vector vtemp1, N_Vector vtemp2, N_Vector vtemp3);
+
+static int CVDenseSolve(CVodeMem cv_mem, N_Vector b, N_Vector weight,
+                        N_Vector ycur, N_Vector fcur);
+
+static void CVDenseFree(CVodeMem cv_mem);
+
+/* CVDENSE lfreeB function */
+
+static void CVDenseFreeB(CVadjMem ca_mem);
+
+/* Wrapper function for adjoint code */
+
+static int CVAdenseJac(long int nB, DenseMat JB, realtype t, 
+                       N_Vector yB, N_Vector fyB, void *cvadj_mem,
+                       N_Vector tmp1B, N_Vector tmp2B, N_Vector tmp3B);
+
+
+/* CVDENSE DQJac routine */
+
+static int CVDenseDQJac(long int n, DenseMat J, realtype t, 
+                        N_Vector y, N_Vector fy, void *jac_data,
+                        N_Vector tmp1, N_Vector tmp2, N_Vector tmp3);
+
+
+/* 
+ * ================================================================
+ *
+ *                   PART I - forward problems
+ *
+ * ================================================================
+ */
+
+
+/* Readability Replacements */
+
+#define lmm       (cv_mem->cv_lmm)
+#define f         (cv_mem->cv_f)
+#define f_data    (cv_mem->cv_f_data)
+#define uround    (cv_mem->cv_uround)
+#define nst       (cv_mem->cv_nst)
+#define tn        (cv_mem->cv_tn)
+#define h         (cv_mem->cv_h)
+#define gamma     (cv_mem->cv_gamma)
+#define gammap    (cv_mem->cv_gammap)
+#define gamrat    (cv_mem->cv_gamrat)
+#define ewt       (cv_mem->cv_ewt)
+#define linit     (cv_mem->cv_linit)
+#define lsetup    (cv_mem->cv_lsetup)
+#define lsolve    (cv_mem->cv_lsolve)
+#define lfree     (cv_mem->cv_lfree)
+#define lmem      (cv_mem->cv_lmem)
+#define vec_tmpl     (cv_mem->cv_tempv)
+#define setupNonNull (cv_mem->cv_setupNonNull)
+
+#define n         (cvdense_mem->d_n)
+#define jac       (cvdense_mem->d_jac)
+#define M         (cvdense_mem->d_M)
+#define pivots    (cvdense_mem->d_pivots)
+#define savedJ    (cvdense_mem->d_savedJ)
+#define nstlj     (cvdense_mem->d_nstlj)
+#define nje       (cvdense_mem->d_nje)
+#define nfeD      (cvdense_mem->d_nfeD)
+#define J_data    (cvdense_mem->d_J_data)
+#define last_flag (cvdense_mem->d_last_flag)
+
+/*
+ * -----------------------------------------------------------------
+ * CVDense
+ * -----------------------------------------------------------------
+ * This routine initializes the memory record and sets various function
+ * fields specific to the dense linear solver module.  CVDense first
+ * calls the existing lfree routine if this is not NULL.  Then it sets
+ * the cv_linit, cv_lsetup, cv_lsolve, cv_lfree fields in (*cvode_mem)
+ * to be CVDenseInit, CVDenseSetup, CVDenseSolve, and CVDenseFree,
+ * respectively.  It allocates memory for a structure of type
+ * CVDenseMemRec and sets the cv_lmem field in (*cvode_mem) to the
+ * address of this structure.  It sets setupNonNull in (*cvode_mem) to
+ * TRUE, and the d_jac field to the default CVDenseDQJac.
+ * Finally, it allocates memory for M, savedJ, and pivots.
+ * The return value is SUCCESS = 0, or LMEM_FAIL = -1.
+ *
+ * NOTE: The dense linear solver assumes a serial implementation
+ *       of the NVECTOR package. Therefore, CVDense will first 
+ *       test for compatible a compatible N_Vector internal
+ *       representation by checking that N_VGetArrayPointer and
+ *       N_VSetArrayPointer exist.
+ * -----------------------------------------------------------------
+ */
+
+int CVDense(void *cvode_mem, long int N)
+{
+  CVodeMem cv_mem;
+  CVDenseMem cvdense_mem;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVDENSE_MEM_NULL, "CVDENSE", "CVDense", MSGDS_CVMEM_NULL);
+    return(CVDENSE_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  /* Test if the NVECTOR package is compatible with the DENSE solver */
+  if (vec_tmpl->ops->nvgetarraypointer == NULL ||
+      vec_tmpl->ops->nvsetarraypointer == NULL) {
+    CVProcessError(cv_mem, CVDENSE_ILL_INPUT, "CVDENSE", "CVDense", MSGDS_BAD_NVECTOR);
+    return(CVDENSE_ILL_INPUT);
+  }
+
+  if (lfree !=NULL) lfree(cv_mem);
+
+  /* Set four main function fields in cv_mem */
+  linit  = CVDenseInit;
+  lsetup = CVDenseSetup;
+  lsolve = CVDenseSolve;
+  lfree  = CVDenseFree;
+
+  /* Get memory for CVDenseMemRec */
+  cvdense_mem = NULL;
+  cvdense_mem = (CVDenseMem) malloc(sizeof(CVDenseMemRec));
+  if (cvdense_mem == NULL) {
+    CVProcessError(cv_mem, CVDENSE_MEM_FAIL, "CVDENSE", "CVDense", MSGDS_MEM_FAIL);
+    return(CVDENSE_MEM_FAIL);
+  }
+
+  /* Set default Jacobian routine and Jacobian data */
+  jac = CVDenseDQJac;
+  J_data = cvode_mem;
+  last_flag = CVDENSE_SUCCESS;
+
+  setupNonNull = TRUE;
+
+  /* Set problem dimension */
+  n = N;
+
+  /* Allocate memory for M, savedJ, and pivot array */
+
+  M = NULL;
+  M = DenseAllocMat(N, N);
+  if (M == NULL) {
+    CVProcessError(cv_mem, CVDENSE_MEM_FAIL, "CVDENSE", "CVDense", MSGDS_MEM_FAIL);
+    free(cvdense_mem); cvdense_mem = NULL;
+    return(CVDENSE_MEM_FAIL);
+  }
+  savedJ = NULL;
+  savedJ = DenseAllocMat(N, N);
+  if (savedJ == NULL) {
+    CVProcessError(cv_mem, CVDENSE_MEM_FAIL, "CVDENSE", "CVDense", MSGDS_MEM_FAIL);
+    DenseFreeMat(M);
+    free(cvdense_mem); cvdense_mem = NULL;
+    return(CVDENSE_MEM_FAIL);
+  }
+  pivots = NULL;
+  pivots = DenseAllocPiv(N);
+  if (pivots == NULL) {
+    CVProcessError(cv_mem, CVDENSE_MEM_FAIL, "CVDENSE", "CVDense", MSGDS_MEM_FAIL);
+    DenseFreeMat(M);
+    DenseFreeMat(savedJ);
+    free(cvdense_mem); cvdense_mem = NULL;
+    return(CVDENSE_MEM_FAIL);
+  }
+
+  /* Attach linear solver memory to integrator memory */
+  lmem = cvdense_mem;
+
+  return(CVDENSE_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVDenseSetJacFn
+ * -----------------------------------------------------------------
+ */
+
+int CVDenseSetJacFn(void *cvode_mem, CVDenseJacFn djac, void *jac_data)
+{
+  CVodeMem cv_mem;
+  CVDenseMem cvdense_mem;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVDENSE_MEM_NULL, "CVDENSE", "CVDenseSetJacFn", MSGDS_CVMEM_NULL);
+    return(CVDENSE_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (lmem == NULL) {
+    CVProcessError(cv_mem, CVDENSE_LMEM_NULL, "CVDENSE", "CVDenseSetJacFn", MSGDS_LMEM_NULL);
+    return(CVDENSE_LMEM_NULL);
+  }
+  cvdense_mem = (CVDenseMem) lmem;
+
+  jac = djac;
+  if (djac != NULL) J_data = jac_data;
+
+  return(CVDENSE_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVDenseGetWorkSpace
+ * -----------------------------------------------------------------
+ */
+
+int CVDenseGetWorkSpace(void *cvode_mem, long int *lenrwLS, long int *leniwLS)
+{
+  CVodeMem cv_mem;
+  CVDenseMem cvdense_mem;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVDENSE_MEM_NULL, "CVDENSE", "CVDenseGetWorkSpace", MSGDS_CVMEM_NULL);
+    return(CVDENSE_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (lmem == NULL) {
+    CVProcessError(cv_mem, CVDENSE_LMEM_NULL, "CVDENSE", "CVDenseGetWorkSpace", MSGDS_LMEM_NULL);
+    return(CVDENSE_LMEM_NULL);
+  }
+  cvdense_mem = (CVDenseMem) lmem;
+
+  *lenrwLS = 2*n*n;
+  *leniwLS = n;
+
+  return(CVDENSE_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVDenseGetNumJacEvals
+ * -----------------------------------------------------------------
+ */
+
+int CVDenseGetNumJacEvals(void *cvode_mem, long int *njevals)
+{
+  CVodeMem cv_mem;
+  CVDenseMem cvdense_mem;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVDENSE_MEM_NULL, "CVDENSE", "CVDenseGetNumJacEvals", MSGDS_CVMEM_NULL);
+    return(CVDENSE_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (lmem == NULL) {
+    CVProcessError(cv_mem, CVDENSE_LMEM_NULL, "CVDENSE", "CVDenseGetNumJacEvals", MSGDS_LMEM_NULL);
+    return(CVDENSE_LMEM_NULL);
+  }
+  cvdense_mem = (CVDenseMem) lmem;
+
+  *njevals = nje;
+
+  return(CVDENSE_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVDenseGetNumRhsEvals
+ * -----------------------------------------------------------------
+ */
+
+int CVDenseGetNumRhsEvals(void *cvode_mem, long int *nfevalsLS)
+{
+  CVodeMem cv_mem;
+  CVDenseMem cvdense_mem;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVDENSE_MEM_NULL, "CVDENSE", "CVDenseGetNumRhsEvals", MSGDS_CVMEM_NULL);
+    return(CVDENSE_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (lmem == NULL) {
+    CVProcessError(cv_mem, CVDENSE_LMEM_NULL, "CVDENSE", "CVDenseGetNumRhsEvals", MSGDS_LMEM_NULL);
+    return(CVDENSE_LMEM_NULL);
+  }
+  cvdense_mem = (CVDenseMem) lmem;
+
+  *nfevalsLS = nfeD;
+
+  return(CVDENSE_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVDenseGetLastFlag
+ * -----------------------------------------------------------------
+ */
+
+int CVDenseGetLastFlag(void *cvode_mem, int *flag)
+{
+  CVodeMem cv_mem;
+  CVDenseMem cvdense_mem;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVDENSE_MEM_NULL, "CVDENSE", "CVDenseGetLastFlag", MSGDS_CVMEM_NULL);
+    return(CVDENSE_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (lmem == NULL) {
+    CVProcessError(cv_mem, CVDENSE_LMEM_NULL, "CVDENSE", "CVDenseGetLastFlag", MSGDS_LMEM_NULL);
+    return(CVDENSE_LMEM_NULL);
+  }
+  cvdense_mem = (CVDenseMem) lmem;
+
+  *flag = last_flag;
+
+  return(CVDENSE_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVDenseGetReturnFlagName
+ * -----------------------------------------------------------------
+ */
+
+char *CVDenseGetReturnFlagName(int flag)
+{
+  char *name;
+
+  name = (char *)malloc(30*sizeof(char));
+
+  switch(flag) {
+  case CVDENSE_SUCCESS:
+    sprintf(name,"CVDENSE_SUCCESS");
+    break; 
+  case CVDENSE_MEM_NULL:
+    sprintf(name,"CVDENSE_MEM_NULL");
+    break;
+  case CVDENSE_LMEM_NULL:
+    sprintf(name,"CVDENSE_LMEM_NULL");
+    break;
+  case CVDENSE_ILL_INPUT:
+    sprintf(name,"CVDENSE_ILL_INPUT");
+    break;
+  case CVDENSE_MEM_FAIL:
+    sprintf(name,"CVDENSE_MEM_FAIL");
+    break;
+  case CVDENSE_JACFUNC_UNRECVR:
+    sprintf(name,"CVDENSE_JACFUNC_UNRECVR");
+    break;
+  case CVDENSE_JACFUNC_RECVR:
+    sprintf(name,"CVDENSE_JACFUNC_RECVR");
+    break;
+  case CVDENSE_ADJMEM_NULL:
+    sprintf(name,"CVDENSE_ADJMEM_NULL");
+    break;
+  case CVDENSE_LMEMB_NULL:
+    sprintf(name,"CVDENSE_LMEMB_NULL");
+    break;
+  default:
+    sprintf(name,"NONE");
+  }
+
+  return(name);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVDenseInit
+ * -----------------------------------------------------------------
+ * This routine does remaining initializations specific to the dense
+ * linear solver.
+ * -----------------------------------------------------------------
+ */
+
+static int CVDenseInit(CVodeMem cv_mem)
+{
+  CVDenseMem cvdense_mem;
+
+  cvdense_mem = (CVDenseMem) lmem;
+  
+  nje   = 0;
+  nfeD  = 0;
+  nstlj = 0;
+  
+  if (jac == NULL) {
+    jac = CVDenseDQJac;
+    J_data = cv_mem;
+  }
+
+  last_flag = CVDENSE_SUCCESS;
+  return(0);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVDenseSetup
+ * -----------------------------------------------------------------
+ * This routine does the setup operations for the dense linear solver.
+ * It makes a decision whether or not to call the Jacobian evaluation
+ * routine based on various state variables, and if not it uses the 
+ * saved copy.  In any case, it constructs the Newton matrix 
+ * M = I - gamma*J, updates counters, and calls the dense LU 
+ * factorization routine.
+ * -----------------------------------------------------------------
+ */
+
+static int CVDenseSetup(CVodeMem cv_mem, int convfail, N_Vector ypred,
+                        N_Vector fpred, booleantype *jcurPtr, 
+                        N_Vector vtemp1, N_Vector vtemp2, N_Vector vtemp3)
+{
+  booleantype jbad, jok;
+  realtype dgamma;
+  long int ier;
+  CVDenseMem cvdense_mem;
+  int retval;
+
+  cvdense_mem = (CVDenseMem) lmem;
+ 
+  /* Use nst, gamma/gammap, and convfail to set J eval. flag jok */
+ 
+  dgamma = ABS((gamma/gammap) - ONE);
+  jbad = (nst == 0) || (nst > nstlj + CVD_MSBJ) ||
+         ((convfail == CV_FAIL_BAD_J) && (dgamma < CVD_DGMAX)) ||
+         (convfail == CV_FAIL_OTHER);
+  jok = !jbad;
+ 
+  if (jok) {
+
+    /* If jok = TRUE, use saved copy of J */
+    *jcurPtr = FALSE;
+    DenseCopy(savedJ, M);
+
+  } else {
+
+    /* If jok = FALSE, call jac routine for new J value */
+    nje++;
+    nstlj = nst;
+    *jcurPtr = TRUE;
+    DenseZero(M);
+
+    retval = jac(n, M, tn, ypred, fpred, J_data, vtemp1, vtemp2, vtemp3);
+    if (retval < 0) {
+      CVProcessError(cv_mem, CVDENSE_JACFUNC_UNRECVR, "CVDENSE", "CVDenseSetup", MSGDS_JACFUNC_FAILED);
+      last_flag = CVDENSE_JACFUNC_UNRECVR;
+      return(-1);
+    }
+    if (retval > 0) {
+      last_flag = CVDENSE_JACFUNC_RECVR;
+      return(1);
+    }
+
+    DenseCopy(M, savedJ);
+
+  }
+  
+  /* Scale and add I to get M = I - gamma*J */
+  DenseScale(-gamma, M);
+  DenseAddI(M);
+
+  /* Do LU factorization of M */
+  ier = DenseGETRF(M, pivots); 
+
+  /* Return 0 if the LU was complete; otherwise return 1 */
+  last_flag = ier;
+  if (ier > 0) return(1);
+  return(0);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVDenseSolve
+ * -----------------------------------------------------------------
+ * This routine handles the solve operation for the dense linear solver
+ * by calling the dense backsolve routine.  The returned value is 0.
+ * -----------------------------------------------------------------
+ */
+
+static int CVDenseSolve(CVodeMem cv_mem, N_Vector b, N_Vector weight,
+                        N_Vector ycur, N_Vector fcur)
+{
+  CVDenseMem cvdense_mem;
+  realtype *bd;
+
+  cvdense_mem = (CVDenseMem) lmem;
+  
+  bd = N_VGetArrayPointer(b);
+
+  DenseGETRS(M, pivots, bd);
+
+  /* If CV_BDF, scale the correction to account for change in gamma */
+  if ((lmm == CV_BDF) && (gamrat != ONE)) {
+    N_VScale(TWO/(ONE + gamrat), b, b);
+  }
+  
+  last_flag = CVDENSE_SUCCESS;
+  return(0);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVDenseFree
+ * -----------------------------------------------------------------
+ * This routine frees memory specific to the dense linear solver.
+ * -----------------------------------------------------------------
+ */
+
+static void CVDenseFree(CVodeMem cv_mem)
+{
+  CVDenseMem  cvdense_mem;
+
+  cvdense_mem = (CVDenseMem) lmem;
+  
+  DenseFreeMat(M);
+  DenseFreeMat(savedJ);
+  DenseFreePiv(pivots);
+  free(cvdense_mem); cvdense_mem = NULL;
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVDenseDQJac 
+ * -----------------------------------------------------------------
+ * This routine generates a dense difference quotient approximation to
+ * the Jacobian of f(t,y). It assumes that a dense matrix of type
+ * DenseMat is stored column-wise, and that elements within each column
+ * are contiguous. The address of the jth column of J is obtained via
+ * the macro DENSE_COL and this pointer is associated with an N_Vector
+ * using the N_VGetArrayPointer/N_VSetArrayPointer functions. 
+ * Finally, the actual computation of the jth column of the Jacobian is 
+ * done with a call to N_VLinearSum.
+ * -----------------------------------------------------------------
+ */
+ 
+static int CVDenseDQJac(long int N, DenseMat J, realtype t, 
+                        N_Vector y, N_Vector fy, void *jac_data,
+                        N_Vector tmp1, N_Vector tmp2, N_Vector tmp3)
+{
+  realtype fnorm, minInc, inc, inc_inv, yjsaved, srur;
+  realtype *tmp2_data, *y_data, *ewt_data;
+  N_Vector ftemp, jthCol;
+  long int j;
+  int retval = 0;
+
+  CVodeMem cv_mem;
+  CVDenseMem  cvdense_mem;
+
+  /* jac_data points to cvode_mem */
+  cv_mem = (CVodeMem) jac_data;
+  cvdense_mem = (CVDenseMem) lmem;
+
+  /* Save pointer to the array in tmp2 */
+  tmp2_data = N_VGetArrayPointer(tmp2);
+
+  /* Rename work vectors for readibility */
+  ftemp = tmp1; 
+  jthCol = tmp2;
+
+  /* Obtain pointers to the data for ewt, y */
+  ewt_data = N_VGetArrayPointer(ewt);
+  y_data   = N_VGetArrayPointer(y);
+
+  /* Set minimum increment based on uround and norm of f */
+  srur = RSqrt(uround);
+  fnorm = N_VWrmsNorm(fy, ewt);
+  minInc = (fnorm != ZERO) ?
+           (MIN_INC_MULT * ABS(h) * uround * N * fnorm) : ONE;
+
+  /* This is the only for loop for 0..N-1 in CVODE */
+
+  for (j = 0; j < N; j++) {
+
+    /* Generate the jth col of J(tn,y) */
+
+    N_VSetArrayPointer(DENSE_COL(J,j), jthCol);
+
+    yjsaved = y_data[j];
+    inc = MAX(srur*ABS(yjsaved), minInc/ewt_data[j]);
+    y_data[j] += inc;
+
+    retval = f(tn, y, ftemp, f_data);
+    nfeD++;
+    if (retval != 0) break;
+
+    y_data[j] = yjsaved;
+
+    inc_inv = ONE/inc;
+    N_VLinearSum(inc_inv, ftemp, -inc_inv, fy, jthCol);
+
+    DENSE_COL(J,j) = N_VGetArrayPointer(jthCol);
+  }
+
+  /* Restore original array pointer in tmp2 */
+  N_VSetArrayPointer(tmp2_data, tmp2);
+
+  return(retval);
+}
+
+
+/* 
+ * ================================================================
+ *
+ *                   PART II - backward problems
+ *
+ * ================================================================
+ */
+
+
+/* Additional readability replacements */
+
+#define ytmp        (ca_mem->ca_ytmp)
+#define getY        (ca_mem->ca_getY)
+#define lmemB       (ca_mem->ca_lmemB)
+#define lfreeB      (ca_mem->ca_lfreeB)
+
+#define djac_B      (cvdenseB_mem->d_djacB)
+#define jac_data_B  (cvdenseB_mem->d_jac_dataB)
+
+
+/*
+ * CVDenseB and CVdenseSet*B
+ *
+ * Wrappers for the backward phase around the corresponding 
+ * CVODES functions
+ */
+
+int CVDenseB(void *cvadj_mem, long int nB)
+{
+  CVadjMem ca_mem;
+  CVDenseMemB cvdenseB_mem;
+  CVodeMem cvB_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CVDENSE_ADJMEM_NULL, "CVDENSE", "CVDenseB", MSGDS_CAMEM_NULL);
+    return(CVDENSE_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  cvB_mem = ca_mem->cvb_mem;
+
+  /* Get memory for CVDenseMemRecB */
+  cvdenseB_mem = (CVDenseMemB) malloc(sizeof(CVDenseMemRecB));
+  if (cvdenseB_mem == NULL) {
+    CVProcessError(cvB_mem, CVDENSE_MEM_FAIL, "CVDENSE", "CVDenseB", MSGDS_MEM_FAIL);
+    return(CVDENSE_MEM_FAIL);
+  }
+
+  djac_B = NULL;
+  jac_data_B = NULL;
+
+  /* attach lmemB and lfreeB */
+  lmemB = cvdenseB_mem;
+  lfreeB = CVDenseFreeB;
+
+  flag = CVDense(cvB_mem, nB);
+
+  if (flag != CVDENSE_SUCCESS) {
+    free(cvdenseB_mem);
+    cvdenseB_mem = NULL;
+  }
+
+  return(flag);
+}
+
+int CVDenseSetJacFnB(void *cvadj_mem, CVDenseJacFnB djacB, void *jac_dataB)
+{
+  CVadjMem ca_mem;
+  CVDenseMemB cvdenseB_mem;
+  CVodeMem cvB_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CVDENSE_ADJMEM_NULL, "CVDENSE", "CVDenseSetJacFnB", MSGDS_CAMEM_NULL);
+    return(CVDENSE_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  cvB_mem = ca_mem->cvb_mem;
+
+  if (lmemB == NULL) {
+    CVProcessError(cvB_mem, CVDENSE_LMEMB_NULL, "CVDENSE", "CVDenseSetJacFnB", MSGDS_LMEMB_NULL);
+    return(CVDENSE_LMEMB_NULL);
+  }
+  cvdenseB_mem = (CVDenseMemB) lmemB;
+
+  djac_B     = djacB;
+  jac_data_B = jac_dataB;
+
+  flag = CVDenseSetJacFn(cvB_mem, CVAdenseJac, cvadj_mem);
+
+  return(flag);
+}
+
+/*
+ * CVDenseFreeB 
+ */
+
+
+static void CVDenseFreeB(CVadjMem ca_mem)
+{
+  CVDenseMemB cvdenseB_mem;
+
+  cvdenseB_mem = (CVDenseMemB) lmemB;
+
+  free(cvdenseB_mem);
+}
+
+
+/*
+ * CVAdenseJac
+ *
+ * This routine interfaces to the CVDenseJacFnB routine provided 
+ * by the user.
+ * NOTE: jac_data actually contains cvadj_mem
+ */
+
+static int CVAdenseJac(long int nB, DenseMat JB, realtype t, 
+                       N_Vector yB, N_Vector fyB, void *cvadj_mem,
+                       N_Vector tmp1B, N_Vector tmp2B, N_Vector tmp3B)
+{
+  CVadjMem ca_mem;
+  CVodeMem cvB_mem;
+  CVDenseMemB cvdenseB_mem;
+  int retval, flag;
+
+  ca_mem = (CVadjMem) cvadj_mem;
+  cvB_mem = ca_mem->cvb_mem;
+  cvdenseB_mem = (CVDenseMemB) lmemB;
+
+  /* Forward solution from interpolation */
+  flag = getY(ca_mem, t, ytmp);
+  if (flag != CV_SUCCESS) {
+    CVProcessError(cvB_mem, -1, "CVDENSE", "CVAdenseJac", MSGDS_BAD_T);
+    return(-1);
+  }
+
+  /* Call user's adjoint dense djacB routine */
+  retval = djac_B(nB, JB, t, ytmp, yB, fyB, jac_data_B, 
+                  tmp1B, tmp2B, tmp3B);
+
+  return(retval);
+
+}
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_dense_impl.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_dense_impl.h
new file mode 100644
index 0000000000000000000000000000000000000000..9082818827084d92b7e2a3c7957eb2270530c220
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_dense_impl.h
@@ -0,0 +1,99 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2005, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * Implementation header file for the dense linear solver, CVDENSE.
+ * -----------------------------------------------------------------
+ */
+
+#ifndef _CVSDENSE_IMPL_H
+#define _CVSDENSE_IMPL_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#include <cvodes/cvodes_dense.h>
+
+  /*
+   * -----------------------------------------------------------------
+   * Types : CVDenseMemRec, CVDenseMem                             
+   * -----------------------------------------------------------------
+   * The type CVDenseMem is pointer to a CVDenseMemRec.
+   * This structure contains CVDense solver-specific data.
+   *
+   * CVDense attaches such a structure to the lmem field of CVodeMem
+   * -----------------------------------------------------------------
+   */
+
+  typedef struct {
+
+    long int d_n;        /* problem dimension                       */
+
+    CVDenseJacFn d_jac;  /* jac = Jacobian routine to be called     */
+
+    DenseMat d_M;        /* M = I - gamma J, gamma = h / l1         */
+  
+    long int *d_pivots;  /* pivots = pivot array for PM = LU        */
+  
+    DenseMat d_savedJ;   /* savedJ = old Jacobian                   */
+  
+    long int  d_nstlj;   /* nstlj = nst at last Jacobian eval.      */
+  
+    long int d_nje;      /* nje = no. of calls to jac               */
+
+    long int d_nfeD;     /* nfeD = no. of calls to f due to
+                            difference quotient approximation of J  */
+  
+    void *d_J_data;      /* J_data is passed to jac                 */
+
+    int d_last_flag;     /* last error return flag                  */
+  
+  } CVDenseMemRec, *CVDenseMem;
+
+
+  /*
+   * -----------------------------------------------------------------
+   * Types : CVDenseMemRecB, CVDenseMemB       
+   * -----------------------------------------------------------------
+   * CVDenseB attaches such a structure to the lmemB filed of CVadjMem
+   * -----------------------------------------------------------------
+   */
+
+  typedef struct {
+
+    CVDenseJacFnB d_djacB;
+    void *d_jac_dataB;
+
+  } CVDenseMemRecB, *CVDenseMemB;
+
+  /*
+   * -----------------------------------------------------------------
+   * Error Messages 
+   * -----------------------------------------------------------------
+   */
+
+#define MSGDS_CVMEM_NULL "Integrator memory is NULL."
+#define MSGDS_MEM_FAIL "A memory request failed."
+#define MSGDS_BAD_NVECTOR "A required vector operation is not implemented."
+#define MSGDS_LMEM_NULL "CVDENSE memory is NULL."
+#define MSGDS_JACFUNC_FAILED "The Jacobian routine failed in an unrecoverable manner."
+
+#define MSGDS_CAMEM_NULL "cvadj_mem = NULL illegal."
+#define MSGDS_LMEMB_NULL "CVDENSE memory is NULL for the backward integration."
+#define MSGDS_BAD_T "Bad t for interpolation."
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_diag.c b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_diag.c
new file mode 100644
index 0000000000000000000000000000000000000000..3f965d1003c460c622dbf3f2b18db457bd5ecb53
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_diag.c
@@ -0,0 +1,488 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2005, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the implementation file for the CVDIAG linear solver.
+ * -----------------------------------------------------------------
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "cvodes_diag_impl.h"
+#include "cvodes_impl.h"
+
+/* Other Constants */
+  
+#define FRACT RCONST(0.1)
+#define ONE   RCONST(1.0)
+
+/* CVDIAG linit, lsetup, lsolve, and lfree routines */
+
+static int CVDiagInit(CVodeMem cv_mem);
+
+static int CVDiagSetup(CVodeMem cv_mem, int convfail, N_Vector ypred,
+                       N_Vector fpred, booleantype *jcurPtr, N_Vector vtemp1,
+                       N_Vector vtemp2, N_Vector vtemp3);
+
+static int CVDiagSolve(CVodeMem cv_mem, N_Vector b, N_Vector weight,
+                       N_Vector ycur, N_Vector fcur);
+
+static void CVDiagFree(CVodeMem cv_mem);
+
+
+/* 
+ * ================================================================
+ *
+ *                   PART I - forward problems
+ *
+ * ================================================================
+ */
+
+
+/* Readability Replacements */
+
+#define lrw1      (cv_mem->cv_lrw1)
+#define liw1      (cv_mem->cv_liw1)
+#define f         (cv_mem->cv_f)
+#define f_data    (cv_mem->cv_f_data)
+#define uround    (cv_mem->cv_uround)
+#define tn        (cv_mem->cv_tn)
+#define h         (cv_mem->cv_h)
+#define rl1       (cv_mem->cv_rl1)
+#define gamma     (cv_mem->cv_gamma)
+#define ewt       (cv_mem->cv_ewt)
+#define nfe       (cv_mem->cv_nfe)
+#define zn        (cv_mem->cv_zn)
+#define linit     (cv_mem->cv_linit)
+#define lsetup    (cv_mem->cv_lsetup)
+#define lsolve    (cv_mem->cv_lsolve)
+#define lfree     (cv_mem->cv_lfree)
+#define lmem      (cv_mem->cv_lmem)
+#define vec_tmpl  (cv_mem->cv_tempv)
+#define setupNonNull   (cv_mem->cv_setupNonNull)
+
+#define gammasv   (cvdiag_mem->di_gammasv)
+#define M         (cvdiag_mem->di_M)
+#define bit       (cvdiag_mem->di_bit)
+#define bitcomp   (cvdiag_mem->di_bitcomp)
+#define nfeDI     (cvdiag_mem->di_nfeDI)
+#define last_flag (cvdiag_mem->di_last_flag)
+
+
+/*
+ * -----------------------------------------------------------------
+ * CVDiag 
+ * -----------------------------------------------------------------
+ * This routine initializes the memory record and sets various function
+ * fields specific to the diagonal linear solver module.  CVDense first
+ * calls the existing lfree routine if this is not NULL.  Then it sets
+ * the cv_linit, cv_lsetup, cv_lsolve, cv_lfree fields in (*cvode_mem)
+ * to be CVDiagInit, CVDiagSetup, CVDiagSolve, and CVDiagFree,
+ * respectively.  It allocates memory for a structure of type
+ * CVDiagMemRec and sets the cv_lmem field in (*cvode_mem) to the
+ * address of this structure.  It sets setupNonNull in (*cvode_mem) to
+ * TRUE.  Finally, it allocates memory for M, bit, and bitcomp.
+ * The CVDiag return value is SUCCESS = 0, LMEM_FAIL = -1, or 
+ * LIN_ILL_INPUT=-2.
+ * -----------------------------------------------------------------
+ */
+  
+int CVDiag(void *cvode_mem)
+{
+  CVodeMem cv_mem;
+  CVDiagMem cvdiag_mem;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVDIAG_MEM_NULL, "CVDIAG", "CVDiag", MSGDG_CVMEM_NULL);
+    return(CVDIAG_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  /* Check if N_VCompare and N_VInvTest are present */
+  if(vec_tmpl->ops->nvcompare == NULL ||
+     vec_tmpl->ops->nvinvtest == NULL) {
+    CVProcessError(cv_mem, CVDIAG_ILL_INPUT, "CVDIAG", "CVDiag", MSGDG_BAD_NVECTOR);
+    return(CVDIAG_ILL_INPUT);
+  }
+
+  if (lfree != NULL) lfree(cv_mem);
+  
+  /* Set four main function fields in cv_mem */
+  linit  = CVDiagInit;
+  lsetup = CVDiagSetup;
+  lsolve = CVDiagSolve;
+  lfree  = CVDiagFree;
+
+  /* Get memory for CVDiagMemRec */
+  cvdiag_mem = NULL;
+  cvdiag_mem = (CVDiagMem) malloc(sizeof(CVDiagMemRec));
+  if (cvdiag_mem == NULL) {
+    CVProcessError(cv_mem, CVDIAG_MEM_FAIL, "CVDIAG", "CVDiag", MSGDG_MEM_FAIL);
+    return(CVDIAG_MEM_FAIL);
+  }
+
+  last_flag = CVDIAG_SUCCESS;
+
+  /* Set flag setupNonNull = TRUE */
+  setupNonNull = TRUE;
+
+  /* Allocate memory for M, bit, and bitcomp */
+    
+  M = NULL;
+  M = N_VClone(vec_tmpl);
+  if (M == NULL) {
+    CVProcessError(cv_mem, CVDIAG_MEM_FAIL, "CVDIAG", "CVDiag", MSGDG_MEM_FAIL);
+    free(cvdiag_mem); cvdiag_mem = NULL;
+    return(CVDIAG_MEM_FAIL);
+  }
+  bit = NULL;
+  bit = N_VClone(vec_tmpl);
+  if (bit == NULL) {
+    CVProcessError(cv_mem, CVDIAG_MEM_FAIL, "CVDIAG", "CVDiag", MSGDG_MEM_FAIL);
+    N_VDestroy(M);
+    free(cvdiag_mem); cvdiag_mem = NULL;
+    return(CVDIAG_MEM_FAIL);
+  }
+  bitcomp = NULL;
+  bitcomp = N_VClone(vec_tmpl);
+  if (bitcomp == NULL) {
+    CVProcessError(cv_mem, CVDIAG_MEM_FAIL, "CVDIAG", "CVDiag", MSGDG_MEM_FAIL);
+    N_VDestroy(M);
+    N_VDestroy(bit);
+    free(cvdiag_mem); cvdiag_mem = NULL;
+    return(CVDIAG_MEM_FAIL);
+  }
+
+  /* Attach linear solver memory to integrator memory */
+  lmem = cvdiag_mem;
+
+  return(CVDIAG_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVDiagGetWorkSpace
+ * -----------------------------------------------------------------
+ */
+
+int CVDiagGetWorkSpace(void *cvode_mem, long int *lenrwLS, long int *leniwLS)
+{
+  CVodeMem cv_mem;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVDIAG_MEM_NULL, "CVDIAG", "CVDiagGetWorkSpace", MSGDG_CVMEM_NULL);
+    return(CVDIAG_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  *lenrwLS = 3*lrw1;
+  *leniwLS = 3*liw1;
+
+  return(CVDIAG_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVDiagGetNumRhsEvals
+ * -----------------------------------------------------------------
+ */
+
+int CVDiagGetNumRhsEvals(void *cvode_mem, long int *nfevalsLS)
+{
+  CVodeMem cv_mem;
+  CVDiagMem cvdiag_mem;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVDIAG_MEM_NULL, "CVDIAG", "CVDiagGetNumRhsEvals", MSGDG_CVMEM_NULL);
+    return(CVDIAG_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (lmem == NULL) {
+    CVProcessError(cv_mem, CVDIAG_LMEM_NULL, "CVDIAG", "CVDiagGetNumRhsEvals", MSGDG_LMEM_NULL);
+    return(CVDIAG_LMEM_NULL);
+  }
+  cvdiag_mem = (CVDiagMem) lmem;
+
+  *nfevalsLS = nfeDI;
+
+  return(CVDIAG_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVDiagGetLastFlag
+ * -----------------------------------------------------------------
+ */
+
+int CVDiagGetLastFlag(void *cvode_mem, int *flag)
+{
+  CVodeMem cv_mem;
+  CVDiagMem cvdiag_mem;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVDIAG_MEM_NULL, "CVDIAG", "CVDiagGetLastFlag", MSGDG_CVMEM_NULL);
+    return(CVDIAG_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (lmem == NULL) {
+    CVProcessError(cv_mem, CVDIAG_LMEM_NULL, "CVDIAG", "CVDiagGetLastFlag", MSGDG_LMEM_NULL);
+    return(CVDIAG_LMEM_NULL);
+  }
+  cvdiag_mem = (CVDiagMem) lmem;
+
+  *flag = last_flag;
+
+  return(CVDIAG_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVDiagGetReturnFlagName
+ * -----------------------------------------------------------------
+ */
+
+char *CVDiagGetReturnFlagName(int flag)
+{
+  char *name;
+
+  name = (char *)malloc(30*sizeof(char));
+
+  switch(flag) {
+  case CVDIAG_SUCCESS:
+    sprintf(name,"CVDIAG_SUCCESS");
+    break;  
+  case CVDIAG_MEM_NULL:
+    sprintf(name,"CVDIAG_MEM_NULL");
+    break;
+  case CVDIAG_LMEM_NULL:
+    sprintf(name,"CVDIAG_LMEM_NULL");
+    break;
+  case CVDIAG_ILL_INPUT:
+    sprintf(name,"CVDIAG_ILL_INPUT");
+    break;
+  case CVDIAG_MEM_FAIL:
+    sprintf(name,"CVDIAG_MEM_FAIL");
+    break;
+  case CVDIAG_INV_FAIL:
+    sprintf(name,"CVDIAG_INV_FAIL");
+    break;
+  case CVDIAG_RHSFUNC_UNRECVR:
+    sprintf(name,"CVDIAG_RHSFUNC_UNRECVR");
+    break;
+  case CVDIAG_RHSFUNC_RECVR:
+    sprintf(name,"CVDIAG_RHSFUNC_RECVR");
+    break;
+  case CVDIAG_ADJMEM_NULL:
+    sprintf(name,"CVDIAG_ADJMEM_NULL");
+    break;
+  default:
+    sprintf(name,"NONE");
+  }
+
+  return(name);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVDiagInit
+ * -----------------------------------------------------------------
+ * This routine does remaining initializations specific to the diagonal
+ * linear solver.
+ * -----------------------------------------------------------------
+ */
+
+static int CVDiagInit(CVodeMem cv_mem)
+{
+  CVDiagMem cvdiag_mem;
+
+  cvdiag_mem = (CVDiagMem) lmem;
+
+  nfeDI = 0;
+
+  last_flag = CVDIAG_SUCCESS;
+  return(0);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVDiagSetup
+ * -----------------------------------------------------------------
+ * This routine does the setup operations for the diagonal linear 
+ * solver.  It constructs a diagonal approximation to the Newton matrix 
+ * M = I - gamma*J, updates counters, and inverts M.
+ * -----------------------------------------------------------------
+ */
+
+static int CVDiagSetup(CVodeMem cv_mem, int convfail, N_Vector ypred,
+                       N_Vector fpred, booleantype *jcurPtr, N_Vector vtemp1,
+                       N_Vector vtemp2, N_Vector vtemp3)
+{
+  realtype r;
+  N_Vector ftemp, y;
+  booleantype invOK;
+  CVDiagMem cvdiag_mem;
+  int retval;
+
+  cvdiag_mem = (CVDiagMem) lmem;
+
+  /* Rename work vectors for use as temporary values of y and f */
+  ftemp = vtemp1;
+  y     = vtemp2;
+
+  /* Form y with perturbation = FRACT*(func. iter. correction) */
+  r = FRACT * rl1;
+  N_VLinearSum(h, fpred, -ONE, zn[1], ftemp);
+  N_VLinearSum(r, ftemp, ONE, ypred, y);
+
+  /* Evaluate f at perturbed y */
+  retval = f(tn, y, M, f_data);
+  nfeDI++;
+  if (retval < 0) {
+    CVProcessError(cv_mem, CVDIAG_RHSFUNC_UNRECVR, "CVDIAG", "CVDiagSetup", MSGDG_RHSFUNC_FAILED);
+    last_flag = CVDIAG_RHSFUNC_UNRECVR;
+    return(-1);
+  }
+  if (retval > 0) {
+    last_flag = CVDIAG_RHSFUNC_RECVR;
+    return(1);
+  }
+
+  /* Construct M = I - gamma*J with J = diag(deltaf_i/deltay_i) */
+  N_VLinearSum(ONE, M, -ONE, fpred, M);
+  N_VLinearSum(FRACT, ftemp, -h, M, M);
+  N_VProd(ftemp, ewt, y);
+  /* Protect against deltay_i being at roundoff level */
+  N_VCompare(uround, y, bit);
+  N_VAddConst(bit, -ONE, bitcomp);
+  N_VProd(ftemp, bit, y);
+  N_VLinearSum(FRACT, y, -ONE, bitcomp, y);
+  N_VDiv(M, y, M);
+  N_VProd(M, bit, M);
+  N_VLinearSum(ONE, M, -ONE, bitcomp, M);
+
+  /* Invert M with test for zero components */
+  invOK = N_VInvTest(M, M);
+  if (!invOK) {
+    last_flag = CVDIAG_INV_FAIL;
+    return(1);
+  }
+
+  /* Set jcur = TRUE, save gamma in gammasv, and return */
+  *jcurPtr = TRUE;
+  gammasv = gamma;
+  last_flag = CVDIAG_SUCCESS;
+  return(0);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVDiagSolve
+ * -----------------------------------------------------------------
+ * This routine performs the solve operation for the diagonal linear
+ * solver.  If necessary it first updates gamma in M = I - gamma*J.
+ * -----------------------------------------------------------------
+ */
+
+static int CVDiagSolve(CVodeMem cv_mem, N_Vector b, N_Vector weight,
+                       N_Vector ycur, N_Vector fcur)
+{
+  booleantype invOK;
+  realtype r;
+  CVDiagMem cvdiag_mem;
+
+  cvdiag_mem = (CVDiagMem) lmem;
+  
+  /* If gamma has changed, update factor in M, and save gamma value */
+
+  if (gammasv != gamma) {
+    r = gamma / gammasv;
+    N_VInv(M, M);
+    N_VAddConst(M, -ONE, M);
+    N_VScale(r, M, M);
+    N_VAddConst(M, ONE, M);
+    invOK = N_VInvTest(M, M);
+    if (!invOK) {
+      last_flag = CVDIAG_INV_FAIL;
+      return (1);
+    }
+    gammasv = gamma;
+  }
+
+  /* Apply M-inverse to b */
+  N_VProd(b, M, b);
+
+  last_flag = CVDIAG_SUCCESS;
+  return(0);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVDiagFree
+ * -----------------------------------------------------------------
+ * This routine frees memory specific to the diagonal linear solver.
+ * -----------------------------------------------------------------
+ */
+
+static void CVDiagFree(CVodeMem cv_mem)
+{
+  CVDiagMem cvdiag_mem;
+  
+  cvdiag_mem = (CVDiagMem) lmem;
+
+  N_VDestroy(M);
+  N_VDestroy(bit);
+  N_VDestroy(bitcomp);
+  free(cvdiag_mem); cvdiag_mem = NULL;
+}
+
+
+/* 
+ * ================================================================
+ *
+ *                   PART II - backward problems
+ *
+ * ================================================================
+ */
+
+
+/*
+ * CVDiagB
+ *
+ * Wrappers for the backward phase around the corresponding 
+ * CVODES functions
+ */
+
+int CVDiagB(void *cvadj_mem)
+{
+  CVadjMem ca_mem;
+  CVodeMem cvB_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CVDIAG_ADJMEM_NULL, "CVDIAG", "CVDiagB", MSGDG_CAMEM_NULL);
+    return(CVDIAG_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  cvB_mem = ca_mem->cvb_mem;
+  
+  flag = CVDiag(cvB_mem);
+
+  return(flag);
+}
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_diag_impl.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_diag_impl.h
new file mode 100644
index 0000000000000000000000000000000000000000..c49b0a840e73fb5d6c7f4c102ea726125ba46020
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_diag_impl.h
@@ -0,0 +1,67 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2005, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * Implementation header file for the diagonal linear solver, CVDIAG.
+ * -----------------------------------------------------------------
+ */
+
+#ifndef _CVSDIAG_IMPL_H
+#define _CVSDIAG_IMPL_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#include <cvodes/cvodes_diag.h>
+
+  /*
+   * -----------------------------------------------------------------
+   * Types: CVDiagMemRec, CVDiagMem
+   * -----------------------------------------------------------------
+   * The type CVDiagMem is pointer to a CVDiagMemRec.
+   * This structure contains CVDiag solver-specific data.
+   * -----------------------------------------------------------------
+   */
+
+  typedef struct {
+
+    realtype di_gammasv; /* gammasv = gamma at the last call to setup */
+    /* or solve                                  */
+
+    N_Vector di_M;       /* M = (I - gamma J)^{-1} , gamma = h / l1   */
+
+    N_Vector di_bit;     /* temporary storage vector                  */
+
+    N_Vector di_bitcomp; /* temporary storage vector                  */
+
+    long int di_nfeDI;   /* no. of calls to f due to difference 
+                            quotient diagonal Jacobian approximation  */
+
+    int di_last_flag;    /* last error return flag                    */
+
+  } CVDiagMemRec, *CVDiagMem;
+
+  /* Error Messages */
+
+#define MSGDG_CVMEM_NULL "Integrator memory is NULL."
+#define MSGDG_MEM_FAIL "A memory request failed."
+#define MSGDG_BAD_NVECTOR "A required vector operation is not implemented."
+#define MSGDG_LMEM_NULL "CVDIAG memory is NULL."
+#define MSGDG_RHSFUNC_FAILED "The right-hand side routine failed in an unrecoverable manner."
+
+#define MSGDG_CAMEM_NULL "cvadj_mem = NULL illegal."
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_impl.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_impl.h
new file mode 100644
index 0000000000000000000000000000000000000000..d3f52ced857d2c3105662d193e093a5bc9d864ed
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_impl.h
@@ -0,0 +1,918 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2005, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * Implementation header file for the main CVODES integrator.
+ * -----------------------------------------------------------------
+ */
+
+#ifndef _CVODES_IMPL_H
+#define _CVODES_IMPL_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#include <stdarg.h>
+
+#include <cvodes/cvodes.h>
+#include <sundials/sundials_nvector.h>
+#include <sundials/sundials_types.h>
+
+  /* 
+   * =================================================================
+   *   M A I N    I N T E G R A T O R    M E M O R Y    B L O C K
+   * =================================================================
+   */
+
+  /* Basic CVODES constants */
+
+#define ADAMS_Q_MAX 12      /* max value of q for lmm == ADAMS    */
+#define BDF_Q_MAX    5      /* max value of q for lmm == BDF      */
+#define Q_MAX  ADAMS_Q_MAX  /* max value of q for either lmm      */
+#define L_MAX  (Q_MAX+1)    /* max value of L for either lmm      */
+#define NUM_TESTS    5      /* number of error test quantities    */
+
+#define HMIN_DEFAULT     RCONST(0.0)    /* hmin default value     */
+#define HMAX_INV_DEFAULT RCONST(0.0)    /* hmax_inv default value */
+#define MXHNIL_DEFAULT   10             /* mxhnil default value   */
+#define MXSTEP_DEFAULT   500            /* mxstep default value   */
+
+  /*                                                                
+   * ifS is the type of the function returning the sensitivity
+   * right-hand side. ifS can be either CV_ALLSENS if the function    
+   * (of type CVSensRhsFn) returns right hand sides for all    
+   * sensitivity systems at once, or CV_ONESENS if the function 
+   * (of type SensRhs1Fn) returns the right hand side of one 
+   *  sensitivity system at a time.                           
+   */
+
+#define CV_ONESENS 1
+#define CV_ALLSENS 2
+
+  /*
+   * -----------------------------------------------------------------
+   * Types: struct CVodeMemRec, CVodeMem
+   * -----------------------------------------------------------------
+   * The type CVodeMem is type pointer to struct CVodeMemRec.
+   * This structure contains fields to keep track of problem state.
+   * -----------------------------------------------------------------
+   */
+  
+  typedef struct CVodeMemRec {
+    
+    realtype cv_uround;      /* machine unit roundoff                        */   
+
+    /*-------------------------- 
+      Problem Specification Data 
+      --------------------------*/
+
+    CVRhsFn cv_f;            /* y' = f(t,y(t))                               */
+    void *cv_f_data;         /* user pointer passed to f                     */
+    int cv_lmm;              /* lmm = ADAMS or BDF                           */
+    int cv_iter;             /* iter = FUNCTIONAL or NEWTON                  */
+    int cv_itol;             /* itol = SS or SV                              */
+
+    realtype cv_reltol;      /* relative tolerance                           */
+    realtype cv_Sabstol;     /* scalar absolute tolerance                    */
+    N_Vector cv_Vabstol;     /* vector absolute tolerance                    */
+    CVEwtFn cv_efun;         /* function to set ewt                          */
+    void *cv_e_data;         /* user pointer passed to efun                  */
+
+    /*-----------------------
+      Quadrature Related Data 
+      -----------------------*/
+
+    booleantype cv_quadr;    /* TRUE if integrating quadratures              */
+
+    CVQuadRhsFn cv_fQ;
+    void *cv_fQ_data;        /* user pointer passed to fQ                    */
+    int cv_itolQ;
+    booleantype cv_errconQ;
+
+    realtype cv_reltolQ;     /* relative tolerance for quadratures           */
+    realtype cv_SabstolQ;    /* scalar absolute tolerance for quadratures    */
+    N_Vector cv_VabstolQ;    /* vector absolute tolerance for quadratures    */
+
+    /*------------------------
+      Sensitivity Related Data 
+      ------------------------*/
+
+    booleantype cv_sensi;    /* TRUE if computing sensitivities              */
+
+    int cv_Ns;               /* Number of sensitivities                      */
+
+    int cv_ism;              /* ism = SIMULTANEOUS or STAGGERED              */
+
+    CVSensRhsFn cv_fS;       /* fS = (df/dy)*yS + (df/dp)                    */
+    CVSensRhs1Fn cv_fS1;     /* fS1 = (df/dy)*yS_i + (df/dp)                 */
+    void *cv_user_fS_data;   /* user data pointer for fS                     */
+    void *cv_fS_data;        /* actual data pointer passed to fS             */
+    booleantype cv_fSDQ;
+    int cv_ifS;              /* ifS = ALLSENS or ONESENS                     */
+
+    realtype *cv_p;          /* parameters in f(t,y,p)                       */
+    realtype *cv_pbar;       /* scale factors for parameters                 */
+    int *cv_plist;           /* list of sensitivities                        */
+    int cv_DQtype;           /* central/forward finite differences           */
+    realtype cv_DQrhomax;    /* cut-off value for separate/simultaneous FD   */
+
+    booleantype cv_errconS;  /* TRUE if sensitivities are in err. control    */
+
+    int cv_itolS;
+    realtype cv_reltolS;     /* relative tolerance for sensitivities         */
+    realtype *cv_SabstolS;   /* scalar absolute tolerances for sensi.        */
+    N_Vector *cv_VabstolS;   /* vector absolute tolerances for sensi.        */
+
+    /*-----------------------
+      Nordsieck History Array 
+      -----------------------*/
+
+    N_Vector cv_zn[L_MAX];   /* Nordsieck array, of size N x (q+1).
+                                zn[j] is a vector of length N (j=0,...,q)
+                                zn[j] = [1/factorial(j)] * h^j * 
+                                (jth derivative of the interpolating 
+                                polynomial                                   */
+
+    /*-------------------
+      Vectors of length N 
+      -------------------*/
+
+    N_Vector cv_ewt;         /* error weight vector                          */
+    N_Vector cv_y;           /* y is used as temporary storage by the solver.
+                                The memory is provided by the user to CVode 
+                                where the vector is named yout.              */
+    N_Vector cv_acor;        /* In the context of the solution of the
+                                nonlinear equation, acor = y_n(m) - y_n(0).
+                                On return, this vector is scaled to give
+                                the estimated local error in y.              */
+    N_Vector cv_tempv;       /* temporary storage vector                     */
+    N_Vector cv_ftemp;       /* temporary storage vector                     */
+
+    /*--------------------------
+      Quadrature Related Vectors 
+      --------------------------*/
+
+    N_Vector cv_znQ[L_MAX];  /* Nordsieck arrays for quadratures             */
+    N_Vector cv_ewtQ;        /* error weight vector for quadratures          */
+    N_Vector cv_yQ;          /* Unlike y, yQ is not allocated by the user    */
+    N_Vector cv_acorQ;       /* acorQ = yQ_n(m) - yQ_n(0)                    */
+    N_Vector cv_tempvQ;      /* temporary storage vector (~ tempv)           */
+
+    /*---------------------------
+      Sensitivity Related Vectors 
+      ---------------------------*/
+
+    N_Vector *cv_znS[L_MAX]; /* Nordsieck arrays for sensitivities           */
+    N_Vector *cv_ewtS;       /* error weight vectors for sensitivities       */
+    N_Vector *cv_yS;         /* yS=yS0 (allocated by the user)               */
+    N_Vector *cv_acorS;      /* acorS = yS_n(m) - yS_n(0)                    */
+    N_Vector *cv_tempvS;     /* temporary storage vector (~ tempv)           */
+    N_Vector *cv_ftempS;     /* temporary storage vector (~ ftemp)           */
+
+    /*-----------------------------------------------
+      Does CVodeSensMalloc allocate additional space?
+      -----------------------------------------------*/  
+
+    booleantype cv_stgr1alloc; /* Did we allocate ncfS1, ncfnS1, and nniS1?  */
+
+    /*-----------------
+      Tstop information
+      -----------------*/
+    booleantype cv_istop;
+    booleantype cv_tstopset;
+    realtype cv_tstop;
+
+    /*---------
+      Step Data 
+      ---------*/
+
+    int cv_q;                    /* current order                            */
+    int cv_qprime;               /* order to be used on the next step        */ 
+    /* = q-1, q, or q+1                         */
+    int cv_next_q;               /* order to be used on the next step        */
+    int cv_qwait;                /* number of internal steps to wait before  */
+    /* considering a change in q                */
+    int cv_L;                    /* L = q + 1                                */
+
+    realtype cv_hin;
+    realtype cv_h;               /* current step size                        */
+    realtype cv_hprime;          /* step size to be used on the next step    */ 
+    realtype cv_next_h;          /* step size to be used on the next step    */ 
+    realtype cv_eta;             /* eta = hprime / h                         */
+    realtype cv_hscale;          /* value of h used in zn                    */
+    realtype cv_tn;              /* current internal value of t              */
+    realtype cv_tretlast;        /* last value of t returned                 */
+
+    realtype cv_tau[L_MAX+1];    /* array of previous q+1 successful step
+                                    sizes indexed from 1 to q+1              */
+    realtype cv_tq[NUM_TESTS+1]; /* array of test quantities indexed from
+                                    1 to NUM_TESTS(=5)                       */
+    realtype cv_l[L_MAX];        /* coefficients of l(x) (degree q poly)     */
+
+    realtype cv_rl1;             /* the scalar 1/l[1]                        */
+    realtype cv_gamma;           /* gamma = h * rl1                          */
+    realtype cv_gammap;          /* gamma at the last setup call             */
+    realtype cv_gamrat;          /* gamma / gammap                           */
+
+    realtype cv_crate;           /* est. corrector conv. rate in Nls         */
+    realtype cv_crateS;          /* est. corrector conv. rate in NlsStgr     */
+    realtype cv_acnrm;           /* | acor |                                 */
+    realtype cv_acnrmS;          /* | acorS |                                */
+    realtype cv_acnrmQ;          /* | acorQ |                                */
+    realtype cv_nlscoef;         /* coeficient in nonlinear convergence test */
+    int  cv_mnewt;               /* Newton iteration counter                 */
+    int  *cv_ncfS1;              /* Array of Ns local counters for conv.  
+                                    failures (used in CVStep for STAGGERED1) */
+
+    /*------
+      Limits 
+      ------*/
+
+    int cv_qmax;             /* q <= qmax                                    */
+    long int cv_mxstep;      /* maximum number of internal steps for one 
+                                user call                                    */
+    int cv_maxcor;           /* maximum number of corrector iterations for 
+                                the solution of the nonlinear equation       */
+    int cv_maxcorS;
+    int cv_mxhnil;           /* maximum number of warning messages issued to 
+                                the user that t + h == t for the next 
+                                internal step                                */
+    int cv_maxnef;           /* maximum number of error test failures        */
+    int cv_maxncf;           /* maximum number of nonlinear conv. failures   */
+
+    realtype cv_hmin;        /* |h| >= hmin                                  */
+    realtype cv_hmax_inv;    /* |h| <= 1/hmax_inv                            */
+    realtype cv_etamax;      /* eta <= etamax                                */
+
+    /*----------
+      Counters 
+      ----------*/
+
+    long int cv_nst;         /* number of internal steps taken               */
+    long int cv_nfe;         /* number of f calls                            */
+    long int cv_nfSe;        /* number of fS calls                           */
+    long int cv_nfQe;        /* number of fQ calls                           */
+    long int cv_nfeS;        /* number of f calls from sensi DQ              */
+
+    long int cv_ncfn;        /* number of corrector convergence failures     */
+    long int cv_ncfnS;       /* number of total sensi. corr. conv. failures  */
+    long int *cv_ncfnS1;     /* number of sensi. corrector conv. failures    */
+
+    long int cv_nni;         /* number of nonlinear iterations performed     */
+    long int cv_nniS;        /* number of total sensi. nonlinear iterations  */
+    long int *cv_nniS1;      /* number of sensi. nonlinear iterations        */
+
+    long int cv_netf;        /* number of error test failures                */
+    long int cv_netfS;       /* number of sensi. error test failures         */
+    long int cv_netfQ;       /* number of quadr. error test failures         */
+
+    long int cv_nsetups;     /* number of setup calls                        */
+    long int cv_nsetupsS;    /* number of setup calls due to sensitivities   */
+
+    int cv_nhnil;            /* number of messages issued to the user that
+                                t + h == t for the next iternal step    */
+
+    /*-----------------------------
+      Space requirements for CVODES 
+      -----------------------------*/
+
+    long int cv_lrw1;        /* no. of realtype words in 1 N_Vector y        */ 
+    long int cv_liw1;        /* no. of integer words in 1 N_Vector y         */ 
+    long int cv_lrw1Q;       /* no. of realtype words in 1 N_Vector yQ       */ 
+    long int cv_liw1Q;       /* no. of integer words in 1 N_Vector yQ        */ 
+    long int cv_lrw;         /* no. of realtype words in CVODES work vectors */
+    long int cv_liw;         /* no. of integer words in CVODES work vectors  */
+
+    /*----------------
+      Step size ratios
+      ----------------*/
+
+    realtype cv_etaqm1;      /* ratio of new to old h for order q-1          */
+    realtype cv_etaq;        /* ratio of new to old h for order q            */
+    realtype cv_etaqp1;      /* ratio of new to old h for order q+1          */
+
+    /*------------------
+      Linear Solver Data 
+      ------------------*/
+
+    /* Linear Solver functions to be called */
+
+    int (*cv_linit)(struct CVodeMemRec *cv_mem);
+
+    int (*cv_lsetup)(struct CVodeMemRec *cv_mem, int convfail, 
+                     N_Vector ypred, N_Vector fpred, booleantype *jcurPtr, 
+                     N_Vector vtemp1, N_Vector vtemp2, N_Vector vtemp3); 
+
+    int (*cv_lsolve)(struct CVodeMemRec *cv_mem, N_Vector b, N_Vector weight,
+                     N_Vector ycur, N_Vector fcur);
+
+    void (*cv_lfree)(struct CVodeMemRec *cv_mem);
+
+    /* Linear Solver specific memory */
+
+    void *cv_lmem;           
+
+    /* Flag to request a call to the setup routine */
+
+    booleantype cv_forceSetup;
+
+    /*------------
+      Saved Values
+      ------------*/
+
+    int cv_qu;             /* last successful q value used                        */
+    long int cv_nstlp;     /* step number of last setup call                      */
+    realtype cv_h0u;       /* actual initial stepsize                             */
+    realtype cv_hu;        /* last successful h value used                        */
+    realtype cv_saved_tq5; /* saved value of tq[5]                                */
+    booleantype cv_jcur;   /* Is the Jacobian info used by linear solver current? */
+    realtype cv_tolsf;     /* tolerance scale factor                              */
+    int cv_qmax_alloc;     /* value of qmax used when allocating memory           */
+    int cv_qmax_allocQ;    /* value of qmax used when allocating quad. memory     */
+    int cv_qmax_allocS;    /* value of qmax used when allocating sensi. memory    */
+    int cv_indx_acor;      /* index of the zn vector in which acor is saved       */
+    booleantype cv_setupNonNull; /* Does setup do something?                      */
+
+    /*--------------------------------------------------------------------
+      Flags turned ON by CVodeMalloc, CVodeSensMalloc, and CVodeQuadMalloc 
+      and read by CVodeReInit, CVodeSensReInit, and CVodeQuadReInit
+      --------------------------------------------------------------------*/
+
+    booleantype cv_VabstolMallocDone;
+    booleantype cv_MallocDone;
+
+    booleantype cv_VabstolQMallocDone;
+    booleantype cv_quadMallocDone;
+
+    booleantype cv_VabstolSMallocDone;
+    booleantype cv_SabstolSMallocDone;
+    booleantype cv_sensMallocDone;
+
+    /*-------------------------------------------
+      Error handler function and error ouput file 
+      -------------------------------------------*/
+
+    CVErrHandlerFn cv_ehfun;    /* Error messages are handled by ehfun       */
+    void *cv_eh_data;           /* user pointer passed to ehfun              */
+    FILE *cv_errfp;             /* CVODES error messages are sent to errfp   */    
+
+    /*-------------------------
+      Stability Limit Detection
+      -------------------------*/
+
+    booleantype cv_sldeton;     /* Is Stability Limit Detection on?          */
+    realtype cv_ssdat[6][4];    /* scaled data array for STALD               */
+    int cv_nscon;               /* counter for STALD method                  */
+    long int cv_nor;            /* counter for number of order reductions    */
+
+    /*----------------
+      Rootfinding Data
+      ----------------*/
+
+    CVRootFn cv_gfun;     /* Function g for roots sought                     */
+    int cv_nrtfn;         /* number of components of g                       */
+    void *cv_g_data;      /* pointer to user data for g                      */
+    int *cv_iroots;       /* int array for root information                  */
+    realtype cv_tlo;      /* nearest endpoint of interval in root search     */
+    realtype cv_thi;      /* farthest endpoint of interval in root search    */
+    realtype cv_trout;    /* t value returned by rootfinding routine         */
+    realtype *cv_glo;     /* saved array of g values at t = tlo              */
+    realtype *cv_ghi;     /* saved array of g values at t = thi              */
+    realtype *cv_grout;   /* array of g values at t = trout                  */
+    realtype cv_toutc;    /* copy of tout (if NORMAL mode)                   */
+    realtype cv_ttol;     /* tolerance on root location trout                */
+    int cv_taskc;         /* copy of parameter task                          */
+    int cv_irfnd;         /* flag showing whether last step had a root       */
+    long int cv_nge;      /* counter for g evaluations                       */
+
+  } *CVodeMem;
+
+
+  /* 
+   * =================================================================
+   *   A D J O I N T   M O D U L E    M E M O R Y    B L O C K
+   * =================================================================
+   */
+
+  /*
+   * -----------------------------------------------------------------
+   * Forward references for pointers to various structures 
+   * -----------------------------------------------------------------
+   */
+
+  typedef struct CVadjMemRec *CVadjMem;
+  typedef struct CkpntMemRec *CkpntMem;
+  typedef struct DtpntMemRec *DtpntMem;
+
+  /*
+   * -----------------------------------------------------------------
+   * Types for functions provided by an interpolation module
+   * -----------------------------------------------------------------
+   * CVAGetYFn:   Function type for a function that returns the 
+   *              interpolated forward solution.
+   * CVAStorePnt: Function type for a function that stores a new
+   *              point in the structure d
+   * -----------------------------------------------------------------
+   */
+
+  typedef int (*CVAGetYFn)(CVadjMem ca_mem, realtype t, N_Vector y);
+  typedef int (*CVAStorePntFn)(CVodeMem cv_mem, DtpntMem d);
+
+  /*
+   * -----------------------------------------------------------------
+   * Types : struct CkpntMemRec, CkpntMem
+   * -----------------------------------------------------------------
+   * The type CkpntMem is type pointer to struct CkpntMemRec.
+   * This structure contains fields to store all information at a
+   * check point that is needed to 'hot' start cvodes.
+   * -----------------------------------------------------------------
+   */
+
+  struct CkpntMemRec {
+
+    /* Integration limits */
+    realtype ck_t0;
+    realtype ck_t1;
+    
+    /* Nordsieck History Array */
+    N_Vector ck_zn[L_MAX];
+    
+    /* Nordsieck History Array for quadratures */
+    N_Vector ck_znQ[L_MAX];
+    
+    /* Do we need to carry quadratures? */
+    booleantype ck_quadr;
+    
+    /* Was ck_zn[qmax] allocated?
+       ck_zqm = 0    - no
+       ck_zqm = qmax - yes      */
+    int ck_zqm;
+    
+    /* Step data */
+    long int ck_nst;
+    realtype ck_tretlast;
+    int      ck_q;
+    int      ck_qprime;
+    int      ck_qwait;
+    int      ck_L;
+    realtype ck_gammap;
+    realtype ck_h;
+    realtype ck_hprime;
+    realtype ck_hscale;
+    realtype ck_eta;
+    realtype ck_etamax;
+    realtype ck_tau[L_MAX+1];
+    realtype ck_tq[NUM_TESTS+1];
+    realtype ck_l[L_MAX];
+    
+    /* Saved values */
+    realtype ck_saved_tq5;
+    
+    /* Pointer to next structure in list */
+    struct CkpntMemRec *ck_next;
+    
+  };
+  
+  /*
+   * -----------------------------------------------------------------
+   * Type : struct DtpntMemRec
+   * -----------------------------------------------------------------
+   * This structure contains fields to store all information at a
+   * data point that is needed to interpolate solution of forward
+   * simulations. Its content field is interpType-dependent.
+   * -----------------------------------------------------------------
+   */
+  
+  struct DtpntMemRec {
+    realtype t;    /* time */
+    void *content; /* interpType-dependent content */
+  };
+
+  /* Data for cubic Hermite interpolation */
+  typedef struct HermiteDataMemRec {
+    N_Vector y;
+    N_Vector yd;
+  } *HermiteDataMem;
+
+  /* Data for polynomial interpolation */
+  typedef struct PolynomialDataMemRec {
+    N_Vector y;
+    int order;
+  } *PolynomialDataMem;
+
+  /*
+   * -----------------------------------------------------------------
+   * Type : struct CVadjMemRec
+   * -----------------------------------------------------------------
+   * The type CVadjMem is type pointer to struct CVadjMemRec.
+   * This structure contins fields to store all information
+   * necessary for adjoint sensitivity analysis.
+   * -----------------------------------------------------------------
+   */
+
+  struct CVadjMemRec {
+    
+    /* CVODE memory for forward runs */
+    struct CVodeMemRec *cv_mem;
+    
+    /* CVODE memory for backward run */
+    struct CVodeMemRec *cvb_mem;
+    
+    /* Storage for check point information */
+    struct CkpntMemRec *ck_mem;
+
+    /* Interpolation type */
+    int ca_interpType;
+
+    /* Storage for data from forward runs */
+    struct DtpntMemRec **dt_mem;
+    
+    /* Functions set by the interpolation module */
+    CVAStorePntFn ca_storePnt; /* store a new interpolation point */
+    CVAGetYFn     ca_getY;     /* interpolate forward solution    */
+    
+    /* Right hand side function (fB) for backward run */
+    CVRhsFnB ca_fB;
+    
+    /* Right hand side quadrature function (fQB) for backward run */
+    CVQuadRhsFnB ca_fQB;
+
+    /* User f_dataB */
+    void *ca_f_dataB;
+    
+    /* User fQ_dataB */
+    void *ca_fQ_dataB;
+    
+    /* Memory block for a linear solver's interface to CVODEA */
+    void *ca_lmemB;
+
+    /* Function to free any memory allocated by the linear solver */
+    void (*ca_lfreeB)(CVadjMem ca_mem);
+
+    /* Memory block for a preconditioner's module interface to CVODEA */ 
+    void *ca_pmemB;
+    
+    /* Unit roundoff */
+    realtype ca_uround;
+    
+    /* Integration interval */
+    realtype ca_tinitial, ca_tfinal;
+    
+    /* Time at which to extract quadratures */
+    realtype ca_t_for_quad;
+    
+    /* Number of check points */
+    int ca_nckpnts;
+    
+    /* Number of steps between 2 check points */
+    long int ca_nsteps;
+    
+    /* Flag to indicate that data in dt_mem is new */
+    booleantype ca_newData;
+    
+    /* address of the check point structure for which data is available */
+    struct CkpntMemRec *ca_ckpntData;
+    
+    /* Actual number of data points saved in current dt_mem */
+    /* Commonly, np = nsteps+1                              */
+    long int ca_np;
+    
+    /* Workspace used by the Hermite interpolation */
+    N_Vector ca_Y0, ca_Y1;    /* pointers to zn[0] and zn[1] */
+
+    /* Workspace for polynomial interpolation */
+    N_Vector ca_Y[L_MAX];     /* pointers to zn[i] */
+    realtype ca_T[L_MAX];
+
+    /* Workspace for wrapper functions */
+    N_Vector ca_ytmp;
+    
+  };
+  
+
+  /*
+   * =================================================================
+   *     I N T E R F A C E   T O    L I N E A R   S O L V E R S
+   * =================================================================
+   */
+
+  /*
+   * -----------------------------------------------------------------
+   * Communication between CVODE and a CVODE Linear Solver
+   * -----------------------------------------------------------------
+   * convfail (input to cv_lsetup)
+   *
+   * CV_NO_FAILURES : Either this is the first cv_setup call for this
+   *                  step, or the local error test failed on the
+   *                  previous attempt at this step (but the Newton
+   *                  iteration converged).
+   *
+   * CV_FAIL_BAD_J  : This value is passed to cv_lsetup if
+   *
+   *                  (a) The previous Newton corrector iteration
+   *                      did not converge and the linear solver's
+   *                      setup routine indicated that its Jacobian-
+   *                      related data is not current
+   *                                   or
+   *                  (b) During the previous Newton corrector
+   *                      iteration, the linear solver's solve routine
+   *                      failed in a recoverable manner and the
+   *                      linear solver's setup routine indicated that
+   *                      its Jacobian-related data is not current.
+   *
+   * CV_FAIL_OTHER  : During the current internal step try, the
+   *                  previous Newton iteration failed to converge
+   *                  even though the linear solver was using current
+   *                  Jacobian-related data.
+   * -----------------------------------------------------------------
+   */
+
+  /* Constants for convfail (input to cv_lsetup) */
+
+#define CV_NO_FAILURES 0
+#define CV_FAIL_BAD_J  1
+#define CV_FAIL_OTHER  2
+
+  /*
+   * -----------------------------------------------------------------
+   * int (*cv_linit)(CVodeMem cv_mem);
+   * -----------------------------------------------------------------
+   * The purpose of cv_linit is to complete initializations for a
+   * specific linear solver, such as counters and statistics.
+   * An LInitFn should return 0 if it has successfully initialized the
+   * CVODE linear solver and a negative value otherwise.
+   * If an error does occur, an appropriate message should be sent to
+   * the error handler function.
+   * -----------------------------------------------------------------
+   */
+
+  /*
+   * -----------------------------------------------------------------
+   * int (*cv_lsetup)(CVodeMem cv_mem, int convfail, N_Vector ypred,
+   *                 N_Vector fpred, booleantype *jcurPtr,
+   *                 N_Vector vtemp1, N_Vector vtemp2,
+   *                 N_Vector vtemp3);
+   * -----------------------------------------------------------------
+   * The job of cv_lsetup is to prepare the linear solver for
+   * subsequent calls to cv_lsolve. It may recompute Jacobian-
+   * related data is it deems necessary. Its parameters are as
+   * follows:
+   *
+   * cv_mem - problem memory pointer of type CVodeMem. See the
+   *          typedef earlier in this file.
+   *
+   * convfail - a flag to indicate any problem that occurred during
+   *            the solution of the nonlinear equation on the
+   *            current time step for which the linear solver is
+   *            being used. This flag can be used to help decide
+   *            whether the Jacobian data kept by a CVODE linear
+   *            solver needs to be updated or not.
+   *            Its possible values have been documented above.
+   *
+   * ypred - the predicted y vector for the current CVODE internal
+   *         step.
+   *
+   * fpred - f(tn, ypred).
+   *
+   * jcurPtr - a pointer to a boolean to be filled in by cv_lsetup.
+   *           The function should set *jcurPtr=TRUE if its Jacobian
+   *           data is current after the call and should set
+   *           *jcurPtr=FALSE if its Jacobian data is not current.
+   *           Note: If cv_lsetup calls for re-evaluation of
+   *           Jacobian data (based on convfail and CVODE state
+   *           data), it should return *jcurPtr=TRUE always;
+   *           otherwise an infinite loop can result.
+   *
+   * vtemp1 - temporary N_Vector provided for use by cv_lsetup.
+   *
+   * vtemp3 - temporary N_Vector provided for use by cv_lsetup.
+   *
+   * vtemp3 - temporary N_Vector provided for use by cv_lsetup.
+   *
+   * The cv_lsetup routine should return 0 if successful, a positive
+   * value for a recoverable error, and a negative value for an
+   * unrecoverable error.
+   * -----------------------------------------------------------------
+   */
+
+  /*
+   * -----------------------------------------------------------------
+   * int (*cv_lsolve)(CVodeMem cv_mem, N_Vector b, N_Vector weight,
+   *                  N_Vector ycur, N_Vector fcur);
+   * -----------------------------------------------------------------
+   * cv_lsolve must solve the linear equation P x = b, where
+   * P is some approximation to (I - gamma J), J = (df/dy)(tn,ycur)
+   * and the RHS vector b is input. The N-vector ycur contains
+   * the solver's current approximation to y(tn) and the vector
+   * fcur contains the N_Vector f(tn,ycur). The solution is to be
+   * returned in the vector b. cv_lsolve returns a positive value
+   * for a recoverable error and a negative value for an
+   * unrecoverable error. Success is indicated by a 0 return value.
+   * -----------------------------------------------------------------
+   */
+
+  /*
+   * -----------------------------------------------------------------
+   * void (*cv_lfree)(CVodeMem cv_mem);
+   * -----------------------------------------------------------------
+   * cv_lfree should free up any memory allocated by the linear
+   * solver. This routine is called once a problem has been
+   * completed and the linear solver is no longer needed.
+   * -----------------------------------------------------------------
+   */
+
+  /*
+   * =================================================================
+   *   C V O D E S    I N T E R N A L   F U N C T I O N S
+   * =================================================================
+   */
+  
+  /* Prototype of internal ewtSet function */
+
+  int CVEwtSet(N_Vector ycur, N_Vector weight, void *e_data);
+
+  /* High level error handler */
+
+  void CVProcessError(CVodeMem cv_mem, 
+                      int error_code, const char *module, const char *fname, 
+                      const char *msgfmt, ...);
+
+  /* Prototype of internal errHandler function */
+
+  void CVErrHandler(int error_code, const char *module, const char *function, 
+                    char *msg, void *eh_data);
+
+  /* Prototypes for internal sensitivity rhs DQ functions */
+
+  int CVSensRhsDQ(int Ns, realtype t, 
+                  N_Vector y, N_Vector ydot, 
+                  N_Vector *yS, N_Vector *ySdot, 
+                  void *fS_data,  
+                  N_Vector tempv, N_Vector ftemp);
+
+  int CVSensRhs1DQ(int Ns, realtype t, 
+                   N_Vector y, N_Vector ydot, 
+                   int is, N_Vector yS, N_Vector ySdot, 
+                   void *fS_data,
+                   N_Vector tempv, N_Vector ftemp);
+
+
+  /* 
+   * =================================================================
+   *   C V O D E S    E R R O R    M E S S A G E S
+   * =================================================================
+   */
+
+#if defined(SUNDIALS_EXTENDED_PRECISION)
+
+#define MSG_TIME      "t = %Lg"
+#define MSG_TIME_H    "t = %Lg and h = %Lg"
+#define MSG_TIME_INT  "t = %Lg is not between tcur - hu = %Lg and tcur = %Lg."
+#define MSG_TIME_TOUT "tout = %Lg"
+
+#elif defined(SUNDIALS_DOUBLE_PRECISION)
+
+#define MSG_TIME      "t = %lg"
+#define MSG_TIME_H    "t = %lg and h = %lg"
+#define MSG_TIME_INT  "t = %lg is not between tcur - hu = %lg and tcur = %lg."
+#define MSG_TIME_TOUT "tout = %lg"
+
+#else
+
+#define MSG_TIME      "t = %g"
+#define MSG_TIME_H    "t = %g and h = %g"
+#define MSG_TIME_INT  "t = %g is not between tcur - hu = %g and tcur = %g."
+#define MSG_TIME_TOUT "tout = %g"
+
+#endif
+
+
+/* Initialization and I/O error messages */
+
+#define MSGCV_NO_MEM "cvode_mem = NULL illegal."
+#define MSGCV_CVMEM_FAIL "Allocation of cvode_mem failed."
+#define MSGCV_MEM_FAIL "A memory request failed."
+#define MSGCV_BAD_LMM  "Illegal value for lmm. The legal values are CV_ADAMS and CV_BDF."
+#define MSGCV_BAD_ITER  "Illegal value for iter. The legal values are CV_FUNCTIONAL and CV_NEWTON."
+#define MSGCV_BAD_ITOL "Illegal value for itol. The legal values are CV_SS, CV_SV, and CV_WF."
+#define MSGCV_NO_MALLOC "Attempt to call before CVodeMalloc."
+#define MSGCV_NEG_MAXORD "maxord <= 0 illegal."
+#define MSGCV_BAD_MAXORD  "Illegal attempt to increase maximum method order."
+#define MSGCV_NEG_MXSTEPS "mxsteps < 0 illegal."
+#define MSGCV_SET_SLDET  "Attempt to use stability limit detection with the CV_ADAMS method illegal."
+#define MSGCV_NEG_HMIN "hmin < 0 illegal."
+#define MSGCV_NEG_HMAX "hmax < 0 illegal."
+#define MSGCV_BAD_HMIN_HMAX "Inconsistent step size limits: hmin > hmax."
+#define MSGCV_BAD_RELTOL "reltol < 0 illegal."
+#define MSGCV_BAD_ABSTOL "abstol has negative component(s) (illegal)."
+#define MSGCV_NULL_ABSTOL "abstol = NULL illegal."
+#define MSGCV_NULL_Y0 "y0 = NULL illegal."
+#define MSGCV_NULL_F "f = NULL illegal."
+#define MSGCV_NULL_G "g = NULL illegal."
+#define MSGCV_BAD_NVECTOR "A required vector operation is not implemented."
+#define MSGCV_BAD_K "Illegal value for k."
+#define MSGCV_NULL_DKY "dky = NULL illegal."
+#define MSGCV_BAD_T "Illegal value for t." MSG_TIME_INT
+
+#define MSGCV_NO_QUAD  "Illegal attempt to call before calling CVodeQuadMalloc."
+#define MSGCV_BAD_ITOLQ "Illegal value for itolQ. The legal values are CV_SS and CV_SV."
+#define MSGCV_NULL_ABSTOLQ "abstolQ = NULL illegal."
+#define MSGCV_BAD_RELTOLQ "reltolQ < 0 illegal."
+#define MSGCV_BAD_ABSTOLQ "abstolQ has negative component(s) (illegal)."  
+
+#define MSGCV_NO_SENSI  "Illegal attempt to call before calling CVodeSensMalloc."
+#define MSGCV_BAD_ITOLS "Illegal value for itolS. The legal values are CV_SS, CV_SV, and CV_EE."
+#define MSGCV_NULL_ABSTOLS "abstolS = NULL illegal."
+#define MSGCV_BAD_RELTOLS "reltolS < 0 illegal."
+#define MSGCV_BAD_ABSTOLS "abstolS has negative component(s) (illegal)."  
+#define MSGCV_BAD_PBAR "pbar has zero component(s) (illegal)."
+#define MSGCV_BAD_PLIST "plist has negative component(s) (illegal)."
+#define MSGCV_BAD_NS "NS <= 0 illegal."
+#define MSGCV_NULL_YS0 "yS0 = NULL illegal."
+#define MSGCV_BAD_ISM "Illegal value for ism. Legal values are: CV_SIMULTANEOUS, CV_STAGGERED and CV_STAGGERED1."
+#define MSGCV_BAD_IS "Illegal value for is."
+#define MSGCV_NULL_DKYA "dkyA = NULL illegal."
+#define MSGCV_BAD_DQTYPE "Illegal value for DQtype. Legal values are: CV_CENTERED and CV_FORWARD."
+#define MSGCV_BAD_DQRHO "DQrhomax < 0 illegal."
+
+/* CVode Error Messages */
+
+#define MSGCV_LSOLVE_NULL "The linear solver's solve routine is NULL."
+#define MSGCV_YOUT_NULL "yout = NULL illegal."
+#define MSGCV_TRET_NULL "tret = NULL illegal."
+#define MSGCV_BAD_EWT "Initial ewt has component(s) equal to zero (illegal)."
+#define MSGCV_EWT_NOW_BAD "At " MSG_TIME ", a component of ewt has become <= 0."
+#define MSGCV_BAD_ITASK "Illegal value for itask."
+#define MSGCV_BAD_H0 "h0 and tout - t0 inconsistent."
+#define MSGCV_BAD_INIT_ROOT "Root found at and very near initial t."
+#define MSGCV_BAD_TOUT "Trouble interpolating at " MSG_TIME_TOUT ". tout too far back in direction of integration"
+#define MSGCV_NO_EFUN "itol = CV_WF but no EwtSet function was provided."
+#define MSGCV_NO_TSTOP "itask = CV_NORMAL_TSTOP or itask = CV_ONE_STEP_TSTOP but tstop was not set."
+#define MSGCV_EWT_FAIL "The user-provide EwtSet function failed."
+#define MSGCV_EWT_NOW_FAIL "At " MSG_TIME ", the user-provide EwtSet function failed."
+#define MSGCV_LINIT_FAIL "The linear solver's init routine failed."
+#define MSGCV_HNIL_DONE "The above warning has been issued mxhnil times and will not be issued again for this problem."
+#define MSGCV_TOO_CLOSE "tout too close to t0 to start integration."
+#define MSGCV_MAX_STEPS "At " MSG_TIME ", mxstep steps taken before reaching tout."
+#define MSGCV_TOO_MUCH_ACC "At " MSG_TIME ", too much accuracy requested."
+#define MSGCV_HNIL "Internal " MSG_TIME_H " are such that t + h = t on the next step. The solver will continue anyway."
+#define MSGCV_ERR_FAILS "At " MSG_TIME_H ", the error test failed repeatedly or with |h| = hmin."
+#define MSGCV_CONV_FAILS "At " MSG_TIME_H ", the corrector convergence test failed repeatedly or with |h| = hmin."
+#define MSGCV_SETUP_FAILED "At " MSG_TIME ", the setup routine failed in an unrecoverable manner."
+#define MSGCV_SOLVE_FAILED "At " MSG_TIME ", the solve routine failed in an unrecoverable manner."
+#define MSGCV_RHSFUNC_FAILED "At " MSG_TIME ", the right-hand side routine failed in an unrecoverable manner."
+#define MSGCV_RHSFUNC_UNREC "At " MSG_TIME ", the right-hand side failed in a recoverable manner, but no recovery is possible."
+#define MSGCV_RHSFUNC_REPTD "At " MSG_TIME "repeated recoverable right-hand side function errors."
+#define MSGCV_RHSFUNC_FIRST "The right-hand side routine failed at the first call."
+#define MSGCV_RTFUNC_FAILED "At " MSG_TIME ", the rootfinding routine failed in an unrecoverable manner."
+#define MSGCV_CLOSE_ROOTS "Root found at and very near " MSG_TIME "."
+#define MSGCV_BAD_TSTOP "tstop is behind current " MSG_TIME "in the direction of integration."
+
+#define MSGCV_BAD_EWTQ "Initial ewtQ has component(s) equal to zero (illegal)."
+#define MSGCV_EWTQ_NOW_BAD "At " MSG_TIME ", a component of ewtQ has become <= 0."
+#define MSGCV_QRHSFUNC_FAILED "At " MSG_TIME ", the quadrature right-hand side routine failed in an unrecoverable manner."
+#define MSGCV_QRHSFUNC_UNREC "At " MSG_TIME ", the quadrature right-hand side failed in a recoverable manner, but no recovery is possible."
+#define MSGCV_QRHSFUNC_REPTD "At " MSG_TIME "repeated recoverable quadrature right-hand side function errors."
+#define MSGCV_QRHSFUNC_FIRST "The quadrature right-hand side routine failed at the first call."
+
+#define MSGCV_BAD_ISM_IFS "Illegal sens. rhs for ism = CV_STAGGERED1."
+#define MSGCV_NULL_P "p = NULL when using internal DQ for sensitivity RHS illegal."
+#define MSGCV_BAD_EWTS "Initial ewtS has component(s) equal to zero (illegal)."
+#define MSGCV_EWTS_NOW_BAD "At " MSG_TIME ", a component of ewtS has become <= 0."
+#define MSGCV_SRHSFUNC_FAILED "At " MSG_TIME ", the sensitivity right-hand side routine failed in an unrecoverable manner."
+#define MSGCV_SRHSFUNC_UNREC "At " MSG_TIME ", the sensitivity right-hand side failed in a recoverable manner, but no recovery is possible."
+#define MSGCV_SRHSFUNC_REPTD "At " MSG_TIME "repeated recoverable sensitivity right-hand side function errors."
+#define MSGCV_SRHSFUNC_FIRST "The sensitivity right-hand side routine failed at the first call."
+
+  /* 
+   * =================================================================
+   *   C V O D E A    E R R O R    M E S S A G E S
+   * =================================================================
+   */
+
+#define MSGAM_NULL_CVMEM   "cvode_mem = NULL illegal."
+#define MSGAM_NULL_CAMEM   "cvadj_mem = NULL illegal."
+#define MSGAM_BAD_STEPS    "Steps nonpositive illegal."
+#define MSGAM_MEM_FAIL     "A memory request failed."
+#define MSGAM_BAD_INTERP   "Illegal value for interp."
+#define MSGAM_BAD_ITASKB   "Illegal value for itaskB. Legal values are CV_NORMAL and CV_ONE_STEP."
+#define MSGAM_BAD_TB0      "The initial time tB0 is outside the interval over which the forward problem was solved."
+#define MSGAM_BAD_TBOUT    "The final time tBout is outside the interval over which the forward problem was solved."
+#define MSGAM_BAD_T        "Bad t for interpolation."
+#define MSGAM_WRONG_INTERP "This function cannot be called for the specified interp type."
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_io.c b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_io.c
new file mode 100644
index 0000000000000000000000000000000000000000..59c4cde97916f7075dbd260639f056c43b21bbe9
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_io.c
@@ -0,0 +1,2051 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * -----------------------------------------------------------------
+ * Programmer(s): Alan C. Hindmarsh and Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2005, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the implementation file for the optional input and output
+ * functions for the CVODES solver.
+ * -----------------------------------------------------------------
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "cvodes_impl.h"
+
+#include <sundials/sundials_math.h>
+#include <sundials/sundials_types.h>
+
+#define ZERO RCONST(0.0)
+#define ONE  RCONST(1.0)
+
+/* 
+ * =================================================================
+ * CVODES optional input functions
+ * =================================================================
+ */
+
+/* 
+ * Readability constants
+ */
+
+#define lrw   (cv_mem->cv_lrw)
+#define liw   (cv_mem->cv_liw)
+#define lrw1  (cv_mem->cv_lrw1)
+#define liw1  (cv_mem->cv_liw1)
+
+/* 
+ * CVodeSetErrHandlerFn
+ *
+ * Specifies the error handler function
+ */
+
+int CVodeSetErrHandlerFn(void *cvode_mem, CVErrHandlerFn ehfun, void *eh_data)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSetErrHandlerFn", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  cv_mem->cv_ehfun = ehfun;
+  cv_mem->cv_eh_data = eh_data;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeSetErrFile
+ *
+ * Specifies the FILE pointer for output (NULL means no messages)
+ */
+
+int CVodeSetErrFile(void *cvode_mem, FILE *errfp)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSetErrFile", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  cv_mem->cv_errfp = errfp;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeSetIterType
+ *
+ * Specifies the iteration type (CV_FUNCTIONAL or CV_NEWTON)
+ */
+
+int CVodeSetIterType(void *cvode_mem, int iter)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSetIterType", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if ((iter != CV_FUNCTIONAL) && (iter != CV_NEWTON)) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSetIterType", MSGCV_BAD_ITER);
+    return (CV_ILL_INPUT);
+  }
+
+  cv_mem->cv_iter = iter;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeSetFdata
+ *
+ * Specifies the user data pointer for f
+ */
+
+int CVodeSetFdata(void *cvode_mem, void *f_data)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSetFdata", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  cv_mem->cv_f_data = f_data;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeSetMaxOrd
+ *
+ * Specifies the maximum method order
+ */
+
+int CVodeSetMaxOrd(void *cvode_mem, int maxord)
+{
+  CVodeMem cv_mem;
+  int qmax_alloc;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSetMaxOrd", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (maxord <= 0) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSetMaxOrd", MSGCV_NEG_MAXORD);
+    return(CV_ILL_INPUT);
+  }
+  
+  /* Cannot increase maximum order beyond the value that
+     was used when allocating memory */
+  qmax_alloc = cv_mem->cv_qmax_alloc;
+  qmax_alloc = MIN(qmax_alloc, cv_mem->cv_qmax_allocQ);
+  qmax_alloc = MIN(qmax_alloc, cv_mem->cv_qmax_allocS);  
+
+  if (maxord > qmax_alloc) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSetMaxOrd", MSGCV_BAD_MAXORD);
+    return(CV_ILL_INPUT);
+  }
+
+  cv_mem->cv_qmax = maxord;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeSetMaxNumSteps
+ *
+ * Specifies the maximum number of integration steps
+ */
+
+int CVodeSetMaxNumSteps(void *cvode_mem, long int mxsteps)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSetMaxNumSteps", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (mxsteps < 0) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSetMaxNumSteps", MSGCV_NEG_MXSTEPS);
+    return(CV_ILL_INPUT);
+  }
+
+  /* Passing 0 sets the default */
+  if (mxsteps == 0)
+    cv_mem->cv_mxstep = MXSTEP_DEFAULT;
+  else
+    cv_mem->cv_mxstep = mxsteps;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeSetMaxHnilWarns
+ *
+ * Specifies the maximum number of warnings for small h
+ */
+
+int CVodeSetMaxHnilWarns(void *cvode_mem, int mxhnil)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSetMaxHnilWarns", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  cv_mem->cv_mxhnil = mxhnil;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ *CVodeSetStabLimDet
+ *
+ * Turns on/off the stability limit detection algorithm
+ */
+
+int CVodeSetStabLimDet(void *cvode_mem, booleantype sldet)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSetStabLimDet", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if( sldet && (cv_mem->cv_lmm != CV_BDF) ) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSetStabLimDet", MSGCV_SET_SLDET);
+    return(CV_ILL_INPUT);
+  }
+
+  cv_mem->cv_sldeton = sldet;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeSetInitStep
+ *
+ * Specifies the initial step size
+ */
+
+int CVodeSetInitStep(void *cvode_mem, realtype hin)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSetInitStep", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  cv_mem->cv_hin = hin;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeSetMinStep
+ *
+ * Specifies the minimum step size
+ */
+
+int CVodeSetMinStep(void *cvode_mem, realtype hmin)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSetMinStep", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (hmin<0) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSetMinStep", MSGCV_NEG_HMIN);
+    return(CV_ILL_INPUT);
+  }
+
+  /* Passing 0 sets hmin = zero */
+  if (hmin == ZERO) {
+    cv_mem->cv_hmin = HMIN_DEFAULT;
+    return(CV_SUCCESS);
+  }
+
+  if (hmin * cv_mem->cv_hmax_inv > ONE) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSetMinStep", MSGCV_BAD_HMIN_HMAX);
+    return(CV_ILL_INPUT);
+  }
+
+  cv_mem->cv_hmin = hmin;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeSetMaxStep
+ *
+ * Specifies the maximum step size
+ */
+
+int CVodeSetMaxStep(void *cvode_mem, realtype hmax)
+{
+  realtype hmax_inv;
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSetMaxStep", MSGCV_NO_MEM);
+    return (CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (hmax < 0) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSetMaxStep", MSGCV_NEG_HMAX);
+    return(CV_ILL_INPUT);
+  }
+
+  /* Passing 0 sets hmax = infinity */
+  if (hmax == ZERO) {
+    cv_mem->cv_hmax_inv = HMAX_INV_DEFAULT;
+    return(CV_SUCCESS);
+  }
+
+  hmax_inv = ONE/hmax;
+  if (hmax_inv * cv_mem->cv_hmin > ONE) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSetMaxStep", MSGCV_BAD_HMIN_HMAX);
+    return(CV_ILL_INPUT);
+  }
+
+  cv_mem->cv_hmax_inv = hmax_inv;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeSetStopTime
+ *
+ * Specifies the time beyond which the integration is not to
+ * proceed
+ */
+
+int CVodeSetStopTime(void *cvode_mem, realtype tstop)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSetStopTime", MSGCV_NO_MEM);
+    return (CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  cv_mem->cv_tstop = tstop;
+  cv_mem->cv_tstopset = TRUE;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeSetMaxErrTestFails
+ *
+ * Specifies the maximum number of error test failures during one
+ * step try.
+ */
+
+int CVodeSetMaxErrTestFails(void *cvode_mem, int maxnef)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSetMaxErrTestFails", MSGCV_NO_MEM);
+    return (CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  cv_mem->cv_maxnef = maxnef;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeSetMaxConvFails
+ *
+ * Specifies the maximum number of nonlinear convergence failures 
+ * during one step try.
+ */
+
+int CVodeSetMaxConvFails(void *cvode_mem, int maxncf)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSetMaxConvFails", MSGCV_NO_MEM);
+    return (CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  cv_mem->cv_maxncf = maxncf;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeSetMaxNonlinIters
+ *
+ * Specifies the maximum number of nonlinear iterations during
+ * one solve.
+ */
+
+int CVodeSetMaxNonlinIters(void *cvode_mem, int maxcor)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSetMaxNonlinIters", MSGCV_NO_MEM);
+    return (CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  cv_mem->cv_maxcor = maxcor;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeSetNonlinConvCoef
+ *
+ * Specifies the coeficient in the nonlinear solver convergence
+ * test
+ */
+
+int CVodeSetNonlinConvCoef(void *cvode_mem, realtype nlscoef)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSetNonlinConvCoef", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  cv_mem->cv_nlscoef = nlscoef;
+
+  return(CV_SUCCESS);
+}
+
+/*
+ * CVodeSetTolerances
+ *
+ * Changes the integration tolerances between calls to CVode()
+ */
+
+int CVodeSetTolerances(void *cvode_mem, 
+                       int itol, realtype reltol, void *abstol)
+{
+  CVodeMem cv_mem;
+  booleantype neg_abstol;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSetTolerances", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  /* Check if cvode_mem was allocated */
+
+  if (cv_mem->cv_MallocDone == FALSE) {
+    CVProcessError(cv_mem, CV_NO_MALLOC, "CVODES", "CVodeSetTolerances", MSGCV_NO_MALLOC);
+    return(CV_NO_MALLOC);
+  }
+
+  /* Check inputs */
+
+  if ( (itol != CV_SS) && (itol != CV_SV) ) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSetTolerances", MSGCV_BAD_ITOL);
+    return(CV_ILL_INPUT);
+  }
+
+  if (abstol == NULL) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSetTolerances", MSGCV_NULL_ABSTOL);
+    return(CV_ILL_INPUT);
+  }
+
+  if (reltol < ZERO) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSetTolerances", MSGCV_BAD_RELTOL);
+    return(CV_ILL_INPUT);
+  }
+
+  if (itol == CV_SS)
+    neg_abstol = (*((realtype *)abstol) < ZERO);
+  else
+    neg_abstol = (N_VMin((N_Vector)abstol) < ZERO);
+    
+  if (neg_abstol) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSetTolerances", MSGCV_BAD_ABSTOL);
+    return(CV_ILL_INPUT);
+  }
+
+  /* Copy tolerances into memory */
+
+  if ( (itol != CV_SV) && (cv_mem->cv_VabstolMallocDone) ) {
+    N_VDestroy(cv_mem->cv_Vabstol);
+    lrw -= lrw1;
+    liw -= liw1;
+    cv_mem->cv_VabstolMallocDone = FALSE;
+  }
+
+  if ( (itol == CV_SV) && !(cv_mem->cv_VabstolMallocDone) ) {
+    cv_mem->cv_Vabstol = NULL;
+    cv_mem->cv_Vabstol = N_VClone(cv_mem->cv_ewt);
+    lrw += lrw1;
+    liw += liw1;
+    cv_mem->cv_VabstolMallocDone = TRUE;
+  }
+
+  cv_mem->cv_itol   = itol;
+  cv_mem->cv_reltol = reltol;
+  if (itol == CV_SS)
+    cv_mem->cv_Sabstol = *((realtype *)abstol);
+  else
+    N_VScale(ONE, (N_Vector)abstol, cv_mem->cv_Vabstol);
+
+  cv_mem->cv_efun = CVEwtSet;
+  cv_mem->cv_e_data = cvode_mem;
+
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeSetEwtFn
+ *
+ * Specifies the user-provide EwtSet function and data pointer for e
+ */
+
+int CVodeSetEwtFn(void *cvode_mem, CVEwtFn efun, void *e_data)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSetEwtFn", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if ( cv_mem->cv_VabstolMallocDone ) {
+    N_VDestroy(cv_mem->cv_Vabstol);
+    lrw -= lrw1;
+    liw -= liw1;
+    cv_mem->cv_VabstolMallocDone = FALSE;
+  }
+
+  cv_mem->cv_itol = CV_WF;
+  cv_mem->cv_efun = efun;
+  cv_mem->cv_e_data = e_data;
+
+  return(CV_SUCCESS);
+}
+
+
+/* 
+ * =================================================================
+ * Quadrature optional input functions
+ * =================================================================
+ */
+
+/* 
+ * Readability constants
+ */
+
+#define lrw1Q (cv_mem->cv_lrw1Q)
+#define liw1Q (cv_mem->cv_liw1Q)
+
+/*-----------------------------------------------------------------*/
+
+int CVodeSetQuadFdata(void *cvode_mem, void *fQ_data)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSetQuadFdata", MSGCV_NO_MEM);    
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  cv_mem->cv_fQ_data = fQ_data;
+
+  return(CV_SUCCESS);
+}
+
+/*-----------------------------------------------------------------*/
+
+int CVodeSetQuadErrCon(void *cvode_mem, booleantype errconQ, 
+                       int itolQ, realtype reltolQ, void *abstolQ)
+{
+  CVodeMem cv_mem;
+  booleantype neg_abstol;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSetQuadErrCon", MSGCV_NO_MEM);    
+    return(CV_MEM_NULL);
+  }
+  
+  cv_mem = (CVodeMem) cvode_mem;
+
+  cv_mem->cv_errconQ = errconQ;
+
+  /* Ckeck if quadrature was initialized? */
+
+  if (cv_mem->cv_quadMallocDone == FALSE) {
+    CVProcessError(cv_mem, CV_NO_QUAD, "CVODES", "CVodeSetQuadErrCon", MSGCV_NO_QUAD); 
+    return(CV_NO_QUAD);
+  }
+
+  /* Check inputs */
+
+  if(errconQ == FALSE) {
+    if (cv_mem->cv_VabstolQMallocDone) {
+      N_VDestroy(cv_mem->cv_VabstolQ);
+      lrw -= lrw1Q;
+      liw -= liw1Q;
+      cv_mem->cv_VabstolQMallocDone = FALSE;
+    }
+    return(CV_SUCCESS);
+  }
+  
+  if ((itolQ != CV_SS) && (itolQ != CV_SV)) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSetQuadErrCon", MSGCV_BAD_ITOLQ);
+    return(CV_ILL_INPUT);
+  }
+
+  if (abstolQ == NULL) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSetQuadErrCon", MSGCV_NULL_ABSTOLQ);
+    return(CV_ILL_INPUT);
+  }
+
+  if (reltolQ < ZERO) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSetQuadErrCon", MSGCV_BAD_RELTOLQ);
+    return(CV_ILL_INPUT);
+  }
+
+  if (itolQ == CV_SS)
+    neg_abstol = (*((realtype *)abstolQ) < ZERO);
+  else
+    neg_abstol = (N_VMin((N_Vector)abstolQ) < ZERO);
+
+  if (neg_abstol) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSetQuadErrCon", MSGCV_BAD_ABSTOLQ);
+    return(CV_ILL_INPUT);
+  }
+
+  /* See if we need to free or allocate memory */
+
+  if ( (itolQ != CV_SV) && (cv_mem->cv_VabstolQMallocDone) ) {
+    N_VDestroy(cv_mem->cv_VabstolQ);
+    lrw -= lrw1Q;
+    liw -= liw1Q;
+    cv_mem->cv_VabstolQMallocDone = FALSE;
+  }
+
+  if ( (itolQ == CV_SV) && !(cv_mem->cv_VabstolQMallocDone) ) {
+    cv_mem->cv_VabstolQ = NULL;
+    cv_mem->cv_VabstolQ = N_VClone(cv_mem->cv_tempvQ);
+    lrw += lrw1Q;
+    liw += liw1Q;
+    cv_mem->cv_VabstolQMallocDone = TRUE;
+  }
+
+  /* Copy tolerances into memory */
+
+  cv_mem->cv_itolQ    = itolQ;
+  cv_mem->cv_reltolQ  = reltolQ;
+
+  if (itolQ == CV_SS)
+    cv_mem->cv_SabstolQ = *((realtype *)abstolQ);
+  else
+    N_VScale(ONE, (N_Vector)abstolQ, cv_mem->cv_VabstolQ);
+  
+  return(CV_SUCCESS);
+}
+
+/* 
+ * =================================================================
+ * FSA optional input functions
+ * =================================================================
+ */
+
+
+int CVodeSetSensRhsFn(void *cvode_mem, CVSensRhsFn fS, void *fS_data)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSetSensRhsFn", MSGCV_NO_MEM);    
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (fS != NULL) {
+    cv_mem->cv_ifS  = CV_ALLSENS;
+    cv_mem->cv_fS      = fS;
+    cv_mem->cv_fS_data = fS_data;
+    cv_mem->cv_fSDQ    = FALSE;
+  } else {
+    cv_mem->cv_fSDQ    = TRUE;
+  }
+
+  return(CV_SUCCESS);
+}
+
+/*-----------------------------------------------------------------*/
+
+int CVodeSetSensRhs1Fn(void *cvode_mem, CVSensRhs1Fn fS1, void *fS_data)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSetSensRhs1Fn", MSGCV_NO_MEM);    
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+  
+  if(fS1 != NULL) {
+    cv_mem->cv_ifS  = CV_ONESENS;
+    cv_mem->cv_fS1     = fS1;
+    cv_mem->cv_fS_data = fS_data;
+    cv_mem->cv_fSDQ    = FALSE;
+  } else {
+    cv_mem->cv_fSDQ    = TRUE;
+  }
+
+  return(CV_SUCCESS);
+}
+
+/*-----------------------------------------------------------------*/
+
+int CVodeSetSensDQMethod(void *cvode_mem, int DQtype, realtype DQrhomax)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSetSensDQMethod", MSGCV_NO_MEM);    
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if ( (DQtype != CV_CENTERED) && (DQtype != CV_FORWARD) ) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSetSensDQMethod", MSGCV_BAD_DQTYPE);    
+    return(CV_ILL_INPUT);
+  }
+
+  if (DQrhomax < ZERO ) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSetSensDQMethod", MSGCV_BAD_DQRHO);    
+    return(CV_ILL_INPUT);
+  }
+
+  cv_mem->cv_DQtype = DQtype;
+  cv_mem->cv_DQrhomax = DQrhomax;
+
+  return(CV_SUCCESS);
+}
+
+/*-----------------------------------------------------------------*/
+
+int CVodeSetSensErrCon(void *cvode_mem, booleantype errconS)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSetSensErrCon", MSGCV_NO_MEM);    
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  cv_mem->cv_errconS = errconS;
+
+  return(CV_SUCCESS);
+}
+
+/*-----------------------------------------------------------------*/
+
+int CVodeSetSensMaxNonlinIters(void *cvode_mem, int maxcorS)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSetSensMaxNonlinIters", MSGCV_NO_MEM);    
+    return (CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  cv_mem->cv_maxcorS = maxcorS;
+
+  return(CV_SUCCESS);
+}
+
+/*-----------------------------------------------------------------*/
+
+int CVodeSetSensParams(void *cvode_mem, realtype *p, realtype *pbar, int *plist)
+{
+  CVodeMem cv_mem;
+  int is, Ns;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSetSensParams", MSGCV_NO_MEM);    
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  /* Was sensitivity initialized? */
+
+  if (cv_mem->cv_sensMallocDone == FALSE) {
+    CVProcessError(cv_mem, CV_NO_SENS, "CVODES", "CVodeSetSensParams", MSGCV_NO_SENSI);
+    return(CV_NO_SENS);
+  }
+
+  Ns = cv_mem->cv_Ns;
+
+  /* Parameters */
+
+  cv_mem->cv_p = p;
+
+  /* pbar */
+
+  if (pbar != NULL)
+    for (is=0; is<Ns; is++) {
+      if (pbar[is] == ZERO) {
+        CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSetSensParams", MSGCV_BAD_PBAR);
+        return(CV_ILL_INPUT);
+      }
+      cv_mem->cv_pbar[is] = ABS(pbar[is]);
+    }
+  else
+    for (is=0; is<Ns; is++)
+      cv_mem->cv_pbar[is] = ONE;
+
+  /* plist */
+
+  if (plist != NULL)
+    for (is=0; is<Ns; is++) {
+      if ( plist[is] < 0 ) {
+        CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSetSensParams", MSGCV_BAD_PLIST);
+        return(CV_ILL_INPUT);
+      }
+      cv_mem->cv_plist[is] = plist[is];
+    }
+  else
+    for (is=0; is<Ns; is++)
+      cv_mem->cv_plist[is] = is;
+
+  return(CV_SUCCESS);
+}
+
+/*-----------------------------------------------------------------*/
+
+int CVodeSetSensTolerances(void *cvode_mem, int itolS,
+                           realtype reltolS, void *abstolS)
+{
+  CVodeMem cv_mem;
+  booleantype neg_abstol;
+  realtype *atolSS;
+  N_Vector *atolSV;
+  int is, Ns;
+
+  atolSS = NULL;
+  atolSV = NULL;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeSetSensTolerances", MSGCV_NO_MEM);    
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  /* Was sensitivity initialized? */
+
+  if (cv_mem->cv_sensMallocDone == FALSE) {
+    CVProcessError(cv_mem, CV_NO_SENS, "CVODES", "CVodeSetSensTolerances", MSGCV_NO_SENSI);
+    return(CV_NO_SENS);
+  } 
+
+  /* Check inputs */
+
+  Ns = cv_mem->cv_Ns;
+
+  if ((itolS != CV_SS) && (itolS != CV_SV) && (itolS != CV_EE)) {
+    CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSetSensTolerances", MSGCV_BAD_ITOLS);
+    return(CV_ILL_INPUT);
+  }
+
+  if (itolS != CV_EE) {
+
+    /* Test user-supplied tolerances */
+    
+    if (reltolS < ZERO) {
+      CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSetSensTolerances", MSGCV_BAD_RELTOLS);
+      return(CV_ILL_INPUT);
+    }
+
+    if (abstolS == NULL) {
+      CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSetSensTolerances", MSGCV_NULL_ABSTOLS);
+      return(CV_ILL_INPUT);
+    }
+
+    neg_abstol = FALSE;
+
+    if (itolS == CV_SS) {
+      atolSS = (realtype *) abstolS;
+      for (is=0; is<Ns; is++)
+        if (atolSS[is] < ZERO) {neg_abstol = TRUE; break;}
+    } else {
+      atolSV = (N_Vector *) abstolS;
+      for (is=0; is<Ns; is++) 
+        if (N_VMin(atolSV[is]) < ZERO) {neg_abstol = TRUE; break;}
+    }
+
+    if (neg_abstol) {
+      CVProcessError(cv_mem, CV_ILL_INPUT, "CVODES", "CVodeSetSensTolerances", MSGCV_BAD_ABSTOLS);
+      return(CV_ILL_INPUT);
+    }
+    
+  }
+
+  /* See if we should release some memory */
+
+  if ( (itolS != CV_SV) && (cv_mem->cv_VabstolSMallocDone) ) {
+    N_VDestroyVectorArray(cv_mem->cv_VabstolS, Ns);
+    lrw -= Ns*lrw1;
+    liw -= Ns*liw1;
+    cv_mem->cv_VabstolSMallocDone = FALSE;
+  }
+
+  if ( (itolS != CV_SS) && (cv_mem->cv_SabstolSMallocDone) ) {
+    free(cv_mem->cv_SabstolS); cv_mem->cv_SabstolS = NULL;
+    lrw -= Ns;
+    cv_mem->cv_SabstolSMallocDone = FALSE;
+  }
+
+  /* If tolerances will be estimated, return now */
+
+  if (itolS == CV_EE) return(CV_SUCCESS);
+
+  /* See if we need to allocate some memory */
+
+  if ( (itolS == CV_SV) && !(cv_mem->cv_VabstolSMallocDone) ) {
+    cv_mem->cv_VabstolS = NULL;
+    cv_mem->cv_VabstolS = N_VCloneVectorArray(Ns, cv_mem->cv_tempv);
+    lrw += Ns*lrw1;
+    liw += Ns*liw1;
+    cv_mem->cv_VabstolSMallocDone = TRUE;
+  }
+
+  if ( (itolS == CV_SS) && !(cv_mem->cv_SabstolSMallocDone) ) {
+    cv_mem->cv_SabstolS = NULL;
+    cv_mem->cv_SabstolS = (realtype *)malloc(Ns*sizeof(realtype));
+    lrw += Ns;
+    cv_mem->cv_SabstolSMallocDone = TRUE;
+  }
+
+  /* Copy tolerances into memory */
+
+  cv_mem->cv_itolS   = itolS;
+  cv_mem->cv_reltolS = reltolS;
+
+  if (itolS == CV_SS)
+    for (is=0; is<Ns; is++)
+      cv_mem->cv_SabstolS[is] = atolSS[is];
+  else
+    for (is=0; is<Ns; is++)    
+      N_VScale(ONE, atolSV[is], cv_mem->cv_VabstolS[is]);
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * =================================================================
+ * CVODES optional output functions
+ * =================================================================
+ */
+
+/* 
+ * Readability constants
+ */
+
+#define nst            (cv_mem->cv_nst)
+#define nfe            (cv_mem->cv_nfe)
+#define ncfn           (cv_mem->cv_ncfn)
+#define netf           (cv_mem->cv_netf)
+#define nni            (cv_mem->cv_nni)
+#define nsetups        (cv_mem->cv_nsetups)
+#define qu             (cv_mem->cv_qu)
+#define next_q         (cv_mem->cv_next_q)
+#define ewt            (cv_mem->cv_ewt)  
+#define hu             (cv_mem->cv_hu)
+#define next_h         (cv_mem->cv_next_h)
+#define h0u            (cv_mem->cv_h0u)
+#define tolsf          (cv_mem->cv_tolsf)  
+#define acor           (cv_mem->cv_acor)
+#define lrw            (cv_mem->cv_lrw)
+#define liw            (cv_mem->cv_liw)
+#define nge            (cv_mem->cv_nge)
+#define iroots         (cv_mem->cv_iroots)
+#define nor            (cv_mem->cv_nor)
+#define sldeton        (cv_mem->cv_sldeton)
+#define tn             (cv_mem->cv_tn)
+#define efun           (cv_mem->cv_efun)
+#define e_data         (cv_mem->cv_e_data) 
+
+/*
+ * CVodeGetNumSteps
+ *
+ * Returns the current number of integration steps
+ */
+
+int CVodeGetNumSteps(void *cvode_mem, long int *nsteps)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetNumSteps", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  *nsteps = nst;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeGetNumRhsEvals
+ *
+ * Returns the current number of calls to f
+ */
+
+int CVodeGetNumRhsEvals(void *cvode_mem, long int *nfevals)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetNumRhsEvals", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  *nfevals = nfe;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeGetNumLinSolvSetups
+ *
+ * Returns the current number of calls to the linear solver setup routine
+ */
+
+int CVodeGetNumLinSolvSetups(void *cvode_mem, long int *nlinsetups)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetNumLinSolvSetups", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  *nlinsetups = nsetups;
+
+  return(CV_SUCCESS);
+}
+
+/*
+ * CVodeGetNumErrTestFails
+ *
+ * Returns the current number of error test failures
+ */
+
+int CVodeGetNumErrTestFails(void *cvode_mem, long int *netfails)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetNumErrTestFails", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  *netfails = netf;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeGetLastOrder
+ *
+ * Returns the order on the last succesful step
+ */
+
+int CVodeGetLastOrder(void *cvode_mem, int *qlast)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetLastOrder", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  *qlast = qu;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeGetCurrentOrder
+ *
+ * Returns the order to be attempted on the next step
+ */
+
+int CVodeGetCurrentOrder(void *cvode_mem, int *qcur)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetCurrentOrder", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  *qcur = next_q;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeGetNumStabLimOrderReds
+ *
+ * Returns the number of order reductions triggered by the stability
+ * limit detection algorithm
+ */
+
+int CVodeGetNumStabLimOrderReds(void *cvode_mem, long int *nslred)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetNumStabLimOrderReds", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (sldeton==FALSE)
+    *nslred = 0;
+  else
+    *nslred = nor;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeGetActualInitStep
+ *
+ * Returns the step size used on the first step
+ */
+
+int CVodeGetActualInitStep(void *cvode_mem, realtype *hinused)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetActualInitStep", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  *hinused = h0u;
+
+  return(CV_SUCCESS);
+}
+
+/*
+ * CVodeGetLastStep
+ *
+ * Returns the step size used on the last successful step
+ */
+
+int CVodeGetLastStep(void *cvode_mem, realtype *hlast)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetLastStep", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  *hlast = hu;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeGetCurrentStep
+ *
+ * Returns the step size to be attempted on the next step
+ */
+
+int CVodeGetCurrentStep(void *cvode_mem, realtype *hcur)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetCurrentStep", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+  
+  *hcur = next_h;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeGetCurrentTime
+ *
+ * Returns the current value of the independent variable
+ */
+
+int CVodeGetCurrentTime(void *cvode_mem, realtype *tcur)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetCurrentTime", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  *tcur = tn;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeGetTolScaleFactor
+ *
+ * Returns a suggested factor for scaling tolerances
+ */
+
+int CVodeGetTolScaleFactor(void *cvode_mem, realtype *tolsfact)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetTolScaleFactor", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  *tolsfact = tolsf;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeGetErrWeights
+ *
+ * This routine returns the current weight vector.
+ */
+
+int CVodeGetErrWeights(void *cvode_mem, N_Vector eweight)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetErrWeights", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  N_VScale(ONE, ewt, eweight);
+
+  return(CV_SUCCESS);
+}
+
+/*
+ * CVodeGetEstLocalErrors
+ *
+ * Returns an estimate of the local error
+ */
+
+int CVodeGetEstLocalErrors(void *cvode_mem, N_Vector ele)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetEstLocalErrors", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  N_VScale(ONE, acor, ele);
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeGetWorkSpace
+ *
+ * Returns integrator work space requirements
+ */
+
+int CVodeGetWorkSpace(void *cvode_mem, long int *lenrw, long int *leniw)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetWorkSpace", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  *leniw = liw;
+  *lenrw = lrw;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeGetIntegratorStats
+ *
+ * Returns integrator statistics
+ */
+
+int CVodeGetIntegratorStats(void *cvode_mem, long int *nsteps, long int *nfevals, 
+                            long int *nlinsetups, long int *netfails, int *qlast, 
+                            int *qcur, realtype *hinused, realtype *hlast, 
+                            realtype *hcur, realtype *tcur)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetIntegratorStats", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  *nsteps = nst;
+  *nfevals = nfe;
+  *nlinsetups = nsetups;
+  *netfails = netf;
+  *qlast = qu;
+  *qcur = next_q;
+  *hinused = h0u;
+  *hlast = hu;
+  *hcur = next_h;
+  *tcur = tn;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeGetNumGEvals
+ *
+ * Returns the current number of calls to g (for rootfinding)
+ */
+
+int CVodeGetNumGEvals(void *cvode_mem, long int *ngevals)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetNumGEvals", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  *ngevals = nge;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeGetRootInfo
+ *
+ * Returns pointer to array rootsfound showing roots found
+ */
+
+int CVodeGetRootInfo(void *cvode_mem, int *rootsfound)
+{
+  CVodeMem cv_mem;
+  int i, nrt;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetRootInfo", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  nrt = cv_mem->cv_nrtfn;
+
+  for (i=0; i<nrt; i++) rootsfound[i] = iroots[i];
+
+  return(CV_SUCCESS);
+}
+
+
+/* 
+ * CVodeGetNumNonlinSolvIters
+ *
+ * Returns the current number of iterations in the nonlinear solver
+ */
+
+int CVodeGetNumNonlinSolvIters(void *cvode_mem, long int *nniters)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetNumNonlinSolvIters", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  *nniters = nni;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeGetNumNonlinSolvConvFails
+ *
+ * Returns the current number of convergence failures in the
+ * nonlinear solver
+ */
+
+int CVodeGetNumNonlinSolvConvFails(void *cvode_mem, long int *nncfails)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetNumNonlinSolvConvFails", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  *nncfails = ncfn;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * CVodeGetNonlinSolvStats
+ *
+ * Returns nonlinear solver statistics
+ */
+
+int CVodeGetNonlinSolvStats(void *cvode_mem, long int *nniters, 
+                            long int *nncfails)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetNonlinSolvStats", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  *nniters = nni;
+  *nncfails = ncfn;
+
+  return(CV_SUCCESS);
+}
+
+
+/* 
+ * =================================================================
+ * Quadrature optional output functions
+ * =================================================================
+ */
+
+/* 
+ * Readability constants
+ */
+
+#define quadr          (cv_mem->cv_quadr)
+#define nfQe           (cv_mem->cv_nfQe)
+#define netfQ          (cv_mem->cv_netfQ)
+#define ewtQ           (cv_mem->cv_ewtQ)
+#define errconQ        (cv_mem->cv_errconQ)
+
+/*-----------------------------------------------------------------*/
+
+int CVodeGetQuadNumRhsEvals(void *cvode_mem, long int *nfQevals)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetQuadNumRhsEvals", MSGCV_NO_MEM);    
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (quadr==FALSE) {
+    CVProcessError(cv_mem, CV_NO_QUAD, "CVODES", "CVodeGetQuadNumRhsEvals", MSGCV_NO_QUAD); 
+    return(CV_NO_QUAD);
+  }
+
+  *nfQevals = nfQe;
+
+  return(CV_SUCCESS);
+}
+
+/*-----------------------------------------------------------------*/
+
+int CVodeGetQuadNumErrTestFails(void *cvode_mem, long int *nQetfails)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetQuadNumErrTestFails", MSGCV_NO_MEM);    
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (quadr==FALSE) {
+    CVProcessError(cv_mem, CV_NO_QUAD, "CVODES", "CVodeGetQuadNumErrTestFails", MSGCV_NO_QUAD); 
+    return(CV_NO_QUAD);
+  }
+
+  *nQetfails = netfQ;
+
+  return(CV_SUCCESS);
+}
+
+/*-----------------------------------------------------------------*/
+
+int CVodeGetQuadErrWeights(void *cvode_mem, N_Vector eQweight)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetQuadErrWeights", MSGCV_NO_MEM); 
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (quadr==FALSE) {
+    CVProcessError(cv_mem, CV_NO_QUAD, "CVODES", "CVodeGetQuadErrWeights", MSGCV_NO_QUAD); 
+    return(CV_NO_QUAD);
+  }
+
+  if(errconQ) N_VScale(ONE, ewtQ, eQweight);
+
+  return(CV_SUCCESS);
+}
+
+/*-----------------------------------------------------------------*/
+
+int CVodeGetQuadStats(void *cvode_mem, long int *nfQevals, long int *nQetfails)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetQuadStats", MSGCV_NO_MEM);    
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (quadr==FALSE) {
+    CVProcessError(cv_mem, CV_NO_QUAD, "CVODES", "CVodeGetQuadStats", MSGCV_NO_QUAD); 
+    return(CV_NO_QUAD);
+  }
+
+  *nfQevals = nfQe;
+  *nQetfails = netfQ;
+
+  return(CV_SUCCESS);
+}
+
+/* 
+ * =================================================================
+ * FSA optional output functions
+ * =================================================================
+ */
+
+/* 
+ * Readability constants
+ */
+
+#define sensi          (cv_mem->cv_sensi)
+#define ism            (cv_mem->cv_ism)
+#define ewtS           (cv_mem->cv_ewtS)
+#define nfSe           (cv_mem->cv_nfSe)
+#define nfeS           (cv_mem->cv_nfeS)
+#define nniS           (cv_mem->cv_nniS)
+#define ncfnS          (cv_mem->cv_ncfnS)
+#define netfS          (cv_mem->cv_netfS)
+#define nsetupsS       (cv_mem->cv_nsetupsS)
+#define nniS1          (cv_mem->cv_nniS1)
+#define ncfnS1         (cv_mem->cv_ncfnS1)
+#define ncfS1          (cv_mem->cv_ncfS1)
+
+/*-----------------------------------------------------------------*/
+
+int CVodeGetNumSensRhsEvals(void *cvode_mem, long int *nfSevals)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetNumSensRhsEvals", MSGCV_NO_MEM);    
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (sensi==FALSE) {
+    CVProcessError(cv_mem, CV_NO_SENS, "CVODES", "CVodeGetNumSensRhsEvals", MSGCV_NO_SENSI);
+    return(CV_NO_SENS);
+  }
+
+  *nfSevals = nfSe;
+
+  return(CV_SUCCESS);
+}
+
+/*-----------------------------------------------------------------*/
+
+int CVodeGetNumRhsEvalsSens(void *cvode_mem, long int *nfevalsS)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetNumRhsEvalsSens", MSGCV_NO_MEM);    
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (sensi==FALSE) {
+    CVProcessError(cv_mem, CV_NO_SENS, "CVODES", "CVodeGetNumRhsEvalsSens", MSGCV_NO_SENSI);
+    return(CV_NO_SENS);
+  }
+
+  *nfevalsS = nfeS;
+
+  return(CV_SUCCESS);
+}
+
+/*-----------------------------------------------------------------*/
+
+int CVodeGetNumSensErrTestFails(void *cvode_mem, long int *nSetfails)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetNumSensErrTestFails", MSGCV_NO_MEM);    
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (sensi==FALSE) {
+    CVProcessError(cv_mem, CV_NO_SENS, "CVODES", "CVodeGetNumSensErrTestFails", MSGCV_NO_SENSI);
+    return(CV_NO_SENS);
+  }
+
+  *nSetfails = netfS;
+
+  return(CV_SUCCESS);
+}
+
+/*-----------------------------------------------------------------*/
+
+int CVodeGetNumSensLinSolvSetups(void *cvode_mem, long int *nlinsetupsS)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetNumSensLinSolvSetups", MSGCV_NO_MEM);    
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (sensi==FALSE) {
+    CVProcessError(cv_mem, CV_NO_SENS, "CVODES", "CVodeGetNumSensLinSolvSetups", MSGCV_NO_SENSI);
+    return(CV_NO_SENS);
+  }
+
+  *nlinsetupsS = nsetupsS;
+
+  return(CV_SUCCESS);
+}
+
+/*-----------------------------------------------------------------*/
+
+int CVodeGetSensErrWeights(void *cvode_mem, N_Vector_S eSweight)
+{
+  CVodeMem cv_mem;
+  int is, Ns;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetSensErrWeights", MSGCV_NO_MEM);    
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (sensi==FALSE) {
+    CVProcessError(cv_mem, CV_NO_SENS, "CVODES", "CVodeGetSensErrWeights", MSGCV_NO_SENSI);
+    return(CV_NO_SENS);
+  }
+
+  Ns = cv_mem->cv_Ns;
+
+  for (is=0; is<Ns; is++)
+    N_VScale(ONE, ewtS[is], eSweight[is]);
+
+  return(CV_SUCCESS);
+}
+
+/*-----------------------------------------------------------------*/
+
+int CVodeGetSensStats(void *cvode_mem, long int *nfSevals, long int *nfevalsS, 
+                      long int *nSetfails, long int *nlinsetupsS)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetSensStats", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (sensi==FALSE) {
+    CVProcessError(cv_mem, CV_NO_SENS, "CVODES", "CVodeGetSensStats", MSGCV_NO_SENSI);
+    return(CV_NO_SENS);
+  }
+
+  *nfSevals = nfSe;
+  *nfevalsS = nfeS;
+  *nSetfails = netfS;
+  *nlinsetupsS = nsetupsS;
+
+  return(CV_SUCCESS);
+}
+
+/*-----------------------------------------------------------------*/
+
+int CVodeGetNumSensNonlinSolvIters(void *cvode_mem, long int *nSniters)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetNumSensNonlinSolvIters", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (sensi==FALSE) {
+    CVProcessError(cv_mem, CV_NO_SENS, "CVODES", "CVodeGetNumSensNonlinSolvIters", MSGCV_NO_SENSI);
+    return(CV_NO_SENS);
+  }
+
+  *nSniters = nniS;
+
+  return(CV_SUCCESS);
+}
+
+/*-----------------------------------------------------------------*/
+
+int CVodeGetNumSensNonlinSolvConvFails(void *cvode_mem, long int *nSncfails)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetNumSensNonlinSolvConvFails", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (sensi==FALSE) {
+    CVProcessError(cv_mem, CV_NO_SENS, "CVODES", "CVodeGetNumSensNonlinSolvConvFails", MSGCV_NO_SENSI);
+    return(CV_NO_SENS);
+  }
+
+  *nSncfails = ncfnS;
+
+  return(CV_SUCCESS);
+}
+
+/*-----------------------------------------------------------------*/
+
+int CVodeGetNumStgrSensNonlinSolvIters(void *cvode_mem, long int *nSTGR1niters)
+{
+  CVodeMem cv_mem;
+  int is, Ns;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetNumStgrSensNonlinSolvIters", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  Ns = cv_mem->cv_Ns;
+
+  if (sensi==FALSE) {
+    CVProcessError(cv_mem, CV_NO_SENS, "CVODES", "CVodeGetNumStgrSensNonlinSolvIters", MSGCV_NO_SENSI);
+    return(CV_NO_SENS);
+  }
+
+  if(ism==CV_STAGGERED1) 
+    for(is=0; is<Ns; is++) nSTGR1niters[is] = nniS1[is];
+
+  return(CV_SUCCESS);
+}
+
+/*-----------------------------------------------------------------*/
+
+int CVodeGetNumStgrSensNonlinSolvConvFails(void *cvode_mem, long int *nSTGR1ncfails)
+{
+  CVodeMem cv_mem;
+  int is, Ns;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetNumStgrSensNonlinSolvConvFails", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  Ns = cv_mem->cv_Ns;
+
+  if (sensi==FALSE) {
+    CVProcessError(cv_mem, CV_NO_SENS, "CVODES", "CVodeGetNumStgrSensNonlinSolvConvFails", MSGCV_NO_SENSI);
+    return(CV_NO_SENS);
+  }
+
+  if(ism==CV_STAGGERED1) 
+    for(is=0; is<Ns; is++) nSTGR1ncfails[is] = ncfnS1[is];
+
+  return(CV_SUCCESS);
+}
+
+/*-----------------------------------------------------------------*/
+
+int CVodeGetSensNonlinSolvStats(void *cvode_mem, long int *nSniters, 
+                                long int *nSncfails)
+{
+  CVodeMem cv_mem;
+
+  if (cvode_mem==NULL) {
+    CVProcessError(NULL, CV_MEM_NULL, "CVODES", "CVodeGetSensNonlinSolvstats", MSGCV_NO_MEM);
+    return(CV_MEM_NULL);
+  }
+
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (sensi==FALSE) {
+    CVProcessError(cv_mem, CV_NO_SENS, "CVODES", "CVodeGetSensNonlinSolvStats", MSGCV_NO_SENSI);
+    return(CV_NO_SENS);
+  }
+
+  *nSniters = nniS;
+  *nSncfails = ncfnS;
+
+  return(CV_SUCCESS);
+}
+
+/*-----------------------------------------------------------------*/
+
+char *CVodeGetReturnFlagName(int flag)
+{
+  char *name;
+
+  name = (char *)malloc(24*sizeof(char));
+
+  switch(flag) {
+  case CV_SUCCESS:
+    sprintf(name,"CV_SUCCESS");
+    break;
+  case CV_TSTOP_RETURN:
+    sprintf(name,"CV_TSTOP_RETURN");
+    break;
+  case CV_ROOT_RETURN:
+    sprintf(name,"CV_ROOT_RETURN");
+    break;
+  case CV_TOO_MUCH_WORK:
+    sprintf(name,"CV_TOO_MUCH_WORK");
+    break;
+  case CV_TOO_MUCH_ACC:
+    sprintf(name,"CV_TOO_MUCH_ACC");
+    break;
+  case CV_ERR_FAILURE:
+    sprintf(name,"CV_ERR_FAILURE");
+    break;
+  case CV_CONV_FAILURE:
+    sprintf(name,"CV_CONV_FAILURE");
+    break;
+  case CV_LINIT_FAIL:
+    sprintf(name,"CV_LINIT_FAIL");
+    break;
+  case CV_LSETUP_FAIL:
+    sprintf(name,"CV_LSETUP_FAIL");
+    break;
+  case CV_LSOLVE_FAIL:
+    sprintf(name,"CV_LSOLVE_FAIL");
+    break;
+  case CV_RHSFUNC_FAIL:
+    sprintf(name,"CV_RHSFUNC_FAIL");
+    break;
+  case CV_FIRST_RHSFUNC_ERR:
+    sprintf(name,"CV_FIRST_RHSFUNC_ERR");
+    break;
+  case CV_REPTD_RHSFUNC_ERR:
+    sprintf(name,"CV_REPTD_RHSFUNC_ERR");
+    break;
+  case CV_UNREC_RHSFUNC_ERR:
+    sprintf(name,"CV_UNREC_RHSFUNC_ERR");
+    break;
+  case CV_RTFUNC_FAIL:
+    sprintf(name,"CV_RTFUNC_FAIL");
+    break;
+  case CV_MEM_FAIL:
+    sprintf(name,"CV_MEM_FAIL");
+    break;
+  case CV_MEM_NULL:
+    sprintf(name,"CV_MEM_NULL");
+    break;
+  case CV_ILL_INPUT:
+    sprintf(name,"CV_ILL_INPUT");
+    break;
+  case CV_NO_MALLOC:
+    sprintf(name,"CV_NO_MALLOC");
+    break;
+  case CV_BAD_K:
+    sprintf(name,"CV_BAD_K");
+    break;
+  case CV_BAD_T:
+    sprintf(name,"CV_BAD_T");
+    break;
+  case CV_BAD_DKY:
+    sprintf(name,"CV_BAD_DKY");
+    break;
+  case CV_NO_QUAD:
+    sprintf(name,"CV_NO_QUAD");
+    break;
+  case CV_QRHSFUNC_FAIL:
+    sprintf(name,"CV_QRHSFUNC_FAIL");
+    break;
+  case CV_FIRST_QRHSFUNC_ERR:
+    sprintf(name,"CV_FIRST_QRHSFUNC_ERR");
+    break;
+  case CV_REPTD_QRHSFUNC_ERR:
+    sprintf(name,"CV_REPTD_QRHSFUNC_ERR");
+    break;
+  case CV_UNREC_QRHSFUNC_ERR:
+    sprintf(name,"CV_UNREC_QRHSFUNC_ERR");
+    break;
+  case CV_BAD_IS:
+    sprintf(name,"CV_BAD_IS");
+    break;
+  case CV_NO_SENS:
+    sprintf(name,"CV_NO_SENS");
+    break;
+  case CV_SRHSFUNC_FAIL:
+    sprintf(name,"CV_SRHSFUNC_FAIL");
+    break;
+  case CV_FIRST_SRHSFUNC_ERR:
+    sprintf(name,"CV_FIRST_SRHSFUNC_ERR");
+    break;
+  case CV_REPTD_SRHSFUNC_ERR:
+    sprintf(name,"CV_REPTD_SRHSFUNC_ERR");
+    break;
+  case CV_UNREC_SRHSFUNC_ERR:
+    sprintf(name,"CV_UNREC_SRHSFUNC_ERR");
+    break;
+  case CV_TOO_CLOSE:
+    sprintf(name,"CV_TOO_CLOSE");
+    break;    
+  default:
+    sprintf(name,"NONE");
+  }
+
+  return(name);
+}
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_spbcgs.c b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_spbcgs.c
new file mode 100644
index 0000000000000000000000000000000000000000..ba8142b087210e05e3815a828c697fe5ded75d70
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_spbcgs.c
@@ -0,0 +1,550 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Aaron Collier and Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2005, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the implementation file for the CVSPBCG linear solver.
+ * -----------------------------------------------------------------
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <cvodes/cvodes_spbcgs.h>
+#include "cvodes_spils_impl.h"
+#include "cvodes_impl.h"
+
+#include <sundials/sundials_spbcgs.h>
+#include <sundials/sundials_math.h>
+
+/* Constants */
+
+#define ZERO RCONST(0.0)
+#define ONE  RCONST(1.0)
+
+/* CVSPBCG linit, lsetup, lsolve, and lfree routines */
+
+static int CVSpbcgInit(CVodeMem cv_mem);
+
+static int CVSpbcgSetup(CVodeMem cv_mem, int convfail, N_Vector ypred,
+                        N_Vector fpred, booleantype *jcurPtr, N_Vector vtemp1,
+                        N_Vector vtemp2, N_Vector vtemp3);
+
+static int CVSpbcgSolve(CVodeMem cv_mem, N_Vector b, N_Vector weight,
+                        N_Vector ynow, N_Vector fnow);
+
+static void CVSpbcgFree(CVodeMem cv_mem);
+
+/* CVSPBCG lfreeB function */
+
+static void CVSpbcgFreeB(CVadjMem ca_mem);
+
+/* 
+ * ================================================================
+ *
+ *                   PART I - forward problems
+ *
+ * ================================================================
+ */
+
+/* Readability Replacements */
+
+#define tq           (cv_mem->cv_tq)
+#define nst          (cv_mem->cv_nst)
+#define tn           (cv_mem->cv_tn)
+#define gamma        (cv_mem->cv_gamma)
+#define gammap       (cv_mem->cv_gammap)
+#define f            (cv_mem->cv_f)
+#define f_data       (cv_mem->cv_f_data)
+#define ewt          (cv_mem->cv_ewt)
+#define errfp        (cv_mem->cv_errfp)
+#define mnewt        (cv_mem->cv_mnewt)
+#define linit        (cv_mem->cv_linit)
+#define lsetup       (cv_mem->cv_lsetup)
+#define lsolve       (cv_mem->cv_lsolve)
+#define lfree        (cv_mem->cv_lfree)
+#define lmem         (cv_mem->cv_lmem)
+#define vec_tmpl     (cv_mem->cv_tempv)
+#define setupNonNull (cv_mem->cv_setupNonNull)
+
+#define sqrtN     (cvspils_mem->s_sqrtN)   
+#define ytemp     (cvspils_mem->s_ytemp)
+#define x         (cvspils_mem->s_x)
+#define ycur      (cvspils_mem->s_ycur)
+#define fcur      (cvspils_mem->s_fcur)
+#define delta     (cvspils_mem->s_delta)
+#define deltar    (cvspils_mem->s_deltar)
+#define npe       (cvspils_mem->s_npe)
+#define nli       (cvspils_mem->s_nli)
+#define nps       (cvspils_mem->s_nps)
+#define ncfl      (cvspils_mem->s_ncfl)
+#define nstlpre   (cvspils_mem->s_nstlpre)
+#define njtimes   (cvspils_mem->s_njtimes)
+#define nfes      (cvspils_mem->s_nfes)
+#define spils_mem (cvspils_mem->s_spils_mem)
+#define last_flag (cvspils_mem->s_last_flag)
+
+/*
+ * -----------------------------------------------------------------
+ * Function : CVSpbcg
+ * -----------------------------------------------------------------
+ * This routine initializes the memory record and sets various function
+ * fields specific to the Spbcg linear solver module. CVSpbcg first
+ * calls the existing lfree routine if this is not NULL. It then sets
+ * the cv_linit, cv_lsetup, cv_lsolve, cv_lfree fields in (*cvode_mem)
+ * to be CVSpbcgInit, CVSpbcgSetup, CVSpbcgSolve, and CVSpbcgFree,
+ * respectively. It allocates memory for a structure of type
+ * CVSpilsMemRec and sets the cv_lmem field in (*cvode_mem) to the
+ * address of this structure. It sets setupNonNull in (*cvode_mem),
+ * and sets the following fields in the CVSpilsMemRec structure:
+ *
+ *   s_pretype   = pretype
+ *   s_maxl      = CVSPILS_MAXL  if maxl <= 0
+ *               = maxl          if maxl >  0
+ *   s_delt      = CVSPILS_DELT
+ *   s_P_data    = NULL
+ *   s_pset      = NULL
+ *   s_psolve    = NULL
+ *   s_jtimes    = CVSpilsDQJtimes
+ *   s_j_data    = cvode_mem
+ *   s_last_flag = CVSPILS_SUCCESS
+ *
+ * Finally, CVSpbcg allocates memory for ytemp and x, and calls
+ * SpbcgMalloc to allocate memory for the Spbcg solver.
+ * -----------------------------------------------------------------
+ */
+
+int CVSpbcg(void *cvode_mem, int pretype, int maxl)
+{
+  CVodeMem cv_mem;
+  CVSpilsMem cvspils_mem;
+  SpbcgMem spbcg_mem;
+  int mxl;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVSPILS_MEM_NULL, "CVSPBCG", "CVSpbcg", MSGS_CVMEM_NULL);
+    return(CVSPILS_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  /* Check if N_VDotProd is present */
+  if (vec_tmpl->ops->nvdotprod == NULL) {
+    CVProcessError(cv_mem, CVSPILS_ILL_INPUT, "CVSPBCG", "CVSpbcg", MSGS_BAD_NVECTOR);
+    return(CVSPILS_ILL_INPUT);
+  }
+
+  if (lfree != NULL) lfree(cv_mem);
+
+  /* Set four main function fields in cv_mem */
+  linit  = CVSpbcgInit;
+  lsetup = CVSpbcgSetup;
+  lsolve = CVSpbcgSolve;
+  lfree  = CVSpbcgFree;
+
+  /* Get memory for CVSpilsMemRec */
+  cvspils_mem = NULL;
+  cvspils_mem = (CVSpilsMem) malloc(sizeof(CVSpilsMemRec));
+  if (cvspils_mem == NULL) {
+    CVProcessError(cv_mem, CVSPILS_MEM_FAIL, "CVSPBCG", "CVSpbcg", MSGS_MEM_FAIL);
+    return(CVSPILS_MEM_FAIL);
+  }
+
+  /* Set ILS type */
+  cvspils_mem->s_type = SPILS_SPBCG;
+
+  /* Set Spbcg parameters that have been passed in call sequence */
+  cvspils_mem->s_pretype = pretype;
+  mxl = cvspils_mem->s_maxl = (maxl <= 0) ? CVSPILS_MAXL : maxl;
+
+  /* Set default values for the rest of the Spbcg parameters */
+  cvspils_mem->s_delt      = CVSPILS_DELT;
+  cvspils_mem->s_P_data    = NULL;
+  cvspils_mem->s_pset      = NULL;
+  cvspils_mem->s_psolve    = NULL;
+  cvspils_mem->s_jtimes    = CVSpilsDQJtimes;
+  cvspils_mem->s_j_data    = cvode_mem;
+  cvspils_mem->s_last_flag = CVSPILS_SUCCESS;
+
+  setupNonNull = FALSE;
+
+  /* Check for legal pretype */ 
+  if ((pretype != PREC_NONE) && (pretype != PREC_LEFT) &&
+      (pretype != PREC_RIGHT) && (pretype != PREC_BOTH)) {
+    CVProcessError(cv_mem, CVSPILS_ILL_INPUT, "CVSPBCG", "CVSpbcg", MSGS_BAD_PRETYPE);
+    return(CVSPILS_ILL_INPUT);
+  }
+
+  /* Allocate memory for ytemp and x */
+  ytemp = NULL;
+  ytemp = N_VClone(vec_tmpl);
+  if (ytemp == NULL) {
+    CVProcessError(cv_mem, CVSPILS_MEM_FAIL, "CVSPBCG", "CVSpbcg", MSGS_MEM_FAIL);
+    free(cvspils_mem); cvspils_mem = NULL;
+    return(CVSPILS_MEM_FAIL);
+  }
+  x = NULL;
+  x = N_VClone(vec_tmpl);
+  if (x == NULL) {
+    CVProcessError(cv_mem, CVSPILS_MEM_FAIL, "CVSPBCG", "CVSpbcg", MSGS_MEM_FAIL);
+    N_VDestroy(ytemp);
+    free(cvspils_mem); cvspils_mem = NULL;
+    return(CVSPILS_MEM_FAIL);
+  }
+
+  /* Compute sqrtN from a dot product */
+  N_VConst(ONE, ytemp);
+  sqrtN = RSqrt(N_VDotProd(ytemp, ytemp));
+
+  /* Call SpbcgMalloc to allocate workspace for Spbcg */
+  spbcg_mem = NULL;
+  spbcg_mem = SpbcgMalloc(mxl, vec_tmpl);
+  if (spbcg_mem == NULL) {
+    CVProcessError(cv_mem, CVSPILS_MEM_FAIL, "CVSPBCG", "CVSpbcg", MSGS_MEM_FAIL);
+    N_VDestroy(ytemp);
+    N_VDestroy(x);
+    free(cvspils_mem); cvspils_mem = NULL;
+    return(CVSPILS_MEM_FAIL);
+  }
+  
+  /* Attach SPBCG memory to spils memory structure */
+  spils_mem = (void *) spbcg_mem;
+
+  /* Attach linear solver memory to integrator memory */
+  lmem = cvspils_mem;
+
+  return(CVSPILS_SUCCESS);
+}
+
+
+
+/* Additional readability replacements */
+
+#define pretype (cvspils_mem->s_pretype)
+#define delt    (cvspils_mem->s_delt)
+#define maxl    (cvspils_mem->s_maxl)
+#define psolve  (cvspils_mem->s_psolve)
+#define pset    (cvspils_mem->s_pset)
+#define P_data  (cvspils_mem->s_P_data)
+#define jtimes  (cvspils_mem->s_jtimes)
+#define j_data  (cvspils_mem->s_j_data)
+
+/*
+ * -----------------------------------------------------------------
+ * Function : CVSpbcgInit
+ * -----------------------------------------------------------------
+ * This routine does remaining initializations specific to the Spbcg
+ * linear solver.
+ * -----------------------------------------------------------------
+ */
+
+static int CVSpbcgInit(CVodeMem cv_mem)
+{
+  CVSpilsMem cvspils_mem;
+  SpbcgMem spbcg_mem;
+
+  cvspils_mem = (CVSpilsMem) lmem;
+  spbcg_mem = (SpbcgMem) spils_mem;
+
+
+  /* Initialize counters */
+  npe = nli = nps = ncfl = nstlpre = 0;
+  njtimes = nfes = 0;
+
+  /* Check for legal combination pretype - psolve */
+  if ((pretype != PREC_NONE) && (psolve == NULL)) {
+    CVProcessError(cv_mem, -1, "CVSPBCG", "CVSpbcgInit", MSGS_PSOLVE_REQ);
+    last_flag = CVSPILS_ILL_INPUT;
+    return(-1);
+  }
+
+  /* Set setupNonNull = TRUE iff there is preconditioning
+     (pretype != PREC_NONE)  and there is a preconditioning
+     setup phase (pset != NULL) */
+  setupNonNull = (pretype != PREC_NONE) && (pset != NULL);
+
+  /* If jtimes is NULL at this time, set it to DQ */
+  if (jtimes == NULL) {
+    jtimes = CVSpilsDQJtimes;
+    j_data = cv_mem;
+  }
+
+  /*  Set maxl in the SPBCG memory in case it was changed by the user */
+  spbcg_mem->l_max  = maxl;
+
+  last_flag = CVSPILS_SUCCESS;
+  return(0);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * Function : CVSpbcgSetup
+ * -----------------------------------------------------------------
+ * This routine does the setup operations for the Spbcg linear solver.
+ * It makes a decision as to whether or not to signal for reevaluation
+ * of Jacobian data in the pset routine, based on various state
+ * variables, then it calls pset. If we signal for reevaluation,
+ * then we reset jcur = *jcurPtr to TRUE, regardless of the pset output.
+ * In any case, if jcur == TRUE, we increment npe and save nst in nstlpre.
+ * -----------------------------------------------------------------
+ */
+
+static int CVSpbcgSetup(CVodeMem cv_mem, int convfail, N_Vector ypred,
+                        N_Vector fpred, booleantype *jcurPtr, N_Vector vtemp1,
+                        N_Vector vtemp2, N_Vector vtemp3)
+{
+  booleantype jbad, jok;
+  realtype dgamma;
+  int  retval;
+  CVSpilsMem cvspils_mem;
+
+  cvspils_mem = (CVSpilsMem) lmem;
+
+  /* Use nst, gamma/gammap, and convfail to set J eval. flag jok */
+  dgamma = ABS((gamma/gammap) - ONE);
+  jbad = (nst == 0) || (nst > nstlpre + CVSPILS_MSBPRE) ||
+      ((convfail == CV_FAIL_BAD_J) && (dgamma < CVSPILS_DGMAX)) ||
+      (convfail == CV_FAIL_OTHER);
+  *jcurPtr = jbad;
+  jok = !jbad;
+
+  /* Call pset routine and possibly reset jcur */
+  retval = pset(tn, ypred, fpred, jok, jcurPtr, gamma, P_data, 
+                vtemp1, vtemp2, vtemp3);
+  if (retval < 0) {
+    CVProcessError(cv_mem, SPBCG_PSET_FAIL_UNREC, "CVSPBCG", "CVSpbcgSetup", MSGS_PSET_FAILED);
+    last_flag = SPBCG_PSET_FAIL_UNREC;
+  }
+  if (retval > 0) {
+    last_flag = SPBCG_PSET_FAIL_REC;
+  }
+
+  if (jbad) *jcurPtr = TRUE;
+
+  /* If jcur = TRUE, increment npe and save nst value */
+  if (*jcurPtr) {
+    npe++;
+    nstlpre = nst;
+  }
+
+  last_flag = SPBCG_SUCCESS;
+
+  /* Return the same value that pset returned */
+  return(retval);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * Function : CVSpbcgSolve
+ * -----------------------------------------------------------------
+ * This routine handles the call to the generic solver SpbcgSolve
+ * for the solution of the linear system Ax = b with the SPBCG method.
+ * The solution x is returned in the vector b.
+ *
+ * If the WRMS norm of b is small, we return x = b (if this is the first
+ * Newton iteration) or x = 0 (if a later Newton iteration).
+ *
+ * Otherwise, we set the tolerance parameter and initial guess (x = 0),
+ * call SpbcgSolve, and copy the solution x into b. The x-scaling and
+ * b-scaling arrays are both equal to weight.
+ *
+ * The counters nli, nps, and ncfl are incremented, and the return value
+ * is set according to the success of SpbcgSolve. The success flag is
+ * returned if SpbcgSolve converged, or if this is the first Newton
+ * iteration and the residual norm was reduced below its initial value.
+ * -----------------------------------------------------------------
+ */
+
+static int CVSpbcgSolve(CVodeMem cv_mem, N_Vector b, N_Vector weight,
+                        N_Vector ynow, N_Vector fnow)
+{
+  realtype bnorm, res_norm;
+  CVSpilsMem cvspils_mem;
+  SpbcgMem spbcg_mem;
+  int nli_inc, nps_inc, retval;
+  
+  cvspils_mem = (CVSpilsMem) lmem;
+
+  spbcg_mem = (SpbcgMem) spils_mem;
+
+  /* Test norm(b); if small, return x = 0 or x = b */
+  deltar = delt * tq[4]; 
+
+  bnorm = N_VWrmsNorm(b, weight);
+  if (bnorm <= deltar) {
+    if (mnewt > 0) N_VConst(ZERO, b); 
+    return(0);
+  }
+
+  /* Set vectors ycur and fcur for use by the Atimes and Psolve routines */
+  ycur = ynow;
+  fcur = fnow;
+
+  /* Set inputs delta and initial guess x = 0 to SpbcgSolve */  
+  delta = deltar * sqrtN;
+  N_VConst(ZERO, x);
+  
+  /* Call SpbcgSolve and copy x to b */
+  retval = SpbcgSolve(spbcg_mem, cv_mem, x, b, pretype, delta,
+                      cv_mem, weight, weight, CVSpilsAtimes, CVSpilsPSolve,
+                      &res_norm, &nli_inc, &nps_inc);
+
+  N_VScale(ONE, x, b);
+  
+  /* Increment counters nli, nps, and ncfl */
+  nli += nli_inc;
+  nps += nps_inc;
+  if (retval != SPBCG_SUCCESS) ncfl++;
+
+  /* Interpret return value from SpbcgSolve */
+
+  last_flag = retval;
+
+  switch(retval) {
+
+  case SPBCG_SUCCESS:
+    return(0);
+    break;
+  case SPBCG_RES_REDUCED:
+    if (mnewt == 0) return(0);
+    else            return(1);
+    break;
+  case SPBCG_CONV_FAIL:
+    return(1);
+    break;
+  case SPBCG_PSOLVE_FAIL_REC:
+    return(1);
+    break;
+  case SPBCG_ATIMES_FAIL_REC:
+    return(1);
+    break;
+  case SPBCG_MEM_NULL:
+    return(-1);
+    break;
+  case SPBCG_ATIMES_FAIL_UNREC:
+    CVProcessError(cv_mem, SPBCG_ATIMES_FAIL_UNREC, "CVSPBCG", "CVSpbcgSolve", MSGS_JTIMES_FAILED);    
+    return(-1);
+    break;
+  case SPBCG_PSOLVE_FAIL_UNREC:
+    CVProcessError(cv_mem, SPBCG_PSOLVE_FAIL_UNREC, "CVSPBCG", "CVSpbcgSolve", MSGS_PSOLVE_FAILED);
+    return(-1);
+    break;
+  }
+
+  return(0);  
+
+}
+
+/*
+ * -----------------------------------------------------------------
+ * Function : CVSpbcgFree
+ * -----------------------------------------------------------------
+ * This routine frees memory specific to the Spbcg linear solver.
+ * -----------------------------------------------------------------
+ */
+
+static void CVSpbcgFree(CVodeMem cv_mem)
+{
+  CVSpilsMem cvspils_mem;
+  SpbcgMem spbcg_mem;
+
+  cvspils_mem = (CVSpilsMem) lmem;
+
+  spbcg_mem = (SpbcgMem) spils_mem;
+
+  N_VDestroy(ytemp);
+  N_VDestroy(x);
+  SpbcgFree(spbcg_mem);
+  free(cvspils_mem); cvspils_mem = NULL;
+}
+
+
+/* 
+ * ================================================================
+ *
+ *                   PART II - backward problems
+ *
+ * ================================================================
+ */
+
+
+/* Additional readability replacements */
+
+#define lmemB       (ca_mem->ca_lmemB)
+#define lfreeB      (ca_mem->ca_lfreeB)
+
+#define pset_B      (cvspilsB_mem->s_psetB)
+#define psolve_B    (cvspilsB_mem->s_psolveB)
+#define jtimes_B    (cvspilsB_mem->s_jtimesB)
+#define P_data_B    (cvspilsB_mem->s_P_dataB)
+#define jac_data_B  (cvspilsB_mem->s_jac_dataB)
+
+/*
+ * CVSpbcgB
+ *
+ * Wrapper for the backward phase
+ */
+
+int CVSpbcgB(void *cvadj_mem, int pretypeB, int maxlB)
+{
+  CVadjMem ca_mem;
+  CVSpilsMemB cvspilsB_mem;
+  CVodeMem cvB_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CVSPILS_ADJMEM_NULL, "CVSPBCG", "CVSpbcgB", MSGS_CAMEM_NULL);
+    return(CVSPILS_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  cvB_mem = ca_mem->cvb_mem;
+  
+  /* Get memory for CVSpilsMemRecB */
+  cvspilsB_mem = NULL;
+  cvspilsB_mem = (CVSpilsMemB) malloc(sizeof(CVSpilsMemRecB));
+  if (cvspilsB_mem == NULL) {
+    CVProcessError(cvB_mem, CVSPILS_MEM_FAIL, "CVSPBCG", "CVSpbcgB", MSGS_MEM_FAIL);
+    return(CVSPILS_MEM_FAIL);
+  }
+
+  pset_B = NULL;
+  psolve_B = NULL;
+  jtimes_B = NULL;
+  P_data_B = NULL;
+  jac_data_B = NULL;
+
+  /* attach lmemB and lfree */
+  lmemB = cvspilsB_mem;
+  lfreeB = CVSpbcgFreeB;
+
+  flag = CVSpbcg(cvB_mem, pretypeB, maxlB);
+
+  if (flag != CVSPILS_SUCCESS) {
+    free(cvspilsB_mem);
+    cvspilsB_mem = NULL;
+  }
+
+  return(flag);
+}
+
+/*
+ * CVSpbcgFreeB 
+ */
+
+
+static void CVSpbcgFreeB(CVadjMem ca_mem)
+{
+  CVSpilsMemB cvspilsB_mem;
+
+  cvspilsB_mem = (CVSpilsMemB) lmemB;
+
+  free(cvspilsB_mem);
+}
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_spgmr.c b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_spgmr.c
new file mode 100644
index 0000000000000000000000000000000000000000..bd2bacc8ee8d247d7baaa40810d6044809cc6af4
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_spgmr.c
@@ -0,0 +1,558 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2005, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the implementation file for the CVSPGMR linear solver.
+ * -----------------------------------------------------------------
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <cvodes/cvodes_spgmr.h>
+#include "cvodes_spils_impl.h"
+#include "cvodes_impl.h"
+
+#include <sundials/sundials_spgmr.h>
+#include <sundials/sundials_math.h>
+
+/* Constants */
+
+#define ZERO RCONST(0.0)
+#define ONE  RCONST(1.0)
+
+/* CVSPGMR linit, lsetup, lsolve, and lfree routines */
+
+static int CVSpgmrInit(CVodeMem cv_mem);
+
+static int CVSpgmrSetup(CVodeMem cv_mem, int convfail, N_Vector ypred,
+                        N_Vector fpred, booleantype *jcurPtr, N_Vector vtemp1,
+                        N_Vector vtemp2, N_Vector vtemp3);
+
+static int CVSpgmrSolve(CVodeMem cv_mem, N_Vector b, N_Vector weight,
+                        N_Vector ynow, N_Vector fnow);
+
+static void CVSpgmrFree(CVodeMem cv_mem);
+
+/* CVSPGMR lfreeB function */
+
+static void CVSpgmrFreeB(CVadjMem ca_mem);
+
+/* 
+ * ================================================================
+ *
+ *                   PART I - forward problems
+ *
+ * ================================================================
+ */
+
+
+/* Readability Replacements */
+
+#define uround  (cv_mem->cv_uround)
+#define tq      (cv_mem->cv_tq)
+#define nst     (cv_mem->cv_nst)
+#define tn      (cv_mem->cv_tn)
+#define h       (cv_mem->cv_h)
+#define gamma   (cv_mem->cv_gamma)
+#define gammap  (cv_mem->cv_gammap)   
+#define f       (cv_mem->cv_f)
+#define f_data  (cv_mem->cv_f_data)
+#define ewt     (cv_mem->cv_ewt)
+#define mnewt   (cv_mem->cv_mnewt)
+#define ropt    (cv_mem->cv_ropt)
+#define linit   (cv_mem->cv_linit)
+#define lsetup  (cv_mem->cv_lsetup)
+#define lsolve  (cv_mem->cv_lsolve)
+#define lfree   (cv_mem->cv_lfree)
+#define lmem    (cv_mem->cv_lmem)
+#define vec_tmpl     (cv_mem->cv_tempv)
+#define setupNonNull (cv_mem->cv_setupNonNull)
+
+#define sqrtN   (cvspils_mem->s_sqrtN)   
+#define ytemp   (cvspils_mem->s_ytemp)
+#define x       (cvspils_mem->s_x)
+#define ycur    (cvspils_mem->s_ycur)
+#define fcur    (cvspils_mem->s_fcur)
+#define delta   (cvspils_mem->s_delta)
+#define deltar  (cvspils_mem->s_deltar)
+#define npe     (cvspils_mem->s_npe)
+#define nli     (cvspils_mem->s_nli)
+#define nps     (cvspils_mem->s_nps)
+#define ncfl    (cvspils_mem->s_ncfl)
+#define nstlpre (cvspils_mem->s_nstlpre)
+#define njtimes (cvspils_mem->s_njtimes)
+#define nfes   (cvspils_mem->s_nfes)
+#define spils_mem (cvspils_mem->s_spils_mem)
+#define last_flag (cvspils_mem->s_last_flag)
+
+/*
+ * -----------------------------------------------------------------
+ * CVSpgmr
+ * -----------------------------------------------------------------
+ * This routine initializes the memory record and sets various function
+ * fields specific to the Spgmr linear solver module. CVSpgmr first
+ * calls the existing lfree routine if this is not NULL.  It then sets
+ * the cv_linit, cv_lsetup, cv_lsolve, cv_lfree fields in (*cvode_mem)
+ * to be CVSpgmrInit, CVSpgmrSetup, CVSpgmrSolve, and CVSpgmrFree,
+ * respectively.  It allocates memory for a structure of type
+ * CVSpilsMemRec and sets the cv_lmem field in (*cvode_mem) to the
+ * address of this structure.  It sets setupNonNull in (*cvode_mem),
+ * and sets the following fields in the CVSpilsMemRec structure:
+ *   s_pretype = pretype                                       
+ *   s_gstype  = gstype                                       
+ *   s_maxl    = MIN(N,CVSPILS_MAXL  if maxl <= 0             
+ *             = maxl                 if maxl > 0              
+ *   s_delt    = CVSPILS_DELT if delt == 0.0                     
+ *             = delt         if delt != 0.0                     
+ *   s_P_data  = P_data                                        
+ *   s_pset    = pset                                       
+ *   s_psolve  = psolve                                        
+ *   s_jtimes  = input parameter jtimes  if jtimes != NULL
+ *             = CVSpilsDQJtimes         otherwise
+ *   s_j_data  = input parameter jac_data
+ * Finally, CVSpgmr allocates memory for ytemp and x, and calls
+ * SpgmrMalloc to allocate memory for the Spgmr solver.
+ * -----------------------------------------------------------------
+ */
+
+int CVSpgmr(void *cvode_mem, int pretype, int maxl)
+{
+  CVodeMem cv_mem;
+  CVSpilsMem cvspils_mem;
+  SpgmrMem spgmr_mem;
+  int mxl;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVSPILS_MEM_NULL, "CVSPGMR", "CVSpgmr", MSGS_CVMEM_NULL);
+    return(CVSPILS_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  /* Check if N_VDotProd is present */
+  if(vec_tmpl->ops->nvdotprod == NULL) {
+    CVProcessError(cv_mem, CVSPILS_ILL_INPUT, "CVSPGMR", "CVSpgmr", MSGS_BAD_NVECTOR);
+    return(CVSPILS_ILL_INPUT);
+  }
+
+  if (lfree != NULL) lfree(cv_mem);
+
+  /* Set four main function fields in cv_mem */
+  linit  = CVSpgmrInit;
+  lsetup = CVSpgmrSetup;
+  lsolve = CVSpgmrSolve;
+  lfree  = CVSpgmrFree;
+
+  /* Get memory for CVSpilsMemRec */
+  cvspils_mem = NULL;
+  cvspils_mem = (CVSpilsMem) malloc(sizeof(CVSpilsMemRec));
+  if (cvspils_mem == NULL) {
+    CVProcessError(cv_mem, CVSPILS_MEM_FAIL, "CVSPGMR", "CVSpgmr", MSGS_MEM_FAIL);
+    return(CVSPILS_MEM_FAIL);
+  }
+
+  /* Set ILS type */
+  cvspils_mem->s_type = SPILS_SPGMR;
+
+  /* Set Spgmr parameters that have been passed in call sequence */
+  cvspils_mem->s_pretype    = pretype;
+  mxl = cvspils_mem->s_maxl = (maxl <= 0) ? CVSPILS_MAXL : maxl;
+
+  /* Set default values for the rest of the Spgmr parameters */
+  cvspils_mem->s_gstype     = MODIFIED_GS;
+  cvspils_mem->s_delt       = CVSPILS_DELT;
+  cvspils_mem->s_P_data     = NULL;
+  cvspils_mem->s_pset       = NULL;
+  cvspils_mem->s_psolve     = NULL;
+  cvspils_mem->s_jtimes     = CVSpilsDQJtimes;
+  cvspils_mem->s_j_data     = cvode_mem;
+  cvspils_mem->s_last_flag  = CVSPILS_SUCCESS;
+
+
+  setupNonNull = FALSE;
+
+  /* Check for legal pretype */ 
+  if ((pretype != PREC_NONE) && (pretype != PREC_LEFT) &&
+      (pretype != PREC_RIGHT) && (pretype != PREC_BOTH)) {
+    CVProcessError(cv_mem, CVSPILS_ILL_INPUT, "CVSPGMR", "CVSpgmr", MSGS_BAD_PRETYPE);
+    return(CVSPILS_ILL_INPUT);
+  }
+
+  /* Allocate memory for ytemp and x */
+  ytemp = NULL;
+  ytemp = N_VClone(vec_tmpl);
+  if (ytemp == NULL) {
+    CVProcessError(cv_mem, CVSPILS_MEM_FAIL, "CVSPGMR", "CVSpgmr", MSGS_MEM_FAIL);
+    free(cvspils_mem); cvspils_mem = NULL;
+    return(CVSPILS_MEM_FAIL);
+  }
+  x = NULL;
+  x = N_VClone(vec_tmpl);
+  if (x == NULL) {
+    CVProcessError(cv_mem, CVSPILS_MEM_FAIL, "CVSPGMR", "CVSpgmr", MSGS_MEM_FAIL);
+    N_VDestroy(ytemp);
+    free(cvspils_mem); cvspils_mem = NULL;
+    return(CVSPILS_MEM_FAIL);
+  }
+
+  /* Compute sqrtN from a dot product */
+  N_VConst(ONE, ytemp);
+  sqrtN = RSqrt( N_VDotProd(ytemp, ytemp) );
+
+  /* Call SpgmrMalloc to allocate workspace for Spgmr */
+  spgmr_mem = NULL;
+  spgmr_mem = SpgmrMalloc(mxl, vec_tmpl);
+  if (spgmr_mem == NULL) {
+    CVProcessError(cv_mem, CVSPILS_MEM_FAIL, "CVSPGMR", "CVSpgmr", MSGS_MEM_FAIL);
+    N_VDestroy(ytemp);
+    N_VDestroy(x);
+    free(cvspils_mem); cvspils_mem = NULL;
+    return(CVSPILS_MEM_FAIL);
+  }
+  
+  /* Attach SPGMR memory to spils memory structure */
+  spils_mem = (void *) spgmr_mem;
+
+  /* Attach linear solver memory to integrator memory */
+  lmem = cvspils_mem;
+
+  return(CVSPILS_SUCCESS);
+}
+
+
+/* Additional readability Replacements */
+
+#define pretype (cvspils_mem->s_pretype)
+#define gstype  (cvspils_mem->s_gstype)
+#define delt    (cvspils_mem->s_delt)
+#define maxl    (cvspils_mem->s_maxl)
+#define psolve  (cvspils_mem->s_psolve)
+#define pset    (cvspils_mem->s_pset)
+#define P_data  (cvspils_mem->s_P_data)
+#define jtimes  (cvspils_mem->s_jtimes)
+#define j_data  (cvspils_mem->s_j_data)
+
+/*
+ * -----------------------------------------------------------------
+ * CVSpgmrInit
+ * -----------------------------------------------------------------
+ * This routine does remaining initializations specific to the Spgmr 
+ * linear solver.
+ * -----------------------------------------------------------------
+ */
+
+static int CVSpgmrInit(CVodeMem cv_mem)
+{
+  CVSpilsMem cvspils_mem;
+  cvspils_mem = (CVSpilsMem) lmem;
+
+  /* Initialize counters */
+  npe = nli = nps = ncfl = nstlpre = 0;
+  njtimes = nfes = 0;
+
+  /* Check for legal combination pretype - psolve */
+  if ((pretype != PREC_NONE) && (psolve == NULL)) {
+    CVProcessError(cv_mem, -1, "CVSPGMR", "CVSpgmrInit", MSGS_PSOLVE_REQ);
+    last_flag = CVSPILS_ILL_INPUT;
+    return(-1);
+  }
+
+  /* Set setupNonNull = TRUE iff there is preconditioning (pretype != PREC_NONE)
+     and there is a preconditioning setup phase (pset != NULL)             */
+  setupNonNull = (pretype != PREC_NONE) && (pset != NULL);
+
+  /* If jtimes is NULL at this time, set it to DQ */
+  if (jtimes == NULL) {
+    jtimes = CVSpilsDQJtimes;
+    j_data = cv_mem;
+  }
+
+  last_flag = CVSPILS_SUCCESS;
+  return(0);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVSpgmrSetup
+ * -----------------------------------------------------------------
+ * This routine does the setup operations for the Spgmr linear solver.
+ * It makes a decision as to whether or not to signal for re-evaluation
+ * of Jacobian data in the pset routine, based on various state
+ * variables, then it calls pset.  If we signal for re-evaluation,
+ * then we reset jcur = *jcurPtr to TRUE, regardless of the pset output.
+ * In any case, if jcur == TRUE, we increment npe and save nst in nstlpre.
+ * -----------------------------------------------------------------
+ */
+
+static int CVSpgmrSetup(CVodeMem cv_mem, int convfail, N_Vector ypred,
+                        N_Vector fpred, booleantype *jcurPtr, N_Vector vtemp1,
+                        N_Vector vtemp2, N_Vector vtemp3)
+{
+  booleantype jbad, jok;
+  realtype dgamma;
+  int  retval;
+  CVSpilsMem cvspils_mem;
+
+  cvspils_mem = (CVSpilsMem) lmem;
+
+  /* Use nst, gamma/gammap, and convfail to set J eval. flag jok */
+  dgamma = ABS((gamma/gammap) - ONE);
+  jbad = (nst == 0) || (nst > nstlpre + CVSPILS_MSBPRE) ||
+    ((convfail == CV_FAIL_BAD_J) && (dgamma < CVSPILS_DGMAX)) ||
+    (convfail == CV_FAIL_OTHER);
+  *jcurPtr = jbad;
+  jok = !jbad;
+
+  /* Call pset routine and possibly reset jcur */
+  retval = pset(tn, ypred, fpred, jok, jcurPtr, gamma, P_data, 
+                vtemp1, vtemp2, vtemp3);
+  if (retval < 0) {
+    CVProcessError(cv_mem, SPGMR_PSET_FAIL_UNREC, "CVSPGMR", "CVSpgmrSetup", MSGS_PSET_FAILED);
+    last_flag = SPGMR_PSET_FAIL_UNREC;
+  }
+  if (retval > 0) {
+    last_flag = SPGMR_PSET_FAIL_REC;
+  }
+
+  if (jbad) *jcurPtr = TRUE;
+
+  /* If jcur = TRUE, increment npe and save nst value */
+  if (*jcurPtr) {
+    npe++;
+    nstlpre = nst;
+  }
+
+  last_flag = SPGMR_SUCCESS;
+
+  /* Return the same value that pset returned */
+  return(retval);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVSpgmrSolve
+ * -----------------------------------------------------------------
+ * This routine handles the call to the generic solver SpgmrSolve
+ * for the solution of the linear system Ax = b with the SPGMR method,
+ * without restarts.  The solution x is returned in the vector b.
+ *
+ * If the WRMS norm of b is small, we return x = b (if this is the first
+ * Newton iteration) or x = 0 (if a later Newton iteration).
+ *
+ * Otherwise, we set the tolerance parameter and initial guess (x = 0),
+ * call SpgmrSolve, and copy the solution x into b.  The x-scaling and
+ * b-scaling arrays are both equal to weight, and no restarts are allowed.
+ *
+ * The counters nli, nps, and ncfl are incremented, and the return value
+ * is set according to the success of SpgmrSolve.  The success flag is
+ * returned if SpgmrSolve converged, or if this is the first Newton
+ * iteration and the residual norm was reduced below its initial value.
+ * -----------------------------------------------------------------
+ */
+
+static int CVSpgmrSolve(CVodeMem cv_mem, N_Vector b, N_Vector weight,
+                        N_Vector ynow, N_Vector fnow)
+{
+  realtype bnorm, res_norm;
+  CVSpilsMem cvspils_mem;
+  SpgmrMem spgmr_mem;
+  int nli_inc, nps_inc, retval;
+  
+  cvspils_mem = (CVSpilsMem) lmem;
+
+  spgmr_mem = (SpgmrMem) spils_mem;
+
+  /* Test norm(b); if small, return x = 0 or x = b */
+  deltar = delt*tq[4]; 
+
+  bnorm = N_VWrmsNorm(b, weight);
+  if (bnorm <= deltar) {
+    if (mnewt > 0) N_VConst(ZERO, b); 
+    return(0);
+  }
+
+  /* Set vectors ycur and fcur for use by the Atimes and Psolve routines */
+  ycur = ynow;
+  fcur = fnow;
+
+  /* Set inputs delta and initial guess x = 0 to SpgmrSolve */  
+  delta = deltar * sqrtN;
+  N_VConst(ZERO, x);
+  
+  /* Call SpgmrSolve and copy x to b */
+  retval = SpgmrSolve(spgmr_mem, cv_mem, x, b, pretype, gstype, delta, 0,
+                   cv_mem, weight, weight, CVSpilsAtimes, CVSpilsPSolve,
+                   &res_norm, &nli_inc, &nps_inc);
+
+  N_VScale(ONE, x, b);
+  
+  /* Increment counters nli, nps, and ncfl */
+  nli += nli_inc;
+  nps += nps_inc;
+  if (retval != SPGMR_SUCCESS) ncfl++;
+
+  /* Interpret return value from SpgmrSolve */
+
+  last_flag = retval;
+
+  switch(retval) {
+
+  case SPGMR_SUCCESS:
+    return(0);
+    break;
+  case SPGMR_RES_REDUCED:
+    if (mnewt == 0) return(0);
+    else            return(1);
+    break;
+  case SPGMR_CONV_FAIL:
+    return(1);
+    break;
+  case SPGMR_QRFACT_FAIL:
+    return(1);
+    break;
+  case SPGMR_PSOLVE_FAIL_REC:
+    return(1);
+    break;
+  case SPGMR_ATIMES_FAIL_REC:
+    return(1);
+    break;
+  case SPGMR_MEM_NULL:
+    return(-1);
+    break;
+  case SPGMR_ATIMES_FAIL_UNREC:
+    CVProcessError(cv_mem, SPGMR_ATIMES_FAIL_UNREC, "CVSPGMR", "CVSpgmrSolve", MSGS_JTIMES_FAILED);    
+    return(-1);
+    break;
+  case SPGMR_PSOLVE_FAIL_UNREC:
+    CVProcessError(cv_mem, SPGMR_PSOLVE_FAIL_UNREC, "CVSPGMR", "CVSpgmrSolve", MSGS_PSOLVE_FAILED);
+    return(-1);
+    break;
+  case SPGMR_GS_FAIL:
+    return(-1);
+    break;
+  case SPGMR_QRSOL_FAIL:
+    return(-1);
+    break;
+  }
+
+  return(0);  
+
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVSpgmrFree
+ * -----------------------------------------------------------------
+ * This routine frees memory specific to the Spgmr linear solver.
+ * -----------------------------------------------------------------
+ */
+
+static void CVSpgmrFree(CVodeMem cv_mem)
+{
+  CVSpilsMem cvspils_mem;
+  SpgmrMem spgmr_mem;
+
+  cvspils_mem = (CVSpilsMem) lmem;
+  
+  spgmr_mem = (SpgmrMem) spils_mem;
+
+  N_VDestroy(ytemp);
+  N_VDestroy(x);
+  SpgmrFree(spgmr_mem);
+  free(cvspils_mem); cvspils_mem = NULL;
+}
+
+
+/* 
+ * ================================================================
+ *
+ *                   PART II - backward problems
+ *
+ * ================================================================
+ */
+
+
+/* Additional readability replacements */
+
+#define lmemB       (ca_mem->ca_lmemB)
+#define lfreeB      (ca_mem->ca_lfreeB)
+
+#define pset_B      (cvspilsB_mem->s_psetB)
+#define psolve_B    (cvspilsB_mem->s_psolveB)
+#define jtimes_B    (cvspilsB_mem->s_jtimesB)
+#define P_data_B    (cvspilsB_mem->s_P_dataB)
+#define jac_data_B  (cvspilsB_mem->s_jac_dataB)
+
+/*
+ * CVSpgmrB
+ *
+ * Wrapper for the backward phase
+ *
+ */
+
+int CVSpgmrB(void *cvadj_mem, int pretypeB, int maxlB)
+{
+  CVadjMem ca_mem;
+  CVSpilsMemB cvspilsB_mem;
+  CVodeMem cvB_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CVSPILS_ADJMEM_NULL, "CVSPGMR", "CVSpgmrB", MSGS_CAMEM_NULL);
+    return(CVSPILS_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  cvB_mem = ca_mem->cvb_mem;
+
+  /* Get memory for CVSpilsMemRecB */
+  cvspilsB_mem = NULL;
+  cvspilsB_mem = (CVSpilsMemB) malloc(sizeof(CVSpilsMemRecB));
+  if (cvspilsB_mem == NULL) {
+    CVProcessError(cvB_mem, CVSPILS_MEM_FAIL, "CVSPGMR", "CVSpgmrB", MSGS_MEM_FAIL);
+    return(CVSPILS_MEM_FAIL);
+  }
+
+  pset_B = NULL;
+  psolve_B = NULL;
+  jtimes_B = NULL;
+  P_data_B = NULL;
+  jac_data_B = NULL;
+
+  /* attach lmemB and lfreeB */
+  lmemB = cvspilsB_mem;
+  lfreeB = CVSpgmrFreeB;
+  
+  flag = CVSpgmr(cvB_mem, pretypeB, maxlB);
+
+  if (flag != CVSPILS_SUCCESS) {
+    free(cvspilsB_mem);
+    cvspilsB_mem = NULL;
+  }
+
+  return(flag);
+}
+
+
+/*
+ * CVSpgmrFreeB 
+ */
+
+
+static void CVSpgmrFreeB(CVadjMem ca_mem)
+{
+  CVSpilsMemB cvspilsB_mem;
+
+  cvspilsB_mem = (CVSpilsMemB) lmemB;
+
+  free(cvspilsB_mem);
+}
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_spils.c b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_spils.c
new file mode 100644
index 0000000000000000000000000000000000000000..802a92584060a92b6cd86e0d4322fb434943770d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_spils.c
@@ -0,0 +1,988 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s):Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2005, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the implementation file for the CVSPILS linear solvers.
+ *
+ * Part II contains wrappers for using the CVODES iterative linear 
+ * solvers on adjoint (backward) problems.
+ * -----------------------------------------------------------------
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "cvodes_impl.h"
+#include "cvodes_spils_impl.h"
+
+/* Private constants */
+
+#define ZERO   RCONST(0.0)
+#define PT25   RCONST(0.25)
+#define ONE    RCONST(1.0)
+
+/* Algorithmic constants */
+
+#define MAX_ITERS  3  /* max. number of attempts to recover in DQ J*v */
+
+/* 
+ * ================================================================
+ *
+ *                   PART I - forward problems
+ *
+ * ================================================================
+ */
+
+/* Readability Replacements */
+
+#define lrw1    (cv_mem->cv_lrw1)
+#define liw1    (cv_mem->cv_liw1)
+#define tq      (cv_mem->cv_tq)
+#define tn      (cv_mem->cv_tn)
+#define h       (cv_mem->cv_h)
+#define gamma   (cv_mem->cv_gamma)
+#define nfe     (cv_mem->cv_nfe)
+#define f       (cv_mem->cv_f)
+#define f_data  (cv_mem->cv_f_data)
+#define ewt     (cv_mem->cv_ewt)
+#define lmem    (cv_mem->cv_lmem)
+
+#define ils_type (cvspils_mem->s_type)
+#define sqrtN   (cvspils_mem->s_sqrtN)   
+#define ytemp   (cvspils_mem->s_ytemp)
+#define x       (cvspils_mem->s_x)
+#define ycur    (cvspils_mem->s_ycur)
+#define fcur    (cvspils_mem->s_fcur)
+#define delta   (cvspils_mem->s_delta)
+#define npe     (cvspils_mem->s_npe)
+#define nli     (cvspils_mem->s_nli)
+#define nps     (cvspils_mem->s_nps)
+#define ncfl    (cvspils_mem->s_ncfl)
+#define njtimes (cvspils_mem->s_njtimes)
+#define nfes    (cvspils_mem->s_nfes)
+
+#define last_flag (cvspils_mem->s_last_flag)
+
+
+/*
+ * -----------------------------------------------------------------
+ * OPTIONAL INPUT and OUTPUT FUNCTIONS
+ * -----------------------------------------------------------------
+ */
+
+
+/*
+ * -----------------------------------------------------------------
+ * CVSpilsSetPrecType
+ * -----------------------------------------------------------------
+ */
+
+int CVSpilsSetPrecType(void *cvode_mem, int pretype)
+{
+  CVodeMem cv_mem;
+  CVSpilsMem cvspils_mem;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVSPILS_MEM_NULL, "CVSPILS", "CVSpilsSetPrecType", MSGS_CVMEM_NULL);
+    return(CVSPILS_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (lmem == NULL) {
+    CVProcessError(cv_mem, CVSPILS_LMEM_NULL, "CVSPILS", "CVSpilsSetPrecType", MSGS_LMEM_NULL);
+    return(CVSPILS_LMEM_NULL);
+  }
+  cvspils_mem = (CVSpilsMem) lmem;
+
+  /* Check for legal pretype */ 
+  if ((pretype != PREC_NONE) && (pretype != PREC_LEFT) &&
+      (pretype != PREC_RIGHT) && (pretype != PREC_BOTH)) {
+    CVProcessError(cv_mem, CVSPILS_ILL_INPUT, "CVSPILS", "CVSpilsSetPrecType", MSGS_BAD_PRETYPE);
+    return(CVSPILS_ILL_INPUT);
+  }
+
+  cvspils_mem->s_pretype = pretype;
+
+  return(CVSPILS_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVSpilsSetGSType
+ * -----------------------------------------------------------------
+ */
+
+int CVSpilsSetGSType(void *cvode_mem, int gstype)
+{
+  CVodeMem cv_mem;
+  CVSpilsMem cvspils_mem;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVSPILS_MEM_NULL, "CVSPILS", "CVSpilsSetGSType", MSGS_CVMEM_NULL);
+    return(CVSPILS_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (lmem == NULL) {
+    CVProcessError(cv_mem, CVSPILS_LMEM_NULL, "CVSPILS", "CVSpilsSetGSType", MSGS_LMEM_NULL);
+    return(CVSPILS_LMEM_NULL);
+  }
+  cvspils_mem = (CVSpilsMem) lmem;
+
+  if (ils_type != SPILS_SPGMR) {
+    CVProcessError(cv_mem, CVSPILS_ILL_INPUT, "CVSPILS", "CVSpilsSetGSType", MSGS_BAD_LSTYPE);
+    return(CVSPILS_ILL_INPUT);
+  }
+
+  /* Check for legal gstype */
+  if ((gstype != MODIFIED_GS) && (gstype != CLASSICAL_GS)) {
+    CVProcessError(cv_mem, CVSPILS_ILL_INPUT, "CVSPILS", "CVSpilsSetGSType", MSGS_BAD_GSTYPE);
+    return(CVSPILS_ILL_INPUT);
+  }
+
+  cvspils_mem->s_gstype = gstype;
+
+  return(CVSPILS_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * Function : CVSpilsSetMaxl
+ * -----------------------------------------------------------------
+ */
+
+int CVSpilsSetMaxl(void *cvode_mem, int maxl)
+{
+  CVodeMem cv_mem;
+  CVSpilsMem cvspils_mem;
+  int mxl;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVSPILS_MEM_NULL, "CVSPILS", "CVSpilsSetMaxl", MSGS_CVMEM_NULL);
+    return(CVSPILS_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (lmem == NULL) {
+    CVProcessError(NULL, CVSPILS_LMEM_NULL, "CVSPILS", "CVSpilsSetMaxl", MSGS_LMEM_NULL);
+    return(CVSPILS_LMEM_NULL);
+  }
+  cvspils_mem = (CVSpilsMem) lmem;
+
+  if (ils_type == SPILS_SPGMR) {
+    CVProcessError(cv_mem, CVSPILS_ILL_INPUT, "CVSPILS", "CVSpilsSetMaxl", MSGS_BAD_LSTYPE);
+    return(CVSPILS_ILL_INPUT);
+  }
+
+  mxl = (maxl <= 0) ? CVSPILS_MAXL : maxl;
+  cvspils_mem->s_maxl = mxl;
+
+  /*  spbcg_mem->l_max  = mxl; */
+
+  return(CVSPILS_SUCCESS);
+}
+
+
+/*
+ * -----------------------------------------------------------------
+ * CVSpilsSetDelt
+ * -----------------------------------------------------------------
+ */
+
+int CVSpilsSetDelt(void *cvode_mem, realtype delt)
+{
+  CVodeMem cv_mem;
+  CVSpilsMem cvspils_mem;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVSPILS_MEM_NULL, "CVSPILS", "CVSpilsSetDelt", MSGS_CVMEM_NULL);
+    return(CVSPILS_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (lmem == NULL) {
+    CVProcessError(cv_mem, CVSPILS_LMEM_NULL, "CVSPILS", "CVSpilsSetDelt", MSGS_LMEM_NULL);
+    return(CVSPILS_LMEM_NULL);
+  }
+  cvspils_mem = (CVSpilsMem) lmem;
+
+  /* Check for legal delt */
+  if(delt < ZERO) {
+    CVProcessError(cv_mem, CVSPILS_ILL_INPUT, "CVSPILS", "CVSpilsSetDelt", MSGS_BAD_DELT);
+    return(CVSPILS_ILL_INPUT);
+  }
+
+  cvspils_mem->s_delt = (delt == ZERO) ? CVSPILS_DELT : delt;
+
+  return(CVSPILS_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVSpilsSetPrecSetupFn
+ * -----------------------------------------------------------------
+ */
+
+int CVSpilsSetPreconditioner(void *cvode_mem, CVSpilsPrecSetupFn pset, 
+                             CVSpilsPrecSolveFn psolve, void *P_data)
+{
+  CVodeMem cv_mem;
+  CVSpilsMem cvspils_mem;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVSPILS_MEM_NULL, "CVSPILS", "CVSpilsSetPreconditioner", MSGS_CVMEM_NULL);
+    return(CVSPILS_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (lmem == NULL) {
+    CVProcessError(cv_mem, CVSPILS_LMEM_NULL, "CVSPILS", "CVSpilsSetPreconditioner", MSGS_LMEM_NULL);
+    return(CVSPILS_LMEM_NULL);
+  }
+  cvspils_mem = (CVSpilsMem) lmem;
+
+  cvspils_mem->s_pset = pset;
+  cvspils_mem->s_psolve = psolve;
+  if (psolve != NULL) cvspils_mem->s_P_data = P_data;
+
+  return(CVSPILS_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVSpilsSetJacTimesVecFn
+ * -----------------------------------------------------------------
+ */
+
+int CVSpilsSetJacTimesVecFn(void *cvode_mem, CVSpilsJacTimesVecFn jtimes, void *jac_data)
+{
+  CVodeMem cv_mem;
+  CVSpilsMem cvspils_mem;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVSPILS_MEM_NULL, "CVSPILS", "CVSpilsSetJacTimesVecFn", MSGS_CVMEM_NULL);
+    return(CVSPILS_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (lmem == NULL) {
+    CVProcessError(cv_mem, CVSPILS_LMEM_NULL, "CVSPILS", "CVSpilsSetJacTimesVecFn", MSGS_LMEM_NULL);
+    return(CVSPILS_LMEM_NULL);
+  }
+  cvspils_mem = (CVSpilsMem) lmem;
+
+  cvspils_mem->s_jtimes = jtimes;
+  if (jtimes != NULL) cvspils_mem->s_j_data = jac_data;
+
+  return(CVSPILS_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVSpilsGetWorkSpace
+ * -----------------------------------------------------------------
+ */
+
+int CVSpilsGetWorkSpace(void *cvode_mem, long int *lenrwLS, long int *leniwLS)
+{
+  CVodeMem cv_mem;
+  CVSpilsMem cvspils_mem;
+  int maxl;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVSPILS_MEM_NULL, "CVSPILS", "CVSpilsGetWorkSpace", MSGS_CVMEM_NULL);
+    return(CVSPILS_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (lmem == NULL) {
+    CVProcessError(cv_mem, CVSPILS_LMEM_NULL, "CVSPILS", "CVSpilsGetWorkSpace", MSGS_LMEM_NULL);
+    return(CVSPILS_LMEM_NULL);
+  }
+  cvspils_mem = (CVSpilsMem) lmem;
+
+  
+  switch(ils_type) {
+  case SPILS_SPGMR:
+    maxl = cvspils_mem->s_maxl;
+    *lenrwLS = lrw1*(maxl + 5) + maxl*(maxl + 4) + 1;
+    *leniwLS = liw1*(maxl + 5);
+    break;
+  case SPILS_SPBCG:
+    *lenrwLS = lrw1 * 9;
+    *leniwLS = liw1 * 9;
+    break;
+  case SPILS_SPTFQMR:
+    *lenrwLS = lrw1*11;
+    *leniwLS = liw1*11;
+    break;
+  }
+
+
+  return(CVSPILS_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVSpilsGetNumPrecEvals
+ * -----------------------------------------------------------------
+ */
+
+int CVSpilsGetNumPrecEvals(void *cvode_mem, long int *npevals)
+{
+  CVodeMem cv_mem;
+  CVSpilsMem cvspils_mem;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVSPILS_MEM_NULL, "CVSPILS", "CVSpilsGetNumPrecEvals", MSGS_CVMEM_NULL);
+    return(CVSPILS_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (lmem == NULL) {
+    CVProcessError(cv_mem, CVSPILS_LMEM_NULL, "CVSPILS", "CVSpilsGetNumPrecEvals", MSGS_LMEM_NULL);
+    return(CVSPILS_LMEM_NULL);
+  }
+  cvspils_mem = (CVSpilsMem) lmem;
+
+  *npevals = npe;
+
+  return(CVSPILS_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVSpilsGetNumPrecSolves
+ * -----------------------------------------------------------------
+ */
+
+int CVSpilsGetNumPrecSolves(void *cvode_mem, long int *npsolves)
+{
+  CVodeMem cv_mem;
+  CVSpilsMem cvspils_mem;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVSPILS_MEM_NULL, "CVSPILS", "CVSpilsGetNumPrecSolves", MSGS_CVMEM_NULL);
+    return(CVSPILS_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (lmem == NULL) {
+    CVProcessError(cv_mem, CVSPILS_LMEM_NULL, "CVSPILS", "CVSpilsGetNumPrecSolves", MSGS_LMEM_NULL);
+    return(CVSPILS_LMEM_NULL);
+  }
+  cvspils_mem = (CVSpilsMem) lmem;
+
+  *npsolves = nps;
+
+  return(CVSPILS_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVSpilsGetNumLinIters
+ * -----------------------------------------------------------------
+ */
+
+int CVSpilsGetNumLinIters(void *cvode_mem, long int *nliters)
+{
+  CVodeMem cv_mem;
+  CVSpilsMem cvspils_mem;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVSPILS_MEM_NULL, "CVSPILS", "CVSpilsGetNumLinIters", MSGS_CVMEM_NULL);
+    return(CVSPILS_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (lmem == NULL) {
+    CVProcessError(cv_mem, CVSPILS_LMEM_NULL, "CVSPILS", "CVSpilsGetNumLinIters", MSGS_LMEM_NULL);
+    return(CVSPILS_LMEM_NULL);
+  }
+  cvspils_mem = (CVSpilsMem) lmem;
+
+  *nliters = nli;
+
+  return(CVSPILS_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVSpilsGetNumConvFails
+ * -----------------------------------------------------------------
+ */
+
+int CVSpilsGetNumConvFails(void *cvode_mem, long int *nlcfails)
+{
+  CVodeMem cv_mem;
+  CVSpilsMem cvspils_mem;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVSPILS_MEM_NULL, "CVSPILS", "CVSpilsGetNumConvFails", MSGS_CVMEM_NULL);
+    return(CVSPILS_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (lmem == NULL) {
+    CVProcessError(cv_mem, CVSPILS_LMEM_NULL, "CVSPILS", "CVSpilsGetNumConvFails", MSGS_LMEM_NULL);
+    return(CVSPILS_LMEM_NULL);
+  }
+  cvspils_mem = (CVSpilsMem) lmem;
+
+  *nlcfails = ncfl;
+
+  return(CVSPILS_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVSpilsGetNumJtimesEvals
+ * -----------------------------------------------------------------
+ */
+
+int CVSpilsGetNumJtimesEvals(void *cvode_mem, long int *njvevals)
+{
+  CVodeMem cv_mem;
+  CVSpilsMem cvspils_mem;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVSPILS_MEM_NULL, "CVSPILS", "CVSpilsGetNumJtimesEvals", MSGS_CVMEM_NULL);
+    return(CVSPILS_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (lmem == NULL) {
+    CVProcessError(cv_mem, CVSPILS_LMEM_NULL, "CVSPILS", "CVSpilsGetNumJtimesEvals", MSGS_LMEM_NULL);
+    return(CVSPILS_LMEM_NULL);
+  }
+  cvspils_mem = (CVSpilsMem) lmem;
+
+  *njvevals = njtimes;
+
+  return(CVSPILS_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVSpilsGetNumRhsEvals
+ * -----------------------------------------------------------------
+ */
+
+int CVSpilsGetNumRhsEvals(void *cvode_mem, long int *nfevalsLS)
+{
+  CVodeMem cv_mem;
+  CVSpilsMem cvspils_mem;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVSPILS_MEM_NULL, "CVSPILS", "CVSpilsGetNumRhsEvals", MSGS_CVMEM_NULL);
+    return(CVSPILS_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (lmem == NULL) {
+    CVProcessError(cv_mem, CVSPILS_LMEM_NULL, "CVSPILS", "CVSpilsGetNumRhsEvals", MSGS_LMEM_NULL);
+    return(CVSPILS_LMEM_NULL);
+  }
+  cvspils_mem = (CVSpilsMem) lmem;
+
+  *nfevalsLS = nfes;
+
+  return(CVSPILS_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVSpilsGetLastFlag
+ * -----------------------------------------------------------------
+ */
+
+int CVSpilsGetLastFlag(void *cvode_mem, int *flag)
+{
+  CVodeMem cv_mem;
+  CVSpilsMem cvspils_mem;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVSPILS_MEM_NULL, "CVSPILS", "CVSpilsGetLastFlag", MSGS_CVMEM_NULL);
+    return(CVSPILS_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  if (lmem == NULL) {
+    CVProcessError(cv_mem, CVSPILS_LMEM_NULL, "CVSPILS", "CVSpilsGetLastFlag", MSGS_LMEM_NULL);
+    return(CVSPILS_LMEM_NULL);
+  }
+  cvspils_mem = (CVSpilsMem) lmem;
+
+  *flag = last_flag;
+
+  return(CVSPILS_SUCCESS);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVSpilsGetReturnFlagName
+ * -----------------------------------------------------------------
+ */
+
+char *CVSpilsGetReturnFlagName(int flag)
+{
+  char *name;
+
+  name = (char *)malloc(30*sizeof(char));
+
+  switch(flag) {
+  case CVSPILS_SUCCESS:
+    sprintf(name,"CVSPILS_SUCCESS");
+    break;    
+  case CVSPILS_MEM_NULL:
+    sprintf(name,"CVSPILS_MEM_NULL");
+    break;
+  case CVSPILS_LMEM_NULL:
+    sprintf(name,"CVSPILS_LMEM_NULL");
+    break;
+  case CVSPILS_ILL_INPUT:
+    sprintf(name,"CVSPILS_ILL_INPUT");
+    break;
+  case CVSPILS_MEM_FAIL:
+    sprintf(name,"CVSPILS_MEM_FAIL");
+    break;
+  case CVSPILS_ADJMEM_NULL:
+    sprintf(name,"CVSPILS_ADJMEM_NULL");
+    break;
+  case CVSPILS_LMEMB_NULL:
+    sprintf(name,"CVSPILS_LMEMB_NULL");
+    break;
+  default:
+    sprintf(name,"NONE");
+  }
+
+  return(name);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVSPILS private functions
+ * -----------------------------------------------------------------
+ */
+
+
+/* Additional readability Replacements */
+
+#define pretype (cvspils_mem->s_pretype)
+#define delt    (cvspils_mem->s_delt)
+#define maxl    (cvspils_mem->s_maxl)
+#define psolve  (cvspils_mem->s_psolve)
+#define P_data  (cvspils_mem->s_P_data)
+#define jtimes  (cvspils_mem->s_jtimes)
+#define j_data  (cvspils_mem->s_j_data)
+
+/*
+ * -----------------------------------------------------------------
+ * CVSpilsAtimes
+ * -----------------------------------------------------------------
+ * This routine generates the matrix-vector product z = Mv, where
+ * M = I - gamma*J. The product J*v is obtained by calling the jtimes 
+ * routine. It is then scaled by -gamma and added to v to obtain M*v.
+ * The return value is the same as the value returned by jtimes --
+ * 0 if successful, nonzero otherwise.
+ * -----------------------------------------------------------------
+ */
+
+int CVSpilsAtimes(void *cvode_mem, N_Vector v, N_Vector z)
+{
+  CVodeMem   cv_mem;
+  CVSpilsMem cvspils_mem;
+  int retval;
+
+  cv_mem = (CVodeMem) cvode_mem;
+  cvspils_mem = (CVSpilsMem) lmem;
+
+  retval = jtimes(v, z, tn, ycur, fcur, j_data, ytemp);
+  njtimes++;
+  if (retval != 0) return(retval);
+
+  N_VLinearSum(ONE, v, -gamma, z, z);
+
+  return(0);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVSpilsPSolve
+ * -----------------------------------------------------------------
+ * This routine interfaces between the generic SpgmrSolve routine and
+ * the user's psolve routine.  It passes to psolve all required state 
+ * information from cvode_mem.  Its return value is the same as that
+ * returned by psolve. Note that the generic SPGMR solver guarantees
+ * that CVSpilsPSolve will not be called in the case in which
+ * preconditioning is not done. This is the only case in which the
+ * user's psolve routine is allowed to be NULL.
+ * -----------------------------------------------------------------
+ */
+
+int CVSpilsPSolve(void *cvode_mem, N_Vector r, N_Vector z, int lr)
+{
+  CVodeMem   cv_mem;
+  CVSpilsMem cvspils_mem;
+  int retval;
+
+  cv_mem = (CVodeMem) cvode_mem;
+  cvspils_mem = (CVSpilsMem)lmem;
+
+  /* This call is counted in nps within the CVSp***Solve routine */
+  retval = psolve(tn, ycur, fcur, r, z, gamma, delta, lr, P_data, ytemp);
+
+  return(retval);     
+}
+
+/*
+ * -----------------------------------------------------------------
+ * CVSpilsDQJtimes
+ * -----------------------------------------------------------------
+ * This routine generates a difference quotient approximation to
+ * the Jacobian times vector f_y(t,y) * v. The approximation is 
+ * Jv = vnrm[f(y + v/vnrm) - f(y)], where vnrm = (WRMS norm of v) is
+ * input, i.e. the WRMS norm of v/vnrm is 1.
+ * -----------------------------------------------------------------
+ */
+
+int CVSpilsDQJtimes(N_Vector v, N_Vector Jv, realtype t, 
+                    N_Vector y, N_Vector fy,
+                    void *jac_data, N_Vector work)
+{
+  CVodeMem cv_mem;
+  CVSpilsMem cvspils_mem;
+  realtype sig, siginv;
+  int iter, retval;
+
+  /* jac_data is cvode_mem */
+  cv_mem = (CVodeMem) jac_data;
+  cvspils_mem = (CVSpilsMem) lmem;
+
+  /* Initialize perturbation to 1/||v|| */
+  sig = ONE/N_VWrmsNorm(v, ewt);
+
+  for (iter=0; iter<MAX_ITERS; iter++) {
+
+    /* Set work = y + sig*v */
+    N_VLinearSum(sig, v, ONE, y, work);
+
+    /* Set Jv = f(tn, y+sig*v) */
+    retval = f(t, work, Jv, f_data); 
+    nfes++;
+    if (retval == 0) break;
+    if (retval < 0)  return(-1);
+
+    sig *= PT25;
+  }
+
+  if (retval > 0) return(+1);
+
+  /* Replace Jv by (Jv - fy)/sig */
+  siginv = ONE/sig;
+  N_VLinearSum(siginv, Jv, -siginv, fy, Jv);
+
+  return(0);
+}
+
+/* 
+ * ================================================================
+ *
+ *                   PART II - backward problems
+ *
+ * ================================================================
+ */
+
+/* Readability replacements */
+
+#define ytmp        (ca_mem->ca_ytmp)
+#define getY        (ca_mem->ca_getY)
+#define lmemB       (ca_mem->ca_lmemB)
+
+#define pset_B      (cvspilsB_mem->s_psetB)
+#define psolve_B    (cvspilsB_mem->s_psolveB)
+#define jtimes_B    (cvspilsB_mem->s_jtimesB)
+#define P_data_B    (cvspilsB_mem->s_P_dataB)
+#define jac_data_B  (cvspilsB_mem->s_jac_dataB)
+
+/*
+ * -----------------------------------------------------------------
+ * OPTIONAL INPUT and OUTPUT FUNCTIONS
+ * -----------------------------------------------------------------
+ */
+
+int CVSpilsSetPrecTypeB(void *cvadj_mem, int pretypeB)
+{
+  CVadjMem ca_mem;
+  CVodeMem cvB_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CVSPILS_ADJMEM_NULL, "CVSPILS", "CVSpilsSetPrecTypeB", MSGS_CAMEM_NULL);
+    return(CVSPILS_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  cvB_mem = ca_mem->cvb_mem;
+
+  flag = CVSpilsSetPrecType(cvB_mem, pretypeB);
+
+  return(flag);
+}
+
+int CVSpilsSetGSTypeB(void *cvadj_mem, int gstypeB)
+{
+  CVadjMem ca_mem;
+  CVodeMem cvB_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CVSPILS_ADJMEM_NULL, "CVSPILS", "CVSpilsSetGSTypeB", MSGS_CAMEM_NULL);
+    return(CVSPILS_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  cvB_mem = ca_mem->cvb_mem;
+
+  flag = CVSpilsSetGSType(cvB_mem,gstypeB);
+
+  return(flag);
+}
+
+int CVSpilsSetDeltB(void *cvadj_mem, realtype deltB)
+{
+  CVadjMem ca_mem;
+  CVodeMem cvB_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CVSPILS_ADJMEM_NULL, "CVSPILS", "CVSpilsSetDeltB", MSGS_CAMEM_NULL);
+    return(CVSPILS_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  cvB_mem = ca_mem->cvb_mem;
+
+  flag = CVSpilsSetDelt(cvB_mem,deltB);
+
+  return(flag);
+}
+
+int CVSpilsSetMaxlB(void *cvadj_mem, int maxlB)
+{
+  CVadjMem ca_mem;
+  CVodeMem cvB_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CVSPILS_ADJMEM_NULL, "CVSPILS", "CVSpilsSetMaxlB", MSGS_CAMEM_NULL);
+    return(CVSPILS_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  cvB_mem = ca_mem->cvb_mem;
+
+  flag = CVSpilsSetMaxl(cvB_mem,maxlB);
+
+  return(flag);
+}
+
+int CVSpilsSetPreconditionerB(void *cvadj_mem, CVSpilsPrecSetupFnB psetB,
+                              CVSpilsPrecSolveFnB psolveB, void *P_dataB)
+{
+  CVadjMem ca_mem;
+  CVSpilsMemB cvspilsB_mem; 
+  CVodeMem cvB_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CVSPILS_ADJMEM_NULL, "CVSPILS", "CVSpilsSetPreconditionerB", MSGS_CAMEM_NULL);
+    return(CVSPILS_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  cvB_mem = ca_mem->cvb_mem;
+
+  if (lmemB == NULL) {
+    CVProcessError(cvB_mem, CVSPILS_LMEMB_NULL, "CVSPILS", "CVSpilsSetPreconditonerB", MSGS_LMEMB_NULL);
+    return(CVSPILS_LMEMB_NULL);
+  }
+  cvspilsB_mem = (CVSpilsMemB) lmemB;
+
+  pset_B   = psetB;
+  psolve_B = psolveB;
+  P_data_B = P_dataB;
+
+  flag = CVSpilsSetPreconditioner(cvB_mem, CVAspilsPrecSetup, CVAspilsPrecSolve, cvadj_mem);
+
+  return(flag);
+}
+
+int CVSpilsSetJacTimesVecFnB(void *cvadj_mem, CVSpilsJacTimesVecFnB jtimesB,
+                             void *jac_dataB)
+{
+  CVadjMem ca_mem;
+  CVSpilsMemB cvspilsB_mem; 
+  CVodeMem cvB_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CVSPILS_ADJMEM_NULL, "CVSPILS", "CVSpilsSetJacTimesVecFnB", MSGS_CAMEM_NULL);
+    return(CVSPILS_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  cvB_mem = ca_mem->cvb_mem;
+
+  if (lmemB == NULL) {
+    CVProcessError(cvB_mem, CVSPILS_LMEMB_NULL, "CVSPILS", "CVSpilsSetJacTimesVecFnB", MSGS_LMEMB_NULL);
+    return(CVSPILS_LMEMB_NULL);
+  }
+  cvspilsB_mem = (CVSpilsMemB) lmemB;
+
+  jtimes_B   = jtimesB;
+  jac_data_B = jac_dataB;
+
+  flag = CVSpilsSetJacTimesVecFn(cvB_mem, CVAspilsJacTimesVec, cvadj_mem);
+
+  return(flag);
+}
+
+
+/*
+ * -----------------------------------------------------------------
+ * CVSPILS private functions
+ * -----------------------------------------------------------------
+ */
+
+/*
+ * CVAspilsPrecSetup
+ *
+ * This routine interfaces to the CVSpilsPrecSetupFnB routine 
+ * provided by the user.
+ * NOTE: p_data actually contains cvadj_mem
+ */
+
+int CVAspilsPrecSetup(realtype t, N_Vector yB, 
+                      N_Vector fyB, booleantype jokB, 
+                      booleantype *jcurPtrB, realtype gammaB,
+                      void *cvadj_mem,
+                      N_Vector tmp1B, N_Vector tmp2B, N_Vector tmp3B)
+{
+  CVadjMem ca_mem;
+  CVodeMem cvB_mem;
+  CVSpilsMemB cvspilsB_mem;
+  int retval, flag;
+
+  ca_mem = (CVadjMem) cvadj_mem;
+  cvB_mem = ca_mem->cvb_mem;
+  cvspilsB_mem = (CVSpilsMemB) lmemB;
+
+  /* Forward solution from interpolation */
+  flag = getY(ca_mem, t, ytmp);
+  if (flag != CV_SUCCESS) {
+    CVProcessError(cvB_mem, -1, "CVSPILS", "CVAspilsPrecSetup", MSGS_BAD_T);
+    return(-1);
+  } 
+
+  /* Call user's adjoint precondB routine */
+  retval = pset_B(t, ytmp, yB, fyB, jokB, jcurPtrB, gammaB,
+                  P_data_B, tmp1B, tmp2B, tmp3B);
+
+  return(retval);
+}
+
+
+/*
+ * CVAspilsPrecSolve
+ *
+ * This routine interfaces to the CVSpilsPrecSolveFnB routine 
+ * provided by the user.
+ * NOTE: p_data actually contains cvadj_mem
+ */
+
+int CVAspilsPrecSolve(realtype t, N_Vector yB, N_Vector fyB,
+                      N_Vector rB, N_Vector zB,
+                      realtype gammaB, realtype deltaB,
+                      int lrB, void *cvadj_mem, N_Vector tmpB)
+{
+  CVadjMem ca_mem;
+  CVodeMem cvB_mem;
+  CVSpilsMemB cvspilsB_mem;
+  int retval, flag;
+
+  ca_mem = (CVadjMem) cvadj_mem;
+  cvB_mem = ca_mem->cvb_mem;
+  cvspilsB_mem = (CVSpilsMemB) lmemB;
+
+  /* Forward solution from interpolation */
+  flag = getY(ca_mem, t, ytmp);
+  if (flag != CV_SUCCESS) {
+    CVProcessError(cvB_mem, -1, "CVSPILS", "CVAspilsPrecSolve", MSGS_BAD_T);
+    return(-1);
+  }
+
+  /* Call user's adjoint psolveB routine */
+  retval = psolve_B(t, ytmp, yB, fyB, rB, zB, gammaB, deltaB, 
+                    lrB, P_data_B, tmpB);
+
+  return(retval);
+}
+
+
+/*
+ * CVAspilsJacTimesVec
+ *
+ * This routine interfaces to the CVSpilsJacTimesVecFnB routine 
+ * provided by the user.
+ * NOTE: jac_data actually contains cvadj_mem
+ */
+
+int CVAspilsJacTimesVec(N_Vector vB, N_Vector JvB, realtype t, 
+                        N_Vector yB, N_Vector fyB, 
+                        void *cvadj_mem, N_Vector tmpB)
+{
+  CVadjMem ca_mem;
+  CVodeMem cvB_mem;
+  CVSpilsMemB cvspilsB_mem;
+  int retval, flag;
+
+  ca_mem = (CVadjMem) cvadj_mem;
+  cvB_mem = ca_mem->cvb_mem;
+  cvspilsB_mem = (CVSpilsMemB) lmemB;
+
+  /* Forward solution from interpolation */
+  flag = getY(ca_mem, t, ytmp);
+  if (flag != CV_SUCCESS) {
+    CVProcessError(cvB_mem, -1, "CVSPILS", "CVAspilsJacTimesVec", MSGS_BAD_T);
+    return(-1);
+  } 
+
+  /* Call user's adjoint jtimesB routine */
+  retval = jtimes_B(vB, JvB, t, ytmp, yB, fyB, jac_data_B, tmpB);
+
+  return(retval);
+}
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_spils_impl.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_spils_impl.h
new file mode 100644
index 0000000000000000000000000000000000000000..2f6f7058de19decd4222622c9cfada5fc186dae5
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_spils_impl.h
@@ -0,0 +1,212 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2005, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * Common implementation header file for the scaled, preconditioned
+ * iterative linear solvers
+ * -----------------------------------------------------------------
+ */
+
+#ifndef _CVSSPILS_IMPL_H
+#define _CVSSPILS_IMPL_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#include <cvodes/cvodes_spils.h>
+
+  /* Types of iterative linear solvers */
+
+#define SPILS_SPGMR   1
+#define SPILS_SPBCG   2
+#define SPILS_SPTFQMR 3
+
+
+  /* 
+   * -----------------------------------------------------------------
+   * PART I - forward problems
+   * -----------------------------------------------------------------
+   */
+
+  /*
+   * -----------------------------------------------------------------
+   * Types : CVSpilsMemRec, CVSpilsMem
+   * -----------------------------------------------------------------
+   * The type CVSpilsMem is pointer to a CVSpilsMemRec.
+   * -----------------------------------------------------------------
+   */
+
+  typedef struct {
+
+    int s_type;           /* type of scaled preconditioned iterative LS   */
+
+    int  s_pretype;       /* type of preconditioning                      */
+    int  s_gstype;        /* type of Gram-Schmidt orthogonalization       */
+    realtype s_sqrtN;     /* sqrt(N)                                      */
+    realtype s_delt;      /* delt = user specified or DELT_DEFAULT        */
+    realtype s_deltar;    /* deltar = delt * tq4                          */
+    realtype s_delta;     /* delta = deltar * sqrtN                       */
+    int  s_maxl;          /* maxl = maximum dimension of the Krylov space */
+
+    long int s_nstlpre;   /* value of nst at the last pset call           */
+    long int s_npe;       /* npe = total number of pset calls             */
+    long int s_nli;       /* nli = total number of linear iterations      */
+    long int s_nps;       /* nps = total number of psolve calls           */
+    long int s_ncfl;      /* ncfl = total number of convergence failures  */
+    long int s_njtimes;   /* njtimes = total number of calls to jtimes    */
+    long int s_nfes;      /* nfeSG = total number of calls to f for     
+                             difference quotient Jacobian-vector products */
+
+    N_Vector s_ytemp;     /* temp vector passed to jtimes and psolve      */
+    N_Vector s_x;         /* temp vector used by CVSpilsSolve             */
+    N_Vector s_ycur;      /* CVODE current y vector in Newton Iteration   */
+    N_Vector s_fcur;      /* fcur = f(tn, ycur)                           */
+
+    CVSpilsPrecSetupFn s_pset; 
+    /* pset = user-supplied routine to compute      */
+    /* a preconditioner                             */
+
+    CVSpilsPrecSolveFn s_psolve;   
+    /* psolve = user-supplied routine to solve      */
+    /* preconditioner linear system                 */
+
+    void *s_P_data;       /* P_data passed to psolve and pset             */
+
+    void* s_spils_mem;    /* memory used by the generic solver            */
+
+    CVSpilsJacTimesVecFn s_jtimes;  
+    /* jtimes = Jacobian * vector routine           */
+    void *s_j_data;       /* j_data is passed to jtimes                   */
+
+    int s_last_flag;      /* last error flag returned by any function     */
+
+  } CVSpilsMemRec, *CVSpilsMem;
+
+  /*
+   * -----------------------------------------------------------------
+   * Prototypes of internal functions
+   * -----------------------------------------------------------------
+   */
+
+  /* Atimes and PSolve routines called by generic solver */
+
+  int CVSpilsAtimes(void *cv_mem, N_Vector v, N_Vector z);
+
+  int CVSpilsPSolve(void *cv_mem, N_Vector r, N_Vector z, int lr);
+
+  /* Difference quotient approximation for Jac times vector */
+
+  int CVSpilsDQJtimes(N_Vector v, N_Vector Jv, realtype t,
+                      N_Vector y, N_Vector fy, void *jac_data,
+                      N_Vector work);
+
+
+  /*
+   * -----------------------------------------------------------------
+   * Error Messages
+   * -----------------------------------------------------------------
+   */
+
+#define MSGS_CVMEM_NULL  "Integrator memory is NULL."
+#define MSGS_MEM_FAIL    "A memory request failed."
+#define MSGS_BAD_NVECTOR "A required vector operation is not implemented."
+#define MSGS_BAD_LSTYPE  "Incompatible linear solver type."
+#define MSGS_BAD_PRETYPE "Illegal value for pretype. Legal values are PREC_NONE, PREC_LEFT, PREC_RIGHT, and PREC_BOTH."
+#define MSGS_PSOLVE_REQ  "pretype != PREC_NONE, but PSOLVE = NULL is illegal."
+#define MSGS_LMEM_NULL   "Linear solver memory is NULL."
+#define MSGS_BAD_GSTYPE  "Illegal value for gstype. Legal values are MODIFIED_GS and CLASSICAL_GS."
+#define MSGS_BAD_DELT    "delt < 0 illegal."
+  
+#define MSGS_PSET_FAILED "The preconditioner setup routine failed in an unrecoverable manner."
+#define MSGS_PSOLVE_FAILED "The preconditioner solve routine failed in an unrecoverable manner."
+#define MSGS_JTIMES_FAILED "The Jacobian x vector routine failed in an unrecoverable manner."
+
+
+  /* 
+   * -----------------------------------------------------------------
+   * PART II - backward problems
+   * -----------------------------------------------------------------
+   */
+
+  /*
+   * -----------------------------------------------------------------
+   * Types : CVSpilsMemRecB, CVSpilsMemB       
+   * -----------------------------------------------------------------
+   * CVSpgmrB, CVSpbcgB, and CVSptfqmr attach such a structure to the 
+   * lmemB filed of CVadjMem
+   * -----------------------------------------------------------------
+   */
+
+  typedef struct {
+
+    CVSpilsJacTimesVecFnB s_jtimesB;
+    CVSpilsPrecSetupFnB s_psetB;
+    CVSpilsPrecSolveFnB s_psolveB;
+    void *s_P_dataB;
+    void *s_jac_dataB;
+
+  } CVSpilsMemRecB, *CVSpilsMemB;
+
+
+  /*
+   * ------------------------------------------------
+   * Wrapper functions for using the iterative linear 
+   * solvers on adjoint (backward) problems
+   * ------------------------------------------------
+   */
+
+  /* 
+   * CVAspilsPrecSetup has type CVSpilsPrecSetupFn
+   * It wraps around the user-provided function of type CVSpilsPrecSetupFnB
+   */
+
+  int CVAspilsPrecSetup(realtype t, N_Vector yB, 
+                        N_Vector fyB, booleantype jokB, 
+                        booleantype *jcurPtrB, realtype gammaB,
+                        void *cvadj_mem,
+                        N_Vector tmp1B, N_Vector tmp2B, N_Vector tmp3B);
+
+  /* 
+   * CVAspilsPrecSolve has type CVSpilsPrecSolveFn 
+   * It wraps around the user-provided function of type CVSpilsPrecSolveFnB
+   */
+
+  int CVAspilsPrecSolve(realtype t, N_Vector yB, N_Vector fyB,
+                        N_Vector rB, N_Vector zB,
+                        realtype gammaB, realtype deltaB,
+                        int lrB, void *cvadj_mem, N_Vector tmpB);
+  
+  /* 
+   * CVAspilsJacTimesVec has type CVSpilsJacTimesVecFn 
+   * It wraps around the user-provided function of type CVSpilsJacTimesVecFnB
+   */
+
+  int CVAspilsJacTimesVec(N_Vector vB, N_Vector JvB, realtype t, 
+                          N_Vector yB, N_Vector fyB, 
+                          void *cvadj_mem, N_Vector tmpB);
+
+  /*
+   * -----------------------------------------------------------------
+   * Error Messages 
+   * -----------------------------------------------------------------
+   */
+
+#define MSGS_CAMEM_NULL "cvadj_mem = NULL illegal."
+#define MSGS_LMEMB_NULL "Linear solver memory is NULL for the backward integration."
+#define MSGS_BAD_T      "Bad t for interpolation."
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_sptfqmr.c b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_sptfqmr.c
new file mode 100644
index 0000000000000000000000000000000000000000..ea1efd1e1c25c82b377f8050eb79d7802dc8df34
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/cvodes_sptfqmr.c
@@ -0,0 +1,547 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Aaron Collier and Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2005, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the implementation file for the CVSPTFQMR linear solver.
+ * -----------------------------------------------------------------
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <cvodes/cvodes_sptfqmr.h>
+#include "cvodes_spils_impl.h"
+#include "cvodes_impl.h"
+
+#include <sundials/sundials_sptfqmr.h>
+#include <sundials/sundials_math.h>
+
+/* Constants */
+
+#define ZERO RCONST(0.0)
+#define ONE  RCONST(1.0)
+
+/* CVSPTFQMR linit, lsetup, lsolve, and lfree routines */
+
+static int CVSptfqmrInit(CVodeMem cv_mem);
+
+static int CVSptfqmrSetup(CVodeMem cv_mem, int convfail, N_Vector ypred,
+			  N_Vector fpred, booleantype *jcurPtr, N_Vector vtemp1,
+			  N_Vector vtemp2, N_Vector vtemp3);
+
+static int CVSptfqmrSolve(CVodeMem cv_mem, N_Vector b, N_Vector weight,
+			  N_Vector ynow, N_Vector fnow);
+
+static void CVSptfqmrFree(CVodeMem cv_mem);
+
+/* CVSPTFQMR lfreeB function */
+
+static void CVSptfqmrFreeB(CVadjMem ca_mem);
+
+/* 
+ * ================================================================
+ *
+ *                   PART I - forward problems
+ *
+ * ================================================================
+ */
+
+/* Readability Replacements */
+
+#define tq           (cv_mem->cv_tq)
+#define nst          (cv_mem->cv_nst)
+#define tn           (cv_mem->cv_tn)
+#define gamma        (cv_mem->cv_gamma)
+#define gammap       (cv_mem->cv_gammap)
+#define f            (cv_mem->cv_f)
+#define f_data       (cv_mem->cv_f_data)
+#define ewt          (cv_mem->cv_ewt)
+#define errfp        (cv_mem->cv_errfp)
+#define mnewt        (cv_mem->cv_mnewt)
+#define linit        (cv_mem->cv_linit)
+#define lsetup       (cv_mem->cv_lsetup)
+#define lsolve       (cv_mem->cv_lsolve)
+#define lfree        (cv_mem->cv_lfree)
+#define lmem         (cv_mem->cv_lmem)
+#define vec_tmpl     (cv_mem->cv_tempv)
+#define setupNonNull (cv_mem->cv_setupNonNull)
+
+#define sqrtN       (cvspils_mem->s_sqrtN)   
+#define ytemp       (cvspils_mem->s_ytemp)
+#define x           (cvspils_mem->s_x)
+#define ycur        (cvspils_mem->s_ycur)
+#define fcur        (cvspils_mem->s_fcur)
+#define delta       (cvspils_mem->s_delta)
+#define deltar      (cvspils_mem->s_deltar)
+#define npe         (cvspils_mem->s_npe)
+#define nli         (cvspils_mem->s_nli)
+#define nps         (cvspils_mem->s_nps)
+#define ncfl        (cvspils_mem->s_ncfl)
+#define nstlpre     (cvspils_mem->s_nstlpre)
+#define njtimes     (cvspils_mem->s_njtimes)
+#define nfes        (cvspils_mem->s_nfes)
+#define spils_mem   (cvspils_mem->s_spils_mem)
+#define last_flag   (cvspils_mem->s_last_flag)
+
+/*
+ * -----------------------------------------------------------------
+ * Function : CVSptfqmr
+ * -----------------------------------------------------------------
+ * This routine initializes the memory record and sets various function
+ * fields specific to the Sptfqmr linear solver module. CVSptfqmr first
+ * calls the existing lfree routine if this is not NULL. It then sets
+ * the cv_linit, cv_lsetup, cv_lsolve, cv_lfree fields in (*cvode_mem)
+ * to be CVSptfqmrInit, CVSptfqmrSetup, CVSptfqmrSolve, and CVSptfqmrFree,
+ * respectively. It allocates memory for a structure of type
+ * CVSpilsMemRec and sets the cv_lmem field in (*cvode_mem) to the
+ * address of this structure. It sets setupNonNull in (*cvode_mem),
+ * and sets the following fields in the CVSpilsMemRec structure:
+ *
+ *   s_pretype   = pretype
+ *   s_maxl      = CVSPILS_MAXL  if maxl <= 0
+ *               = maxl          if maxl >  0
+ *   s_delt      = CVSPILS_DELT
+ *   s_P_data    = NULL
+ *   s_pset      = NULL
+ *   s_psolve    = NULL
+ *   s_jtimes    = CVSpilsDQJtimes
+ *   s_j_data    = cvode_mem
+ *   s_last_flag = CVSPILS_SUCCESS
+ *
+ * Finally, CVSptfqmr allocates memory for ytemp and x, and calls
+ * SptfqmrMalloc to allocate memory for the Sptfqmr solver.
+ * -----------------------------------------------------------------
+ */
+
+int CVSptfqmr(void *cvode_mem, int pretype, int maxl)
+{
+  CVodeMem cv_mem;
+  CVSpilsMem cvspils_mem;
+  SptfqmrMem sptfqmr_mem;
+  int mxl;
+
+  /* Return immediately if cvode_mem is NULL */
+  if (cvode_mem == NULL) {
+    CVProcessError(NULL, CVSPILS_MEM_NULL, "CVSPTFQMR", "CVSptfqmr", MSGS_CVMEM_NULL);
+    return(CVSPILS_MEM_NULL);
+  }
+  cv_mem = (CVodeMem) cvode_mem;
+
+  /* Check if N_VDotProd is present */
+  if (vec_tmpl->ops->nvdotprod == NULL) {
+    CVProcessError(cv_mem, CVSPILS_ILL_INPUT, "CVSPTFQMR", "CVSptfqmr", MSGS_BAD_NVECTOR);
+    return(CVSPILS_ILL_INPUT);
+  }
+
+  if (lfree != NULL) lfree(cv_mem);
+
+  /* Set four main function fields in cv_mem */
+  linit  = CVSptfqmrInit;
+  lsetup = CVSptfqmrSetup;
+  lsolve = CVSptfqmrSolve;
+  lfree  = CVSptfqmrFree;
+
+  /* Get memory for CVSpilsMemRec */
+  cvspils_mem = NULL;
+  cvspils_mem = (CVSpilsMem) malloc(sizeof(CVSpilsMemRec));
+  if (cvspils_mem == NULL) {
+    CVProcessError(cv_mem, CVSPILS_MEM_FAIL, "CVSPTFQMR", "CVSptfqmr", MSGS_MEM_FAIL);
+    return(CVSPILS_MEM_FAIL);
+  }
+
+  /* Set ILS type */
+  cvspils_mem->s_type = SPILS_SPTFQMR;
+
+  /* Set Sptfqmr parameters that have been passed in call sequence */
+  cvspils_mem->s_pretype = pretype;
+  mxl = cvspils_mem->s_maxl = (maxl <= 0) ? CVSPILS_MAXL : maxl;
+
+  /* Set default values for the rest of the Sptfqmr parameters */
+  cvspils_mem->s_delt      = CVSPILS_DELT;
+  cvspils_mem->s_P_data    = NULL;
+  cvspils_mem->s_pset      = NULL;
+  cvspils_mem->s_psolve    = NULL;
+  cvspils_mem->s_jtimes    = CVSpilsDQJtimes;
+  cvspils_mem->s_j_data    = cvode_mem;
+  cvspils_mem->s_last_flag = CVSPILS_SUCCESS;
+
+  setupNonNull = FALSE;
+
+  /* Check for legal pretype */ 
+  if ((pretype != PREC_NONE) && (pretype != PREC_LEFT) &&
+      (pretype != PREC_RIGHT) && (pretype != PREC_BOTH)) {
+    CVProcessError(cv_mem, CVSPILS_ILL_INPUT, "CVSPTFQMR", "CVSptfqmr", MSGS_BAD_PRETYPE);
+    return(CVSPILS_ILL_INPUT);
+  }
+
+  /* Allocate memory for ytemp and x */
+  ytemp = NULL;
+  ytemp = N_VClone(vec_tmpl);
+  if (ytemp == NULL) {
+    CVProcessError(cv_mem, CVSPILS_MEM_FAIL, "CVSPTFQMR", "CVSptfqmr", MSGS_MEM_FAIL);
+    free(cvspils_mem); cvspils_mem = NULL;
+    return(CVSPILS_MEM_FAIL);
+  }
+  x = NULL;
+  x = N_VClone(vec_tmpl);
+  if (x == NULL) {
+    CVProcessError(cv_mem, CVSPILS_MEM_FAIL, "CVSPTFQMR", "CVSptfqmr", MSGS_MEM_FAIL);
+    N_VDestroy(ytemp);
+    free(cvspils_mem); cvspils_mem = NULL;
+    return(CVSPILS_MEM_FAIL);
+  }
+
+  /* Compute sqrtN from a dot product */
+  N_VConst(ONE, ytemp);
+  sqrtN = RSqrt(N_VDotProd(ytemp, ytemp));
+
+  /* Call SptfqmrMalloc to allocate workspace for Sptfqmr */
+  sptfqmr_mem = NULL;
+  sptfqmr_mem = SptfqmrMalloc(mxl, vec_tmpl);
+  if (sptfqmr_mem == NULL) {
+    CVProcessError(cv_mem, CVSPILS_MEM_FAIL, "CVSPTFQMR", "CVSptfqmr", MSGS_MEM_FAIL);
+    N_VDestroy(ytemp);
+    N_VDestroy(x);
+    free(cvspils_mem); cvspils_mem = NULL;
+    return(CVSPILS_MEM_FAIL);
+  }
+  
+  /* Attach SPTFQMR memory to spils memory structure */
+  spils_mem = (void *) sptfqmr_mem;
+
+  /* Attach linear solver memory to integrator memory */
+  lmem = cvspils_mem;
+
+  return(CVSPILS_SUCCESS);
+}
+
+/* Additional readability replacements */
+
+#define pretype (cvspils_mem->s_pretype)
+#define delt    (cvspils_mem->s_delt)
+#define maxl    (cvspils_mem->s_maxl)
+#define psolve  (cvspils_mem->s_psolve)
+#define pset    (cvspils_mem->s_pset)
+#define P_data  (cvspils_mem->s_P_data)
+#define jtimes  (cvspils_mem->s_jtimes)
+#define j_data  (cvspils_mem->s_j_data)
+
+/*
+ * -----------------------------------------------------------------
+ * Function : CVSptfqmrInit
+ * -----------------------------------------------------------------
+ * This routine does remaining initializations specific to the Sptfqmr
+ * linear solver.
+ * -----------------------------------------------------------------
+ */
+
+static int CVSptfqmrInit(CVodeMem cv_mem)
+{
+  CVSpilsMem cvspils_mem;
+  SptfqmrMem sptfqmr_mem;
+
+  cvspils_mem = (CVSpilsMem) lmem;
+  sptfqmr_mem = (SptfqmrMem) spils_mem;
+
+  /* Initialize counters */
+  npe = nli = nps = ncfl = nstlpre = 0;
+  njtimes = nfes = 0;
+
+  /* Check for legal combination pretype - psolve */
+  if ((pretype != PREC_NONE) && (psolve == NULL)) {
+    CVProcessError(cv_mem, -1, "CVSPTFQMR", "CVSptfqmrInit", MSGS_PSOLVE_REQ);
+    last_flag = CVSPILS_ILL_INPUT;
+    return(-1);
+  }
+
+  /* Set setupNonNull = TRUE iff there is preconditioning
+     (pretype != PREC_NONE)  and there is a preconditioning
+     setup phase (pset != NULL) */
+  setupNonNull = (pretype != PREC_NONE) && (pset != NULL);
+
+  /* If jtimes is NULL at this time, set it to DQ */
+  if (jtimes == NULL) {
+    jtimes = CVSpilsDQJtimes;
+    j_data = cv_mem;
+  }
+
+  /*  Set maxl in the SPTFQMR memory in case it was changed by the user */
+  sptfqmr_mem->l_max  = maxl;
+
+  last_flag = CVSPILS_SUCCESS;
+  return(0);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * Function : CVSptfqmrSetup
+ * -----------------------------------------------------------------
+ * This routine does the setup operations for the Sptfqmr linear solver.
+ * It makes a decision as to whether or not to signal for reevaluation
+ * of Jacobian data in the pset routine, based on various state
+ * variables, then it calls pset. If we signal for reevaluation,
+ * then we reset jcur = *jcurPtr to TRUE, regardless of the pset output.
+ * In any case, if jcur == TRUE, we increment npe and save nst in nstlpre.
+ * -----------------------------------------------------------------
+ */
+
+static int CVSptfqmrSetup(CVodeMem cv_mem, int convfail, N_Vector ypred,
+			  N_Vector fpred, booleantype *jcurPtr, N_Vector vtemp1,
+			  N_Vector vtemp2, N_Vector vtemp3)
+{
+  booleantype jbad, jok;
+  realtype dgamma;
+  int  retval;
+  CVSpilsMem cvspils_mem;
+
+  cvspils_mem = (CVSpilsMem) lmem;
+
+  /* Use nst, gamma/gammap, and convfail to set J eval. flag jok */
+  dgamma = ABS((gamma/gammap) - ONE);
+  jbad = (nst == 0) || (nst > nstlpre + CVSPILS_MSBPRE) ||
+      ((convfail == CV_FAIL_BAD_J) && (dgamma < CVSPILS_DGMAX)) ||
+      (convfail == CV_FAIL_OTHER);
+  *jcurPtr = jbad;
+  jok = !jbad;
+
+  /* Call pset routine and possibly reset jcur */
+  retval = pset(tn, ypred, fpred, jok, jcurPtr, gamma, P_data, 
+                vtemp1, vtemp2, vtemp3);
+  if (retval < 0) {
+    CVProcessError(cv_mem, SPTFQMR_PSET_FAIL_UNREC, "CVSPTFQMR", "CVSptfqmrSetup", MSGS_PSET_FAILED);
+    last_flag = SPTFQMR_PSET_FAIL_UNREC;
+  }
+  if (retval > 0) {
+    last_flag = SPTFQMR_PSET_FAIL_REC;
+  }
+
+  if (jbad) *jcurPtr = TRUE;
+
+  /* If jcur = TRUE, increment npe and save nst value */
+  if (*jcurPtr) {
+    npe++;
+    nstlpre = nst;
+  }
+
+  last_flag = SPTFQMR_SUCCESS;
+
+  /* Return the same value that pset returned */
+  return(retval);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * Function : CVSptfqmrSolve
+ * -----------------------------------------------------------------
+ * This routine handles the call to the generic solver SptfqmrSolve
+ * for the solution of the linear system Ax = b with the SPTFQMR method.
+ * The solution x is returned in the vector b.
+ *
+ * If the WRMS norm of b is small, we return x = b (if this is the first
+ * Newton iteration) or x = 0 (if a later Newton iteration).
+ *
+ * Otherwise, we set the tolerance parameter and initial guess (x = 0),
+ * call SptfqmrSolve, and copy the solution x into b. The x-scaling and
+ * b-scaling arrays are both equal to weight.
+ *
+ * The counters nli, nps, and ncfl are incremented, and the return value
+ * is set according to the success of SptfqmrSolve. The success flag is
+ * returned if SptfqmrSolve converged, or if this is the first Newton
+ * iteration and the residual norm was reduced below its initial value.
+ * -----------------------------------------------------------------
+ */
+
+static int CVSptfqmrSolve(CVodeMem cv_mem, N_Vector b, N_Vector weight,
+			  N_Vector ynow, N_Vector fnow)
+{
+  realtype bnorm, res_norm;
+  CVSpilsMem cvspils_mem;
+  SptfqmrMem sptfqmr_mem;
+  int nli_inc, nps_inc, retval;
+  
+  cvspils_mem = (CVSpilsMem) lmem;
+
+  sptfqmr_mem = (SptfqmrMem) spils_mem;
+
+  /* Test norm(b); if small, return x = 0 or x = b */
+  deltar = delt * tq[4]; 
+
+  bnorm = N_VWrmsNorm(b, weight);
+  if (bnorm <= deltar) {
+    if (mnewt > 0) N_VConst(ZERO, b); 
+    return(0);
+  }
+
+  /* Set vectors ycur and fcur for use by the Atimes and Psolve routines */
+  ycur = ynow;
+  fcur = fnow;
+
+  /* Set inputs delta and initial guess x = 0 to SptfqmrSolve */  
+  delta = deltar * sqrtN;
+  N_VConst(ZERO, x);
+  
+  /* Call SptfqmrSolve and copy x to b */
+  retval = SptfqmrSolve(sptfqmr_mem, cv_mem, x, b, pretype, delta,
+                        cv_mem, weight, weight, CVSpilsAtimes, CVSpilsPSolve,
+                        &res_norm, &nli_inc, &nps_inc);
+
+  N_VScale(ONE, x, b);
+  
+  /* Increment counters nli, nps, and ncfl */
+  nli += nli_inc;
+  nps += nps_inc;
+  if (retval != SPTFQMR_SUCCESS) ncfl++;
+
+  /* Interpret return value from SpgmrSolve */
+
+  last_flag = retval;
+
+  switch(retval) {
+
+  case SPTFQMR_SUCCESS:
+    return(0);
+    break;
+  case SPTFQMR_RES_REDUCED:
+    if (mnewt == 0) return(0);
+    else            return(1);
+    break;
+  case SPTFQMR_CONV_FAIL:
+    return(1);
+    break;
+  case SPTFQMR_PSOLVE_FAIL_REC:
+    return(1);
+    break;
+  case SPTFQMR_ATIMES_FAIL_REC:
+    return(1);
+    break;
+  case SPTFQMR_MEM_NULL:
+    return(-1);
+    break;
+  case SPTFQMR_ATIMES_FAIL_UNREC:
+    CVProcessError(cv_mem, SPTFQMR_ATIMES_FAIL_UNREC, "CVSPTFQMR", "CVSptfqmrSolve", MSGS_JTIMES_FAILED);    
+    return(-1);
+    break;
+  case SPTFQMR_PSOLVE_FAIL_UNREC:
+    CVProcessError(cv_mem, SPTFQMR_PSOLVE_FAIL_UNREC, "CVSPTFQMR", "CVSptfqmrSolve", MSGS_PSOLVE_FAILED);
+    return(-1);
+    break;
+  }
+
+  return(0);  
+
+}
+
+/*
+ * -----------------------------------------------------------------
+ * Function : CVSptfqmrFree
+ * -----------------------------------------------------------------
+ * This routine frees memory specific to the Sptfqmr linear solver.
+ * -----------------------------------------------------------------
+ */
+
+static void CVSptfqmrFree(CVodeMem cv_mem)
+{
+  CVSpilsMem cvspils_mem;
+  SptfqmrMem sptfqmr_mem;
+    
+  cvspils_mem = (CVSpilsMem) lmem;
+
+  sptfqmr_mem = (SptfqmrMem) spils_mem;
+
+  N_VDestroy(ytemp);
+  N_VDestroy(x);
+  SptfqmrFree(sptfqmr_mem);
+  free(cvspils_mem); cvspils_mem = NULL;
+
+  return;
+}
+
+/* 
+ * ================================================================
+ *
+ *                   PART II - backward problems
+ *
+ * ================================================================
+ */
+      
+/* Additional readability replacements */
+
+#define lmemB       (ca_mem->ca_lmemB)
+#define lfreeB      (ca_mem->ca_lfreeB)
+
+#define pset_B      (cvspilsB_mem->s_psetB)
+#define psolve_B    (cvspilsB_mem->s_psolveB)
+#define jtimes_B    (cvspilsB_mem->s_jtimesB)
+#define P_data_B    (cvspilsB_mem->s_P_dataB)
+#define jac_data_B  (cvspilsB_mem->s_jac_dataB)
+
+/*
+ * CVSptfqmrB
+ *
+ * Wrapper for the backward phase
+ */
+
+int CVSptfqmrB(void *cvadj_mem, int pretypeB, int maxlB)
+{
+  CVadjMem ca_mem;
+  CVSpilsMemB cvspilsB_mem;
+  CVodeMem cvB_mem;
+  int flag;
+
+  if (cvadj_mem == NULL) {
+    CVProcessError(NULL, CVSPILS_ADJMEM_NULL, "CVSPTFQMR", "CVSptfqmrB", MSGS_CAMEM_NULL);
+    return(CVSPILS_ADJMEM_NULL);
+  }
+  ca_mem = (CVadjMem) cvadj_mem;
+
+  cvB_mem = ca_mem->cvb_mem;
+  
+  /* Get memory for CVSpilsMemRecB */
+  cvspilsB_mem = NULL;
+  cvspilsB_mem = (CVSpilsMemB) malloc(sizeof(CVSpilsMemRecB));
+  if (cvspilsB_mem == NULL) {
+    CVProcessError(cvB_mem, CVSPILS_MEM_FAIL, "CVSPTFQMR", "CVSptfqmrB", MSGS_MEM_FAIL);
+    return(CVSPILS_MEM_FAIL);
+  }
+
+  pset_B = NULL;
+  psolve_B = NULL;
+  jtimes_B = NULL;
+  P_data_B = NULL;
+  jac_data_B = NULL;
+
+  /* attach lmemB and lfreeB */
+  lmemB = cvspilsB_mem;
+  lfreeB = CVSptfqmrFreeB;
+
+  flag = CVSptfqmr(cvB_mem, pretypeB, maxlB);
+
+  if (flag != CVSPILS_SUCCESS) {
+    free(cvspilsB_mem); 
+    cvspilsB_mem = NULL;
+  }
+
+  return(flag);
+}
+
+/*
+ * CVSptfqmrFreeB 
+ */
+
+
+static void CVSptfqmrFreeB(CVadjMem ca_mem)
+{
+  CVSpilsMemB cvspilsB_mem;
+
+  cvspilsB_mem = (CVSpilsMemB) lmemB;
+
+  free(cvspilsB_mem);
+}
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/fnvector_parallel.c_does_not_need_to_be_compiled_for_SBT2 b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/fnvector_parallel.c_does_not_need_to_be_compiled_for_SBT2
new file mode 100644
index 0000000000000000000000000000000000000000..7ce300f72cece7d850703227e54dd35b151c735f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/fnvector_parallel.c_does_not_need_to_be_compiled_for_SBT2
@@ -0,0 +1,182 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2002, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This file (companion of nvector_parallel.h) contains the 
+ * implementation needed for the Fortran initialization of parallel 
+ * vector operations.
+ * -----------------------------------------------------------------
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "fnvector_parallel.h"
+
+/* Define global vector variables */
+
+N_Vector F2C_CVODE_vec;
+N_Vector F2C_CVODE_vecQ;
+N_Vector *F2C_CVODE_vecS;
+N_Vector F2C_CVODE_vecB;
+N_Vector F2C_CVODE_vecQB;
+
+N_Vector F2C_IDA_vec;
+N_Vector F2C_IDA_vecQ;
+N_Vector *F2C_IDA_vecS;
+N_Vector F2C_IDA_vecB;
+N_Vector F2C_IDA_vecQB;
+
+N_Vector F2C_KINSOL_vec;
+
+#ifndef SUNDIALS_MPI_COMM_F2C
+#define MPI_Fint int
+#endif
+
+/* Fortran callable interfaces */
+
+void FNV_INITP(MPI_Fint *comm, int *code, long int *L, long int *N, int *ier)
+{
+  MPI_Comm F2C_comm;
+
+#ifdef SUNDIALS_MPI_COMM_F2C
+  F2C_comm = MPI_Comm_f2c(*comm);
+#else
+  F2C_comm = MPI_COMM_WORLD;
+#endif
+
+  *ier = 0;
+
+  switch(*code) {
+  case FCMIX_CVODE:
+    F2C_CVODE_vec = NULL;
+    F2C_CVODE_vec = N_VNewEmpty_Parallel(F2C_comm, *L, *N);
+    if (F2C_CVODE_vec == NULL) *ier = -1;
+    break;
+  case FCMIX_IDA:
+    F2C_IDA_vec = NULL;
+    F2C_IDA_vec = N_VNewEmpty_Parallel(F2C_comm, *L, *N);
+    if (F2C_IDA_vec == NULL) *ier = -1;
+    break;
+  case FCMIX_KINSOL:
+    F2C_KINSOL_vec = NULL;
+    F2C_KINSOL_vec = N_VNewEmpty_Parallel(F2C_comm, *L, *N);
+    if (F2C_KINSOL_vec == NULL) *ier = -1;
+    break;
+  default:
+    *ier = -1;
+  }
+}
+
+void FNV_INITP_Q(MPI_Fint *comm, int *code, long int *Lq, long int *Nq, int *ier)
+{
+  MPI_Comm F2C_comm;
+
+#ifdef SUNDIALS_MPI_COMM_F2C
+  F2C_comm = MPI_Comm_f2c(*comm);
+#else
+  F2C_comm = MPI_COMM_WORLD;
+#endif
+
+  *ier = 0;
+
+  switch(*code) {
+  case FCMIX_CVODE:
+    F2C_CVODE_vecQ = NULL;
+    F2C_CVODE_vecQ = N_VNewEmpty_Parallel(F2C_comm, *Lq, *Nq);
+    if (F2C_CVODE_vecQ == NULL) *ier = -1;
+    break;
+  case FCMIX_IDA:
+    F2C_IDA_vecQ = NULL;
+    F2C_IDA_vecQ = N_VNewEmpty_Parallel(F2C_comm, *Lq, *Nq);
+    if (F2C_IDA_vecQ == NULL) *ier = -1;
+    break;
+  default:
+    *ier = -1;
+  }
+}
+
+void FNV_INITP_B(MPI_Fint *comm, int *code, long int *LB, long int *NB, int *ier)
+{
+  MPI_Comm F2C_comm;
+
+#ifdef SUNDIALS_MPI_COMM_F2C
+  F2C_comm = MPI_Comm_f2c(*comm);
+#else
+  F2C_comm = MPI_COMM_WORLD;
+#endif
+
+  *ier = 0;
+
+  switch(*code) {
+  case FCMIX_CVODE:
+    F2C_CVODE_vecB = NULL;
+    F2C_CVODE_vecB = N_VNewEmpty_Parallel(F2C_comm, *LB, *NB);
+    if (F2C_CVODE_vecB == NULL) *ier = -1;
+    break;
+  case FCMIX_IDA:
+    F2C_IDA_vecB = NULL;
+    F2C_IDA_vecB = N_VNewEmpty_Parallel(F2C_comm, *LB, *NB);
+    if (F2C_IDA_vecB == NULL) *ier = -1;
+    break;
+  default:
+    *ier = -1;
+  }
+}
+
+void FNV_INITP_QB(MPI_Fint *comm, int *code, long int *LqB, long int *NqB, int *ier)
+{
+  MPI_Comm F2C_comm;
+
+#ifdef SUNDIALS_MPI_COMM_F2C
+  F2C_comm = MPI_Comm_f2c(*comm);
+#else
+  F2C_comm = MPI_COMM_WORLD;
+#endif
+
+
+  *ier = 0;
+
+  switch(*code) {
+  case FCMIX_CVODE:
+    F2C_CVODE_vecQB = NULL;
+    F2C_CVODE_vecQB = N_VNewEmpty_Parallel(F2C_comm, *LqB, *NqB);
+    if (F2C_CVODE_vecQB == NULL) *ier = -1;
+    break;
+  case FCMIX_IDA:
+    F2C_IDA_vecQB = NULL;
+    F2C_IDA_vecQB = N_VNewEmpty_Parallel(F2C_comm, *LqB, *NqB);
+    if (F2C_IDA_vecQB == NULL) *ier = -1;
+    break;
+  default:
+    *ier = -1;
+  }
+}
+
+void FNV_INITP_S(int *code, int *Ns, int *ier)
+{
+  *ier = 0;
+
+  switch(*code) {
+  case FCMIX_CVODE:
+    F2C_CVODE_vecS = NULL;
+    F2C_CVODE_vecS = (N_Vector *) N_VCloneVectorArrayEmpty_Parallel(*Ns, F2C_CVODE_vec);
+    if (F2C_CVODE_vecS == NULL) *ier = -1;
+    break;
+  case FCMIX_IDA:
+    F2C_IDA_vecS = NULL;
+    F2C_IDA_vecS = (N_Vector *) N_VCloneVectorArrayEmpty_Parallel(*Ns, F2C_IDA_vec);
+    if (F2C_IDA_vecS == NULL) *ier = -1;
+    break;
+  default:
+    *ier = -1;
+  }
+}
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/fnvector_parallel.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/fnvector_parallel.h
new file mode 100644
index 0000000000000000000000000000000000000000..c90689bfe3fc954f4b2d2378be573a80a2174f6b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/fnvector_parallel.h
@@ -0,0 +1,128 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Radu Serban and Aaron Collier @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2002, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This file (companion of nvector_parallel.c) contains the
+ * definitions needed for the initialization of parallel
+ * vector operations in Fortran.
+ * -----------------------------------------------------------------
+ */
+
+#ifndef _FNVECTOR_PARALLEL_H
+#define _FNVECTOR_PARALLEL_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#include <nvector/nvector_parallel.h>  
+#include <sundials/sundials_fnvector.h>
+
+#if defined(F77_FUNC)
+
+#define FNV_INITP    F77_FUNC(fnvinitp, FNVINITP)
+#define FNV_INITP_Q  F77_FUNC_(fnvinitp_q, FNVINITP_Q)
+#define FNV_INITP_S  F77_FUNC_(fnvinitp_s, FNVINITP_S)
+#define FNV_INITP_B  F77_FUNC_(fnvinitp_b, FNVINITP_B)
+#define FNV_INITP_QB F77_FUNC_(fnvinitp_qb, FNVINITP_QB)
+
+#elif defined(SUNDIALS_UNDERSCORE_NONE) && defined(SUNDIALS_CASE_LOWER)
+
+#define FNV_INITP    fnvinitp
+#define FNV_INITP_Q  fnvinitp_q
+#define FNV_INITP_S  fnvinitp_s
+#define FNV_INITP_B  fnvinitp_b
+#define FNV_INITP_QB fnvinitp_qb
+
+#elif defined(SUNDIALS_UNDERSCORE_NONE) && defined(SUNDIALS_CASE_UPPER)
+
+#define FNV_INITP    FNVINITP
+#define FNV_INITP_Q  FNVINITP_Q
+#define FNV_INITP_S  FNVINITP_S
+#define FNV_INITP_B  FNVINITP_B
+#define FNV_INITP_QB FNVINITP_QB
+
+#elif defined(SUNDIALS_UNDERSCORE_ONE) && defined(SUNDIALS_CASE_LOWER)
+
+#define FNV_INITP    fnvinitp_
+#define FNV_INITP_Q  fnvinitp_q_
+#define FNV_INITP_S  fnvinitp_s_
+#define FNV_INITP_B  fnvinitp_b_
+#define FNV_INITP_QB fnvinitp_qb_
+
+#elif defined(SUNDIALS_UNDERSCORE_ONE) && defined(SUNDIALS_CASE_UPPER)
+
+#define FNV_INITP    FNVINITP_
+#define FNV_INITP_Q  FNVINITP_Q_
+#define FNV_INITP_S  FNVINITP_S_
+#define FNV_INITP_B  FNVINITP_B_
+#define FNV_INITP_QB FNVINITP_QB_
+
+#elif defined(SUNDIALS_UNDERSCORE_TWO) && defined(SUNDIALS_CASE_LOWER)
+
+#define FNV_INITP    fnvinitp__
+#define FNV_INITP_Q  fnvinitp_q__
+#define FNV_INITP_S  fnvinitp_s__
+#define FNV_INITP_B  fnvinitp_b__
+#define FNV_INITP_QB fnvinitp_qb__
+
+#elif defined(SUNDIALS_UNDERSCORE_TWO) && defined(SUNDIALS_CASE_UPPER)
+
+#define FNV_INITP    FNVINITP__
+#define FNV_INITP_Q  FNVINITP_Q__
+#define FNV_INITP_S  FNVINITP_S__
+#define FNV_INITP_B  FNVINITP_B__
+#define FNV_INITP_QB FNVINITP_QB__
+
+#endif
+
+  /* Declarations of global variables */
+
+  extern N_Vector F2C_CVODE_vec;
+  extern N_Vector F2C_CVODE_vecQ;
+  extern N_Vector *F2C_CVODE_vecS;
+  extern N_Vector F2C_CVODE_vecB;
+  extern N_Vector F2C_CVODE_vecQB;
+
+  extern N_Vector F2C_IDA_vec;
+  extern N_Vector F2C_IDA_vecQ;
+  extern N_Vector *F2C_IDA_vecS;
+  extern N_Vector F2C_IDA_vecB;
+  extern N_Vector F2C_IDA_vecQB;
+
+  extern N_Vector F2C_KINSOL_vec;
+
+  /* 
+   * Prototypes of exported functions 
+   *
+   * FNV_INITP    - initializes parallel vector operations for main problem
+   * FNV_INITP_Q  - initializes parallel vector operations for quadratures
+   * FNV_INITP_S  - initializes parallel vector operations for sensitivities
+   * FNV_INITP_B  - initializes parallel vector operations for adjoint problem
+   * FNV_INITP_QB - initializes parallel vector operations for adjoint quadratures
+   *
+   */
+
+#ifndef SUNDIALS_MPI_COMM_F2C
+#define MPI_Fint int
+#endif
+
+  void FNV_INITP(MPI_Fint *comm, int *code, long int *L, long int *N, int *ier);
+  void FNV_INITP_Q(MPI_Fint *comm, int *code, long int *Lq, long int *Nq, int *ier);
+  void FNV_INITP_B(MPI_Fint *comm, int *code, long int *LB, long int *NB, int *ier);
+  void FNV_INITP_QB(MPI_Fint *comm, int *code, long int *LqB, long int *NqB, int *ier);
+  void FNV_INITP_S(int *code, int *Ns, int *ier);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/fnvector_serial.c b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/fnvector_serial.c
new file mode 100644
index 0000000000000000000000000000000000000000..efd39922461755243f352111651dfad16e2e6714
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/fnvector_serial.c
@@ -0,0 +1,147 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2002, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This file (companion of nvector_serial.h) contains the
+ * implementation needed for the Fortran initialization of serial
+ * vector operations.
+ * -----------------------------------------------------------------
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "fnvector_serial.h"
+
+/* Define global vector variables */
+
+N_Vector F2C_CVODE_vec;
+N_Vector F2C_CVODE_vecQ;
+N_Vector *F2C_CVODE_vecS;
+N_Vector F2C_CVODE_vecB;
+N_Vector F2C_CVODE_vecQB;
+
+N_Vector F2C_IDA_vec;
+N_Vector F2C_IDA_vecQ;
+N_Vector *F2C_IDA_vecS;
+N_Vector F2C_IDA_vecB;
+N_Vector F2C_IDA_vecQB;
+
+N_Vector F2C_KINSOL_vec;
+
+/* Fortran callable interfaces */
+
+void FNV_INITS(int *code, long int *N, int *ier)
+{
+  *ier = 0;
+
+  switch(*code) {
+  case FCMIX_CVODE:
+    F2C_CVODE_vec = NULL;
+    F2C_CVODE_vec = N_VNewEmpty_Serial(*N);
+    if (F2C_CVODE_vec == NULL) *ier = -1;
+    break;
+  case FCMIX_IDA:
+    F2C_IDA_vec = NULL;
+    F2C_IDA_vec = N_VNewEmpty_Serial(*N);
+    if (F2C_IDA_vec == NULL) *ier = -1;
+    break;
+  case FCMIX_KINSOL:
+    F2C_KINSOL_vec = NULL;
+    F2C_KINSOL_vec = N_VNewEmpty_Serial(*N);
+    if (F2C_KINSOL_vec == NULL) *ier = -1;
+    break;
+  default:
+    *ier = -1;
+  }
+}
+
+void FNV_INITS_Q(int *code, long int *Nq, int *ier)
+{
+  *ier = 0;
+
+  switch(*code) {
+  case FCMIX_CVODE:
+    F2C_CVODE_vecQ = NULL;
+    F2C_CVODE_vecQ = N_VNewEmpty_Serial(*Nq);
+    if (F2C_CVODE_vecQ == NULL) *ier = -1;
+    break;
+  case FCMIX_IDA:
+    F2C_IDA_vecQ = NULL;
+    F2C_IDA_vecQ = N_VNewEmpty_Serial(*Nq);
+    if (F2C_IDA_vecQ == NULL) *ier = -1;
+    break;
+  default:
+    *ier = -1;
+  }
+}
+
+void FNV_INITS_B(int *code, long int *NB, int *ier)
+{
+  *ier = 0;
+
+  switch(*code) {
+  case FCMIX_CVODE:
+    F2C_CVODE_vecB = NULL;
+    F2C_CVODE_vecB = N_VNewEmpty_Serial(*NB);
+    if (F2C_CVODE_vecB == NULL) *ier = -1;
+    break;
+  case FCMIX_IDA:
+    F2C_IDA_vecB = NULL;
+    F2C_IDA_vecB = N_VNewEmpty_Serial(*NB);
+    if (F2C_IDA_vecB == NULL) *ier = -1;
+    break;
+  default:
+    *ier = -1;
+  }
+}
+
+void FNV_INITS_QB(int *code, long int *NqB, int *ier)
+{
+  *ier = 0;
+
+  switch(*code) {
+  case FCMIX_CVODE:
+    F2C_CVODE_vecQB = NULL;
+    F2C_CVODE_vecQB = N_VNewEmpty_Serial(*NqB);
+    if (F2C_CVODE_vecQB == NULL) *ier = -1;
+    break;
+  case FCMIX_IDA:
+    F2C_IDA_vecQB = NULL;
+    F2C_IDA_vecQB = N_VNewEmpty_Serial(*NqB);
+    if (F2C_IDA_vecQB == NULL) *ier = -1;
+    break;
+  default:
+    *ier = -1;
+  }
+}
+
+void FNV_INITS_S(int *code, int *Ns, int *ier)
+{
+  *ier = 0;
+
+  switch(*code) {
+  case FCMIX_CVODE:
+    F2C_CVODE_vecS = NULL;
+    F2C_CVODE_vecS = (N_Vector *) N_VCloneVectorArrayEmpty_Serial(*Ns, F2C_CVODE_vec);
+    if (F2C_CVODE_vecS == NULL) *ier = -1;
+    break;
+  case FCMIX_IDA:
+    F2C_IDA_vecS = NULL;
+    F2C_IDA_vecS = (N_Vector *) N_VCloneVectorArrayEmpty_Serial(*Ns, F2C_IDA_vec);
+    if (F2C_IDA_vecS == NULL) *ier = -1;
+    break;
+  default:
+    *ier = -1;
+  }
+}
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/fnvector_serial.h b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/fnvector_serial.h
new file mode 100644
index 0000000000000000000000000000000000000000..cff3b8813df6f9c6ff7134dc16646eeb98c4a563
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/fnvector_serial.h
@@ -0,0 +1,124 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Radu Serban and Aaron Collier @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2002, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This file (companion of nvector_serial.h) contains the
+ * definitions needed for the initialization of serial
+ * vector operations in Fortran.
+ * -----------------------------------------------------------------
+ */
+
+#ifndef _FNVECTOR_SERIAL_H
+#define _FNVECTOR_SERIAL_H
+
+#ifdef __cplusplus  /* wrapper to enable C++ usage */
+extern "C" {
+#endif
+
+#include <nvector/nvector_serial.h>  
+#include <sundials/sundials_fnvector.h>
+
+#if defined(F77_FUNC)
+
+#define FNV_INITS    F77_FUNC(fnvinits, FNVINITS)
+#define FNV_INITS_Q  F77_FUNC_(fnvinits_q, FNVINITS_Q)
+#define FNV_INITS_S  F77_FUNC_(fnvinits_s, FNVINITS_S)
+#define FNV_INITS_B  F77_FUNC_(fnvinits_b, FNVINITS_B)
+#define FNV_INITS_QB F77_FUNC_(fnvinits_qb, FNVINITS_QB)
+
+#elif defined(SUNDIALS_UNDERSCORE_NONE) && defined(SUNDIALS_CASE_LOWER)
+
+#define FNV_INITS    fnvinits
+#define FNV_INITS_Q  fnvinits_q
+#define FNV_INITS_S  fnvinits_s
+#define FNV_INITS_B  fnvinits_b
+#define FNV_INITS_QB fnvinits_qb
+
+#elif defined(SUNDIALS_UNDERSCORE_NONE) && defined(SUNDIALS_CASE_UPPER)
+
+#define FNV_INITS    FNVINITS
+#define FNV_INITS_Q  FNVINITS_Q
+#define FNV_INITS_S  FNVINITS_S
+#define FNV_INITS_B  FNVINITS_B
+#define FNV_INITS_QB FNVINITS_QB
+
+#elif defined(SUNDIALS_UNDERSCORE_ONE) && defined(SUNDIALS_CASE_LOWER)
+
+#define FNV_INITS    fnvinits_
+#define FNV_INITS_Q  fnvinits_q_
+#define FNV_INITS_S  fnvinits_s_
+#define FNV_INITS_B  fnvinits_b_
+#define FNV_INITS_QB fnvinits_qb_
+
+#elif defined(SUNDIALS_UNDERSCORE_ONE) && defined(SUNDIALS_CASE_UPPER)
+
+#define FNV_INITS    FNVINITS_
+#define FNV_INITS_Q  FNVINITS_Q_
+#define FNV_INITS_S  FNVINITS_S_
+#define FNV_INITS_B  FNVINITS_B_
+#define FNV_INITS_QB FNVINITS_QB_
+
+#elif defined(SUNDIALS_UNDERSCORE_TWO) && defined(SUNDIALS_CASE_LOWER)
+
+#define FNV_INITS    fnvinits__
+#define FNV_INITS_Q  fnvinits_q__
+#define FNV_INITS_S  fnvinits_s__
+#define FNV_INITS_B  fnvinits_b__
+#define FNV_INITS_QB fnvinits_qb__
+
+#elif defined(SUNDIALS_UNDERSCORE_TWO) && defined(SUNDIALS_CASE_UPPER)
+
+#define FNV_INITS    FNVINITS__
+#define FNV_INITS_Q  FNVINITS_Q__
+#define FNV_INITS_S  FNVINITS_S__
+#define FNV_INITS_B  FNVINITS_B__
+#define FNV_INITS_QB FNVINITS_QB__
+
+#endif
+
+  /* Declarations of global variables */
+
+  extern N_Vector F2C_CVODE_vec;
+  extern N_Vector F2C_CVODE_vecQ;
+  extern N_Vector *F2C_CVODE_vecS;
+  extern N_Vector F2C_CVODE_vecB;
+  extern N_Vector F2C_CVODE_vecQB;
+
+  extern N_Vector F2C_IDA_vec;
+  extern N_Vector F2C_IDA_vecQ;
+  extern N_Vector *F2C_IDA_vecS;
+  extern N_Vector F2C_IDA_vecB;
+  extern N_Vector F2C_IDA_vecQB;
+
+  extern N_Vector F2C_KINSOL_vec;
+
+  /* 
+   * Prototypes of exported functions 
+   *
+   * FNV_INITS    - initializes serial vector operations for main problem
+   * FNV_INITS_Q  - initializes serial vector operations for quadratures
+   * FNV_INITS_S  - initializes serial vector operations for sensitivities
+   * FNV_INITS_B  - initializes serial vector operations for adjoint problem
+   * FNV_INITS_QB - initializes serial vector operations for adjoint quadratures
+   *
+   */
+
+  void FNV_INITS(int *code, long int *neq, int *ier);
+  void FNV_INITS_Q(int *code, long int *Nq, int *ier);
+  void FNV_INITS_S(int *code, int *Ns, int *ier);
+  void FNV_INITS_B(int *code, long int *NB, int *ier);
+  void FNV_INITS_QB(int *code, long int *NqB, int *ier);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/nvector_serial.c b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/nvector_serial.c
new file mode 100644
index 0000000000000000000000000000000000000000..1766b833b9fc162afb4ad3c4189787c3fb15b0fd
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/nvector_serial.c
@@ -0,0 +1,1034 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Scott D. Cohen, Alan C. Hindmarsh, Radu Serban,
+ *                and Aaron Collier @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2002, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the implementation file for a serial implementation
+ * of the NVECTOR package.
+ * -----------------------------------------------------------------
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <nvector/nvector_serial.h>
+#include <sundials/sundials_math.h>
+
+#define ZERO   RCONST(0.0)
+#define HALF   RCONST(0.5)
+#define ONE    RCONST(1.0)
+#define ONEPT5 RCONST(1.5)
+
+/* Private function prototypes */
+/* z=x */
+static void VCopy_Serial(N_Vector x, N_Vector z);
+/* z=x+y */
+static void VSum_Serial(N_Vector x, N_Vector y, N_Vector z);
+/* z=x-y */
+static void VDiff_Serial(N_Vector x, N_Vector y, N_Vector z);
+/* z=-x */
+static void VNeg_Serial(N_Vector x, N_Vector z);
+/* z=c(x+y) */
+static void VScaleSum_Serial(realtype c, N_Vector x, N_Vector y, N_Vector z);
+/* z=c(x-y) */
+static void VScaleDiff_Serial(realtype c, N_Vector x, N_Vector y, N_Vector z); 
+/* z=ax+y */
+static void VLin1_Serial(realtype a, N_Vector x, N_Vector y, N_Vector z);
+/* z=ax-y */
+static void VLin2_Serial(realtype a, N_Vector x, N_Vector y, N_Vector z);
+/* y <- ax+y */
+static void Vaxpy_Serial(realtype a, N_Vector x, N_Vector y);
+/* x <- ax */
+static void VScaleBy_Serial(realtype a, N_Vector x);
+
+/*
+ * -----------------------------------------------------------------
+ * exported functions
+ * -----------------------------------------------------------------
+ */
+
+/* ----------------------------------------------------------------------------
+ * Function to create a new empty serial vector 
+ */
+
+N_Vector N_VNewEmpty_Serial(long int length)
+{
+  N_Vector v;
+  N_Vector_Ops ops;
+  N_VectorContent_Serial content;
+
+  /* Create vector */
+  v = NULL;
+  v = (N_Vector) malloc(sizeof *v);
+  if (v == NULL) return(NULL);
+  
+  /* Create vector operation structure */
+  ops = NULL;
+  ops = (N_Vector_Ops) malloc(sizeof(struct _generic_N_Vector_Ops));
+  if (ops == NULL) { free(v); return(NULL); }
+
+  ops->nvclone           = N_VClone_Serial;
+  ops->nvcloneempty      = N_VCloneEmpty_Serial;
+  ops->nvdestroy         = N_VDestroy_Serial;
+  ops->nvspace           = N_VSpace_Serial;
+  ops->nvgetarraypointer = N_VGetArrayPointer_Serial;
+  ops->nvsetarraypointer = N_VSetArrayPointer_Serial;
+  ops->nvlinearsum       = N_VLinearSum_Serial;
+  ops->nvconst           = N_VConst_Serial;
+  ops->nvprod            = N_VProd_Serial;
+  ops->nvdiv             = N_VDiv_Serial;
+  ops->nvscale           = N_VScale_Serial;
+  ops->nvabs             = N_VAbs_Serial;
+  ops->nvinv             = N_VInv_Serial;
+  ops->nvaddconst        = N_VAddConst_Serial;
+  ops->nvdotprod         = N_VDotProd_Serial;
+  ops->nvmaxnorm         = N_VMaxNorm_Serial;
+  ops->nvwrmsnormmask    = N_VWrmsNormMask_Serial;
+  ops->nvwrmsnorm        = N_VWrmsNorm_Serial;
+  ops->nvmin             = N_VMin_Serial;
+  ops->nvwl2norm         = N_VWL2Norm_Serial;
+  ops->nvl1norm          = N_VL1Norm_Serial;
+  ops->nvcompare         = N_VCompare_Serial;
+  ops->nvinvtest         = N_VInvTest_Serial;
+  ops->nvconstrmask      = N_VConstrMask_Serial;
+  ops->nvminquotient     = N_VMinQuotient_Serial;
+
+  /* Create content */
+  content = NULL;
+  content = (N_VectorContent_Serial) malloc(sizeof(struct _N_VectorContent_Serial));
+  if (content == NULL) { free(ops); free(v); return(NULL); }
+
+  content->length   = length;
+  content->own_data = FALSE;
+  content->data     = NULL;
+
+  /* Attach content and ops */
+  v->content = content;
+  v->ops     = ops;
+
+  return(v);
+}
+
+/* ----------------------------------------------------------------------------
+ * Function to create a new serial vector 
+ */
+
+N_Vector N_VNew_Serial(long int length)
+{
+  N_Vector v;
+  realtype *data;
+
+  v = NULL;
+  v = N_VNewEmpty_Serial(length);
+  if (v == NULL) return(NULL);
+
+  /* Create data */
+  if (length > 0) {
+
+    /* Allocate memory */
+    data = NULL;
+    data = (realtype *) malloc(length * sizeof(realtype));
+    if(data == NULL) { N_VDestroy_Serial(v); return(NULL); }
+
+    /* Attach data */
+    NV_OWN_DATA_S(v) = TRUE;
+    NV_DATA_S(v)     = data;
+
+  }
+
+  return(v);
+}
+
+/* ----------------------------------------------------------------------------
+ * Function to create a serial N_Vector with user data component 
+ */
+
+N_Vector N_VMake_Serial(long int length, realtype *v_data)
+{
+  N_Vector v;
+
+  v = NULL;
+  v = N_VNewEmpty_Serial(length);
+  if (v == NULL) return(NULL);
+
+  if (length > 0) {
+    /* Attach data */
+    NV_OWN_DATA_S(v) = FALSE;
+    NV_DATA_S(v)     = v_data;
+  }
+
+  return(v);
+}
+
+/* ----------------------------------------------------------------------------
+ * Function to create an array of new serial vectors. 
+ */
+
+N_Vector *N_VCloneVectorArray_Serial(int count, N_Vector w)
+{
+  N_Vector *vs;
+  int j;
+
+  if (count <= 0) return(NULL);
+
+  vs = NULL;
+  vs = (N_Vector *) malloc(count * sizeof(N_Vector));
+  if(vs == NULL) return(NULL);
+
+  for (j = 0; j < count; j++) {
+    vs[j] = NULL;
+    vs[j] = N_VClone_Serial(w);
+    if (vs[j] == NULL) {
+      N_VDestroyVectorArray_Serial(vs, j-1);
+      return(NULL);
+    }
+  }
+
+  return(vs);
+}
+
+/* ----------------------------------------------------------------------------
+ * Function to create an array of new serial vectors with NULL data array. 
+ */
+
+N_Vector *N_VCloneVectorArrayEmpty_Serial(int count, N_Vector w)
+{
+  N_Vector *vs;
+  int j;
+
+  if (count <= 0) return(NULL);
+
+  vs = NULL;
+  vs = (N_Vector *) malloc(count * sizeof(N_Vector));
+  if(vs == NULL) return(NULL);
+
+  for (j = 0; j < count; j++) {
+    vs[j] = NULL;
+    vs[j] = N_VCloneEmpty_Serial(w);
+    if (vs[j] == NULL) {
+      N_VDestroyVectorArray_Serial(vs, j-1);
+      return(NULL);
+    }
+  }
+
+  return(vs);
+}
+
+/* ----------------------------------------------------------------------------
+ * Function to free an array created with N_VCloneVectorArray_Serial
+ */
+
+void N_VDestroyVectorArray_Serial(N_Vector *vs, int count)
+{
+  int j;
+
+  for (j = 0; j < count; j++) N_VDestroy_Serial(vs[j]);
+
+  free(vs); vs = NULL;
+
+  return;
+}
+
+/* ----------------------------------------------------------------------------
+ * Function to print the a serial vector 
+ */
+ 
+void N_VPrint_Serial(N_Vector x)
+{
+  long int i, N;
+  realtype *xd;
+
+  xd = NULL;
+
+  N  = NV_LENGTH_S(x);
+  xd = NV_DATA_S(x);
+
+  for (i = 0; i < N; i++) {
+#if defined(SUNDIALS_EXTENDED_PRECISION)
+    printf("%11.8Lg\n", xd[i]);
+#elif defined(SUNDIALS_DOUBLE_PRECISION)
+    printf("%11.8lg\n", xd[i]);
+#else
+    printf("%11.8g\n", xd[i]);
+#endif
+  }
+  printf("\n");
+
+  return;
+}
+
+/*
+ * -----------------------------------------------------------------
+ * implementation of vector operations
+ * -----------------------------------------------------------------
+ */
+
+N_Vector N_VCloneEmpty_Serial(N_Vector w)
+{
+  N_Vector v;
+  N_Vector_Ops ops;
+  N_VectorContent_Serial content;
+
+  if (w == NULL) return(NULL);
+
+  /* Create vector */
+  v = NULL;
+  v = (N_Vector) malloc(sizeof *v);
+  if (v == NULL) return(NULL);
+
+  /* Create vector operation structure */
+  ops = NULL;
+  ops = (N_Vector_Ops) malloc(sizeof(struct _generic_N_Vector_Ops));
+  if (ops == NULL) { free(v); return(NULL); }
+  
+  ops->nvclone           = w->ops->nvclone;
+  ops->nvcloneempty      = w->ops->nvcloneempty;
+  ops->nvdestroy         = w->ops->nvdestroy;
+  ops->nvspace           = w->ops->nvspace;
+  ops->nvgetarraypointer = w->ops->nvgetarraypointer;
+  ops->nvsetarraypointer = w->ops->nvsetarraypointer;
+  ops->nvlinearsum       = w->ops->nvlinearsum;
+  ops->nvconst           = w->ops->nvconst;  
+  ops->nvprod            = w->ops->nvprod;   
+  ops->nvdiv             = w->ops->nvdiv;
+  ops->nvscale           = w->ops->nvscale; 
+  ops->nvabs             = w->ops->nvabs;
+  ops->nvinv             = w->ops->nvinv;
+  ops->nvaddconst        = w->ops->nvaddconst;
+  ops->nvdotprod         = w->ops->nvdotprod;
+  ops->nvmaxnorm         = w->ops->nvmaxnorm;
+  ops->nvwrmsnormmask    = w->ops->nvwrmsnormmask;
+  ops->nvwrmsnorm        = w->ops->nvwrmsnorm;
+  ops->nvmin             = w->ops->nvmin;
+  ops->nvwl2norm         = w->ops->nvwl2norm;
+  ops->nvl1norm          = w->ops->nvl1norm;
+  ops->nvcompare         = w->ops->nvcompare;    
+  ops->nvinvtest         = w->ops->nvinvtest;
+  ops->nvconstrmask      = w->ops->nvconstrmask;
+  ops->nvminquotient     = w->ops->nvminquotient;
+
+  /* Create content */
+  content = NULL;
+  content = (N_VectorContent_Serial) malloc(sizeof(struct _N_VectorContent_Serial));
+  if (content == NULL) { free(ops); free(v); return(NULL); }
+
+  content->length   = NV_LENGTH_S(w);
+  content->own_data = FALSE;
+  content->data     = NULL;
+
+  /* Attach content and ops */
+  v->content = content;
+  v->ops     = ops;
+
+  return(v);
+}
+
+N_Vector N_VClone_Serial(N_Vector w)
+{
+  N_Vector v;
+  realtype *data;
+  long int length;
+
+  v = NULL;
+  v = N_VCloneEmpty_Serial(w);
+  if (v == NULL) return(NULL);
+
+  length = NV_LENGTH_S(w);
+
+  /* Create data */
+  if (length > 0) {
+
+    /* Allocate memory */
+    data = NULL;
+    data = (realtype *) malloc(length * sizeof(realtype));
+    if(data == NULL) { N_VDestroy_Serial(v); return(NULL); }
+
+    /* Attach data */
+    NV_OWN_DATA_S(v) = TRUE;
+    NV_DATA_S(v)     = data;
+
+  }
+
+  return(v);
+}
+
+void N_VDestroy_Serial(N_Vector v)
+{
+  if (NV_OWN_DATA_S(v) == TRUE) {
+    free(NV_DATA_S(v));
+    NV_DATA_S(v) = NULL;
+  }
+  free(v->content); v->content = NULL;
+  free(v->ops); v->ops = NULL;
+  free(v); v = NULL;
+
+  return;
+}
+
+void N_VSpace_Serial(N_Vector v, long int *lrw, long int *liw)
+{
+  *lrw = NV_LENGTH_S(v);
+  *liw = 1;
+
+  return;
+}
+
+realtype *N_VGetArrayPointer_Serial(N_Vector v)
+{
+  return((realtype *) NV_DATA_S(v));
+}
+
+void N_VSetArrayPointer_Serial(realtype *v_data, N_Vector v)
+{
+  if (NV_LENGTH_S(v) > 0) NV_DATA_S(v) = v_data;
+
+  return;
+}
+
+void N_VLinearSum_Serial(realtype a, N_Vector x, realtype b, N_Vector y, N_Vector z)
+{
+  long int i, N;
+  realtype c, *xd, *yd, *zd;
+  N_Vector v1, v2;
+  booleantype test;
+
+  xd = yd = zd = NULL;
+
+  if ((b == ONE) && (z == y)) {    /* BLAS usage: axpy y <- ax+y */
+    Vaxpy_Serial(a,x,y);
+    return;
+  }
+
+  if ((a == ONE) && (z == x)) {    /* BLAS usage: axpy x <- by+x */
+    Vaxpy_Serial(b,y,x);
+    return;
+  }
+
+  /* Case: a == b == 1.0 */
+
+  if ((a == ONE) && (b == ONE)) {
+    VSum_Serial(x, y, z);
+    return;
+  }
+
+  /* Cases: (1) a == 1.0, b = -1.0, (2) a == -1.0, b == 1.0 */
+
+  if ((test = ((a == ONE) && (b == -ONE))) || ((a == -ONE) && (b == ONE))) {
+    v1 = test ? y : x;
+    v2 = test ? x : y;
+    VDiff_Serial(v2, v1, z);
+    return;
+  }
+
+  /* Cases: (1) a == 1.0, b == other or 0.0, (2) a == other or 0.0, b == 1.0 */
+  /* if a or b is 0.0, then user should have called N_VScale */
+
+  if ((test = (a == ONE)) || (b == ONE)) {
+    c  = test ? b : a;
+    v1 = test ? y : x;
+    v2 = test ? x : y;
+    VLin1_Serial(c, v1, v2, z);
+    return;
+  }
+
+  /* Cases: (1) a == -1.0, b != 1.0, (2) a != 1.0, b == -1.0 */
+
+  if ((test = (a == -ONE)) || (b == -ONE)) {
+    c = test ? b : a;
+    v1 = test ? y : x;
+    v2 = test ? x : y;
+    VLin2_Serial(c, v1, v2, z);
+    return;
+  }
+
+  /* Case: a == b */
+  /* catches case both a and b are 0.0 - user should have called N_VConst */
+
+  if (a == b) {
+    VScaleSum_Serial(a, x, y, z);
+    return;
+  }
+
+  /* Case: a == -b */
+
+  if (a == -b) {
+    VScaleDiff_Serial(a, x, y, z);
+    return;
+  }
+
+  /* Do all cases not handled above:
+     (1) a == other, b == 0.0 - user should have called N_VScale
+     (2) a == 0.0, b == other - user should have called N_VScale
+     (3) a,b == other, a !=b, a != -b */
+  
+  N  = NV_LENGTH_S(x);
+  xd = NV_DATA_S(x);
+  yd = NV_DATA_S(y);
+  zd = NV_DATA_S(z);
+
+  for (i = 0; i < N; i++)
+    zd[i] = (a*xd[i])+(b*yd[i]);
+
+  return;
+}
+
+void N_VConst_Serial(realtype c, N_Vector z)
+{
+  long int i, N;
+  realtype *zd;
+
+  zd = NULL;
+
+  N  = NV_LENGTH_S(z);
+  zd = NV_DATA_S(z);
+
+  for (i = 0; i < N; i++) zd[i] = c;
+
+  return;
+}
+
+void N_VProd_Serial(N_Vector x, N_Vector y, N_Vector z)
+{
+  long int i, N;
+  realtype *xd, *yd, *zd;
+
+  xd = yd = zd = NULL;
+
+  N  = NV_LENGTH_S(x);
+  xd = NV_DATA_S(x);
+  yd = NV_DATA_S(y);
+  zd = NV_DATA_S(z);
+
+  for (i = 0; i < N; i++)
+    zd[i] = xd[i]*yd[i];
+
+  return;
+}
+
+void N_VDiv_Serial(N_Vector x, N_Vector y, N_Vector z)
+{
+  long int i, N;
+  realtype *xd, *yd, *zd;
+
+  xd = yd = zd = NULL;
+
+  N  = NV_LENGTH_S(x);
+  xd = NV_DATA_S(x);
+  yd = NV_DATA_S(y);
+  zd = NV_DATA_S(z);
+
+  for (i = 0; i < N; i++)
+    zd[i] = xd[i]/yd[i];
+
+  return;
+}
+
+void N_VScale_Serial(realtype c, N_Vector x, N_Vector z)
+{
+  long int i, N;
+  realtype *xd, *zd;
+
+  xd = zd = NULL;
+
+  if (z == x) {  /* BLAS usage: scale x <- cx */
+    VScaleBy_Serial(c, x);
+    return;
+  }
+
+  if (c == ONE) {
+    VCopy_Serial(x, z);
+  } else if (c == -ONE) {
+    VNeg_Serial(x, z);
+  } else {
+    N  = NV_LENGTH_S(x);
+    xd = NV_DATA_S(x);
+    zd = NV_DATA_S(z);
+    for (i = 0; i < N; i++) 
+      zd[i] = c*xd[i];
+  }
+
+  return;
+}
+
+void N_VAbs_Serial(N_Vector x, N_Vector z)
+{
+  long int i, N;
+  realtype *xd, *zd;
+
+  xd = zd = NULL;
+
+  N  = NV_LENGTH_S(x);
+  xd = NV_DATA_S(x);
+  zd = NV_DATA_S(z);
+
+  for (i = 0; i < N; i++)
+    zd[i] = ABS(xd[i]);
+
+  return;
+}
+
+void N_VInv_Serial(N_Vector x, N_Vector z)
+{
+  long int i, N;
+  realtype *xd, *zd;
+
+  xd = zd = NULL;
+
+  N  = NV_LENGTH_S(x);
+  xd = NV_DATA_S(x);
+  zd = NV_DATA_S(z);
+
+  for (i = 0; i < N; i++)
+    zd[i] = ONE/xd[i];
+
+  return;
+}
+
+void N_VAddConst_Serial(N_Vector x, realtype b, N_Vector z)
+{
+  long int i, N;
+  realtype *xd, *zd;
+
+  xd = zd = NULL;
+
+  N  = NV_LENGTH_S(x);
+  xd = NV_DATA_S(x);
+  zd = NV_DATA_S(z);
+
+  for (i = 0; i < N; i++) 
+    zd[i] = xd[i]+b;
+
+  return;
+}
+
+realtype N_VDotProd_Serial(N_Vector x, N_Vector y)
+{
+  long int i, N;
+  realtype sum, *xd, *yd;
+
+  sum = ZERO;
+  xd = yd = NULL;
+
+  N  = NV_LENGTH_S(x);
+  xd = NV_DATA_S(x);
+  yd = NV_DATA_S(y);
+
+  for (i = 0; i < N; i++)
+    sum += xd[i]*yd[i];
+  
+  return(sum);
+}
+
+realtype N_VMaxNorm_Serial(N_Vector x)
+{
+  long int i, N;
+  realtype max, *xd;
+
+  max = ZERO;
+  xd = NULL;
+
+  N  = NV_LENGTH_S(x);
+  xd = NV_DATA_S(x);
+
+  for (i = 0; i < N; i++) {
+    if (ABS(xd[i]) > max) max = ABS(xd[i]);
+  }
+
+  return(max);
+}
+
+realtype N_VWrmsNorm_Serial(N_Vector x, N_Vector w)
+{
+  long int i, N;
+  realtype sum, prodi, *xd, *wd;
+
+  sum = ZERO;
+  xd = wd = NULL;
+
+  N  = NV_LENGTH_S(x);
+  xd = NV_DATA_S(x);
+  wd = NV_DATA_S(w);
+
+  for (i = 0; i < N; i++) {
+    prodi = xd[i]*wd[i];
+    sum += SQR(prodi);
+  }
+
+  return(RSqrt(sum/N));
+}
+
+realtype N_VWrmsNormMask_Serial(N_Vector x, N_Vector w, N_Vector id)
+{
+  long int i, N;
+  realtype sum, prodi, *xd, *wd, *idd;
+
+  sum = ZERO;
+  xd = wd = idd = NULL;
+
+  N  = NV_LENGTH_S(x);
+  xd  = NV_DATA_S(x);
+  wd  = NV_DATA_S(w);
+  idd = NV_DATA_S(id);
+
+  for (i = 0; i < N; i++) {
+    if (idd[i] > ZERO) {
+      prodi = xd[i]*wd[i];
+      sum += SQR(prodi);
+    }
+  }
+
+  return(RSqrt(sum / N));
+}
+
+realtype N_VMin_Serial(N_Vector x)
+{
+  long int i, N;
+  realtype min, *xd;
+
+  xd = NULL;
+
+  N  = NV_LENGTH_S(x);
+  xd = NV_DATA_S(x);
+
+  min = xd[0];
+
+  for (i = 1; i < N; i++) {
+    if (xd[i] < min) min = xd[i];
+  }
+
+  return(min);
+}
+
+realtype N_VWL2Norm_Serial(N_Vector x, N_Vector w)
+{
+  long int i, N;
+  realtype sum, prodi, *xd, *wd;
+
+  sum = ZERO;
+  xd = wd = NULL;
+
+  N  = NV_LENGTH_S(x);
+  xd = NV_DATA_S(x);
+  wd = NV_DATA_S(w);
+
+  for (i = 0; i < N; i++) {
+    prodi = xd[i]*wd[i];
+    sum += SQR(prodi);
+  }
+
+  return(RSqrt(sum));
+}
+
+realtype N_VL1Norm_Serial(N_Vector x)
+{
+  long int i, N;
+  realtype sum, *xd;
+
+  sum = ZERO;
+  xd = NULL;
+
+  N  = NV_LENGTH_S(x);
+  xd = NV_DATA_S(x);
+  
+  for (i = 0; i<N; i++)  
+    sum += ABS(xd[i]);
+
+  return(sum);
+}
+
+void N_VCompare_Serial(realtype c, N_Vector x, N_Vector z)
+{
+  long int i, N;
+  realtype *xd, *zd;
+
+  xd = zd = NULL;
+
+  N  = NV_LENGTH_S(x);
+  xd = NV_DATA_S(x);
+  zd = NV_DATA_S(z);
+
+  for (i = 0; i < N; i++) {
+    zd[i] = (ABS(xd[i]) >= c) ? ONE : ZERO;
+  }
+
+  return;
+}
+
+booleantype N_VInvTest_Serial(N_Vector x, N_Vector z)
+{
+  long int i, N;
+  realtype *xd, *zd;
+
+  xd = zd = NULL;
+
+  N  = NV_LENGTH_S(x);
+  xd = NV_DATA_S(x);
+  zd = NV_DATA_S(z);
+
+  for (i = 0; i < N; i++) {
+    if (xd[i] == ZERO) return(FALSE);
+    zd[i] = ONE/xd[i];
+  }
+
+  return(TRUE);
+}
+
+booleantype N_VConstrMask_Serial(N_Vector c, N_Vector x, N_Vector m)
+{
+  long int i, N;
+  booleantype test;
+  realtype *cd, *xd, *md;
+
+  cd = xd = md = NULL;
+
+  N  = NV_LENGTH_S(x);
+  xd = NV_DATA_S(x);
+  cd = NV_DATA_S(c);
+  md = NV_DATA_S(m);
+
+  test = TRUE;
+
+  for (i = 0; i < N; i++) {
+    md[i] = ZERO;
+    if (cd[i] == ZERO) continue;
+    if (cd[i] > ONEPT5 || cd[i] < -ONEPT5) {
+      if ( xd[i]*cd[i] <= ZERO) { test = FALSE; md[i] = ONE; }
+      continue;
+    }
+    if ( cd[i] > HALF || cd[i] < -HALF) {
+      if (xd[i]*cd[i] < ZERO ) { test = FALSE; md[i] = ONE; }
+    }
+  }
+
+  return(test);
+}
+
+realtype N_VMinQuotient_Serial(N_Vector num, N_Vector denom)
+{
+  booleantype notEvenOnce;
+  long int i, N;
+  realtype *nd, *dd, min;
+
+  nd = dd = NULL;
+
+  N  = NV_LENGTH_S(num);
+  nd = NV_DATA_S(num);
+  dd = NV_DATA_S(denom);
+
+  notEvenOnce = TRUE;
+  min = BIG_REAL;
+
+  for (i = 0; i < N; i++) {
+    if (dd[i] == ZERO) continue;
+    else {
+      if (!notEvenOnce) min = MIN(min, nd[i]/dd[i]);
+      else {
+	min = nd[i]/dd[i];
+        notEvenOnce = FALSE;
+      }
+    }
+  }
+
+  return(min);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * private functions
+ * -----------------------------------------------------------------
+ */
+
+static void VCopy_Serial(N_Vector x, N_Vector z)
+{
+  long int i, N;
+  realtype *xd, *zd;
+
+  xd = zd = NULL;
+
+  N  = NV_LENGTH_S(x);
+  xd = NV_DATA_S(x);
+  zd = NV_DATA_S(z);
+
+  for (i = 0; i < N; i++)
+    zd[i] = xd[i]; 
+
+  return;
+}
+
+static void VSum_Serial(N_Vector x, N_Vector y, N_Vector z)
+{
+  long int i, N;
+  realtype *xd, *yd, *zd;
+
+  xd = yd = zd = NULL;
+
+  N  = NV_LENGTH_S(x);
+  xd = NV_DATA_S(x);
+  yd = NV_DATA_S(y);
+  zd = NV_DATA_S(z);
+
+  for (i = 0; i < N; i++)
+    zd[i] = xd[i]+yd[i];
+
+  return;
+}
+
+static void VDiff_Serial(N_Vector x, N_Vector y, N_Vector z)
+{
+  long int i, N;
+  realtype *xd, *yd, *zd;
+
+  xd = yd = zd = NULL;
+
+  N  = NV_LENGTH_S(x);
+  xd = NV_DATA_S(x);
+  yd = NV_DATA_S(y);
+  zd = NV_DATA_S(z);
+
+  for (i = 0; i < N; i++)
+    zd[i] = xd[i]-yd[i];
+
+  return;
+}
+
+static void VNeg_Serial(N_Vector x, N_Vector z)
+{
+  long int i, N;
+  realtype *xd, *zd;
+
+  xd = zd = NULL;
+
+  N  = NV_LENGTH_S(x);
+  xd = NV_DATA_S(x);
+  zd = NV_DATA_S(z);
+  
+  for (i = 0; i < N; i++)
+    zd[i] = -xd[i];
+
+  return;
+}
+
+static void VScaleSum_Serial(realtype c, N_Vector x, N_Vector y, N_Vector z)
+{
+  long int i, N;
+  realtype *xd, *yd, *zd;
+
+  xd = yd = zd = NULL;
+
+  N  = NV_LENGTH_S(x);
+  xd = NV_DATA_S(x);
+  yd = NV_DATA_S(y);
+  zd = NV_DATA_S(z);
+
+  for (i = 0; i < N; i++)
+    zd[i] = c*(xd[i]+yd[i]);
+
+  return;
+}
+
+static void VScaleDiff_Serial(realtype c, N_Vector x, N_Vector y, N_Vector z)
+{
+  long int i, N;
+  realtype *xd, *yd, *zd;
+
+  xd = yd = zd = NULL;
+
+  N  = NV_LENGTH_S(x);
+  xd = NV_DATA_S(x);
+  yd = NV_DATA_S(y);
+  zd = NV_DATA_S(z);
+
+  for (i = 0; i < N; i++)
+    zd[i] = c*(xd[i]-yd[i]);
+
+  return;
+}
+
+static void VLin1_Serial(realtype a, N_Vector x, N_Vector y, N_Vector z)
+{
+  long int i, N;
+  realtype *xd, *yd, *zd;
+
+  xd = yd = zd = NULL;
+
+  N  = NV_LENGTH_S(x);
+  xd = NV_DATA_S(x);
+  yd = NV_DATA_S(y);
+  zd = NV_DATA_S(z);
+
+  for (i = 0; i < N; i++)
+    zd[i] = (a*xd[i])+yd[i];
+
+  return;
+}
+
+static void VLin2_Serial(realtype a, N_Vector x, N_Vector y, N_Vector z)
+{
+  long int i, N;
+  realtype *xd, *yd, *zd;
+
+  xd = yd = zd = NULL;
+
+  N  = NV_LENGTH_S(x);
+  xd = NV_DATA_S(x);
+  yd = NV_DATA_S(y);
+  zd = NV_DATA_S(z);
+
+  for (i = 0; i < N; i++)
+    zd[i] = (a*xd[i])-yd[i];
+
+  return;
+}
+
+static void Vaxpy_Serial(realtype a, N_Vector x, N_Vector y)
+{
+  long int i, N;
+  realtype *xd, *yd;
+
+  xd = yd = NULL;
+
+  N  = NV_LENGTH_S(x);
+  xd = NV_DATA_S(x);
+  yd = NV_DATA_S(y);
+
+  if (a == ONE) {
+    for (i = 0; i < N; i++)
+      yd[i] += xd[i];
+    return;
+  }
+
+  if (a == -ONE) {
+    for (i = 0; i < N; i++)
+      yd[i] -= xd[i];
+    return;
+  }    
+
+  for (i = 0; i < N; i++)
+    yd[i] += a*xd[i];
+
+  return;
+}
+
+static void VScaleBy_Serial(realtype a, N_Vector x)
+{
+  long int i, N;
+  realtype *xd;
+
+  xd = NULL;
+
+  N  = NV_LENGTH_S(x);
+  xd = NV_DATA_S(x);
+
+  for (i = 0; i < N; i++)
+    xd[i] *= a;
+
+  return;
+}
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/source_SUNDIALS_CVODES b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/source_SUNDIALS_CVODES
new file mode 100644
index 0000000000000000000000000000000000000000..2675704d64f6f4294fabf95a19beb4b5dd177701
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/source_SUNDIALS_CVODES
@@ -0,0 +1,959 @@
+/*
+ * interfaceSER.c: MEX/CVODES Interface
+ *
+ * SBPD 
+ * Copyright 2006 by Fraunhofer-Chalmers Research Centre, Gothenburg, Sweden
+ * All rights reserved.me
+ *
+ * The main author of SBaddon is Henning Schmidt (henning@sbtoolbox.org). 
+ */
+
+/* General includes */
+#include <stddef.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+
+/* MEX file inculde */
+#include <mex.h>
+#include <matrix.h>
+
+/* CVODES relevant includes */
+#include <cvodes/cvodes.h>
+#include <nvector/nvector_serial.h>
+#include <sundials/sundials_types.h>
+#include <sundials/sundials_math.h>
+
+/* Include file for this interface */
+#include "interfaceSER.h"
+
+/* CVODES related contstants */
+#define ATOL  1.0e-6  /* default absolute tolerance */
+#define RTOL  1.0e-6  /* default relative tolerance */
+
+/* Accessor macros */
+#define Ith(v,i) NV_Ith_S(v,i-1)
+
+/* Help function to add a row vector to a matrix */
+static void includeVectorInMatrix(double *matrix, double *rowvector, int row, int nrows, int ncols);
+
+/* Function(s) Called by the Solver */
+static void f(double time, N_Vector u, N_Vector udot, void *f_data);
+static void g(double time, N_Vector y, double *gout, void *g_data);
+
+/* Error Function */
+static void error(char *text);
+
+/* All Variables */
+    /* Input variables */
+    mxArray *timevectorMX = NULL;
+    mxArray *parametervectorMX = NULL;
+    mxArray *initialconditionsMX = NULL;
+    mxArray *optionsMX = NULL;
+    mxArray *minstepMX = NULL;
+    mxArray *maxstepMX = NULL;
+    mxArray *maxnumstepsMX = NULL;
+    mxArray *methodMX = NULL;
+    mxArray *reltolMX = NULL;
+    mxArray *abstolMX = NULL;
+    mxArray *simdataMX = NULL;
+    mxArray *sensitivityMX = NULL;
+    mxArray *sensparamMX = NULL;
+    mxArray *sensstatesMX = NULL;
+    mxArray *senstypeMX = NULL;
+    mxArray *senserrorMX = NULL;
+    mxArray *sensparamscalingMX = NULL;
+    double *timevector = NULL;
+    int numbertimesteps;
+    double *parametervector = NULL;
+    double *parametervectorCVODE = NULL; /* parameters for right hand side. in case of sensitivity analysis eventually augmented by states */
+    double *initialconditions = NULL;
+    double minstep;
+    double maxstep;
+    long int maxnumsteps;
+    int method;
+    double reltol;
+    double abstol;
+    int simdata;
+    int sensitivity;
+    int senstype;
+    booleantype senserror;
+    int *sensparamstates;
+    /* Output variables */
+    mxArray *outputMX = NULL;
+    mxArray *statevaluesMX = NULL;
+    mxArray *variablevaluesMX = NULL;
+    mxArray *reactionvaluesMX = NULL;
+    mxArray *statesMX = NULL;
+    mxArray *variablesMX = NULL;
+    mxArray *reactionsMX = NULL;
+    mxArray *eventsMX = NULL;
+    mxArray *eventtimesMX = NULL;
+    mxArray *eventflagsMX = NULL;
+    double *output = NULL;
+    double *statevalues = NULL;
+    double *variablevalues = NULL;
+    double *reactionvalues = NULL;
+    double *eventtimes = NULL;
+    double *eventflags = NULL;
+    /* Help variables */
+    int ncols, nrows, inputStringLength;
+    int k,k2;
+    /* Model Data */
+    ModelData modeldata;
+    /* CVODE IVP related variables */
+    N_Vector u;
+    void *cvode_mem;
+    int flag, flagr;
+    double treturn;
+    /* Simulation related variables */
+    double tendstep;
+    double *statevector = NULL;
+    double *variablevector = NULL;
+    double *reactionvector = NULL;
+    int *eventvector = NULL;
+    double *oldeventvalues = NULL;
+    int numberevents;
+    double *eventflagscollect = NULL;
+    double checkeventcorrect;
+    /* Sensitivity related variables */
+    int nrsensparam;
+    int sensparamdefault;
+    int sensstatesdefault;
+    double *sensparamdouble = NULL;
+    int nrsensstates;
+    double *sensstatesdouble = NULL;
+    double *sensparamscaling = NULL;
+    double *sensparamscalingdata = NULL;
+    N_Vector *uS = NULL;
+    double *sensvector = NULL;
+    double **sensitivitydataparam = NULL;
+    double **sensitivitydatastates = NULL;
+    mxArray **sensitivitydataparamMX = NULL;
+    mxArray **sensitivitydatastatesMX = NULL;
+    mxArray *sensparamoutMX = NULL;
+    mxArray *sensitivityparamdataoutMX = NULL;
+    mxArray *sensstatesoutMX = NULL;
+    mxArray *sensitivitystatesdataoutMX = NULL;
+    /* Output function related */
+    mxArray *outputfunctionMX = NULL;
+    mxArray *checkoutputfunctionMX = NULL;
+    mxArray **outputfunctionRHS = NULL;
+    char outputfunction[100];
+    double *checkoutputfunction = NULL;
+    bool outputfunctionFlag;
+    /* whatever */
+    double *temp;
+    double timestepout;
+    char buffer[250];
+    
+/*
+ *========================================================================
+ * MEX interface to MATLAB
+ *========================================================================
+ */
+void interfaceSER(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
+{
+    /*
+     * ==============================================
+     * HANDLE VARIABLE INPUT ARGUMENTS
+     * ==============================================
+     */
+    if (nrhs == 0) {
+        /* In the case of no input argument the default initial conditions
+           of the model are returned. */
+        outputMX = mxCreateDoubleMatrix(NRSTATES, 1, mxREAL);
+        output = mxGetPr(outputMX);
+        for (k=0; k<NRSTATES; k++) output[k] = initialconditionsDefault[k];
+        plhs[0] = outputMX;
+        return;
+    } else if (nrhs == 1) {
+        /*
+           In the case of a single input argument the following cases exist:
+           1) arg = 'states' => output = species names in cell-array
+           2) arg = 'parameters' => output = parameter names in cell-array
+           3) arg = 'parametervalues' => output = parameter values in column vector
+           4) arg = [timevector] => do simulation, output = data structure
+           We start by checking if input argument is a string
+         */
+        if (mxIsChar(prhs[0])) {
+            /*
+               Get the length of the input string
+               Comparison of the string lengths instead of the string itself
+               (easier, faster, etc.)
+             */
+            inputStringLength = (mxGetM(prhs[0]) * mxGetN(prhs[0]));
+            if (inputStringLength == 6) {       /* "states" */
+                /* Return cellarray containing the state names */
+                outputMX = mxCreateCellMatrix(NRSTATES, 1);
+                for (k=0; k<NRSTATES; k++) mxSetCell(outputMX,k,mxCreateString(statenames[k]));
+                plhs[0] = outputMX;
+                return;
+            }
+            else if (inputStringLength == 10) { /* "parameters" */
+                /* Return cellarray containing the parameter names */
+                outputMX = mxCreateCellMatrix(NRPARAMETERS, 1);
+                for (k=0; k<NRPARAMETERS; k++) mxSetCell(outputMX,k,mxCreateString(parameternames[k]));
+                plhs[0] = outputMX;
+                return;
+            }
+            else if (inputStringLength == 15) { /* "parametervalues" */
+                /* Return vector containing the parameter values */
+                outputMX = mxCreateDoubleMatrix(NRPARAMETERS, 1, mxREAL);
+                output = mxGetPr(outputMX);
+                for (k=0; k<NRPARAMETERS; k++) output[k] = parametervectorDefault[k];
+                plhs[0] = outputMX;
+                return;
+            } else error("Incorrect input argument.");
+        } else {
+            /* Input argument is not a string. Check if it contains doubles, if not display error message and exit.*/
+            if (!mxIsDouble(prhs[0])) error("Check 'timevector' input argument.");
+            /*
+               Input argument is a double ... assume it is the timevector (checked later)
+               Get the timevector and set all other optional data to NULL
+             */
+            timevectorMX = (mxArray *) prhs[0];
+            parametervectorMX = NULL;
+            initialconditionsMX = NULL;
+            optionsMX = NULL;
+        }
+    } else if (nrhs == 2) {
+        /* check if timevector is a double */
+        if (!mxIsDouble(prhs[0])) error("Check 'timevector' input argument.");
+        timevectorMX = (mxArray *) prhs[0];
+        /* check if initialconditions is a double or empty */
+        if (!mxIsDouble(prhs[1]) && !mxIsEmpty(prhs[1])) error("Check 'initialconditions' input argument.");
+        initialconditionsMX = (mxArray *) prhs[1];
+        parametervectorMX = NULL;
+        optionsMX = NULL;
+    } else if (nrhs == 3) {
+        /* check if timevector is a double */
+        if (!mxIsDouble(prhs[0])) error("Check 'timevector' input argument.");
+        timevectorMX = (mxArray *) prhs[0];
+        /* check if initialconditions is a double */
+        if (!mxIsDouble(prhs[1]) && !mxIsEmpty(prhs[1])) error("Check 'initialconditions' input argument.");
+        initialconditionsMX = (mxArray *) prhs[1];
+        /* check if parametervector  is a double */
+        if (!mxIsDouble(prhs[2]) && !mxIsEmpty(prhs[1])) error("Check 'parametervector' input argument.");
+        parametervectorMX = (mxArray *) prhs[2];
+        optionsMX = NULL;
+    } else if (nrhs == 4) {
+        /* check if timevector is a double */
+        if (!mxIsDouble(prhs[0])) error("Check 'timevector' input argument.");
+        timevectorMX = (mxArray *) prhs[0];
+        /* check if initialconditions is a double */
+        if (!mxIsDouble(prhs[1]) && !mxIsEmpty(prhs[1])) error("Check 'initialconditions' input argument.");
+        initialconditionsMX = (mxArray *) prhs[1];
+        /* check if parametervector  is a double */
+        if (!mxIsDouble(prhs[2]) && !mxIsEmpty(prhs[1])) error("Check 'parametervector' input argument.");
+        parametervectorMX = (mxArray *) prhs[2];
+        /* check if options is a structure (empty [] is allowed) */
+        if (!mxIsStruct(prhs[3]) && !mxIsEmpty(prhs[3])) error("Check 'options' input argument.");
+        optionsMX = (mxArray *) prhs[3];
+    } else {
+        error("Incorrect number of input arguments.");
+    }
+    /*
+       Check if the time vector is a vector. If not then display an error message.
+       Otherwise get the timevector data
+     */
+    ncols = mxGetN(timevectorMX);
+    nrows = mxGetM(timevectorMX);
+    if (ncols*nrows == 1 || (nrows > 1 && ncols > 1)) error("'timevector' input argument needs to be a vector.");
+    timevector = mxGetPr(timevectorMX);
+    numbertimesteps = ncols*nrows;
+    /*
+       Check if initialconditions is a vector of correct length. If not then display error.
+       Otherwise get the initialconditions data
+     */
+    initialconditions = (double *) mxCalloc(NRSTATES,sizeof(double));
+    if (initialconditions == NULL) error("Memory allocation for initial conditions failed.");
+    for (k=0;k<NRSTATES;k++) initialconditions[k] = initialconditionsDefault[k];
+    if (initialconditionsMX != NULL) {
+        if (!mxIsEmpty(initialconditionsMX)) {
+            ncols = mxGetN(initialconditionsMX);
+            nrows = mxGetM(initialconditionsMX);
+            if (ncols*nrows != NRSTATES || (nrows > 1 && ncols > 1)) error("'initialconditions' needs to be a vector of 'number states' length.");
+            /* Need to duplicate the initial condition MX array */
+            initialconditions = mxGetPr(mxDuplicateArray(initialconditionsMX));
+        }
+    }
+    /*
+       Check if parametervector is a vector of correct length. If not then display error.
+       Otherwise get the parametervector data
+     */
+    parametervector = parametervectorDefault;
+    if (parametervectorMX != NULL) {
+        if (!mxIsEmpty(parametervectorMX)) {
+            ncols = mxGetN(parametervectorMX);
+            nrows = mxGetM(parametervectorMX);
+            if (ncols*nrows != NRPARAMETERS || (nrows > 1 && ncols > 1)) error("'parametervector' needs to be a vector of 'number parameters' length.");
+            parametervector = mxGetPr(parametervectorMX);
+        }
+    }
+    /*
+       Check if options is not empty and a structure. If not then use default values.
+       Otherwise get the options data. Set first the default values:
+     */
+    minstep = -1;
+    maxstep = -1;
+    maxnumsteps = -1; /* max number internal steps <0 => default (500) */
+    method = 0;     /* 0 = stiff, 1 = nonstiff, default: 0 */
+    reltol = RTOL;  /* default values for relative tolerance */
+    abstol = ATOL;  /* default values for absolute tolerance */
+    simdata = 0;    /* 0 = 'states', 1 = 'all', default: 0 */
+    sensitivity = 0;  /* 0 = no sensitivity computation, 1 = sensitivity computation */
+    senstype = CV_SIMULTANEOUS;     /* 1 = simultaneous, 2 = staggered, 3 = staggered1 */
+    senserror = false;    /* TRUE = full, FALSE = partial */
+    sensparamstates = NULL; /* default: all parameters */
+    sensparamscalingdata = NULL;
+    outputfunctionFlag = false;
+    if (optionsMX != NULL) {
+        if (!mxIsEmpty(optionsMX)) {
+            /* read out the options structure */
+            /*  1) simulation related */
+            minstepMX = mxGetField(optionsMX, 0, "minstep");
+            maxstepMX = mxGetField(optionsMX, 0, "maxstep");
+            maxnumstepsMX = mxGetField(optionsMX, 0, "maxnumsteps");
+            methodMX = mxGetField(optionsMX, 0, "method");
+            reltolMX = mxGetField(optionsMX, 0, "reltol");
+            abstolMX = mxGetField(optionsMX, 0, "abstol");
+            simdataMX = mxGetField(optionsMX, 0, "simdata");
+            /*  2) sensitivity related */
+            sensitivityMX = mxGetField(optionsMX, 0, "sensitivity");
+            sensparamMX = mxGetField(optionsMX, 0, "sensparams");
+            sensstatesMX = mxGetField(optionsMX, 0, "sensstates");
+            senstypeMX = mxGetField(optionsMX, 0, "senstype");
+            senserrorMX = mxGetField(optionsMX, 0, "senserror");
+            sensparamscalingMX = mxGetField(optionsMX, 0, "sensparamscaling");
+            /*  3) output function related */
+            outputfunctionMX = mxGetField(optionsMX, 0, "outputfunction");
+            /* get the values of the fields now */
+            if (minstepMX != NULL) if (mxIsDouble(minstepMX)) minstep = mxGetScalar(minstepMX); else error("'options.minstep' wrongly defined.");
+            if (maxstepMX != NULL) if (mxIsDouble(maxstepMX)) maxstep = mxGetScalar(maxstepMX); else error("'options.maxstep' wrongly defined.");
+            if (maxnumstepsMX != NULL) if (mxIsDouble(maxnumstepsMX)) maxnumsteps = (long int)mxGetScalar(maxnumstepsMX); else error("'options.maxnumsteps' wrongly defined.");
+            if (methodMX != NULL) {
+                if (mxIsChar(methodMX)) {
+                    if (mxGetM(methodMX) * mxGetN(methodMX) == 8) {
+                        method = 1; /* "nonstiff" method */
+                    } else if (mxGetM(methodMX) * mxGetN(methodMX) == 5) {
+                        method = 0; /* "stiff method */
+                    } else {
+                        error("'options.method' wrongly defined.");
+                    }
+                } else {
+                    error("'options.method' wrongly defined.");
+                }
+            }
+            if (reltolMX != NULL) if (mxIsDouble(reltolMX)) reltol = mxGetScalar(reltolMX); else error("'options.reltol' wrongly defined.");
+            if (abstolMX != NULL) if (mxIsDouble(abstolMX)) abstol = mxGetScalar(abstolMX); else error("'options.abstol' wrongly defined.");
+            if (simdataMX != NULL) {
+                if (mxIsChar(simdataMX)) {
+                    if (mxGetM(simdataMX) * mxGetN(simdataMX) == 3) {
+                        simdata = 1; /* "all" */
+                    } else if (mxGetM(simdataMX) * mxGetN(simdataMX) == 6) {
+                        simdata = 0; /* "states" */
+                    } else {
+                        error("'options.simdata' wrongly defined.");
+                    }
+                } else {
+                    error("'options.simdata' wrongly defined.");
+                }
+            }
+            /* handle sensitivity related options */
+            if (sensitivityMX != NULL) {
+                if (mxIsChar(sensitivityMX)) {
+                    if (mxGetM(sensitivityMX) * mxGetN(sensitivityMX) == 3) {
+                        sensitivity = 1; /* "yes" */
+                    } else if (mxGetM(sensitivityMX) * mxGetN(sensitivityMX) == 2) {
+                        sensitivity = 0; /* "no" */
+                    } else {
+                        error("'options.sensitivity' wrongly defined ('yes' or 'no').");
+                    }
+                } else {
+                    error("'options.sensitivity' wrongly defined ('yes' or 'no').");
+                }
+            }
+            if (senstypeMX != NULL && sensitivity == 1) {
+                if (mxIsChar(senstypeMX)) {
+                    if (mxGetM(senstypeMX) * mxGetN(senstypeMX) == 12) {
+                        senstype = CV_SIMULTANEOUS; /* "simultaneous" */
+                    } else if (mxGetM(senstypeMX) * mxGetN(senstypeMX) == 9) {
+                        senstype = CV_STAGGERED; /* "staggered" */
+                    } else if (mxGetM(senstypeMX) * mxGetN(senstypeMX) == 10) {
+                        senstype = CV_STAGGERED1; /* "staggered1" */
+                    } else {
+                        error("'options.senstype' wrongly defined ('simultaneous' or 'staggered' or 'staggered1').");
+                    }
+                } else {
+                    error("'options.senstype' wrongly defined ('simultaneous' or 'staggered' or 'staggered1').");
+                }
+            }
+            if (senserrorMX != NULL && sensitivity == 1) {
+                if (mxIsChar(senserrorMX)) {
+                    if (mxGetM(senserrorMX) * mxGetN(senserrorMX) == 4) {
+                        senserror = true; /* "full" */
+                    } else if (mxGetM(senserrorMX) * mxGetN(senserrorMX) == 7) {
+                        senserror = false; /* "partial" */
+                    } else {
+                        error("'options.senserror' wrongly defined ('full' or 'partial').");
+                    }
+                } else {
+                    error("'options.senserror' wrongly defined ('full' or 'partial').");
+                }
+            }
+            if (sensparamMX != NULL && sensitivity == 1) {
+                if (mxIsEmpty(sensparamMX)) sensparamMX = NULL;
+                else {
+                    if (!mxIsDouble(sensparamMX)) error("Check 'options.sensparams' input argument.");
+                    sensparamdouble = mxGetPr(sensparamMX);
+                }
+            }
+            if (sensstatesMX != NULL && sensitivity == 1) {
+                if (mxIsEmpty(sensstatesMX)) sensstatesMX = NULL;
+                else {
+                    if (!mxIsDouble(sensstatesMX)) error("Check 'options.sensstates' input argument.");
+                    sensstatesdouble = mxGetPr(sensstatesMX);
+                }
+            }
+            if (sensparamscalingMX != NULL && sensitivity == 1) {
+                if (!mxIsDouble(sensparamscalingMX)) error("Check 'options.sensparamscaling' input argument.");
+                sensparamscalingdata = mxGetPr(sensparamscalingMX);
+            }
+            if (sensparamMX != NULL && sensparamscalingMX != NULL) {
+                if (mxGetM(sensparamMX)*mxGetN(sensparamMX) == 0)
+                    error("No parameters for sensitivity analysis are defined.");
+                if (mxGetM(sensparamMX)*mxGetN(sensparamMX) != mxGetM(sensparamscalingMX)*mxGetN(sensparamscalingMX))
+                    error("Different number of 'sensparamstates' and 'sensparamscaling' elements.");
+            }
+            if (sensparamMX == NULL && sensparamscalingMX != NULL) {
+                if (mxGetM(sensparamscalingMX)*mxGetN(sensparamscalingMX) != NRPARAMETERS)
+                    error("Please specify 'options.sensparamscaling' for all parameters in the model.");
+            }
+            if (outputfunctionMX != NULL) {
+                if (!mxIsEmpty(outputfunctionMX)) {
+                    if (!mxIsChar(outputfunctionMX)) error("Check 'options.outputfunction' input argument.");
+                    /* Check if given string determines an existing function in matlab */
+                    mexCallMATLAB(1, &checkoutputfunctionMX, 1, &outputfunctionMX, "exist");
+                    checkoutputfunction = (double *) mxGetData(checkoutputfunctionMX);
+                    if (checkoutputfunction[0] != 2 && checkoutputfunction[0] != 3)
+                        error("Defined output function does not exist in MATLAB path! Check 'options.outputfunction' input argument.");
+                    mxGetString(outputfunctionMX, outputfunction, (mxGetM(outputfunctionMX) * mxGetN(outputfunctionMX) * sizeof(mxChar)) + 1);
+                    outputfunctionFlag = true;
+                }
+            }
+        }
+    }
+    
+    /*
+     * ==============================================
+     * ALLOCATE MEMORY FOR THE SIMULATION
+     * ==============================================
+     */
+    /* statevalues is a 2 dimensional array with NRSTATES columns and nrtimesteps rows */
+    statevaluesMX = mxCreateDoubleMatrix(numbertimesteps, NRSTATES, mxREAL);
+    if (statevaluesMX == NULL) error("Memory allocation for state values failed.");
+    statevalues = mxGetPr(statevaluesMX);
+    /* if simdata = 1 then do allocate memory for additional simulation results */
+    if (simdata == 1) {
+        if (NRVARIABLES > 0) {
+            /* allocate memory for the variablevector */
+            variablevector = (double *) mxCalloc(NRVARIABLES, sizeof(double));
+            if (variablevector == NULL) error("Memory allocation for variable vector failed.");
+            /* variablevalues is a 2 dimensional array with NRVARIABLES columns and nrtimesteps rows */
+            variablevaluesMX = mxCreateDoubleMatrix(numbertimesteps, NRVARIABLES, mxREAL);
+            if (variablevaluesMX == NULL) error("Memory allocation for variable values failed.");
+            variablevalues = mxGetPr(variablevaluesMX);
+        }
+        if (NRREACTIONS > 0) {
+            /* allocate memory for the reactionvector */
+            reactionvector = (double *) mxCalloc(NRREACTIONS, sizeof(double));
+            if (reactionvector == NULL) error("Memory allocation for reaction vector failed.");
+            /* reactionvalues is a 2 dimensional array with NRVARIABLES columns and nrtimesteps rows */
+            reactionvaluesMX = mxCreateDoubleMatrix(numbertimesteps, NRREACTIONS, mxREAL);
+            if (reactionvaluesMX == NULL) error("Memory allocation for reaction values failed.");
+            reactionvalues = mxGetPr(reactionvaluesMX);
+        }
+    }
+    /* Allocate memory for the eventvector array */
+    if (NREVENTS > 0) {
+        eventvector = (int *) mxCalloc(NREVENTS, sizeof(int));
+        if (eventvector == NULL) error("Memory allocation for eventvector vector failed.");
+        oldeventvalues = (double *) mxCalloc(NREVENTS, sizeof(double));
+        if (oldeventvalues == NULL) error("Memory allocation for oldeventvalues vector failed.");
+    }
+    if (sensitivity == 1) {
+        /* Allocate memory for index list of sensitivity parameters (parameters + initial conditions) */
+        /* parameters */
+        if (sensparamMX == NULL) { nrsensparam = NRPARAMETERS; sensparamdefault = 1; }
+        else { nrsensparam = mxGetM(sensparamMX) * mxGetN(sensparamMX);  sensparamdefault = 0; }
+        
+        /* states (initial conditions) */
+        if (sensstatesMX == NULL) { nrsensstates = NRSTATES; sensstatesdefault = 1; }
+        else { nrsensstates = mxGetM(sensstatesMX) * mxGetN(sensstatesMX); sensstatesdefault = 0; }
+        /* sensparamstates' includes both parameter and state indices */
+        sensparamstates = (int *) mxCalloc(nrsensparam+nrsensstates, sizeof(int));
+        if (sensparamstates == NULL) error("Memory allocation for sensparamstates vector failed.");
+        /* Check the number of parameters and states to use in computation */
+        if (nrsensparam == 0 && nrsensstates == 0) error("No parameters or states specified. Sensitivity analysis does not make sense!");
+        /* Allocate memory for scaling factors of sensitivity parameters (if needed) */
+        sensparamscaling = (double *) mxCalloc(nrsensparam+nrsensstates, sizeof(double));
+        if (sensparamscaling == NULL) error("Memory allocation for sensparamscaling failed.");
+        /* Allocate memory for sensitivity data pointers */
+        sensitivitydataparam = (double **) mxCalloc(nrsensparam, sizeof(double *));
+        if (sensitivitydataparam == NULL) error("Memory allocation for sensitivitydataparam failed.");
+        sensitivitydatastates = (double **) mxCalloc(nrsensstates, sizeof(double *));
+        if (sensitivitydatastates == NULL) error("Memory allocation for sensitivitydatastates failed.");
+        /* Allocate memory for sensitivity data mxArrays */
+        sensitivitydataparamMX = (mxArray **) mxCalloc(nrsensparam, sizeof(mxArray *));
+        if (sensitivitydataparamMX == NULL) error("Memory allocation for sensitivitydataparamMX failed.");
+        sensitivitydatastatesMX = (mxArray **) mxCalloc(nrsensstates, sizeof(mxArray *));
+        if (sensitivitydatastatesMX == NULL) error("Memory allocation for sensitivitydatastatesMX failed.");
+        /* Allocate memory for sensitivity trajectories */
+        for (k=0; k<nrsensparam; k++) {
+            sensitivitydataparamMX[k] = (mxArray *) mxCreateDoubleMatrix(numbertimesteps, NRSTATES, mxREAL);
+            if (sensitivitydataparamMX[k] == NULL) error("Memory allocation for sensitivity data failed.");
+            sensitivitydataparam[k] = mxGetPr(sensitivitydataparamMX[k]);
+        }
+        for (k=0; k<nrsensstates; k++) {
+            sensitivitydatastatesMX[k] = (mxArray *) mxCreateDoubleMatrix(numbertimesteps, NRSTATES, mxREAL);
+            if (sensitivitydatastatesMX[k] == NULL) error("Memory allocation for sensitivity data failed.");
+            sensitivitydatastates[k] = mxGetPr(sensitivitydatastatesMX[k]);
+        }
+    }
+    
+    /*
+     * ==============================================
+     * SET THE MODEL DATA (PARAMETERS)
+     * In the case of sensitivity analysis also with respect to initial conditions
+     * the parameter vector needs to be augmented by the number of states
+     * ==============================================
+     */
+    if (sensitivity == 1) {
+        /* get augmented memory for right hand side parameter vector */
+        parametervectorCVODE = (double *) mxCalloc(NRPARAMETERS+NRSTATES, sizeof(double));
+        if (parametervectorCVODE == NULL) error("Memory allocation for parametervectorCVODE failed.");
+        /* copy parameter values from parametervector the values corresponding to the states are arbitrary since not used in the model */
+        for (k=0; k<NRPARAMETERS; k++) parametervectorCVODE[k] = parametervector[k];
+        for (k=NRPARAMETERS; k<NRSTATES+NRPARAMETERS; k++) parametervectorCVODE[k] = 1.0;
+        modeldata.parametervector = parametervectorCVODE;
+    }
+    else {
+        /* If no sensitivity calculations the non augmented parametervector can be used */
+        modeldata.parametervector = parametervector;
+    }
+    
+    /*
+     * ==============================================
+     * INITIALIZE CVODE (INTEGRATION)
+     * ==============================================
+     */
+    u = NULL;
+    cvode_mem = NULL;
+    /* Create serial vector and initialize it with the initial conditions */
+    u = N_VMake_Serial(NRSTATES,initialconditions);
+    /* Call CvodeCreate to create integrator memory */
+    if (method == 0) cvode_mem = CVodeCreate(CV_BDF, CV_NEWTON);    /* default (stiff) */
+    else cvode_mem = CVodeCreate(CV_ADAMS, CV_FUNCTIONAL);          /* nonstiff */
+    if (cvode_mem == NULL) error("Error: CVodeCreate.");
+    /*
+       Call CVodeMalloc to initialize the integrator memory:
+       cvode_mem is the pointer to the integrator memory returned by CVodeCreate
+       f       is the user's right hand side function in y'=f(t,y)
+       T0      is the initial time
+       u       is the initial dependent variable vector
+       CV_SS   specifies scalar relative and absolute tolerances
+       reltol  is the scalar relative tolerance
+       &abstol is a pointer to the scalar absolute tolerance
+     */
+    flag = CVodeMalloc(cvode_mem, f, timevector[0], u, CV_SS, reltol, &abstol);
+    if (flag < 0) error("Error: CVodeMalloc.");
+    /* Add the root finding function in case that events are present */
+    if (NREVENTS > 0) {
+        flag = CVodeRootInit(cvode_mem, NREVENTS, g, &modeldata);
+        if (flag < 0) error("Error: CVodeRootInit.");
+    }
+    /* Set the pointer to modeldata */
+    flag = CVodeSetFdata(cvode_mem, &modeldata);
+    if(flag < 0) error("Error: CVodeSetFdata.");
+    /* Set min and max steps if given by user */
+    if (minstep > 0) {
+        flag = CVodeSetMinStep(cvode_mem, minstep);
+        if (flag < 0) error("Error: CVodeSetMinStep.");
+    }
+    if (maxstep > 0) {
+        flag = CVodeSetMaxStep(cvode_mem, maxstep);
+        if (flag < 0) error("Error: CVodeSetMaxStep.");
+    }
+    if (maxnumsteps > 0) {
+        flag = CVodeSetMaxNumSteps(cvode_mem, maxnumsteps);
+        if (flag < 0) error("Error: CVodeSetMaxNumSteps.");
+    }
+    /* Call CVDense to specify the CVDense band linear solver */
+    flag = CVDense(cvode_mem,NRSTATES);
+    if (flag < 0) error("Error: CVDense.");
+    /*
+     * ==============================================
+     * INITIALIZE CVODE (SENSITIVITY)
+     * ==============================================
+     */
+    if (sensitivity) {
+        /* fill the sensparamstates vector with the indices of the parameters and states that are to be considered */
+        /* nrsensparams needs to be added to the state indices */
+        if (sensparamdefault) {
+            /* per default use all parameters in same order as in model */
+            for(k=0; k<nrsensparam; k++) sensparamstates[k] = k+1;
+        } else {
+            /* if parameter indices given then convert them from double to int */
+            for (k=0; k<nrsensparam; k++) sensparamstates[k] = (int)sensparamdouble[k];
+        }
+        if (sensstatesdefault) {
+        /* per default use all states in same order as in model */
+            for(k=0; k<nrsensstates; k++) sensparamstates[nrsensparam+k] = NRPARAMETERS+k+1;
+        } else {
+        /* if state indices given then convert them from double to int */
+            for (k=0; k<nrsensstates; k++) sensparamstates[nrsensparam+k] = NRPARAMETERS+(int)sensstatesdouble[k];
+        }
+        /* Assign scaling factors for each sensitivity parameter (for ics values are arbitrary) */
+        if (sensparamscalingdata == NULL) for(k=0; k<nrsensparam+nrsensstates; k++) sensparamscaling[k] = 1.0;
+        else {
+            for(k=0; k<nrsensparam; k++) sensparamscaling[k] = sensparamscalingdata[k];
+            for(k=nrsensparam; k<nrsensparam+nrsensstates; k++) sensparamscaling[k] = 1.0;
+        }
+        /* Initial conditions for sensitivities (0 for parameters and 1 for states) */
+        uS = N_VCloneVectorArray_Serial(nrsensparam+nrsensstates,u);
+        for(k=0;k<nrsensparam;k++) N_VConst(0.0, uS[k]);    /* parameters */
+        for(k=0; k<nrsensstates; k++) {
+            N_VConst(0.0, uS[k+nrsensparam]); /* states ics */
+            Ith(uS[k+nrsensparam],sensparamstates[k+nrsensparam]-NRPARAMETERS) = 1.0; /* set ics for icstate trajectories to identity matrix */
+        }
+        /* Initialize memory for sensitivity computation */
+        flag = CVodeSensMalloc(cvode_mem, nrsensparam+nrsensstates, senstype, uS);
+        if (flag < 0) error("Error: CVodeSensMalloc.");
+        /* Set error control method */
+        flag = CVodeSetSensErrCon(cvode_mem, senserror);
+        if (flag < 0) error("Error: CVodeSetSensErrCon.");
+        /* Set parameter information */
+        flag = CVodeSetSensParams(cvode_mem, modeldata.parametervector, sensparamscaling, sensparamstates);
+        if (flag < 0) error("Error: CVodeSetSensParams.");
+    }
+    /*
+     * ==============================================
+     * PERFORM THE INTEGRATION
+     * ==============================================
+     */
+    /* Add initial conditions as first entry to simulation results (statevalues) */
+    includeVectorInMatrix(statevalues,initialconditions,0,numbertimesteps,NRSTATES);
+    if (sensitivity) {
+    /* Add initial conditions for initial condition sensitivities (identity matrix) */
+    /* The parameter sensitivities have zero initial conditions and thus do not need to be set (already zero) */
+        for (k=0; k<nrsensstates; k++) {
+            sensvector = NV_DATA_S(uS[nrsensparam+k]);
+            includeVectorInMatrix(sensitivitydatastates[k], sensvector, 0, numbertimesteps, NRSTATES);
+        }
+    }
+    /* If simdata = 1 then determine variables and reactions for initialconditions */
+    if (simdata == 1) {
+        model(timevector[0], initialconditions, NULL, &modeldata, CVODE_VARREAC, variablevector, reactionvector,NULL,NULL);
+        /* Add data to simulation results */
+        if (NRVARIABLES > 0) includeVectorInMatrix(variablevalues,variablevector,0,numbertimesteps,NRVARIABLES);
+        if (NRREACTIONS > 0) includeVectorInMatrix(reactionvalues,reactionvector,0,numbertimesteps,NRREACTIONS);
+    }
+    if (NREVENTS > 0) {
+        /*
+           If events are present in the model then determine the
+           event evaluation vector for last successful step
+           This will be needed to determine directions of events
+           (only from negative to positive zero crossings are valid events)
+         */
+        model(timevector[0], initialconditions, NULL, &modeldata, CVODE_EVENTS, NULL, NULL, oldeventvalues, NULL);
+    }
+    /* Loop over the time vector */
+    k = 1;
+    tendstep = timevector[k]; /* Define first desired endstep */
+    numberevents = 0; /* initialize saying no event found so far */
+    while(1) {
+        /* integrate the time step */
+        flag = CVode(cvode_mem, tendstep, u, &treturn, CV_NORMAL);
+
+        sprintf(buffer, "%f\n",tendstep);
+        mexPrintf(buffer);
+        
+        if (flag < 0) {
+            if (flag == CV_TOO_MUCH_WORK) error("Error: CVode. To large time steps in timevector and/or to small value of 'maxnumsteps' options.");
+            else if (flag == CV_TOO_MUCH_ACC) error("Error: CVode. Given tolerances could not be met.");
+            else if (flag == CV_ERR_FAILURE || flag == CV_CONV_FAILURE) error("Error: CVode. Error or convergence test fails to often or minimum step size reached.");
+            else {
+                sprintf(buffer, "Error: CVode. You might want to try different tolerances, steps, method. %d",flag);
+                error(buffer);
+            }
+        }
+        /* Get new statevector */
+        statevector = NV_DATA_S(u);
+        /* CHECK IF RETURNED FROM AN EVENT */
+        if (flag == CV_ROOT_RETURN) {
+            /* Handle the event */
+            flagr = CVodeGetRootInfo(cvode_mem, eventvector);
+            if (flagr < 0) error("Error: CVodeGetRootInfo.");
+            /* call the model to determine new statevector */
+            checkeventcorrect = 0;
+            model(treturn, statevector, &checkeventcorrect, &modeldata, CVODE_EVENTASSIGNMENT, NULL, NULL, oldeventvalues, eventvector);
+            /* reinitialize CVODE */
+            flag = CVodeReInit(cvode_mem, f, treturn, u, CV_SS, reltol, &abstol);
+            if (flag < 0) error("Error: CVodeReInit.");
+            /* if event was correct then add it to output variable */
+            if (checkeventcorrect > 0) {
+                numberevents += 1;  /* increase counter */
+                /* add event time to vector and reallocate memory */
+                if (numberevents == 1) {
+                    /* allocate memory for saving event information (only for first step) */
+                    eventtimes = (double *) mxCalloc(1, sizeof(double));
+                    eventflagscollect = (double *) mxCalloc(NREVENTS, sizeof(double));
+                } else {
+                    /* reallocate memory for saving event information (only for first step) */
+                    eventtimes = (double *) mxRealloc((void *) eventtimes, numberevents*sizeof(double));
+                    eventflagscollect = (double *) mxRealloc((void *) eventflagscollect, NREVENTS*numberevents*sizeof(double));
+                }
+                eventtimes[numberevents-1] = treturn;
+                for (k2=0;k2<NREVENTS;k2++) eventflagscollect[NREVENTS*(numberevents-1)+k2] = (double)eventvector[k2];
+            }
+            /* Leave tendstep and k unchanged */
+        }
+        if (tendstep == treturn) { /* it can happen that an event happens exactly on a time step */
+            includeVectorInMatrix(statevalues,statevector,k,numbertimesteps,NRSTATES);
+            /*
+               If simdata = 1 then determine variables and reactions for current step
+               and include the results in the result matrices.
+             */
+            if (simdata == 1) {
+                model(tendstep, statevector, NULL, &modeldata, CVODE_VARREAC, variablevector, reactionvector, NULL, NULL);
+                if (NRVARIABLES > 0) includeVectorInMatrix(variablevalues,variablevector,k,numbertimesteps,NRVARIABLES);
+                if (NRREACTIONS > 0) includeVectorInMatrix(reactionvalues,reactionvector,k,numbertimesteps,NRREACTIONS);
+            }
+            /* Get sensitivities and save them for output */
+            if (sensitivity) {
+                if (CVodeGetSens(cvode_mem, treturn, uS) < 0) error("Error: CVodeGetSens.");
+                /* parameters */
+                for (k2=0; k2<nrsensparam; k2++) {
+                    sensvector = NV_DATA_S(uS[k2]);
+                    includeVectorInMatrix(sensitivitydataparam[k2], sensvector, k, numbertimesteps, NRSTATES);
+                }
+                /* states */
+                for (k2=0; k2<nrsensstates; k2++) {
+                    sensvector = NV_DATA_S(uS[nrsensparam+k2]);
+                    includeVectorInMatrix(sensitivitydatastates[k2], sensvector, k, numbertimesteps, NRSTATES);
+                }
+            }
+            /* Handle output function if specified */
+            if (outputfunctionFlag) {
+                outputfunctionRHS = (mxArray **) mxCalloc(4, sizeof(mxArray *));
+                /* Check if given string determines an existing function in matlab */
+                timestepout = tendstep;
+                outputfunctionRHS[0] = mxCreateDoubleScalar(timestepout);
+                outputfunctionRHS[1] = mxCreateDoubleMatrix(NRSTATES, 1, mxREAL);
+                temp = mxGetPr(outputfunctionRHS[1]);
+                for (k2=0;k2<NRSTATES;k2++) temp[k2] = statevector[k2];
+                if (simdata == 1) {
+                    outputfunctionRHS[2] = mxCreateDoubleMatrix(NRVARIABLES, 1, mxREAL);
+                    temp = mxGetPr(outputfunctionRHS[2]);
+                    for (k2=0;k2<NRVARIABLES;k2++) temp[k2] = variablevector[k2];
+                    outputfunctionRHS[3] = mxCreateDoubleMatrix(NRREACTIONS, 1, mxREAL);
+                    temp = mxGetPr(outputfunctionRHS[3]);
+                    for (k2=0;k2<NRREACTIONS;k2++) temp[k2] = reactionvector[k2];
+                }
+                else {
+                    outputfunctionRHS[2] = mxCreateDoubleMatrix(NRVARIABLES, 0, mxREAL);
+                    outputfunctionRHS[3] = mxCreateDoubleMatrix(NRREACTIONS, 0, mxREAL);
+                }
+                mexCallMATLAB(0, NULL, 4, outputfunctionRHS, outputfunction);
+                mxDestroyArray(outputfunctionRHS[0]);
+                mxDestroyArray(outputfunctionRHS[1]);
+                mxDestroyArray(outputfunctionRHS[2]);
+                mxDestroyArray(outputfunctionRHS[3]);
+            }
+            /* increase k and set new tendstep - leave loop if last timestep reached */
+            k = k+1;
+            if (k < numbertimesteps) tendstep = timevector[k];
+            else break; /* leave the integration loop when end time reached */
+        }
+        if (NREVENTS > 0) {
+            /*
+               If events are present in the model then determine the
+               event evaluation vector for last successful step
+               This will be needed to determine directions of events
+               (only from negative to positive zero crossings are valid events)
+             */
+            model(treturn, statevector, NULL, &modeldata, CVODE_EVENTS, NULL, NULL, oldeventvalues, NULL);
+        }
+    }
+    /*
+     * ==============================================
+     * FREE CVODE RELATED VARIABLES
+     * ==============================================
+     */
+    N_VDestroy_Serial(u);  /* Free the u vector */
+    if (sensitivity) {
+        N_VDestroyVectorArray_Serial(uS,nrsensparam);
+        mxFree(sensparamscaling);
+        mxFree(parametervectorCVODE);
+    }
+    CVodeFree(cvode_mem);  /* Free the integrator memory */
+    /*
+     * ==============================================
+     * CONSTRUCT OUTPUT VARIABLE
+     * ==============================================
+     */
+    outputMX = mxCreateStructMatrix(1,1,0,NULL);
+    /* Create fields in output structure */
+    mxAddField(outputMX,"time");
+    mxAddField(outputMX,"states");
+    mxAddField(outputMX,"statevalues");
+    /* If simdata = 1, add variables and reactions to the structure */
+    if (simdata == 1) {
+        mxAddField(outputMX,"variables");
+        mxAddField(outputMX,"variablevalues");
+        mxAddField(outputMX,"reactions");
+        mxAddField(outputMX,"reactionvalues");
+    }
+    if (NREVENTS > 0) {
+        mxAddField(outputMX,"events");
+        mxAddField(outputMX,"eventtimes");
+        mxAddField(outputMX,"eventflags");
+    }
+    if (sensitivity) {
+        mxAddField(outputMX,"sensparameters");
+        mxAddField(outputMX,"sensparamtrajectories");
+        mxAddField(outputMX,"sensicstates");
+        mxAddField(outputMX,"sensicstatetrajectories");
+    }
+    /* Add numeric information to output structure */
+    mxSetField(outputMX, 0, "time", mxDuplicateArray(timevectorMX));
+    mxSetField(outputMX, 0, "statevalues", statevaluesMX);
+    /* If simdata = 1, add variables and reactions to the structure */
+    if (simdata == 1) {
+        if (NRVARIABLES > 0) mxSetField(outputMX, 0, "variablevalues", variablevaluesMX);
+        if (NRREACTIONS > 0) mxSetField(outputMX, 0, "reactionvalues", reactionvaluesMX);
+    }
+    /* Construct state name cell array */
+    statesMX = mxCreateCellMatrix(1, NRSTATES);
+    for (k=0;k<NRSTATES;k++) mxSetCell(statesMX,k,mxCreateString(statenames[k]));
+    mxSetField(outputMX, 0, "states", statesMX);
+    /* If simdata = 1, add variables and reactions to the structure */
+    if (simdata == 1) {
+        /* Construct variable name cell array */
+        if (NRVARIABLES > 0) {
+            variablesMX = mxCreateCellMatrix(1, NRVARIABLES);
+            for (k=0;k<NRVARIABLES;k++) mxSetCell(variablesMX,k,mxCreateString(variablenames[k]));
+            mxSetField(outputMX, 0, "variables", variablesMX);
+        }
+        /* Construct reaction name cell array */
+        if (NRREACTIONS > 0) {
+            reactionsMX = mxCreateCellMatrix(1, NRREACTIONS);
+            for (k=0;k<NRREACTIONS;k++) mxSetCell(reactionsMX,k,mxCreateString(reactionnames[k]));
+            mxSetField(outputMX, 0, "reactions", reactionsMX);
+        }
+    }
+    if (NREVENTS > 0) {
+        eventsMX = mxCreateCellMatrix(1, NREVENTS);
+        for (k=0;k<NREVENTS;k++) mxSetCell(eventsMX,k,mxCreateString(eventnames[k]));
+        mxSetField(outputMX, 0, "events", eventsMX);
+        if (numberevents > 0) {
+            eventtimesMX = mxCreateDoubleMatrix(1,numberevents,mxREAL);
+            mxSetData(eventtimesMX, eventtimes);
+            mxSetField(outputMX, 0, "eventtimes", eventtimesMX);
+            eventflagsMX = mxCreateDoubleMatrix(NREVENTS,numberevents,mxREAL);
+            mxSetData(eventflagsMX, eventflagscollect);
+            mxSetField(outputMX, 0, "eventflags", eventflagsMX);
+        }
+    }
+    if (sensitivity) {
+        sensparamoutMX = mxCreateCellMatrix(1, nrsensparam);
+        sensitivityparamdataoutMX = mxCreateCellMatrix(1, nrsensparam);
+        for (k=0;k<nrsensparam;k++) {
+            mxSetCell(sensparamoutMX,k,mxCreateString(parameternames[sensparamstates[k]-1]));
+            mxSetCell(sensitivityparamdataoutMX,k,sensitivitydataparamMX[k]);
+        }
+        mxSetField(outputMX, 0, "sensparameters", sensparamoutMX);
+        mxSetField(outputMX, 0, "sensparamtrajectories", sensitivityparamdataoutMX);
+        sensstatesoutMX = mxCreateCellMatrix(1, nrsensstates);
+        sensitivitystatesdataoutMX = mxCreateCellMatrix(1, nrsensstates);
+        for (k=0;k<nrsensstates;k++) {
+            mxSetCell(sensstatesoutMX,k,mxCreateString(statenames[sensparamstates[nrsensparam+k]-1-NRPARAMETERS]));
+            mxSetCell(sensitivitystatesdataoutMX,k,sensitivitydatastatesMX[k]);
+        }
+        mxSetField(outputMX, 0, "sensicstatetrajectories", sensitivitystatesdataoutMX);
+        mxSetField(outputMX, 0, "sensicstates", sensstatesoutMX);
+    }
+    /* Return the output argument 'outputMX' */
+    plhs[0] = outputMX;
+}
+
+/*
+ *========================================================================
+ * Help function to add a row vector to a matrix
+ *========================================================================
+ */
+static void includeVectorInMatrix(double *matrix, double *rowvector, int row, int nrows, int ncols)
+{
+    int k;
+    for (k=0;k<ncols;k++) {
+        matrix[row+k*nrows] = rowvector[k];
+    }
+}
+
+/*
+ *========================================================================
+ * RHS function f(t,u) (INTERFACE TO CVODE)
+ *========================================================================
+ */
+static int f(double time, N_Vector u, N_Vector udot, void *f_data)
+{
+    double *statevector, *ODERHSvector;
+    
+int k;
+    
+    ModelData *modeldataPtr;
+    /* get pointer to modeldata */
+    modeldataPtr = (ModelData*) f_data;
+    /* connect input and output data */
+    statevector = NV_DATA_S(u);
+    ODERHSvector = NV_DATA_S(udot);
+    /* run the model */
+    model(time, statevector, ODERHSvector, modeldataPtr, CVODE_RHS, NULL, NULL, NULL, NULL);
+    
+for (k=0; k<9; k++) {
+    mexPrintf("%f: %f\n",statevector[k],ODERHSvector[k]);
+}
+    
+    return(0);
+}
+
+/*
+ *========================================================================
+ * Event function (INTERFACE TO CVODE)
+ *========================================================================
+ */
+static void g(double time, N_Vector y, double *gout, void *g_data)
+{
+    double *statevector;
+    ModelData *modeldataPtr;
+    /* get pointer to model data */
+    modeldataPtr = (ModelData*) g_data;
+    /* connect input data */
+    statevector = NV_DATA_S(y);
+    /* run the event function */
+    model(time, statevector, NULL, modeldataPtr, CVODE_EVENTS, NULL, NULL, gout, NULL);
+}
+
+/*
+ *========================================================================
+ * Error function ... 
+ *========================================================================
+ */
+static void error(char *text)
+{
+    mexErrMsgTxt(text);
+}
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/source_SUNDIALS_CVODES_25 b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/source_SUNDIALS_CVODES_25
new file mode 100644
index 0000000000000000000000000000000000000000..46b85751162bf1d89f21cdabf02833cccf2b983d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/source_SUNDIALS_CVODES_25
@@ -0,0 +1,572 @@
+/*
+ * CVODEmex25.c: MEX/CVODES Interface for Sundials CVODES version 2.5
+ *
+ * Information:
+ * ============
+ * SBPD Package - Systems Biology Parameter Determination Package
+ * Copyright 2008 by Henning Schmidt, henning@sbtoolbox2.org
+ */
+
+#include <mex.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <stdarg.h>
+#include <string.h>
+#include <matrix.h>
+#include <math.h>
+
+/* CVODES includes */
+#include <cvodes/cvodes.h>
+#include <nvector/nvector_serial.h>
+#include <sundials/sundials_types.h>
+#include <sundials/sundials_math.h>
+#include "CVODEmex25.h"
+
+/* Definitions for CVODES */
+#define ABSTOL  1.0e-6  
+#define RELTOL  1.0e-6  
+#define Ith(v,i) NV_Ith_S(v,i-1)
+
+/* Initialize functions */
+static void resetDelayInformation();
+static mxArray* handleInputArguments(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]);
+static mxArray* doXdotCalc();
+static void allocSimMemory();
+static void initCVODE();
+static void integrate();
+static mxArray* constructOutput();
+static void addVec2Mat(double *matrix, double *rowvector, int row, int nrows, int ncols);
+static int f(double time, N_Vector u, N_Vector udot, void *f_data);
+static int g(double time, N_Vector y, double *gout, void *g_data);
+static void errorMsg(char *text);
+static void freeMem();
+
+/* Some global variables for the interface */
+int k,k2;   /* some loop variables */
+
+int length2check;
+
+char stringbuffer[256];
+
+mxArray *timesimvectorMX = NULL;
+double *timesimvector = NULL;
+
+mxArray *parametervectorMX = NULL;
+double *parametervector = NULL;
+double *parametervectorCVODES = NULL; 
+
+mxArray *initialconditionsMX = NULL;
+double *initialconditions = NULL;
+
+mxArray *optionsMX = NULL;
+
+mxArray *minstepMX = NULL;
+double minstep;
+
+mxArray *maxstepMX = NULL;
+double maxstep;
+
+mxArray *maxnumstepsMX = NULL;
+long int maxnumsteps;
+
+mxArray *reltolMX = NULL;
+double reltol;
+
+mxArray *abstolMX = NULL;
+double abstol;
+
+mxArray *xdotcalcMX = NULL;
+double xdotcalc;
+
+int numbertimesteps;
+
+mxArray *resultMX = NULL;
+double *result = NULL;
+
+mxArray *statesMX = NULL;
+
+mxArray *statevaluesMX = NULL;
+double *statevalues = NULL;
+
+mxArray *variablesMX = NULL;
+
+mxArray *variablevaluesMX = NULL;
+double *variablevalues = NULL;
+
+mxArray *reactionsMX = NULL;
+
+mxArray *reactionvaluesMX = NULL;
+double *reactionvalues = NULL;
+
+mxArray *eventsMX = NULL;
+
+mxArray *eventtimesMX = NULL;
+double *eventtimes = NULL;
+
+mxArray *eventflagsMX = NULL;
+double *eventflags = NULL;
+
+/* CVODES needed data */
+ParamData modeldata;
+N_Vector u = NULL;
+void *cvode_mem;
+int flag, flagroot;
+double treturn;
+double tendstep;
+
+/* Interface to model RHS */
+double *statevec = NULL;
+double *variablevec = NULL;
+double *reactionvec = NULL;
+int *eventvec = NULL;
+double *eventdataold = NULL;
+int nreventshappend;
+double *eventflagsdata = NULL;
+double eventcorrecttest;
+
+/* Error Flags */
+int timevectorEmpty = 0;
+int timevectorNotVector = 0;
+  
+/*
+ *========================================================================
+ * MEX INTERFACE FOR MEX SIMULATION MODELS
+ *========================================================================
+ */
+void CVODEmex25(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
+{
+    /* Handle variable input arguments */
+    resultMX = handleInputArguments(nlhs, plhs, nrhs, prhs);
+    if (resultMX != NULL) {
+        /* No integration requested */
+        plhs[0] = resultMX;
+        return;
+    }
+    /* check if integration or xdot calculation */
+    if (xdotcalc != 0) {
+        /* return the RHS of the ODEs at given state and parameter values */
+        resultMX = doXdotCalc();
+        plhs[0] = resultMX;
+        return;
+    }
+    /* Do error checks ... timevector needs to be defined if integration is to be done! */
+    if (timevectorEmpty == 1) mexErrMsgTxt("Timevector is empty.");
+    if (timevectorNotVector == 1) mexErrMsgTxt("'timevector' input argument needs to be a vector.");
+    /* Otherwise do the integration */
+    /* Allocate memory for the simulation */
+    allocSimMemory();
+    /* Initialize CVODES */
+    initCVODE();
+    /* Integrate */
+    integrate();
+    /* Construct result */
+    plhs[0] = constructOutput();
+    /* Free allocated memory */
+    freeMem();
+}
+
+/*
+ *========================================================================
+ * Reset delay information
+ *========================================================================
+ */
+static void resetDelayInformation()
+{
+    for (k=0; k<NRDELAYS; k++) {
+        delaydataMX[k] = NULL;
+        delaytimeMX[k] = NULL;
+        delaytimearraylengths[k] = 0;
+    }
+}
+
+/*
+ *========================================================================
+ * Help function to add a row vector to a matrix
+ *========================================================================
+ */
+static void addVec2Mat(double *matrix, double *rowvector, int row, int nrrows, int nrcols)
+{
+    int k;
+    for (k=0;k<nrcols;k++) {
+        matrix[row+k*nrrows] = rowvector[k];
+    }
+}
+
+/*
+ *========================================================================
+ * RHS function f(t,u) 
+ *========================================================================
+ */
+static int f(double time, N_Vector u, N_Vector udot, void *f_data)
+{
+    double *statevec, *DDTvector;
+    ParamData *paramdataPtr;
+    /* get pointer to modeldata */
+    paramdataPtr = (ParamData*) f_data;
+    /* connect input and result data */
+    statevec = NV_DATA_S(u);
+    DDTvector = NV_DATA_S(udot);
+    /* run the model */
+    model(time, statevec, DDTvector, paramdataPtr, DOFLAG_DDT, NULL, NULL, NULL, NULL);
+    return(0);
+}
+
+/*
+ *========================================================================
+ * Event function 
+ *========================================================================
+ */
+static int g(double time, N_Vector y, double *gout, void *g_data)
+{
+    double *statevec;
+    ParamData *paramdataPtr;
+    /* get pointer to model data */
+    paramdataPtr = (ParamData*) g_data;
+    /* connect input data */
+    statevec = NV_DATA_S(y);
+    /* run the event function */
+    model(time, statevec, NULL, paramdataPtr, DOFLAG_EVENTS, NULL, NULL, gout, NULL);
+    return(0);
+}
+
+/*
+ *========================================================================
+ * Error function 
+ *========================================================================
+ */
+static void errorMsg(char *text)
+{
+    /* First free the allocated memory */
+    freeMem();
+    /* Then print error message and exit */
+    mexErrMsgTxt(text);
+}
+
+/*
+ *========================================================================
+ * Free the memory 
+ *========================================================================
+ */
+static void freeMem()
+{
+    /* Free all CVODE related memory */
+    N_VDestroy_Serial(u);  /* Free the u vector */
+    CVodeFree(&cvode_mem);  /* Free the integrator memory */
+    /* Free delay related memory if allocated */
+    for (k=0; k<NRDELAYS; k++) {
+        if (delaydataMX[k] != NULL) { mxDestroyArray(delaydataarrays[k]); delaydataMX[k] = NULL; }
+        if (delaytimeMX[k] != NULL) { mxDestroyArray(delaytimearrays[k]); delaytimeMX[k] = NULL; }
+    }
+}
+
+    /*
+     * ==============================================
+     * HANDLE THE VARIABLE INPUT ARGUMENTS
+     * ==============================================
+     */
+static mxArray* handleInputArguments(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
+{
+    if (nrhs == 0) {
+        resultMX = mxCreateDoubleMatrix(NRSTATES, 1, mxREAL);
+        result = mxGetPr(resultMX);
+        for (k=0; k<NRSTATES; k++) result[k] = defaultICs[k];
+        return resultMX;
+    } else if (nrhs == 1) {
+        if (mxIsEmpty(prhs[0])) {
+            mexErrMsgTxt("Timevector is empty.");
+        } 
+        if (mxIsChar(prhs[0])) {
+            length2check = (mxGetM(prhs[0]) * mxGetN(prhs[0]));
+            if (length2check == 6) {       
+                resultMX = mxCreateCellMatrix(NRSTATES, 1);
+                for (k=0; k<NRSTATES; k++) mxSetCell(resultMX,k,mxCreateString(stateNames[k]));
+                return resultMX;
+            }
+            else if (length2check == 10) { 
+                resultMX = mxCreateCellMatrix(NRPARAMETERS, 1);
+                for (k=0; k<NRPARAMETERS; k++) mxSetCell(resultMX,k,mxCreateString(parameterNames[k]));
+                return resultMX;
+            }
+            else if (length2check == 15) { 
+                resultMX = mxCreateDoubleMatrix(NRPARAMETERS, 1, mxREAL);
+                result = mxGetPr(resultMX);
+                for (k=0; k<NRPARAMETERS; k++) result[k] = defaultParam[k];
+                return resultMX;
+            } else mexErrMsgTxt("Incorrect input argument.");
+        } else {
+            if (!mxIsDouble(prhs[0])) mexErrMsgTxt("Check the 'timevector' (first) input argument.");
+            /* if no error then the first argument is the timevector for simulation */
+            timesimvectorMX = (mxArray *) prhs[0];
+        }
+    } else {
+        if (!mxIsDouble(prhs[0])) mexErrMsgTxt("Check 'timevector' (first) input argument.");
+        timesimvectorMX = (mxArray *) prhs[0];
+        if (nrhs >= 2) {
+            if (!mxIsDouble(prhs[1]) && !mxIsEmpty(prhs[1])) mexErrMsgTxt("Check 'initialconditions' (second) input argument.");
+            initialconditionsMX = (mxArray *) prhs[1];
+        }
+        if (nrhs >= 3) {
+            if (!mxIsDouble(prhs[2]) && !mxIsEmpty(prhs[2])) mexErrMsgTxt("Check 'parametervector' (third) input argument.");
+            parametervectorMX = (mxArray *) prhs[2];
+        } 
+        if (nrhs >= 4) {
+            if (!mxIsStruct(prhs[3]) && !mxIsEmpty(prhs[3])) mexErrMsgTxt("Check 'options' (fourth) input argument.");
+            optionsMX = (mxArray *) prhs[3];
+        }
+        if (nrhs >= 5) {
+            mexErrMsgTxt("Incorrect number of input arguments.");
+        }
+    }
+    /* process timevector only if not empty */
+    if (!mxIsEmpty(timesimvectorMX)) {
+        numbertimesteps = mxGetM(timesimvectorMX)*mxGetN(timesimvectorMX);
+        if (numbertimesteps == 1 || (mxGetN(timesimvectorMX) > 1 && mxGetM(timesimvectorMX) > 1)) timevectorNotVector = 1;
+        else timesimvector = mxGetPr(timesimvectorMX);
+    } else {
+        /* set error flag for simulation case */
+        timevectorEmpty = 1;
+    }
+    /* process initial conditions */
+    initialconditions = (double *) mxCalloc(NRSTATES,sizeof(double));
+    for (k=0;k<NRSTATES;k++) initialconditions[k] = defaultICs[k];
+    if (initialconditionsMX != NULL) {
+        if (!mxIsEmpty(initialconditionsMX)) {
+            if (mxGetN(initialconditionsMX)*mxGetM(initialconditionsMX) != NRSTATES || (mxGetN(initialconditionsMX) > 1 && mxGetM(initialconditionsMX) > 1)) mexErrMsgTxt("'initialconditions' needs to be a vector of 'number states' length.");
+            initialconditions = mxGetPr(mxDuplicateArray(initialconditionsMX));
+        }
+    }
+    /* check parametervector */
+    parametervector = defaultParam;
+    if (parametervectorMX != NULL) {
+        if (!mxIsEmpty(parametervectorMX)) {
+            if (mxGetN(parametervectorMX)*mxGetM(parametervectorMX) != NRPARAMETERS || (mxGetN(parametervectorMX) > 1 && mxGetM(parametervectorMX) > 1)) mexErrMsgTxt("'parametervector' needs to be a vector of 'number parameters' length.");
+            parametervector = mxGetPr(parametervectorMX);
+        }
+    }
+    /* assign parametervector to modeldata struct */
+    modeldata.parametervector = parametervector;
+    /* check options */
+    minstep = -1;
+    maxstep = -1;
+    maxnumsteps = -1; 
+    reltol = RELTOL;  
+    abstol = ABSTOL;  
+    xdotcalc = 0;
+    if (optionsMX != NULL) {
+        if (!mxIsEmpty(optionsMX)) {
+            minstepMX = mxGetField(optionsMX, 0, "minstep");
+            if (minstepMX != NULL) 
+                if (mxIsDouble(minstepMX)) 
+                    minstep = mxGetScalar(minstepMX); 
+                else 
+                    mexErrMsgTxt("'options.minstep' wrongly defined.");
+            maxstepMX = mxGetField(optionsMX, 0, "maxstep");
+            if (maxstepMX != NULL) 
+                if (mxIsDouble(maxstepMX)) 
+                    maxstep = mxGetScalar(maxstepMX); 
+                else 
+                    mexErrMsgTxt("'options.maxstep' wrongly defined.");
+            maxnumstepsMX = mxGetField(optionsMX, 0, "maxnumsteps");
+            if (maxnumstepsMX != NULL) 
+                if (mxIsDouble(maxnumstepsMX)) 
+                    maxnumsteps = (long int)mxGetScalar(maxnumstepsMX); 
+                else 
+                    mexErrMsgTxt("'options.maxnumsteps' wrongly defined.");
+            reltolMX = mxGetField(optionsMX, 0, "reltol");
+            if (reltolMX != NULL) 
+                if (mxIsDouble(reltolMX)) 
+                    reltol = mxGetScalar(reltolMX); 
+                else 
+                    mexErrMsgTxt("'options.reltol' wrongly defined.");
+            abstolMX = mxGetField(optionsMX, 0, "abstol");
+            if (abstolMX != NULL) 
+                if (mxIsDouble(abstolMX)) 
+                    abstol = mxGetScalar(abstolMX); 
+                else 
+                    mexErrMsgTxt("'options.abstol' wrongly defined.");
+            xdotcalcMX = mxGetField(optionsMX, 0, "xdotcalc");
+            if (xdotcalcMX != NULL) 
+                if (mxIsDouble(xdotcalcMX)) 
+                    xdotcalc = mxGetScalar(xdotcalcMX); 
+                else 
+                    mexErrMsgTxt("'options.xdotcalc' wrongly defined.");
+        }
+    }
+    return NULL;
+}
+
+    /*
+     * ==============================================
+     * GET RHS OF ODEs (fir time = 0)
+     * ==============================================
+     */
+static mxArray* doXdotCalc()
+{
+    resultMX = mxCreateDoubleMatrix(NRSTATES, 1, mxREAL);
+    result = mxGetPr(resultMX);
+    model(0.0, initialconditions, result, &modeldata, DOFLAG_DDT, NULL, NULL, NULL, NULL);
+    return resultMX;
+}
+
+    /*
+     * ==============================================
+     * ALLOCATE MEMORY 
+     * ==============================================
+     */
+static void allocSimMemory()
+{
+    statevaluesMX = mxCreateDoubleMatrix(numbertimesteps, NRSTATES, mxREAL);
+    statevalues = mxGetPr(statevaluesMX);
+    if (NRVARIABLES > 0) {
+        variablevec = (double *) mxCalloc(NRVARIABLES, sizeof(double));
+        variablevaluesMX = mxCreateDoubleMatrix(numbertimesteps, NRVARIABLES, mxREAL);
+        variablevalues = mxGetPr(variablevaluesMX);
+    }
+    if (NRREACTIONS > 0) {
+        reactionvec = (double *) mxCalloc(NRREACTIONS, sizeof(double));
+        reactionvaluesMX = mxCreateDoubleMatrix(numbertimesteps, NRREACTIONS, mxREAL);
+        reactionvalues = mxGetPr(reactionvaluesMX);
+    }
+    if (NREVENTS > 0) {
+        eventvec = (int *) mxCalloc(NREVENTS, sizeof(int));
+        eventdataold = (double *) mxCalloc(NREVENTS, sizeof(double));
+    }
+}
+    
+    /*
+     * ==============================================
+     * INITIALIZE INTEGRATOR
+     * ==============================================
+     */
+static void initCVODE()
+{
+    u = N_VMake_Serial(NRSTATES,initialconditions);
+    cvode_mem = CVodeCreate(CV_BDF, CV_NEWTON);
+    CVodeMalloc(cvode_mem, f, timesimvector[0], u, CV_SS, reltol, &abstol);
+    if (NREVENTS > 0) {
+        CVodeRootInit(cvode_mem, NREVENTS, g, &modeldata);
+    }
+    CVodeSetFdata(cvode_mem, &modeldata);
+    if (minstep > 0) CVodeSetMinStep(cvode_mem, minstep);
+    if (maxstep > 0) CVodeSetMaxStep(cvode_mem, maxstep);
+    if (maxnumsteps > 0) CVodeSetMaxNumSteps(cvode_mem, maxnumsteps);
+	CVDense(cvode_mem,NRSTATES);
+}
+
+    /*
+     * ==============================================
+     * DO THE INTEGRATION
+     * ==============================================
+     */
+static void integrate()
+{
+    addVec2Mat(statevalues,initialconditions,0,numbertimesteps,NRSTATES);
+    model(timesimvector[0], initialconditions, NULL, &modeldata, DOFLAG_VARREAC, variablevec, reactionvec,NULL,NULL);
+    if (NRVARIABLES > 0) addVec2Mat(variablevalues,variablevec,0,numbertimesteps,NRVARIABLES);
+    if (NRREACTIONS > 0) addVec2Mat(reactionvalues,reactionvec,0,numbertimesteps,NRREACTIONS);
+    if (NREVENTS > 0) /* determine eventdataold to be able to detect directions of events */
+        model(timesimvector[0], initialconditions, NULL, &modeldata, DOFLAG_EVENTS, NULL, NULL, eventdataold, NULL);
+    k = 1;
+    tendstep = timesimvector[k]; 
+    nreventshappend = 0; 
+    while(1) {
+        flag = CVode(cvode_mem, tendstep, u, &treturn, CV_NORMAL);
+        if (flag < 0) {
+            if (flag == CV_TOO_MUCH_WORK) errorMsg("CVODE Error: CV_TOO_MUCH_WORK");
+            else if (flag == CV_TOO_MUCH_ACC) errorMsg("CVODE Error: CV_TOO_MUCH_ACC");
+            else if (flag == CV_ERR_FAILURE || flag == CV_CONV_FAILURE) errorMsg("CVODE Error: CV_ERR_FAILURE");
+            else {
+                sprintf(stringbuffer, "CVODE Error Flag: %d",flag);
+                errorMsg(stringbuffer);
+            }
+        }
+        statevec = NV_DATA_S(u);
+        if (flag == CV_ROOT_RETURN) {
+            /* Event happened */
+            CVodeGetRootInfo(cvode_mem, eventvec);
+            eventcorrecttest = 0;
+            model(treturn, statevec, &eventcorrecttest, &modeldata, DOFLAG_EVENTASSIGN, NULL, NULL, eventdataold, eventvec);
+            flag = CVodeReInit(cvode_mem, f, treturn, u, CV_SS, reltol, &abstol);
+            if (eventcorrecttest > 0) {
+                nreventshappend += 1;  
+                if (nreventshappend == 1) {
+                    eventtimes = (double *) mxCalloc(1, sizeof(double));
+                    eventflagsdata = (double *) mxCalloc(NREVENTS, sizeof(double));
+                } else {
+                    eventtimes = (double *) mxRealloc((void *) eventtimes, nreventshappend*sizeof(double));
+                    eventflagsdata = (double *) mxRealloc((void *) eventflagsdata, NREVENTS*nreventshappend*sizeof(double));
+                }
+                eventtimes[nreventshappend-1] = treturn;
+                for (k2=0;k2<NREVENTS;k2++) eventflagsdata[NREVENTS*(nreventshappend-1)+k2] = (double)eventvec[k2];
+            }
+        }
+        if (tendstep == treturn) { 
+            addVec2Mat(statevalues,statevec,k,numbertimesteps,NRSTATES);
+            model(tendstep, statevec, NULL, &modeldata, DOFLAG_VARREAC, variablevec, reactionvec, NULL, NULL);
+            if (NRVARIABLES > 0) addVec2Mat(variablevalues,variablevec,k,numbertimesteps,NRVARIABLES);
+            if (NRREACTIONS > 0) addVec2Mat(reactionvalues,reactionvec,k,numbertimesteps,NRREACTIONS);
+            k = k+1;
+            if (k < numbertimesteps) 
+                tendstep = timesimvector[k];
+            else 
+                break; 
+        }
+        if (NREVENTS > 0) /* determine eventdataold to be able to detect directions of events */
+            model(treturn, statevec, NULL, &modeldata, DOFLAG_EVENTS, NULL, NULL, eventdataold, NULL);
+    }
+}
+
+    /*
+     * ==============================================
+     * CONSTRUCT OUTPUT VARIABLE
+     * ==============================================
+     */
+static mxArray* constructOutput()
+{
+    resultMX = mxCreateStructMatrix(1,1,0,NULL);
+    /* Create fields in result structure */
+    mxAddField(resultMX,"time");
+    mxAddField(resultMX,"states");
+    mxAddField(resultMX,"statevalues");
+    mxAddField(resultMX,"variables");
+    mxAddField(resultMX,"variablevalues");
+    mxAddField(resultMX,"reactions");
+    mxAddField(resultMX,"reactionvalues");
+    if (NREVENTS > 0) {
+        mxAddField(resultMX,"events");
+        mxAddField(resultMX,"eventtimes");
+        mxAddField(resultMX,"eventflags");
+    }
+    mxSetField(resultMX, 0, "time", mxDuplicateArray(timesimvectorMX));
+    mxSetField(resultMX, 0, "statevalues", statevaluesMX);
+    if (NRVARIABLES > 0) mxSetField(resultMX, 0, "variablevalues", variablevaluesMX);
+    if (NRREACTIONS > 0) mxSetField(resultMX, 0, "reactionvalues", reactionvaluesMX);
+    statesMX = mxCreateCellMatrix(1, NRSTATES);
+    for (k=0;k<NRSTATES;k++) mxSetCell(statesMX,k,mxCreateString(stateNames[k]));
+    mxSetField(resultMX, 0, "states", statesMX);
+    if (NRVARIABLES > 0) {
+        variablesMX = mxCreateCellMatrix(1, NRVARIABLES);
+        for (k=0;k<NRVARIABLES;k++) mxSetCell(variablesMX,k,mxCreateString(variableNames[k]));
+        mxSetField(resultMX, 0, "variables", variablesMX);
+    }
+    if (NRREACTIONS > 0) {
+        reactionsMX = mxCreateCellMatrix(1, NRREACTIONS);
+        for (k=0;k<NRREACTIONS;k++) mxSetCell(reactionsMX,k,mxCreateString(reactionNames[k]));
+        mxSetField(resultMX, 0, "reactions", reactionsMX);
+    }
+    if (NREVENTS > 0) {
+        eventsMX = mxCreateCellMatrix(1, NREVENTS);
+        for (k=0;k<NREVENTS;k++) mxSetCell(eventsMX,k,mxCreateString(eventNames[k]));
+        mxSetField(resultMX, 0, "events", eventsMX);
+        if (nreventshappend > 0) {
+            eventtimesMX = mxCreateDoubleMatrix(1,nreventshappend,mxREAL);
+            mxSetData(eventtimesMX, eventtimes);
+            mxSetField(resultMX, 0, "eventtimes", eventtimesMX);
+            eventflagsMX = mxCreateDoubleMatrix(NREVENTS,nreventshappend,mxREAL);
+            mxSetData(eventflagsMX, eventflagsdata);
+            mxSetField(resultMX, 0, "eventflags", eventflagsMX);
+        }
+    }
+    return resultMX;
+}
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/sundials_band.c b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/sundials_band.c
new file mode 100644
index 0000000000000000000000000000000000000000..956e884fa8520a5bae78c20e579ee262027d28fb
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/sundials_band.c
@@ -0,0 +1,371 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * -----------------------------------------------------------------
+ * Programmer(s): Alan C. Hindmarsh and Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2002, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the implementation file for a generic BAND linear
+ * solver package.
+ * -----------------------------------------------------------------
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <sundials/sundials_band.h>
+#include <sundials/sundials_math.h>
+
+#define ZERO RCONST(0.0)
+#define ONE  RCONST(1.0)
+
+#define ROW(i,j,smu) (i-j+smu)
+
+/* Implementation */
+
+BandMat BandAllocMat(long int N, long int mu, long int ml, long int smu)
+{
+  BandMat A;
+
+  if (N <= 0) return(NULL);
+  
+  A = NULL;
+  A = (BandMat) malloc(sizeof *A);
+  if (A == NULL) return (NULL);
+
+  A->data = NULL;
+  A->data = bandalloc(N, smu, ml);
+  if (A->data == NULL) {
+    free(A); A = NULL;
+    return(NULL);
+  }
+  
+  A->size = N;
+  A->mu = mu;
+  A->ml = ml;
+  A->smu = smu;
+
+  return(A);
+}
+
+long int *BandAllocPiv(long int N)
+{
+  return(bandallocpiv(N));
+}
+
+long int BandGBTRF(BandMat A, long int *p)
+{
+  return(bandGBTRF(A->data, A->size, A->mu, A->ml, A->smu, p));
+}
+
+void BandGBTRS(BandMat A, long int *p, realtype *b)
+{
+  bandGBTRS(A->data, A->size, A->smu, A->ml, p, b);
+}
+
+void BandZero(BandMat A)
+{
+  bandzero(A->data, A->size, A->mu, A->ml, A->smu);
+}
+
+void BandCopy(BandMat A, BandMat B, long int copymu, 
+              long int copyml)
+{
+  bandcopy(A->data, B->data, A->size, A->smu, B->smu, copymu, copyml);
+}
+
+void BandScale(realtype c, BandMat A)
+{
+  bandscale(c, A->data, A->size, A->mu, A->ml, A->smu);
+}
+
+void BandAddI(BandMat A)
+{
+  bandaddI(A->data, A->size, A->smu);
+}
+
+void BandFreeMat(BandMat A)
+{
+  bandfree(A->data);
+  free(A); A = NULL;
+}
+
+void BandFreePiv(long int *p)
+{ 
+  bandfreepiv(p);
+}
+
+void BandPrint(BandMat A)
+{
+  bandprint(A->data, A->size, A->mu, A->ml, A->smu);
+}
+
+realtype **bandalloc(long int n, long int smu, long int ml)
+{
+  realtype **a;
+  long int j, colSize;
+
+  if (n <= 0) return(NULL);
+
+  a = NULL;
+  a = (realtype **) malloc(n * sizeof(realtype *));
+  if (a == NULL) return(NULL);
+
+  colSize = smu + ml + 1;
+  a[0] = NULL;
+  a[0] = (realtype *) malloc(n * colSize * sizeof(realtype));
+  if (a[0] == NULL) {
+    free(a); a = NULL;
+    return(NULL);
+  }
+
+  for (j=1; j < n; j++) a[j] = a[0] + j * colSize;
+
+  return(a);
+}
+
+long int *bandallocpiv(long int n)
+{
+  long int *piv;
+
+  if (n <= 0) return(NULL);
+
+  piv = NULL;
+  piv = (long int *) malloc(n * sizeof(long int));
+  if (piv == NULL) return(NULL);
+
+  return(piv);
+}
+
+long int bandGBTRF(realtype **a, long int n, long int mu, long int ml, 
+                   long int smu, long int *p)
+{
+  long int c, r, num_rows;
+  long int i, j, k, l, storage_l, storage_k, last_col_k, last_row_k;
+  realtype *a_c, *col_k, *diag_k, *sub_diag_k, *col_j, *kptr, *jptr;
+  realtype max, temp, mult, a_kj;
+  booleantype swap;
+
+  /* zero out the first smu - mu rows of the rectangular array a */
+
+  num_rows = smu - mu;
+  if (num_rows > 0) {
+    for (c=0; c < n; c++) {
+      a_c = a[c];
+      for (r=0; r < num_rows; r++) {
+	a_c[r] = ZERO;
+      }
+    }
+  }
+
+  /* k = elimination step number */
+
+  for (k=0; k < n-1; k++, p++) {
+    
+    col_k     = a[k];
+    diag_k    = col_k + smu;
+    sub_diag_k = diag_k + 1;
+    last_row_k = MIN(n-1,k+ml);
+
+    /* find l = pivot row number */
+
+    l=k;
+    max = ABS(*diag_k);
+    for (i=k+1, kptr=sub_diag_k; i <= last_row_k; i++, kptr++) { 
+      if (ABS(*kptr) > max) {
+	l=i;
+	max = ABS(*kptr);
+      }
+    }
+    storage_l = ROW(l, k, smu);
+    *p = l;
+    
+    /* check for zero pivot element */
+
+    if (col_k[storage_l] == ZERO) return(k+1);
+    
+    /* swap a(l,k) and a(k,k) if necessary */
+    
+    if ( (swap = (l != k) )) {
+      temp = col_k[storage_l];
+      col_k[storage_l] = *diag_k;
+      *diag_k = temp;
+    }
+
+    /* Scale the elements below the diagonal in         */
+    /* column k by -1.0 / a(k,k). After the above swap, */
+    /* a(k,k) holds the pivot element. This scaling     */
+    /* stores the pivot row multipliers -a(i,k)/a(k,k)  */
+    /* in a(i,k), i=k+1, ..., MIN(n-1,k+ml).            */
+    
+    mult = -ONE / (*diag_k);
+    for (i=k+1, kptr = sub_diag_k; i <= last_row_k; i++, kptr++)
+      (*kptr) *= mult;
+
+    /* row_i = row_i - [a(i,k)/a(k,k)] row_k, i=k+1, ..., MIN(n-1,k+ml) */
+    /* row k is the pivot row after swapping with row l.                */
+    /* The computation is done one column at a time,                    */
+    /* column j=k+1, ..., MIN(k+smu,n-1).                               */
+    
+    last_col_k = MIN(k+smu,n-1);
+    for (j=k+1; j <= last_col_k; j++) {
+      
+      col_j = a[j];
+      storage_l = ROW(l,j,smu); 
+      storage_k = ROW(k,j,smu); 
+      a_kj = col_j[storage_l];
+
+      /* Swap the elements a(k,j) and a(k,l) if l!=k. */
+      
+      if (swap) {
+	col_j[storage_l] = col_j[storage_k];
+	col_j[storage_k] = a_kj;
+      }
+
+      /* a(i,j) = a(i,j) - [a(i,k)/a(k,k)]*a(k,j) */
+      /* a_kj = a(k,j), *kptr = - a(i,k)/a(k,k), *jptr = a(i,j) */
+
+      if (a_kj != ZERO) {
+	for (i=k+1, kptr=sub_diag_k, jptr=col_j+ROW(k+1,j,smu);
+	     i <= last_row_k;
+	     i++, kptr++, jptr++)
+	  (*jptr) += a_kj * (*kptr);
+      }
+    }    
+  }
+  
+  /* set the last pivot row to be n-1 and check for a zero pivot */
+
+  *p = n-1; 
+  if (a[n-1][smu] == ZERO) return(n);
+
+  /* return 0 to indicate success */
+
+  return(0);
+}
+
+void bandGBTRS(realtype **a, long int n, long int smu, long int ml, 
+               long int *p, realtype *b)
+{
+  long int k, l, i, first_row_k, last_row_k;
+  realtype mult, *diag_k;
+  
+  /* Solve Ly = Pb, store solution y in b */
+  
+  for (k=0; k < n-1; k++) {
+    l = p[k];
+    mult = b[l];
+    if (l != k) {
+      b[l] = b[k];
+      b[k] = mult;
+    }
+    diag_k = a[k]+smu;
+    last_row_k = MIN(n-1,k+ml);
+    for (i=k+1; i <= last_row_k; i++)
+      b[i] += mult * diag_k[i-k];
+  }
+  
+  /* Solve Ux = y, store solution x in b */
+  
+  for (k=n-1; k >= 0; k--) {
+    diag_k = a[k]+smu;
+    first_row_k = MAX(0,k-smu);
+    b[k] /= (*diag_k);
+    mult = -b[k];
+    for (i=first_row_k; i <= k-1; i++)
+      b[i] += mult*diag_k[i-k];
+  }
+}
+
+void bandzero(realtype **a, long int n, long int mu, long int ml, 
+              long int smu)
+{
+  long int i, j, colSize;
+  realtype *col_j;
+
+  colSize = mu + ml + 1;
+  for (j=0; j < n; j++) {
+    col_j = a[j]+smu-mu;
+    for (i=0; i < colSize; i++)
+      col_j[i] = ZERO;
+  }
+}
+
+void bandcopy(realtype **a, realtype **b, long int n, long int a_smu, 
+              long int b_smu, long int copymu, long int copyml)
+{
+  long int i, j, copySize;
+  realtype *a_col_j, *b_col_j;
+
+  copySize = copymu + copyml + 1;
+ 
+  for (j=0; j < n; j++) {
+    a_col_j = a[j]+a_smu-copymu;
+    b_col_j = b[j]+b_smu-copymu;
+    for (i=0; i < copySize; i++)
+      b_col_j[i] = a_col_j[i];
+  }
+}
+
+void bandscale(realtype c, realtype **a, long int n, long int mu, 
+               long int ml, long int smu)
+{
+  long int i, j, colSize;
+  realtype *col_j;
+
+  colSize = mu + ml + 1;
+
+  for(j=0; j < n; j++) {
+    col_j = a[j]+smu-mu;
+    for (i=0; i < colSize; i++)
+      col_j[i] *= c;
+  }
+}
+
+void bandaddI(realtype **a, long int n, long int smu)
+{
+  long int j;
+ 
+  for(j=0; j < n; j++)
+    a[j][smu] += ONE;
+}
+
+void bandfreepiv(long int *p)
+{
+  free(p); p = NULL;
+}
+
+void bandfree(realtype **a)
+{
+  free(a[0]); a[0] = NULL;
+  free(a); a = NULL;
+}
+
+void bandprint(realtype **a, long int n, long int mu, long int ml, 
+               long int smu)
+{
+  long int i, j, start, finish;
+ 
+  printf("\n");
+  for (i=0; i < n; i++) {
+    start = MAX(0,i-ml);
+    finish = MIN(n-1,i+mu);
+    for (j=0; j < start; j++) printf("%12s  ","");
+    for (j=start; j <= finish; j++) {
+#if defined(SUNDIALS_EXTENDED_PRECISION)
+      printf("%12Lg  ", a[j][i-j+smu]);
+#elif defined(SUNDIALS_DOUBLE_PRECISION)
+      printf("%12lg  ", a[j][i-j+smu]);
+#else
+      printf("%12g  ", a[j][i-j+smu]);
+#endif
+    }
+    printf("\n");
+  }
+  printf("\n");
+}
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/sundials_dense.c b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/sundials_dense.c
new file mode 100644
index 0000000000000000000000000000000000000000..3a52a3853f59915933afcbcca1558f58d94b2221
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/sundials_dense.c
@@ -0,0 +1,102 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * -----------------------------------------------------------------
+ * Programmer(s): Scott D. Cohen, Alan C. Hindmarsh and
+ *                Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2002, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the implementation file for a generic package of dense
+ * matrix operations.
+ * -----------------------------------------------------------------
+ */ 
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <sundials/sundials_dense.h>
+#include <sundials/sundials_math.h>
+
+#define ZERO RCONST(0.0)
+#define ONE  RCONST(1.0)
+
+/* Implementation */
+
+DenseMat DenseAllocMat(long int M, long int N)
+{
+  DenseMat A;
+
+  /* Note that M and N are tested in denalloc */
+
+  A = NULL;
+  A = (DenseMat) malloc(sizeof *A);
+  if (A==NULL) return (NULL);
+  
+  A->data = NULL;
+  A->data = denalloc(M, N);
+  if (A->data == NULL) {
+    free(A); A = NULL;
+    return(NULL);
+  }
+
+  A->M = M;
+  A->N = N;
+
+  return(A);
+}
+
+long int *DenseAllocPiv(long int N)
+{
+  return(denallocpiv(N));
+}
+
+long int DenseGETRF(DenseMat A, long int *p)
+{
+  return(denGETRF(A->data, A->M, A->N, p));
+}
+
+void DenseGETRS(DenseMat A, long int *p, realtype *b)
+{
+  denGETRS(A->data, A->N, p, b);
+}
+
+void DenseZero(DenseMat A)
+{
+  denzero(A->data, A->M, A->N);
+}
+
+void DenseCopy(DenseMat A, DenseMat B)
+{
+  dencopy(A->data, B->data, A->M, A->N);
+}
+
+void DenseScale(realtype c, DenseMat A)
+{
+  denscale(c, A->data, A->M, A->N);
+}
+
+void DenseAddI(DenseMat A)
+{
+  denaddI(A->data, A->N);
+}
+
+void DenseFreeMat(DenseMat A)
+{
+  denfree(A->data);
+  free(A); A = NULL;
+}
+
+void DenseFreePiv(long int *p)
+{  
+  denfreepiv(p);
+}
+
+void DensePrint(DenseMat A)
+{
+  denprint(A->data, A->M, A->N);
+}
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/sundials_iterative.c b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/sundials_iterative.c
new file mode 100644
index 0000000000000000000000000000000000000000..36a17c76b6699d3cf6f6feacbea15830ec3a50c3
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/sundials_iterative.c
@@ -0,0 +1,288 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Scott D. Cohen, Alan C. Hindmarsh and
+ *                Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2002, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the implementation file for the iterative.h header
+ * file. It contains the implementation of functions that may be
+ * useful for many different iterative solvers of A x = b.
+ * -----------------------------------------------------------------
+ */
+
+#include <stdio.h>
+
+#include <sundials/sundials_iterative.h>
+#include <sundials/sundials_math.h>
+
+#define FACTOR RCONST(1000.0)
+#define ZERO   RCONST(0.0)
+#define ONE    RCONST(1.0)
+
+/*
+ * -----------------------------------------------------------------
+ * Function : ModifiedGS
+ * -----------------------------------------------------------------
+ * This implementation of ModifiedGS is a slight modification of a
+ * previous modified Gram-Schmidt routine (called mgs) written by
+ * Milo Dorr.
+ * -----------------------------------------------------------------
+ */
+ 
+int ModifiedGS(N_Vector *v, realtype **h, int k, int p, 
+               realtype *new_vk_norm)
+{
+  int  i, k_minus_1, i0;
+  realtype new_norm_2, new_product, vk_norm, temp;
+  
+  vk_norm = RSqrt(N_VDotProd(v[k],v[k]));
+  k_minus_1 = k - 1;
+  i0 = MAX(k-p, 0);
+  
+  /* Perform modified Gram-Schmidt */
+  
+  for (i=i0; i < k; i++) {
+    h[i][k_minus_1] = N_VDotProd(v[i], v[k]);
+    N_VLinearSum(ONE, v[k], -h[i][k_minus_1], v[i], v[k]);
+  }
+
+  /* Compute the norm of the new vector at v[k] */
+
+  *new_vk_norm = RSqrt(N_VDotProd(v[k], v[k]));
+
+  /* If the norm of the new vector at v[k] is less than
+     FACTOR (== 1000) times unit roundoff times the norm of the
+     input vector v[k], then the vector will be reorthogonalized
+     in order to ensure that nonorthogonality is not being masked
+     by a very small vector length. */
+
+  temp = FACTOR * vk_norm;
+  if ((temp + (*new_vk_norm)) != temp) return(0);
+  
+  new_norm_2 = ZERO;
+
+  for (i=i0; i < k; i++) {
+    new_product = N_VDotProd(v[i], v[k]);
+    temp = FACTOR * h[i][k_minus_1];
+    if ((temp + new_product) == temp) continue;
+    h[i][k_minus_1] += new_product;
+    N_VLinearSum(ONE, v[k],-new_product, v[i], v[k]);
+    new_norm_2 += SQR(new_product);
+  }
+
+  if (new_norm_2 != ZERO) {
+    new_product = SQR(*new_vk_norm) - new_norm_2;
+    *new_vk_norm = (new_product > ZERO) ? RSqrt(new_product) : ZERO;
+  }
+
+  return(0);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * Function : ClassicalGS
+ * -----------------------------------------------------------------
+ * This implementation of ClassicalGS was contributed by Homer Walker
+ * and Peter Brown.
+ * -----------------------------------------------------------------
+ */
+
+int ClassicalGS(N_Vector *v, realtype **h, int k, int p, 
+                realtype *new_vk_norm, N_Vector temp, realtype *s)
+{
+  int  i, k_minus_1, i0;
+  realtype vk_norm;
+
+  k_minus_1 = k - 1;
+  
+  /* Perform Classical Gram-Schmidt */
+
+  vk_norm = RSqrt(N_VDotProd(v[k], v[k]));
+
+  i0 = MAX(k-p, 0);
+  for (i=i0; i < k; i++) {
+    h[i][k_minus_1] = N_VDotProd(v[i], v[k]);
+  }
+
+  for (i=i0; i < k; i++) {
+    N_VLinearSum(ONE, v[k], -h[i][k_minus_1], v[i], v[k]);
+  }
+
+  /* Compute the norm of the new vector at v[k] */
+
+  *new_vk_norm = RSqrt(N_VDotProd(v[k], v[k]));
+
+  /* Reorthogonalize if necessary */
+
+  if ((FACTOR * (*new_vk_norm)) < vk_norm) {
+
+    for (i=i0; i < k; i++) {
+      s[i] = N_VDotProd(v[i], v[k]);
+    }
+
+    if (i0 < k) {
+      N_VScale(s[i0], v[i0], temp);
+      h[i0][k_minus_1] += s[i0];
+    }
+    for (i=i0+1; i < k; i++) {
+      N_VLinearSum(s[i], v[i], ONE, temp, temp);
+      h[i][k_minus_1] += s[i];
+    }
+    N_VLinearSum(ONE, v[k], -ONE, temp, v[k]);
+
+    *new_vk_norm = RSqrt(N_VDotProd(v[k],v[k]));
+  }
+
+  return(0);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * Function : QRfact
+ * -----------------------------------------------------------------
+ * This implementation of QRfact is a slight modification of a
+ * previous routine (called qrfact) written by Milo Dorr.
+ * -----------------------------------------------------------------
+ */
+
+int QRfact(int n, realtype **h, realtype *q, int job)
+{
+  realtype c, s, temp1, temp2, temp3;
+  int i, j, k, q_ptr, n_minus_1, code=0;
+
+  switch (job) {
+  case 0:
+
+    /* Compute a new factorization of H */
+
+    code = 0;
+    for (k=0; k < n; k++) {
+      
+      /* Multiply column k by the previous k-1 Givens rotations */
+
+      for (j=0; j < k-1; j++) {
+	i = 2*j;
+	temp1 = h[j][k];
+	temp2 = h[j+1][k];
+	c = q[i];
+	s = q[i+1];
+	h[j][k] = c*temp1 - s*temp2;
+	h[j+1][k] = s*temp1 + c*temp2;
+      }
+      
+      /* Compute the Givens rotation components c and s */
+
+      q_ptr = 2*k;
+      temp1 = h[k][k];
+      temp2 = h[k+1][k];
+      if( temp2 == ZERO) {
+	c = ONE;
+	s = ZERO;
+      } else if (ABS(temp2) >= ABS(temp1)) {
+	temp3 = temp1/temp2;
+	s = -ONE/RSqrt(ONE+SQR(temp3));
+	c = -s*temp3;
+      } else {
+	temp3 = temp2/temp1;
+	c = ONE/RSqrt(ONE+SQR(temp3));
+	s = -c*temp3;
+      }
+      q[q_ptr] = c;
+      q[q_ptr+1] = s;
+      if( (h[k][k] = c*temp1 - s*temp2) == ZERO) code = k+1;
+    }
+    break;
+
+  default:
+
+    /* Update the factored H to which a new column has been added */
+
+    n_minus_1 = n - 1;
+    code = 0;
+    
+    /* Multiply the new column by the previous n-1 Givens rotations */
+
+    for (k=0; k < n_minus_1; k++) {
+      i = 2*k;
+      temp1 = h[k][n_minus_1];
+      temp2 = h[k+1][n_minus_1];
+      c = q[i];
+      s = q[i+1];
+      h[k][n_minus_1] = c*temp1 - s*temp2;
+      h[k+1][n_minus_1] = s*temp1 + c*temp2;
+    }
+    
+    /* Compute new Givens rotation and multiply it times the last two
+       entries in the new column of H.  Note that the second entry of 
+       this product will be 0, so it is not necessary to compute it. */
+
+    temp1 = h[n_minus_1][n_minus_1];
+    temp2 = h[n][n_minus_1];
+    if (temp2 == ZERO) {
+      c = ONE;
+      s = ZERO;
+    } else if (ABS(temp2) >= ABS(temp1)) {
+      temp3 = temp1/temp2;
+      s = -ONE/RSqrt(ONE+SQR(temp3));
+      c = -s*temp3;
+    } else {
+      temp3 = temp2/temp1;
+      c = ONE/RSqrt(ONE+SQR(temp3));
+      s = -c*temp3;
+    }
+    q_ptr = 2*n_minus_1;
+    q[q_ptr] = c;
+    q[q_ptr+1] = s;
+    if ((h[n_minus_1][n_minus_1] = c*temp1 - s*temp2) == ZERO)
+      code = n;
+  }
+  
+  return (code);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * Function : QRsol
+ * -----------------------------------------------------------------
+ * This implementation of QRsol is a slight modification of a
+ * previous routine (called qrsol) written by Milo Dorr.
+ * -----------------------------------------------------------------
+ */
+
+int QRsol(int n, realtype **h, realtype *q, realtype *b)
+{
+  realtype c, s, temp1, temp2;
+  int i, k, q_ptr, code=0;
+
+  /* Compute Q*b */
+  
+  for (k=0; k < n; k++) {
+    q_ptr = 2*k;
+    c = q[q_ptr];
+    s = q[q_ptr+1];
+    temp1 = b[k];
+    temp2 = b[k+1];
+    b[k] = c*temp1 - s*temp2;
+    b[k+1] = s*temp1 + c*temp2;
+  }
+
+  /* Solve  R*x = Q*b */
+
+  for (k=n-1; k >= 0; k--) {
+    if (h[k][k] == ZERO) {
+      code = k + 1;
+      break;
+    }
+    b[k] /= h[k][k];
+    for (i=0; i < k; i++) b[i] -= b[k]*h[i][k];
+  }
+  
+  return (code);
+}
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/sundials_math.c b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/sundials_math.c
new file mode 100644
index 0000000000000000000000000000000000000000..9ca8d36fe0a92f9f1bcfc01ee069e8239f71dba7
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/sundials_math.c
@@ -0,0 +1,94 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * -----------------------------------------------------------------
+ * Programmer(s): Scott D. Cohen, Alan C. Hindmarsh and
+ *                Aaron Collier @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2002, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the implementation file for a simple C-language math
+ * library.
+ * -----------------------------------------------------------------
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <math.h>
+
+#include <sundials/sundials_math.h>
+
+#define ZERO RCONST(0.0)
+#define ONE  RCONST(1.0)
+
+realtype RPowerI(realtype base, int exponent)
+{
+  int i, expt;
+  realtype prod;
+
+  prod = ONE;
+  expt = abs(exponent);
+  for(i = 1; i <= expt; i++) prod *= base;
+  if (exponent < 0) prod = ONE/prod;
+  return(prod);
+}
+
+realtype RPowerR(realtype base, realtype exponent)
+{
+  if (base <= ZERO) return(ZERO);
+
+#if defined(SUNDIALS_USE_GENERIC_MATH)
+  return((realtype) pow((double) base, (double) exponent));
+#elif defined(SUNDIALS_DOUBLE_PRECISION)
+  return(pow(base, exponent));
+#elif defined(SUNDIALS_SINGLE_PRECISION)
+  return(powf(base, exponent));
+#elif defined(SUNDIALS_EXTENDED_PRECISION)
+  return(powl(base, exponent));
+#endif
+}
+
+realtype RSqrt(realtype x)
+{
+  if (x <= ZERO) return(ZERO);
+
+#if defined(SUNDIALS_USE_GENERIC_MATH)
+  return((realtype) sqrt((double) x));
+#elif defined(SUNDIALS_DOUBLE_PRECISION)
+  return(sqrt(x));
+#elif defined(SUNDIALS_SINGLE_PRECISION)
+  return(sqrtf(x));
+#elif defined(SUNDIALS_EXTENDED_PRECISION)
+  return(sqrtl(x));
+#endif
+}
+
+realtype RAbs(realtype x)
+{
+#if defined(SUNDIALS_USE_GENERIC_MATH)
+  return((realtype) fabs((double) x));
+#elif defined(SUNDIALS_DOUBLE_PRECISION)
+  return(fabs(x));
+#elif defined(SUNDIALS_SINGLE_PRECISION)
+  return(fabsf(x));
+#elif defined(SUNDIALS_EXTENDED_PRECISION)
+  return(fabsl(x));
+#endif
+}
+
+realtype RExp(realtype x)
+{
+#if defined(SUNDIALS_USE_GENERIC_MATH)
+  return((realtype) exp((double) x));
+#elif defined(SUNDIALS_DOUBLE_PRECISION)
+  return(exp(x));
+#elif defined(SUNDIALS_SINGLE_PRECISION)
+  return(expf(x));
+#elif defined(SUNDIALS_EXTENDED_PRECISION)
+  return(expl(x));
+#endif
+}
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/sundials_nvector.c b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/sundials_nvector.c
new file mode 100644
index 0000000000000000000000000000000000000000..fcf938f5a458b82af55cc15b1d35306cfa97d05a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/sundials_nvector.c
@@ -0,0 +1,230 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * ----------------------------------------------------------------- 
+ * Programmer(s): Radu Serban and Aaron Collier @ LLNL                               
+ * -----------------------------------------------------------------
+ * Copyright (c) 2002, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the implementation file for a generic NVECTOR package.
+ * It contains the implementation of the N_Vector operations listed
+ * in nvector.h.
+ * -----------------------------------------------------------------
+ */
+
+#include <stdlib.h>
+
+#include <sundials/sundials_nvector.h>
+
+/*
+ * -----------------------------------------------------------------
+ * Functions in the 'ops' structure
+ * -----------------------------------------------------------------
+ */
+
+N_Vector N_VClone(N_Vector w)
+{
+  return(w->ops->nvclone(w));
+}
+
+N_Vector N_VCloneEmpty(N_Vector w)
+{
+  return(w->ops->nvcloneempty(w));
+}
+
+void N_VDestroy(N_Vector v)
+{
+  v->ops->nvdestroy(v);
+  return;
+}
+
+void N_VSpace(N_Vector v, long int *lrw, long int *liw)
+{
+  v->ops->nvspace(v, lrw, liw);
+  return;
+}
+
+realtype *N_VGetArrayPointer(N_Vector v)
+{
+  return((realtype *) v->ops->nvgetarraypointer(v));
+}
+
+void N_VSetArrayPointer(realtype *v_data, N_Vector v)
+{
+  v->ops->nvsetarraypointer(v_data, v);
+  return;
+}
+
+void N_VLinearSum(realtype a, N_Vector x, realtype b, N_Vector y, N_Vector z)
+{
+  z->ops->nvlinearsum(a, x, b, y, z);
+  return;
+}
+
+void N_VConst(realtype c, N_Vector z)
+{
+  z->ops->nvconst(c, z);
+  return;
+}
+
+void N_VProd(N_Vector x, N_Vector y, N_Vector z)
+{
+  z->ops->nvprod(x, y, z);
+  return;
+}
+
+void N_VDiv(N_Vector x, N_Vector y, N_Vector z)
+{
+  z->ops->nvdiv(x, y, z);
+  return;
+}
+
+void N_VScale(realtype c, N_Vector x, N_Vector z) 
+{
+  z->ops->nvscale(c, x, z);
+  return;
+}
+
+void N_VAbs(N_Vector x, N_Vector z)
+{
+  z->ops->nvabs(x, z);
+  return;
+}
+
+void N_VInv(N_Vector x, N_Vector z)
+{
+  z->ops->nvinv(x, z);
+  return;
+}
+
+void N_VAddConst(N_Vector x, realtype b, N_Vector z)
+{
+  z->ops->nvaddconst(x, b, z);
+  return;
+}
+
+realtype N_VDotProd(N_Vector x, N_Vector y)
+{
+  return((realtype) y->ops->nvdotprod(x, y));
+}
+
+realtype N_VMaxNorm(N_Vector x)
+{
+  return((realtype) x->ops->nvmaxnorm(x));
+}
+
+realtype N_VWrmsNorm(N_Vector x, N_Vector w)
+{
+  return((realtype) x->ops->nvwrmsnorm(x, w));
+}
+
+realtype N_VWrmsNormMask(N_Vector x, N_Vector w, N_Vector id)
+{
+  return((realtype) x->ops->nvwrmsnormmask(x, w, id));
+}
+
+realtype N_VMin(N_Vector x)
+{
+  return((realtype) x->ops->nvmin(x));
+}
+
+realtype N_VWL2Norm(N_Vector x, N_Vector w)
+{
+  return((realtype) x->ops->nvwl2norm(x, w));
+}
+
+realtype N_VL1Norm(N_Vector x)
+{
+  return((realtype) x->ops->nvl1norm(x));
+}
+
+void N_VCompare(realtype c, N_Vector x, N_Vector z)
+{
+  z->ops->nvcompare(c, x, z);
+  return;
+}
+
+booleantype N_VInvTest(N_Vector x, N_Vector z)
+{
+  return((booleantype) z->ops->nvinvtest(x, z));
+}
+
+booleantype N_VConstrMask(N_Vector c, N_Vector x, N_Vector m)
+{
+  return((booleantype) x->ops->nvconstrmask(c, x, m));
+}
+
+realtype N_VMinQuotient(N_Vector num, N_Vector denom)
+{
+  return((realtype) num->ops->nvminquotient(num, denom));
+}
+
+/*
+ * -----------------------------------------------------------------
+ * Additional functions exported by the generic NVECTOR:
+ *   N_VCloneEmptyVectorArray
+ *   N_VCloneVectorArray
+ *   N_VDestroyVectorArray
+ * -----------------------------------------------------------------
+ */
+
+N_Vector *N_VCloneEmptyVectorArray(int count, N_Vector w)
+{
+  N_Vector *vs;
+  int j;
+
+  if (count <= 0) return(NULL);
+
+  vs = NULL;
+  vs = (N_Vector *) malloc(count * sizeof(N_Vector));
+  if(vs == NULL) return(NULL);
+
+  for (j = 0; j < count; j++) {
+    vs[j] = NULL;
+    vs[j] = N_VCloneEmpty(w);
+    if (vs[j] == NULL) {
+      N_VDestroyVectorArray(vs, j-1);
+      return(NULL);
+    }
+  }
+
+  return(vs);
+}
+
+N_Vector *N_VCloneVectorArray(int count, N_Vector w)
+{
+  N_Vector *vs;
+  int j;
+
+  if (count <= 0) return(NULL);
+
+  vs = NULL;
+  vs = (N_Vector *) malloc(count * sizeof(N_Vector));
+  if(vs == NULL) return(NULL);
+
+  for (j = 0; j < count; j++) {
+    vs[j] = NULL;
+    vs[j] = N_VClone(w);
+    if (vs[j] == NULL) {
+      N_VDestroyVectorArray(vs, j-1);
+      return(NULL);
+    }
+  }
+
+  return(vs);
+}
+
+void N_VDestroyVectorArray(N_Vector *vs, int count)
+{
+  int j;
+
+  for (j = 0; j < count; j++) N_VDestroy(vs[j]);
+
+  free(vs); vs = NULL;
+
+  return;
+}
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/sundials_smalldense.c b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/sundials_smalldense.c
new file mode 100644
index 0000000000000000000000000000000000000000..4abb9424b500b322835fb2ecb7a8ddb1944a7972
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/sundials_smalldense.c
@@ -0,0 +1,233 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * -----------------------------------------------------------------
+ * Programmer: Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2006, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the implementation file for a generic DENSE linear
+ * solver package, intended for small dense matrices.
+ * -----------------------------------------------------------------
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <sundials/sundials_smalldense.h>
+#include <sundials/sundials_math.h>
+
+#define ZERO RCONST(0.0)
+#define ONE  RCONST(1.0)
+
+/* Implementation */
+
+
+realtype **denalloc(long int m, long int n)
+{
+  long int j;
+  realtype **a;
+
+  if ( (n <= 0) || (m <= 0) ) return(NULL);
+
+  a = NULL;
+  a = (realtype **) malloc(n * sizeof(realtype *));
+  if (a == NULL) return(NULL);
+
+  a[0] = NULL;
+  a[0] = (realtype *) malloc(m * n * sizeof(realtype));
+  if (a[0] == NULL) {
+    free(a); a = NULL;
+    return(NULL);
+  }
+
+  for (j=1; j < n; j++) a[j] = a[0] + j * m;
+
+  return(a);
+}
+
+long int *denallocpiv(long int n)
+{
+  long int *piv;
+
+  if (n <= 0) return(NULL);
+
+  piv = NULL;
+  piv = (long int *) malloc(n * sizeof(long int));
+
+  return(piv);
+}
+
+long int denGETRF(realtype **a, long int m, long int n, long int *p)
+{
+  long int i, j, k, l;
+  realtype *col_j, *col_k;
+  realtype temp, mult, a_kj;
+
+  /* k-th elimination step number */
+  for (k=0; k < n; k++) {
+
+    col_k  = a[k];
+
+    /* find l = pivot row number */
+    l=k;
+    for (i=k+1; i < m; i++)
+      if (ABS(col_k[i]) > ABS(col_k[l])) l=i;
+    p[k] = l;
+
+    /* check for zero pivot element */
+    if (col_k[l] == ZERO) return(k+1);
+    
+    /* swap a(k,1:n) and a(l,1:n) if necessary */    
+    if ( l!= k ) {
+      for (i=0; i<n; i++) {
+        temp = a[i][l];
+        a[i][l] = a[i][k];
+        a[i][k] = temp;
+      }
+    }
+
+    /* Scale the elements below the diagonal in
+     * column k by 1.0/a(k,k). After the above swap
+     * a(k,k) holds the pivot element. This scaling
+     * stores the pivot row multipliers a(i,k)/a(k,k)
+     * in a(i,k), i=k+1, ..., m-1.                      
+     */
+    mult = ONE/col_k[k];
+    for(i=k+1; i < m; i++) col_k[i] *= mult;
+
+    /* row_i = row_i - [a(i,k)/a(k,k)] row_k, i=k+1, ..., m-1 */
+    /* row k is the pivot row after swapping with row l.      */
+    /* The computation is done one column at a time,          */
+    /* column j=k+1, ..., n-1.                                */
+
+    for (j=k+1; j < n; j++) {
+
+      col_j = a[j];
+      a_kj = col_j[k];
+
+      /* a(i,j) = a(i,j) - [a(i,k)/a(k,k)]*a(k,j)  */
+      /* a_kj = a(k,j), col_k[i] = - a(i,k)/a(k,k) */
+
+      if (a_kj != ZERO) {
+	for (i=k+1; i < m; i++)
+	  col_j[i] -= a_kj * col_k[i];
+      }
+    }
+  }
+
+  /* return 0 to indicate success */
+
+  return(0);
+}
+
+void denGETRS(realtype **a, long int n, long int *p, realtype *b)
+{
+  long int i, k, pk;
+  realtype *col_k, tmp;
+
+  /* Permute b, based on pivot information in p */
+  for (k=0; k<n; k++) {
+    pk = p[k];
+    if(pk != k) {
+      tmp = b[k];
+      b[k] = b[pk];
+      b[pk] = tmp;
+    }
+  }
+
+  /* Solve Ly = b, store solution y in b */
+  for (k=0; k<n-1; k++) {
+    col_k = a[k];
+    for (i=k+1; i<n; i++) b[i] -= col_k[i]*b[k];
+  }
+
+  /* Solve Ux = y, store solution x in b */
+  for (k = n-1; k > 0; k--) {
+    col_k = a[k];
+    b[k] /= col_k[k];
+    for (i=0; i<k; i++) b[i] -= col_k[i]*b[k];
+  }
+  b[0] /= a[0][0];
+
+}
+
+void denzero(realtype **a, long int m, long int n)
+{
+  long int i, j;
+  realtype *col_j;
+
+  for (j=0; j < n; j++) {
+    col_j = a[j];
+    for (i=0; i < m; i++)
+      col_j[i] =  ZERO;
+  }
+}
+
+void dencopy(realtype **a, realtype **b, long int m, long int n)
+{
+  long int i, j;
+  realtype *a_col_j, *b_col_j;
+
+  for (j=0; j < n; j++) {
+    a_col_j = a[j];
+    b_col_j = b[j];
+    for (i=0; i < m; i++)
+      b_col_j[i] = a_col_j[i];
+  }
+
+}
+
+void denscale(realtype c, realtype **a, long int m, long int n)
+{
+  long int i, j;
+  realtype *col_j;
+
+  for (j=0; j < n; j++) {
+    col_j = a[j];
+    for (i=0; i < m; i++)
+      col_j[i] *= c;
+  }
+}
+
+void denaddI(realtype **a, long int n)
+{
+  long int i;
+  
+  for (i=0; i < n; i++) a[i][i] += ONE;
+}
+
+void denfreepiv(long int *p)
+{
+  free(p); p = NULL;
+}
+
+void denfree(realtype **a)
+{
+  free(a[0]); a[0] = NULL;
+  free(a); a = NULL;
+}
+
+void denprint(realtype **a, long int m, long int n)
+{
+  long int i, j;
+
+  printf("\n");
+  for (i=0; i < m; i++) {
+    for (j=0; j < n; j++) {
+#if defined(SUNDIALS_EXTENDED_PRECISION)
+      printf("%12Lg  ", a[j][i]);
+#elif defined(SUNDIALS_DOUBLE_PRECISION)
+      printf("%12lg  ", a[j][i]);
+#else
+      printf("%12g  ", a[j][i]);
+#endif
+    }
+    printf("\n");
+  }
+  printf("\n");
+}
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/sundials_spbcgs.c b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/sundials_spbcgs.c
new file mode 100644
index 0000000000000000000000000000000000000000..9dad08dc9d353e4b0cf79eba5b7b5f994e149399
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/sundials_spbcgs.c
@@ -0,0 +1,386 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * -----------------------------------------------------------------
+ * Programmer(s): Peter Brown and Aaron Collier @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2004, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the implementation file for the scaled, preconditioned
+ * Bi-CGSTAB (SPBCG) iterative linear solver.
+ * -----------------------------------------------------------------
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <sundials/sundials_spbcgs.h>
+#include <sundials/sundials_math.h>
+
+/*
+ * -----------------------------------------------------------------
+ * private constants
+ * -----------------------------------------------------------------
+ */
+
+#define ZERO RCONST(0.0)
+#define ONE  RCONST(1.0)
+
+/*
+ * -----------------------------------------------------------------
+ * Function : SpbcgMalloc
+ * -----------------------------------------------------------------
+ */
+
+SpbcgMem SpbcgMalloc(int l_max, N_Vector vec_tmpl)
+{
+  SpbcgMem mem;
+  N_Vector r_star, r, p, q, u, Ap, vtemp;
+
+  /* Check the input parameters */
+
+  if (l_max <= 0) return(NULL);
+
+  /* Get arrays to hold temporary vectors */
+
+  r_star = NULL;
+  r_star = N_VClone(vec_tmpl);
+  if (r_star == NULL) {
+    return(NULL);
+  }
+
+  r = NULL;
+  r = N_VClone(vec_tmpl);
+  if (r == NULL) {
+    N_VDestroy(r_star);
+    return(NULL);
+  }
+
+  p = NULL;
+  p = N_VClone(vec_tmpl);
+  if (p == NULL) {
+    N_VDestroy(r_star);
+    N_VDestroy(r);
+    return(NULL);
+  }
+
+  q = NULL;
+  q = N_VClone(vec_tmpl);
+  if (q == NULL) {
+    N_VDestroy(r_star);
+    N_VDestroy(r);
+    N_VDestroy(p);
+    return(NULL);
+  }
+
+  u = NULL;
+  u = N_VClone(vec_tmpl);
+  if (u == NULL) {
+    N_VDestroy(r_star);
+    N_VDestroy(r);
+    N_VDestroy(p);
+    N_VDestroy(q);
+    return(NULL);
+  }
+
+  Ap = NULL;
+  Ap = N_VClone(vec_tmpl);
+  if (Ap == NULL) {
+    N_VDestroy(r_star);
+    N_VDestroy(r);
+    N_VDestroy(p);
+    N_VDestroy(q);
+    N_VDestroy(u);
+    return(NULL);
+  }
+
+  vtemp = NULL;
+  vtemp = N_VClone(vec_tmpl);
+  if (vtemp == NULL) {
+    N_VDestroy(r_star);
+    N_VDestroy(r);
+    N_VDestroy(p);
+    N_VDestroy(q);
+    N_VDestroy(u);
+    N_VDestroy(Ap);
+    return(NULL);
+  }
+
+  /* Get memory for an SpbcgMemRec containing SPBCG matrices and vectors */
+
+  mem = NULL;
+  mem = (SpbcgMem) malloc(sizeof(SpbcgMemRec));
+  if (mem == NULL) {
+    N_VDestroy(r_star);
+    N_VDestroy(r);
+    N_VDestroy(p);
+    N_VDestroy(q);
+    N_VDestroy(u);
+    N_VDestroy(Ap);
+    N_VDestroy(vtemp);
+    return(NULL);
+  }
+
+  /* Set the fields of mem */
+
+  mem->l_max  = l_max;
+  mem->r_star = r_star;
+  mem->r      = r;
+  mem->p      = p;
+  mem->q      = q;
+  mem->u      = u;
+  mem->Ap     = Ap;
+  mem->vtemp  = vtemp;
+
+  /* Return the pointer to SPBCG memory */
+
+  return(mem);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * Function : SpbcgSolve
+ * -----------------------------------------------------------------
+ */
+
+int SpbcgSolve(SpbcgMem mem, void *A_data, N_Vector x, N_Vector b,
+               int pretype, realtype delta, void *P_data, N_Vector sx,
+               N_Vector sb, ATimesFn atimes, PSolveFn psolve,
+               realtype *res_norm, int *nli, int *nps)
+{
+  realtype alpha, beta, omega, omega_denom, beta_num, beta_denom, r_norm, rho;
+  N_Vector r_star, r, p, q, u, Ap, vtemp;
+  booleantype preOnLeft, preOnRight, scale_x, scale_b, converged;
+  int l, l_max, ier;
+
+  if (mem == NULL) return(SPBCG_MEM_NULL);
+
+  /* Make local copies of mem variables */
+
+  l_max  = mem->l_max;
+  r_star = mem->r_star;
+  r      = mem->r;
+  p      = mem->p;
+  q      = mem->q;
+  u      = mem->u;
+  Ap     = mem->Ap;
+  vtemp  = mem->vtemp;
+
+  *nli = *nps = 0;    /* Initialize counters */
+  converged = FALSE;  /* Initialize converged flag */
+
+  if ((pretype != PREC_LEFT) && (pretype != PREC_RIGHT) && (pretype != PREC_BOTH)) pretype = PREC_NONE;
+
+  preOnLeft  = ((pretype == PREC_BOTH) || (pretype == PREC_LEFT));
+  preOnRight = ((pretype == PREC_BOTH) || (pretype == PREC_RIGHT));
+
+  scale_x = (sx != NULL);
+  scale_b = (sb != NULL);
+
+  /* Set r_star to initial (unscaled) residual r_0 = b - A*x_0 */
+
+  if (N_VDotProd(x, x) == ZERO) N_VScale(ONE, b, r_star);
+  else {
+    ier = atimes(A_data, x, r_star);
+    if (ier != 0)
+      return((ier < 0) ? SPBCG_ATIMES_FAIL_UNREC : SPBCG_ATIMES_FAIL_REC);
+    N_VLinearSum(ONE, b, -ONE, r_star, r_star);
+  }
+
+  /* Apply left preconditioner and b-scaling to r_star = r_0 */
+
+  if (preOnLeft) {
+    ier = psolve(P_data, r_star, r, PREC_LEFT);
+    (*nps)++;
+    if (ier != 0) return((ier < 0) ? SPBCG_PSOLVE_FAIL_UNREC : SPBCG_PSOLVE_FAIL_REC);
+  }
+  else N_VScale(ONE, r_star, r);
+
+  if (scale_b) N_VProd(sb, r, r_star);
+  else N_VScale(ONE, r, r_star);
+
+  /* Initialize beta_denom to the dot product of r0 with r0 */
+
+  beta_denom = N_VDotProd(r_star, r_star);
+
+  /* Set r_norm to L2 norm of r_star = sb P1_inv r_0, and
+     return if small */
+
+  *res_norm = r_norm = rho = RSqrt(beta_denom);
+  if (r_norm <= delta) return(SPBCG_SUCCESS);
+
+  /* Copy r_star to r and p */
+
+  N_VScale(ONE, r_star, r);
+  N_VScale(ONE, r_star, p);
+
+  /* Begin main iteration loop */
+
+  for(l = 0; l < l_max; l++) {
+
+    (*nli)++;
+
+    /* Generate Ap = A-tilde p, where A-tilde = sb P1_inv A P2_inv sx_inv */
+
+    /*   Apply x-scaling: vtemp = sx_inv p */
+
+    if (scale_x) N_VDiv(p, sx, vtemp);
+    else N_VScale(ONE, p, vtemp);
+
+    /*   Apply right preconditioner: vtemp = P2_inv sx_inv p */
+
+    if (preOnRight) {
+      N_VScale(ONE, vtemp, Ap);
+      ier = psolve(P_data, Ap, vtemp, PREC_RIGHT);
+      (*nps)++;
+      if (ier != 0) return((ier < 0) ? SPBCG_PSOLVE_FAIL_UNREC : SPBCG_PSOLVE_FAIL_REC);
+    }
+
+    /*   Apply A: Ap = A P2_inv sx_inv p */
+
+    ier = atimes(A_data, vtemp, Ap );
+    if (ier != 0)
+      return((ier < 0) ? SPBCG_ATIMES_FAIL_UNREC : SPBCG_ATIMES_FAIL_REC);
+
+    /*   Apply left preconditioner: vtemp = P1_inv A P2_inv sx_inv p */
+
+    if (preOnLeft) {
+      ier = psolve(P_data, Ap, vtemp, PREC_LEFT);
+      (*nps)++;
+      if (ier != 0) return((ier < 0) ? SPBCG_PSOLVE_FAIL_UNREC : SPBCG_PSOLVE_FAIL_REC);
+    }
+    else N_VScale(ONE, Ap, vtemp);
+
+    /*   Apply b-scaling: Ap = sb P1_inv A P2_inv sx_inv p */
+
+    if (scale_b) N_VProd(sb, vtemp, Ap);
+    else N_VScale(ONE, vtemp, Ap);
+
+
+    /* Calculate alpha = <r,r_star>/<Ap,r_star> */
+
+    alpha = ((N_VDotProd(r, r_star) / N_VDotProd(Ap, r_star)));
+
+    /* Update q = r - alpha*Ap = r - alpha*(sb P1_inv A P2_inv sx_inv p) */
+
+    N_VLinearSum(ONE, r, -alpha, Ap, q);
+
+    /* Generate u = A-tilde q */
+
+    /*   Apply x-scaling: vtemp = sx_inv q */
+
+    if (scale_x) N_VDiv(q, sx, vtemp);
+    else N_VScale(ONE, q, vtemp);
+
+    /*   Apply right preconditioner: vtemp = P2_inv sx_inv q */
+
+    if (preOnRight) {
+      N_VScale(ONE, vtemp, u);
+      ier = psolve(P_data, u, vtemp, PREC_RIGHT);
+      (*nps)++;
+      if (ier != 0) return((ier < 0) ? SPBCG_PSOLVE_FAIL_UNREC : SPBCG_PSOLVE_FAIL_REC);
+    }
+
+    /*   Apply A: u = A P2_inv sx_inv u */
+
+    ier = atimes(A_data, vtemp, u );
+    if (ier != 0)
+      return((ier < 0) ? SPBCG_ATIMES_FAIL_UNREC : SPBCG_ATIMES_FAIL_REC);
+
+    /*   Apply left preconditioner: vtemp = P1_inv A P2_inv sx_inv p */
+
+    if (preOnLeft) {
+      ier = psolve(P_data, u, vtemp, PREC_LEFT);
+      (*nps)++;
+      if (ier != 0) return((ier < 0) ? SPBCG_PSOLVE_FAIL_UNREC : SPBCG_PSOLVE_FAIL_REC);
+    }
+    else N_VScale(ONE, u, vtemp);
+
+    /*   Apply b-scaling: u = sb P1_inv A P2_inv sx_inv u */
+
+    if (scale_b) N_VProd(sb, vtemp, u);
+    else N_VScale(ONE, vtemp, u);
+
+
+    /* Calculate omega = <u,q>/<u,u> */
+
+    omega_denom = N_VDotProd(u, u);
+    if (omega_denom == ZERO) omega_denom = ONE;
+    omega = (N_VDotProd(u, q) / omega_denom);
+
+    /* Update x = x + alpha*p + omega*q */
+
+    N_VLinearSum(alpha, p, omega, q, vtemp);
+    N_VLinearSum(ONE, x, ONE, vtemp, x);
+
+    /* Update the residual r = q - omega*u */
+
+    N_VLinearSum(ONE, q, -omega, u, r);
+
+    /* Set rho = norm(r) and check convergence */
+
+    *res_norm = rho = RSqrt(N_VDotProd(r, r));
+    if (rho <= delta) {
+      converged = TRUE;
+      break;
+    }
+
+    /* Not yet converged, continue iteration */
+    /* Update beta = <rnew,r_star> / <rold,r_start> * alpha / omega */
+
+    beta_num = N_VDotProd(r, r_star);
+    beta = ((beta_num / beta_denom) * (alpha / omega));
+    beta_denom = beta_num;
+
+    /* Update p = r + beta*(p - omega*Ap) */
+
+    N_VLinearSum(ONE, p, -omega, Ap, vtemp);
+    N_VLinearSum(ONE, r, beta, vtemp, p);
+
+  }
+
+  /* Main loop finished */
+
+  if ((converged == TRUE) || (rho < r_norm)) {
+
+    /* Apply the x-scaling and right preconditioner: x = P2_inv sx_inv x */
+
+    if (scale_x) N_VDiv(x, sx, x);
+    if (preOnRight) {
+      ier = psolve(P_data, x, vtemp, PREC_RIGHT);
+      (*nps)++;
+      if (ier != 0) return((ier < 0) ? SPBCG_PSOLVE_FAIL_UNREC : SPBCG_PSOLVE_FAIL_REC);
+      N_VScale(ONE, vtemp, x);
+    }
+
+    if (converged == TRUE) return(SPBCG_SUCCESS);
+    else return(SPBCG_RES_REDUCED);
+  }
+  else return(SPBCG_CONV_FAIL);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * Function : SpbcgFree
+ * -----------------------------------------------------------------
+ */
+
+void SpbcgFree(SpbcgMem mem)
+{
+
+  if (mem == NULL) return;
+
+  N_VDestroy(mem->r_star);
+  N_VDestroy(mem->r);
+  N_VDestroy(mem->p);
+  N_VDestroy(mem->q);
+  N_VDestroy(mem->u);
+  N_VDestroy(mem->Ap);
+  N_VDestroy(mem->vtemp);
+
+  free(mem); mem = NULL;
+}
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/sundials_spgmr.c b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/sundials_spgmr.c
new file mode 100644
index 0000000000000000000000000000000000000000..78b3c8c235c0982a0926370ae0eef730d91a52c8
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/sundials_spgmr.c
@@ -0,0 +1,461 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * -----------------------------------------------------------------
+ * Programmer(s): Scott D. Cohen, Alan C. Hindmarsh and
+ *                Radu Serban @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2002, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the implementation file for the scaled preconditioned
+ * GMRES (SPGMR) iterative linear solver.
+ * -----------------------------------------------------------------
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <sundials/sundials_spgmr.h>
+#include <sundials/sundials_math.h>
+
+/*
+ * -----------------------------------------------------------------
+ * private constants
+ * -----------------------------------------------------------------
+ */
+
+#define ZERO RCONST(0.0)
+#define ONE  RCONST(1.0)
+
+/*
+ * -----------------------------------------------------------------
+ * Function : SpgmrMalloc
+ * -----------------------------------------------------------------
+ */
+
+SpgmrMem SpgmrMalloc(int l_max, N_Vector vec_tmpl)
+{
+  SpgmrMem mem;
+  N_Vector *V, xcor, vtemp;
+  realtype **Hes, *givens, *yg;
+  int k, i;
+ 
+  /* Check the input parameters. */
+
+  if (l_max <= 0) return(NULL);
+
+  /* Get memory for the Krylov basis vectors V[0], ..., V[l_max]. */
+
+  V = NULL;
+  V = N_VCloneVectorArray(l_max+1, vec_tmpl);
+  if (V == NULL) return(NULL);
+
+  /* Get memory for the Hessenberg matrix Hes. */
+
+  Hes = NULL;
+  Hes = (realtype **) malloc((l_max+1)*sizeof(realtype *)); 
+  if (Hes == NULL) {
+    N_VDestroyVectorArray(V, l_max+1);
+    return(NULL);
+  }
+
+  for (k = 0; k <= l_max; k++) {
+    Hes[k] = NULL;
+    Hes[k] = (realtype *) malloc(l_max*sizeof(realtype));
+    if (Hes[k] == NULL) {
+      for (i = 0; i < k; i++) {free(Hes[i]); Hes[i] = NULL;}
+      free(Hes); Hes = NULL;
+      N_VDestroyVectorArray(V, l_max+1);
+      return(NULL);
+    }
+  }
+  
+  /* Get memory for Givens rotation components. */
+  
+  givens = NULL;
+  givens = (realtype *) malloc(2*l_max*sizeof(realtype));
+  if (givens == NULL) {
+    for (i = 0; i <= l_max; i++) {free(Hes[i]); Hes[i] = NULL;}
+    free(Hes); Hes = NULL;
+    N_VDestroyVectorArray(V, l_max+1);
+    return(NULL);
+  }
+
+  /* Get memory to hold the correction to z_tilde. */
+
+  xcor = NULL;
+  xcor = N_VClone(vec_tmpl);
+  if (xcor == NULL) {
+    free(givens); givens = NULL;
+    for (i = 0; i <= l_max; i++) {free(Hes[i]); Hes[i] = NULL;}
+    free(Hes); Hes = NULL;
+    N_VDestroyVectorArray(V, l_max+1);
+    return(NULL);
+  }
+
+  /* Get memory to hold SPGMR y and g vectors. */
+
+  yg = NULL;
+  yg = (realtype *) malloc((l_max+1)*sizeof(realtype));
+  if (yg == NULL) {
+    N_VDestroy(xcor);
+    free(givens); givens = NULL;
+    for (i = 0; i <= l_max; i++) {free(Hes[i]); Hes[i] = NULL;}
+    free(Hes); Hes = NULL;
+    N_VDestroyVectorArray(V, l_max+1);
+    return(NULL);
+  }
+
+  /* Get an array to hold a temporary vector. */
+
+  vtemp = NULL;
+  vtemp = N_VClone(vec_tmpl);
+  if (vtemp == NULL) {
+    free(yg); yg = NULL;
+    N_VDestroy(xcor);
+    free(givens); givens = NULL;
+    for (i = 0; i <= l_max; i++) {free(Hes[i]); Hes[i] = NULL;}
+    free(Hes); Hes = NULL;
+    N_VDestroyVectorArray(V, l_max+1);
+    return(NULL);
+  }
+
+  /* Get memory for an SpgmrMemRec containing SPGMR matrices and vectors. */
+
+  mem = NULL;
+  mem = (SpgmrMem) malloc(sizeof(SpgmrMemRec));
+  if (mem == NULL) {
+    N_VDestroy(vtemp);
+    free(yg); yg = NULL;
+    N_VDestroy(xcor);
+    free(givens); givens = NULL;
+    for (i = 0; i <= l_max; i++) {free(Hes[i]); Hes[i] = NULL;}
+    free(Hes); Hes = NULL;
+    N_VDestroyVectorArray(V, l_max+1);
+    return(NULL); 
+  }
+
+  /* Set the fields of mem. */
+
+  mem->l_max = l_max;
+  mem->V = V;
+  mem->Hes = Hes;
+  mem->givens = givens;
+  mem->xcor = xcor;
+  mem->yg = yg;
+  mem->vtemp = vtemp;
+
+  /* Return the pointer to SPGMR memory. */
+
+  return(mem);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * Function : SpgmrSolve
+ * -----------------------------------------------------------------
+ */
+
+int SpgmrSolve(SpgmrMem mem, void *A_data, N_Vector x, N_Vector b,
+               int pretype, int gstype, realtype delta, int max_restarts,
+               void *P_data, N_Vector s1, N_Vector s2, ATimesFn atimes,
+               PSolveFn psolve, realtype *res_norm, int *nli, int *nps)
+{
+  N_Vector *V, xcor, vtemp;
+  realtype **Hes, *givens, *yg;
+  realtype beta, rotation_product, r_norm, s_product, rho;
+  booleantype preOnLeft, preOnRight, scale2, scale1, converged;
+  int i, j, k, l, l_plus_1, l_max, krydim, ier, ntries;
+
+  if (mem == NULL) return(SPGMR_MEM_NULL);
+
+  /* Initialize some variables */
+
+  l_plus_1 = 0;
+  krydim = 0;
+
+  /* Make local copies of mem variables. */
+
+  l_max  = mem->l_max;
+  V      = mem->V;
+  Hes    = mem->Hes;
+  givens = mem->givens;
+  xcor   = mem->xcor;
+  yg     = mem->yg;
+  vtemp  = mem->vtemp;
+
+  *nli = *nps = 0;    /* Initialize counters */
+  converged = FALSE;  /* Initialize converged flag */
+
+  if (max_restarts < 0) max_restarts = 0;
+
+  if ((pretype != PREC_LEFT) && (pretype != PREC_RIGHT) && (pretype != PREC_BOTH))
+    pretype = PREC_NONE;
+  
+  preOnLeft  = ((pretype == PREC_LEFT) || (pretype == PREC_BOTH));
+  preOnRight = ((pretype == PREC_RIGHT) || (pretype == PREC_BOTH));
+  scale1 = (s1 != NULL);
+  scale2 = (s2 != NULL);
+
+  /* Set vtemp and V[0] to initial (unscaled) residual r_0 = b - A*x_0. */
+
+  if (N_VDotProd(x, x) == ZERO) {
+    N_VScale(ONE, b, vtemp);
+  } else {
+    ier = atimes(A_data, x, vtemp);
+    if (ier != 0)
+      return((ier < 0) ? SPGMR_ATIMES_FAIL_UNREC : SPGMR_ATIMES_FAIL_REC);
+    N_VLinearSum(ONE, b, -ONE, vtemp, vtemp);
+  }
+  N_VScale(ONE, vtemp, V[0]);
+
+  /* Apply left preconditioner and left scaling to V[0] = r_0. */
+  
+  if (preOnLeft) {
+    ier = psolve(P_data, V[0], vtemp, PREC_LEFT);
+    (*nps)++;
+    if (ier != 0)
+      return((ier < 0) ? SPGMR_PSOLVE_FAIL_UNREC : SPGMR_PSOLVE_FAIL_REC);
+  } else {
+    N_VScale(ONE, V[0], vtemp);
+  }
+  
+  if (scale1) {
+    N_VProd(s1, vtemp, V[0]);   
+  } else {
+    N_VScale(ONE, vtemp, V[0]);
+  }
+
+  /* Set r_norm = beta to L2 norm of V[0] = s1 P1_inv r_0, and
+     return if small.  */
+
+  *res_norm = r_norm = beta = RSqrt(N_VDotProd(V[0], V[0])); 
+  if (r_norm <= delta)
+    return(SPGMR_SUCCESS);
+
+  /* Initialize rho to avoid compiler warning message */
+
+  rho = beta;
+
+  /* Set xcor = 0. */
+
+  N_VConst(ZERO, xcor);
+
+
+  /* Begin outer iterations: up to (max_restarts + 1) attempts. */
+  
+  for (ntries = 0; ntries <= max_restarts; ntries++) {
+    
+    /* Initialize the Hessenberg matrix Hes and Givens rotation
+       product.  Normalize the initial vector V[0].             */
+    
+    for (i = 0; i <= l_max; i++)
+      for (j = 0; j < l_max; j++)
+        Hes[i][j] = ZERO;
+    
+    rotation_product = ONE;
+    
+    N_VScale(ONE/r_norm, V[0], V[0]);
+    
+    /* Inner loop: generate Krylov sequence and Arnoldi basis. */
+    
+    for (l = 0; l < l_max; l++) {
+      
+      (*nli)++;
+      
+      krydim = l_plus_1 = l + 1;
+      
+      /* Generate A-tilde V[l], where A-tilde = s1 P1_inv A P2_inv s2_inv. */
+      
+      /* Apply right scaling: vtemp = s2_inv V[l]. */
+
+      if (scale2) N_VDiv(V[l], s2, vtemp);
+      else N_VScale(ONE, V[l], vtemp);
+      
+      /* Apply right preconditioner: vtemp = P2_inv s2_inv V[l]. */ 
+
+      if (preOnRight) {
+        N_VScale(ONE, vtemp, V[l_plus_1]);
+        ier = psolve(P_data, V[l_plus_1], vtemp, PREC_RIGHT);
+        (*nps)++;
+        if (ier != 0)
+          return((ier < 0) ? SPGMR_PSOLVE_FAIL_UNREC : SPGMR_PSOLVE_FAIL_REC);
+      }
+      
+      /* Apply A: V[l+1] = A P2_inv s2_inv V[l]. */
+
+      ier = atimes(A_data, vtemp, V[l_plus_1] );
+      if (ier != 0)
+        return((ier < 0) ? SPGMR_ATIMES_FAIL_UNREC : SPGMR_ATIMES_FAIL_REC);
+      
+      /* Apply left preconditioning: vtemp = P1_inv A P2_inv s2_inv V[l]. */
+
+      if (preOnLeft) {
+        ier = psolve(P_data, V[l_plus_1], vtemp, PREC_LEFT);
+        (*nps)++;
+        if (ier != 0)
+          return((ier < 0) ? SPGMR_PSOLVE_FAIL_UNREC : SPGMR_PSOLVE_FAIL_REC);
+      } else {
+        N_VScale(ONE, V[l_plus_1], vtemp);
+      }
+      
+      /* Apply left scaling: V[l+1] = s1 P1_inv A P2_inv s2_inv V[l]. */
+
+      if (scale1) {
+        N_VProd(s1, vtemp, V[l_plus_1]);
+      } else {
+        N_VScale(ONE, vtemp, V[l_plus_1]);
+      }
+      
+      /*  Orthogonalize V[l+1] against previous V[i]: V[l+1] = w_tilde. */
+      
+      if (gstype == CLASSICAL_GS) {
+        if (ClassicalGS(V, Hes, l_plus_1, l_max, &(Hes[l_plus_1][l]),
+                        vtemp, yg) != 0)
+          return(SPGMR_GS_FAIL);
+      } else {
+        if (ModifiedGS(V, Hes, l_plus_1, l_max, &(Hes[l_plus_1][l])) != 0) 
+          return(SPGMR_GS_FAIL);
+      }
+      
+      /*  Update the QR factorization of Hes. */
+      
+      if(QRfact(krydim, Hes, givens, l) != 0 )
+        return(SPGMR_QRFACT_FAIL);
+      
+      /*  Update residual norm estimate; break if convergence test passes. */
+      
+      rotation_product *= givens[2*l+1];
+      *res_norm = rho = ABS(rotation_product*r_norm);
+      
+      if (rho <= delta) { converged = TRUE; break; }
+      
+      /* Normalize V[l+1] with norm value from the Gram-Schmidt routine. */
+
+      N_VScale(ONE/Hes[l_plus_1][l], V[l_plus_1], V[l_plus_1]);
+    }
+    
+    /* Inner loop is done.  Compute the new correction vector xcor. */
+    
+    /* Construct g, then solve for y. */
+
+    yg[0] = r_norm;
+    for (i = 1; i <= krydim; i++) yg[i]=ZERO;
+    if (QRsol(krydim, Hes, givens, yg) != 0)
+      return(SPGMR_QRSOL_FAIL);
+    
+    /* Add correction vector V_l y to xcor. */
+
+    for (k = 0; k < krydim; k++)
+      N_VLinearSum(yg[k], V[k], ONE, xcor, xcor);
+    
+    /* If converged, construct the final solution vector x and return. */
+
+    if (converged) {
+      
+      /* Apply right scaling and right precond.: vtemp = P2_inv s2_inv xcor. */
+      
+      if (scale2) N_VDiv(xcor, s2, xcor);
+      if (preOnRight) {
+        ier = psolve(P_data, xcor, vtemp, PREC_RIGHT);
+        (*nps)++;
+        if (ier != 0)
+          return((ier < 0) ? SPGMR_PSOLVE_FAIL_UNREC : SPGMR_PSOLVE_FAIL_REC);
+      } else {
+        N_VScale(ONE, xcor, vtemp);
+      }
+      
+      /* Add vtemp to initial x to get final solution x, and return */
+
+      N_VLinearSum(ONE, x, ONE, vtemp, x);
+      
+      return(SPGMR_SUCCESS);
+    }
+    
+    /* Not yet converged; if allowed, prepare for restart. */
+    
+    if (ntries == max_restarts) break;
+    
+    /* Construct last column of Q in yg. */
+
+    s_product = ONE;
+    for (i = krydim; i > 0; i--) {
+      yg[i] = s_product*givens[2*i-2];
+      s_product *= givens[2*i-1];
+    }
+    yg[0] = s_product;
+    
+    /* Scale r_norm and yg. */
+    r_norm *= s_product;
+    for (i = 0; i <= krydim; i++)
+      yg[i] *= r_norm;
+    r_norm = ABS(r_norm);
+    
+    /* Multiply yg by V_(krydim+1) to get last residual vector; restart. */
+    N_VScale(yg[0], V[0], V[0]);
+    for (k = 1; k <= krydim; k++)
+      N_VLinearSum(yg[k], V[k], ONE, V[0], V[0]);
+    
+  }
+  
+  /* Failed to converge, even after allowed restarts.
+     If the residual norm was reduced below its initial value, compute
+     and return x anyway.  Otherwise return failure flag. */
+
+  if (rho < beta) {
+    
+    /* Apply right scaling and right precond.: vtemp = P2_inv s2_inv xcor. */
+    
+    if (scale2) N_VDiv(xcor, s2, xcor);
+    if (preOnRight) {
+      ier = psolve(P_data, xcor, vtemp, PREC_RIGHT);
+      (*nps)++;
+      if (ier != 0)
+        return((ier < 0) ? SPGMR_PSOLVE_FAIL_UNREC : SPGMR_PSOLVE_FAIL_REC);
+      } else {
+      N_VScale(ONE, xcor, vtemp);
+    }
+
+    /* Add vtemp to initial x to get final solution x, and return. */
+
+    N_VLinearSum(ONE, x, ONE, vtemp, x);
+    
+    return(SPGMR_RES_REDUCED);
+  }
+
+  return(SPGMR_CONV_FAIL); 
+}
+
+/*
+ * -----------------------------------------------------------------
+ * Function : SpgmrFree
+ * -----------------------------------------------------------------
+ */
+
+void SpgmrFree(SpgmrMem mem)
+{
+  int i, l_max;
+  realtype **Hes, *givens, *yg;
+  
+  if (mem == NULL) return;
+
+  l_max  = mem->l_max;
+  Hes    = mem->Hes;
+  givens = mem->givens;
+  yg     = mem->yg;
+
+  for (i = 0; i <= l_max; i++) {free(Hes[i]); Hes[i] = NULL;}
+  free(Hes); Hes = NULL;
+  free(mem->givens); givens = NULL; 
+  free(mem->yg); yg = NULL;
+
+  N_VDestroyVectorArray(mem->V, l_max+1);
+  N_VDestroy(mem->xcor);
+  N_VDestroy(mem->vtemp);
+
+  free(mem); mem = NULL;
+}
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/sundials_sptfqmr.c b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/sundials_sptfqmr.c
new file mode 100644
index 0000000000000000000000000000000000000000..b4cf2aa4545eb5d98167667113974bfdfdf2c317
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/CVODEMEX/src/source_SUNDIALS_CVODES_25/sundials_sptfqmr.c
@@ -0,0 +1,525 @@
+/*
+ * -----------------------------------------------------------------
+ * $Revision: 749 $
+ * $Date: 2011-06-22 14:49:10 +0200 (Wed, 22 Jun 2011) $
+ * -----------------------------------------------------------------
+ * Programmer(s): Aaron Collier @ LLNL
+ * -----------------------------------------------------------------
+ * Copyright (c) 2005, The Regents of the University of California.
+ * Produced at the Lawrence Livermore National Laboratory.
+ * All rights reserved.
+ * For details, see the LICENSE file.
+ * -----------------------------------------------------------------
+ * This is the implementation file for the scaled preconditioned
+ * Transpose-Free Quasi-Minimal Residual (SPTFQMR) linear solver.
+ * -----------------------------------------------------------------
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <sundials/sundials_sptfqmr.h>
+#include <sundials/sundials_math.h>
+
+/*
+ * -----------------------------------------------------------------
+ * private constants
+ * -----------------------------------------------------------------
+ */
+
+#define ZERO RCONST(0.0)
+#define ONE  RCONST(1.0)
+
+/*
+ * -----------------------------------------------------------------
+ * Function : SptfqmrMalloc
+ * -----------------------------------------------------------------
+ */
+
+SptfqmrMem SptfqmrMalloc(int l_max, N_Vector vec_tmpl)
+{
+  SptfqmrMem mem;
+  N_Vector *r;
+  N_Vector q, d, v, p, u;
+  N_Vector r_star, vtemp1, vtemp2, vtemp3;
+
+  /* Check the input parameters */
+  if ((l_max <= 0) || (vec_tmpl == NULL)) return(NULL);
+
+  /* Allocate space for vectors */
+  r_star = NULL;
+  r_star = N_VClone(vec_tmpl);
+  if (r_star == NULL) return(NULL);
+
+  q = NULL;
+  q = N_VClone(vec_tmpl);
+  if (q == NULL) {
+    N_VDestroy(r_star);
+    return(NULL);
+  }
+
+  d = NULL;
+  d = N_VClone(vec_tmpl);
+  if (d == NULL) {
+    N_VDestroy(r_star);
+    N_VDestroy(q);
+    return(NULL);
+  }
+
+  v = NULL;
+  v = N_VClone(vec_tmpl);
+  if (v == NULL) {
+    N_VDestroy(r_star);
+    N_VDestroy(q);
+    N_VDestroy(d);
+    return(NULL);
+  }
+
+  p = NULL;
+  p = N_VClone(vec_tmpl);
+  if (p == NULL) {
+    N_VDestroy(r_star);
+    N_VDestroy(q);
+    N_VDestroy(d);
+    N_VDestroy(v);
+    return(NULL);
+  }
+
+  r = NULL;
+  r = N_VCloneVectorArray(2, vec_tmpl);
+  if (r == NULL) {
+    N_VDestroy(r_star);
+    N_VDestroy(q);
+    N_VDestroy(d);
+    N_VDestroy(v);
+    N_VDestroy(p);
+    return(NULL);
+  }
+
+  u = NULL;
+  u = N_VClone(vec_tmpl);
+  if (u == NULL) {
+    N_VDestroy(r_star);
+    N_VDestroy(q);
+    N_VDestroy(d);
+    N_VDestroy(v);
+    N_VDestroy(p);
+    N_VDestroyVectorArray(r, 2);
+    return(NULL);
+  }
+
+  vtemp1 = NULL;
+  vtemp1 = N_VClone(vec_tmpl);
+  if (vtemp1 == NULL) {
+    N_VDestroy(r_star);
+    N_VDestroy(q);
+    N_VDestroy(d);
+    N_VDestroy(v);
+    N_VDestroy(p);
+    N_VDestroyVectorArray(r, 2);
+    N_VDestroy(u);
+    return(NULL);
+  }
+
+  vtemp2 = NULL;
+  vtemp2 = N_VClone(vec_tmpl);
+  if (vtemp2 == NULL) {
+    N_VDestroy(r_star);
+    N_VDestroy(q);
+    N_VDestroy(d);
+    N_VDestroy(v);
+    N_VDestroy(p);
+    N_VDestroyVectorArray(r, 2);
+    N_VDestroy(u);
+    N_VDestroy(vtemp1);
+    return(NULL);
+  }
+
+  vtemp3 = NULL;
+  vtemp3 = N_VClone(vec_tmpl);
+  if (vtemp3 == NULL) {
+    N_VDestroy(r_star);
+    N_VDestroy(q);
+    N_VDestroy(d);
+    N_VDestroy(v);
+    N_VDestroy(p);
+    N_VDestroyVectorArray(r, 2);
+    N_VDestroy(u);
+    N_VDestroy(vtemp1);
+    N_VDestroy(vtemp2);
+    return(NULL);
+  }
+
+  /* Allocate memory for SptfqmrMemRec */
+  mem = NULL;
+  mem = (SptfqmrMem) malloc(sizeof(SptfqmrMemRec));
+  if (mem == NULL) {
+    N_VDestroy(r_star);
+    N_VDestroy(q);
+    N_VDestroy(d);
+    N_VDestroy(v);
+    N_VDestroy(p);
+    N_VDestroyVectorArray(r, 2);
+    N_VDestroy(u);
+    N_VDestroy(vtemp1);
+    N_VDestroy(vtemp2);
+    N_VDestroy(vtemp3);
+    return(NULL);
+  }
+
+  /* Intialize SptfqmrMemRec data structure */
+  mem->l_max  = l_max;
+  mem->r_star = r_star;
+  mem->q      = q;
+  mem->d      = d;
+  mem->v      = v;
+  mem->p      = p;
+  mem->r      = r;
+  mem->u      = u;
+  mem->vtemp1 = vtemp1;
+  mem->vtemp2 = vtemp2;
+  mem->vtemp3 = vtemp3;
+
+  /* Return pointer to SPTFQMR memory block */
+  return(mem);
+}
+
+#define l_max  (mem->l_max)
+#define r_star (mem->r_star)
+#define q_     (mem->q)
+#define d_     (mem->d)
+#define v_     (mem->v)
+#define p_     (mem->p)
+#define r_     (mem->r)
+#define u_     (mem->u)
+#define vtemp1 (mem->vtemp1)
+#define vtemp2 (mem->vtemp2)
+#define vtemp3 (mem->vtemp3)
+
+/*
+ * -----------------------------------------------------------------
+ * Function : SptfqmrSolve
+ * -----------------------------------------------------------------
+ */
+
+int SptfqmrSolve(SptfqmrMem mem, void *A_data, N_Vector x, N_Vector b,
+		 int pretype, realtype delta, void *P_data, N_Vector sx,
+		 N_Vector sb, ATimesFn atimes, PSolveFn psolve,
+		 realtype *res_norm, int *nli, int *nps)
+{
+  realtype alpha, tau, eta, beta, c, sigma, v_bar, omega;
+  realtype rho[2];
+  realtype r_init_norm, r_curr_norm;
+  realtype temp_val;
+  booleantype preOnLeft, preOnRight, scale_x, scale_b, converged;
+  booleantype b_ok;
+  int n, m, ier;
+
+  /* Exit immediately if memory pointer is NULL */
+  if (mem == NULL) return(SPTFQMR_MEM_NULL);
+
+  temp_val = r_curr_norm = -ONE;  /* Initialize to avoid compiler warnings */
+
+  *nli = *nps = 0;    /* Initialize counters */
+  converged = FALSE;  /* Initialize convergence flag */
+  b_ok = FALSE;
+
+  if ((pretype != PREC_LEFT)  &&
+      (pretype != PREC_RIGHT) &&
+      (pretype != PREC_BOTH)) pretype = PREC_NONE;
+
+  preOnLeft  = ((pretype == PREC_BOTH) || (pretype == PREC_LEFT));
+  preOnRight = ((pretype == PREC_BOTH) || (pretype == PREC_RIGHT));
+
+  scale_x = (sx != NULL);
+  scale_b = (sb != NULL);
+
+  /* Set r_star to initial (unscaled) residual r_star = r_0 = b - A*x_0 */
+  /* NOTE: if x == 0 then just set residual to b and continue */
+  if (N_VDotProd(x, x) == ZERO) N_VScale(ONE, b, r_star);
+  else {
+    ier = atimes(A_data, x, r_star);
+    if (ier != 0)
+      return((ier < 0) ? SPTFQMR_ATIMES_FAIL_UNREC : SPTFQMR_ATIMES_FAIL_REC);
+    N_VLinearSum(ONE, b, -ONE, r_star, r_star);
+  }
+
+  /* Apply left preconditioner and b-scaling to r_star (or really just r_0) */
+  if (preOnLeft) {
+    ier = psolve(P_data, r_star, vtemp1, PREC_LEFT);
+    (*nps)++;
+    if (ier != 0)
+      return((ier < 0) ? SPTFQMR_PSOLVE_FAIL_UNREC : SPTFQMR_PSOLVE_FAIL_REC);
+  }
+  else N_VScale(ONE, r_star, vtemp1);
+  if (scale_b) N_VProd(sb, vtemp1, r_star);
+  else N_VScale(ONE, vtemp1, r_star);
+
+  /* Initialize rho[0] */
+  /* NOTE: initialized here to reduce number of computations - avoid need
+           to compute r_star^T*r_star twice, and avoid needlessly squaring
+           values */
+  rho[0] = N_VDotProd(r_star, r_star);
+
+  /* Compute norm of initial residual (r_0) to see if we really need
+     to do anything */
+  *res_norm = r_init_norm = RSqrt(rho[0]);
+  if (r_init_norm <= delta) return(SPTFQMR_SUCCESS);
+
+  /* Set v_ = A*r_0 (preconditioned and scaled) */
+  if (scale_x) N_VDiv(r_star, sx, vtemp1);
+  else N_VScale(ONE, r_star, vtemp1);
+  if (preOnRight) {
+    N_VScale(ONE, vtemp1, v_);
+    ier = psolve(P_data, v_, vtemp1, PREC_RIGHT);
+    (*nps)++;
+    if (ier != 0) return((ier < 0) ? SPTFQMR_PSOLVE_FAIL_UNREC : SPTFQMR_PSOLVE_FAIL_REC);
+  }
+  ier = atimes(A_data, vtemp1, v_);
+  if (ier != 0)
+    return((ier < 0) ? SPTFQMR_ATIMES_FAIL_UNREC : SPTFQMR_ATIMES_FAIL_REC);
+  if (preOnLeft) {
+    ier = psolve(P_data, v_, vtemp1, PREC_LEFT);
+    (*nps)++;
+    if (ier != 0) return((ier < 0) ? SPTFQMR_PSOLVE_FAIL_UNREC : SPTFQMR_PSOLVE_FAIL_REC);
+  }
+  else N_VScale(ONE, v_, vtemp1);
+  if (scale_b) N_VProd(sb, vtemp1, v_);
+  else N_VScale(ONE, vtemp1, v_);
+
+  /* Initialize remaining variables */
+  N_VScale(ONE, r_star, r_[0]);
+  N_VScale(ONE, r_star, u_);
+  N_VScale(ONE, r_star, p_);
+  N_VConst(ZERO, d_);
+
+  tau = r_init_norm;
+  v_bar = eta = ZERO;
+
+  /* START outer loop */
+  for (n = 0; n < l_max; ++n) {
+
+    /* Increment linear iteration counter */
+    (*nli)++;
+
+    /* sigma = r_star^T*v_ */
+    sigma = N_VDotProd(r_star, v_);
+
+    /* alpha = rho[0]/sigma */
+    alpha = rho[0]/sigma;
+
+    /* q_ = u_-alpha*v_ */
+    N_VLinearSum(ONE, u_, -alpha, v_, q_);
+
+    /* r_[1] = r_[0]-alpha*A*(u_+q_) */
+    N_VLinearSum(ONE, u_, ONE, q_, r_[1]);
+    if (scale_x) N_VDiv(r_[1], sx, r_[1]);
+    if (preOnRight) {
+      N_VScale(ONE, r_[1], vtemp1);
+      ier = psolve(P_data, vtemp1, r_[1], PREC_RIGHT);
+      (*nps)++;
+      if (ier != 0) return((ier < 0) ? SPTFQMR_PSOLVE_FAIL_UNREC : SPTFQMR_PSOLVE_FAIL_REC);
+    }
+    ier = atimes(A_data, r_[1], vtemp1);
+    if (ier != 0)
+      return((ier < 0) ? SPTFQMR_ATIMES_FAIL_UNREC : SPTFQMR_ATIMES_FAIL_REC);
+    if (preOnLeft) {
+      ier = psolve(P_data, vtemp1, r_[1], PREC_LEFT);
+      (*nps)++;
+      if (ier != 0) return((ier < 0) ? SPTFQMR_PSOLVE_FAIL_UNREC : SPTFQMR_PSOLVE_FAIL_REC);
+    }
+    else N_VScale(ONE, vtemp1, r_[1]);
+    if (scale_b) N_VProd(sb, r_[1], vtemp1);
+    else N_VScale(ONE, r_[1], vtemp1);
+    N_VLinearSum(ONE, r_[0], -alpha, vtemp1, r_[1]);
+
+    /* START inner loop */
+    for (m = 0; m < 2; ++m) {
+
+      /* d_ = [*]+(v_bar^2*eta/alpha)*d_ */
+      /* NOTES:
+       *   (1) [*] = u_ if m == 0, and q_ if m == 1
+       *   (2) using temp_val reduces the number of required computations
+       *       if the inner loop is executed twice
+       */
+      if (m == 0) {
+	temp_val = RSqrt(N_VDotProd(r_[1], r_[1]));
+	omega = RSqrt(RSqrt(N_VDotProd(r_[0], r_[0]))*temp_val);
+	N_VLinearSum(ONE, u_, SQR(v_bar)*eta/alpha, d_, d_);
+      }
+      else {
+	omega = temp_val;
+	N_VLinearSum(ONE, q_, SQR(v_bar)*eta/alpha, d_, d_);
+      }
+
+      /* v_bar = omega/tau */
+      v_bar = omega/tau;
+
+      /* c = (1+v_bar^2)^(-1/2) */
+      c = ONE / RSqrt(ONE+SQR(v_bar));
+
+      /* tau = tau*v_bar*c */
+      tau = tau*v_bar*c;
+
+      /* eta = c^2*alpha */
+      eta = SQR(c)*alpha;
+
+      /* x = x+eta*d_ */
+      N_VLinearSum(ONE, x, eta, d_, x);
+
+      /* Check for convergence... */
+      /* NOTE: just use approximation to norm of residual, if possible */
+      *res_norm = r_curr_norm = tau*RSqrt(m+1);
+
+      /* Exit inner loop if iteration has converged based upon approximation
+	 to norm of current residual */
+      if (r_curr_norm <= delta) {
+	converged = TRUE;
+	break;
+      }
+
+      /* Decide if actual norm of residual vector should be computed */
+      /* NOTES:
+       *   (1) if r_curr_norm > delta, then check if actual residual norm
+       *       is OK (recall we first compute an approximation)
+       *   (2) if r_curr_norm >= r_init_norm and m == 1 and n == l_max, then
+       *       compute actual residual norm to see if the iteration can be
+       *       saved
+       *   (3) the scaled and preconditioned right-hand side of the given
+       *       linear system (denoted by b) is only computed once, and the
+       *       result is stored in vtemp3 so it can be reused - reduces the
+       *       number of psovles if using left preconditioning
+       */
+      if ((r_curr_norm > delta) ||
+	  (r_curr_norm >= r_init_norm && m == 1 && n == l_max)) {
+
+	/* Compute norm of residual ||b-A*x||_2 (preconditioned and scaled) */
+	if (scale_x) N_VDiv(x, sx, vtemp1);
+	else N_VScale(ONE, x, vtemp1);
+	if (preOnRight) {
+	  ier = psolve(P_data, vtemp1, vtemp2, PREC_RIGHT);
+	  (*nps)++;
+	  if (ier != 0) return((ier < 0) ? SPTFQMR_PSOLVE_FAIL_UNREC : SPTFQMR_PSOLVE_FAIL_UNREC);
+	  N_VScale(ONE, vtemp2, vtemp1);
+	}
+	ier = atimes(A_data, vtemp1, vtemp2);
+        if (ier != 0)
+          return((ier < 0) ? SPTFQMR_ATIMES_FAIL_UNREC : SPTFQMR_ATIMES_FAIL_REC);
+	if (preOnLeft) {
+	  ier = psolve(P_data, vtemp2, vtemp1, PREC_LEFT);
+	  (*nps)++;
+	  if (ier != 0) return((ier < 0) ? SPTFQMR_PSOLVE_FAIL_UNREC : SPTFQMR_PSOLVE_FAIL_REC);
+	}
+	else N_VScale(ONE, vtemp2, vtemp1);
+	if (scale_b) N_VProd(sb, vtemp1, vtemp2);
+	else N_VScale(ONE, vtemp1, vtemp2);
+	/* Only precondition and scale b once (result saved for reuse) */
+	if (!b_ok) {
+	  b_ok = TRUE;
+	  if (preOnLeft) {
+	    ier = psolve(P_data, b, vtemp3, PREC_LEFT);
+	    (*nps)++;
+	    if (ier != 0) return((ier < 0) ? SPTFQMR_PSOLVE_FAIL_UNREC : SPTFQMR_PSOLVE_FAIL_REC);
+	  }
+	  else N_VScale(ONE, b, vtemp3);
+	  if (scale_b) N_VProd(sb, vtemp3, vtemp3);
+	}
+	N_VLinearSum(ONE, vtemp3, -ONE, vtemp2, vtemp1);
+	*res_norm = r_curr_norm = RSqrt(N_VDotProd(vtemp1, vtemp1));
+
+	/* Exit inner loop if inequality condition is satisfied 
+	   (meaning exit if we have converged) */
+	if (r_curr_norm <= delta) {
+	  converged = TRUE;
+	  break;
+	}
+
+      }
+
+    }  /* END inner loop */
+
+    /* If converged, then exit outer loop as well */
+    if (converged == TRUE) break;
+
+    /* rho[1] = r_star^T*r_[1] */
+    rho[1] = N_VDotProd(r_star, r_[1]);
+
+    /* beta = rho[1]/rho[0] */
+    beta = rho[1]/rho[0];
+
+    /* u_ = r_[1]+beta*q_ */
+    N_VLinearSum(ONE, r_[1], beta, q_, u_);
+
+    /* p_ = u_+beta*(q_+beta*p_) */
+    N_VLinearSum(beta, q_, SQR(beta), p_, p_);
+    N_VLinearSum(ONE, u_, ONE, p_, p_);
+
+    /* v_ = A*p_ */
+    if (scale_x) N_VDiv(p_, sx, vtemp1);
+    else N_VScale(ONE, p_, vtemp1);
+    if (preOnRight) {
+      N_VScale(ONE, vtemp1, v_);
+      ier = psolve(P_data, v_, vtemp1, PREC_RIGHT);
+      (*nps)++;
+      if (ier != 0) return((ier < 0) ? SPTFQMR_PSOLVE_FAIL_UNREC : SPTFQMR_PSOLVE_FAIL_REC);
+    }
+    ier = atimes(A_data, vtemp1, v_);
+    if (ier != 0)
+      return((ier < 0) ? SPTFQMR_ATIMES_FAIL_UNREC : SPTFQMR_ATIMES_FAIL_REC);
+    if (preOnLeft) {
+      ier = psolve(P_data, v_, vtemp1, PREC_LEFT);
+      (*nps)++;
+      if (ier != 0) return((ier < 0) ? SPTFQMR_PSOLVE_FAIL_UNREC : SPTFQMR_PSOLVE_FAIL_REC);
+    }
+    else N_VScale(ONE, v_, vtemp1);
+    if (scale_b) N_VProd(sb, vtemp1, v_);
+    else N_VScale(ONE, vtemp1, v_);
+
+    /* Shift variable values */
+    /* NOTE: reduces storage requirements */
+    N_VScale(ONE, r_[1], r_[0]);
+    rho[0] = rho[1];
+
+  }  /* END outer loop */
+
+  /* Determine return value */
+  /* If iteration converged or residual was reduced, then return current iterate (x) */
+  if ((converged == TRUE) || (r_curr_norm < r_init_norm)) {
+    if (scale_x) N_VDiv(x, sx, x);
+    if (preOnRight) {
+      ier = psolve(P_data, x, vtemp1, PREC_RIGHT);
+      (*nps)++;
+      if (ier != 0) return((ier < 0) ? SPTFQMR_PSOLVE_FAIL_UNREC : SPTFQMR_PSOLVE_FAIL_UNREC);
+      N_VScale(ONE, vtemp1, x);
+    }
+    if (converged == TRUE) return(SPTFQMR_SUCCESS);
+    else return(SPTFQMR_RES_REDUCED);
+  }
+  /* Otherwise, return error code */
+  else return(SPTFQMR_CONV_FAIL);
+}
+
+/*
+ * -----------------------------------------------------------------
+ * Function : SptfqmrFree
+ * -----------------------------------------------------------------
+ */
+
+void SptfqmrFree(SptfqmrMem mem)
+{
+
+  if (mem == NULL) return;
+
+  N_VDestroy(r_star);
+  N_VDestroy(q_);
+  N_VDestroy(d_);
+  N_VDestroy(v_);
+  N_VDestroy(p_);
+  N_VDestroyVectorArray(r_, 2);
+  N_VDestroy(u_);
+  N_VDestroy(vtemp1);
+  N_VDestroy(vtemp2);
+  N_VDestroy(vtemp3);
+
+  free(mem); mem = NULL;
+}
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/mfiles/convertNNCa2NANNCaSBPD.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/mfiles/convertNNCa2NANNCaSBPD.m
new file mode 100644
index 0000000000000000000000000000000000000000..ccb588e8fcde2c478efc588dc4bd8a1110dfb30a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/mfiles/convertNNCa2NANNCaSBPD.m
@@ -0,0 +1,36 @@
+function [output] = convertNNCa2NANNCaSBPD(input)
+% convertNNCa2NANNCaSBPD: complicated name for simple function. This
+% function is called by a MEX simulation function when returning
+% non-numeric initial conditions. input is a cell-array with string
+% entries, defining the initial conditions. some of the strings only
+% contain numeric values. this function here will convert these from
+% strings to numbers. 
+
+% Information:
+% ============
+% Copyright (C) 2005-2013 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+output = {};
+for k=1:length(input),
+    test = str2double(input{k});
+    if isnan(test),
+        output{k} = input{k};
+    else
+        output{k} = test;
+    end
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/mfiles/getparamindicesSBPD.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/mfiles/getparamindicesSBPD.m
new file mode 100644
index 0000000000000000000000000000000000000000..b840c77ea6b4bf7a153e6c608009eb601f188269
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/mfiles/getparamindicesSBPD.m
@@ -0,0 +1,53 @@
+function [output] = getparamindicesSBPD(model,parameters)
+% getparamindicesSBPD: Determines a vector of model parameter indices, the 
+% order corresponding to the parameters argument.
+% 
+% USAGE:
+% ======
+% [output] = getparamindicesSBPD(model,parameters)
+% 
+% model: SBmodel, ODE file model, or MEX simulation model
+% parameters: Cell-array of parameter names
+% 
+% OUTPUT:
+% =======
+% output: Vector of parameter indices
+
+% Information:
+% ============
+% Copyright (C) 2005-2013 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+% check if parameter names is not a cell array
+if ischar(parameters),
+    parameters = {parameters};
+end
+% Get all parameter names in the order as they are stored in the model
+allnames = SBparameters(model);
+% Get the indices
+output = zeros(1,length(parameters));
+for k = 1:length(parameters),
+    % get the index
+    index = strmatchSB(parameters{k},allnames,'exact');
+    % check ... if error then the current parameter does not exist in the model
+    if isempty(index),
+        error('Parameter ''%s'' does not exist in the model.',parameters{k});
+    end
+    output(k) = index;
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/mfiles/getstateindicesSBPD.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/mfiles/getstateindicesSBPD.m
new file mode 100644
index 0000000000000000000000000000000000000000..2ebd8a468a1e97181aab62fac5f915e5d3788327
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/mfiles/getstateindicesSBPD.m
@@ -0,0 +1,50 @@
+function [output] = getstateindicesSBPD(model,statenames)
+% getstateindicesSBPD: Determines a vector of model state indices, the 
+% order corresponding to the states argument.
+% 
+% USAGE:
+% ======
+% [output] = getstateindicesSBPD(model,states)
+% 
+% model: SBmodel, ODE file model, or MEX simulation model
+% states: Cell-array of state names
+% 
+% OUTPUT:
+% =======
+% output: Vector of state indices
+
+% Information:
+% ============
+% Copyright (C) 2005-2013 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+% Convert to cell array if necessary
+if ischar(statenames),
+    statenames = {statenames};
+end
+% Get all state names in order as stored in the model
+allnames = SBstates(model);
+% Get the indices
+output = zeros(1,length(statenames));
+for k = 1:length(statenames),
+    index = strmatchSB(statenames{k},allnames,'exact');
+    if isempty(index),
+        error(sprintf('State ''%s'' does not exist in the model.',statenames{k}));
+    end
+    output(k) = index;
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/mfiles/makeTempMEXmodelSBPD.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/mfiles/makeTempMEXmodelSBPD.m
new file mode 100644
index 0000000000000000000000000000000000000000..94b22198083398f9ec0959d2303e290bd9dadcba
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/mfiles/makeTempMEXmodelSBPD.m
@@ -0,0 +1,89 @@
+function [MEXmodel, MEXmodelfullpath] = makeTempMEXmodelSBPD(model)
+% makeTempMEXmodelSBPD: This function can be used to create a temporary 
+% MEX simulation function. Temporary means that it is created in the 
+% systems temp directory and that no name can be chosen, but that a unique
+% temporary filename is automatically chosen and returned.
+% 
+% USAGE:
+% ======
+% [MEXmodel, MEXmodelfullpath] = makeTempMEXmodelSBPD(model)
+% 
+% model: SBmodel to convert to a temporary MEX simulation function
+% 
+% OUTPUT ARGUMENTS:
+% =================
+% MEXmodel: name of the MEX simulation function (filename without .mex extension)
+% MEXmodelfullpath: complete path to the created MEX simulation function (including mex extension)
+%                   This information can be used to delete the function as
+%                   soon as it is not needed anymore.
+
+% Information:
+% ============
+% Copyright (C) 2005-2013 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% TEMPDIR 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+addpath(tempdirSB);   % add it to the path
+returndir = pwd;      % save the current dir to return to it
+cd(tempdirSB);        % change to tempdir
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CREATE THE MEX SIMULATION FUNCTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Unfortunately this strange while loop is required,
+% since the compilation of MEX files using MinGW sometimes 
+% produces invalid MEX files. It is so seldom that it does not matter
+% to have this loop here. And after all a 3x speed increase in simulation
+% is worth a lot :). Why does Mathworks use such a sh...y compiler?
+notOk = 1;
+warning off;
+while notOk,
+    try
+        % GET TEMP FILE NAME
+        tempfilefullpath = tempnameSB;
+        [pathstr,tempfilename,ext] = fileparts(tempfilefullpath);
+        SBPDmakeMEXmodel(model,tempfilename);
+        feval(tempfilename,'parameters');
+        notOk = 0;
+    catch
+        if ~isempty(strfind(lasterr,'Invalid MEX-file')),
+            % disp('Nu isses wieder passiert');
+            clear mex;
+            delete([tempfilename,'.',mexext]);
+            delete([tempfilename,'.c']);
+            delete([tempfilename,'.h']);
+            notOk = 1;
+        elseif ~isempty(strfind(lasterr,'Error using ==> mex')),
+            error(sprintf('MEX compilation of model failed. Please check the model syntax.\nThe output of the compiler above will guide you to the error.\ntp******.c is the .c file that showed the error.\nOpen it using ">> edit tp******.c" and look at the indicated lines.\nDo not correct it in the .c file but in the corresponding model\n(or experiment) description.'));
+        else
+            cd(returndir);
+            error(lasterr); 
+        end            
+    end
+end
+warning on;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% RETURN TO THE PREVIOUS DIRECTORY AND CREATE OUTPUT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+rehash;
+cd(returndir);
+MEXmodel = tempfilename;
+MEXmodelfullpath = sprintf('%s.%s',tempfilefullpath,mexext);
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/mfiles/makeinicondvectorSBPD.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/mfiles/makeinicondvectorSBPD.m
new file mode 100644
index 0000000000000000000000000000000000000000..69d810513128ed8aca6335be41bcb4db82352c55
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/mfiles/makeinicondvectorSBPD.m
@@ -0,0 +1,62 @@
+function [icvector] = makeinicondvectorSBPD(model,states,statevalues)
+% makeinicondvectorSBPD: The mex simulation functions take a full initial
+% condition vector as an input. In order to construct such a vector while
+% changing some but possibly not all IC values this function can be used.
+%
+% This function does handle also non-numeric initial conditions. The
+% default state vector is determined based on the given model. Then the
+% user provided changes are added as given.
+%
+% USAGE:
+% ======
+% [icvector] = makeinicondvectorSBPD(model,states,statevalues)
+% 
+% model: SBmodel, ODE file model, or MEX file model
+% states: Cell-array of state names for which to change the ICs
+% statevalues: Vector with the corresponding values for the ICs of the states.
+% 
+% OUTPUT:
+% =======
+% icvector: Constructed initial condition vector
+
+% Information:
+% ============
+% Copyright (C) 2005-2013 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+% Convert to cell-array if necessary
+if ischar(states),
+    states = {states};
+end
+% State input arguments need to have same length ...
+if length(states) ~= length(statevalues),
+    error('Different numbers of states and statevalues.');
+end
+% Get the initialconditions from the model
+icvector = SBcalcICvector(model);
+% Get all state names to check against the given state names
+allstates = SBstates(model);
+% Update the icvector with given values
+for k = 1:length(states),
+    index = strmatchSB(states{k},allstates,'exact');
+    if isempty(index),
+        error(sprintf('Statename ''%s'' is no state in the model.',states{k}));
+    end
+    icvector(index) = statevalues(k);
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/mfiles/makeparamvecSBPD.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/mfiles/makeparamvecSBPD.m
new file mode 100644
index 0000000000000000000000000000000000000000..f77df6960ef22c83597dfba6294b6bc2bcdfcf2a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/mfiles/makeparamvecSBPD.m
@@ -0,0 +1,55 @@
+function [paramvector] = makeparamvecSBPD(model,parameters,parametervalues)
+% makeparamvecSBPD: The mex simulation functions take a full parameter value
+% vector as an input. In order to construct such a vector while changing 
+% some but possibly not all parameter values this function can be used.
+% 
+% USAGE:
+% ======
+% [paramvector] = makeparamvecSBPD(model,parameters,parametervalues)
+% 
+% model: SBmodel, ODE file model, or MEX file model
+% parameters: Cell-array of parameter names for which to change the parametervalues
+% parametervalues: Vector with the corresponding values for the parameters 
+% 
+% OUTPUT:
+% =======
+% paramvector: Constructed initial condition vector
+
+% Information:
+% ============
+% Copyright (C) 2005-2013 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+% Convert to cell-array if necessary
+if ischar(parameters),
+    parameters = {parameters};
+end
+% Parameter input arguments need to have same length ...
+if length(parameters) ~= length(parametervalues),
+    error('Different numbers of parameters and parametervalues.');
+end
+% Get the parametervalues from the model
+[allParams,paramvector] = SBparameters(model);
+% Update the paramvector with given values
+for k = 1:length(parameters),
+    index = strmatchSB(parameters{k},allParams,'exact');
+    if isempty(index),
+        error(sprintf('Parameter name ''%s'' is no parameter in the model.',parameters{k}));
+    end
+    paramvector(index) = parametervalues(k);
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/mfiles/mexcompileSBPD.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/mfiles/mexcompileSBPD.m
new file mode 100644
index 0000000000000000000000000000000000000000..30d937a1ad417b99a9bb24639a283cdd0e3f6e62
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/mfiles/mexcompileSBPD.m
@@ -0,0 +1,39 @@
+function [] = mexcompileSBPD(filename)
+% mexcompileSBPD: Compiles an SBmodel that has been converted to a mexfile.h 
+% and mexfile.c and links it with the CVODE integrator from the SUNDIALS
+% suite (http://www.llnl.gov/CASC/sundials/). 
+% 
+% USAGE:
+% ======
+% [] = mexcompileSBPD(mexfile)
+%
+% mexfile: Basename of the model files (mexfile.c and mexfile.h)  
+    
+% Information:
+% ============
+% Copyright (C) 2005-2013 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+if ~isunix,
+    libpath = which('CVODEmex25.lib');
+else
+    libpath = which('CVODEmex25.a');
+end
+includefolder = fileparts(which('mexmathaddon.h'));
+% do compilation
+eval(sprintf('mex -O -I''%s'' %s.c ''%s'';',includefolder,filename,libpath));
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/mfiles/updateparamvecSBPD.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/mfiles/updateparamvecSBPD.m
new file mode 100644
index 0000000000000000000000000000000000000000..d4e7fc51ec494613a3080a572427e6e785547c90
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPD/tools/mexmodelhandling/auxiliary/mfiles/updateparamvecSBPD.m
@@ -0,0 +1,60 @@
+function [newparamvector] = updateparamvecSBPD(paramnames, oldparamvector, pnames, pvalues)
+% updateparamvecSBPD: The mex simulation functions take a full parameter value
+% vector as an input. In order to construct such a vector from an existing 
+% parameter vector while changing some but possibly not all parameter
+% values this function can be used. 
+% 
+% USAGE:
+% ======
+% [newparamvector] = updateparamvecSBPD(paramnames, oldparamvector, pnames, pvalues)
+% 
+% paramnames: Cell-array of all model parameter names (in the order as they
+%   appear in the model)
+% oldparamvector: Full parameter vector before the change
+% pnames: Cell-array of parameter names for which to change the
+%   parametervalues 
+% pvalues: Vector with parameter values for the parameters to be changed
+%   (order defined by pnames)
+% 
+% OUTPUT:
+% =======
+% newparamvector: Constructed new parameter vector with changed parameters
+
+% Information:
+% ============
+% Copyright (C) 2005-2013 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+% Convert to cell-array if necessary
+if ischar(pnames),
+    pnames = {pnames};
+end
+% Parameter input arguments need to have same length ...
+if length(pnames) ~= length(pvalues),
+    error('Different numbers of parameters and parametervalues to be changed.');
+end
+
+% Update the paramvector with given values
+newparamvector = oldparamvector;
+for k = 1:length(pnames),
+    index = strmatchSB(pnames{k}, paramnames, 'exact');
+    if isempty(index),
+        disp(sprintf('Parameter name ''%s'' is no parameter in the model.',pnames{k}));
+    end
+    newparamvector(index) = pvalues(k);
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/Contents.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/Contents.m
new file mode 100644
index 0000000000000000000000000000000000000000..6cba441a7b89a1365528e401ee9bdb4bf941f5ef
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/Contents.m
@@ -0,0 +1,325 @@
+% SBPOP 
+% Version $Rev: 1754 $ (R2010b-R2014a) $Date: 2014-12-10 18:41:04 +0100 (Wed, 10 Dec 2014) $
+% 
+% Installation of the package
+% ===========================
+%   installSBPOP            - Installation script for the SBPOP package
+%   lookforSBPOP            - Searches SBPOP functions for strings and
+%                             opens the documents in which these strings
+%                             appear 
+%   newscriptSBPOP          - Function creating a template file for a new
+%                             script 
+%   newfunctionSBPOP        - Function creating a template file for a new
+%                             function 
+%   setseedSBPOP            - Set the default stream to defaultSeed
+%
+%
+% Dosing schedule related functions
+% =================================
+%   SBPOPdosing             - Creates an SBPOPdosing object defining a
+%                             dosing schedule
+%   SBPOPstruct             - Returns the internal data structure of an
+%                             SBPOPdosing object
+%   isSBPOPdosing           - Checks if input argument is an SBPOPdosing
+%                             object 
+%   SBPOPcreateDOSfile      - Creates a *.dos file with the dosing text
+%                             description 
+%   SBPOPcreateDOSING       - Creating a desired SBPOPdosing scheme 
+%   SBPOPdoseupdatevalue    - Allows to update the dosing amount for a
+%                             given input, defined in an SBPOPdosing object
+%   SBPOPsimulate           - Simulates a given SBmodel with a given
+%                             SBPOPdosing scheme 
+%   SBPOPmergemoddos        - Based on a model and dosing object, a new
+%                             SBmodel is generated, that implements the
+%                             defined dosings. Multiple dosing schedules
+%                             are realized by updating the parameters of
+%                             subsequent dosings using events. 
+%   mergemoddosSBPOP        - This function takes an SBmodel and an
+%                             SBPOPdosing scheme as inputs. It adds
+%                             necessary elements to the model that are
+%                             required to implement the different dosing
+%                             inputs (bolus, infusion, absorption0,
+%                             absorption1) for simulation purposes (e.g. by
+%                             the SBPOPsimdosing function).
+%   SBPOPsimdosing          - Simulates the application of a dosing
+%                             schedule to a model that has been prepared
+%                             for it (using the mergemoddosSBPOP function)
+%                             and either plots or returns the simulation
+%                             results.
+%   getmoddosinputinfoSBPOP - Checks the availability of dosing input
+%                             definitions used in the model in the dosing
+%                             object and returns a structure similar to
+%                             the "input" field structure of an SBmodel,
+%                             augmented with the dosing information,
+%                             defined in the SBPOPdosing object. 
+%   dosing2doseeventSBPOP   - This function takes an SBPOP dosing object as
+%                             input and returns a structure in which the
+%                             dosing events, happening, are sorted
+%                             according to the times at which they happen.
+%                             Additionally, the output structure contains
+%                             information about the dosing amount and the
+%                             names of the parameters in a model to change
+%                             in order to apply the dosing.
+%   doseinputsSBPOP         - Extracts names and types of dosing inputs
+%                             from a SBPOPdosing object
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% TOOLS 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+% General data file handling
+% ==========================
+% SBPOPloadCSVdataset 		- Loads a CSV dataset as a MATLAB dataset
+% SBPOPloadNONCSVdataset 	- Loads a non-CSV dataset as a MATLAB dataset.
+%                             Example: NONMEM and Monolix output tables 
+% SBPOPexportCSVdataset 	- Exports a MATLAB dataset as a CSV file
+% SBPOPdataset2wide         - Expands a dataset from a row based format to
+%                             a column based format 
+% SBPOPsas7bdat2csv         - Convert a sas7bdat file to a CSV file
+%                             (Requires presence of SAS on your systems
+%                             command line)
+%
+% Plotting Tools
+% ==============
+% SBPOPplotCovarianceCat    - This function plots the covariance
+%                             relationship between a list of continuous
+%                             variables and a list of categorical variabels 
+% SBPOPplotfacetgrid        - This function allows to generate facet-grid
+%                             plot with many different settings
+% SBPOPplotfill             - Function allowing to plot shaded areas with
+%                             transparency 
+% SBPOPplotHistogram 		- This function plots histograms of the data
+%                             provided, allows grouping and plotting
+%                             several histograms on top of each other
+% SBPOPplotpairwiseCorr     - Plots pairwise correlations of data
+% SBPOPplotQQ 				- QQ plot for provided input data
+% SBPOPplottrellis          - Nice function to do Trellis plots with many
+%                             different settings
+% SBPOPplotXY 	    		- This function plots Ydata vs. Xdata with many
+%                             different settings
+%
+% Monolix related functions
+% =========================
+% SBPOPcreateMLXTRANfile 		- Create MLXTRAN structural model based on
+%                                 SBmodel and SBPOPdosing scheme
+% SBPOPcreateMONOLIXproject 	- Create Monolix project (includes structural
+%                                 model creation) 
+% SBPOPrunMONOLIXproject    	- Runs specified Monolix project
+% SBPOPrunMONOLIXprojectFolder  - Runs all Monolix projects within a folder
+% SBPOPsampleMONOLIXparam   	- Samples population and individual parameters
+%                           	  from a Monolix fitting result. The resulting
+%                           	  population and individual parameters can be
+%                           	  used for model simulations
+% SBPOPgetMonolixdataHeader     - Determines the data header for MONOLIX project generation
+% isMONOLIXfitSBPOP         	- Checks if a NLME project is a Monolix one
+% parseMONOLIXetasSBPOP     	- Parses the ETAs from a Monolix project
+% parseMONOLIXpredictionsSBPOP  - Parses the predictions from a Monolix project
+% parseMONOLIXindivparamSBPOP   - Parses the individual param from a Monolix project
+%
+% NONMEM related functions
+% ========================
+% SBPOPcreateNONMEMproject		- Creates a NONMEM project
+% SBPOPrunNONMEMproject 		- Runs a NONMEM project
+% SBPOPrunNONMEMprojectFolder   - Runs all NONMEM projects within a folder
+% SBPOPreportNONMEMresults 		- Reports the results of a NONMEM run
+% SBPOPplotConvergenceNONMEM 	- Plots the convergence trajectories
+% SBPOPsampleNONMEMparam 		- Samples model parameters from a NONMEM project
+% SBPOPgetNONMEMdataHeader 		- Determines the data header for NONMEM project generation
+% isNONMEMfitSBPOP 				- Checks if a NLME project is a NONMEM one
+% parseNONMEMetasSBPOP 			- Parses the ETAs from a NONMEM project
+% parseNONMEMpredictionsSBPOP   - Parses the predictions from a NONMEM project
+% parseNONMEMindivparamSBPOP    - Parses the individual param from a NONMEM project
+%
+% General NLME (MONOLIX and NONMEM) related functions
+% ===================================================
+% SBPOPsampleNLMEfitParam 		- Sample parameters from NLME (MONOLIX or NONMEM fit)
+% SBPOPcreateNLMEproject		- Creates an NLME (NONMEM or MONOLIX) project
+% SBPOPrunNONMEMprojectFolder   - Runs all NLME (NONMEM or MONOLIX) projects within a folder
+% getCovariateInformationSBPOP  - Get covariate information from a NLME project
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% AUXILIARY FUNCTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+% Figure export tools
+% ===================
+% printFigureSBPOP          - Exports MATLAB figures as JPG, PNG, or PS
+%                             files. For PS files it appends them in same
+%                             file. 
+% startNewPrintFigureSBPOP  - Removes PS file (windows) or PDF file (unix)
+%                             if it exists (so new figures are not
+%                             appended)  
+% convert2pdfSBPOP          - Converts PS to PDF files on unix/linux
+%
+% Other
+% =====
+% getcolorsSBPOP 			- Function returns color settings and
+%                             linestyles, etc. Useful for plots to be able
+%                             to use better colors than the MATLAB default
+% usernameSBPOP             - Get the name of the current user
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% TASKS 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+% Please note that the functions in the "tasks" folder within SBPOP assume
+% a standard dataset format. Nothing really exciting but some standard is
+% needed in order to simplify things.
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% TASKS - popPKtoolbox
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SBPOPcreatePopPKproject   - Set-up of a popPK workflow, automatically
+%                             creating documented template scripts that can
+%                             be used 
+% SBPOPexplorePopPKdata     - Creates a wide range of data exploration
+%                             plots specific for popPK analyses
+% SBPOPcleanPopPKdata       - Supports simple data cleaning specific for
+%                             popPK analyses
+% SBPOPconvert2popPKdataset - Convert dataset to popPK dataset. Removing
+%                             placebo patients, keeping only certain
+%                             columns, keeping only dose and PK in the
+%                             dataset
+% SBPOPbuildPopPKModelSpace - Function allowing to generate a PK model
+%                             subspace, running all the estimations,
+%                             generating tables for comparison of models,
+%                             and generating a wide range of fit analysis
+%                             plots. For current limitations of possible
+%                             models, please look at the help text to this
+%                             function
+% SBPOPcomparePopPKmodels   - Compares popPK model fits
+% SBPOPcreatePopPKstratifiedVPC - Allows to generate a stratified VPC with 
+% 								  even less input arguments, but limited to
+% 							      popPK models built with the popPKPD toolbox 
+% 								  in SBPOP
+% SBPOPscmPopPK 			- Stepwise covariate search (forward inclusion,
+% 						      backward elimination) for popPK modeling 
+% 							  workflow			
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% TASKS - popPDtoolbox
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SBPOPexplorePopPDdata     				- Creates a wide range of data exploration
+%                             				  plots specific for popPD analyses
+% SBPOPcleanPopPDdata       				- Supports simple data cleaning specific for
+%                             				  popPD analyses
+% SBPOPgraphicalExplorationContinuousPD		- Additional exploration of continuous PD data
+% SBPOPgraphicalExplorationResponderRatePD  - Exploration of categorical PD data
+% SBPOPconvert2popPDparametersDataset       - Convert dataset to popPD dataset, including individual 
+%                                             PK parameters for simulation of the PK
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% TASKS - General
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SBPOPcheckGeneralDataFormat 	 		- Checks if data in the general dataset format
+% SBPOPconvertGeneralDataFormat         - Converts the general dataset format into an
+% 										  augmented one 
+% SBPOPcheckDataFormat      			- Checking the data format and reporting problems
+% SBPOPexploreCovariateCorrelations     - Plots correlation information for covariates
+% SBPOPexploreIndivData     			- This function allows to plot individual data
+%                                     	  from a standardized PKPD dataset
+% SBPOPexploreSummaryStats  			- This function produces summary statistics for
+%                                     	  the provided dataset 
+% SBPOPcleanImputeCovariates        	- Covariate imputation 
+% SBPOPcleanRemoveFewObsSubjects    	- Removal of subjects with not more than Nobs observations
+% SBPOPcleanRemovePlaceboSubjects   	- Removal of placebo subjects
+% SBPOPcleanRemoveRecordsSUBJECTs   	- Removal of user defined subjects and records
+% SBPOPhandleSameTimeObservationRecords - Auxiliary for VPC generation
+% SBPOPfitanalysisETAvsCOV          	- Plots the individual variations over
+%                                         covariates and categorical covariates
+% SBPOPfitanalysisGOFplots          	- Produces several plots that can be
+%                                         used for checking the goodness of fit
+% SBPOPfitanalysisIndividualFits    	- Plots individual fits and population
+%                                         prediction against observed data over
+%                                         time 
+% SBPOPfitanalysisOutlierDetection  	- Considers PWRES and searches for
+%                                         outliers and displays info about them
+% SBPOPfitanalysisRandomEffects     	- Plots information about the random
+%                                         effects in different ways
+% SBPOPfitanalysisProjectsFolderPlots 	- Creates fit analysis plots for all 
+%                                         Monolix/NONMEM project folders in specified
+% 										  folder. The underlying models do not 
+% 										  need to contain the same parameters
+% SBPOPfitanalysisProjectsFolderInfo  	- Creates model comparison tables for all 
+%                                         Monolix/NONMEM project folders in specified
+% 										  folder. The underlying models do not 
+% 										  need to contain the same parameters
+% SBPOPfitanalysisGeneralPlots  	 	- Plots fit analysis plots for a single specified 
+% 								  	      Monolix/NONMEM project folder 
+% SBPOPcovariateChangeAssessment    	- Assesses the changes that a
+%                                     	  covariates introduces on the model
+%                                         parameters, based on the contents of
+%                                     	  the dataset (no uncertainty)
+% SBPOPcovariateAssessmentUncertainty   - Assesses the changes that a
+%                                     	  covariates introduces on the model
+%                                     	  parameters, based on the contents of
+%                                     	  the dataset (with uncertainty) 
+% SBPOPcompareModels 					- This function allows to compare the same 
+%							   	  		  structural model for different estimation 
+%							   	  		  results from Monolix/NONMEM. 
+% SBPOPassessInformationContent 		- This function allows to predict the 
+% 							      	  	  information content in data of (a) future 
+% 								  		  studies, given the planned dosing and 
+% 								  		  observation schedule
+% SBPOPcreateVPC 						- Generation and plotting of simple VPC
+% SBPOPcreateStratifiedVPC      		- Allows to generate a stratified VPC
+% SBPOPbootstrap 						- Runs a bootstrap analysis on a defined 
+% 										  NLME project
+% SBPOPscm 								- Stepwise covariate search (forward inclusion,
+%			 						      backward elimination) for general models
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% TASKS - mPDtoolbox
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SBPOPcreateDatasetMedianOptimization	- Generate a dataset for the median modeling, based on 
+% 										  the standard SBPOP dataset
+% SBPOPrunMEDIANoptimization 			- Run the median modeling to fit median responses or
+% 									      responder rates
+% getMedianModelingDataStructSBPOP 		- Auxiliary function to generate data structure for fitting
+% 										  based on median modeling dataset
+% SBPOPcreateAllFitAssessmentsMedian    - Generate all fit assessments for a median modeling 
+% 										  project (already done by SBPOPrunMEDIANoptimization)
+%										  This function calls the following function below:
+% SBPOPassessConvergenceMedian          - Plots convergence information for median modeling runs
+% SBPOPcontributionTRTcostMedian        - Displays the relative contribution of TRT groups to cost function
+% SBPOPbootstrapFitsMedian              - Displays DV vs. PRED plots for all bootstraps
+% SBPOPuncertaintyDistributionMedian    - Displays estimated parameter distribution and values
+% SBPOPvpcMedianBootstrapParam          - Generates a VPC based on the bootstrap estimates
+% SBPOPvpcMedianSampledParam            - Generates a VPC based on sampling from the estimated 
+% 										  parameter distribution
+% SBPOPsimulationMedianBootstrapParam   - Simulate a defined median model using the bootstrap parameter estimates
+% SBPOPsimulationMedianSampledParam     - Simulate a defined median model using sampled parameters
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% TASKS - EBtoolbox
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% standard_Drug_LigandTarget_model.txtbc  - Standard mAb model
+% SBPOPtissuedata                         - Literature data on tissue and
+%                                           interstitial volumes
+% SBPOPcreateDRUGligandTargetModel        - Copies the standard model in
+%                                           desired location
+% SBPOPoptimizeDRUGkinetics               - Estimate parameters of the standard 
+%                                           model to adjust the kinetics of a molecule
+% SBPOPoptimizeLigandTARGETkinetics       - Estimate parameters of the standard model 
+%                                           to adjust the kinetics of a target (ligand)
+% SBPOPoptimizeLigandTARGETsynthesis      - Estimate parameters of the standard model 
+%                                           to adjust the steady-state concentrations of a target
+% SBPOPplotDoseEffectCurve                - Plots a dose/effect curve for given input arguments
+% SBPOPplotDoseParamCurve                 - Plots a dose/parameter curve for given input arguments
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/SBPOPpublish.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/SBPOPpublish.m
new file mode 100644
index 0000000000000000000000000000000000000000..eac8b3a1f95af45a3242cf4b44c44c66edb14f49
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/SBPOPpublish.m
@@ -0,0 +1,110 @@
+function [] = SBPOPpublish(scriptname,outputpath)
+
+% scriptname  = 'SCRIPT_01_popPK';
+% outputpath  = './';
+
+outputname  = [scriptname '.html'];
+
+%% Publish script using MATLAB function
+options     = struct('format','html','outputDir',outputpath,'evalCode',false);
+publish(scriptname,options);
+try, movefile(fullfile(outputpath,[scriptname '.html']),fullfile(outputpath,outputname)); catch, end
+
+%% Postprocess
+content = fileread(fullfile(outputpath,outputname));
+
+% Remove the Source code
+ixstart = strfind(content,'##### SOURCE BEGIN #####');
+ixend   = strfind(content,'##### SOURCE END #####');
+content(ixstart-5:ixend+25) = [];
+content = strrep(content,'<p class="footer"><br><a href="http://www.mathworks.com/products/matlab/">Published with MATLAB&reg; R2013a</a><br></p>','');
+
+% Handle the Henning-Markup links
+while ~isempty(strfind(content,'#_#'))
+    ixLinks     = strfind(content,'#_#');
+    ixstart     = ixLinks(1);
+    ixend       = ixLinks(2)+2;
+    link        = content(ixstart:ixend);
+    link        = strrep(link,'#_#','');
+    linkterms   = explodePCSB(link,'|');
+    if length(linkterms) == 1,
+        link = linkterms{1};
+        name = linkterms{1};
+    elseif length(linkterms) == 2,
+        link = linkterms{2};
+        name = linkterms{1};
+    else
+        error('Wrong Link');
+    end
+    linkText    = ['<a href="' link '" target="newwindow">' name '</a>'];
+    content = [content(1:ixstart-1) linkText content(ixend+1:end)];
+end
+
+%% Handle Table of contents Henning markup
+
+% Get the contents table elements
+ixContentsStart         = strfind(content,'<h2>Contents</h2>')+22;
+ixUL                    = strfind(content,'</ul>');
+ixContentsEnd           = ixUL(find(ixUL-ixContentsStart>0)); ixContentsEnd = ixContentsEnd(1)+4;
+contentsTextOriginal    = content(ixContentsStart:ixContentsEnd);
+contentsTextReplace     = contentsTextOriginal;
+% Remove <ul> tags
+contentsTextOriginal    = strrep(contentsTextOriginal,'<ul>','');
+contentsTextOriginal    = strrep(contentsTextOriginal,'</ul>','');
+% Remove </li> tags
+contentsTextOriginal    = strrep(contentsTextOriginal,'</li>','');
+% Remove first <li> tag
+contentsTextOriginal    = contentsTextOriginal(5:end);
+% EXCHANGE <li> tags
+contentsTextOriginal    = strrep(contentsTextOriginal,'<li>','$');
+% Get contents items
+terms = explodePCSB(contentsTextOriginal,'$');
+% Piece them together again ... assume a === In the name means a main
+% section and not === means a subsection
+ix_main = [];
+for k=1:length(terms),
+    if ~isempty(strfind(terms{k},'===')),
+        ix_main = [ix_main k];
+    end
+end
+if isempty(ix_main),
+    error('At least one main section needs to be available.');
+end
+if ix_main(1)~=1,
+    error('The first section needs to be a main section.');
+end
+ix_sub = {};
+for k=2:length(ix_main),
+    ix_maincurrent  = ix_main(k);
+    ix_mainprevious = ix_main(k-1);
+    ix_subk = [ix_mainprevious+1:1:ix_maincurrent-1];
+    ix_sub{k-1} = ix_subk;
+end
+ix_sub{end+1} = ix_main(end)+1:1:length(terms);
+text = sprintf('<ul>\n');
+for k=1:length(ix_main),
+    text = sprintf('%s    <li>',text);
+    text = sprintf('%s<b>%s</b>\n',text,strtrim(strrep(upper(terms{ix_main(k)}),'===','')));
+    if ~isempty(ix_sub{k}),
+        text = sprintf('%s        <ul>\n',text);
+        for k2=1:length(ix_sub{k}),
+            text = sprintf('%s            <li>',text);
+            text = sprintf('%s%s',text,strtrim(strrep(terms{ix_sub{k}(k2)},'===','')));
+            text = sprintf('%s</li>\n',text);
+        end
+        text = sprintf('%s        </ul>\n',text);
+    end
+    text = sprintf('%s    </li>\n',text);
+end
+text = sprintf('%s</ul>\n',text);
+content = strrep(content,contentsTextReplace,text);
+content = strrep(content,'<h2>===','<h2>');
+
+% Save post-processed result
+fid = fopen(fullfile(outputpath,outputname),'w');
+fprintf(fid,'%s',content);
+fclose(fid);
+
+% %% Open result
+% oldpath = pwd(); cd(outputpath); path = pwd; cd(oldpath)
+% system(sprintf('"C:\\Program Files\\Internet Explorer\\iexplore" %s',fullfile(path,outputname)))
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/export_figures_to_files/convert2pdfSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/export_figures_to_files/convert2pdfSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..2b5e1d69381edb1f18d79ee42e606f5aa18f7fab
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/export_figures_to_files/convert2pdfSBPOP.m
@@ -0,0 +1,57 @@
+function [] = convert2pdfSBPOP(filename)
+% [DESCRIPTION]
+% Function converting a PS file to a PDF file.
+% Now just a wrapper for ps2pdfSB to allow the definition of just one
+% filename.
+%
+% [SYNTAX]
+% [] = convert2pdfSBPOP(filename)
+%
+% [INPUT]
+% filename:     filename to be used
+% 
+% [OUTPUT]
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 16th May 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MATLAB R2009a, MATLAB
+%
+% [KEYWORDS]
+% MATLAB, SBPOP, median, averaging plot
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+% Remove extension from filename
+filename = strrep(filename,'.ps','');
+
+ps2pdfSB([filename '.ps'],[filename '.pdf']);
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/export_figures_to_files/printFigureSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/export_figures_to_files/printFigureSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..d8d73cd5f44b54c871c953d482ae728007f5794f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/export_figures_to_files/printFigureSBPOP.m
@@ -0,0 +1,114 @@
+function [] = printFigureSBPOP(hfig, filename, varargin)
+% [DESCRIPTION]
+% Print figure "hfig" to file "filename". Supported formats: png, ps, jpg.
+% PS is default. Several figures can be appended in the same file by using 
+% format='ps'. Just run the function repeatedly with same filename.
+% If format='png' or 'jpg', figures are not appended, but overwritten.
+%
+% Tips when using PS files:
+%   1) If you want a PDF you need to generate it afterwards using the function: 
+%             convert2pdfSBPOP (on Unix/Linux).
+%   2) Dont use the PS format if you have transparency in your plots!
+%   3) If you want to start a new file then remove the file first (by default 
+%      plots are appended in PS mode). Files can be removed by: 
+%             startNewPrintFigureSBPOP
+%
+% This function also adds a time stamp to the figure
+%
+% [SYNTAX]
+% [] = printFigureSBPOP(hfig, filename)
+% [] = printFigureSBPOP(hfig, filename, format)
+%
+% [INPUT]
+% hfig:         handle of figure to be printed
+% filename:     filename to be used 
+% format:       'ps', 'png', 'jpg' (default: 'ps')
+% 
+% [OUTPUT]
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 16th May 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MATLAB R2009a, MATLAB
+%
+% [KEYWORDS]
+% MATLAB, SBPOP, median, averaging plot
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+ 
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+% The adding of the creation date does not work when running things in
+% parallel :( ... e.g. GoF plots in a parfor loop.
+
+% % Add creation date
+% date_created    = ['Figure created: ' datestr(now,'dd-mmm-yyyy HH:MM:SS')];
+% h               = uicontrol('style','text');
+% set(h,'String',date_created);
+% set(h,'Units','normalized')
+% set(h,'FontUnits','pixels')
+% set(h,'FontSize',10)
+% set(h,'Position',[0,0,1,0.04])
+% set(h,'BackgroundColor',[1 1 1])
+
+% Do the rest
+imgformat   = 'psc2';
+if nargin == 3,
+    format = varargin{1};
+    if strcmp(format,'ps'),
+        imgformat   = 'psc2';
+    elseif strcmp(format,'png'),
+        imgformat   = 'png';        
+    elseif strcmp(format,'jpg'),
+        imgformat   = 'jpeg95';    
+    elseif strcmp(format,'pdf'),
+        imgformat   = 'pdf';    
+    else
+        error('Unknown image format');
+    end
+end
+        
+% Always PS-color
+% Setting figure properties for printing
+if strcmp(imgformat,'png'),
+    set(hfig,'PaperOrientation','portrait');
+else
+    set(hfig,'PaperOrientation','landscape');
+end    
+set(hfig,'PaperType','A4');
+set(hfig,'PaperPositionMode', 'manual');
+set(hfig,'PaperUnits', 'centimeters');
+set(hfig,'PaperPosition', [0 0 29.7 21]);
+
+% Print
+[path,file,ext] = fileparts(filename);
+oldPath = pwd;
+if ~isempty(path), cd(path); end
+print(hfig,['-d',imgformat],file,'-append');
+cd(oldPath);
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/export_figures_to_files/startNewPrintFigureSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/export_figures_to_files/startNewPrintFigureSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..710f0ff68dd1c77ff042376c381d4fe604aacf09
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/export_figures_to_files/startNewPrintFigureSBPOP.m
@@ -0,0 +1,84 @@
+function [] = startNewPrintFigureSBPOP(filename)
+% [DESCRIPTION]
+% Function starts a new file in which figures are to be printed.
+% Basically this means, that it is checked if the file exists and if yes it is deleted.
+% The function "printFigureSBPOP" can then be used to print a figure into this file.
+% The function "convert2pdfSBPOP" can then be used to convert from PS to PDF (only unix).
+% On Unix check is done for .PDF, on windows for .PS
+%
+% [SYNTAX]
+% [] = startNewPrintFigureSBPOP(filename)
+%
+% [INPUT]
+% filename:     filename to be used
+% 
+% [OUTPUT]
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 16th May 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MATLAB R2009a, MATLAB
+%
+% [KEYWORDS]
+% MATLAB, SBPOP, median, averaging plot
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+ 
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create folder if it is not existing
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+folder = fileparts(filename);
+if ~isempty(folder),
+    warning off
+    mkdir(folder);
+    warning on
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% If filename exists then delete it
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(filename),
+    [path,file,ext] = fileparts(filename);
+    filename_pdf = fullfile(path,[file '.pdf']);
+    filename_ps  = fullfile(path,[file '.ps']);
+
+    warning off;
+    try
+        delete(filename_pdf);
+    catch
+    end
+    
+    try
+        delete(filename_ps);
+    catch
+    end
+    warning on;
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/graphics/getcolorsSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/graphics/getcolorsSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..ab490a011bc93ff6e21289ab68328b3fa37813b6
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/graphics/getcolorsSBPOP.m
@@ -0,0 +1,131 @@
+function [colors,lines,dots,bwcolors] = getcolorsSBPOP()
+% [DESCRIPTION]
+% Help function to generate colors for plotting and for black and white
+% plotting also line types.
+%
+% [SYNTAX]
+% [colors,lines,dots,bwcolors] = getcolorsSBPOP()
+%
+% [INPUT]
+% NONE
+%
+% [OUTPUT]
+% colors: Nx3 matrix with colors to be used (see below in detail)
+% lines:  cell-array with 48 unique line-styles
+% dots:   cell-array with 12 unique dot-styles
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 15th April 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MATLAB R2009a, MATLAB
+%
+% [KEYWORDS]
+% MATLAB, SBPOP, DV, PRED, IPRED, diagnostic, plot, DV vs PRED, DV vs IPRED
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+colors = [
+    0         0.4470    0.7410
+    0.8500    0.3250    0.0980
+    0.9290    0.6940    0.1250
+    0.4940    0.1840    0.5560
+    0.4660    0.6740    0.1880
+    0.3010    0.7450    0.9330
+    0.6350    0.0780    0.1840
+         0    0.2980    0.4940
+    0.5667    0.2167    0.0653
+    0.6193    0.4627    0.0833
+    0.3293    0.1227    0.3707
+    0.3107    0.4493    0.1253
+    0.2007    0.4967    0.6220
+    0.4233    0.0520    0.1227
+    0.25 0.25 0.25
+    0.6 0.2 0
+    0.75 0.75 0
+    0 0.75 0.75
+    0 0.5 0
+    0 0 1
+    0.75 0 0.75
+    1 0 0
+    0.04 0.14 0.42
+    0.31 0.31 0.31
+    0.5 0.5 0.5
+    0 0 0
+    1 0.69 0.39
+    0 1 0
+    0 1 1
+    1 0 1
+    0.7 0.78 1
+    1 1 0
+    0.68 0.92 1
+    0.85 0.7 1
+    1 0.6 0.78
+    ];
+
+
+
+
+% colors = [0.87 0.49 0
+%            0.17 0.51 0.34
+% 		   0.08 0.16 0.55
+% 		   0.48 0.06 0.89
+% 		   0.85 0.16 0
+% 		   0.68 0.47 0
+% 		   0.04 0.52 0.78
+% 		   0.25 0.25 0.25 
+% 		   0.6 0.2 0
+% 		   0.75 0.75 0
+% 		   0 0.75 0.75
+% 		   0 0.5 0
+% 		   0 0 1
+% 		   0.75 0 0.75
+% 		   1 0 0
+% 		   0.04 0.14 0.42
+% 		   0.31 0.31 0.31
+% 		   0.5 0.5 0.5
+% 		   0 0 0
+% 		   1 0.69 0.39
+% 		   0 1 0
+% 		   0 1 1
+% 		   1 0 1
+% 		   0.7 0.78 1
+% 		   1 1 0
+% 		   0.68 0.92 1
+% 		   0.85 0.7 1
+% 		   1 0.6 0.78];
+      
+lines = {'o-','x-','+-','*-','s-','d-','v-','^-','<-','>-','p-','h-',       'o--','x--','+--','*--','s--','d--','v--','^--','<--','>--','p--','h--',     'o-.','x-.','+-.','*-.','s-.','d-.','v-.','^-.','<-.','>-.','p-.','h-.',   'o:','x:','+:','*:','s:','d:','v:','^:','<:','>:','p:','h:'   };
+      
+dots = {'o','x','+','*','s','d','v','^','<','>','p','h'};      
+
+bwcolors = [0 0 0; 0.33 0.33 0.33; 0.66 0.66 0.66];
+      
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/graphics/subaxis/parseArgs.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/graphics/subaxis/parseArgs.m
new file mode 100644
index 0000000000000000000000000000000000000000..9bf5efa099dd3a7e501711cabcc43e9d235a8125
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/graphics/subaxis/parseArgs.m
@@ -0,0 +1,126 @@
+function ArgStruct=parseArgs(args,ArgStruct,varargin)
+% Helper function for parsing varargin. 
+%
+%
+% ArgStruct=parseArgs(varargin,ArgStruct[,FlagtypeParams[,Aliases]])
+%
+% * ArgStruct is the structure full of named arguments with default values.
+% * Flagtype params is params that don't require a value. (the value will be set to 1 if it is present)
+% * Aliases can be used to map one argument-name to several argstruct fields
+%
+%
+% example usage: 
+% --------------
+% function parseargtest(varargin)
+%
+% %define the acceptable named arguments and assign default values
+% Args=struct('Holdaxis',0, ...
+%        'SpacingVertical',0.05,'SpacingHorizontal',0.05, ...
+%        'PaddingLeft',0,'PaddingRight',0,'PaddingTop',0,'PaddingBottom',0, ...
+%        'MarginLeft',.1,'MarginRight',.1,'MarginTop',.1,'MarginBottom',.1, ...
+%        'rows',[],'cols',[]); 
+%
+% %The capital letters define abrreviations.  
+% %  Eg. parseargtest('spacingvertical',0) is equivalent to  parseargtest('sv',0) 
+%
+% Args=parseArgs(varargin,Args, ... % fill the arg-struct with values entered by the user
+%           {'Holdaxis'}, ... %this argument has no value (flag-type)
+%           {'Spacing' {'sh','sv'}; 'Padding' {'pl','pr','pt','pb'}; 'Margin' {'ml','mr','mt','mb'}});
+%
+% disp(Args)
+%
+%
+%
+%
+% % Aslak Grinsted 2003
+
+Aliases={};
+FlagTypeParams='';
+
+if (length(varargin)>0) 
+    FlagTypeParams=strvcat(varargin{1});
+    if length(varargin)>1
+        Aliases=varargin{2};
+    end
+end
+ 
+
+%---------------Get "numeric" arguments
+NumArgCount=1;
+while (NumArgCount<=size(args,2))&(~ischar(args{NumArgCount}))
+    NumArgCount=NumArgCount+1;
+end
+NumArgCount=NumArgCount-1;
+if (NumArgCount>0)
+    ArgStruct.NumericArguments={args{1:NumArgCount}};
+else
+    ArgStruct.NumericArguments={};
+end 
+
+
+%--------------Make an accepted fieldname matrix (case insensitive)
+Fnames=fieldnames(ArgStruct);
+for i=1:length(Fnames)
+    name=lower(Fnames{i,1});
+    Fnames{i,2}=name; %col2=lower
+    AbbrevIdx=find(Fnames{i,1}~=name);
+    Fnames{i,3}=[name(AbbrevIdx) ' ']; %col3=abreviation letters (those that are uppercase in the ArgStruct) e.g. SpacingHoriz->sh
+    %the space prevents strvcat from removing empty lines
+    Fnames{i,4}=isempty(strmatchSB(Fnames{i,2},FlagTypeParams)); %Does this parameter have a value? (e.g. not flagtype)
+end
+FnamesFull=strvcat(Fnames{:,2});
+FnamesAbbr=strvcat(Fnames{:,3});
+
+if length(Aliases)>0  
+    for i=1:length(Aliases)
+        name=lower(Aliases{i,1});
+        FieldIdx=strmatchSB(name,FnamesAbbr,'exact'); %try abbreviations (must be exact)
+        if isempty(FieldIdx) 
+            FieldIdx=strmatchSB(name,FnamesFull); %&??????? exact or not? 
+        end
+        Aliases{i,2}=FieldIdx;
+        AbbrevIdx=find(Aliases{i,1}~=name);
+        Aliases{i,3}=[name(AbbrevIdx) ' ']; %the space prevents strvcat from removing empty lines
+        Aliases{i,1}=name; %dont need the name in uppercase anymore for aliases
+    end
+    %Append aliases to the end of FnamesFull and FnamesAbbr
+    FnamesFull=strvcat(FnamesFull,strvcat(Aliases{:,1})); 
+    FnamesAbbr=strvcat(FnamesAbbr,strvcat(Aliases{:,3}));
+end
+
+%--------------get parameters--------------------
+l=NumArgCount+1; 
+while (l<=length(args))
+    a=args{l};
+    if ischar(a)
+        paramHasValue=1; % assume that the parameter has is of type 'param',value
+        a=lower(a);
+        FieldIdx=strmatchSB(a,FnamesAbbr,'exact'); %try abbreviations (must be exact)
+        if isempty(FieldIdx) 
+            FieldIdx=strmatchSB(a,FnamesFull); 
+        end
+        if (length(FieldIdx)>1) %shortest fieldname should win 
+            [mx,mxi]=max(sum(FnamesFull(FieldIdx,:)==' ',2));
+            FieldIdx=FieldIdx(mxi);
+        end
+        if FieldIdx>length(Fnames) %then it's an alias type.
+            FieldIdx=Aliases{FieldIdx-length(Fnames),2}; 
+        end
+        
+        if isempty(FieldIdx) 
+            error(['Unknown named parameter: ' a])
+        end
+        for curField=FieldIdx' %if it is an alias it could be more than one.
+            if (Fnames{curField,4})
+                val=args{l+1};
+            else
+                val=1; %parameter is of flag type and is set (1=true)....
+            end
+            ArgStruct.(Fnames{curField,1})=val;
+        end
+        l=l+1+Fnames{FieldIdx(1),4}; %if a wildcard matches more than one
+    else
+        error(['Expected a named parameter: ' num2str(a)])
+    end
+end
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/graphics/subaxis/subaxis.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/graphics/subaxis/subaxis.m
new file mode 100644
index 0000000000000000000000000000000000000000..34b4cf4eea64c88860b438c705102853be2fd281
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/graphics/subaxis/subaxis.m
@@ -0,0 +1,100 @@
+function h=subaxis(varargin)
+%SUBAXIS Create axes in tiled positions. (just like subplot)
+%   Usage:
+%      h=subaxis(rows,cols,cellno[,settings])
+%      h=subaxis(rows,cols,cellx,celly[,settings])
+%      h=subaxis(rows,cols,cellx,celly,spanx,spany[,settings])
+%
+% SETTINGS: Spacing,SpacingHoriz,SpacingVert
+%           Padding,PaddingRight,PaddingLeft,PaddingTop,PaddingBottom
+%           Margin,MarginRight,MarginLeft,MarginTop,MarginBottom
+%           Holdaxis
+%
+%           all units are relative (e.g from 0 to 1)
+%
+%           Abbreviations of parameters can be used.. (Eg MR instead of MarginRight)
+%           (holdaxis means that it wont delete any axes below.)
+%
+%
+% Example:
+%
+%   >> subaxis(2,1,1,'SpacingVert',0,'MR',0); 
+%   >> imagesc(magic(3))
+%   >> subaxis(2,'p',.02);
+%   >> imagesc(magic(4))
+%
+% 2001 / Aslak Grinsted  (Feel free to modify this code.)
+f=gcf;
+
+
+Args=[];
+UserDataArgsOK=0;
+Args=get(f,'UserData');
+if isstruct(Args) 
+    UserDataArgsOK=isfield(Args,'SpacingHorizontal')&isfield(Args,'Holdaxis')&isfield(Args,'rows')&isfield(Args,'cols');
+end
+OKToStoreArgs=isempty(Args)|UserDataArgsOK;
+
+if isempty(Args)&(~UserDataArgsOK)
+    Args=struct('Holdaxis',0, ...
+        'SpacingVertical',0.05,'SpacingHorizontal',0.05, ...
+        'PaddingLeft',0,'PaddingRight',0,'PaddingTop',0,'PaddingBottom',0, ...
+        'MarginLeft',.1,'MarginRight',.1,'MarginTop',.1,'MarginBottom',.1, ...
+        'rows',[],'cols',[]); 
+end
+Args=parseArgs(varargin,Args,{'Holdaxis'},{'Spacing' {'sh','sv'}; 'Padding' {'pl','pr','pt','pb'}; 'Margin' {'ml','mr','mt','mb'}});
+
+if (length(Args.NumericArguments)>1)
+    Args.rows=Args.NumericArguments{1};
+    Args.cols=Args.NumericArguments{2};
+%remove these 2 numerical arguments
+    Args.NumericArguments={Args.NumericArguments{3:end}};
+end
+
+if OKToStoreArgs
+    set(f,'UserData',Args);
+end
+
+
+    
+
+switch length(Args.NumericArguments)
+   case 0
+       return % no arguments but rows/cols.... 
+   case 1
+      x1=mod((Args.NumericArguments{1}-1),Args.cols)+1; x2=x1;
+      y1=floor((Args.NumericArguments{1}-1)/Args.cols)+1; y2=y1;
+   case 2
+      x1=Args.NumericArguments{1};x2=x1;
+      y1=Args.NumericArguments{2};y2=y1;
+   case 4
+      x1=Args.NumericArguments{1};x2=x1+Args.NumericArguments{3}-1;
+      y1=Args.NumericArguments{2};y2=y1+Args.NumericArguments{4}-1;
+   otherwise
+      error('subaxis argument error')
+end
+    
+
+cellwidth=((1-Args.MarginLeft-Args.MarginRight)-(Args.cols-1)*Args.SpacingHorizontal)/Args.cols;
+cellheight=((1-Args.MarginTop-Args.MarginBottom)-(Args.rows-1)*Args.SpacingVertical)/Args.rows;
+xpos1=Args.MarginLeft+Args.PaddingLeft+cellwidth*(x1-1)+Args.SpacingHorizontal*(x1-1);
+xpos2=Args.MarginLeft-Args.PaddingRight+cellwidth*x2+Args.SpacingHorizontal*(x2-1);
+ypos1=Args.MarginTop+Args.PaddingTop+cellheight*(y1-1)+Args.SpacingVertical*(y1-1);
+ypos2=Args.MarginTop-Args.PaddingBottom+cellheight*y2+Args.SpacingVertical*(y2-1);
+
+if Args.Holdaxis
+    h=axes('position',[xpos1 1-ypos2 xpos2-xpos1 ypos2-ypos1]);
+else
+    h=subplot('position',[xpos1 1-ypos2 xpos2-xpos1 ypos2-ypos1]);
+end
+
+
+set(h,'box','on');
+%h=axes('position',[x1 1-y2 x2-x1 y2-y1]);
+set(h,'units',get(gcf,'defaultaxesunits'));
+set(h,'tag','subaxis');
+
+
+
+if (nargout==0) clear h; end;
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/other/cellmaxlengthSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/other/cellmaxlengthSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..edf0dd2526373817e64034f58c8f7804f88e5a32
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/other/cellmaxlengthSBPOP.m
@@ -0,0 +1,34 @@
+function [maxlength] = cellmaxlengthSBPOP(input)
+% cellmaxlengthSBPOP: for a cell-array with only string entries the function
+% determines the maxlength of these strings.
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+if ~iscell(input),
+    error('Input is not a cell-array.');
+end
+
+maxlength = 0;
+for k=1:length(input),
+    if ~ischar(input{k}),
+        error('Elements of cell-array need to be strings.');
+    end
+    if length(input{k}) > maxlength,
+        maxlength = length(input{k});
+    end
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/other/getNLMEtoolInfoSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/other/getNLMEtoolInfoSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..a2b343019acc6b0a90d8eebd04d84e44a204a1f2
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/other/getNLMEtoolInfoSBPOP.m
@@ -0,0 +1,18 @@
+function [PATH_MONOLIX,PATH_NONMEM,PATH_NONMEM_PAR,PATH_SAS] = getNLMEtoolInfoSBPOP()
+% Function loads and returns the content of SETUP_NLME_TOOLS already
+% correct for the system. 
+
+% Run the SETUP_NLME_TOOLS script
+SETUP_PATHS_TOOLS
+
+if isunix,
+    PATH_MONOLIX    = PATH_SYSTEM_MONOLIX_UNIX;
+    PATH_NONMEM     = PATH_SYSTEM_NONMEM_UNIX;
+    PATH_NONMEM_PAR = PATH_SYSTEM_NONMEM_PARALLEL_UNIX;
+    PATH_SAS        = PATH_SYSTEM_SAS_UNIX;
+else
+    PATH_MONOLIX    = PATH_SYSTEM_MONOLIX_WINDOWS;
+    PATH_NONMEM     = PATH_SYSTEM_NONMEM_WINDOWS;
+    PATH_NONMEM_PAR = PATH_SYSTEM_NONMEM_PARALLEL_WINDOWS;
+    PATH_SAS        = PATH_SYSTEM_SAS_WINDOWS;
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/other/lookforSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/other/lookforSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..0056cb61f2ff42c3e35e37e5056138bb332048c0
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/other/lookforSBPOP.m
@@ -0,0 +1,54 @@
+function [] = lookforSBPOP(text)
+% lookforSBPOP: searches all m-files in the SBPOP folder tree for the 
+% text given as argument. It displays the filenames in which the text
+% appears and additionally opens the files in the editor.
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+old = pwd;
+cd([fileparts(which('installSBPOP')) '/..']);
+recurseFolder('SBPOP',text);
+cd(old);
+return
+
+
+function recurseFolder(folder,text)
+% change folder
+cd(folder);
+% check all m files in folder for the text
+mfiles = dir('*.m');
+for k = 1:length(mfiles),
+    % read file
+    content = fileread(mfiles(k).name);
+    if strfind(content,text),
+        disp(mfiles(k).name);
+        edit(mfiles(k).name);
+    else
+%        edit(mfiles(k).name);
+    end
+end
+% recurse in all subfolders
+allfiles = dir;
+for k = 1:length(allfiles),
+    if ~strcmp(allfiles(k).name,'.git') && ~strcmp(allfiles(k).name,'..') && ~strcmp(allfiles(k).name,'.') && allfiles(k).isdir == 1,
+        recurseFolder(allfiles(k).name,text);
+    end
+end
+% up we go
+cd ..
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/other/setseedSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/other/setseedSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..6ef4fb42d0f91e26e435147fbf689ec1205cbcc3
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/other/setseedSBPOP.m
@@ -0,0 +1,75 @@
+function [] = setseedSBPOP(defaultSeed)
+% [DESCRIPTION]
+% Set the default stream to defaultSeed. 
+% In versions of MATLAB prior to 7.7, the control of the internal state of
+% the random number stream used by rand is done by calling rand and randn
+% directly with the 'seed'.
+% For posterior version, the default stream is set by using RandStream
+%
+% [SYNTAX]
+% [] = setseedSBPOP(defaultSeed)
+%
+% [INPUT]
+% defaultSeed:   integer between 0 and 2^32.
+%
+% [OUTPUT]
+%
+% [ASSUMPTIONS]
+% 
+% [AUTHOR]
+% SBPOP package 
+% Copyright 2009 Novartis AG
+% Author: Bruno Bieth (bruno.bieth@novartis.com)
+% Created: 2009-12-03
+%
+% [DATE]
+%
+% [PLATFORM]
+% Windows XP Engine, MATLAB R2007a, MATLAB R2009a
+%
+% [KEYWORDS]
+% seed, seed generation, default seed
+% 
+% [TOOLBOXES USED]
+%
+% [EXAMPLES]
+%
+% [VERIFIED BY]
+% NOT YET
+
+% Information:
+% ============
+% Copyright © 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check that seed is an integer between 0 and 2^32
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if (mod(defaultSeed,1)~=0) || defaultSeed<0 || defaultSeed>2^32,
+    error('Seed must be an integer between 0 and 2^32');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get the version release
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+v=version('-release');
+
+if str2num(v(1:3)) <7.7,
+    randn('seed',seed);
+    rand('seed',seed);
+else
+    s=RandStream.create('mrg32k3a','Seed',defaultSeed);
+    RandStream.setGlobalStream(s);
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/other/usernameSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/other/usernameSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..1908ff95b63e1175fad16620d97d6644ded026f6
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/other/usernameSBPOP.m
@@ -0,0 +1,26 @@
+function [username] = usernameSBPOP(text)
+% usernameSBPOP: Get the name of the current user
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+if ispc,
+    username = getenv('UserName');
+else
+    username = getenv('USER');
+end
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/templates/functionTemplateSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/templates/functionTemplateSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..23072e551cb7bbc4bb2b1d1f1afcc76743443068
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/templates/functionTemplateSBPOP.m
@@ -0,0 +1,53 @@
+function [ output_args ] = functionTemplateSBPOP( input_args )
+% [DESCRIPTION]
+% In this section the purpose of the function should be described.
+% Additionally, the different possible syntaxes. 
+%
+% [SYNTAX]
+% Here you can show how the function can be called
+%
+% [INPUT]
+% Define the input arguments or other inputs (e.g. required files, etc.)
+% Please do NOT use hardcoded data in MATLAB functions.
+%
+% [OUTPUT]
+% Define the output arguments or other outputs (e.g. produced log files,
+% figures, etc.) 
+%
+% [ASSUMPTIONS]
+% Here you can add any additional background information about assumptions.
+%
+% [AUTHOR]
+% Original author, ideally with email address
+%
+% [DATE]
+% Date of first creation
+%
+% [PLATFORM]
+% Windows XP, MATLAB R2012a, ...
+%
+% [KEYWORDS]
+% Any keyword you like ... comma separated
+% 
+% [TOOLBOXES USED]
+% Any commercial and other MATLAB toolboxes that need to be available for
+% this script to be run. PLEASE ADD ALSO THE VERSION/REVISION NUMBER OF THE
+% USED TOOLBOXES, so you are always able to reproduce your results.
+%
+% [EXAMPLES]
+% Here you can provide one or more examples that allow to run the
+% function.
+%
+% [VALIDATION HISTORY]
+% �
+% [MODIFICATION HISTORY]
+% including version numbering, changes, author and date of changes
+
+% Here your function starts. The above header should be ended by an empty
+% line.
+
+
+
+
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/templates/newfunctionSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/templates/newfunctionSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..d03136bf23589be11a288bf3234aa86a4643db4c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/templates/newfunctionSBPOP.m
@@ -0,0 +1,42 @@
+function [] = newfunctionSBPOP(varargin)
+% newfunctionSBPOP: Creates a new SBPOP function that is compatible with the
+% business guidelines in terms of header and additionally compatible with 
+% the MODSPACE requirements for MATLAB file parsing.
+%
+% USAGE:
+% ======
+%   newfunctionsSBPOP
+%   newfunctionsSBPOP('functionname')
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+file = which('functionTemplateSBPOP.m');
+if nargin == 0,
+    copyfile(file,[pwd '/newfunction.m']);
+elseif nargin == 1,
+    if ~ischar(varargin{1}),
+        copyfile(file,[pwd '/newfunction.m']);
+    else
+        filename = varargin{1};
+        filename = strrep(filename,'.m','');
+        copyfile(file,[pwd '/' filename '.m']);
+    end
+else
+    error('Incorrect number of input arguments.');
+end
+    
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/templates/newscriptSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/templates/newscriptSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..70134751e82a0bed13b75af97508494fb56adf71
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/templates/newscriptSBPOP.m
@@ -0,0 +1,42 @@
+function [] = newscriptSBPOP(varargin)
+% newscriptSBPOP: Creates a new SBPOP script that is compatible with the
+% business guidelines in terms of header and additionally compatible with 
+% the MODSPACE requirements for MATLAB file parsing.
+%
+% USAGE:
+% ======
+%   newscriptSBPOP
+%   newscriptSBPOP('scriptname')
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+file = which('scriptTemplateSBPOP.m');
+if nargin == 0,
+    copyfile(file,[pwd '/newscript.m']);
+elseif nargin == 1,
+    if ~ischar(varargin{1}),
+        copyfile(file,[pwd '/newscript.m']);
+    else
+        filename = varargin{1};
+        filename = strrep(filename,'.m','');
+        copyfile(file,[pwd '/' filename '.m']);
+    end
+else
+    error('Incorrect number of input arguments.');
+end
+    
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/templates/scriptTemplateSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/templates/scriptTemplateSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..f5b2079eee5e41a4d5f6e5dd52dfc3ecbc40f7f3
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/auxiliary/templates/scriptTemplateSBPOP.m
@@ -0,0 +1,39 @@
+% [DESCRIPTION]
+% In this section the purpose of the script should be described.
+% Additionally, the different possible syntaxes. 
+%
+% [INPUT]
+% Define the input arguments or other inputs (e.g. required files, etc.)
+% Please do NOT use hardcoded data in MATLAB scripts.
+%
+% [OUTPUT]
+% Define the output arguments or other outputs (e.g. produced log files,
+% figures, etc.) 
+%
+% [ASSUMPTIONS]
+% Here you can add any additional background information about assumptions.
+%
+% [AUTHOR]
+% Original author, ideally with email address
+%
+% [DATE]
+% Date of first creation
+%
+% [PLATFORM]
+% Windows XP, MATLAB R2012a, ...
+%
+% [KEYWORDS]
+% Any keyword you like ... comma separated
+% 
+% [TOOLBOXES USED]
+% Any commercial and other MATLAB toolboxes that need to be available for
+% this script to be run. 
+%
+% [VALIDATION HISTORY]
+% �
+% [MODIFICATION HISTORY]
+% including version numbering, changes, author and date of changes
+
+% Here your script starts. The above header should be ended by an empty
+% line.
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classes/@SBPOPdosing/SBPOPdosing.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classes/@SBPOPdosing/SBPOPdosing.m
new file mode 100644
index 0000000000000000000000000000000000000000..ec49bad6a72abcfb8e0f39ea7d82ae446c910973
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classes/@SBPOPdosing/SBPOPdosing.m
@@ -0,0 +1,120 @@
+function [dos] = SBPOPdosing(varargin)
+% SBPOPdosing: creates an SBPOPdosing object defining a dosing schedule
+%
+% USAGE:
+% ======
+% [dos] = SBPOPdosing()             creates an empty SBPOPdosing object
+% [dos] = SBPOPdosing(SBstructure)  creates an SBPOPdosing object from a MATLAB
+%                                   structure in the internal SBPOPdosing format
+% [dos] = SBPOPdosing(dosin)        construction from a given SBPOPdosing object (dosin)
+% [dos] = SBPOPdosing('file.dos')   converting a SBPOPdosing text description 
+%                                   to an SBPOPdosing object.
+%
+% Output Arguments:
+% =================
+% dos: SBPOPdosing object 
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK THE TYPE OF THE INPUT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin==0,
+    inputType = 'empty';
+elseif nargin == 1 || nargin == 2,
+    if isSBPOPdosing(varargin{1}),
+        inputType = 'SBPOPdosing';
+        dosInput = varargin{1};
+    elseif isstruct(varargin{1}),
+        inputType = 'SBstructure';
+        SBstructure = varargin{1};
+    elseif ischar(varargin{1}),
+        % check if '.dos' given as extension. If yes, then import text description
+        filename = varargin{1};
+        if ~isempty(strfind(filename,'.dos')),
+            inputType = 'TextDosFile';
+        elseif strcmp('DosingAsTextString', varargin{2}),
+            inputType = varargin{2};
+        else
+            error('Input argument of unknown type');
+        end
+    else 
+        error('Input argument of unknown type');
+    end
+else
+    error('Wrong number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONSTRUCT THE SBPOPdosing OBJECT 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp('empty',inputType),
+    % Create empty SBstructure
+    % parameters substructure
+    parametersStruct = struct('name',{},'value',{},'notes',{});
+    % inputs substructure
+    inputsStruct = struct('name',{},'type',{},'time',{},'Tlag',{},'D',{},'parameters',parametersStruct,'TlagNotes',{},'notes',{});
+    % Create SBstructure
+    SBstructure = struct('type','SBPOPdosing','name','unnamed_dosing','notes','no notes','inputs',inputsStruct);
+    % construct the dosing object
+    dos = class(SBstructure,'SBPOPdosing');
+elseif strcmp('SBPOPdosing',inputType),
+    % copy the object
+    dos = dosInput;
+elseif strcmp('SBstructure',inputType),
+    % check if the given structure is a SBstructure 
+    if isfield(SBstructure,'type'),
+        if ~strcmp(SBstructure.type,'SBPOPdosing'),
+            error('Given structure is not a valid internal SBPOPdosing structure.');
+        end
+    else
+        error('Given structure is not a valid internal SBPOPdosing structure.');
+    end
+    % construct the dosing object
+    dos = class(SBstructure,'SBPOPdosing');
+elseif strcmp('TextDosFile',inputType),
+    % check if a file with given filename exists
+    [path,filename,ext] = fileparts(filename);
+    filename = fullfile(path, [filename '.dos']); 
+    if ~exist(filename),
+        error(sprintf('Dosing file, "%s", does not exist.', filename));
+    end
+    % If file exists then first load it
+    dosText = fileread(filename);
+    % then convert it to SBstructure
+    [SBstructure, errorMsg] = convertTextToDosSBPOP(dosText);
+    % Check if error occurred while importing the dosing description
+    if ~isempty(errorMsg),
+        error(errorMsg);
+    end
+    % construct the dosing object
+    dos = class(SBstructure,'SBPOPdosing');
+elseif strcmp('DosingAsTextString', inputType),
+    dosText = varargin{1};
+    % then convert text dosing to SBstructure
+    [SBstructure, errorMsg] = convertTextToDosSBPOP(dosText);
+    % Check if error occurred while importing the dosing definition
+    if ~isempty(errorMsg),
+        error(errorMsg);
+    end
+    % construct the dosing object
+    dos = class(SBstructure,'SBPOPdosing');
+else
+    error('Wrong input arguments.');
+end
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classes/@SBPOPdosing/SBPOPstruct.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classes/@SBPOPdosing/SBPOPstruct.m
new file mode 100644
index 0000000000000000000000000000000000000000..3b345f4cc67f20249a99303efa754599ab530af3
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classes/@SBPOPdosing/SBPOPstruct.m
@@ -0,0 +1,36 @@
+function [SBstructure] = SBPOPstruct(dos)
+% SBPOPstruct: This function returns the internal data structure
+% of an SBPOPdosing object
+%
+% USAGE:
+% ======
+% [SBstructure] = SBPOPstruct(dos) 
+%
+% dos: SBPOPdosing object 
+%
+% Output Arguments:
+% =================
+% SBstructure: internal data structure of the SBPOPdosing object
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% VERY SIMPLE FUNCTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBstructure = struct(dos);
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classes/@SBPOPdosing/display.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classes/@SBPOPdosing/display.m
new file mode 100644
index 0000000000000000000000000000000000000000..25820700fcf1fdd868cb7025301d8ebc91df9d13
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classes/@SBPOPdosing/display.m
@@ -0,0 +1,49 @@
+function [] = display(dos)
+% display: Displays information about SBPOPdosing object. This function is 
+% called by MATLAB whenever an object is the result of a statement that
+% is not terminated by a semicolon. 
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% COLLECT INFORMATION ABOUT THE EXPERIMENT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+nrinputs = length(dos.inputs);
+nameinputs = {dos.inputs.name};
+typeinputs = {dos.inputs.type};
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DISPLAY INFORMATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+text = sprintf('\tSBPOPdosing\n\t===========\n');
+text = sprintf('%s\tName:  %s\n',text,dos.name);
+% text = sprintf('%s\tNotes: %s\n',text,dos.notes);
+text = sprintf('%s\tNumber inputs:     %d',text,nrinputs);
+disp(text);
+for k=1:length(nameinputs),
+    if length(dos.inputs(k).time) > 1,
+        type2 = 'muliple';
+    else 
+        type2 = 'single';
+    end
+    if ~isempty(dos.inputs(k).Tlag),
+        disp(sprintf('\t\t%s: %s %s\t\t(LAG)',dos.inputs(k).name,type2,dos.inputs(k).type));
+    else
+        disp(sprintf('\t\t%s: %s %s',dos.inputs(k).name,type2,dos.inputs(k).type));
+    end
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/SBPOPcreateDOSING.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/SBPOPcreateDOSING.m
new file mode 100644
index 0000000000000000000000000000000000000000..f3b039e5e198ab16d5f8eb16ce16f844f89588a9
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/SBPOPcreateDOSING.m
@@ -0,0 +1,147 @@
+function [dosing] = SBPOPcreateDOSING(type,dose,time,parametervalue,varargin)
+% SBPOPcreateDOSING: Creates a dosing scheme as desired based on inputs
+%
+% USAGE:
+% ======
+% [dosing] = SBPOPcreateDOSING(type,dose,time,parametervalue)         
+% [dosing] = SBPOPcreateDOSING(type,dose,time,parametervalue,tlagvalue)         
+%
+% type:             cell-array with input types in the order as inputs will be defined
+%                   possible types: "INFUSION", "ABSORPTION0", "ABSORPTION1", "BOLUS"
+% dose:             cell-array with dose vectors for each defined input - if scalar then same dose will be used for each dosing time
+% time:             cell-array with time vectors for each defined input
+% parametervalue:   cell-array with TINF, ka, TK0 values - if scalar then same value assumed for each dosing time
+% tlagvalue:        cell-array with lag time for each input definition
+%
+% dosing:           produced dosing scheme
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create empty dosing scheme
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ds = struct(SBPOPdosing);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 5,
+    tlagvalue = varargin{1};
+    if ~iscell(tlagvalue), tlagvalue = {tlagvalue}; end
+else
+    tlagvalue = [];
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check inputs and convert to cells if needed
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~iscell(type), type = {type}; end
+if ~iscell(dose), dose = {dose}; end
+if ~iscell(time), time = {time}; end
+if ~iscell(parametervalue), parametervalue = {parametervalue}; end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Update name fields
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(type),
+    ds.inputs(k).name = sprintf('INPUT%d',k);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Update type fields
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(type),
+    ds.inputs(k).type = type{k};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Update time fields
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if length(time) ~= length(type),
+    error('Number of entries in time cell-array different from number in type cell-array');
+end
+for k=1:length(time),
+    ds.inputs(k).time = time{k};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Update dose fields
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if length(dose) ~= length(type),
+    error('Number of entries in dose cell-array different from number in type cell-array');
+end
+for k=1:length(dose),
+    dosek = dose{k};
+    if length(dosek) == 1,
+        ds.inputs(k).D = dosek*ones(1,length(ds.inputs(k).time));
+    else
+        if length(dosek) ~= length(ds.inputs(k).time),
+            error('Different lengths of time and dose vectors for input %d',k);
+        else
+            ds.inputs(k).D = dosek;
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Update parameters fields
+% Only handle if type not BOLUS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if length(parametervalue) ~= length(type),
+    error('Number of entries in parametervalue cell-array different from number in type cell-array');
+end
+for k=1:length(type),
+    if ~strcmp(type{k},'BOLUS'),
+        pvk = parametervalue{k};
+        if strcmp(type{k},'INFUSION'),
+            ds.inputs(k).parameters.name = 'Tinf';
+        elseif strcmp(type{k},'ABSORPTION1'),
+            ds.inputs(k).parameters.name = 'ka';
+        elseif strcmp(type{k},'ABSORPTION0'),
+            ds.inputs(k).parameters.name = 'Tk0';
+        end            
+        ds.inputs(k).parameters.notes = '';
+        
+        if length(pvk) == 1,
+            ds.inputs(k).parameters.value = pvk*ones(1,length(ds.inputs(k).time));
+        else
+            if length(pvk) ~= length(ds.inputs(k).time),
+                error('Different lengths of parameter values and dose vectors for input %d',k);
+            else
+                ds.inputs(k).parameters.value = pvk;
+            end
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Update Tlag fields
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(tlagvalue),
+    if length(tlagvalue) ~= length(type),
+        error('Number of entries in tlagvalue cell-array different from number in type cell-array');
+    end
+    for k=1:length(tlagvalue),
+        ds.inputs(k).Tlag = tlagvalue{k};
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create dosing scheme
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dosing = SBPOPdosing(ds);
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/SBPOPcreateDOSfile.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/SBPOPcreateDOSfile.m
new file mode 100644
index 0000000000000000000000000000000000000000..b693ad4b56df1aa9101c2702437183dfce90f59b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/SBPOPcreateDOSfile.m
@@ -0,0 +1,89 @@
+function SBPOPcreateDOSfile(varargin)
+% SBPOPcreateDOSfile: creates a *.dos file with the dosing text description
+%
+% USAGE:
+% ======
+% [] = SBPOPcreateDOSfile()         
+% [] = SBPOPcreateDOSfile(filename)         
+% [] = SBPOPcreateDOSfile(dos)         
+% [] = SBPOPcreateDOSfile(dos,filename)
+%
+% dos: SBPOPdosing object to convert to a textfile description
+% filename: filename for the created textfile 
+%
+% If dos is undefined, then an empty SBPOPdosing textfile will be created.
+%
+% DEFAULT VALUES:
+% ===============
+% dos: the SBPOPdosing object to be exported as DOS file. 
+% filename: constructed from the SBPOPdosing object name
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 0,
+    % create empty SBPOPdosing file with the name "unnamed.dos"
+    dos = SBPOPdosing();
+    filename = 'unnamed.dos';
+elseif nargin == 1,
+    % check if first input argument dosing object or filename
+    if isSBPOPdosing(varargin{1}),
+        % dosing object given
+        dos = varargin{1};
+        % if no filename provided then use the name of the SBPOPdosing
+        % object as filename but remove unwanted characters first
+        ds = struct(dos);
+        functionName = regexprep(ds.name,'\W','');
+        filename = strcat(functionName,'.dos');
+    else
+        % filename given?
+        if ~ischar(varargin{1}),
+            error('Wrong input argument.');
+        end
+        filename = strcat(varargin{1},'.dos');
+        dos = SBPOPdosing();
+    end
+elseif nargin == 2,
+    dos = varargin{1};
+    filename = strcat(varargin{2},'.dos');
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK INPUT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBPOPdosing(dos),
+    error('No SBPOPdosing object as first argument.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONVERT DOSING TO TEXT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[dosTextStructure] = convertDosToTextSBPOP(dos);
+[completeText] = setPartsToCompleteTextDosSBPOP(dosTextStructure);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% WRITE THE FILE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen(filename,'w');
+fwrite(fid,completeText);
+fclose(fid);
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/SBPOPdoseupdatevalue.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/SBPOPdoseupdatevalue.m
new file mode 100644
index 0000000000000000000000000000000000000000..d982bb9cd0674f716682b139c09b32758fee1c1d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/SBPOPdoseupdatevalue.m
@@ -0,0 +1,58 @@
+function [dosingchanged] = SBPOPdoseupdatevalue(dosing,inputname,value)
+% SBPOPdoseupdatevalue: Allows to update the dosing amount for a given
+%   input, defined in an SBPOPdosing object.
+%
+% USAGE:
+% ======
+% [dosingchanged] = SBPOPdoseupdatevalue(dosing,inputname,value)         
+%
+% dosing: SBPOPdosing object 
+% inputname: name of the input for which to change the dosing amount
+% value: value to set the dosing amount to (only scalar value allowed, used
+%   for all dosing instances in case of multiple doses)
+%
+% Output Arguments:
+% =================
+% dosingchanged: updated SBPOPdosing object with changed dosing amount
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get dosing structure
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ds = struct(dosing);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Find input name
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+index = strmatchSB(inputname,{ds.inputs.name},'exact');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Change Dosing amount if index found
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(index),
+    disp(['Input ' inputname ' does not exist in the dosing schedule.']);
+else
+    % update dosing amount with new value
+    ds.inputs(index).D = value*ones(1,length(ds.inputs(index).time));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DONE => Construct output
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dosingchanged = SBPOPdosing(ds);
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/SBPOPmergemoddos.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/SBPOPmergemoddos.m
new file mode 100644
index 0000000000000000000000000000000000000000..ab5dec0b49e5e64943f07315dfd2de43c45331a0
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/SBPOPmergemoddos.m
@@ -0,0 +1,63 @@
+function [simmodel] = SBPOPmergemoddos(model,dosing)
+% SBPOPmergemoddos: Based on a model and dosing object, a new SBmodel is
+% generated, that implements the defined dosings. Multiple dosing schedules
+% are realized by updating the parameters of subsequent dosings using
+% events.
+%
+% This function is useful to simulate single dosing schedules. However, if
+% you want to run trial simulations, which change the dosing amounts (or
+% other things) between simulations, this function is not the best way to
+% go, since you would need to apply these changes to the dosing schedule,
+% run this function, recompile your model, etc.
+%
+% USAGE:
+% ======
+% [simmodel] = SBPOPmergemoddos(model,dosing) 
+%
+% model: SBmodel
+% dosing: SBPOPdosing object
+%
+% Output Arguments:
+% =================
+% simmodel: Simulation model, implementing the dosing scheme, defined in
+%   the model and the SBPOPdosing object.
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBmodel(model),
+    error('First input argument is not an SBmodel.');
+end
+if ~isSBPOPdosing(dosing),
+    error('Second input argument is not an SBPOPdosing object.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get model augmented with dosing related 
+% components and the experiment description,
+% implementing the dosing applications
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[moddos,experiment] = mergemoddosSBPOP(model,dosing);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Combine new model with experiment to get the
+% simulation model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+simmodel = SBmergemodexp(moddos,experiment);
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/SBPOPsimdosing.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/SBPOPsimdosing.m
new file mode 100644
index 0000000000000000000000000000000000000000..52ceb848e79a3f75f0c2e2a10df95487bdd7d189
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/SBPOPsimdosing.m
@@ -0,0 +1,399 @@
+function [varargout] = SBPOPsimdosing(moddos,dosing,varargin)
+% SBPOPsimdosing: Simulates the application of a dosing schedule to a model
+% that has been prepared for it and either plots or returns the simulation
+% results.
+%
+% USAGE:
+% ======
+% [output] = SBPOPsimdosing(moddos,dosing)         
+% [output] = SBPOPsimdosing(moddos,dosing,time)         
+% [output] = SBPOPsimdosing(moddos,dosing,time,ICs)         
+% [output] = SBPOPsimdosing(moddos,dosing,time,ICs,paramnames,paramvalues)         
+% [output] = SBPOPsimdosing(moddos,dosing,time,ICs,paramnames,paramvalues,OPTIONS)         
+%
+% moddos: SBmodel or MEXmodel which has been prepared using the
+%   mergemoddosSBPOP function. Note that if you use here a model that does
+%   not fit to the dosing input, the result will most certainly be wrong.
+% dosing: SBPOPdosing object with which the moddos model has been prepared.
+%   This input argument defines the dosing schedule to simulate
+% time: timevector to simulate. If scalar than the value defines the end
+%   simulation time and the time vector starts at 0. 
+% ICs: vector with initial conditions
+% paramnames: parameter name or cell-array with parameter-names 
+%             Parameters which are passed to the function to be modified do have 
+%             priority over parameters that are defined in the dosing scheme
+%             (Tinf,ka, Tlag, etc.)
+% paramvalues: vector with values for the parameters (in the same order as
+%   paramnames)
+% OPTIONS: CVODE integrator options
+%
+% DEFAULT VALUES:
+% ===============
+% time: If not defined or left empty ([]), then the timevector will be
+%   chosen to cover the full dosing schedule +50%
+%   If the only dosing event occurs at time = 0, then a default time of 20
+%   is then used.
+% ICs: [] (use initial conditions, stored in the model)
+% paramnames: {}
+% paramvalues: [] (use values stored in the model)
+% OPTIONS: 
+%   OPTIONs.method        = 'stiff'
+%   OPTIONS.abstol        = 1e-6;
+%   OPTIONS.reltol        = 1e-6;
+%   OPTIONS.maxnumsteps   = 100000;
+%
+% Output Arguments:
+% =================
+% If an output argument is given, this variable will contain a standard
+% simulation result structure containing the time and the state, variable,
+% and reactions names and values. 
+% If no output argument is given, the result is plotted using the SBplot
+% function.
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+global doseeventstruct_sim
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SET DEFAULT VALUES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+time = [];  % indicates to calculate timevector from dosing schedule
+OPTIONS = [];
+OPTIONS.method = 'stiff';
+OPTIONS.abstol = 1e-6;
+OPTIONS.reltol = 1e-6;
+OPTIONS.maxnumstep = 100000;
+paramnames = {};
+paramvalues = [];
+ICs = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 2,
+elseif nargin == 3,
+    time = varargin{1};
+elseif nargin == 4,
+    time = varargin{1};
+    ICs = varargin{2};
+elseif nargin == 6,
+    time = varargin{1};
+    ICs = varargin{2};
+    paramnames = varargin{3};
+    paramvalues = varargin{4};
+elseif nargin == 7,
+    time = varargin{1};
+    ICs = varargin{2};
+    paramnames = varargin{3};
+    paramvalues = varargin{4};
+    OPTIONS = varargin{5};
+else
+    error('Incorrect number of input arguments.');
+end
+% char => cell 
+if ischar(paramnames),
+    paramnames = {paramnames};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF SBmodel and create MEXmodel
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isSBmodel(moddos),
+    [MEXmodel, MEXmodelfullpath] = makeTempMEXmodelSBPD(moddos);
+else
+    MEXmodel = moddos;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create doseeventstruct
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+doseeventstruct = dosing2doseeventSBPOP(dosing);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle timevector definition
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(time),
+    time = round(1.5*doseeventstruct(end).time);
+    % Could handle when the dosing event is at time 0
+    % then set time to a default end time
+    if time == 0
+        time = 20;
+    end
+    timevector = [0:time/1000:time];    
+elseif length(time) == 1,
+    timevector = [0:time/1000:time];
+else
+    timevector = time;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle the case when final simulation time is smaller than the last dosing
+% times. Simply remove the corresponding entries from the doseeventstruct.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+doseeventstruct_sim = doseeventstruct;
+doseeventstruct_sim(find([doseeventstruct.time] > timevector(end))) = [];
+if isempty(doseeventstruct_sim),
+    error('Please use a final simulation time that is larger than the first dosing time.')
+end 
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Prepare the simulation
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Split the time vector into pieces from 0 to start of dosing
+% applications, during dosing applications and from last application to
+% final time.
+firstdosing = doseeventstruct_sim(1).time;
+lastdosing = doseeventstruct_sim(end).time;
+timevectorpre = timevector(find(timevector < firstdosing));
+timevectorpost = timevector(find(timevector > lastdosing));
+timevectorduring = setdiff(setdiff(timevector,timevectorpre),timevectorpost);
+% Adjust time vectors to include dosing times. This leads to the first and
+% last dosing times being included twice (need to handle this later).
+if ~isempty(timevectorpre),
+    % Add first dosing time only if pre time vector is not empty.
+    timevectorpre = [timevectorpre(:); firstdosing];
+end
+if ~isempty(timevectorpost),
+    % Add last dosing time only if post time vector is not empty.
+    timevectorpost = [lastdosing; timevectorpost(:)];
+end
+timvectorduring = sort(unique([timevectorduring(:); [doseeventstruct_sim.time]']));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Prepare the simulation output structure
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+simout = [];
+simout.time = [];
+simout.states = {};
+simout.statevalues = [];
+simout.variables = {};
+simout.variablevalues = [];
+simout.reactions = {};
+simout.reactionvalues = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Simulate the prepart (only if timevectorpre is not empty)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(timevectorpre),
+    presim = SBPDsimulate(MEXmodel,timevectorpre,ICs,paramnames,paramvalues,OPTIONS);
+    % add results to output structure (neglect last index, since it is also
+    % available in the during timevector). But save last state as IC for
+    % next stage simulation
+    simout.time = [simout.time; presim.time(1:end-1)];
+    simout.states = presim.states;
+    simout.statevalues = [simout.statevalues; presim.statevalues(1:end-1,:)];
+    simout.variables = presim.variables;
+    simout.variablevalues = [simout.variablevalues; presim.variablevalues(1:end-1,:)];
+    simout.reactions = presim.reactions;
+    simout.reactionvalues = [simout.reactionvalues; presim.reactionvalues(1:end-1,:)];
+    % Save info for next stage simulation
+    ICnext_values = presim.statevalues(end,:);
+else
+    % No simulation of first part => define ICs as the ones given or stored
+    % in the model
+    ICnext_values = ICs;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Simulate the part in which dosing applications occur. Here we need to
+% simulate piecewise inbetween dosing times
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length([doseeventstruct_sim.time])-1,
+    dosetime = doseeventstruct_sim(k).time;
+    nextdosetime = doseeventstruct_sim(k+1).time;
+
+    % Determine the changes to parameters to implement dosing and timing of doses
+    paramchangevalues = [];
+    paramchangenames = {};
+    for k2 = 1:length(doseeventstruct_sim(k).input),
+        paramchangevalues = [paramchangevalues(:)' doseeventstruct_sim(k).input(k2).parametervalues(:)' dosetime];
+        paramchangenames = {paramchangenames{:} doseeventstruct_sim(k).input(k2).parameternames{:} doseeventstruct_sim(k).input(k2).timeparname};
+    end
+    % paramchangevalues and paramchangenames contains the values for dose, time, ka, Tinf, etc that are defined in the dosing scheme
+    % we need to make sure that parameters that are defined in the model or in the parameters that are passed to the SBPOPsimdosing
+    % function to have priority over the parameters defined in the dosing scheme.
+    % This is done by checking if paramnames has same elements as paramchangenames and then remove these double definitions from the 
+    % paramchangenames and paramchangevalues arrays.
+    double_defined_parameters = intersect(paramchangenames,paramnames);
+    for k2=1:length(double_defined_parameters),
+        % Remove the double defined ones from the paramchangenames and values (parameters passed to the simulation function have priority over definition in 
+        % dosing scheme).
+        indexremove = strmatchSB(double_defined_parameters{k2},paramchangenames,'exact');
+        paramchangevalues(indexremove) = [];
+        paramchangenames(indexremove) = [];
+        % Report what is done
+%        fprintf('Parameter "%s" passed to SBPOPsimdosing function has priority over definition of same parameter in dosing scheme.',double_defined_parameters{k2});
+    end
+
+    % Combine parameter changes from dosing scheme and passed parameters to simulation function
+    paramchangevalues = [paramchangevalues(:)' paramvalues(:)'];
+    paramchangenames = {paramchangenames{:} paramnames{:}};
+    % paramchangevalues = [paramvalues(:)' doseeventstruct_sim(k).input.parametervalues dosetime*ones(1,length(doseeventstruct_sim(k).input))];
+    % paramchangenames = {paramnames{:} doseeventstruct_sim(k).input.parameternames{:} doseeventstruct_sim(k).input.timeparname};
+    
+    % Determine the timevector piece (from dosing time to next dosing time (wo application at the latter)
+    timevectorpiece = timvectorduring;
+    timevectorpiece(timevectorpiece<dosetime) = [];
+    timevectorpiece(timevectorpiece>nextdosetime) = [];
+    
+    sim = SBPDsimulate(MEXmodel,timevectorpiece,ICnext_values,paramchangenames,paramchangevalues,OPTIONS);
+    % add results to output structure (if timevectorpost not empty => 
+    % neglect last index, since it is also available in the next timevector
+    % piece. Do NOT neglect if timevectorpost is empty). In any case 
+    % save last state as IC for next stage simulation
+    if ~isempty(timevectorpost),
+        simout.time = [simout.time; sim.time(1:end-1)];
+        simout.statevalues = [simout.statevalues; sim.statevalues(1:end-1,:)];
+        simout.variablevalues = [simout.variablevalues; sim.variablevalues(1:end-1,:)];
+        simout.reactionvalues = [simout.reactionvalues; sim.reactionvalues(1:end-1,:)];
+    else
+        simout.time = [simout.time; sim.time(1:end)];
+        simout.statevalues = [simout.statevalues; sim.statevalues(1:end,:)];
+        simout.variablevalues = [simout.variablevalues; sim.variablevalues(1:end,:)];
+        simout.reactionvalues = [simout.reactionvalues; sim.reactionvalues(1:end,:)];
+    end
+    % add them here also (since presim might not happen ifg dosing at 0).
+    simout.states = sim.states;
+    simout.variables = sim.variables;
+    simout.reactions = sim.reactions;
+    % Save info for next stage simulation
+    ICnext_values = sim.statevalues(end,:);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Simulate the postpart (only if timevectorpost is not empty)
+% The postpart starts with the application of the LAST dosing amount
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(timevectorpost),
+    dosetime = doseeventstruct_sim(end).time;
+    % Determine the changes to parameters to implement dosing and timing of doses
+    
+    paramchangevalues = [];
+    paramchangenames = {};
+    for k2 = 1:length(doseeventstruct_sim(end).input),
+        paramchangevalues = [paramchangevalues(:)' doseeventstruct_sim(end).input(k2).parametervalues(:)' dosetime];
+        paramchangenames = {paramchangenames{:} doseeventstruct_sim(end).input(k2).parameternames{:} doseeventstruct_sim(end).input(k2).timeparname};
+    end
+    % paramchangevalues and paramchangenames contains the values for dose, time, ka, Tinf, etc that are defined in the dosing scheme
+    % we need to make sure that parameters that are defined in the model or in the parameters that are passed to the SBPOPsimdosing
+    % function to have priority over the parameters defined in the dosing scheme.
+    % This is done by checking if paramnames has same elements as paramchangenames and then remove these double definitions from the 
+    % paramchangenames and paramchangevalues arrays.
+    double_defined_parameters = intersect(paramchangenames,paramnames);
+    for k2=1:length(double_defined_parameters),
+        % Remove the double defined ones from the paramchangenames and values (parameters passed to the simulation function have priority over definition in 
+        % dosing scheme).
+        indexremove = strmatchSB(double_defined_parameters{k2},paramchangenames,'exact');
+        paramchangevalues(indexremove) = [];
+        paramchangenames(indexremove) = [];
+        % Report what is done
+%        fprintf('Parameter "%s" passed to SBPOPsimdosing function has priority over definition of same parameter in dosing scheme.',double_defined_parameters{k2});
+    end
+    
+    paramchangevalues = [paramchangevalues(:)' paramvalues(:)'];
+    paramchangenames = {paramchangenames{:} paramnames{:}};
+
+    % Do simulation of last piece
+    sim = SBPDsimulate(MEXmodel,timevectorpost,ICnext_values,paramchangenames,paramchangevalues,OPTIONS);
+    % Collect simulation results
+    simout.time = [simout.time; sim.time(1:end)];
+    simout.statevalues = [simout.statevalues; sim.statevalues(1:end,:)];
+    simout.variablevalues = [simout.variablevalues; sim.variablevalues(1:end,:)];
+    simout.reactionvalues = [simout.reactionvalues; sim.reactionvalues(1:end,:)];
+    % add them here also (since presim might not happen ifg dosing at 0).
+    simout.states = sim.states;
+    simout.variables = sim.variables;
+    simout.reactions = sim.reactions;    
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Finally, do remove the timepoints that are dosing time points but not
+% defined in the desired simulation time vector.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[values,removeindices] = setdiff(simout.time,timevector);
+while ~isempty(removeindices),
+    simout.time(removeindices) = [];
+    simout.statevalues(removeindices,:) = [];
+    if ~isempty(simout.variables),
+        simout.variablevalues(removeindices,:) = [];
+    end
+    if ~isempty(simout.reactions),
+        simout.reactionvalues(removeindices,:) = [];
+    end
+    [values,removeindices] = setdiff(simout.time,timevector);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Really finally, do remove double definitions of
+% time points, which can happen in the case that
+% dosing and observation time points are the same
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+lengthOLD = Inf;
+% seems that sometimes MATLABis not picking it up correctly, then 
+% we need to redo the exercise :(
+while length(simout.time) ~= lengthOLD,
+    lengthOLD = length(simout.time);
+    
+    [B,I,J] = unique(simout.time);
+    removeindices = setdiff(J,I);
+    simout.time(removeindices) = [];
+    simout.statevalues(removeindices,:) = [];
+    if ~isempty(simout.variables),
+        simout.variablevalues(removeindices,:) = [];
+    end
+    if ~isempty(simout.reactions),
+        simout.reactionvalues(removeindices,:) = [];
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle variable output arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output = simout;
+if nargout == 1,
+    varargout{1} = output;
+elseif nargout == 0,
+    % prepare data for plotting
+    time = output.time;
+    datanames = {};
+    dataindex = 1;
+    for k = 1:length(output.states),
+        datanames{dataindex} = sprintf('%s (state)',output.states{k});
+        dataindex = dataindex + 1;
+    end
+    for k = 1:length(output.variables),
+        datanames{dataindex} = sprintf('%s (variable)',output.variables{k});
+        dataindex = dataindex + 1;
+    end
+    for k = 1:length(output.reactions),
+        datanames{dataindex} = sprintf('%s (reaction rate)',output.reactions{k});
+        dataindex = dataindex + 1;
+    end
+    datavalues = [output.statevalues, output.variablevalues, output.reactionvalues];
+    SBplot(createdatastructSBplotSB(time,datavalues,datanames));
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Delete MEX file if created in this function
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isSBmodel(moddos),
+    clear mex
+    delete(MEXmodelfullpath);
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/SBPOPsimulate.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/SBPOPsimulate.m
new file mode 100644
index 0000000000000000000000000000000000000000..db6bd596d45fdeb4c67dd46c1767587717b40c70
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/SBPOPsimulate.m
@@ -0,0 +1,393 @@
+function [varargout] = SBPOPsimulate(model,dosing,varargin)
+% SBPOPsimdosing: Simulates the application of a dosing schedule to an SBmodel with relevant INPUT definitions.
+%
+% USAGE:
+% ======
+% [output] = SBPOPsimulate(model,dosing)         
+% [output] = SBPOPsimulate(model,dosing,time)         
+% [output] = SBPOPsimulate(model,dosing,time,ICs)         
+% [output] = SBPOPsimulate(model,dosing,time,ICs,paramnames,paramvalues)         
+% [output] = SBPOPsimulate(model,dosing,time,ICs,paramnames,paramvalues,OPTIONS)         
+%
+% moddos:      SBmodel with INPUT definitions matching the input definitions in the provided dosing scheme 
+% dosing:      SBPOPdosing object with dosing information to simulate the model with
+% time:        timevector to simulate. If scalar than the value defines the end
+%              simulation time and the time vector starts at 0. 
+% ICs:         vector with initial conditions
+% paramnames:  string with parameter name or cell-array with parameter-names 
+% paramvalues: vector with values for the parameters (in the same order as paramnames)
+% OPTIONS:     CVODE integrator options
+%
+% DEFAULT VALUES:
+% ===============
+% time: If not defined or left empty ([]), then the timevector will be
+%   chosen to cover the full dosing schedule +50%
+%   If the only dosing event occurs at time = 0, then a default time of 20 is then used.
+% ICs: [] (use initial conditions, stored in the model)
+% paramnames: []
+% paramvalues: [] (use values stored in the model)
+% OPTIONS: 
+%   OPTIONs.method        = 'stiff'
+%   OPTIONS.abstol        = 1e-10;
+%   OPTIONS.reltol        = 1e-10;
+%   OPTIONS.maxnumsteps   = 100000;
+%
+% Output Arguments:
+% =================
+% If an output argument is given, this variable will contain a standard
+% simulation result structure containing the time and the state, variable,
+% and reactions names and values. 
+% If no output argument is given, the result is plotted using the SBplot
+% function.
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+global doseeventstruct_sim
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SET DEFAULT VALUES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+time = [];  % indicates to calculate timevector from dosing schedule
+OPTIONS = [];
+OPTIONS.method = 'stiff';
+OPTIONS.abstol = 1e-10;
+OPTIONS.reltol = 1e-10;
+OPTIONS.maxnumstep = 100000;
+paramnames = {};
+paramvalues = [];
+ICs = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 2,
+elseif nargin == 3,
+    time = varargin{1};
+elseif nargin == 4,
+    time = varargin{1};
+    ICs = varargin{2};
+elseif nargin == 6,
+    time = varargin{1};
+    ICs = varargin{2};
+    paramnames = varargin{3};
+    paramvalues = varargin{4};
+elseif nargin == 7,
+    time = varargin{1};
+    ICs = varargin{2};
+    paramnames = varargin{3};
+    paramvalues = varargin{4};
+    OPTIONS = varargin{5};
+else
+    error('Incorrect number of input arguments.');
+end
+% char => cell 
+if ischar(paramnames),
+    paramnames = {paramnames};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK somethings
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBmodel(model),
+    error('First input argument needs to be an SBmodel');
+end
+if ~isSBPOPdosing(dosing),
+    error('Second input argument needs to be an SBPOPdosing object');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create moddos and MEX model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+moddos = mergemoddosSBPOP(model,dosing);
+[MEXmodel, MEXmodelfullpath] = makeTempMEXmodelSBPD(moddos);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create doseeventstruct
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+doseeventstruct = dosing2doseeventSBPOP(dosing);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle timevector definition
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(time),
+    time = round(1.5*doseeventstruct(end).time);
+    % Could handle when the dosing event is at time 0
+    % then set time to a default end time
+    if time == 0
+        time = 20;
+    end
+    timevector = [0:time/1000:time];    
+elseif length(time) == 1,
+    timevector = [0:time/1000:time];
+else
+    timevector = time;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle the case when final simulation time is smaller than the last dosing
+% times. Simply remove the corresponding entries from the doseeventstruct.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+doseeventstruct_sim = doseeventstruct;
+doseeventstruct_sim(find([doseeventstruct.time] > timevector(end))) = [];
+if isempty(doseeventstruct_sim),
+    error('Please use a final simulation time that is larger than the first dosing time.')
+end 
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Prepare the simulation
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Split the time vector into pieces from 0 to start of dosing
+% applications, during dosing applications and from last application to
+% final time.
+firstdosing = doseeventstruct_sim(1).time;
+lastdosing = doseeventstruct_sim(end).time;
+timevectorpre = timevector(find(timevector < firstdosing));
+timevectorpost = timevector(find(timevector > lastdosing));
+timevectorduring = setdiff(setdiff(timevector,timevectorpre),timevectorpost);
+% Adjust time vectors to include dosing times. This leads to the first and
+% last dosing times being included twice (need to handle this later).
+if ~isempty(timevectorpre),
+    % Add first dosing time only if pre time vector is not empty.
+    timevectorpre = [timevectorpre(:); firstdosing];
+end
+if ~isempty(timevectorpost),
+    % Add last dosing time only if post time vector is not empty.
+    timevectorpost = [lastdosing; timevectorpost(:)];
+end
+timvectorduring = sort(unique([timevectorduring(:); [doseeventstruct_sim.time]']));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Prepare the simulation output structure
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+simout = [];
+simout.time = [];
+simout.states = {};
+simout.statevalues = [];
+simout.variables = {};
+simout.variablevalues = [];
+simout.reactions = {};
+simout.reactionvalues = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Simulate the prepart (only if timevectorpre is not empty)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(timevectorpre),
+    presim = SBPDsimulate(MEXmodel,timevectorpre,ICs,paramnames,paramvalues,OPTIONS);
+    % add results to output structure (neglect last index, since it is also
+    % available in the during timevector). But save last state as IC for
+    % next stage simulation
+    simout.time = [simout.time; presim.time(1:end-1)];
+    simout.states = presim.states;
+    simout.statevalues = [simout.statevalues; presim.statevalues(1:end-1,:)];
+    simout.variables = presim.variables;
+    simout.variablevalues = [simout.variablevalues; presim.variablevalues(1:end-1,:)];
+    simout.reactions = presim.reactions;
+    simout.reactionvalues = [simout.reactionvalues; presim.reactionvalues(1:end-1,:)];
+    % Save info for next stage simulation
+    ICnext_values = presim.statevalues(end,:);
+else
+    % No simulation of first part => define ICs as the ones given or stored
+    % in the model
+    ICnext_values = ICs;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Simulate the part in which dosing applications occur. Here we need to
+% simulate piecewise inbetween dosing times
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length([doseeventstruct_sim.time])-1,
+    dosetime = doseeventstruct_sim(k).time;
+    nextdosetime = doseeventstruct_sim(k+1).time;
+
+    % Determine the changes to parameters to implement dosing and timing of doses
+    paramchangevalues = [];
+    paramchangenames = {};
+    for k2 = 1:length(doseeventstruct_sim(k).input),
+        paramchangevalues = [paramchangevalues(:)' doseeventstruct_sim(k).input(k2).parametervalues(:)' dosetime];
+        paramchangenames = {paramchangenames{:} doseeventstruct_sim(k).input(k2).parameternames{:} doseeventstruct_sim(k).input(k2).timeparname};
+    end
+    % paramchangevalues and paramchangenames contains the values for dose, time, ka, Tinf, etc that are defined in the dosing scheme
+    % we need to make sure that parameters that are defined in the model or in the parameters that are passed to the SBPOPsimdosing
+    % function to have priority over the parameters defined in the dosing scheme.
+    % This is done by checking if paramnames has same elements as paramchangenames and then remove these double definitions from the 
+    % paramchangenames and paramchangevalues arrays.
+    double_defined_parameters = intersect(paramchangenames,paramnames);
+    for k2=1:length(double_defined_parameters),
+        % Remove the double defined ones from the paramchangenames and values (parameters passed to the simulation function have priority over definition in 
+        % dosing scheme).
+        indexremove = strmatchSB(double_defined_parameters{k2},paramchangenames,'exact');
+        paramchangevalues(indexremove) = [];
+        paramchangenames(indexremove) = [];
+        % Report what is done
+%        fprintf('Parameter "%s" passed to SBPOPsimdosing function has priority over definition of same parameter in dosing scheme.',double_defined_parameters{k2});
+    end
+
+    % Combine parameter changes from dosing scheme and passed parameters to simulation function
+    paramchangevalues = [paramchangevalues(:)' paramvalues(:)'];
+    paramchangenames = {paramchangenames{:} paramnames{:}};
+    % paramchangevalues = [paramvalues(:)' doseeventstruct_sim(k).input.parametervalues dosetime*ones(1,length(doseeventstruct_sim(k).input))];
+    % paramchangenames = {paramnames{:} doseeventstruct_sim(k).input.parameternames{:} doseeventstruct_sim(k).input.timeparname};
+    
+    % Determine the timevector piece (from dosing time to next dosing time (wo application at the latter)
+    timevectorpiece = timvectorduring;
+    timevectorpiece(timevectorpiece<dosetime) = [];
+    timevectorpiece(timevectorpiece>nextdosetime) = [];
+    
+    sim = SBPDsimulate(MEXmodel,timevectorpiece,ICnext_values,paramchangenames,paramchangevalues,OPTIONS);
+    % add results to output structure (if timevectorpost not empty => 
+    % neglect last index, since it is also available in the next timevector
+    % piece. Do NOT neglect if timevectorpost is empty). In any case 
+    % save last state as IC for next stage simulation
+    if ~isempty(timevectorpost),
+        simout.time = [simout.time; sim.time(1:end-1)];
+        simout.statevalues = [simout.statevalues; sim.statevalues(1:end-1,:)];
+        simout.variablevalues = [simout.variablevalues; sim.variablevalues(1:end-1,:)];
+        simout.reactionvalues = [simout.reactionvalues; sim.reactionvalues(1:end-1,:)];
+    else
+        simout.time = [simout.time; sim.time(1:end)];
+        simout.statevalues = [simout.statevalues; sim.statevalues(1:end,:)];
+        simout.variablevalues = [simout.variablevalues; sim.variablevalues(1:end,:)];
+        simout.reactionvalues = [simout.reactionvalues; sim.reactionvalues(1:end,:)];
+    end
+    % add them here also (since presim might not happen ifg dosing at 0).
+    simout.states = sim.states;
+    simout.variables = sim.variables;
+    simout.reactions = sim.reactions;
+    % Save info for next stage simulation
+    ICnext_values = sim.statevalues(end,:);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Simulate the postpart (only if timevectorpost is not empty)
+% The postpart starts with the application of the LAST dosing amount
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(timevectorpost),
+    dosetime = doseeventstruct_sim(end).time;
+    % Determine the changes to parameters to implement dosing and timing of doses
+    
+    paramchangevalues = [];
+    paramchangenames = {};
+    for k2 = 1:length(doseeventstruct_sim(end).input),
+        paramchangevalues = [paramchangevalues(:)' doseeventstruct_sim(end).input(k2).parametervalues(:)' dosetime];
+        paramchangenames = {paramchangenames{:} doseeventstruct_sim(end).input(k2).parameternames{:} doseeventstruct_sim(end).input(k2).timeparname};
+    end
+    % paramchangevalues and paramchangenames contains the values for dose, time, ka, Tinf, etc that are defined in the dosing scheme
+    % we need to make sure that parameters that are defined in the model or in the parameters that are passed to the SBPOPsimdosing
+    % function to have priority over the parameters defined in the dosing scheme.
+    % This is done by checking if paramnames has same elements as paramchangenames and then remove these double definitions from the 
+    % paramchangenames and paramchangevalues arrays.
+    double_defined_parameters = intersect(paramchangenames,paramnames);
+    for k2=1:length(double_defined_parameters),
+        % Remove the double defined ones from the paramchangenames and values (parameters passed to the simulation function have priority over definition in 
+        % dosing scheme).
+        indexremove = strmatchSB(double_defined_parameters{k2},paramchangenames,'exact');
+        paramchangevalues(indexremove) = [];
+        paramchangenames(indexremove) = [];
+        % Report what is done
+%        fprintf('Parameter "%s" passed to SBPOPsimdosing function has priority over definition of same parameter in dosing scheme.',double_defined_parameters{k2});
+    end
+    
+    paramchangevalues = [paramchangevalues(:)' paramvalues(:)'];
+    paramchangenames = {paramchangenames{:} paramnames{:}};
+
+    % Do simulation of last piece
+    sim = SBPDsimulate(MEXmodel,timevectorpost,ICnext_values,paramchangenames,paramchangevalues,OPTIONS);
+    % Collect simulation results
+    simout.time = [simout.time; sim.time(1:end)];
+    simout.statevalues = [simout.statevalues; sim.statevalues(1:end,:)];
+    simout.variablevalues = [simout.variablevalues; sim.variablevalues(1:end,:)];
+    simout.reactionvalues = [simout.reactionvalues; sim.reactionvalues(1:end,:)];
+    % add them here also (since presim might not happen ifg dosing at 0).
+    simout.states = sim.states;
+    simout.variables = sim.variables;
+    simout.reactions = sim.reactions;    
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Finally, do remove the timepoints that are dosing time points but not
+% defined in the desired simulation time vector.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[values,removeindices] = setdiff(simout.time,timevector);
+simout.time(removeindices) = [];
+simout.statevalues(removeindices,:) = [];
+if ~isempty(simout.variables),
+    simout.variablevalues(removeindices,:) = [];
+end
+if ~isempty(simout.reactions),
+    simout.reactionvalues(removeindices,:) = [];
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Really finally, do remove double definitions of
+% time points, which can happen in the case that
+% dosing and observation time points are the same
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+lengthOLD = Inf;
+% seems that sometimes MATLABis not picking it up correctly, then 
+% we need to redo the exercise :(
+while length(simout.time) ~= lengthOLD,
+    lengthOLD = length(simout.time);
+    
+    [B,I,J] = unique(simout.time);
+    removeindices = setdiff(J,I);
+    simout.time(removeindices) = [];
+    simout.statevalues(removeindices,:) = [];
+    if ~isempty(simout.variables),
+        simout.variablevalues(removeindices,:) = [];
+    end
+    if ~isempty(simout.reactions),
+        simout.reactionvalues(removeindices,:) = [];
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle variable output arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output = simout;
+if nargout == 1,
+    varargout{1} = output;
+elseif nargout == 0,
+    % prepare data for plotting
+    time = output.time;
+    datanames = {};
+    dataindex = 1;
+    for k = 1:length(output.states),
+        datanames{dataindex} = sprintf('%s (state)',output.states{k});
+        dataindex = dataindex + 1;
+    end
+    for k = 1:length(output.variables),
+        datanames{dataindex} = sprintf('%s (variable)',output.variables{k});
+        dataindex = dataindex + 1;
+    end
+    for k = 1:length(output.reactions),
+        datanames{dataindex} = sprintf('%s (reaction rate)',output.reactions{k});
+        dataindex = dataindex + 1;
+    end
+    datavalues = [output.statevalues, output.variablevalues, output.reactionvalues];
+    SBplot(createdatastructSBplotSB(time,datavalues,datanames));
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Delete MEX file if created in this function
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isSBmodel(moddos),
+    clear mex
+    delete(MEXmodelfullpath);
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/auxiliary/doseinputsSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/auxiliary/doseinputsSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..4181a8a76bd14997c3ead821591abad7a6949aae
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/auxiliary/doseinputsSBPOP.m
@@ -0,0 +1,45 @@
+function [names,types] = doseinputsSBPOP(dos)
+% doseinputsSBPOP: Extracts names and types of dosing inputs from a
+% SBPOPdosing object.
+%
+% USAGE:
+% ======
+% [names,types] = doseinputsSBPOP(dos) 
+%
+% dos: SBPOPdosing object
+%
+% Output Arguments:
+% =================
+% names: cell-array with input names
+% types: cell-array with input types
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBPOPdosing(dos),
+    error('Input argument is not an SBPOPdosing object.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get names and types
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ds = struct(dos);
+names = {ds.inputs.name};
+types = {ds.inputs.type};
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/auxiliary/dosing2doseeventSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/auxiliary/dosing2doseeventSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..7d3e828347627d027ff13b417089fd6c525b9440
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/auxiliary/dosing2doseeventSBPOP.m
@@ -0,0 +1,147 @@
+function [doseeventstruct] = dosing2doseeventSBPOP(dosing)
+% dosing2doseeventSBPOP: This function takes an SBPOP dosing object as
+% input and returns a structure in which the dosing events, happening, are
+% sorted according to the times at which they happen. Additionally, the
+% output structure contains information about the dosing amount and the
+% names of the parameters in a model to change in order to apply the
+% dosing. Also lag and the other dosing type dependend informations are
+% collected.
+% 
+% USAGE:
+% ======
+% [doseeventstruct] = dosing2doseeventSBPOP(dosing) 
+%
+% dosing: SBPOPdosing object
+%
+% Output Arguments:
+% =================
+% doseeventstruct: output argument with the following structure:
+%   .time                   time of dosing application
+%   .input 
+%   .input.index            index of dosing input in dosing object to be applied
+%   .input.timeparname      name of time parameter for this input
+%   .input.parameternames   cell-array with other parameter names to change the values for
+%   .input.parametervalues  vector with new parameter values (same order as
+%                           parameternames cell-array)
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBPOPdosing(dosing),
+    error('Input argument is not an SBPOPdosing object.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get dosing structure
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ds = struct(dosing);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get a dosing matrix and dose/time parameter 
+% names as added to a model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dosingmatrix = [];
+inames = {}; 
+for k=1:length(ds.inputs),
+    dosingmatrix = [dosingmatrix; ds.inputs(k).time(:) ds.inputs(k).D(:) k*ones(length(ds.inputs(k).D),1)];
+    inames{k} = ds.inputs(k).name;
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Check if dosing times unique
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    if length(ds.inputs(k).time) ~= length(unique(ds.inputs(k).time)),
+        error('Dosing times in dosing object are not unique.');
+    end
+end
+% sort the dosing matrix according to the time vector
+dosingmatrix = sortrows(dosingmatrix,1);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% For each input in dosing scheme get info about 
+% Tlag and the parameter
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+inputinfoadditional = [];
+for k=1:length(ds.inputs),
+    inputinfoadditional(k).input = ds.inputs(k).name; % unused but just to have it in there when looking at this structure
+    inputinfoadditional(k).index = k; % unused but just to have it in there when looking at this structure
+    try
+        inputinfoadditional(k).paramname = ds.inputs(k).parameters.name;
+        inputinfoadditional(k).param = ds.inputs(k).parameters.value;
+    catch
+        inputinfoadditional(k).paramname = {};
+        inputinfoadditional(k).param = [];
+    end
+    inputinfoadditional(k).Tlag = ds.inputs(k).Tlag;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% convert dosing matrix to structure
+% dosingevent.time
+% dosingevent.input.index
+% dosingevent.input.timeparname
+% dosingevent.input.parameternames
+% dosingevent.input.parametervalues
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+inputstruct = struct('index',{},'timeparname',{},'parameternames',{},'parametervalues',{});
+dosingevent = struct('time',{},'input',inputstruct);
+times = unique(dosingmatrix(:,1));
+for k=1:length(times),
+    % find dosings for current time
+    di = find(dosingmatrix(:,1)==times(k));
+    % add info to dosingevent structure
+    dosingevent(k).time = times(k);
+    for k2=1:length(di),
+        index = dosingmatrix(di(k2),3);
+        dosingevent(k).input(k2).index = index;
+        dosingevent(k).input(k2).timeparname = ['Time_' lower(inames{index})]; % Name definition used in mergemoddosSBPOP
+        % other parameters
+        parameternames = {};
+        parameternames{end+1} = ['Dose_' lower(inames{index})];
+        if ~isempty(inputinfoadditional(index).Tlag),
+            parameternames{end+1} = ['Tlag_' lower(inames{index})];
+        end
+        
+        if ~isempty(inputinfoadditional(index).paramname),
+            parameternames{end+1} = [inputinfoadditional(index).paramname '_' lower(inames{index})];
+        end
+
+        parametervalues = [];
+        parametervalues(end+1) = dosingmatrix(di(k2),2);
+        if ~isempty(inputinfoadditional(index).Tlag),
+            parametervalues(end+1) = inputinfoadditional(index).Tlag;
+        end
+
+        if ~isempty(inputinfoadditional(index).param),
+            timedoseinput = dosingevent(k).time;
+            timeINPUT = ds.inputs(dosingevent(k).input(k2).index).time;
+            paramvalueINPUT = ds.inputs(dosingevent(k).input(k2).index).parameters.value;
+            pvalue = paramvalueINPUT(timeINPUT==timedoseinput);
+            parametervalues(end+1) = pvalue;
+        end
+        
+        dosingevent(k).input(k2).parameternames = parameternames;
+        dosingevent(k).input(k2).parametervalues = parametervalues;
+    end
+end
+%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Return the result
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+doseeventstruct = dosingevent;
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/auxiliary/getmoddosinputinfoSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/auxiliary/getmoddosinputinfoSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..6f19bb602eca0654ae34fcb5c2a086691ef4e342
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/auxiliary/getmoddosinputinfoSBPOP.m
@@ -0,0 +1,116 @@
+function [inputinfo] = getmoddosinputinfoSBPOP(model,dosing)
+% getmoddosinputinfoSBPOP: Checks the availability of dosing input
+% definitions used in the model in the dosing object and returns a
+% structure similar to the "input" field structure of an SBmodel, augmented
+% with the dosing information, defined in the SBPOPdosing object.
+%
+% If the dosing object does not contain all inputs, required by the model,
+% a warning is displayed and the undefined inputs are deleted from the
+% "inputinfo" structure. This allows inputs in an SBmodel to be kept
+% undefined.
+%
+% USAGE:
+% ======
+% [inputinfo] = getmoddosinputinfoSBPOP(model,dosing) 
+%
+% model: SBmodel
+% dose: SBPOPdosing object
+%
+% Output Arguments:
+% =================
+% inputinfo: Same structure as defined in the SBmodel "input" field.
+%   Augmented by the dosing input information, stroed in the dosing object.
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBmodel(model),
+    error('First input argument is not an SBmodel.');
+end
+if ~isSBPOPdosing(dosing),
+    error('Second input argument is not an SBPOPdosing object.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get model and dosing structures
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ms = struct(model);
+ds = struct(dosing);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if model contains inputs.
+% If not => error!
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    
+if isempty(ms.inputs),
+    error('The model does not contain any inputs. Merging with dosing objects does not make sense.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Initialize the inputinfo structure
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+inputinfo = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run through all inputs, defined in the model 
+% and process the information in the dosing
+% object accordingly
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+minputs = ms.inputs;
+dinputs = ds.inputs;
+for k=1:length(minputs),
+    % First get the info stored in the model
+    minfo = minputs(k);
+    % Check if input exists in the dosing object
+    index = strmatchSB(minfo.name,{dinputs.name},'exact');
+    if ~isempty(index),
+        % Input does exist in the dosing object => Now add the complete
+        % input information to the inputinfo structure 
+        % Get the info for this input stored in the dosing object
+        dinfo = dinputs(index);
+        % Add dosing schedule information to the minfo structure
+        minfo.type = dinfo.type;
+        minfo.time = dinfo.time;
+        minfo.Tlag = dinfo.Tlag;
+        minfo.D = dinfo.D;
+        minfo.parameters = dinfo.parameters;
+        minfo.notes = dinfo.notes;
+        % Check if Tlag to be estimated
+        minfo.TlagNotes = dinfo.TlagNotes;
+        % Add minfo structure to the inputinfo output structure
+        if isempty(inputinfo),
+            inputinfo = minfo;
+        else
+            inputinfo(end+1) = minfo;
+        end
+    else
+        % Input does not exist in the dosing object => warning to user 
+        % and do not put it into the inputinfo structure
+%         disp(sprintf('The input ''%s'', defined in the model, is not defined in the SBPOPdosing object.',minfo.name));
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if any inputs of the models have been 
+% found in the dosing object. If not => error!
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    
+if isempty(inputinfo),
+    error('No inputs defined in the model could be found in the dosing object. This should be wrong ...')        
+end
+    
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/auxiliary/mergemoddosSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/auxiliary/mergemoddosSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..a6709ad4fe549154bebbf02407b4aa004b142fe2
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/auxiliary/mergemoddosSBPOP.m
@@ -0,0 +1,587 @@
+function [moddos,expdos] = mergemoddosSBPOP(model,dosing)
+% mergemoddosSBPOP: This function takes an SBmodel and an SBPOPdosing
+% scheme as inputs. It adds necessary elements to the model that are
+% required to implement the different dosing inputs (bolus, infusion,
+% absorption0, absorption1) for simulation purposes. MLXTRAN and
+% NONMEM will not be handled using this function. 
+%
+% The dose parameters are set to zero, independently of the dosing values
+% given in the dosing settings.
+%
+% The second output argument "expdos" is an experiment description,
+% which contains all state-events that are necessary to realize the dosing
+% applications defined in the dosing object. 
+%
+% USAGE:
+% ======
+% [moddos,expdos] = mergemoddosSBPOP(model,dosing) 
+%
+% model: SBmodel
+% dosing: SBPOPdosing object
+%
+% Output Arguments:
+% =================
+% moddos: SBmodel with added components to implement the different types of
+%  inputs.
+% expdos: SBexperiment containing all information to simulate the dosing
+%  schedule, defined in the SBPOP dosing object.
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBmodel(model),
+    error('First input argument is not an SBmodel.');
+end
+if ~isSBPOPdosing(dosing),
+    error('Second input argument is not an SBPOPdosing object.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get model, experiment and dosing structures
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ms = struct(model);
+ds = struct(dosing);
+mds = ms;               % initialize new model structure
+eds = struct(SBexperiment());
+eds.name = ds.name;
+eds.notes = ds.notes;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get the inputinfo structure
+% This structure contains now all necessary
+% information about all inputs that need to be 
+% implemented.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    
+inputinfo = getmoddosinputinfoSBPOP(model,dosing);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run through the inputinfo struct and modify the model
+% Additionally update the experiment structure ...
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(inputinfo),
+    % Handle the different types differently
+    switch inputinfo(k).type,
+        case 'BOLUS',
+            [mds,eds] = handleBolus(ms,mds,eds,inputinfo(k));
+        case 'INFUSION',
+            [mds,eds] = handleInfusion(ms,mds,eds,inputinfo(k));
+        case 'ABSORPTION1',
+            [mds,eds] = handleAbsorption1(ms,mds,eds,inputinfo(k));
+        case 'ABSORPTION0',
+            [mds,eds] = handleAbsorption0(ms,mds,eds,inputinfo(k));
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Delete the inputs implemented into the model
+% from the input field structure in the model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+removeInputIndex = [];
+for k=1:length(mds.inputs),
+    iname = mds.inputs(k).name;
+    % check if the name exists as parameter in the model (then dont remove it)
+    if isempty(strmatchSB(iname,{mds.parameters.name},'exact')),
+        % input parameter removed => remove input definition
+        removeInputIndex(end+1) = k;
+    end
+end
+if ~isempty(removeInputIndex),
+    mds.inputs(removeInputIndex) = [];
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Construct output model and experimet
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+moddos = SBmodel(mds);
+expdos = SBexperiment(eds);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Return
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% handle BOLUS input
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% also add dosing time and amount names to the inputinfo structure
+function [mds,eds] = handleBolus(ms,mds,eds,inputinfo)
+% Get input name
+iname = inputinfo.name;
+% Cycle through all input different input terms
+for k=1:length(inputinfo.terms),
+    % a) Determine the input variable name and other names to be used in the model
+    ivarname = getoutname(lower(iname), length(inputinfo.terms), k);
+    iDosename = ['Dose_' lower(iname)];
+    iTimename = ['Time_' lower(iname)];
+    iBolusTimename = ['DeltaT_' lower(iname)];
+    iTlagname = ['Tlag_' lower(iname)];
+    % b) Replace ODE INPUT definition with input variable
+    term = inputinfo.terms{k};
+    stateindex = inputinfo.stateindex(k);
+    ODE = mds.states(stateindex).ODE;
+    ODE = strrep(ODE,term,['+' ivarname]);
+    mds.states(stateindex).ODE = ODE;
+    % c) Create the input variable (differently, depending if Tlag is
+    % defined or not)
+    if ~isempty(inputinfo.Tlag),    
+        vformula = sprintf('%s*%s/%s * piecewiseSB(1,andSB(ge(time,%s+%s),lt(time,%s+%s+%s)),0)',inputinfo.factors{k},iDosename,iBolusTimename,iTimename,iTlagname,iTimename,iTlagname,iBolusTimename);
+    else
+        vformula = sprintf('%s*%s/%s * piecewiseSB(1,andSB(ge(time,%s),lt(time,%s+%s)),0)',inputinfo.factors{k},iDosename,iBolusTimename,iTimename,iTimename,iBolusTimename);
+    end        
+    % d) Add the variable to the moddos model
+    mds.variables(end+1).name = ivarname;
+    mds.variables(end).formula = vformula;
+    mds.variables(end).type = '';
+    mds.variables(end).compartment = '';
+    mds.variables(end).unittype = '';
+    mds.variables(end).notes = sprintf(' Input variable realizing ''%s'' on state ''%s'' (BOLUS).',iname,ms.states(stateindex).name);
+    % e) Remove the INPUT* parameter (will change the parindex fields but
+    % doesn't matter, since this input parameters are not used anymore ...
+    % if a dosing input is defined for this INPUT* element).
+    index = strmatchSB(iname,{mds.parameters.name},'exact');
+    mds.parameters(index) = [];
+    % f) Need to define an initial set of parameters used in the vformula.
+    % Single dosing events can be implemented in this way. In the case of
+    % multiple dosing events only the first will be implemented in the
+    % model. The remaining ones will be handled using an outside loop in a
+    % higher level function.
+    if k==1,    % only add Dose and Time parameters once! (also the bolus deltaT)
+        % Dose
+        mds.parameters(end+1).name = iDosename;
+        mds.parameters(end).value = 0; %inputinfo.D(1);
+        mds.parameters(end).type = '';
+        mds.parameters(end).compartment = '';
+        mds.parameters(end).unittype = '';
+        mds.parameters(end).notes = sprintf(' Dose amount for INPUT ''%s'' (BOLUS).', iname);
+        % Time
+        mds.parameters(end+1).name = iTimename;
+        mds.parameters(end).value = inputinfo.time(1);
+        mds.parameters(end).type = '';
+        mds.parameters(end).compartment = '';
+        mds.parameters(end).unittype = '';
+        mds.parameters(end).notes = sprintf(' Dosing instant for INPUT ''%s'' (BOLUS).', iname);
+        % iBolusTimename
+        mds.parameters(end+1).name = iBolusTimename;
+        mds.parameters(end).value = 0.0001; % Assume 1e-4 of time units (should be fast enough to realistically implement a BOLUS)
+        mds.parameters(end).type = '';
+        mds.parameters(end).compartment = '';
+        mds.parameters(end).unittype = '';
+        mds.parameters(end).notes = sprintf(' Very small dosing duration for INPUT ''%s'' (BOLUS).', iname);
+        % Tlag (only if defined in dosing schedule)
+        if ~isempty(inputinfo.Tlag),
+            mds.parameters(end+1).name = iTlagname;
+            mds.parameters(end).value = inputinfo.Tlag;
+            mds.parameters(end).type = '';
+            mds.parameters(end).compartment = '';
+            mds.parameters(end).unittype = '';
+            mds.parameters(end).notes = sprintf('%s Dosing lag time, used in variable ''%s'' (BOLUS).',inputinfo.TlagNotes,ivarname);
+        end
+        % Add the necessary information to the experiment structure (only time
+        % and dosing amounts can change between subsequent dosing instants
+[eds] = buildexpstruct(eds,iDosename,iTimename,iTlagname,inputinfo,iname,'',[]);
+    end
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% handle Infusion input
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% also add dosing time and amount names to the inputinfo structure
+function [mds,eds] = handleInfusion(ms,mds,eds,inputinfo)
+% Get input name
+iname = inputinfo.name;
+% Cycle through all input different input terms
+for k=1:length(inputinfo.terms),
+    % Check if infusion time or infusion rate
+    paramname = inputinfo.parameters.name;
+    if strcmp(paramname,'Tinf'),
+        TinfFlag = 1;
+    else
+        TinfFlag = 0;
+    end
+    % a) Determine the input variable name and other names to be used in the model
+    ivarname = getoutname(lower(iname), length(inputinfo.terms), k);
+    iDosename = ['Dose_' lower(iname)];
+    if TinfFlag,
+        iParamNameInfusion = ['Tinf_' lower(iname)];
+    else
+        iParamNameInfusion = ['Rate_' lower(iname)];
+    end
+    iTimename = ['Time_' lower(iname)];
+    iTlagname = ['Tlag_' lower(iname)];
+    % b) Replace ODE INPUT definition with input variable
+    term = inputinfo.terms{k};
+    stateindex = inputinfo.stateindex(k);
+    ODE = mds.states(stateindex).ODE;
+    ODE = strrep(ODE,term,['+' ivarname]);
+    mds.states(stateindex).ODE = ODE;
+    % c) Create the input variable (differently, depending if Tlag is
+    % defined or not)
+    if TinfFlag,
+        % Implement infusion time
+        if ~isempty(inputinfo.Tlag),
+            vformula = sprintf('%s*%s/%s * piecewiseSB(1,andSB(ge(time,%s+%s),lt(time,%s+%s+%s)),0)',inputinfo.factors{k},iDosename,iParamNameInfusion,iTimename,iTlagname,iTimename,iTlagname,iParamNameInfusion);
+        else
+            vformula = sprintf('%s*%s/%s * piecewiseSB(1,andSB(ge(time,%s),lt(time,%s+%s)),0)',inputinfo.factors{k},iDosename,iParamNameInfusion,iTimename,iTimename,iParamNameInfusion);
+        end
+    else
+        % Implement infusion Rate
+        if ~isempty(inputinfo.Tlag),
+            vformula = sprintf('%s*%s * piecewiseSB(1,andSB(ge(time,%s+%s),lt(time,%s+%s+%s/%s)),0)',inputinfo.factors{k},iParamNameInfusion,iTimename,iTlagname,iTimename,iTlagname,iDosename,iParamNameInfusion);
+        else
+            vformula = sprintf('%s*%s * piecewiseSB(1,andSB(ge(time,%s),lt(time,%s+%s/%s)),0)',inputinfo.factors{k},iParamNameInfusion,iTimename,iTimename,iDosename,iParamNameInfusion);
+        end
+    end
+    % d) Add the variable to the moddos model
+    mds.variables(end+1).name = ivarname;
+    mds.variables(end).formula = vformula;
+    mds.variables(end).type = '';
+    mds.variables(end).compartment = '';
+    mds.variables(end).unittype = '';
+    mds.variables(end).notes = sprintf(' Input variable realizing ''%s'' on state ''%s'' (INFUSION).',iname,ms.states(stateindex).name);
+    % e) Remove the INPUT* parameter (will change the parindex fields but
+    % doesn't matter, since this input parameters are not used anymore ...
+    % if a dosing input is defined for this INPUT* element).
+    index = strmatchSB(iname,{mds.parameters.name},'exact');
+    mds.parameters(index) = [];
+    % f) Need to define an initial set of parameters used in the vformula.
+    % Single dosing events can be implemented in this way. In the case of
+    % multiple dosing events the parameters will be changed using events.
+    if k==1,    % only add Dose and Time parameters once!
+        % Dose
+        mds.parameters(end+1).name = iDosename;
+        mds.parameters(end).value = 0;%inputinfo.D(1);
+        mds.parameters(end).type = '';
+        mds.parameters(end).compartment = '';
+        mds.parameters(end).unittype = '';
+        mds.parameters(end).notes = sprintf(' Dose amount for INPUT ''%s'' (INFUSION).', iname);
+        % Time
+        mds.parameters(end+1).name = iTimename;
+        mds.parameters(end).value = inputinfo.time(1);
+        mds.parameters(end).type = '';
+        mds.parameters(end).compartment = '';
+        mds.parameters(end).unittype = '';
+        mds.parameters(end).notes = sprintf(' Dosing instant for INPUT ''%s'' (INFUSION).', iname);
+        % Rate
+        mds.parameters(end+1).name = iParamNameInfusion;
+        mds.parameters(end).value = inputinfo.parameters(1).value(1);
+        mds.parameters(end).type = '';
+        mds.parameters(end).compartment = '';
+        mds.parameters(end).unittype = '';
+        if TinfFlag,
+            mds.parameters(end).notes = sprintf(' Dosing infusion time, used in variable ''%s'' (INFUSION).', ivarname);
+        else
+            mds.parameters(end).notes = sprintf(' Dosing infusion rate, used in variable ''%s'' (INFUSION).', ivarname);
+        end
+        % Tlag (only if defined in dosing schedule)
+        if ~isempty(inputinfo.Tlag),
+            mds.parameters(end+1).name = iTlagname;
+            mds.parameters(end).value = inputinfo.Tlag;
+            mds.parameters(end).type = '';
+            mds.parameters(end).compartment = '';
+            mds.parameters(end).unittype = '';
+            mds.parameters(end).notes = sprintf('%s Dosing lag time, used in variable ''%s'' (INFUSION).',inputinfo.TlagNotes,ivarname);
+        end
+        % Add the necessary information to the experiment structure (only time
+        % and dosing amounts can change between subsequent dosing instants
+[eds] = buildexpstruct(eds,iDosename,iTimename,iTlagname,inputinfo,iname,iParamNameInfusion,inputinfo.parameters(1).value);
+%         % Additionally set the Rate/Tinf parameter in the experiment
+%         eds = addparamicsetting(eds,iParamNameInfusion,num2str(inputinfo.parameters(1).value),0,'');
+    end
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% handle Absorption1 input
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% also add dosing time and amount names to the inputinfo structure
+function [mds,eds] = handleAbsorption1(ms,mds,eds,inputinfo)
+% Get input name
+iname = inputinfo.name;
+% Cycle through all input different input terms
+for k=1:length(inputinfo.terms),
+    % a) Determine the input variable name and other names to be used in the model
+    ivarname = getoutname(lower(iname), length(inputinfo.terms), k);
+    iCompname = ['Comp_' ivarname];
+    iabsorptvarname =['vAbsorption_' ivarname];
+    iDosename = ['Dose_' lower(iname)];
+    iTimename = ['Time_' lower(iname)];
+    iBolusTimename = ['DeltaT_' lower(iname)];    
+
+    iKaname   = ['ka_' lower(iname)];
+    iTlagname = ['Tlag_' lower(iname)];
+    
+    % b) Replace ODE INPUT definition with ABSORPTION input variable
+    % (difference to all the other dosing application types).
+    term = inputinfo.terms{k};
+    stateindex = inputinfo.stateindex(k);
+    ODE = mds.states(stateindex).ODE;
+    ODE = strrep(ODE,term,['+' iabsorptvarname]);
+    mds.states(stateindex).ODE = ODE;
+    % c) Add a dosing compartment for the ABSORPTION1 input
+    mds.states(end+1).name = iCompname;
+    mds.states(end).initialCondition = 0;
+    mds.states(end).ODE = [ivarname '-' iabsorptvarname];
+    mds.states(end).type = '';
+    mds.states(end).compartment = '';
+    mds.states(end).unittype = '';
+    mds.states(end).notes = sprintf(' Dosing compartment for input ''%s'' (ABSORPTION1).',iname);
+    % d) Add a variable to define the absorption equation
+    mds.variables(end+1).name = iabsorptvarname;
+    mds.variables(end).formula = [iKaname '*' iCompname];
+    mds.variables(end).type = '';
+    mds.variables(end).compartment = '';
+    mds.variables(end).unittype = '';
+    mds.variables(end).notes = sprintf(' Absorption rate for input ''%s'' (ABSORPTION1).',iname);
+    % e) Create the input variable for application of the bolus to the
+    % dosing compartment (use same approach as for BOLUS applications, this
+    % means, a small application time of 0.0001).
+    if ~isempty(inputinfo.Tlag),    
+        vformula = sprintf('%s*%s/%s * piecewiseSB(1,andSB(ge(time,%s+%s),lt(time,%s+%s+%s)),0)',inputinfo.factors{k},iDosename,iBolusTimename,iTimename,iTlagname,iTimename,iTlagname,iBolusTimename);
+    else
+        vformula = sprintf('%s*%s/%s * piecewiseSB(1,andSB(ge(time,%s),lt(time,%s+%s)),0)',inputinfo.factors{k},iDosename,iBolusTimename,iTimename,iTimename,iBolusTimename);
+    end        
+    % f) Add the variable to the moddos model
+    mds.variables(end+1).name = ivarname;
+    mds.variables(end).formula = vformula;
+    mds.variables(end).type = '';
+    mds.variables(end).compartment = '';
+    mds.variables(end).unittype = '';
+    mds.variables(end).notes = sprintf(' Input variable realizing a BOLUS on state ''%s'', implementing input ''%s'' (ABSORPTION1).',iCompname,iname);
+    % f) Remove the INPUT* parameter (will change the parindex fields but
+    % doesn't matter, since this input parameters are not used anymore ...
+    % if a dosing input is defined for this INPUT* element).
+    index = strmatchSB(iname,{mds.parameters.name},'exact');
+    mds.parameters(index) = [];
+    % f) Need to define an initial set of parameters used in the vformula.
+    % Single dosing events can be implemented in this way. In the case of
+    % multiple dosing events only the first will be implemented in the
+    % model. The remaining ones will be handled using an outside loop in a
+    % higher level function.
+    if k==1,    % only add Dose and Time parameters once! also bolus deltaT
+        % Dose
+        mds.parameters(end+1).name = iDosename;
+        mds.parameters(end).value = 0;%inputinfo.D(1);
+        mds.parameters(end).type = '';
+        mds.parameters(end).compartment = '';
+        mds.parameters(end).unittype = '';
+        mds.parameters(end).notes = sprintf(' Dose amount for INPUT ''%s'' (ABSORPTION1).', iname);
+        % Time
+        mds.parameters(end+1).name = iTimename;
+        mds.parameters(end).value = inputinfo.time(1);
+        mds.parameters(end).type = '';
+        mds.parameters(end).compartment = '';
+        mds.parameters(end).unittype = '';
+        mds.parameters(end).notes = sprintf(' Dosing instant for INPUT ''%s'' (ABSORPTION1).', iname);
+        % iBolusTimename
+        mds.parameters(end+1).name = iBolusTimename;
+        mds.parameters(end).value = 0.0001; % Assume 1e-4 of time units (should be fast enough to realistically implement a BOLUS)
+        mds.parameters(end).type = '';
+        mds.parameters(end).compartment = '';
+        mds.parameters(end).unittype = '';
+        mds.parameters(end).notes = sprintf(' Very small dosing duration (implementing a BOLUS into dosing compartment) for INPUT ''%s'' (ABSORPTION1).', iname);
+        % Ka
+        mds.parameters(end+1).name = iKaname;
+        mds.parameters(end).value = inputinfo.parameters(1).value(1);
+        mds.parameters(end).type = '';
+        mds.parameters(end).compartment = '';
+        mds.parameters(end).unittype = '';
+        mds.parameters(end).notes = sprintf(' Dose absorption rate constant, used in variable ''%s'' (ABSORPTION1).', iabsorptvarname);
+        % Tlag (only if defined in dosing schedule)
+        if ~isempty(inputinfo.Tlag),
+            mds.parameters(end+1).name = iTlagname;
+            mds.parameters(end).value = inputinfo.Tlag;
+            mds.parameters(end).type = '';
+            mds.parameters(end).compartment = '';
+            mds.parameters(end).unittype = '';
+            mds.parameters(end).notes = sprintf('%s Dosing lag time, used in variable ''%s'' (ABSORPTION1).',inputinfo.TlagNotes,ivarname);
+        end
+        % Add the necessary information to the experiment structure (only time
+        % and dosing amounts can change between subsequent dosing instants
+[eds] = buildexpstruct(eds,iDosename,iTimename,iTlagname,inputinfo,iname,iKaname,inputinfo.parameters(1).value);
+%         % Additionally set the ka rate parameters in the experiment
+%         eds = addparamicsetting(eds,iKaname,num2str(inputinfo.parameters(1).value),0,'');
+    end
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% handle Absorption0 input
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% also add dosing time and amount names to the inputinfo structure
+function [mds,eds] = handleAbsorption0(ms,mds,eds,inputinfo)
+% Get input name
+iname = inputinfo.name;
+% Cycle through all input different input terms
+for k=1:length(inputinfo.terms),
+    % a) Determine the input variable name and other names to be used in the model
+    ivarname = getoutname(lower(iname), length(inputinfo.terms), k);
+    iDosename = ['Dose_' lower(iname)];
+    iTimename = ['Time_' lower(iname)];
+    iTk0name = ['Tk0_' lower(iname)];
+    iTlagname = ['Tlag_' lower(iname)];
+    % b) Replace ODE INPUT definition with input variable
+    term = inputinfo.terms{k};
+    stateindex = inputinfo.stateindex(k);
+    ODE = mds.states(stateindex).ODE;
+    ODE = strrep(ODE,term,['+' ivarname]);
+    mds.states(stateindex).ODE = ODE;
+    % c) Create the input variable (differently, depending if Tlag is
+    % defined or not)
+    if ~isempty(inputinfo.Tlag),    
+        vformula = sprintf('%s*%s/%s * piecewiseSB(1,andSB(ge(time,%s+%s),lt(time,%s+%s+%s)),0)',inputinfo.factors{k},iDosename,iTk0name,iTimename,iTlagname,iTimename,iTlagname,iTk0name);
+    else
+        vformula = sprintf('%s*%s/%s * piecewiseSB(1,andSB(ge(time,%s),lt(time,%s+%s)),0)',inputinfo.factors{k},iDosename,iTk0name,iTimename,iTimename,iTk0name);
+    end        
+    % d) Add the variable to the moddos model
+    mds.variables(end+1).name = ivarname;
+    mds.variables(end).formula = vformula;
+    mds.variables(end).type = '';
+    mds.variables(end).compartment = '';
+    mds.variables(end).unittype = '';
+    mds.variables(end).notes = sprintf(' Input variable realizing ''%s'' on state ''%s'' (ABSORPTION0).',iname,ms.states(stateindex).name);
+    % e) Remove the INPUT* parameter (will change the parindex fields but
+    % doesn't matter, since this input parameters are not used anymore ...
+    % if a dosing input is defined for this INPUT* element).
+    index = strmatchSB(iname,{mds.parameters.name},'exact');
+    mds.parameters(index) = [];
+    % f) Need to define an initial set of parameters used in the vformula.
+    % Single dosing events can be implemented in this way. In the case of
+    % multiple dosing events only the first will be implemented in the
+    % model. The remaining ones will be handled using an outside loop in a
+    % higher level function.
+    if k==1,    % only add Dose and Time parameters once!
+        % Dose
+        mds.parameters(end+1).name = iDosename;
+        mds.parameters(end).value = 0;%inputinfo.D(1);
+        mds.parameters(end).type = '';
+        mds.parameters(end).compartment = '';
+        mds.parameters(end).unittype = '';
+        mds.parameters(end).notes = sprintf(' Dose amount for INPUT ''%s'' (ABSORPTION0).', iname);
+        % Time
+        mds.parameters(end+1).name = iTimename;
+        mds.parameters(end).value = inputinfo.time(1);
+        mds.parameters(end).type = '';
+        mds.parameters(end).compartment = '';
+        mds.parameters(end).unittype = '';
+        mds.parameters(end).notes = sprintf(' Dosing instant for INPUT ''%s'' (ABSORPTION0).', iname);
+        % Tk0
+        mds.parameters(end+1).name = iTk0name;
+        mds.parameters(end).value = inputinfo.parameters(1).value(1);
+        mds.parameters(end).type = '';
+        mds.parameters(end).compartment = '';
+        mds.parameters(end).unittype = '';
+        mds.parameters(end).notes = sprintf(' Dosing duration, used in variable ''%s'' (ABSORPTION0).', ivarname);
+        % Tlag (only if defined in dosing schedule)
+        if ~isempty(inputinfo.Tlag),
+            mds.parameters(end+1).name = iTlagname;
+            mds.parameters(end).value = inputinfo.Tlag;
+            mds.parameters(end).type = '';
+            mds.parameters(end).compartment = '';
+            mds.parameters(end).unittype = '';
+            mds.parameters(end).notes = sprintf('%s Dosing lag time, used in variable ''%s'' (ABSORPTION0).',inputinfo.TlagNotes,ivarname);
+        end
+        % Add the necessary information to the experiment structure (only time
+        % and dosing amounts can change between subsequent dosing instants
+[eds] = buildexpstruct(eds,iDosename,iTimename,iTlagname,inputinfo,ivarname,iTk0name,inputinfo.parameters(1).value);
+%         % Additionally set the ka rate parameters in the experiment
+%         eds = addparamicsetting(eds,iTk0name,num2str(inputinfo.parameters(1).value),0,'');
+    end
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% help function to get right names
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function outname = getoutname(base, kmax, k)
+if kmax == 1,
+    outname = base;
+else
+    outname = [base '_' sprintf('%d',k)];
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle the experiment description for simulation
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% The first dosing instant is going to be put into the parameter and ic
+% settings section (same as already in the model). The subsequent
+% dosings in case of multiple doses is put into the event section.
+% parameter section. This function is the same for all dosing types. So no
+% need to write it 4 times.
+function [eds] = buildexpstruct(eds,iDosename,iTimename,iTlagname,inputinfo,ivarname,iParName,iParValue)
+eds = addparamicsetting(eds,iDosename,num2str(inputinfo.D(1)),0,'');
+eds = addparamicsetting(eds,iTimename,num2str(inputinfo.time(1)),0,'');
+% Same with the additional dosing parameter if defined
+if ~isempty(iParName),
+    eds = addparamicsetting(eds,iParName,num2str(iParValue(1)),0,'');
+end
+
+% Tlag (only if defined in dosing schedule) added for each input instant
+if ~isempty(inputinfo.Tlag),
+    eds = addparamicsetting(eds,iTlagname,num2str(inputinfo.Tlag),0,'');
+end
+
+% subsequent dosings in the events (Time and Dose needs to be
+% updated by events and also the dosing parameter, if defined)
+if length(inputinfo.time) > 1,
+    % multiple dosings => get time vector and dose vector (without
+    % first dosing instance)
+    timevec = inputinfo.time(2:end);
+    Dvec = inputinfo.D(2:end);
+    if ~isempty(iParValue),
+        parvec = iParValue(2:end);
+    else
+        parvec = [];
+    end
+    for k2=1:length(timevec),
+        % add the events
+        name = sprintf('%s_event_%d',ivarname,k2);
+        if ~isempty(parvec),
+            eds = addstateevent(eds,name,timevec(k2),{iDosename,iTimename,iParName},{num2str(Dvec(k2)),num2str(timevec(k2)),num2str(parvec(k2))},'');
+        else
+            eds = addstateevent(eds,name,timevec(k2),{iDosename,iTimename},{num2str(Dvec(k2)),num2str(timevec(k2))},'');
+        end            
+    end
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% add parameter or ic to experiment
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [eds] = addparamicsetting(eds,name,formula,icflag,notes)
+    eds.paramicsettings(end+1).name = name;
+    eds.paramicsettings(end).formula = formula;
+    eds.paramicsettings(end).icflag = icflag;
+    eds.paramicsettings(end).notes = notes;
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% add stateevents to experiment
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [eds] = addstateevent(eds,name,time,compnames,compformulas,notes)
+    eds.stateevents(end+1).name = name;
+    eds.stateevents(end).trigger = ['ge(time,' num2str(time) ')'];
+    for k=1:length(compnames),
+        eds.stateevents(end).assignment(k).variable = compnames{k};
+        eds.stateevents(end).assignment(k).formula = compformulas{k};
+    end
+    eds.stateevents(end).notes = notes;
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/auxiliary/sbpopdose2text/convertDosToTextSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/auxiliary/sbpopdose2text/convertDosToTextSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..ba3d00f9f31e531d1d9391b8c6e4d1e3343c5e10
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/auxiliary/sbpopdose2text/convertDosToTextSBPOP.m
@@ -0,0 +1,91 @@
+function [dosTextStructure] = convertDosToTextSBPOP(dos)
+% convertDosToTextSBPOP: Converts an SBPOPdosing object to a structure
+% containing the different parts of the text description of the dosing
+% scheme.
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+% Initialize variables
+dosTextStructure = [];
+% Get SBstructure
+ds = SBPOPstruct(dos);
+% Parse structure into the dosTextStructure description
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Name
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dosTextStructure.name = ds.name;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Notes
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dosTextStructure.notes = ds.notes;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Inputs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dosTextStructure.inputs = {};
+allInputText = {};
+for k=1:length(ds.inputs),
+    inputText = '';
+    input = ds.inputs(k);
+    % Write the limiter (name)
+    inputText = sprintf('********** %s\n',input.name);
+    % Type
+    inputText = sprintf('%stype:         %s\n',inputText,input.type);
+    % Time
+    if length(input.time) == 1,
+        inputText = sprintf('%stime:         %g\n',inputText,input.time);
+    else
+        timeText = sprintf('%g, ',input.time);
+        inputText = sprintf('%stime:         [%s]\n',inputText,timeText(1:end-2));
+    end
+    % Tlag (write only if non-zero)
+    if input.Tlag ~= 0,
+        if isempty(input.TlagNotes),
+            inputText = sprintf('%sTlag:         %g\n',inputText,input.Tlag);
+        else
+            inputText = sprintf('%sTlag:         %g    %% %s\n',inputText,input.Tlag,input.TlagNotes);
+        end
+    end
+    % D
+    if length(input.D) == 1,
+        inputText = sprintf('%sD:            %g\n',inputText,input.D);
+    else
+        doseText = sprintf('%g, ',input.D);
+        inputText = sprintf('%sD:            [%s]\n',inputText,doseText(1:end-2));
+    end
+    % parameters
+    if ~isempty(input.parameters),
+        for k2=1:length(input.parameters),
+            parametersValueText = sprintf('%g, ',input.parameters(k2).value);
+            if isempty(input.parameters(k2).notes),
+                inputText = sprintf('%s%s:%s[%s]\n',inputText,input.parameters(k2).name,char(32*ones(1,14-length(input.parameters(k2).name)-1)),parametersValueText(1:end-2));
+            else
+                inputText = sprintf('%s%s:%s[%s]    %% %s\n',inputText,input.parameters(k2).name,char(32*ones(1,14-length(input.parameters(k2).name)-1)),parametersValueText(1:end-2),input.parameters(k2).notes);
+            end
+        end
+    end
+    % notes
+    if ~isempty(input.notes),
+        inputText = sprintf('%snotes:        %s\n',inputText,input.notes);
+    end
+    % save text
+    dosTextStructure.inputs{k} = inputText;
+end
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/auxiliary/sbpopdose2text/setPartsToCompleteTextDosSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/auxiliary/sbpopdose2text/setPartsToCompleteTextDosSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..a737663a74df9d16e92922fa55cc451cf9eeb36b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/auxiliary/sbpopdose2text/setPartsToCompleteTextDosSBPOP.m
@@ -0,0 +1,82 @@
+function [completeText] = setPartsToCompleteTextDosSBPOP(dosTextStructure)
+% setPartsToCompleteTextDosSBPOP: Sets the different parts of a dosing 
+% scheme description of an SBdosing object together to the complete text
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+completeText = sprintf('********** DOSING NAME\n%s\n\n',dosTextStructure.name);
+completeText = sprintf('%s********** DOSING NOTES\n%s\n\n',completeText,dosTextStructure.notes);
+if ~isempty(dosTextStructure.inputs),
+    for k=1:length(dosTextStructure.inputs),
+        completeText = sprintf('%s%s\n',completeText,dosTextStructure.inputs{k});
+    end
+else
+    % If no inputs defined in the structure then print out a guideline on
+    % how to represent the different type of input.
+    completeText = sprintf('%s********** INPUT1\n',completeText);
+    completeText = sprintf('%s%%%% Data required to define an Bolus (single, multiple)\n',completeText);
+    completeText = sprintf('%s%%type: BOLUS\n',completeText);
+    completeText = sprintf('%s%%notes:              %% (optional)\n',completeText);
+    completeText = sprintf('%s%%time:               %% time for first application or all applications (scalar or vector)\n',completeText);
+    completeText = sprintf('%s%%deltaT:             %% time inbetween applications (only if time scalar)\n',completeText);
+    completeText = sprintf('%s%%nr_repetitions:  	%% number of applications (only if time scalar + optional if time scalar)\n',completeText);
+    completeText = sprintf('%s%%D:                  %% dose (scalar or vector)\n',completeText);
+    completeText = sprintf('%s%%Tlag:               %% lag time for input application (optional). Default: 0\n',completeText);
+    completeText = sprintf('%s\n',completeText);
+    completeText = sprintf('%s%%%% Data required to define an Infusion (with infusion rate as parameter) (single, multiple)\n',completeText);
+    completeText = sprintf('%s%%type: INFUSION\n',completeText);
+    completeText = sprintf('%s%%notes:              %% (optional)\n',completeText);
+    completeText = sprintf('%s%%time:               %% time for first application or all applications (scalar or vector)\n',completeText);
+    completeText = sprintf('%s%%deltaT:             %% time inbetween applications (only if time scalar)\n',completeText);
+    completeText = sprintf('%s%%nr_repetitions: 	%% number of applications (only if time scalar + optional if time scalar)\n',completeText);
+    completeText = sprintf('%s%%D:                  %% dose (scalar or vector)\n',completeText);
+    completeText = sprintf('%s%%Rate:               %% Infusion rate (required)\n',completeText);
+    completeText = sprintf('%s%%Tlag:               %% lag time for input application (optional). Default: 0\n',completeText);
+    completeText = sprintf('%s\n',completeText);
+    completeText = sprintf('%s%%%% ALTERNATIVE: Data required to define an Infusion (with infusion time as parameter) (single, multiple)\n',completeText);
+    completeText = sprintf('%s%%type: INFUSION\n',completeText);
+    completeText = sprintf('%s%%notes:              %% (optional)\n',completeText);
+    completeText = sprintf('%s%%time:               %% time for first application or all applications (scalar or vector)\n',completeText);
+    completeText = sprintf('%s%%deltaT:             %% time inbetween applications (only if time scalar)\n',completeText);
+    completeText = sprintf('%s%%nr_repetitions: 	%% number of applications (only if time scalar + optional if time scalar)\n',completeText);
+    completeText = sprintf('%s%%D:                  %% dose (scalar or vector)\n',completeText);
+    completeText = sprintf('%s%%Tinf:               %% Infusion time (required)\n',completeText);
+    completeText = sprintf('%s%%Tlag:               %% lag time for input application (optional). Default: 0\n',completeText);
+    completeText = sprintf('%s\n',completeText);
+    completeText = sprintf('%s%%%% Data required to define a 1st order absorption (single, multiple)\n',completeText);
+    completeText = sprintf('%s%%type: ABSORPTION1\n',completeText);
+    completeText = sprintf('%s%%notes:              %% (optional)\n',completeText);
+    completeText = sprintf('%s%%time:               %% time for first application or all applications (scalar or vector)\n',completeText);
+    completeText = sprintf('%s%%deltaT:             %% time inbetween applications (only if time scalar)\n',completeText);
+    completeText = sprintf('%s%%nr_repetitions: 	%% number of applications (only if time scalar + optional if time scalar)\n',completeText);
+    completeText = sprintf('%s%%D:                  %% dose (scalar or vector)\n',completeText);
+    completeText = sprintf('%s%%ka:                 %% Absorption rate constant (required)\n',completeText);
+    completeText = sprintf('%s%%Tlag:               %% lag time for input application (optional). Default: 0\n',completeText);
+    completeText = sprintf('%s\n',completeText);
+    completeText = sprintf('%s%%%% Data required to define a 0th order absorption (single, multiple)\n',completeText);
+    completeText = sprintf('%s%%type: ABSORPTION0\n',completeText);
+    completeText = sprintf('%s%%notes:              %% (optional)\n',completeText);
+    completeText = sprintf('%s%%time:               %% time for first application or all applications (scalar or vector)\n',completeText);
+    completeText = sprintf('%s%%deltaT:             %% time inbetween applications (only if time scalar)\n',completeText);
+    completeText = sprintf('%s%%nr_repetitions: 	%% number of applications (only if time scalar + optional if time scalar)\n',completeText);
+    completeText = sprintf('%s%%D:                  %% dose (scalar or vector)\n',completeText);
+    completeText = sprintf('%s%%Tk0:                %% time for absorption (required)\n',completeText);
+    completeText = sprintf('%s%%Tlag:               %% lag time for input application (optional). Default: 0\n',completeText);
+    completeText = sprintf('%s\n',completeText);
+end
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/auxiliary/text2sbpopdose/convertTextToDosSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/auxiliary/text2sbpopdose/convertTextToDosSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..4e2c490480bf8f5331dfbc23bd004ac97b6ea4bf
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/auxiliary/text2sbpopdose/convertTextToDosSBPOP.m
@@ -0,0 +1,399 @@
+function [SBstructure,errorMsg] = convertTextToDosSBPOP(dosText)
+% convertTextToDosSBPOP: Converts a text description of an SBPOPdosing
+% object to the internal SBPOPdosing data structure representation.
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+% % initialize variables
+errorMsg = '';
+% errorConditions = '';
+% errorParameterChanges = '';
+% errorStateEvents = '';
+SBstructure = [];
+
+% cut text into pieces
+dosTextStructure = getPartsFromCompleteTextDosSBPOP(dosText);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%% Initialize structure
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBstructure = struct(SBPOPdosing());
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%% Name
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBstructure.name = strtrim(removeCharacters(dosTextStructure.name));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%% Notes
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBstructure.notes = strtrim(dosTextStructure.notes);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%% READ INPUTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% 0) create empty input structure
+parametersStruct = struct('name',{},'value',{},'notes',{});
+inputStruct = struct('name',{},'type',{},'time',{},'Tlag',{},'D',{},'parameters',parametersStruct,'TlagNotes',{},'notes',{});
+inputfieldnames = fieldnames(inputStruct);
+timeDefStruct = struct('deltaT',{},'nr_repetitions',{});
+for k=1:length(dosTextStructure.input),
+    inputText = dosTextStructure.input{k};
+    % all data for an input is organized in rows. each row holds a
+    % statement. statements over several rows are NOT allowed.
+    % ordering is arbitrary except that the name (INPUTx) will always be in
+    % the first row. all other rows have an identifier followed by a colon
+    % followed by a value.
+    % 1) split text in rows
+    rows = explodePCSB(inputText,char(10));
+    % 2) INPUT name (check that "INPUT" is present)
+    if isempty(regexp(rows{1},'INPUT', 'once' )),
+        error('Please check input dose definitions. An "INPUTx" identifier seems to be corrupted.');
+    end
+    % 3) add name to struct
+    inputStruct(k).name = strtrim(rows{1});
+    % 3b) Initialize Tlag with default empty value
+    inputStruct(k).Tlag = [];   % if undefined then leave empty!!!   
+    % 4) add the rest (if row identifier equal to a input field ... add it
+    % there, otherwise add it as a parameter).
+    nr_repetitions = [];
+    deltaT = [];
+    for k2=2:length(rows),
+        % check if row is empty dont consider it
+        if ~isempty(strtrim(rows{k2})),
+            % cut of everything from first percentage sign on (comment)
+            % comment is saved since used for the additional parameters
+            % (Rate, Tk0, ka)
+            commentindex = strfind(rows{k2},'%');
+            if ~isempty(commentindex),
+                savenotes = strtrim(rows{k2}(commentindex(1)+1:end));
+                rows{k2} = strtrim(rows{k2}(1:commentindex(1)-1));
+            else
+                savenotes = '';
+            end
+            % find first colon (if no colon then error
+            colonindex = strfind(rows{k2},':');
+            if isempty(colonindex),
+                error('Syntax error in dose description. No colon in a row for input "%s".',inputStruct(k).name);
+            end
+            % get identifier and value
+            identifier = strtrim(rows{k2}(1:colonindex-1));
+            valuetry = strtrim(rows{k2}(colonindex+1:end));
+            % evaluate the value (matlab notation allowed e.g. for vectors)
+            % need to try and catch, since some values are strings :)
+            try
+                value = eval(valuetry);
+            catch
+                value = valuetry;
+            end
+            % Add value to field if identifier is fieldname
+            if ~isempty(strmatchSB(identifier,inputfieldnames)),
+                inputStruct(k) = setfield(inputStruct(k),identifier,value);
+                if strcmp(identifier,'Tlag'),
+                    inputStruct(k).TlagNotes = savenotes;
+                end
+            else
+                % handle nr_repetitions and deltaT here
+                if strcmp(identifier,'nr_repetitions'),
+                    nr_repetitions = value;
+                elseif strcmp(identifier,'deltaT'),
+                    deltaT = value;
+                else
+                    % remaining non-field identifiers become parameters for the
+                    % input to be handled later.
+                    inputStruct(k).parameters(end+1).name = identifier;
+                    inputStruct(k).parameters(end).value = value;
+                    inputStruct(k).parameters(end).notes = savenotes;
+                end
+            end                
+        end
+    end
+    % store deltaT and nr_repetitions information to be used in check
+    timeDefStruct(k).deltaT = deltaT;
+    timeDefStruct(k).nr_repetitions = nr_repetitions;
+end
+SBstructure.inputs = inputStruct;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%% CHECK INPUTS for consistency
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(SBstructure.inputs),
+    input = SBstructure.inputs(k);
+    deltaT = timeDefStruct(k).deltaT;
+    nr_repetitions = timeDefStruct(k).nr_repetitions;
+   
+    % Check general input consistency (time, deltaT, nr_repetitions, D,
+    % notes)
+    
+    % 1) Dose D needs to be present and positive
+    if isempty(input.D),
+        error('No dose "D" defined for input "%s".',input.name);
+    end
+    if input.D < 0, 
+        error('Dose "D" not allowed to be negative in input "%s".',input.name);
+    end
+    
+    % 2) time needs to be defined
+    if isempty(input.time),
+        error('"time" needs to be defined in input "%s".',input.name);
+    end
+    
+    % Check time against deltaT and nr_repetitions
+    % 3a) If time is a vector deltaT and nr_rep need to be empty
+    if length(input.time) > 1 && (~isempty(deltaT) || ~isempty(nr_repetitions)),
+        error('When defining a time vector in "time", "nr_repetitions" and "deltaT" are not allowed to be defined in input "%s".',input.name);
+    end
+    % 3b) further checks
+    if ~isempty(nr_repetitions),
+        if nr_repetitions == 1,
+            error('Do not use "nr_repetitions: 1" to specify single applications in input "%s".\nJust remove the "nr_repetitions" identifier.',input.name);
+        end
+        if isempty(deltaT),
+            error('When defining "nr_repetitions", also "deltaT" needs to be defined in input "%s".',input.name);
+        end
+    else
+        if ~isempty(deltaT),
+            error('When defining "deltaT", also "nr_repetitions" needs to be defined in input "%s".',input.name);
+        end
+    end    
+    
+    % 4) Construct the time field (scalar for single or vector for multiple applications)
+    if ~isempty(nr_repetitions),
+        addTimeVector = [0:deltaT:deltaT*(nr_repetitions-1)];
+        input.time = input.time+addTimeVector;
+        % update in final SBPOPdosing structure
+        SBstructure.inputs(k).time = input.time;
+    end
+    
+    % 5) Check length of dose vector (either scalar or same length as time vector)
+    if length(input.D) > 1,
+        if length(input.D) ~= length(input.time),
+            error('Length of "D" vector and "time" vector does not match in input "%s".',input.name);
+        end
+    elseif length(input.time) > 1,
+        % If D scalar and time vector then expand D to a vector with the
+        % same size as time ...
+        D = input.D * ones(1,length(input.time));
+        SBstructure.inputs(k).D = D;
+    end
+       
+    % 5) Check that Tlag is positive
+    if input.Tlag < 0,
+        error('"Tlag" is not allowed to be negative in input "%s".',input.name);
+    end
+
+    % 6) Check parameter value of input
+    if ~isempty(input.parameters),
+        parametervalue = input.parameters.value;
+        if length(parametervalue) == 1,
+            % make vector out of it
+            SBstructure.inputs(k).parameters.value = parametervalue*ones(1,length(SBstructure.inputs(k).time));
+        else
+            % Check length
+            if length(parametervalue) ~= length(SBstructure.inputs(k).time),
+                error('Length of "parameter value" vector and "time" vector does not match in input "%s".',input.name);
+            end
+        end
+    end
+    
+    % Check input type and input type specific information
+    if strcmp(input.type,'BOLUS'),
+        % 1) Check Bolus inputs
+        checkBolusInput(input);
+    elseif strcmp(input.type,'INFUSION'),
+        % 2) Check Infusion inputs
+        checkInfusionInput(input)
+    elseif strcmp(input.type,'ABSORPTION1'),
+        % 3) Check 1st order absorbption inputs
+        checkAbsorption1Input(input)
+    elseif strcmp(input.type,'ABSORPTION0'),
+        % 4) Check 0th order absorbption inputs
+        checkAbsorption0Input(input)
+    else
+        % Error: unknown input type
+        error('Unknown input type in dosing description in input "%s".',input.type);
+    end
+end
+
+% Finally check if inputs with same names
+a = {SBstructure.inputs.name};
+if length(a) ~= length(unique(a)),
+    error('At least two inputs are defined in the dosing scheme, which have the same name.');
+end
+
+
+%%%%%%%%%%%%%%%%%% END OF FUNCTION
+return
+
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check Bolus inputs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [] = checkBolusInput(input)
+    % no additional parameters are required => check that input.parameters
+    % is empty
+    if ~isempty(input.parameters),
+        error('Bolus definition does not require additional parameters in input "%s".',input.name);
+    end
+    % Do check that Tlag is not to large. Tlag+(Tk0 or Dmax/Rate or deltaTBolus) < min delta T dosing is acceptable.
+    % This limitation exists due to the implementation of the multiple
+    % dosings for simulation using events to update the parameters that
+    % perform the multiple inputs. (only if multiple inputs)
+    if length(input.time) > 1,
+        % Determine the minimum time between dosing instances
+        minDeltaT = min(input.time(2:end)-input.time(1:end-1));
+        if input.Tlag + 0.0001 >= minDeltaT,
+            error('Tlag in ''%s'' is to large. Please choose it smaller than the min time between dosings.',input.name);
+        end
+    end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check Infusion inputs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% We need to check that multiple infusions do not lead to one infusion
+% overlaying the previous one(s). This is done by checking that 
+% max(D)/Rate < min delta time in application
+function [] = checkInfusionInput(input)
+    % Rate is required as additional input. 
+    if length(input.parameters) ~= 1,
+        error('Infusion definition does require a single additional parameter "Rate" or "Tinf" in input "%s".',input.name);
+    end
+    % Check name of parameter (required: Rate)
+    if ~strcmp(input.parameters(1).name,'Rate') && ~strcmp(input.parameters(1).name,'Tinf'),
+        error('Please use "Rate" or "Tinf" as infusion related parameter in input "%s".',input.name);
+    end
+    % Check non overlapping infusion inputs (only if multiple inputs)
+    if length(input.time) > 1,
+        if strcmp(input.parameters(1).name,'Rate'),
+            % Determine minimum required time between dosing instances
+            Rate = min(input.parameters(1).value);
+            maxDose = max(input.D);
+            minRequiredDeltaT = maxDose/Rate;
+            % Determine the minimum time between dosing instances
+            minDeltaT = min(input.time(2:end)-input.time(1:end-1));
+            % Do the check
+            if minRequiredDeltaT > minDeltaT,
+                error('Infusion rate for input ''%s'' to low. Previous infusion would not be finished before the next one.',input.name);
+            end
+            % Do check that Tlag is not to large. Tlag+(Tk0 or Dmax/Rate or deltaTBolus) < min delta T dosing is acceptable.
+            % This limitation exists due to the implementation of the multiple
+            % dosings for simulation using events to update the parameters that
+            % perform the multiple inputs. (only if multiple inputs)
+            % Determine the minimum time between dosing instances
+            if input.Tlag + minRequiredDeltaT >= minDeltaT,
+                error('Tlag in ''%s'' is to large. Please choose it smaller than the min time between dosings minus max(Dose)/Rate.',input.name);
+            end
+        elseif strcmp(input.parameters(1).name,'Tinf'),
+            % Determine minimum required time between dosing instances
+            Tinf = max(input.parameters(1).value);
+            minRequiredDeltaT = Tinf;
+            % Determine the minimum time between dosing instances
+            minDeltaT = min(input.time(2:end)-input.time(1:end-1));
+            % Do the check
+            if minRequiredDeltaT > minDeltaT,
+                error('Infusion time for input ''%s'' to low. Previous infusion would not be finished before the next one.',input.name);
+            end
+            % Do check that Tlag is not to large. Tlag+(Tk0 or Dmax/Rate or deltaTBolus) < min delta T dosing is acceptable.
+            % This limitation exists due to the implementation of the multiple
+            % dosings for simulation using events to update the parameters that
+            % perform the multiple inputs. (only if multiple inputs)
+            % Determine the minimum time between dosing instances
+            if input.Tlag + minRequiredDeltaT >= minDeltaT,
+                error('Tlag in ''%s'' is to large. Please choose it smaller than the min time between dosings minus Tinf.',input.name);
+            end
+        end
+    end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check 1st order Absorption inputs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [] = checkAbsorption1Input(input)
+    % ka is required as additional input.
+    if length(input.parameters) ~= 1,
+        error('1st order Absorption definition does require a single additional parameter "ka" in input "%s".',input.name);
+    end
+    % Check name of parameter (required: ka)
+    if ~strcmp(input.parameters(1).name,'ka'),
+        error('Please use "ka" as absorption rate parameter in input "%s".',input.name);
+    end
+    % Do check that Tlag is not to large. Tlag+(Tk0 or Dmax/Rate or deltaTBolus) < min delta T dosing is acceptable.
+    % This limitation exists due to the implementation of the multiple
+    % dosings for simulation using events to update the parameters that
+    % perform the multiple inputs. (only if multiple inputs)
+    if length(input.time) > 1,
+        % Determine the minimum time between dosing instances
+        minDeltaT = min(input.time(2:end)-input.time(1:end-1));
+        if input.Tlag + 0.0001 >= minDeltaT,
+            error('Tlag in ''%s'' is to large. Please choose it smaller than the min time between dosings.',input.name);
+        end
+    end    
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check 0th order Absorption inputs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% We need to check that multiple 0 absorptions do not lead to one
+% absorption overlaying the previous one(s). This is done by checking that 
+% Tk0 < min delta time in application
+function [] = checkAbsorption0Input(input)
+    % Tk0 is required as additional input.
+    if length(input.parameters) ~= 1,
+        error('0th order Absorption definition does require a single additional parameter "Tk0" in input "%s".',input.name);
+    end
+    % Check name of parameter (required: Tk0)
+    if ~strcmp(input.parameters(1).name,'Tk0'),
+        error('Please use "Tk0" as absorption time parameter in input "%s".',input.name);
+    end
+    % Check non overlaying absorption0 inputs (only if multiple inputs)
+    if length(input.time) > 1,
+        % Determine minimum required time between dosing instances
+        minRequiredDeltaT = max(input.parameters(1).value);  % corresponds to Tk0
+        % Determine the minimum time between dosing instances
+        minDeltaT = min(input.time(2:end)-input.time(1:end-1));
+        % Do the check
+        if minRequiredDeltaT > minDeltaT,
+            error('Absorption time Tk0 for input ''%s'' to large. Previous dosing would not be finished before the next one.',input.name);
+        end
+        % Do check that Tlag is not to large. Tlag+(Tk0 or Dmax/Rate or deltaTBolus) < min delta T dosing is acceptable.
+        % This limitation exists due to the implementation of the multiple
+        % dosings for simulation using events to update the parameters that
+        % perform the multiple inputs. (only if multiple inputs)
+        % Determine the minimum time between dosing instances
+        if input.Tlag + minRequiredDeltaT >= minDeltaT,
+            error('Tlag in ''%s'' is to large. Please choose it smaller than the min time between dosings minus Tk0.',input.name);
+        end        
+    end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Remove character function
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [output] = removeCharacters(input)
+% delete all line breaks and tabs from the input string
+temp = double(input);
+temp(find(temp==13)) = 32;  % replace '\cr' by white space
+temp(find(temp==10)) = 32;  % replace '\n' by white space
+temp(find(temp==9)) = 32;   % replace '\t' by white space
+output = char(temp);
+% remove all spaces
+%    output = strrep(output,' ','');
+return
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/auxiliary/text2sbpopdose/getPartsFromCompleteTextDosSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/auxiliary/text2sbpopdose/getPartsFromCompleteTextDosSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..768487c0a776aa8960cf03ec1fb207a84f7da2c0
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/auxiliary/text2sbpopdose/getPartsFromCompleteTextDosSBPOP.m
@@ -0,0 +1,69 @@
+function [dosTextStructure] = getPartsFromCompleteTextDosSBPOP(dosText)
+% getPartsFromCompleteTextDosSBPOP: Cuts a text description of an
+% SBPOPdosing object into the different parts and returns them in a
+% structure 
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+% take commented lines out of the dosing description
+dosText = regexprep(dosText,'\n%[^\n]*','');
+
+% Find the starts of the different sections. NAME and NOTES are required.
+% Following these there can be an arbitrary number of input definitions. 
+% The order of the inputs is defined through the naming of a section 
+% ********** INPUT1  => corresponds to "INPUT1" in a model file.
+
+% Required sections
+nameStart = strfind(dosText,'********** DOSING NAME');
+notesStart = strfind(dosText,'********** DOSING NOTES');
+
+% Check if they are present
+if isempty(nameStart),
+    error('No "DOSING NAME" section in dosing description.');
+end
+if isempty(notesStart),
+    error('No "DOSING NOTES" section in dosing description.');
+end
+
+% Parse the INPUTx sections. They are optional (No input is allowed).
+% 1) Count all *****... etc.
+nrAllSections = length(strfind(dosText,'**********'));
+nrInputSections = length(strfind(dosText,'********** INPUT'));
+
+% 2) Check the number of the sections (allows detecting syntax errors in
+% input section definitions)
+if nrInputSections+2 ~= nrAllSections,
+    error('Please check the input section identifiers in the dose description file for errors.');
+end
+
+% 3) get startindices of input sections
+startIndexInput = strfind(dosText,'********** INPUT');
+
+% 4) Get all sections
+dosTextStructure.name = strtrim(dosText(nameStart+length('********** DOSING NAME'):notesStart-1));
+if isempty(startIndexInput),
+    dosTextStructure.notes = strtrim(dosText(notesStart+length('********** DOSING NOTES'):end));
+else
+    dosTextStructure.notes = strtrim(dosText(notesStart+length('********** DOSING NOTES'):startIndexInput(1)-1));
+end
+dosTextStructure.input = {};
+for k=1:length(startIndexInput)-1,
+    dosTextStructure.input{k} = strtrim(dosText(startIndexInput(k)+length('********** '):startIndexInput(k+1)-1));
+end
+dosTextStructure.input{end+1} = strtrim(dosText(startIndexInput(end)+length('********** '):end));
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/isSBPOPdosing.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/isSBPOPdosing.m
new file mode 100644
index 0000000000000000000000000000000000000000..5a6ad300bd55c64ef465e53182b1e9e10d106590
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/classeshandling/dosehandling/isSBPOPdosing.m
@@ -0,0 +1,21 @@
+function [output] = isSBPOPdosing(input)
+% isSBPOPdosing: check if input argument is an SBPOPdosing object.
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+output = strcmp(class(input),'SBPOPdosing');
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/installSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/installSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..8e8e92633947211ce07250ba54fd8b782a70c7e3
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/installSBPOP.m
@@ -0,0 +1,85 @@
+function [] = installSBPOP(varargin)
+% installSBPOP
+% Installation function for the complete SBPOP package. 
+%
+%       installSBPOP
+%
+% This adds the SBPOP package and all subdirectories to the
+% MATLAB path. 
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check that installSBPOP is started in the right folder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+currentDir = pwd;
+installSBPOPDir = fileparts(which('installSBPOP.m'));
+if ~strcmp(currentDir,installSBPOPDir),
+    error('Run the ''installSBPOP'' script from the folder where it is located.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check that at least the SBTOOLBOX2 is installed 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBT2present = ver('SBTOOLBOX2');
+if isempty(SBT2present),
+    error('Please install the SBTOOLBOX2 first.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check that correct local path (network paths are not allowed)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp(currentDir(1:2),'\\'),
+    error(sprintf('The installation can not be run from a network path (\\\\...).\nPlease run the installation from a local path.'));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if SBPOP already installed
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBPOPver = ver('SBPOP');
+if length(SBPOPver) >= 1,
+    error('You seem to already have an installation of SBPOP. Please use "restoredefaultpath" before installing a different version.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add SBPOP folder to path
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+addpath(genpath(pwd));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Final installation information, version, etc.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+disp(sprintf('SBPOP for SBTOOLBOX2 and SBPD'));
+disp(sprintf(' '));
+disp(sprintf('Copyright (c) 2013 Novartis Pharma AG'));
+disp(sprintf(' '));
+disp(sprintf('This program is Free Open Source Software: you can redistribute it and/or modify '));
+disp(sprintf('it under the terms of the GNU General Public License as published by '));
+disp(sprintf('the Free Software Foundation, either version 3 of the License, or '));
+disp(sprintf('(at your option) any later version. '));
+disp(sprintf(' '));
+disp(sprintf('This program is distributed in the hope that it will be useful, '));
+disp(sprintf('but WITHOUT ANY WARRANTY; without even the implied warranty of '));
+disp(sprintf('MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the '));
+disp(sprintf('GNU General Public License for more details. '));
+disp(sprintf(' '));
+disp(sprintf('You should have received a copy of the GNU General Public License '));
+disp(sprintf('along with this program. If not, see <http://www.gnu.org/licenses/>.'));
+disp(sprintf(' '));
+disp(sprintf(' '));
+disp(sprintf(' '));
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/license.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/license.txt
new file mode 100644
index 0000000000000000000000000000000000000000..65e0ebf47690538cf3e698281babeb102a06b81f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/license.txt
@@ -0,0 +1,674 @@
+					 GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/SBPOPcreateDRUGligandTargetModel.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/SBPOPcreateDRUGligandTargetModel.m
new file mode 100644
index 0000000000000000000000000000000000000000..604e3e10f46b69f4aa474f10c3d4505726efac8c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/SBPOPcreateDRUGligandTargetModel.m
@@ -0,0 +1,41 @@
+function [] = SBPOPcreateDRUGligandTargetModel(filename)
+% SBPOPcreateDRUGligandTargetModel: this function simply copies the file
+% "standard_Drug_LigandTarget_model.txtbc" under the given filename in the current
+% folder. 
+%
+% USAGE:
+% ======
+% SBPOPcreateDRUGligandTargetModel(filename)
+% 
+% filename: name of the model file to create (extension: .txtbc)
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK THE INPUT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~ischar(filename),
+    error('Incorrect input argument.');
+end
+% remove extensions from input filename
+[pathstr,name] = fileparts(filename);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% COPY THE FILE TO NEW LOCATION AND NAME
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+copyfile(which('standard_Drug_LigandTarget_model.txtbc'),[name '.txtbc']);
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/SBPOPoptimizeDRUGkinetics.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/SBPOPoptimizeDRUGkinetics.m
new file mode 100644
index 0000000000000000000000000000000000000000..4509b2465e80e3726aa3445be9f644353e2fb362
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/SBPOPoptimizeDRUGkinetics.m
@@ -0,0 +1,295 @@
+function [popt] = SBPOPoptimizeDRUGkinetics(model,pnames_in,pvalues0,referenceValues_in,varargin)
+% SBPOPoptimizeDRUGkinetics: This function will estimate parameters
+% of the standard model to adjust the kinetics of a drug molecule (mAb,
+% nanobody, etc.) to desired properties (alpha and beta halflife and
+% percentage of steady-state distribution between disease tissue and
+% plasma) 
+%
+% These desired properties are:
+%   - alpha-halftime of drug in plasma                     (referenceValue(1)) 
+%   - beta-halftime of drug in plasma                      (referenceValue(2)) 
+%   - steady-state concentration ration of mAb             (referenceValue(3))
+%     between tissue and plasma
+%
+% IMPORTANT:
+% ==========
+% This function assumes the use of the standard model and the use of
+% "INPUT1" identifier for adding the drug. Nevertheless, the user can provide the
+% parameters to be estimated and initial guesses. 
+%
+% The results are summarized in the MATLAB command window.
+%
+% USAGE:
+% ======
+% [popt] = SBPOPoptimizeDRUGkinetics(model,pnames,pvalues0,referenceValues)
+% [popt] = SBPOPoptimizeDRUGkinetics(model,pnames,pvalues0,referenceValues,parametervector)
+% [popt] = SBPOPoptimizeDRUGkinetics(model,pnames,pvalues0,referenceValues,parametervector,weights)
+% [popt] = SBPOPoptimizeDRUGkinetics(model,pnames,pvalues0,referenceValues,parametervector,weights,input)
+% [popt] = SBPOPoptimizeDRUGkinetics(model,pnames,pvalues0,referenceValues,parametervector,weights,input,timevector)
+%
+% model: SBmodel or MEX simulation model
+% pnames: cell-array with parameters to estimate
+% pvalues0: vector with initial guesses for the parameters
+% referenceValues: vector with 3 entries:
+%   referenceValues(1): desired alpha-halftime of drug in plasma (NOT ALLOWED TO BE ZERO)
+%   referenceValues(2): desired beta-halftime of drug in plasma (NOT ALLOWED TO BE ZERO) 
+%   referenceValues(3): desired ratio between steady-state drug in tissue and plasma (NOT ALLOWED TO BE ZERO)  
+% parametervector: full parameter vector for model simulation. If not
+%   given, the parameters defined in the model are used. The definition of
+%   this parameter vector makes most sense if the function is called on a
+%   MEX simulation function, rather than an SBmodel. If empty vector is
+%   passed then the parameter vector in the model will be used.
+% weights: vector with weights for the residuals for the three different
+%   objectives, defined in the referenceValues vector. This is very useful
+%   in the case that the lymph flow rate is known in advance (for nanobody
+%   drugs the mAb lymph flow is set fixed). Then this function can be used
+%   also to only fit the alpha and beta halflives.
+% input: "INPUT1" or "INPUT2", etc. Depending on the input in your model
+%   that you want to apply the drug to (default: INPUT1).
+% timevector: timevector for simulation during optimization (needs to
+%   capture both the fast and the slow phase of drug distribution and
+%   elimination.
+%
+% DEFAULT VALUES:
+% ===============
+% parametervector: nominal vector defined in the model
+% weights: [1 1 1]
+% timevector: from 0 to referenceValues(2)*10 in 5000 steps
+%
+% Output Arguments:
+% =================
+% popt: vector with optimized parameter values
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+% Display warning message
+disp(' ');
+disp('SBPOPoptimizeDRUGkinetics: Please make sure you have disabled drug/target binding in the model when calling this function.');
+disp(' ');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Make parameter names and reference values 
+% available to the cost function
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+warning off;
+global pnames referenceValues MEXmodel opttimevector plotFlag parameternames parametervector weights input
+warning on;
+pnames = pnames_in;
+referenceValues = referenceValues_in;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ts = 0;
+te = referenceValues(2)*10;
+opttimevector = [ts:(te-ts)/5000:te];
+weights = [1 1 1];
+input = 'INPUT1';
+[parameternames,parametervector_nominal] = SBparameters(model); % get values stored in the model
+parametervector = parametervector_nominal;
+if nargin >= 5,
+    parametervector = varargin{1};
+    if isempty(parametervector),
+        parametervector = parametervector_nominal;
+    else
+        if length(parametervector) ~= length(SBparameters(model)),
+            error('The length of the provided parameter vector does not match the number of parameters in the model.');
+        end
+    end
+end
+if nargin >= 6,
+    weights = varargin{2};
+end
+if nargin >= 7,
+    input = varargin{3};
+end
+if nargin >= 8,
+    opttimevector = varargin{4};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get MEX model if not already provided as mex model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isSBmodel(model),
+    [MEXmodel, MEXmodelfullpath] = makeTempMEXmodelSBPD(model);
+else 
+    MEXmodel = model;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define parameter bounds
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+plb = zeros(1,length(pvalues0));       % lower bounds
+pub = 1000*pvalues0;                   % upper bounds
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run the optimization
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+OPTOPTIONS.lowbounds = plb;
+OPTOPTIONS.highbounds = pub;
+OPTOPTIONS.maxfunevals = 200;
+OPTOPTIONS.silent = 1;
+if isempty(plotFlag)
+    plotFlag = 0;
+end
+plotFlagOld = plotFlag;
+plotFlag = 0;
+[popt, FVAL] = simplexSB(@Drug_exp, pvalues0, OPTOPTIONS);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check "optimal" parameters and plot a check
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+REF_T12_a         = referenceValues(1);   % Drug Alpha half time
+REF_T12_b         = referenceValues(2);   % Drug Beta half time
+REF_delta_c       = referenceValues(3);   % SS-ratio of mAb concentration tissue/plasma
+plotFlag = plotFlagOld;
+[cost,residuals] = Drug_exp(popt);
+disp(' ');
+disp('Optimized drug kinetics:');
+disp('========================');
+disp(sprintf('achieved cost = %g',cost));
+disp(sprintf('achieved_T12_a = %g',residuals(1) + REF_T12_a))
+disp(sprintf('achieved_T12_b = %g',residuals(2) + REF_T12_b))
+disp(sprintf('achieved_delta_c = %g',residuals(3) + REF_delta_c))
+disp('Optimal parameters:');
+for k=1:length(pnames),
+    disp(sprintf('\t%s = %g',pnames{k},popt(k)));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Remove MEX model if created here
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isSBmodel(model),
+    clear mex; delete(MEXmodelfullpath);
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Cost function for optimization of the parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [cost,residuals] = Drug_exp(x)
+% Drug_exp: cost function for the optimization of given model parameters
+% with the goal to achieve a certain (and provided):
+%
+%   - Alpha half-time of mAb
+%   - Beta half-time of mAb
+%   - percent mAb steady state concentration difference plasma interstitium
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% get the global variables
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+global pnames referenceValues MEXmodel opttimevector plotFlag parameternames parametervector weights input
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get the reference values
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+REF_T12_a   = referenceValues(1);
+REF_T12_b   = referenceValues(2);
+REF_delta_c = referenceValues(3);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Perform an experiment to determine the alpha 
+% and beta halflife of the drug in plasma 
+% for given parameters to be optimized
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% set initial concentration of drug in plasma to a value
+icvector = makeinicondvectorSBPD(MEXmodel,{'D_plasma'},1000);
+% set the parameters to be optimized
+parametervector_sim = updateparamvecSBPD(parameternames, parametervector, pnames, x);
+% simulate                                     
+options = [];
+options.abstol = 1e-10;
+options.reltol = 1e-10;
+simdata = feval(MEXmodel, opttimevector, icvector, parametervector_sim, options);
+% Get the interesting data from simulation results (timevector and drug concentration in plasma)
+time     = simdata.time;
+D_plasma = simdata.statevalues(:,getstateindicesSBPD(MEXmodel,'D_plasma'));
+
+% Compute the Alpha half life in plasma (T12_a)
+t1_indx = 10;
+T1_a = time(1);
+T2_a = time(t1_indx);
+Y1_a = D_plasma(1);
+Y2_a = D_plasma(t1_indx);
+T12_a = log(0.5)*(T2_a - T1_a) / (log(Y2_a) - log(Y1_a));
+
+% Compute the Beta half life in plasma (T12_b)
+t2_indx = 100;
+T1_b = time(end-t2_indx);
+T2_b = time(end);
+Y1_b = D_plasma(end-t2_indx);
+Y2_b = D_plasma(end);
+T12_b = log(0.5)*(T2_b - T1_b) / (log(Y2_b) - log(Y1_b));
+
+if plotFlag,
+    figure; clf;
+    plot(time,D_plasma); hold on; drawnow;  
+    plot(T1_a,Y1_a,'ro');
+    plot(T2_a,Y2_a,'go');
+    plot(T1_b,Y1_b,'rx');
+    plot(T2_b,Y2_b,'gx');
+    set(gca,'YScale','log');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Experiment: constant drug input (until 
+% steadystate/final simulation time)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+doseparamnames = {input};
+doseparamvalues = [1000];
+% Apply dosing parameters and parameters to be optimized
+parametervector_sim = updateparamvecSBPD(parameternames, parametervector, {pnames{:}, doseparamnames{:}}, [x(:)' doseparamvalues(:)']);
+% nominal initial conditions
+icvector = [];
+% Simulate      
+options = [];
+options.abstol = 1e-10;
+options.reltol = 1e-10;
+simdata = feval(MEXmodel, opttimevector, icvector, parametervector_sim,options);
+% Get the interesting data from simulation results
+time        = simdata.time;
+D_plasma    = simdata.statevalues(:,getstateindicesSBPD(MEXmodel,'D_plasma'));
+% Which tissue is considered does not really make an important difference. 
+% We select the disease tissue for our calculations (makes more sense than
+% the peripheral tissue)
+D_itst_tissue = simdata.statevalues(:,getstateindicesSBPD(MEXmodel,'D_itst_tissue'));
+
+% Determine ration between drug concentrations in tissue and drug in plasma
+delta_c = D_itst_tissue(end)/D_plasma(end)*100;
+
+if plotFlag,
+    figure; clf;
+    plot(time,[D_plasma D_itst_tissue], '--'); drawnow
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine the residuals
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+res(1) = T12_a - REF_T12_a;
+res(2) = T12_b - REF_T12_b;
+res(3) = delta_c - REF_delta_c;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine the costfunction 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+residuals = [res(1) res(2) res(3)];
+scaledresiduals = residuals./[REF_T12_a REF_T12_b REF_delta_c];
+weightedresiduals = scaledresiduals.*weights;
+cost = sum(weightedresiduals.^2);
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/SBPOPoptimizeLigandTARGETkinetics.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/SBPOPoptimizeLigandTARGETkinetics.m
new file mode 100644
index 0000000000000000000000000000000000000000..7c6ad558d2db924aede3b73e4a573d4b56694f05
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/SBPOPoptimizeLigandTARGETkinetics.m
@@ -0,0 +1,248 @@
+function [popt] = SBPOPoptimizeLigandTARGETkinetics(model,pnames_in,pvalues0,referenceValues_in,varargin)
+% SBPOPoptimizeLigandTARGETkinetics: This function will estimate parameters
+% of the standard model to adjust the kinetics of a target (ligand) to
+% desired properties (alpha and beta halflife)
+%
+% These desired properties are:
+%   - alpha-halftime of target in plasma             (referenceValue(1)) 
+%   - beta-halftime of target in plasma              (referenceValue(2)) 
+% 
+% IMPORTANT:
+% ==========
+% This function assumes the use of the standard model and by default the use of
+% "T1_plasma" as the statename for the target in the plasma compartment.
+% The user can define a different name for the target state in plasma, which is
+% useful if a second soluble target is available in the model which also should 
+% be fitted.
+% The user can provide the parameters to be estimated and initial guesses. 
+%
+% The results are summarized in the MATLAB command window.
+%
+% USAGE:
+% ======
+% [popt] = SBPOPoptimizeLigandTARGETkinetics(model,pnames,pvalues0,referenceValues)
+% [popt] = SBPOPoptimizeLigandTARGETkinetics(model,pnames,pvalues0,referenceValues,parametervector)
+% [popt] = SBPOPoptimizeLigandTARGETkinetics(model,pnames,pvalues0,referenceValues,parametervector,targetparam)
+% [popt] = SBPOPoptimizeLigandTARGETkinetics(model,pnames,pvalues0,referenceValues,parametervector,targetparam,weigthts)
+% [popt] = SBPOPoptimizeLigandTARGETkinetics(model,pnames,pvalues0,referenceValues,parametervector,targetparam,weigthts,timevector)
+%
+% model: SBmodel or MEX simulation model
+% pnames: cell-array with parameters to estimate
+% pvalues0: vector with initial guesses for the parameters
+% referenceValues: vector with 2 entries:
+%   referenceValues(1): desired alpha-halftime of target in plasma (NOT ALLOWED TO BE ZERO) 
+%   referenceValues(2): desired beta-halftime of target in plasma (NOT ALLOWED TO BE ZERO) 
+% parametervector: full parameter vector for model simulation. If not
+%   given, the parameters defined in the model are used. The definition of
+%   this parameter vector makes most sense if the function is called on a
+%   MEX simulation function, rather than an SBmodel. If empty vector is
+%   passed then the parameter vector in the model will be used.
+% targetparam: name of the target state variable to consider (there might
+%   be several targets in the model)
+% weights: vector with weights for the residuals for the two different
+%   objectives, defined in the referenceValues vector. For small halflives
+%   it might happen that the alpha halflife depends on the beta halflife.
+%   In these cases a higher weight for the beta halflife should be chosen
+%   to get this at least onto the desired value.
+% timevector: timevector for simulation during optimization (needs to
+%   capture both the fast and the slow phase of target distribution and
+%   elimination.
+%
+% DEFAULT VALUES:
+% ===============
+% parametervector: nominal vector defined in the model
+% targetparam: 'T1_plasma'
+% timevector: 0 to referenceValues(2)*10 in 5000 steps
+%
+% Output Arguments:
+% =================
+% popt: vector with optimized parameter values
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Make parameter names and reference values 
+% available to the cost function
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+warning off;
+global pnames referenceValues MEXmodel weights opttimevector plotFlag targetparam parameternames parametervector
+warning on;
+pnames = pnames_in;
+referenceValues = referenceValues_in;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ts = 0;
+te = referenceValues(2)*10;
+opttimevector = [ts:(te-ts)/5000:te];
+targetparam = 'T1_plasma';
+weights = [1 1];
+[parameternames,parametervector_nominal] = SBparameters(model); % get values stored in the model
+parametervector = parametervector_nominal;
+if nargin >= 5,
+    parametervector = varargin{1};
+    if isempty(parametervector),
+        parametervector = parametervector_nominal;
+    else
+        if length(parametervector) ~= length(SBparameters(model)),
+            error('The length of the provided parameter vector does not match the number of parameters in the model.');
+        end
+    end
+end
+if nargin >= 6,
+    targetparam = varargin{2};
+end
+if nargin >= 7,
+    weights = varargin{3};
+end
+if nargin >= 8,
+    opttimevector = varargin{4};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get MEX model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isSBmodel(model),
+    [MEXmodel, MEXmodelfullpath] = makeTempMEXmodelSBPD(model);
+else 
+    MEXmodel = model;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define parameter bounds
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+plb = zeros(1,length(pvalues0));       % lower bounds
+pub = 1000*pvalues0;                   % upper bounds
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run the optimization
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+OPTOPTIONS.lowbounds = plb;
+OPTOPTIONS.highbounds = pub;
+OPTOPTIONS.maxfunevals = 200;
+OPTOPTIONS.silent = 1;
+plotFlag = 0;
+[popt, FVAL] = simplexSB(@target_T_a_b, pvalues0, OPTOPTIONS);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check "optimal" parameters and plot a check
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+REF_T12_a         = referenceValues(1);   % Target Alpha half time
+REF_T12_b         = referenceValues(2);   % Target Beta half time
+plotFlag = 1;
+[cost,residuals] = target_T_a_b(popt);
+disp(' ');
+disp('Optimized Target kinetics:');
+disp('==========================');
+disp(sprintf('achieved cost = %g',cost));
+disp(sprintf('achieved_T12_a = %g',residuals(1) + REF_T12_a))
+disp(sprintf('achieved_T12_b = %g',residuals(2) + REF_T12_b))
+disp('Optimal parameters:');
+for k=1:length(pnames),
+    disp(sprintf('\t%s = %g',pnames{k},popt(k)));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Remove MEX model if created here
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isSBmodel(model),
+    clear mex; delete(MEXmodelfullpath);
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Cost function for optimization of the parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [cost,res] = target_T_a_b(x)
+% target_T_a_b: cost function for the optimization of given model parameters
+% with the goal to achieve a certain (and provided):
+%
+%   - Alpha half-time of target
+%   - Beta half-time of target
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% get the global variables
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+global pnames referenceValues MEXmodel weights opttimevector plotFlag targetparam parameternames parametervector
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get the reference values
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+REF_T12_a   = referenceValues(1);
+REF_T12_b   = referenceValues(2);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Perform experiment to determine the alpha 
+% and beta halflife of the target in plasma 
+% for given parameters to be optimized
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% set initial concentration of drug in plasma to a value
+icvector = makeinicondvectorSBPD(MEXmodel,{targetparam},1000);
+% set the parameters to be optimized
+parametervector_sim = updateparamvecSBPD(parameternames, parametervector, pnames, x);
+% simulate                                     
+options = [];
+options.abstol = 1e-10;
+options.reltol = 1e-10;
+simdata = feval(MEXmodel, opttimevector, icvector, parametervector_sim,options);
+% Get the interesting data from simulation results (timevector and drug concentration in plasma)
+time          = simdata.time;
+Target_plasma = simdata.statevalues(:,getstateindicesSBPD(MEXmodel,targetparam));
+
+% Compute the target alpha half time
+t1_indx = 10;
+T1_a = time(1);
+T2_a = time(t1_indx);
+Y1_a = Target_plasma(1);
+Y2_a = Target_plasma(t1_indx);
+T12_a = log(0.5)*(T2_a - T1_a) / (log(Y2_a) - log(Y1_a));
+
+% Compute the target beta half time
+t2_indx = 100;
+T1_b = time(end-t2_indx);
+T2_b = time(end);
+Y1_b = Target_plasma(end-t2_indx);
+Y2_b = Target_plasma(end);
+T12_b = log(0.5)*(T2_b - T1_b) / (log(Y2_b) - log(Y1_b));
+
+if plotFlag,
+    figure; clf;
+    plot(time,Target_plasma); hold on; drawnow;  
+    plot(T1_a,Y1_a,'ro');
+    plot(T2_a,Y2_a,'go');
+    plot(T1_b,Y1_b,'rx');
+    plot(T2_b,Y2_b,'gx');
+    set(gca,'YScale','log');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine the residuals
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+res(1) = T12_a - REF_T12_a;
+res(2) = T12_b - REF_T12_b;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine the costfunction 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+weightedres = [res(1)/REF_T12_a  res(2)/REF_T12_b].*weights(:)';
+cost = sum(weightedres.^2);
+return
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/SBPOPoptimizeLigandTARGETsynthesis.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/SBPOPoptimizeLigandTARGETsynthesis.m
new file mode 100644
index 0000000000000000000000000000000000000000..75fe7df5e1c338e144e71c2ba229bab9874b972a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/SBPOPoptimizeLigandTARGETsynthesis.m
@@ -0,0 +1,257 @@
+function [popt] = SBPOPoptimizeLigandTARGETsynthesis(model,pnames_in,pvalues0,referenceValues_in,varargin)
+% SBPOPoptimizeLigandTARGETsynthesis: This function will estimate parameters
+% of the standard model to adjust the steady-state concentrations of a
+% target (ligand) to desired properties (plasma/disease tissue/peripheral tissue
+% concentrations) 
+%
+% These desired properties are:
+%      - plasma target steady-state concentration              
+%      - disease tissue target steady-state concentration      
+%      - peripheral tissue target steady-state concentration   
+%
+% Before using this function you need to fit the target kinetics (clearance
+% and surface exchange coefficient) using the
+% "SBPOPoptimizeLigandTARGETkinetics" function.
+% 
+% IMPORTANT:
+% ==========
+% This function assumes the use of the standard model and by default the use of
+% "T1_plasma"/"T1_itst_tissue"/"T1_itst_peri" as the statenames for the
+% target concentration in the different tissues. Additionally, it is
+% assumed that the reference values are provided in exactly that order
+% (plasma / tissue / peripheral tissue).
+% The user can define different names for the target state in plasma /
+% tissue / peripheral tissue (that order!), which is useful if a second
+% soluble target is available in the model which also should  be fitted.
+% The user can provide the parameters to be estimated and initial guesses. 
+%
+% The results are shown in the MATLAB command window.
+%
+% USAGE:
+% ======
+% [popt] = SBPOPoptimizeLigandTARGETsynthesis(model,pnames,pvalues0,referenceValues)
+% [popt] = SBPOPoptimizeLigandTARGETsynthesis(model,pnames,pvalues0,referenceValues,parametervector)
+% [popt] = SBPOPoptimizeLigandTARGETsynthesis(model,pnames,pvalues0,referenceValues,parametervector,targetparam)
+% [popt] = SBPOPoptimizeLigandTARGETsynthesis(model,pnames,pvalues0,referenceValues,parametervector,targetparam,weights)
+% [popt] = SBPOPoptimizeLigandTARGETsynthesis(model,pnames,pvalues0,referenceValues,parametervector,targetparam,weights,timevector)
+%
+% model: SBmodel or MEX simulation model
+% pnames: cell-array with parameters to estimate
+% pvalues0: vector with initial guesses for the parameters
+% referenceValues: vector with 2 entries:
+%   referenceValues(1): desired plasma steady-state target concentration (NOT ALLOWED TO BE ZERO)              
+%   referenceValues(2): desired disease tissue steady-state target concentration (NOT ALLOWED TO BE ZERO)      
+%   referenceValues(3): desired peripheral tissue steady-state target concentration (NOT ALLOWED TO BE ZERO)   
+% parametervector: full parameter vector for model simulation. If not given, the parameters
+%   defined in the model are used.
+% weights: vector with weights for the residuals for the three different
+%   objectives, defined in the referenceValues vector. This is very useful
+%   in the case that not all of the steady state concentrations for the 
+%   tissues are known. Set zero as weight for the reference value you do
+%   not have a reasonable guess for.
+% targetparam: names of the target state variables in plasma, disease
+%   tissue, peripheral tissue (that order).
+% timevector: timevector for simulation during optimization (needs to
+%   capture the system until its steady-state).
+%
+% DEFAULT VALUES:
+% ===============
+% parametervector: nominal vector defined in the model
+% targetparam: {'T1_plasma','T1_itst_tissue','T1_itst_peri'}
+% weights: [1 1 1]
+% timevector: [0:0.01:30]
+%
+% Output Arguments:
+% =================
+% popt: vector with optimized parameter values
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Make parameter names and reference values 
+% available to the cost function
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+warning off;
+global pnames referenceValues MEXmodel weights opttimevector plotFlag targetparam parameternames parametervector
+warning on;
+pnames = pnames_in;
+referenceValues = referenceValues_in;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+opttimevector = [0:0.01:30];
+targetparam = {'T1_plasma','T1_itst_tissue','T1_itst_peri'};
+weights = [1 1 1];
+[parameternames,parametervector_nominal] = SBparameters(model); % get values stored in the model
+parametervector = parametervector_nominal;
+if nargin >= 5,
+    parametervector = varargin{1};
+    if isempty(parametervector),
+        parametervector = parametervector_nominal;
+    else
+        if length(parametervector) ~= length(SBparameters(model)),
+            error('The length of the provided parameter vector does not match the number of parameters in the model.');
+        end
+    end
+end
+if nargin >= 6,
+    targetparam = varargin{2};
+end
+if nargin >= 7,
+    weights = varargin{3};
+end
+if nargin >= 8,
+    opttimevector = varargin{4};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get MEX model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isSBmodel(model),
+    [MEXmodel, MEXmodelfullpath] = makeTempMEXmodelSBPD(model);
+else 
+    MEXmodel = model;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define parameter bounds
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+plb = zeros(1,length(pvalues0));       % lower bounds
+pub = 1000*pvalues0;                   % upper bounds
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run the optimization
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+OPTOPTIONS.lowbounds = plb;
+OPTOPTIONS.highbounds = pub;
+OPTOPTIONS.maxfunevals = 200;
+OPTOPTIONS.silent = 1;
+plotFlag = 0;
+[popt, FVAL] = simplexSB(@target_steady_state, pvalues0, OPTOPTIONS);
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check "optimal" parameters and plot a check
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% REF_T_plasma      = referenceValues(1);   % Plasma SS conc Target
+% REF_T_itst_tissue = referenceValues(2);   % Disease tissue SS conc Target
+% REF_T_itst_peri   = referenceValues(3);   % Peripheral tissue SS conc Target
+plotFlag = 1;
+[cost,residuals] = target_steady_state(popt);
+disp(' ');
+disp('Optimized Target Synthesis:');
+disp('===========================');
+disp(sprintf('achieved cost = %g',cost));
+disp('Optimal parameters:');
+for k=1:length(pnames),
+    disp(sprintf('\t%s = %g',pnames{k},popt(k)));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Remove MEX model if created here
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isSBmodel(model),
+    clear mex; delete(MEXmodelfullpath);
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Cost function for optimization of the parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [cost,res] = target_steady_state(x)
+% target_steady_state: cost function for the optimization of given model
+% parameters with the goal to achieve a certain (and provided):
+%
+%   - Plasma SS conc Target
+%   - Disease tissue SS conc Target
+%   - Peripheral tissue SS conc Target
+%
+% The user needs to check that the global parameter "opttimevector" is set
+% such that steady-state can be achieved in the second experiment
+% simulation below.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% get the global variables
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+global pnames referenceValues MEXmodel weights opttimevector plotFlag targetparam parameternames parametervector
+
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% % Use the reference T_plasma value as initial condition. At final
+% % simulation time it needs to be the same => equilibrium between target
+% % removal and production
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% icvector = makeinicondvectorSBPD(MEXmodel,targetparam,referenceValues);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get the parametervector
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+parametervector_sim = updateparamvecSBPD(parameternames, parametervector, pnames, x);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Simulate
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+options = [];
+options.abstol = 1e-10;
+options.reltol = 1e-10;
+simdata = feval(MEXmodel, opttimevector, [], parametervector_sim,options);
+% get the T_concentrations matrix (targetparam can be states or variables)
+T_concentrations = zeros(length(simdata.time),length(targetparam));
+T_concentrations_end = zeros(1,length(targetparam));
+for k=1:length(targetparam),
+    param = targetparam{k};
+    % figure out if state of variable
+    index = strmatchSB(param,simdata.states,'exact');
+    if ~isempty(index),
+        % state
+        T_concentrations(:,k) = simdata.statevalues(:,index);
+        T_concentrations_end(k) = simdata.statevalues(end,index);
+    else
+        % variable
+        index = strmatchSB(param,simdata.variables,'exact');
+        if isempty(index),
+            error('''%s'' is neither a state nor a variable in the model.',param);
+        end
+        T_concentrations(:,k) = simdata.variablevalues(:,index);
+        T_concentrations_end(k) = simdata.variablevalues(end,index);
+    end
+end        
+        
+% Plot to check 
+if plotFlag
+    figure; clf;
+    plot(simdata.time, T_concentrations); hold on;
+    plot([0 simdata.time(end)],[referenceValues(:)';referenceValues(:)'],'--'); 
+    set(gca,'YScale','log'); 
+    legend(targetparam);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine the residuals
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+res = T_concentrations_end(:) - referenceValues(:);
+
+% Get the cost
+weightedres = res(:)./referenceValues(:).*weights(:);
+cost = sum(weightedres.^2);
+return
+
+
+
+
+
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/SBPOPplotDoseEffectCurve.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/SBPOPplotDoseEffectCurve.m
new file mode 100644
index 0000000000000000000000000000000000000000..58a84119ca879fcf6af3e8e93107e3660c4b999c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/SBPOPplotDoseEffectCurve.m
@@ -0,0 +1,50 @@
+function SBPOPplotDoseEffectCurve(effect, dosevector, paramchangevector, ylabeltext, titletext)
+% SBPOPplotDoseEffectCurve: This function plots a dose/effect curve for
+% given input arguments.
+%
+% USAGE:
+% ======
+% SBPOPplotDoseEffectCurve(effect, dosevector, paramchangevector, ylabeltext, titletext)
+%
+% effect: matrix with determined effect values (columns correspond to
+%   different parameter settings (parameterchangevector) and rows correspond
+%    to different dose amount settings (dosevector)).
+% dosevector: vector with different dosing amounts, corresponding to  the
+%   effect matrix.
+% paramchangevector: vector with values for an additional parameter that
+%   was varied.
+% ylabeltext: text to plot on the y-axis
+% titletext: text to use as figure title
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+[dummy,p] = max(var(effect')');
+figure;
+for k = 1:length(paramchangevector)
+    plot(dosevector, effect(:, k),'-', 'LineWidth', 2);
+    text(dosevector(p), effect(p, k), num2str(paramchangevector(k)),'EdgeColor','black','BackgroundColor','white');
+    hold on
+end
+set(gca,'XScale','log');
+hlhlx = title(titletext,'Interpreter','none');
+set(hlhlx,'Interpreter','none');
+xlim([min(dosevector) max(dosevector)]);
+xlabel('Dose');
+hlhlx = ylabel(ylabeltext,'Interpreter','none');
+set(hlhlx,'Interpreter','none');
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/SBPOPplotDoseParamCurve.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/SBPOPplotDoseParamCurve.m
new file mode 100644
index 0000000000000000000000000000000000000000..6be4d396fc795562a0d639de4b47719ac63c836c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/SBPOPplotDoseParamCurve.m
@@ -0,0 +1,145 @@
+function SBPOPplotDoseParamCurve(effect, dosevector, paramchangevector, titletext, effectLevelSteps, targetEffect)
+% SBPOPplotDoseParamCurve: This function plots a dose/parameter curve for
+% given input arguments. Different effect levels are used as parameters for
+% the different curves.
+%
+% USAGE:
+% ======
+% SBPOPplotDoseParamCurve(effect, dosevector, paramchangevector)
+% SBPOPplotDoseParamCurve(effect, dosevector, paramchangevector, titletext)
+% SBPOPplotDoseParamCurve(effect, dosevector, paramchangevector, titletext, effectLevelSteps)
+% SBPOPplotDoseParamCurve(effect, dosevector, paramchangevector, titletext, effectLevelSteps, targetEffect)
+%
+% effect: matrix with determined effect values (columns correspond to
+%   different parameter settings (parameterchangevector) and rows correspond
+%    to different dose amount settings (dosevector)).
+% dosevector: vector with different dosing amounts, corresponding to  the
+%   effect matrix.
+% paramchangevector: vector with values for an additional parameter that
+%   was varied.
+% effectLevelSteps: effect level steps to consider. Default: [5,10,20,30,40,50,60,70,80,90,95]
+% targetEffect: special effect levels that are plotted in a different color.
+% titletext: text to use as figure title
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~exist('titletext','var')
+    titletext  = 'Untitled';
+end
+if ~exist('effectLevelSteps','var')
+    effectLevelSteps  = [5,10,20,30,40,50,60,70,80,90,95];
+end
+if isempty(effectLevelSteps),
+    effectLevelSteps  = [5,10,20,30,40,50,60,70,80,90,95];
+end    
+if ~exist('targetEffect','var')
+    targetEffect  = []; % means undefined!
+end
+% add targetEffect to effectLevelSteps (as last effect level)
+effectLevelSteps = [effectLevelSteps targetEffect];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INTERPLOATE TO OBTAIN DOSE value for given
+% effect level and parametervalue
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+doseMatrix = [];
+for k1=1:length(paramchangevector),
+    for k2=1:length(effectLevelSteps),
+        % we need to find the dose that is needed to obtain with current
+        % parameter the current effect level. The splines not always
+        % invertible => use bisection.
+        effectLevel = effectLevelSteps(k2);
+        dose = getDose4Effect(dosevector, effect(:,k1), effectLevel);
+        doseMatrix(k2,k1) = dose;
+    end
+end
+% doseMatrix: entries: doses to obtain desired effect level with given parameter
+%             columns: each column different parameter
+%             rows: each row different desired effect level
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Split up target Effect Level if present
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(targetEffect),
+    effectLevelSteps = effectLevelSteps(1:end-length(targetEffect));
+    targetDoseMatrix = doseMatrix(end-length(targetEffect)+1:end,:);
+    doseMatrix = doseMatrix(1:end-length(targetEffect),:);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Plot the curves (for effect levels)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+figure; clf;
+for k=1:size(doseMatrix,1)
+    effectLevel = effectLevelSteps(k);
+    dose = doseMatrix(k,:);
+    loglog(dose,paramchangevector, 'LineWidth', 2); hold on;
+    text(mean(dose), mean(paramchangevector), num2str(effectLevel),'EdgeColor','black','BackgroundColor','white');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Plot the curves (for target levels)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(targetEffect),
+    for k=1:size(targetDoseMatrix,1)
+        effectLevel = targetEffect(k);
+        dose = targetDoseMatrix(k,:);
+        loglog(dose,paramchangevector, 'LineWidth', 2, 'Color', 'red'); hold on;
+        text(mean(dose), mean(paramchangevector), num2str(effectLevel),'EdgeColor','red','BackgroundColor','white');
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Decorate the plot
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+xlabel('Dose');
+hlhlx = title(titletext,'Interpreter','none');
+set(hlhlx,'Interpreter','none');
+ylabel('Parameter');
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Do bisection to get the dose for given effect and parameter
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [dose] = getDose4Effect(dosevector, effect, effectLevel)
+lowDose = min(dosevector);
+highDose = max(dosevector);
+currentDose = (highDose+lowDose)/2;
+stopDeltaDose = 1e-3*lowDose;
+while abs(highDose-lowDose) > stopDeltaDose,
+    doseeffect = interpcsSB(dosevector,effect,currentDose);
+    if doseeffect > effectLevel,
+        lowDose = currentDose;
+        highDose = highDose;
+        currentDose = (highDose+lowDose)/2;
+    elseif doseeffect < effectLevel,
+        lowDose = lowDose;
+        highDose = currentDose;
+        currentDose = (highDose+lowDose)/2;
+    else
+        break;
+    end
+end
+dose = currentDose;
+return
+
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/SBPOPtissuedata.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/SBPOPtissuedata.m
new file mode 100644
index 0000000000000000000000000000000000000000..ab96ec8c407d78c0606a000562ee0cefd8f2ad64
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/SBPOPtissuedata.m
@@ -0,0 +1,147 @@
+function SBPOPtissuedata()
+% SBPOPtissuedata: This function is simply a collection of literature data
+% from two references (see below), that stores the volumes of different
+% tissues and the corresponding volumes of the interstitial spaces.
+%
+% PBPK parameters (organ weight and volume and interstitial space volume)
+% for the 70kg, 20% fat "standardhuman" from reference [1] and [2] (see
+% below). 
+%
+% USAGE: 
+% ======
+% SBPOPtissuedata()
+% Just run the function and look at the output. In order to learn how the
+% values have been determined, please read the complete function (this
+% here).
+%
+% References:
+% ===========
+% [1] D.G. Levitt (2003) The pharmacokinetics of the interstitial space in
+% humans, BMC Clinical Pharmacology, 3
+% [2] R.P. Brown et al. (1997) Physiological parameter values for
+% physiologically based pharmacokinetic models, Toxicology and Industrial
+% Health, 13(4), 407-484 
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+
+
+% The following matrices define the considered tissues, their weight and volume 
+% of their interstitial space that is relevant to the antibody/drug distribution.
+% The factor represents the conversion factor from weight to volume for the different
+% organs. It is taken from reference [2]. Some weights needed to be
+% inferred, for more information, please see below. Some of the factors
+% were not defined in the references. Then they have been set to 1 (e.g. blood, 
+% liver, tendon, other) or inferred (e.g. portal, which was determined from
+% the organs involved in it).
+PBPK_data = {
+% Tissue            Weight (kg)       Interstitial tissue volume (L)    factor (L/kg) 
+'blood          '   5.5               2.68345                           1 % not given in [2]  
+'liver          '   1.8               0.2898                            1 % not given in [2]
+% "portal" in reference [1] refers to the organs drained by the portal vein (stomach, small and large
+% intestine, spleen, pancreas)
+'portal         '   1.5               0.351                             1.045 % factor assumed as approx mean from different components factors, defined in [2]
+'muscle         '   26                3.042                             1.04
+'kidney         '   0.31              0.04092                           1.05
+% "brain": blood-brain barrier will prevent the distribution into the interstitial space
+'brain          '  1.4                0                                 1.04
+'heart          '  0.33               0.066                             1.03
+'lung           '  0.536              0.08576                           1.05
+'skin           '  2.6                1.092                             1.45    % manually chosen factor => fits nicely with value used by Matthias in a previous project
+'tendon         '  3                  2.55                              1       % factor assumed (not given in [2])
+% "bone" refers to the inert solid component of bone that has no volume of distribution or blood flow
+'bone           '  4                  0                                 1.99    % factor not including marrow
+'adipose        '  17.5               3.5                               0.916   
+'other          '  5.524              3.75632                           1       % factor assumed (not given in [2])
+};
+
+% Determine the tissue volumes from the weights and factors, defined in the
+% PBPK_data matrix and write the result in the 5th column.
+for k=1:size(PBPK_data,1),
+    weight = PBPK_data{k,2};
+    factor = PBPK_data{k,4};
+    volume = weight*factor;
+    PBPK_data{k,5} = volume;
+end
+
+% Above, "portal" includes 5 different organs: stomach, small and large
+% intestine, spleen, pancreas. Reference [2] tells us the relative weights
+% for a reference man (stomach: 0.21%, small intestine: 0.91%, large
+% intestine: 0.53%, spleen: 0.26%, pancreas: 0.14%). Using these
+% definitions and a 70kg standard human the sum of the weights is 1.435kg.
+% This is in contrast to the 1.5kg for "portal" in reference [1]. We just
+% scale the relative weights to obtain a total weight of 1.5kg and
+% determine the volume of the organ tissues using these weights and the
+% factors, given in [2]. Furthermore, we split the interstitial space
+% volume, defined in [1] for portal (0.351) according to the ratio tissue
+% weight / portal tissue weight. This is all just an approximation, but a
+% reasonable one :-)
+PBPK_data_portal = {
+'stomach        '   0.154             0.036                             1.05  
+'small intestine'   0.666             0.1558                            1.045 
+'large intestine'   0.388             0.0907                            1.042 
+'spleen         '   0.190             0.0445                            1.054 
+'pancreas       '   0.102             0.024                             1.045 
+};
+
+% Determine the tissue volumes for the portal organ tissues
+for k=1:size(PBPK_data_portal,1),
+    weight = PBPK_data_portal{k,2};
+    factor = PBPK_data_portal{k,4};
+    volume = weight*factor;
+    PBPK_data_portal{k,5} = volume;
+end
+
+% Write out the information:
+clc;
+disp('Tissue information: organ volumes and interstitial spaces');
+disp('=========================================================');
+disp('Assumption: 70kg, 20% fat, standardhuman');
+disp(' ');
+disp('Tissue              Volume (L)          Interstitial space (L)');
+disp('---------------------------------------------------------------');
+totalvolume = 0;
+totalitstspace = 0;
+for k=1:size(PBPK_data,1),
+    organ = PBPK_data{k,1};
+    tissuevolume = PBPK_data{k,5};
+    interstitialspace = PBPK_data{k,3};
+    disp(sprintf('%s\t\t%1.4f\t\t\t\t%g',organ,tissuevolume,interstitialspace));
+    totalvolume = totalvolume + tissuevolume;
+    totalitstspace = totalitstspace + interstitialspace;
+end
+disp('---------------------------------------------------------------');
+disp(sprintf('Total:\t\t\t\t%1.4f\t\t\t\t%g',totalvolume,totalitstspace));
+disp('---------------------------------------------------------------');
+disp(' ');
+disp('"Portal" tissue above contains several different organs:');
+disp(' ');
+disp('Tissue              Volume (L)          Interstitial space (L)');
+disp('---------------------------------------------------------------');
+for k=1:size(PBPK_data_portal,1),
+    organ = PBPK_data_portal{k,1};
+    tissuevolume = PBPK_data_portal{k,5};
+    interstitialspace = PBPK_data_portal{k,3};
+    disp(sprintf('%s\t\t%1.4f\t\t\t\t%g',organ,tissuevolume,interstitialspace));
+end
+disp('---------------------------------------------------------------');
+disp('For information about the derivation of these values, please type:');
+disp('               >> type SBPOPtissuedata');
+
+ 
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/standard_Drug_LigandTarget_model.txtbc b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/standard_Drug_LigandTarget_model.txtbc
new file mode 100644
index 0000000000000000000000000000000000000000..51fad7a99ca51daeec77e70a08dc4f3639f9333b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/standard_Drug_LigandTarget_model.txtbc
@@ -0,0 +1,524 @@
+********** MODEL NAME
+standard_Drug_LigandTarget_model
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+********** MODEL NOTES
+General 3 compartment (ligand target) model (plasma, disease tissue, 
+peripheral tissue) containing drug (mAb, nanobody, aptamer, etc.) kinetics, 
+target kinetics, drug/target binding kinetics, target dimerization, binding 
+protein kinetics and binding to target.
+
+Model assumptions are indicated in comment text.
+
+It is modular ... just cut out what you do not need.
+    
+D:          drug (monoclonal antibody, nanobody, aptamer, ...)
+T1:         target 1 (ligand)
+D_T1:       target 1 bound to D
+T1_D_T1:    2times target 1 bound to D (one T1 on each arm)
+T1_T1:      dimerized target 1
+BP:         target binding soluble protein
+T1_BP:      target 1 bound to BP
+
+Possible improvements of the model:
+===================================
+- Adding a second target T2
+- Adding a receptor R1 to which the target can bind 
+    - only in tissue compartment but possible also in all compartments
+- Adding binding of drug to target dimer
+- ...
+
+********** MODEL STATE INFORMATION
+% Definition of initial conditions for all the species. 
+% Mostly they are zero and thus would not need to be defined. However,
+% in this section the connection between species and their compartments is 
+% done, using the additional information {isSpecie:compartmentname:unittype},
+% where "compartmentname" is the name of the parameter or variable, defining 
+% the volume of the compartment and "unittype" is "amount" or "concentration".
+% This additional information is crucial for correct simulation and thus needs
+% to be provided for each state variable!
+
+D_plasma(0)              = 0   {isSpecie:volume_plasma:concentration}        % (nM) concentration of D in plasma
+D_itst_tissue(0)         = 0   {isSpecie:volume_itst_tissue:concentration}   % (nM) concentration of D in interstitial space around disease compartment
+D_itst_peri(0)           = 0   {isSpecie:volume_itst_peri:concentration}     % (nM) concentration of D in interstitial space around peripheral compartment
+
+T1_plasma(0)             = 0   {isSpecie:volume_plasma:concentration}        % (nM) concentration of T1 in plasma
+T1_itst_tissue(0)        = 0   {isSpecie:volume_itst_tissue:concentration}   % (nM) concentration of T1 interstitial space around disease compartment
+T1_itst_peri(0)          = 0   {isSpecie:volume_itst_peri:concentration}     % (nM) concentration of T1 in interstitial space around peripheral compartment
+
+D_T1_plasma(0)           = 0   {isSpecie:volume_plasma:concentration}        % (nM) concentration of D/T1 complex in plasma
+D_T1_itst_tissue(0)      = 0   {isSpecie:volume_itst_tissue:concentration}   % (nM) concentration of D/T1 complex in interstitial space around disease compartment
+D_T1_itst_peri(0)        = 0   {isSpecie:volume_itst_peri:concentration}     % (nM) concentration of D/T1 complex in interstitial space around peripheral compartment 
+
+T1_D_T1_plasma(0)        = 0   {isSpecie:volume_plasma:concentration}        % (nM) concentration of T1/D/T1 complex in plasma
+T1_D_T1_itst_tissue(0)   = 0   {isSpecie:volume_itst_tissue:concentration}   % (nM) concentration of T1/D/T1 complex in interstitial space around disease compartment
+T1_D_T1_itst_peri(0)     = 0   {isSpecie:volume_itst_peri:concentration}     % (nM) concentration of T1/D/T1 complex in interstitial space around peripheral compartment 
+
+T1_T1_plasma(0)          = 0   {isSpecie:volume_plasma:concentration}        % (nM) concentration of dimerized T1 in plasma
+T1_T1_itst_tissue(0)     = 0   {isSpecie:volume_itst_tissue:concentration}   % (nM) concentration of dimerized T1 in interstitial space around disease compartment
+T1_T1_itst_peri(0)       = 0   {isSpecie:volume_itst_peri:concentration}     % (nM) concentration of dimerized T1 in interstitial space around peripheral compartment 
+
+BP_plasma(0)             = 0   {isSpecie:volume_plasma:concentration}        % (nM) concentration of T1 binding soluble protein in plasma
+BP_itst_tissue(0)        = 0   {isSpecie:volume_itst_tissue:concentration}   % (nM) concentration of T1 binding soluble protein in interstitial space around disease compartment
+BP_itst_peri(0)          = 0   {isSpecie:volume_itst_peri:concentration}     % (nM) concentration of T1 binding soluble protein in interstitial space around peripheral compartment 
+
+T1_BP_plasma(0)          = 0   {isSpecie:volume_plasma:concentration}        % (nM) concentration of T1/BP complex in plasma
+T1_BP_itst_tissue(0)     = 0   {isSpecie:volume_itst_tissue:concentration}   % (nM) concentration of T1/BP complex in interstitial space around disease compartment
+T1_BP_itst_peri(0)       = 0   {isSpecie:volume_itst_peri:concentration}     % (nM) concentration of T1/BP complex in interstitial space around peripheral compartment 
+
+
+********** MODEL PARAMETERS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define general parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+weight                     = 70        % (kg) Weight of standard person (needed to determine dose in nmol from mg/kg)
+volume_body                = 74.8757  {isCompartment:}             % (L) Total body volume
+volume_itst                = 17.4572  {isCompartment:volume_body}  % (L) Total volume of interstitial space
+volume_blood               = 5.5      {isCompartment:volume_body}  % (L) Total volume of blood
+volume_plasma              = 2.68345  {isCompartment:volume_body}  % (L) Plasma volume (corresponds to "interstitial space" in blood)
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define disease tissue related parameters (project specific)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+volume_tissue              = 1        {isCompartment:volume_body}  % (L) Volume of disease tissue 
+volume_itst_tissue         = 1        {isCompartment:volume_body}  % (L) Volume of interstitial space around disease tissue
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define lymph flow related rate constant
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ASSUMPTION: Rate constants for lymph flow related clearance from interstitial 
+%             space into plasma compartments are the same for all species. Therefore,
+%             we define a single parameter vor them.
+kL                         = 0         % (1/day) Rate constant for lymph flow related clearance from interstitial space into plasma
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define D only related parameters (project specific)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+F                          = 1         % (.) Bioavailability
+molecularweight_D          = 150000    % (Da) Molecular weight of D
+kPS_D_total                = 0         % (L/day) D total surface area exchange coefficient
+kCL_D_plasma               = 0         % (1/day) Rate constant for clearance of D from the plasma compartment
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define T1 only related parameters (project specific)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+molecularweight_T1         = 10000     % (Da) Molecular weight of T1 (only used for unit conversion for plotting, etc.)
+ksyn_T1_plasma             = 0         % (nmol/day) Synthesis rate of T1 in plasma (amount/time units)
+ksyn_T1_itst_tissue        = 0         % (nmol/day) Synthesis rate of T1 in interstitial space around disease tissue
+ksyn_T1_itst_peri          = 0         % (nmol/day) Synthesis rate of T1 in interstitial space around peripheral compartment
+kPS_T1_total               = 0         % (L/day) Target T1 total surface area exchange coefficient
+kCL_T1_plasma              = 0         % (1/day) Rate constant for clearance of T1 from the plasma compartment
+kCL_T1_itst_tissue         = 0         % (1/day) Rate constant for clearance of T1 from the interstitial space around disease tissue
+kCL_T1_itst_peri           = 0         % (1/day) Rate constant for clearance of T1 from the interstitial space around peripheral compartment
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define D / T1 binding parameters (project specific)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+kon_D_T1                   = 0         % (1/(nM*day)) Binding rate constant drug and T1
+KD_D_T1                    = 0         % (nM) Dissociation constant D and T1 koff_D_T1: KD_D_T1 * kon_D_T1
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define parameters related to T1 dimerization (project specific)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+kon_T1_T1                  = 0         % (1/(nM*day)) Target T1-dimerization rate constant
+KD_T1_T1                   = 0         % (nM) Target T1-Dimer-Dissociation constant koff_T1_T1: KD_T1_T1 * kon_T1_T1
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define parameters related to soluble target T1 binding protein BP (project specific)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+kPS_BP_total               = 0         % (L/day) BP total surface area exchange coefficient
+kon_T1_BP                  = 0         % (1/(nM*day)) Binding rate constant T1 and BP
+KD_T1_BP                   = 0         % (nM) Dissociation constant T1/BP complex koff_T1_BP: KD_T1_BP * kon_T1_BP
+
+********** MODEL VARIABLES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Calculate the disease dependent volumes for the peripheral compartment
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+volume_peri                = volume_body-volume_tissue-volume_blood        {isCompartment:volume_body}  % (L) Peripheral compartment volume
+volume_itst_peri           = volume_itst-volume_itst_tissue-volume_plasma  {isCompartment:volume_body}  % (L) Volume of interstitial space around peripheral compartment
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Calculate D only related parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+kPS_D_plasma_itst_tissue   = volume_tissue/volume_body*kPS_D_total    % (L/day) D surface area exchange coefficient between plasma and interstitial tissue around disease tissue
+kPS_D_plasma_itst_peri     = volume_peri/volume_body*kPS_D_total      % (L/day) D surface area exchange coefficient between plasma and interstitial tissue around peripheral compartment
+% Assume same clearance rate constant in all compartments
+kCL_D_itst_tissue          = kCL_D_plasma                             % (1/day) Rate constant for clearance of D from the interstitial space around disease tissue
+kCL_D_itst_peri            = kCL_D_plasma                             % (1/day) Rate constant for clearance of D from the interstitial space around peripheral compartment
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Calculate T1 only related parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+kPS_T1_plasma_itst_tissue  = volume_tissue/volume_body*kPS_T1_total   % (L/day) Target T1 surface area exchange coefficient between plasma and interstitial tissue around disease tissue
+kPS_T1_plasma_itst_peri    = volume_peri/volume_body*kPS_T1_total     % (L/day) Target T1 surface area exchange coefficient between plasma and interstitial tissue around peripheral compartment
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Calculate T1/D binding related parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ASSUMPTION: same binding kinetics for D with T1 and D/T1 complex to T1
+kon_T1_D_T1                = kon_D_T1                                 % (1/(nM*day)) Binding rate constant D/T1 complex to T1
+KD_T1_D_T1                 = KD_D_T1                                  % (nM) Dissociation constant D/T1 complex and T1 koff_T1_D_T1: KD_T1_D_T1 * kon_T1_D_T1
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Calculate D/T1 complex related parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ASSUMPTION: same kinetic rate constants for exchange, lymph flow, and  
+%             clearance reactions as for the free D
+kPS_D_T1_plasma_itst_tissue    = kPS_D_plasma_itst_tissue             % (L/day) D/T1 complex surface area exchange coefficient between plasma and interstitial tissue around disease tissue
+kPS_D_T1_plasma_itst_peri      = kPS_D_plasma_itst_peri               % (L/day) D/T1 complex surface area exchange coefficient between plasma and interstitial tissue around peripheral compartment
+kCL_D_T1_plasma                = kCL_D_plasma                         % (1/day) Rate constant for clearance of D/T1 from the plasma compartment
+kCL_D_T1_itst_tissue           = kCL_D_itst_tissue                    % (1/day) Rate constant for clearance of D/T1 from the interstitial tissue around disease tissue
+kCL_D_T1_itst_peri             = kCL_D_itst_peri                      % (1/day) Rate constant for clearance of D/T1 from the interstitial tissue around peripheral compartment
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Calculate T1/D/T1 complex related parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ASSUMPTION: same kinetic rate constants for exchange, lymph flow, and  
+%             clearance reactions as for the free D
+kPS_T1_D_T1_plasma_itst_tissue = kPS_D_plasma_itst_tissue             % (L/day) T1/D/T1 complex surface area exchange coefficient between plasma and interstitial tissue around disease tissue
+kPS_T1_D_T1_plasma_itst_peri   = kPS_D_plasma_itst_peri               % (L/day) T1/D/T1 complex surface area exchange coefficient between plasma and interstitial tissue around peripheral compartment
+kCL_T1_D_T1_plasma             = kCL_D_plasma                         % (1/day) Rate constant for clearance of T1/D/T1 from the plasma compartment
+kCL_T1_D_T1_itst_tissue        = kCL_D_itst_tissue                    % (1/day) Rate constant for clearance of T1/D/T1 from the interstitial tissue around disease tissue
+kCL_T1_D_T1_itst_peri          = kCL_D_itst_peri                      % (1/day) Rate constant for clearance of T1/D/T1 from the interstitial tissue around peripheral compartment
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Calculate T1 dimerization related parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ASSUMPTION: same kinetic rate constants for exchange, lymph flow, and  
+%             clearance reactions as for the T1 alone 
+kPS_T1_T1_plasma_itst_tissue   = kPS_T1_plasma_itst_tissue            % (L/day) Dimerized T1 surface area exchange coefficient between plasma and interstitial tissue around disease tissue
+kPS_T1_T1_plasma_itst_peri     = kPS_T1_plasma_itst_peri              % (L/day) Dimerized T1 surface area exchange coefficient between plasma and interstitial tissue around peripheral compartment
+kCL_T1_T1_plasma               = kCL_T1_plasma                        % (1/day) Rate constant for clearance of dimerized T1 from the plasma compartment
+kCL_T1_T1_itst_tissue          = kCL_T1_itst_tissue                   % (1/day) Rate constant for clearance of dimerized T1 from the interstitial tissue around disease tissue
+kCL_T1_T1_itst_peri            = kCL_T1_itst_peri                     % (1/day) Rate constant for clearance of dimerized T1 from the interstitial tissue around peripheral compartment
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Calculate parameters related to soluble T1 binding protein BP (project specific)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+kPS_BP_plasma_itst_tissue      = volume_tissue/volume_body*kPS_BP_total     % (L/day) BP surface area exchange coefficient between plasma and interstitial tissue around disease tissue
+kPS_BP_plasma_itst_peri        = volume_peri/volume_body*kPS_BP_total       % (L/day) BP surface area exchange coefficient between plasma and interstitial tissue around peripheral compartment
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Unit conversion factors
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+FACTOR_mg_per_kg_2_nmol        = weight/molecularweight_D*1e6               % (nmol/(mg/kg)) unit conversion factor for dosing input
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Unit conversions for plotting and checking
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+D_plasma_amount                = D_plasma * volume_plasma
+D_itst_tissue_amount           = D_itst_tissue * volume_itst_tissue
+D_itst_peri_amount             = D_itst_peri*volume_itst_peri
+T1_plasma_amount               = T1_plasma * volume_plasma
+T1_itst_tissue_amount          = T1_itst_tissue * volume_itst_tissue
+T1_itst_peri_amount            = T1_itst_peri*volume_itst_peri
+
+********** MODEL REACTIONS
+% Please note that all reactions should be in amount/time units => nmol/day
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% D only reactions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% D input into plasma compartment (INPUT1 in (mg/kg)/day)
+=> D_plasma : v_D_input                                       % (nmol/day) 
+	vf = F * FACTOR_mg_per_kg_2_nmol*INPUT1
+
+% Passive exchange of D between plasma and interstitial space around disease compartment (diffusion type of mechanism)
+D_plasma <=> D_itst_tissue : v_D_plasma_itst_tissue_ex        % (nmol/day) 
+	vf = kPS_D_plasma_itst_tissue*D_plasma
+    vr = kPS_D_plasma_itst_tissue*D_itst_tissue
+
+% Passive exchange of D between plasma and interstitial space around peripheral compartment (diffusion type of mechanism)
+D_plasma <=> D_itst_peri : v_D_plasma_itst_peripheral_ex      % (nmol/day) 
+	vf = kPS_D_plasma_itst_peri*D_plasma
+    vr = kPS_D_plasma_itst_peri*D_itst_peri
+
+% Active transport of D due to lymph flow from interstitial space around disease tissue into plasma compartment
+D_itst_tissue => D_plasma : v_D_itst_tissue_plasma_lymph      % (nmol/day) 
+	vf = (kL*D_itst_tissue)*volume_itst_tissue
+
+% Active transport of D due to lymph flow from interstitial space around peripheral compartment into plasma compartment
+D_itst_peri => D_plasma : v_D_itst_peri_plasma_lymph          % (nmol/day)
+    vf = (kL*D_itst_peri)*volume_itst_peri 
+
+% Clearance of D from plasma
+D_plasma =>  : v_D_plasma_cl                                    % (nmol/day)
+	vf = (kCL_D_plasma*D_plasma)*volume_plasma
+
+% Clearance of D from interstitial tissue around disease compartment
+D_itst_tissue => : v_D_itst_tissue_cl                           % (nmol/day)
+    vf = (kCL_D_itst_tissue*D_itst_tissue)*volume_itst_tissue
+
+% Clearance of D from interstitial tissue around peripheral compartment
+D_itst_peri => : v_D_itst_peri_cl                               % (nmol/day)
+    vf = (kCL_D_itst_peri*D_itst_peri)*volume_itst_peri
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Target T1 only reactions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    
+% Target T1 synthesis in plasma (constant production rate)
+=> T1_plasma : v_T1_plasma_syn                                        % (nmol/day)
+    vf = ksyn_T1_plasma
+
+% Target T1 synthesis in interstitial space around disease tissue (constant production rate)
+=> T1_itst_tissue : v_T1_itst_tissue_syn                              % (nmol/day)
+    vf = ksyn_T1_itst_tissue
+
+% Target T1 synthesis in interstitial space around peripheral tissue (constant production rate)
+=> T1_itst_peri : v_T1_itst_peri_syn                                  % (nmol/day)
+    vf = ksyn_T1_itst_peri
+
+% Passive exchange of T1 between plasma and interstitial space around disease compartment (diffusion type of mechanism)
+T1_plasma <=> T1_itst_tissue : v_T1_plasma_itst_tissue_ex             % (nmol/day) 
+	vf = kPS_T1_plasma_itst_tissue*T1_plasma
+    vr = kPS_T1_plasma_itst_tissue*T1_itst_tissue
+
+% Passive exchange of T1 between plasma and interstitial space around peripheral compartment (diffusion type of mechanism)
+T1_plasma <=> T1_itst_peri : v_T1_plasma_itst_peripheral_ex            % (nmol/day)
+	vf = kPS_T1_plasma_itst_peri*T1_plasma
+    vr = kPS_T1_plasma_itst_peri*T1_itst_peri
+    
+% Active transport of T1 due to lymph flow from interstitial space around disease tissue into plasma compartment
+T1_itst_tissue => T1_plasma : v_T1_itst_tissue_plasma_lymph            % (nmol/day)
+	vf = (kL*T1_itst_tissue)*volume_itst_tissue
+
+% Active transport of T1 due to lymph flow from interstitial space around peripheral compartment into plasma compartment
+T1_itst_peri => T1_plasma : v_T1_itst_peri_plasma_lymph                % (nmol/day)
+	vf = (kL*T1_itst_peri)*volume_itst_peri
+    
+% Clearance of T1 from plasma
+T1_plasma =>  : v_T1_plasma_cl                                        % (nmol/day)
+	vf = (kCL_T1_plasma*T1_plasma)*volume_plasma
+
+% Clearance of T1 from interstitial tissue around disease compartment
+T1_itst_tissue => : v_T1_itst_tissue_cl                               % (nmol/day)
+    vf = (kCL_T1_itst_tissue*T1_itst_tissue)*volume_itst_tissue
+
+% Clearance of T1 from interstitial tissue around peripheral compartment
+T1_itst_peri => : v_T1_itst_peri_cl                                   % (nmol/day)
+    vf = (kCL_T1_itst_peri*T1_itst_peri)*volume_itst_peri
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% D / Target T1 binding reactions (single binding)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% Binding of D with T1 in plasma compartment
+D_plasma+T1_plasma <=> D_T1_plasma : v_D_T1_plasma_reac          % (nmol/day)
+	vf = (kon_D_T1*D_plasma*T1_plasma)*volume_plasma
+    vr = (kon_D_T1*KD_D_T1*D_T1_plasma)*volume_plasma
+
+% Binding of D with T1 in interstitial tissue around disease tissue
+D_itst_tissue+T1_itst_tissue <=> D_T1_itst_tissue : v_D_T1_itst_tissue_reac % (nmol/day)
+	vf = (kon_D_T1*D_itst_tissue*T1_itst_tissue)*volume_itst_tissue
+    vr = (kon_D_T1*KD_D_T1*D_T1_itst_tissue)*volume_itst_tissue
+
+% Binding of D with T1 in interstitial tissue around peripheral tissue
+D_itst_peri+T1_itst_peri <=> D_T1_itst_peri : v_D_T1_itst_peri_reac % (nmol/day)
+	vf = (kon_D_T1*D_itst_peri*T1_itst_peri)*volume_itst_peri
+    vr = (kon_D_T1*KD_D_T1*D_T1_itst_peri)*volume_itst_peri
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% D_T1 / Target T1 binding reactions (double binding (bivalent drug))
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+       
+% Binding of second T1 to D_T1 in plasma compartment    
+D_T1_plasma+T1_plasma <=> T1_D_T1_plasma : v_T1_D_T1_plasma_reac
+	vf = (kon_T1_D_T1*D_T1_plasma*T1_plasma)*volume_plasma
+    vr = (kon_T1_D_T1*KD_T1_D_T1*T1_D_T1_plasma)*volume_plasma
+
+% Binding of second T1 to D_T1 in interstitial space around disease tissue
+D_T1_itst_tissue+T1_itst_tissue <=> T1_D_T1_itst_tissue : v_T1_D_T1_itst_tissue_reac % (nmol/day)
+	vf = (kon_T1_D_T1*D_T1_itst_tissue*T1_itst_tissue)*volume_itst_tissue
+    vr = (kon_T1_D_T1*KD_T1_D_T1*T1_D_T1_itst_tissue)*volume_itst_tissue
+
+% Binding of second T1 to D_T1 in interstitial space around peripheral tissue
+D_T1_itst_peri+T1_itst_peri <=> T1_D_T1_itst_peri : v_T1_D_T1_itst_peri_reac % (nmol/day)
+	vf = (kon_T1_D_T1*D_T1_itst_peri*T1_itst_peri)*volume_itst_peri
+    vr = (kon_T1_D_T1*KD_T1_D_T1*T1_D_T1_itst_peri)*volume_itst_peri
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% D/T1 complex transport and clearance reactions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% Passive exchange of D/T1 complex between plasma and interstitial space around disease compartment (diffusion type of mechanism)
+D_T1_plasma <=> D_T1_itst_tissue : v_D_T1_plasma_itst_tissue_ex % (nmol/day)
+	vf = kPS_D_T1_plasma_itst_tissue*D_T1_plasma
+    vr = kPS_D_T1_plasma_itst_tissue*D_T1_itst_tissue
+ 
+% Passive exchange of D/T1 complex between plasma and interstitial space around peripheral compartment (diffusion type of mechanism)
+D_T1_plasma <=> D_T1_itst_peri : v_D_T1_plasma_itst_peripheral_ex % (nmol/day)
+	vf = kPS_D_T1_plasma_itst_peri*D_T1_plasma
+    vr = kPS_D_T1_plasma_itst_peri*D_T1_itst_peri
+    
+% Active transport of D/T1 complex due to lymph flow from interstitial space around disease tissue into plasma compartment
+D_T1_itst_tissue => D_T1_plasma : v_D_T1_itst_tissue_plasma_lymph      % (nmol/day) 
+	vf = (kL*D_T1_itst_tissue)*volume_itst_tissue
+
+% Active transport of D/T1 complex due to lymph flow from interstitial space around peripheral compartment into plasma compartment
+D_T1_itst_peri => D_T1_plasma : v_D_T1_itst_peri_plasma_lymph          % (nmol/day)
+    vf = (kL*D_T1_itst_peri)*volume_itst_peri 
+   
+% Clearance of D/T1 complex from plasma
+D_T1_plasma =>  : v_D_T1_plasma_cl                                    % (nmol/day)
+	vf = (kCL_D_T1_plasma*D_T1_plasma)*volume_plasma
+
+% Clearance of D/T1 complex from interstitial tissue around disease compartment
+D_T1_itst_tissue => : v_D_T1_itst_tissue_cl                           % (nmol/day)
+    vf = (kCL_D_T1_itst_tissue*D_T1_itst_tissue)*volume_itst_tissue
+
+% Clearance of D/T1 complex from interstitial tissue around peripheral compartment
+D_T1_itst_peri => : v_D_T1_itst_peri_cl                               % (nmol/day)
+    vf = (kCL_D_T1_itst_peri*D_T1_itst_peri)*volume_itst_peri
+   
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% T1/D/T1 complex transport and clearance reactions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    
+% Passive exchange of T1/D/T1 complex between plasma and interstitial space around disease compartment (diffusion type of mechanism)
+T1_D_T1_plasma <=> T1_D_T1_itst_tissue : v_T1_D_T1_plasma_itst_tissue_ex % (nmol/day)
+	vf = kPS_T1_D_T1_plasma_itst_tissue*T1_D_T1_plasma
+    vr = kPS_T1_D_T1_plasma_itst_tissue*T1_D_T1_itst_tissue
+ 
+% Passive exchange of T1/D/T1 complex between plasma and interstitial space around peripheral compartment (diffusion type of mechanism)
+T1_D_T1_plasma <=> T1_D_T1_itst_peri : v_T1_D_T1_plasma_itst_peripheral_ex % (nmol/day)
+	vf = kPS_T1_D_T1_plasma_itst_peri*T1_D_T1_plasma
+    vr = kPS_T1_D_T1_plasma_itst_peri*T1_D_T1_itst_peri
+    
+% Active transport of T1/D/T1 complex due to lymph flow from interstitial space around disease tissue into plasma compartment
+T1_D_T1_itst_tissue => T1_D_T1_plasma : v_T1_D_T1_itst_tissue_plasma_lymph      % (nmol/day) 
+	vf = (kL*T1_D_T1_itst_tissue)*volume_itst_tissue
+
+% Active transport of T1/D/T1 complex due to lymph flow from interstitial space around peripheral compartment into plasma compartment
+T1_D_T1_itst_peri => T1_D_T1_plasma : v_T1_D_T1_itst_peri_plasma_lymph          % (nmol/day)
+    vf = (kL*T1_D_T1_itst_peri)*volume_itst_peri 
+
+% Clearance of T1/D/T1 complex from plasma
+T1_D_T1_plasma => : v_T1_D_T1_plasma_cl                                    % (nmol/day)
+	vf = (kCL_T1_D_T1_plasma*T1_D_T1_plasma)*volume_plasma
+
+% Clearance of T1/D/T1 complex from interstitial tissue around disease compartment
+T1_D_T1_itst_tissue => : v_T1_D_T1_itst_tissue_cl                           % (nmol/day)
+    vf = (kCL_T1_D_T1_itst_tissue*T1_D_T1_itst_tissue)*volume_itst_tissue
+
+% Clearance of T1/D/T1 complex from interstitial tissue around peripheral compartment
+T1_D_T1_itst_peri => : v_T1_D_T1_itst_peri_cl                               % (nmol/day)
+    vf = (kCL_T1_D_T1_itst_peri*T1_D_T1_itst_peri)*volume_itst_peri
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Target T1 dimerization reactions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    
+
+% Dimerization of T1 in plasma
+T1_plasma + T1_plasma <=> T1_T1_plasma : v_T1_T1_plasma_reac                       % (nmol/day)
+	vf = (kon_T1_T1*T1_plasma*T1_plasma)*volume_plasma
+    vr = (kon_T1_T1*KD_T1_T1*T1_T1_plasma)*volume_plasma
+
+% Dimerization of T1 in interstitial tissue around disease compartment
+T1_itst_tissue+T1_itst_tissue <=> T1_T1_itst_tissue : v_T1_T1_itst_tissue_reac     % (nmol/day)
+	vf = (kon_T1_T1*T1_itst_tissue*T1_itst_tissue)*volume_itst_tissue
+    vr = (kon_T1_T1*KD_T1_T1*T1_T1_itst_tissue)*volume_itst_tissue
+
+% Dimerization of T1 in interstitial tissue around peripheral compartment
+T1_itst_peri+T1_itst_peri <=> T1_T1_itst_peri : v_T1_T1_itst_peri_reac             % (nmol/day)
+	vf = (kon_T1_T1*T1_itst_peri*T1_itst_peri)*volume_itst_peri
+    vr = (kon_T1_T1*KD_T1_T1*T1_T1_itst_peri)*volume_itst_peri
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Dimerized T1 transport and clearance reactions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%      
+
+% Passive exchange of T1 dimer between plasma and interstitial space around disease compartment (diffusion type of mechanism)
+T1_T1_plasma <=> T1_T1_itst_tissue : v_T1_T1_plasma_itst_tissue_ex % (nmol/day)
+	vf = kPS_T1_T1_plasma_itst_tissue*T1_T1_plasma
+    vr = kPS_T1_T1_plasma_itst_tissue*T1_T1_itst_tissue
+ 
+% Passive exchange of T1 dimer complex between plasma and interstitial space around peripheral compartment (diffusion type of mechanism)
+T1_T1_plasma <=> T1_T1_itst_peri : v_T1_T1_plasma_itst_peripheral_ex % (nmol/day)
+	vf = kPS_T1_T1_plasma_itst_peri*T1_T1_plasma
+    vr = kPS_T1_T1_plasma_itst_peri*T1_T1_itst_peri
+    
+% Active transport of T1 dimer complex due to lymph flow from interstitial space around disease tissue into plasma compartment
+T1_T1_itst_tissue => T1_T1_plasma : v_T1_T1_itst_tissue_plasma_lymph      % (nmol/day) 
+	vf = (kL*T1_T1_itst_tissue)*volume_itst_tissue
+
+% Active transport of T1 dimer complex due to lymph flow from interstitial space around peripheral compartment into plasma compartment
+T1_T1_itst_peri => T1_T1_plasma : v_T1_T1_itst_peri_plasma_lymph          % (nmol/day)
+    vf = (kL*T1_T1_itst_peri)*volume_itst_peri 
+
+% Clearance of T1 dimer complex from plasma
+T1_T1_plasma =>  : v_T1_T1_plasma_cl                                    % (nmol/day)
+	vf = (kCL_T1_T1_plasma*T1_T1_plasma)*volume_plasma
+
+% Clearance of T1 dimer complex from interstitial tissue around disease compartment
+T1_T1_itst_tissue => : v_T1_T1_itst_tissue_cl                           % (nmol/day)
+    vf = (kCL_T1_T1_itst_tissue*T1_T1_itst_tissue)*volume_itst_tissue
+
+% Clearance of T1 dimer complex from interstitial tissue around peripheral compartment
+T1_T1_itst_peri => : v_T1_T1_itst_peri_cl                               % (nmol/day)
+    vf = (kCL_T1_T1_itst_peri*T1_T1_itst_peri)*volume_itst_peri
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Soluble protein binding reactions to target T1, exchange and transport reactions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    
+% ASSUMPTION: the soluble binding protein BP and all complexes containing it are 
+%             not secreted since BP is not produced in the model this is a 
+%             necessary assumption to achieve homeostasis 
+% ASSUMPTION: its ok to neglect exchange and transport of BP/T1 complexes. 
+%             After all: to few data available to really estimate all parameters
+%             (unidentifiable!)
+
+% Passive exchange of BP between plasma and interstitial space around disease compartment (diffusion type of mechanism)
+BP_plasma <=> BP_itst_tissue : v_BP_plasma_itst_tissue_ex        % (nmol/day) 
+	vf = kPS_BP_plasma_itst_tissue*BP_plasma
+    vr = kPS_BP_plasma_itst_tissue*BP_itst_tissue
+
+% Passive exchange of BP between plasma and interstitial space around peripheral compartment (diffusion type of mechanism)
+BP_plasma <=> BP_itst_peri : v_BP_plasma_itst_peripheral_ex      % (nmol/day) 
+	vf = kPS_BP_plasma_itst_peri*BP_plasma
+    vr = kPS_BP_plasma_itst_peri*BP_itst_peri
+
+% Active transport of BP due to lymph flow from interstitial space around disease tissue into plasma compartment
+BP_itst_tissue => BP_plasma : v_BP_itst_tissue_plasma_lymph      % (nmol/day) 
+	vf = (kL*BP_itst_tissue)*volume_itst_tissue
+
+% Active transport of BP due to lymph flow from interstitial space around peripheral compartment into plasma compartment
+BP_itst_peri => BP_plasma : v_BP_itst_peri_plasma_lymph          % (nmol/day)
+    vf = (kL*BP_itst_peri)*volume_itst_peri 
+
+% Binding of soluble protein to T1 in plasma
+T1_plasma + BP_plasma <=> T1_BP_plasma : v_T1_BP_plasma_reac                       % (nmol/day)
+	vf = (kon_T1_BP*T1_plasma*BP_plasma)*volume_plasma
+    vr = (kon_T1_BP*KD_T1_BP*T1_BP_plasma)*volume_plasma
+
+% Binding of soluble protein to T1 in interstitial tissue around disease compartment
+T1_itst_tissue+BP_itst_tissue <=> T1_BP_itst_tissue : v_T1_BP_itst_tissue_reac     % (nmol/day)
+	vf = (kon_T1_BP*T1_itst_tissue*BP_itst_tissue)*volume_itst_tissue
+    vr = (kon_T1_BP*KD_T1_BP*T1_BP_itst_tissue)*volume_itst_tissue
+
+% Binding of soluble protein to T1 in interstitial tissue around peripheral compartment
+T1_itst_peri+BP_itst_peri <=> T1_BP_itst_peri : v_T1_BP_itst_peri_reac             % (nmol/day)
+	vf = (kon_T1_BP*T1_itst_peri*BP_itst_peri)*volume_itst_peri
+    vr = (kon_T1_BP*KD_T1_BP*T1_BP_itst_peri)*volume_itst_peri
+
+********** MODEL FUNCTIONS
+********** MODEL EVENTS
+********** MODEL MATLAB FUNCTIONS
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/template example/IV_dosing_14.dos b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/template example/IV_dosing_14.dos
new file mode 100644
index 0000000000000000000000000000000000000000..09159fa7964839582f204fc2f3619300427ce338
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/template example/IV_dosing_14.dos	
@@ -0,0 +1,18 @@
+********** DOSING NAME
+mAb_dosing_schedule_definition_14_days
+
+********** DOSING NOTES
+This dosing schedule defines an infusion of 10mg/kg
+to be given every second week. The infusion time is 2hours.
+Time units are in days.
+
+The drug infusion is repeated 20times and starts at time=0
+
+********** INPUT1
+type:           INFUSION
+time:           0       % time for first application
+deltaT:         14      % (days) time inbetween applications
+nr_repetitions: 20      % number of applications 
+D:              10      % (mg/kg) dose
+Tinf:           2/24    % (days) 2 hours
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/template example/mAb_simple_target_summit_doit.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/template example/mAb_simple_target_summit_doit.m
new file mode 100644
index 0000000000000000000000000000000000000000..50059c36cf451484f7b3e1c9964175cd603b8f01
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/EBtoolbox/template example/mAb_simple_target_summit_doit.m	
@@ -0,0 +1,277 @@
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% This is an example script that performs standard tasks to be done for 
+% target summits. The work is based in the "standard" 3 compartment model,
+% provided in the SBPOP framework and on the target summit work for the
+% TARGETX target.
+% The currently implemented model only features a single target (which is a
+% ligand) and no target binding to a receptor. Depending on the project to
+% be performed the model would need to be changed (receptor as target,
+% several targets, etc.).
+%
+% IMPORTANT:
+% ==========
+% This script serves as an EXAMPLE for how to use some of the implemented
+% functions. It also documents somehow the thoughts behind the work. It
+% might serve in parts as a template for doing own work. But you might
+% still need to write your own scripts.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+clc; clear all; close all; format short g;
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Obtain a copy of the "standard" model, import it, and add initial parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBPOPcreateDRUGligandTargetModel('TARGETX_mAb_model');
+edit('TARGETX_mAb_model.txtbc');
+model = SBmodel('TARGETX_mAb_model.txtbc');
+% Looking at this "TARGETX_mAb_model.txtbc" will be the first step. We need to
+% modify the model to fit the requirements for the task on the TARGETX. You
+% can either a) set these values in the text model, b) update the imported
+% model with the new values of parameters, or c) obtain the model parameter
+% vector and use the function "updateparamvecSBPD" to keep parametervector
+% and model separated. In the following we chose to update the parameters
+% in the model using the SBparameters function:
+%
+%% 1) The volume of the disease tissue and the volume of the corresponding
+% interstitial space need to be set. Human values for these can be obtained
+% using the function "SBPOPtissuedata".
+SBPOPtissuedata
+%% 1a) For the TARGETX project the tissue is the intestine (small+large) 
+model = SBparameters(model,'volume_tissue',0.6960+0.4043);      % set the volume of the disease tissue 
+model = SBparameters(model,'volume_itst_tissue',0.1558+0.0907); % set the volume of the corresponding interstitial space 
+%% 2) The molecular weight of the TARGETX ligand needs to be set (it is 11kDa)
+model = SBparameters(model,'molecularweight_T1',11000);
+%% 3) Finally, we know (from the project team) that TARGETX can
+% dimerize with a KD of 2uM. We have no idea about the kon but we assume
+% 10 and perform afterwards a sensitivity analysis on this value.
+model = SBparameters(model,'KD_T1_T1',2000); % Set the KD for target dimerization
+model = SBparameters(model,'kon_T1_T1',10); % Set the guessed kon for target dimerization
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% We have now a model, parameterized for the TARGETX work. The next step
+% is to fit the mAb kinetics to implement desired halflives and mAb
+% distribution in the tissue. Also the target kinetics to fit the target
+% halflives and finally the synthesis rates of the target to fit the
+% observed target concentrations in the different compartments.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%% Define the desired mAb and target properties
+% If unknown for the mAb typically 2days/20days for alpha/beta halflife is assumed
+T05alphaBetaDrug = [2 20];              % (days) alpha/beta halflife of drug
+% If unknown the assumption is that in steady-state (infinite infusion
+% time) the mAb concentration in the tissue will be 20% of the
+% concentration in the plasma
+SSratio_percent_drug = 20;              % (percent) ratio between ss drug concentration in tissue and plasma
+% If unknown for a small soluble protein as target typically 2 hours is
+% assumed as beta halflife. This will be subjected to a sensitivity
+% analysis later on to see the effect of other halflives in the required
+% dosing amount and schedule. The alpha halflife can often not be chosen
+% freely but is dependent on the beta halflife. We aim at 5min to 10min.
+T05alphaBetaTarget = [5 120]*(1/60/24); % (days) alpha/beta halflife of target (5/120 minutes)
+% The steady-state concentration of target in disease tissue was unknown in
+% this project. Only the ss concentration in plasma was known. Here we use
+% the worst-case concentration, corresponding to Asian patients. 
+Tss_plasma = 0.11028;   % (nmol) Steady-state conc in plasma
+
+%% To speed up our optimizations we generate a MEX simulation function
+SBPDmakeMEXmodel(model,'MEX_model_4_initial_fits');
+% get the models parametervector
+[parameternames_model,paramvalues_model0] = SBparameters('MEX_model_4_initial_fits');
+
+%% Fit the drug kinetics to achieve desired alpha and beta halflife and tissue distribution for the mAb
+% The fitted parameters are the mAb clearance, mAb surface exchange coefficient 
+% and lymph flow rate constant. Since the mAb has a molecular weight of 150
+% kDa it will not be cleared by renal clearance. Here the assumption is
+% that it is cleared in all 3 compartments with the same clearance rate
+% constant. Therefor the clearance in tissue and peripheral tissue has been
+% assigned the value of the clearance in plasma in the model. So changing
+% plasma clearance changes the drug clearance in the other compartments to
+% the same value.
+pnamesopt = {'kCL_D_plasma', 'kPS_D_total', 'kL'}; 
+pvalues0 = [0.1 .5 0.1]; % initial guesses
+referenceValues = [T05alphaBetaDrug SSratio_percent_drug]; % desired properties
+weights = [1 1 1];
+popt = SBPOPoptimizeDRUGkinetics('MEX_model_4_initial_fits',pnamesopt,pvalues0,referenceValues,paramvalues_model0,weights); % do the optimization
+% finally add the optimized parameters the parameter vector
+paramvalues_model1 = updateparamvecSBPD(parameternames_model,paramvalues_model0,pnamesopt,popt);
+% Please check the output in the matlab command window. You can see that
+% the fit was successful and that the objectives have been achieved.
+
+%% Fit the target kinetics to achieve desired alpha and beta halflife
+% The target molecule TARGETX has a molecular weight of ~11kDa. This means
+% it is far below the threshold of ~70kDa from which on the molecule is not
+% anymore cleared by the kidneys. This means, we can assume that the
+% renal clearance in the plasma compartment considerable outweighs the
+% clearance of TARGETX in the tissue compartments. Therefor we assume the
+% clearance of TARGETX in tissue and peripheral tissue to be zero and fit
+% only the clearance in the plasma. Additionally, we fit the surface
+% exchange coefficient for the target.
+pnamesopt   = {'kCL_T1_plasma', 'kPS_T1_total'};
+pvalues0 = [10 200]; % initial guesses
+referenceValues = T05alphaBetaTarget;
+weights = [1 10]; % the weight for the beta halflife is increased on purpose to get a better fit for it (alpha less important than beta)
+popt = SBPOPoptimizeLigandTARGETkinetics('MEX_model_4_initial_fits',pnamesopt,pvalues0,referenceValues,paramvalues_model1,'T1_plasma',weights);
+% finally add the optimized parameters the parameter vector
+paramvalues_model2 = updateparamvecSBPD(parameternames_model,paramvalues_model1,pnamesopt,popt);
+% Please check the output in the matlab command window. You can see that
+% the final objectiove function (achieved_cost) is relatively high. But you can also
+% see that the desired beta halflife (0.083) has been fitted very well and thus 
+% the result is acceptable. For small hallives we have encountered that
+% alpha and beta can not be chosen completely independent, and it is better
+% to get a correct beta than only a correct alpha halflife.
+
+%% Fit the target synthesis rate to obtain desired target steady-state concentrations
+% From literature we know that the concentration of TARGETX in sick patients
+% can be as high as 0.11028 nM in the plasma. We have no idea about the
+% concentration in the disease tissue. So here we do only optimize the
+% synthesis rates in order to achieve the desired steady-state plasma
+% concentration of TARGETX. An additional assumption is that the synthesis
+% rate in plasma and the peripheral tissue is negligible in comparison to
+% the disease tissue (only estimate synthesis in the disease tissue).
+pnamesopt   = {'ksyn_T1_itst_tissue'};
+pvalues0 = [1]; % initial guesses
+referenceValues = [Tss_plasma 1 1]; % neglected values set to "1" ... "0" is not allowed but value does not matter anyway
+weights = [1 0 0]; % neglect tissue and peripheral tissue concentrations (we dont know anything about them anyway)
+popt = SBPOPoptimizeLigandTARGETsynthesis('MEX_model_4_initial_fits',pnamesopt,pvalues0,referenceValues,paramvalues_model2,{'T1_plasma','T1_itst_tissue','T1_itst_peri'},weights);
+% finally add the optimized parameters the parameter vector
+paramvalues_model3 = updateparamvecSBPD(parameternames_model,paramvalues_model2,pnamesopt,popt);
+% Please check the output in the matlab command window. You can see that
+% the fit was successful and that the objectives have been achieved.
+
+%% Get the steady-state of the now parameterized mAb and target model
+simdata = SBPDsimulate('MEX_model_4_initial_fits',[0:1:20],[],parameternames_model,paramvalues_model3);
+ss = simdata.statevalues(end,:);
+
+%% Generate a new SBmodel which contains the optimized parameters and the
+% determined steady-state as initial conditions.
+model_fitted = SBparameters(model,parameternames_model,paramvalues_model3);
+model_fitted = SBinitialconditions(model_fitted,ss);
+
+%% At this point we can remove the MEX model since it has served its purpose
+% and we do not want to keep it longer (reducing confusion). The
+% reason for having it in the first place is the fact that MEX simulation
+% functions are much faster to simulate (crucial for optimization). The
+% compilation of such a model takes some time and using the mexmodel made
+% it possible to only compile once instead of three times.
+clear mex; delete('MEX_model_4_initial_fits.mexw32');
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% The model has now been parameterized in terms of the mAb and target
+% kinetics, the mAb steady-state distribution and the target steady-state
+% concentrations. The next step will be to apply a dosing schedule. We will
+% consider an IV infusion every 14 days (20 times) with a dose of 10mg/kg
+% each time. 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%% Please have a look at the base model (TARGETX_mAb_model.txtbc)
+edit TARGETX_mAb_model.txtbc
+% If you scroll down to the first defined reaction you can see that the
+% identifier "INPUT1" has been used to define that the drug is administered
+% to the plasma compartment. How this does happen is defined in a separate
+% dosing scheme. Here in this example we use the dosing scheme
+% "IV_dosing_14.dos".
+
+%% Look at the dosing scheme
+edit IV_dosing_14.dos
+
+%% We can import this dosing scheme to MATLAB using:
+dosing = SBPOPdosing('IV_dosing_14.dos')
+
+%% Since we chose infusion into the plasma compartment we might want to
+% update the bioavailability parameter in the model
+model_IV = SBparameters(model_fitted,'F',1); 
+
+%% In order to be able to simulate a dosing scheme on a model we need to
+% prepare the model for it:
+moddos = mergemoddosSBPOP(model_IV,dosing);
+% The "moddos" model is now an SBmodel which has been prepared in order to
+% be able to simulate dosing events.
+
+%% Simulate the IV 14-day dosing schedule
+SBPOPsimdosing(moddos,dosing,[0:0.1:360])         
+% Just browse through the plots. You will probably see that the drug does
+% not bind the target. This is due to the fact that the kon_D_T1 parameter
+% is still 0. For the sake of this examlpe we are going to set:
+% kon_D_T1=10 (1/(nM*day)) and KD_D_T1=0.05nM (in the next section)
+
+%% Set drug/target binding parameters and simulate the dosing scheme
+moddos_kon_KD_modified = SBparameters(moddos,{'kon_D_T1','KD_D_T1'},[10 0.05])
+SBPOPsimdosing(moddos_kon_KD_modified,dosing,[0:0.1:360])
+% Have a look at the state "T1_plasma". this is the free target
+% concentration in the plasma in nM units. In this work here we assume that
+% the therapy goal is achieved if the concentration of the free TARGETX in
+% plasma drops below a concentration of 0.013nM. This means that the
+% 10mg/kg treatment here, clearly is achieving the therapy goal.
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% We fitted the model and tested it. And it seemed to work fine. Now
+% we want to determine dose response curves for different values of
+% mAb/TARGETX affinity. Again we want to use the 14 day IV infusion dosing
+% schedule. Again we will use a kon value of 10 (1/(nM*day))
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add the kon value to the model_IV
+model_IV = SBparameters(model_IV,'kon_D_T1',10);
+% Load again the dosing schedule
+dosing = SBPOPdosing('IV_dosing_14.dos');
+% Define the doses to be considered for the dose response calculations
+dose_INPUT1 = logspace(-3,2,10); 
+% Define the KD values to consider
+KD_D_T1 = [0.01 0.02 0.05 0.1 0.2 0.5 1 2 5 10];
+% Define the timevector to use for the simulations
+timevector = [0:0.01:360];
+
+%% The following section performs the dose response calculations based on
+% the definitions above
+%
+% prepare model for dosing application and generate mex model (here at this
+% stage of the example we creata a hidden temporary mex file).
+moddos = mergemoddosSBPOP(model_IV,dosing);
+[MEXmodel, MEXmodelfullpath] = makeTempMEXmodelSBPD(moddos);
+% Define variable to store the data that are needed to determine the
+% efficacy of the treatment. "max_free_T1_plasma" will be a matrix that
+% contains for each KD and dose combination the maximum value of free
+% TARGETX in the plasma when the treatment behavior is in steady-state.
+max_free_T1_plasma = [];
+for k1 =1:length(dose_INPUT1), k1
+    newDosing = SBPOPdoseupdatevalue(dosing,'INPUT1',dose_INPUT1(k1));
+    for k2 = 1:length(KD_D_T1)
+        % Simulate the model with the parameter changes 
+        simresult = SBPOPsimdosing(MEXmodel,newDosing,timevector,[],{'KD_D_T1'},KD_D_T1(k2));
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        % Get the free target in plasma 
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        T1_plasma = simresult.statevalues(:,getstateindicesSBPD(MEXmodel,'T1_plasma'));
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        % Determine the maximum value of relative free target during treatment
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        max_free_T1_plasma_k1_k2 = getlocalmaxSB(T1_plasma);
+        % Take second last value (seen from plot some lines above)
+        max_free_T1_plasma(k1,k2) = max_free_T1_plasma_k1_k2(end-2);
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    end
+end
+
+%% Now plot the dose response curves in the plasma
+% The dashed horizontal line indicates the therapy goal. We can see that 
+% a dose of 10mg/kg together with a KD of 0.1nM allow to achieve the
+% therapy goal.
+SBPOPplotDoseEffectCurve(max_free_T1_plasma, dose_INPUT1, KD_D_T1, 'Free target [nM]', 'Target in plasma (KD_D_T1 as parameter)');
+xlim = get(gca,'Xlim');
+ylim = get(gca,'Ylim'); 
+plot(xlim,[0.013 0.013],'k--');
+
+%% The next plot allows to plot the different affinities over the different
+% doses, whereby each line corresponds to the same achieved therapy effect.
+% The therapy goal is highlighted red. This plot shows that (at least) in
+% the plasma even a smaller KD than 0.01nM would be better. 
+effectLevels = [0.07352 0.02757 0.0068925];
+targetEffectLevel = 0.013785;
+SBPOPplotDoseParamCurve(max_free_T1_plasma, dose_INPUT1, KD_D_T1, 'Target in plasma (effect levels as parameter)',effectLevels,targetEffectLevel);
+% Sidenote: For the real TARGETX project we also considered tissue
+% concentrations and it quickly became obvious that KD~0.1 nM was a
+% reasonable target affinity.
+
+%% Final words: This was a very simple example of how the new SBPOP
+% functions can be used in a target summit work. You will still have to
+% code a little bit yourself (and model to0) but at least this here should
+% serve as an explanation on how you can use the different functions and
+% speed up the work. 
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/01_DataFormat/SBPOPcheckDataFormat.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/01_DataFormat/SBPOPcheckDataFormat.m
new file mode 100644
index 0000000000000000000000000000000000000000..199b032c2139c13834a5fe0c1527eb76897021a1
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/01_DataFormat/SBPOPcheckDataFormat.m
@@ -0,0 +1,351 @@
+function [] = SBPOPcheckDataFormat(data)
+% [DESCRIPTION]
+% Based on a general dataset format used by SBPOP a derived / augmented
+% dataset can be generated using the function
+% SBPOPconvertGeneralDataFormat. This augmented format contains additional
+% columns that are needed for modeling and final conversion to a modeling
+% dataset. The functions in the SBPOP workflow work on this augmented data
+% format. Below the minimum required columns are defined that need to be
+% present in this augmented format.
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Minimum required columns in augmented data format
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% STUDY:            Numeric study number   
+% INDICATION:       Indication flag
+% INDICATION_NAME:  Indication name as text
+% CENTER:           Centre number
+% SUBJECT:          Numeric subject identifier
+% ID:               Unique subject identifier (to be used for model building)
+% VISIT:            Visit number.
+% BASE:             Flag indicating assessments at baseline (=0 for
+%                   non-baseline, =1 for first baseline, 2= for second
+%                   baseline, etc.).  
+% SCREEN:           Flag indicating assessments at screening (=0 for
+%                   non-screening, =1 for first screening, 2= for second
+%                   screening, etc.).  
+% NOMINAL_TIME:     Planned time of event, based on protocol in the time
+%                   unit, defined in TIME_UNIT column. 
+% DATE_DAY:         Date of event.
+% DATE_TIME:        Time of event.
+% TIME:             Time post first dose (negative values for observation
+%                   records pre-first dose)
+% TIMEPOS:          Time post first event (just needed for good old PK
+%                   focused NONMEM)
+% TAD:              Time since last dose (pre-first-dose values same as TIME
+%                   values)
+% TIME_UNIT:         Column with units of time measurements in dataset
+% TYPE:             Column with type identifier for each record 
+%                   Standard assumes dose record has TYPE 0 and PK observation
+%                   record has TYPE 1
+% SUBTYPE:          Column with type identifier for each record 
+%                   Standard assumes dose record has TYPE 0 and PK observation
+%                   record has TYPE 1
+% DV:               Observation value (0 for dose records)
+% UNIT:             Column with units for record entries
+% NAME:             Column with names/labels of record entries
+% MDV:              Missing data value columns (0 if observation value is
+%                   defined, 1 for dose records and for unknown observation
+%                   values)
+% EVID:             Event ID. 0 for observations, 1 for dosing records.
+% AMT:              Dose given at dosing instant (0 for observation records).
+%                   Placebo subjects need AMT=0 at times of placebo
+%                   administration
+% ADM:              Administration column (0 for observation records, 2 for IV
+%                   infusion or bolus, 1 for first order absorption into
+%                   central compartment)  
+% DOSE:             This column contains the value of the last dose given. 
+%                   It is used for dose-normalization of the concentration. 
+% TRT:              Numeric treatment assignment. 
+% TRT_NAME:         Text version of TRT.
+% LLOQ:             Lower limit of quantification for observation record (if
+%                   available - otherwise 0 or NaN)
+% ULOQ:             Upper limit of quantification for observation record (if
+%                   available - otherwise 0 or NaN)
+% TINF:             Infusion time. (0 for observation records, 0 for "Bolus" or
+%                   "first order absorption" dose records, Infusion time in
+%                   TIME_UNIT unit if infusion dose record).
+% - User defined continuous and categorical covariates. Here only time
+%   independent covariates should be considered.
+% - User defined time dependent covariates. These could be used for users
+%   own graphical analysis. "Automatic" generation of exploratory plots for
+%   these currently not supported.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+% [SYNTAX]
+% [] = SBPOPcheckDataFormat(data)
+%
+% [INPUT]
+% data:         MATLAB dataset 
+%
+% [OUTPUT]
+% If at least one of the required columns is not present an error will be
+% shown. Other checks will be done and the user might be warned.
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 11th February 2014
+%
+% [PLATFORM]
+% Windows, Unix, MATLAB
+%
+% [TOOLBOXES USED]
+% Statistics Toolbox
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isa(data,'dataset'),
+    error('Input argument is not a MATLAB dataset.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check column names
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+datanames = get(data,'VarNames');
+requiredColumns = {'STYSID1A' 'STUDY' 'INDICATION' 'INDICATION_NAME' 'CENTER' 'SUBJECT' 'ID' 'VISIT' 'BASE' 'SCREEN' ...
+    'NOMINAL_TIME' 'DATE_DAY' 'DATE_TIME' 'TIME' 'TIMEPOS' 'TAD' 'TIME_UNIT' 'TYPE' 'SUBTYPE' 'DV' 'UNIT' 'NAME' 'MDV' 'EVID' 'AMT' 'ADM' 'DOSE' ...
+    'TRT' 'TRT_NAME' 'LLOQ' 'ULOQ' 'TINF'};
+errorText = '';
+for k=1:length(requiredColumns),
+    ix = strmatchSB(requiredColumns{k},datanames,'exact');
+    if isempty(ix), 
+        errorText = sprintf('%sThe dataset does not contain the column ''%s''.\n',errorText,requiredColumns{k});  %#ok<*SPERR>
+    end    
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if SS is present => error
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(strmatchSB('SS',upper(datanames))),
+    errorText = sprintf('%sColumn "SS" is present in the dataset. This is outdated, please consider the use of "ADDL" in Monolix.',errorText);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Show error if needed
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(errorText),
+    error(errorText);
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Do additional checks
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% If EVID column contains non-zero elements then check that each subject 
+% has received a dose (even placebo subjects - placebo dose of 0 then).
+% If not, then ERROR!
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if sum(data.EVID==1) ~= 0,
+    allID = unique(data.ID);
+    errorText = '';
+    for k=1:length(allID),
+        datak = data(data.ID==allID(k),:);
+        if sum(datak.EVID==1) == 0,
+            errorText = sprintf('%sID=%d (STUDY=%d) does not have any dose records. Please include even for placebo subjects (AMT=0).\n',errorText,allID(k),datak.STUDY(1));
+        end
+    end   
+    if ~isempty(errorText),
+        error(errorText);
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check uniqueness of TIME per ID/TYPE/SUBTYPE
+% Do not warn in case of TYPE=0 TYPE=100 and 101 (DOSE, AEs and COMEDs)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+allID = unique(data.ID);
+for k=1:length(allID),
+    datak = data(data.ID==allID(k),:);
+    allTYPE = unique(datak.TYPE);
+    % Do not consider 0, 100, 101
+    allTYPE(allTYPE==0) = [];
+    allTYPE(allTYPE==100) = [];
+    allTYPE(allTYPE==101) = [];
+    for k2=1:length(allTYPE),
+        % Check only for observation records!
+        datakk2 = datak(datak.TYPE==allTYPE(k2),:);
+        allSUBTYPE = unique(datakk2.SUBTYPE);
+        for k3=1:length(allSUBTYPE),
+            datakk3 = datakk2(datakk2.SUBTYPE==allSUBTYPE(k3),:);
+            % Get TIME
+            TIME = datakk3.TIME;
+            % Check it
+            if ~(length(TIME) == length(unique(TIME))),
+                fprintf('ID=%d has observation records of TYPE=%d / SUBTYPE=%d at same time points.\n',allID(k),allTYPE(k2),allSUBTYPE(k3));
+            end
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check monotonous non decreasing TIME per ID
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+allID = unique(data.ID);
+for k=1:length(allID),
+    datak = data(data.ID==allID(k),:);
+    if sum(diff(datak.TIME) < 0),
+        fprintf('TIME non monotonously increasing for ID=%d.\n',allID(k));
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check uniqueness of TIME_UNIT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+timeunits = unique(data.TIME_UNIT);
+if length(timeunits) > 1,
+    fprintf('Different time units are present in the TIME_UNIT column.\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check uniqueness of NAME and UNIT per TYPE and SUBTYPE
+% Do not check AEs and COMEDs (TYPE 100 and 101)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+allTYPE = unique(data.TYPE);
+allTYPE(allTYPE==100) = [];
+allTYPE(allTYPE==101) = [];
+for k=1:length(allTYPE),
+    datak = data(data.TYPE==allTYPE(k),:);
+    allSUBTYPE = unique(datak.SUBTYPE);
+    for k2=1:length(allSUBTYPE),
+        datak2 = datak(datak.SUBTYPE==allSUBTYPE(k2),:);
+        % Check NAME
+        names = unique(datak2.NAME);
+        if length(names) ~= 1,
+            fprintf('Different entries for TYPE "%d" / SUBTYPE "%d" are present in the NAME column.\n',allTYPE(k),allSUBTYPE(k2));
+        end
+        % Check UNIT
+        unit = unique(datak2.UNIT);
+        if length(unit) ~= 1,
+            fprintf('Different entries for TYPE "%d" / SUBTYPE "%d" are present in the UNIT column.\n',allTYPE(k),allSUBTYPE(k2));
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check NaN in TIME
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if sum(isnan(data.TIME)) > 0,
+    fprintf('Undefined (NaN or empty) values are present in the TIME column. If time undefined in clinical database, don''t include this record into the dataset.\n');
+end    
+
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% % Check NaN in TAD 
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% if sum(isnan(data.TAD)) > 0,
+%     fprintf('Undefined (NaN or empty) values are present in the TAD column. For pre-FIRST-dose samples set TAD=TIME\n');
+% end    
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check NaN in DV 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if sum(isnan(data.DV)) > 0,
+    fprintf('Undefined (NaN or empty) values are present in the DV column. If undefined in clinical database, don''t include this record into the dataset. For dose records use "0".\n');
+end   
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check NaN in TYPE 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if sum(isnan(data.TYPE)) > 0,
+    fprintf('Undefined (NaN or empty) values are present in the TYPE column.\n');
+end   
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check NaN in ID
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if sum(isnan(data.ID)) > 0,
+    fprintf('Undefined (NaN or empty) values are present in the ID column.\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check NaN in AMT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if sum(isnan(data.AMT)) > 0,
+    fprintf('Undefined (NaN or empty) values are present in the AMT column. For observation records, use "0".\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check NaN in ADM
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if sum(isnan(data.ADM)) > 0,
+    fprintf('Undefined (NaN or empty) values are present in the ADM column. For observation records, use "0".\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check NaN in MDV
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if sum(isnan(data.MDV)) > 0,
+    fprintf('Undefined (NaN or empty) values are present in the MDV column.\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check NaN in STUDY
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if sum(isnan(data.STUDY)) > 0,
+    fprintf('Undefined (NaN or empty) values are present in the STUDY column.\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check NaN in SUBJECT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if sum(isnan(data.SUBJECT)) > 0,
+    fprintf('Undefined (NaN or empty) values are present in the SUBJECT column.\n');
+end
+
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% % Check NaN in DOSE
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% if sum(isnan(data.DOSE)) > 0,
+%     fprintf('Undefined (NaN or empty) values are present in the DOSE column.\n');
+% end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check NaN in TRT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if sum(isnan(data.TRT)) > 0,
+    fprintf('Undefined (NaN or empty) values are present in the TRT column.\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check that TRT is unique in each ID
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+allID = unique(data.ID);
+for k=1:length(allID),
+    datak = data(data.ID==allID(k),:);
+    % Check TRT
+    if length(unique(datak.TRT)) ~= 1,
+        fprintf('Different entries for TRT in subject "%d" are present.\n',allID(k));
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check NaN in TINF if TNIF column available
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(strmatchSB('TINF',datanames)),
+    if sum(isnan(data.TINF)) > 0,
+        fprintf('Undefined (NaN or empty) values are present in the TINF column. For observation records, use "0".\n');
+    end
+end
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/01_DataFormat/SBPOPcheckGeneralDataFormat.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/01_DataFormat/SBPOPcheckGeneralDataFormat.m
new file mode 100644
index 0000000000000000000000000000000000000000..e689eb4d0aecbaed4ab26ce84bef2e4498ae62b2
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/01_DataFormat/SBPOPcheckGeneralDataFormat.m
@@ -0,0 +1,339 @@
+function [data] = SBPOPcheckGeneralDataFormat(data)
+% [DESCRIPTION]
+% The SBPOP popPKPDtoolbox assumes a general dataset format that is
+% independent of modeling activities and tools. This function here will
+% check the availability of the required columns. Additionally, it will do
+% some sanity checks of the dataset and report potential issues in the
+% Command Window as text. 
+%
+% The function allows the normal header names but also shortened versions
+% of it. In the case that shortened headers are used the function replaces
+% these with the long versions and returns also the updated dataset.
+%
+% Short versions are only needed in case the programmers are limited to 8
+% characters in column name length. In the 21st century a bit strange, but
+% well ...
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Specification of general dataset format:
+% (Short column names in parentheses)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% COLUMN            DESCRIPTION
+% -------------------------------------------------------------------------
+% STYSID1A (USUBJID)            Unique subject identifier.
+% STUDY                         Study number.
+% CENTER                        Centre number.
+% SUBJECT                       Subject number. 
+% PART                          Part of study (if parts present, otherwise 0). 
+% INDICATION (IND)              Indication flag.
+% INDICATION_NAME (IND_NAME)    Indication name.
+% TRT                           Unique treatment identifier.
+% TRT_NAME                      Analyst given treatment name.
+% VISIT                         Visit number.
+% VISIT_NAME (VIS_NAME)         Visit name as coded in the clinical database.
+% BASE                          Flag indicating assessments at baseline (=0 for
+%                               non-baseline, =1 for first baseline, 2= for second
+%                               baseline, etc.).  
+% SCREEN                        Flag indicating assessments at screening (=0 for
+%                               non-screening, =1 for first screening, 2= for second
+%                               screening, etc.).  
+% DATE_DAY                      Date of event.
+% DATE_TIME (DATE_TIM)          Time of event.
+% NOMINAL_TIME (NT)             Planned time of event, based on protocol in the time
+%                               unit, defined in TIMEUNIT column. 
+% TIME                          Actual time of event in the time unit, defined in
+%                               TIME_UNIT column. Time 0 defined as time of first active
+%                               or placebo dose.  
+% TIME_UNIT (TIMEUNIT)          Unit of all numerical time definitions in the dataset
+%                               (e.g., �hours� or �days�). 
+% TYPE                          Numerical value for grouping of certain types of
+%                               events. Required groups are 0 (for dosing events) and 1
+%                               (for PK observations). Additional groups could consist
+%                               of demographics, metabolites, target capture, MoA
+%                               biomarkers, clinical endpoints, etc.    
+%                               It is assumed that Adverse events have TYPE=100 and
+%                               Comedications TYPE=101.
+% TYPE_NAME (TYPENAME)          Textual representation of the corresponding TYPE value.
+%                               No standard defined. For dosing events �Dose� might be
+%                               used and for PK observation events �PK�.  
+% SUBTYPE                       Numerical identifier for a specific event within a group. 
+% VALUE                         Value of the event, defined by TYPE and SUBTYPE. E.g.,
+%                               the given dose, the observed PK concentration, or the
+%                               value of other readouts. The values need to be in the
+%                               units, defined in the UNIT column.    
+% VALUE_TEXT (VAL_TEXT)         Text version of value (e.g. �male� or �female for �gender�).
+% UNIT                          Unit of the value reported in the VALUE column. For
+%                               same event the same unit has to be used across the
+%                               dataset.    
+% NAME                          Unique name for the event that is coded by TYPE and
+%                               SUBTYPE. No standard defined. For dosing events �Dose
+%                               compound X� and for PK observations �X plasma
+%                               concentration� might be used.   
+% DURATION                      Numeric value capturing the duration of an event, in
+%                               the time units defined in the column TIMEUNIT.  
+% ULOQ                          Upper limit of quantification of event defined by TYPE
+%                               and SUBTYPE (if applicable), empty if not. 
+% LLOQ                          Lower limit of quantification of event defined by TYPE
+%                               and SUBTYPE (if applicable), empty if not. 
+% ROUTE                         For the conversion to a model specific modeling dataset
+%                               the route of administration needs to be defined for
+%                               dosing events. Recognized: "IV", "Oral", "Subcut"
+% INTERVAL                      Interval of dosing in time units, defined in the
+%                               TIME_UNIT column � allows for coding repeated dosing
+%                               more efficiently.  
+% NR_DOSES                      Number of doses given with the specified interval �
+%                               allows for coding repeated dosing more efficiently. 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+% [SYNTAX]
+% []     = SBPOPcheckGeneralDataFormat(data)
+% [data] = SBPOPcheckGeneralDataFormat(data)
+%
+% [INPUT]
+% data:         MATLAB dataset in the general dataset format to be checked
+%               or path to dataset
+%
+% [OUTPUT]
+% If at least one of the required columns is not present an error will be
+% shown. Warnings might be shown for other detected things. No claim on
+% completeness of checks is done!
+%
+% The dataset is also returned but only relevant if header names changed in
+% the function (a warning will be shown).
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 11th February 2014
+%
+% [PLATFORM]
+% Windows, Unix, MATLAB
+%
+% [TOOLBOXES USED]
+% Statistics Toolbox
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ischar(data),
+    data = SBPOPloadCSVdataset(data);
+end
+if ~isa(data,'dataset'),
+    error('Input argument is not a MATLAB dataset.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Attempt renaming the columns (assume short versions have been used)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+headerOld = get(data,'VarNames');
+headerNew = headerOld;
+try, headerNew{strmatchSB('USUBJID',headerOld,'exact')}      = 'STYSID1A'; catch, end
+try, headerNew{strmatchSB('IND',headerOld,'exact')}          = 'INDICATION'; catch, end
+try, headerNew{strmatchSB('IND_NAME',headerOld,'exact')}     = 'INDICATION_NAME'; catch, end
+try, headerNew{strmatchSB('VIS_NAME',headerOld,'exact')}     = 'VISIT_NAME'; catch, end
+try, headerNew{strmatchSB('DATE_TIM',headerOld,'exact')}     = 'DATE_TIME'; catch, end
+try, headerNew{strmatchSB('NT',headerOld,'exact')}           = 'NOMINAL_TIME'; catch, end
+try, headerNew{strmatchSB('TIMEUNIT',headerOld,'exact')}     = 'TIME_UNIT'; catch, end
+try, headerNew{strmatchSB('TYPENAME',headerOld,'exact')}     = 'TYPE_NAME'; catch, end
+try, headerNew{strmatchSB('VAL_TEXT',headerOld,'exact')}     = 'VALUE_TEXT'; catch, end
+data = set(data,'VarNames',headerNew);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check column names against required ones
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+datanames = get(data,'VarNames');
+requiredColumns = {'STYSID1A' 'STUDY' 'CENTER' 'SUBJECT' 'PART' 'INDICATION' 'INDICATION_NAME' 'TRT' 'TRT_NAME' 'VISIT' 'VISIT_NAME' 'BASE'  'SCREEN' ...
+    'DATE_DAY' 'DATE_TIME' 'NOMINAL_TIME' 'TIME' 'TIME_UNIT' 'TYPE' 'TYPE_NAME' 'SUBTYPE' 'VALUE' 'VALUE_TEXT' 'UNIT' 'NAME' 'DURATION' 'ULOQ' 'LLOQ' 'ROUTE' 'INTERVAL' 'NR_DOSES'};
+errorText = '';
+for k=1:length(requiredColumns),
+    ix = strmatchSB(requiredColumns{k},datanames,'exact');
+    if isempty(ix), 
+        errorText = sprintf('%sThe dataset does not contain the column ''%s''.\n',errorText,requiredColumns{k});  %#ok<*SPERR>
+    end    
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Show error if needed
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(errorText),
+    error(errorText);
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% If STYSID1A is numeric, convert to cell with strings
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isnumeric(data.STYSID1A),
+    STYSID1A = cell(length(data),1);
+    for k=1:length(data),
+        STYSID1A{k} = num2str(data.STYSID1A(k));
+    end    
+    data.STYSID1A = STYSID1A;
+end
+
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Do additional checks
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check uniqueness of TIME per STYSID1A/TYPE/SUBTYPE
+% Do not warn in case of TYPE=0 TYPE=100 and 101 (DOSE, AEs and COMEDs)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+allID = unique(data.STYSID1A);
+for k=1:length(allID),
+    datak = data(strcmp(data.STYSID1A,allID{k}),:);
+    allTYPE = unique(datak.TYPE);
+    % Do not consider 0, 100, 101
+    allTYPE(allTYPE==0) = [];
+    allTYPE(allTYPE==100) = [];
+    allTYPE(allTYPE==101) = [];
+    for k2=1:length(allTYPE),
+        % Check only for observation records!
+        datakk2 = datak(datak.TYPE==allTYPE(k2),:);
+        allSUBTYPE = unique(datakk2.SUBTYPE);
+        for k3=1:length(allSUBTYPE),
+            datakk3 = datakk2(datakk2.SUBTYPE==allSUBTYPE(k3),:);
+            % Get TIME
+            TIME = datakk3.TIME;
+            % Check it
+            if ~(length(TIME) == length(unique(TIME))),
+                fprintf('Subject %s has observation records of TYPE=%d / SUBTYPE=%d at same time points.\n',allID{k},allTYPE(k2),allSUBTYPE(k3));
+            end
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check monotonous non decreasing TIME per STYSID1A
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+allID = unique(data.STYSID1A);
+for k=1:length(allID),
+    datak = data(strcmp(data.STYSID1A,allID{k}),:);
+    if sum(diff(datak.TIME) < 0),
+        fprintf('TIME non monotonously increasing for ID=%s.\n',allID{k});
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check uniqueness of TIMEUNIT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+timeunits = unique(data.TIME_UNIT);
+if length(timeunits) > 1,
+    fprintf('Different time units are present in the TIMEUNIT column.\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check uniqueness of NAME and UNIT per TYPE and SUBTYPE
+% Do not check AEs and COMEDs (TYPE 100 and 101)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+allTYPE = unique(data.TYPE);
+allTYPE(allTYPE==100) = [];
+allTYPE(allTYPE==101) = [];
+for k=1:length(allTYPE),
+    datak = data(data.TYPE==allTYPE(k),:);
+    allSUBTYPE = unique(datak.SUBTYPE);
+    for k2=1:length(allSUBTYPE),
+        datak2 = datak(datak.SUBTYPE==allSUBTYPE(k2),:);
+        % Check NAME
+        names = unique(datak2.NAME);
+        if length(names) ~= 1,
+            fprintf('Different entries for TYPE "%d" / SUBTYPE "%d" are present in the NAME column.\n',allTYPE(k),allSUBTYPE(k2));
+        end
+        % Check UNIT
+        unit = unique(datak2.UNIT);
+        if length(unit) ~= 1,
+            fprintf('Different entries for TYPE "%d" / SUBTYPE "%d" are present in the UNIT column.\n',allTYPE(k),allSUBTYPE(k2));
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check NaN in TIME
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if sum(isnan(data.TIME)) > 0,
+    fprintf('Undefined (NaN or empty) values are present in the TIME column.\n');
+end    
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check NaN in VALUE 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if sum(isnan(data.VALUE)) > 0,
+    fprintf('Undefined (NaN or empty) values are present in the VALUE column. This might be due to definition of value in VALUE_TEXT (check!)\n');
+end   
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check NaN in different columns
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+columnsNaNcheck = {'STUDY' 'CENTER' 'SUBJECT' 'PART' 'INDICATION' 'TRT' 'VISIT' 'BASE'  'SCREEN' 'NOMINAL_TIME' 'TIME' 'TYPE' 'SUBTYPE' 'VALUE'};
+for k=1:length(columnsNaNcheck),
+    if sum(isnan(data.(columnsNaNcheck{k}))) > 0,
+        fprintf('Undefined (NaN or empty) values are present in the "%s" column.\n',columnsNaNcheck{k});
+    end   
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check that TRT is unique in each ID
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+allID = unique(data.STYSID1A);
+for k=1:length(allID),
+    datak = data(strcmp(data.STYSID1A,allID{k}),:);
+    % Check TRT
+    if length(unique(datak.TRT)) ~= 1,
+        fprintf('Different entries for TRT in subject "%d" are present.\n',allID(k));
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check that LLOQ is not NaN for PK
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if sum(isnan(data.LLOQ(data.TYPE==1))) > 0,
+    fprintf('LLOQ value not defined for all PK measurements (TYPE=1).\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check contents of route of administration for dosing events
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ROUTE = unique(data.ROUTE(data.TYPE==0));
+for k=1:length(ROUTE),
+    if isempty(strmatchSB(lower(ROUTE{k}),{'iv','oral','subcut'},'exact')),
+        fprintf('ROUTE entry "%s" for a dosing entry (TYPE=0) not recognized - no problem but no automatic handling in popPK workflow.\n',ROUTE{k});
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if header was changed ... then write warning to use output argument
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CHANGED = 0;
+for k=1:length(headerOld),
+    if ~strcmp(headerNew{k},headerOld{k}),
+        CHANGED = 1;
+    end
+end
+if CHANGED && nargout==0,
+    error('Header names were changed from short to long versions. Make sure you provide an output argument for the updated dataset.');
+elseif CHANGED,
+    warning('Header names were changed from short to long versions. Make sure you provide an output argument for the updated dataset.');
+end
+
+
+fprintf('SBPOPcheckGeneralDataFormat: If no output (except this here) is produced then all checks are passed.\n');
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/01_DataFormat/SBPOPconvertGeneralDataFormat.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/01_DataFormat/SBPOPconvertGeneralDataFormat.m
new file mode 100644
index 0000000000000000000000000000000000000000..dbb1a3ebce3d6b3ecbfa2e9c72ee48b79f41c0f9
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/01_DataFormat/SBPOPconvertGeneralDataFormat.m
@@ -0,0 +1,519 @@
+function [dataOut,covNames,catNames] = SBPOPconvertGeneralDataFormat(dataGeneralFormat,covariateInfo)
+% [DESCRIPTION]
+% The SBPOP popPKPDtoolbox assumes a general dataset format that is
+% modeling activity, tool and model independent.
+% This function converts this format into a format that contains additional
+% information that are relevant for modeling but also for graphical
+% analysis.
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Specification of general dataset format:
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% COLUMN            DESCRIPTION
+% -------------------------------------------------------------------------
+% STYSID1A          Unique subject identifier.
+% STUDY             Study number.
+% CENTER            Centre number.
+% SUBJECT           Subject number. 
+% PART              Part of study (if parts present, otherwise 0). 
+% INDICATION        Indication flag.
+% INDICATION_NAME   Indication name.
+% TRT               Unique treatment identifier.
+% TRT_NAME          Analyst given treatment name.
+% VISIT             Visit number.
+% VISIT_NAME        Visit name as coded in the clinical database.
+% BASE              Flag indicating assessments at baseline (=0 for
+%                   non-baseline, =1 for first baseline, 2= for second
+%                   baseline, etc.).  
+% SCREEN            Flag indicating assessments at screening (=0 for
+%                   non-screening, =1 for first screening, 2= for second
+%                   screening, etc.).  
+% DATE_DAY          Date of event.
+% DATE_TIME         Time of event.
+% NOMINAL_TIME      Planned time of event, based on protocol in the time
+%                   unit, defined in TIMEUNIT column. 
+% TIME              Actual time of event in the time unit, defined in
+%                   TIMEUNIT column. Time 0 defined as time of first active
+%                   or placebo dose.  
+% TIME_UNIT         Unit of all numerical time definitions in the dataset
+%                   (e.g., �hours� or �days�). 
+% TYPE              Numerical value for grouping of certain types of
+%                   events. Required groups are 0 (for dosing events) and 1
+%                   (for PK observations). Additional groups could consist
+%                   of demographics, metabolites, target capture, MoA
+%                   biomarkers, clinical endpoints, etc.    
+%                   It is assumed that Adverse events have TYPE=100 and
+%                   Comedications TYPE=101.
+% TYPE_NAME         Textual representation of the corresponding TYPE value.
+%                   No standard defined. For dosing events �Dose� might be
+%                   used and for PK observation events �PK�.  
+% SUBTYPE           Numerical identifier for a specific event within a group. 
+% VALUE             Value of the event, defined by TYPE and SUBTYPE. E.g.,
+%                   the given dose, the observed PK concentration, or the
+%                   value of other readouts. The values need to be in the
+%                   units, defined in the UNIT column.    
+% VALUE_TEXT        Text version of value (e.g. �male� or �female for �gender�).
+% UNIT              Unit of the value reported in the VALUE column. For
+%                   same event the same unit has to be used across the
+%                   dataset.    
+% NAME              Unique name for the event that is coded by TYPE and
+%                   SUBTYPE. No standard defined. For dosing events �Dose
+%                   compound X� and for PK observations �X plasma
+%                   concentration� might be used.   
+% DURATION          Numeric value capturing the duration of an event, in
+%                   the time units defined in the column TIMEUNIT.  
+% ULOQ              Upper limit of quantification of event defined by TYPE
+%                   and SUBTYPE (if applicable), empty if not. 
+% LLOQ              Lower limit of quantification of event defined by TYPE
+%                   and SUBTYPE (if applicable), empty if not. 
+% ROUTE             For the conversion to a model specific modeling dataset
+%                   the route of administration needs to be defined for
+%                   dosing events. Recognized: "IV", "Oral", "Subcut"
+% INTERVAL          Interval of dosing in time units, defined in the
+%                   TIMEUNIT column � allows for coding repeated dosing
+%                   more efficiently.  
+% NR_DOSES          Number of doses given with the specified interval �
+%                   allows for coding repeated dosing more efficiently. 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Specification of converted dataset
+% - The columns of the general dataset format all remain
+% - Several additional columns will be added by this function
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+%   ID:         Unique subject identifier (to be used for model building)
+%   TAD:        Time since last dose (pre-first-dose values same as TIME
+%   DV:         Observation value (0 for dose records)
+%   MDV:        Missing data value columns (0 if observation value is
+%               defined, 1 for dose records and for unknown observation
+%               values)
+% 	EVID: 		Event ID. 0 for observations, 1 for dosing records.
+%   AMT:        Dose given at dosing instant (0 for observation records).
+%               Placebo subjects need AMT=0 at times of placebo
+%               administration
+%   ADM:        Administration column (0 for observation records, 2 for IV
+%               infusion or bolus, 1 for first order absorption into
+%               central compartment)  
+%   DOSE:       This column contains the value of the last dose given. 
+%               It is used for dose-normalization of the concentration. 
+%   TINF:       Infusion time. (0 for observation records, 0 for "Bolus" or
+%               "first order absorption" dose records, Infusion time in
+%               TIMEUNIT unit if infusion dose record).
+%   TIMEPOS:    TIME column changed to start from 0 at first event
+%               Needed for good old NONMEM
+%
+% Additional columns:
+%               User defined continuous and categorical covariates. Here
+%               only time independent covariates will be considered for
+%               now. The covariate columns to be added need to be specified
+%               as second input argument, documented below.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+% [SYNTAX]
+% [data] = SBPOPconvertGeneralDataFormat(dataGeneralFormat,covariateInfo)
+%
+% [INPUT]
+% dataGeneralFormat:    MATLAB dataset in the general dataset format
+% covariateInfo:        MATLAB cell-array, defining which readouts in the
+%                       general dataset should be added as time independent
+%                       covariates. The format for this argument is as
+%                       follows (documented by example):
+% 
+%                       covariateInfo = {
+%                           % NAME              USENAME      CONTINUOUS
+%                            'Gender'            'SEX'          0
+%                            'Age'               'AGE0'         1
+%                            'Bodyweight'        'WT0'          1
+%                            'Height'            'HT0'          1
+%                            'BMI'               'BMI0'         1
+%                       };
+%
+%                       The CONTINUOUS column is optional and will not be used in this 
+%                       function yet. It is used somewhere else to identify what the user
+%                       desires to use as continuous and what as categorical covariate.
+%
+%                       The values for the covariates will be determined as
+%                       follows:
+%                        - Use mean of BASEline assessments by default. 
+%                        - If BASE not defined then use mean of SCREEN assessments.
+%                        - BASE and SCREEN not defined then use mean of pre-first-dose assessments.
+%
+% [OUTPUT]
+% dataOut:              Dataset with added columns, as documented above
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 11th February 2014
+%
+% [PLATFORM]
+% Windows, Unix, MATLAB
+%
+% [TOOLBOXES USED]
+% Statistics Toolbox
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+% Define if doses expanded or the ADDL option used
+FLAG_USE_ADDL = 0;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ischar(dataGeneralFormat),
+    dataGeneralFormat = SBPOPloadCSVdataset(dataGeneralFormat);
+end
+
+if ~isa(dataGeneralFormat,'dataset'),
+    error('Input argument is not a MATLAB dataset.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check names against covariate information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ix_remove_covariate_info = [];
+allNames = unique(dataGeneralFormat.NAME);
+
+for k=1:size(covariateInfo,1),
+    ix = strmatchSB(covariateInfo{k,1},allNames,'exact');
+    if isempty(ix),
+        ix_remove_covariate_info(end+1) = k;
+        disp(sprintf('Covariate "%s" not present in dataset under this name.',covariateInfo{k,1}));
+    end
+end
+covariateInfo(ix_remove_covariate_info,:) = [];
+
+if size(covariateInfo,2) == 3,
+    covNames = covariateInfo(find([covariateInfo{:,3}]==1),2);
+    catNames = covariateInfo(find([covariateInfo{:,3}]==0),2);
+else
+    covNames = {};
+    catNames = {};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Load the standard format 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+data2 = dataGeneralFormat;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Expand INTERVAL and NR_DOSES if defined OR create ADDL and II columns
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if FLAG_USE_ADDL,
+    % Do not expand the doses but use ADDL and II
+    data2b = data2;
+    data2b.ADDL = data2b.NR_DOSES;
+    data2b.II = data2b.INTERVAL;
+    data2b.ADDL(isnan(data2b.ADDL)) = 0;
+    data2b.II(isnan(data2b.II)) = 0;
+else
+    % Expand the doses that are defined by INTERVAL and numbers
+    dataDOSES = data2(data2.TYPE==0,:);
+    dataOTHER = data2(data2.TYPE~=0,:);
+    % Expand doses if both INTERVAL and NR_DOSES defined
+    dataDOSES_expanded = dataset();
+    for k=1:length(dataDOSES),
+        datak = dataDOSES(k,:);
+        if ~isnan(datak.INTERVAL) && ~isnan(datak.NR_DOSES),
+            dataexp = datak(ones(1,datak.NR_DOSES),:);
+            dataexp.TIME = dataexp.TIME+[0:datak.INTERVAL:datak.INTERVAL*(datak.NR_DOSES-1)]';
+            dataexp.DATE_DAY(2:end) = {''};
+            dataexp.DATE_TIME(2:end) = {''};
+            dataexp.NOMINAL_TIME(2:end) = NaN;
+            dataexp.VISIT(2:end) = NaN;
+            dataexp.VISIT_NAME(2:end) = {'Expanded dose record'};
+            dataexp.INTERVAL(1:end) = NaN;
+            dataexp.NR_DOSES(1:end) = NaN;
+            dataDOSES_expanded = [dataDOSES_expanded; dataexp];
+        elseif isnan(datak.INTERVAL) && isnan(datak.NR_DOSES),
+            % Nothing to expand (single dose definition)
+            dataDOSES_expanded = [dataDOSES_expanded; datak];
+        else
+            error('Somewhere either INTERVAL or NR_DOSES is defined but not the other column.')
+        end
+    end
+    data2b = sortrows([dataDOSES_expanded; dataOTHER],{'STUDY','CENTER','SUBJECT','TIME','TYPE','SUBTYPE'});
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Create ID column
+% Make the IDs short ... just 1...N
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+allSUBJ = unique(data2b.STYSID1A);
+data3 = dataset();
+for kID=1:length(allSUBJ),
+    datak = data2b(strcmp(data2b.STYSID1A,allSUBJ{kID}),:);
+    datak.ID = kID*ones(length(datak),1);
+    data3 = [data3; datak];
+end
+data2b = data3;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Create TIMEPOS column
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+allID = unique(data2b.ID);
+data3 = dataset();
+for kID=1:length(allID),
+    datak = data2b(data2b.ID==allID(kID),:);
+    datak.TIMEPOS = datak.TIME-datak.TIME(1);
+    data3 = [data3; datak];
+end
+data2b = data3;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Create DV and AMT column
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% AMT
+data2b.AMT = zeros(length(data2b),1);
+data2b.AMT(data2b.TYPE==0) = data2b.VALUE(data2b.TYPE==0);
+% DV
+data2b.DV = data2b.VALUE;
+data2b.DV(data2b.TYPE==0) = 0;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Create EVID column
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+data2b.EVID = zeros(length(data2b),1);
+data2b.EVID(data2b.TYPE==0) = 1;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Create MDV column
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+data2b.MDV = zeros(length(data2b),1);
+data2b.MDV(data2b.TYPE==0) = 1;
+data2b.MDV(isnan(data2b.DV)) = 1;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Create TINF column
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+data2b.TINF = zeros(length(data2b),1);
+data2b.TINF(data2b.TYPE==0) = data2b.DURATION(data2b.TYPE==0);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Create TAD column
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+data3 = data2b;
+
+dose_subtypes = unique(data3.SUBTYPE(data3.TYPE==0));
+
+if length(dose_subtypes) == 1,
+    data3.TAD = NaN(length(data3),1);
+else
+    for k=1:length(dose_subtypes),
+        data3.(sprintf('TAD%d',dose_subtypes(k))) = zeros(length(data3),1);
+    end    
+end
+
+allID = unique(data3.ID);
+data4 = dataset();
+for k=1:length(allID),
+    datak = data3(data3.ID==allID(k),:);
+    
+    for k3=1:length(dose_subtypes)
+        TIME = datak.TIME;
+        TAD  = TIME;
+        ixDOSE = find(datak.TYPE==0 & datak.SUBTYPE==dose_subtypes(k3));
+        for k2=1:length(ixDOSE),
+            DOSETIME = TIME(ixDOSE(k2));
+            % Get index until which to substract dosetime
+            if k2==length(ixDOSE),
+                END = length(TAD);
+            else
+                END = ixDOSE(k2+1)-1;
+            end
+            % Substract dose time from relevant range
+            TAD(ixDOSE(k2):END) = TAD(ixDOSE(k2):END) - DOSETIME;
+        end
+        if length(dose_subtypes) == 1,
+            datak.TAD = TAD;
+        else
+            datak.(sprintf('TAD%d',dose_subtypes(k3))) = TAD;
+        end
+    end
+    data4 = [data4; datak];
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Create DOSEx columns
+% Always amount doses! Unit defined by modeler
+% One dose column per SUBTYPE/compound - same number!
+% If single compound/subtype then name is DOSE only
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dose_subtypes = unique(data4.SUBTYPE(data4.TYPE==0));
+data5 = dataset();
+
+if length(dose_subtypes) == 1,
+    % Single compound
+    data4.DOSE = zeros(length(data4),1);
+    allID = unique(data4.ID);
+    for k=1:length(allID),
+        datak = data4(data4.ID==allID(k),:);
+        ixDOSE = find(datak.EVID);
+        for k2=1:length(ixDOSE),
+            datak.DOSE(ixDOSE(k2):end) = datak.AMT(ixDOSE(k2));
+        end
+        data5 = [data5; datak];
+    end
+else
+    % Multiple compound
+    for k=1:length(dose_subtypes),
+        data4.(sprintf('DOSE%d',dose_subtypes(k))) = zeros(length(data4),1);
+    end
+    allID = unique(data4.ID);
+    for k2=1:length(allID),
+        datak2 = data4(data4.ID==allID(k2),:);
+        for k=1:length(dose_subtypes),
+            ixDOSE = find(datak2.TYPE==0 & datak2.SUBTYPE==dose_subtypes(k));
+            for k3=1:length(ixDOSE),
+                datak2.(sprintf('DOSE%d',dose_subtypes(k)))(ixDOSE(k3):end) = datak2.AMT(ixDOSE(k3));
+            end
+        end        
+        data5 = [data5; datak2];
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Create ADM column
+% Handle differently for multiple compounds and single compound - if single
+% compound dataset suitable for popPK workflow.
+% Single compound (SUBTYPE==1 and ROUTE info iv,sc, or oral): match IV with ADM=2, SC and ORAL with ADM=1
+% Multiple compound (or single but SUBTYPE~=1): dont match, just show a table with matches to ADM
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get doses
+dataDOSE = data5(data5.TYPE==0,:);
+subtypes = unique(dataDOSE.SUBTYPE);
+routes   = unique(dataDOSE.ROUTE);
+POPPK_WORKFLOW_SUITABLE = 1;
+if length(subtypes) > 1,
+    POPPK_WORKFLOW_SUITABLE = 0;
+elseif subtypes ~= 1,
+    POPPK_WORKFLOW_SUITABLE = 0;
+else    
+    for k=1:length(routes),
+        if isempty(strmatchSB(lower(routes{k}),{'iv','oral','subcut'},'exact')),
+            POPPK_WORKFLOW_SUITABLE = 0;
+        end
+    end
+end
+
+ADMtable = {'ADM' 'TYPE' 'SUBTYPE' 'ROUTE'};
+
+if ~POPPK_WORKFLOW_SUITABLE,
+    % Handle adm independent of popPK workflow requirements
+    ADM = 1;
+    for k=1:length(subtypes),
+        routes = unique(dataDOSE.ROUTE(dataDOSE.SUBTYPE==subtypes(k)));
+        for k2=1:length(routes),
+            ADMtable{ADM+1,1} = ADM;
+            ADMtable{ADM+1,2} = 0;
+            ADMtable{ADM+1,3} = subtypes(k);
+            ADMtable{ADM+1,4} = routes{k2};
+            ADM = ADM+1;
+        end
+    end
+    data5.ADM = zeros(length(data5),1);
+    dataDOSE  = data5(data5.TYPE==0,:);
+    dataOTHER = data5(data5.TYPE~=0,:);
+    dataDOSEnew = dataset();
+    for k=1:length(dataDOSE),
+        datak = dataDOSE(k,:);
+        subtypeFLAG = ([ADMtable{2:end,3}]==datak.SUBTYPE);
+        routeFLAG   = strcmp(ADMtable(2:end,4),datak.ROUTE);
+        ADM = ADMtable{find(subtypeFLAG(:).*routeFLAG(:))+1,1};
+        datak.ADM = ADM;
+        dataDOSEnew = [dataDOSEnew; datak];
+    end
+    data6 = sortrows([dataDOSEnew; dataOTHER],{'STUDY','CENTER','SUBJECT','TIME','TYPE','SUBTYPE'});
+    disp('The doses and routes are matched with ADM numbers as follows:');
+    ADMtable
+else
+    % Use popPK workflow things
+    data6 = data5;
+    data6.ADM = zeros(length(data6),1);
+    data6.ADM(strcmp(lower(data6.ROUTE),'iv')) = 2;
+    data6.ADM(strcmp(lower(data6.ROUTE),'oral')) = 1;
+    data6.ADM(strcmp(lower(data6.ROUTE),'subcut')) = 1;
+    disp('This dataset is suitable for the popPK workflow (based on the used dosing and routes).');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Covariates ... baseline
+% Use mean of BASEline assessments by default. 
+% If BASE not defined then use mean of SCREEN assessments.
+% If not defined then use mean of pre-dose assessments.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+data7 = dataset();
+allID = unique(data6.ID);
+for k=1:length(allID),
+    datak = data6(data6.ID==allID(k),:);
+    
+    for k2=1:size(covariateInfo,1),
+        datak2 = datak(strcmp(datak.NAME,covariateInfo{k2,1}),:);
+        
+        value_BASE = NaN;
+        value_SCREEN = NaN;
+        value_PREDOSE = NaN;
+
+        if ~isempty(datak2),
+            % Get baseline
+            datak2_BASE = datak2(datak2.BASE~=0,:);
+            if ~isempty(datak2_BASE),
+                value_BASE = mean(datak2_BASE.VALUE);
+            end
+            
+            % Get screening
+            datak2_SCREEN = datak2(datak2.SCREEN~=0,:);
+            if ~isempty(datak2_SCREEN),
+                value_SCREEN = mean(datak2_SCREEN.VALUE);
+            end
+            
+            % Get pre-dose
+            datak2_PREDOSE = datak2(datak2.TIME<0,:);
+            if ~isempty(datak2_PREDOSE),
+                value_PREDOSE = mean(datak2_PREDOSE.VALUE);
+            end
+        end
+        
+        if ~isnan(value_BASE),
+            covariateInfo{k2,3} = value_BASE;
+        elseif ~isnan(value_SCREEN),
+            covariateInfo{k2,3} = value_SCREEN;
+        elseif ~isnan(value_PREDOSE),
+            covariateInfo{k2,3} = value_PREDOSE;
+        else
+            covariateInfo{k2,3} = NaN;
+        end
+    end
+    
+    for k2=1:size(covariateInfo,1),
+        datak.(covariateInfo{k2,2}) = covariateInfo{k2,3}*ones(length(datak),1);
+    end
+    
+    data7 = [data7; datak];
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Check and export ... 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dataOut = data7;
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/02_DataExploration/SBPOPexploreCovariateCorrelations.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/02_DataExploration/SBPOPexploreCovariateCorrelations.m
new file mode 100644
index 0000000000000000000000000000000000000000..cd62a05e9bc2fcda5aa023d160ac852a1cafeea3
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/02_DataExploration/SBPOPexploreCovariateCorrelations.m
@@ -0,0 +1,104 @@
+function [] = SBPOPexploreCovariateCorrelations(data,covNames,catNames,filename)
+% [DESCRIPTION]
+% Graphical exploration of covariates. Plots correlations between
+% continuous covariated and between continuous and categorical covariates.
+% And plot histograms of continuous ones.
+%
+% [SYNTAX]
+% [] = SBPOPexploreCovariateCorrelations(data,covNames,catNames,filename)
+%
+% [INPUT]
+% data:         Dataset in augmented generalized format.
+% covNames:     Cell-array with the names of the continuous covariates, as
+%               defined in the dataset
+% catNames:     Cell-array with the names of the categorical covariates, as
+%               defined in the dataset
+% filename:     Filename with path for storing the resulting PDF.
+%
+% [OUTPUT]
+% PDF at filename location.
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 19th April 2014
+%
+% [PLATFORM]
+% Windows, Unix, MATLAB
+%
+% [TOOLBOXES USED]
+% Statistics Toolbox
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+%
+% This program is Free Open Source Software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%% ===Prepare output folder and file
+if ~isempty(filename),
+    [folder,file] = fileparts(filename);
+    if ~isempty(folder),
+        mkdir(folder)
+    end
+    startNewPrintFigureSBPOP(filename); 
+else
+    filename = 'CovariateInformation';
+end
+
+%% ===Correlation of continuous covariates
+if ~isempty(covNames),
+    dataPlot = dataset();
+    allID = unique(data.ID);
+    for k=1:length(allID),
+        datak = data(data.ID==allID(k),:);
+        dataPlot = [dataPlot; datak(1,:)];
+    end
+    dataPlotcovcont = dataset();
+    for k=1:length(covNames),
+        dataPlotcovcont.(covNames{k}) = dataPlot.(covNames{k});
+    end
+    figure; clf;
+    SBPOPplotpairwiseCorr(dataPlotcovcont);
+    set(gcf,'color',[1 1 1]);
+    printFigureSBPOP(gcf,filename);
+    close(gcf);
+end
+
+%% ===Correlation of continuous and categorical covariates
+if ~isempty(catNames),
+    dataPlotcovcontcat = dataPlotcovcont;
+    for k=1:length(catNames),
+        dataPlotcovcontcat.(catNames{k}) = dataPlot.(catNames{k});
+    end
+    SBPOPplotCovarianceCat(dataPlotcovcontcat,covNames,catNames);
+end
+set(gcf,'color',[1 1 1]);
+printFigureSBPOP(gcf,filename);
+close(gcf);
+
+%% ===Histograms of continuous covariates
+for k=1:length(covNames),
+    hist(dataPlotcovcont.(covNames{k}));
+    xlabel(covNames{k},'FontSize',18,'Interpreter','none')
+    ylabel('Numbers','FontSize',18)
+    set(gcf,'color',[1 1 1]);
+    printFigureSBPOP(gcf,filename);
+    close(gcf);
+end
+
+convert2pdfSBPOP(filename);
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/02_DataExploration/SBPOPexploreIndivData.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/02_DataExploration/SBPOPexploreIndivData.m
new file mode 100644
index 0000000000000000000000000000000000000000..46e3eaa6fd0913de7ff6bbf3e0dbfd0f3619cdcf
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/02_DataExploration/SBPOPexploreIndivData.m
@@ -0,0 +1,228 @@
+function [] = SBPOPexploreIndivData(data,TYPE_NAME,filename,options)
+% [DESCRIPTION]
+% This function allows to plot individual data from a standardized PKPD
+% dataset. The standard dataspec is defined in the help to the function 
+% SBPOPcheckDataFormat, so please look there for more information.
+%
+% MDV=1 observation records are not considered
+% 
+% [SYNTAX]
+% [] = SBPOPexploreIndivData(data,TYPE,filename)
+% [] = SBPOPexploreIndivData(data,TYPE,filename,options)
+% [] = SBPOPexploreIndivData(data,NAME,filename)
+% [] = SBPOPexploreIndivData(data,NAME,filename,options)
+%
+% [INPUT]
+% data:         MATLAB PKPD dataset in standard data spec format  
+% TYPE:         Numeric value, determining the TYPE to be plotted. TYPE
+%               should be a value from the elements in the TYPE column.
+%               Standard assumes dose record has TYPE 0 and PK observation 
+%               record has TYPE=1, all other things are up to you.
+%               IMPORTANT: It assumes that a single SUBTYPE value is present
+%               in the dataset. This will be checked. 
+% NAME:         Instead of a TYPE the NAME of the component to plot can be
+%               specified as a string. NAME needs to be the name as entered 
+%               in the NAME column of the dataset.
+% options:      MATLAB structure with additional options
+%
+%       options.logY        = 0: linear Y axis (default), 1: log Y axis
+%       options.showDose    = 1: do show dosing information using vertical
+%                             lines and amount in text, 0: do not show (default)
+%       options.showText    = 1: do show text info next to each observed
+%                             datapoint (shows index in dataset data, TAD,
+%                             and DV values), 0: do not show (default)
+%       options.nIDperPage  = Numeric value, defining number of individual
+%                             subjects per page (rounded to fit). (default: 1)
+%       options.sameaxes    = Use same X and Y axes for all plots (default: 1 if nIDperPage>1 otherwise 0)
+%       options.nameGroup   = Name for grouping ... default: "ID"
+%       options.titlefontsize = Size for the title text (default: 16 if nIDperPage>1 otherwise 10 )
+%
+% [OUTPUT]
+% One plot per ID. If filename is specified the output is directly made to
+% file.
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 15th February 2013
+%
+% [PLATFORM]
+% Windows, Unix, MATLAB
+%
+% [TOOLBOXES USED]
+% Statistics Toolbox
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isa(data,'dataset'),
+    error('First input argument is not a MATLAB dataset.');
+end
+SBPOPcheckDataFormat(data);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% If dataset empty then return
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(data),
+    disp('Empty dataset.');
+    return;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if TYPE or NAME
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isnumeric(TYPE_NAME),
+    % Check if single SUBTYPE value
+    if length(unique(data.SUBTYPE(data.TYPE==TYPE_NAME))) > 1,
+        error('For this TYPE several SUBTYPE values are present.');
+    end
+    FLAG_TYPE = 1;
+else
+    % Check if name present
+    if ~ismember(TYPE_NAME,unique(data.NAME)),
+        error('Specified NAME not present in the dataset.');
+    end
+    FLAG_TYPE = 0;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle options
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try logY                = options.logY;                     catch, logY                 = 0;                end; %#ok<*CTCH>
+try showDose            = options.showDose;                 catch, showDose             = 0;                end;
+try showText            = options.showText;                 catch, showText             = 0;                end;
+try nIDperPage          = options.nIDperPage;               catch, nIDperPage           = 1;                end;
+try sameaxes            = options.sameaxes;                 catch
+    if nIDperPage > 1,
+        sameaxes             = 1;                
+    else
+        sameaxes             = 0;                
+    end
+end
+try nameGroup           = options.nameGroup;                catch, nameGroup            = 'ID';             end;
+try titlefontsize       = options.titlefontsize;            catch
+    if nIDperPage > 1,
+        titlefontsize        = 10;
+    else
+        titlefontsize        = 16;
+    end
+end
+
+ncols = ceil(sqrt(nIDperPage));
+nrows = ceil(nIDperPage/ncols);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Prepare the dataset for plotting
+% assume type==0 is the dose
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add indices to the data
+data.INDEX = (1:length(data))';
+% Get doses
+dataDose = data(data.TYPE==0,:);
+% Get observations
+if FLAG_TYPE,
+    dataObs  = data(data.TYPE==TYPE_NAME,:);
+else
+    dataObs  = data(strcmp(data.NAME,TYPE_NAME),:);
+end
+% Remove MDV==1
+dataObs  = dataObs(dataObs.MDV==0,:);
+
+% Add NaN values at times of doses into dataObs in order not to plot lines accross doses
+dataObsDose_NAN = dataDose;
+if FLAG_TYPE,
+    dataObsDose_NAN.TYPE(1:end) = TYPE_NAME;
+    dataObsDose_NAN.NAME(1:end) = dataObs.NAME(1);
+else
+    dataObsDose_NAN.NAME(1:end) = {TYPE_NAME};
+    dataObsDose_NAN.TYPE(1:end) = dataObs.TYPE(1);
+end
+dataObsDose_NAN.TYPE_NAME(1:end) = dataObs.TYPE_NAME(1);
+dataObsDose_NAN.UNIT(1:end) = dataObs.UNIT(1);
+dataObsDose_NAN.DURATION(1:end) = dataObs.DURATION(1);
+dataObsDose_NAN.ROUTE(1:end) = dataObs.ROUTE(1);
+dataObsDose_NAN.INTERVAL(1:end) = dataObs.INTERVAL(1);
+dataObsDose_NAN.NR_DOSES(1:end) = dataObs.NR_DOSES(1);
+dataObsDose_NAN.VALUE(1:end) = NaN;
+dataObsDose_NAN.DV(1:end) = NaN;
+
+dataObs = [dataObs; dataObsDose_NAN];
+dataObs = sortrows(dataObs,{'STYSID1A','TIME','TYPE'});
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Set up plotting function options (SBPOPplottrellis)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dataPlot                = dataObs;
+nameX                   = 'TIME';
+nameY                   = 'DV';
+options                 = [];
+options.xlabelText      = ['Time [' dataObs.TIME_UNIT{1} ']'];
+options.ylabelText      = [dataObs.NAME{1} ' [' dataObs.UNIT{1} ']'];
+options.nameSubGroup    = 'ID';
+options.logX            = 0;
+options.logY            = logY;
+options.markersize      = 20;
+options.sameaxes        = 0;
+options.showgrid        = 1;
+options.nrows           = nrows;
+options.ncols           = ncols;
+options.linecolor       = 0.2*[1 1 1];
+options.filename        = filename;
+
+if showDose,
+    options.verticallines.data                  = dataDose;
+    options.verticallines.nameDataVertical      = 'AMT';
+    options.verticallines.showtext              = 1;
+    options.verticallines.shownameDataVertical  = 1;
+    options.verticallines.linecolor             = 0.2*[1 1 1];
+end
+
+if nrows>1,
+    options.ylabelfirstonly = 1;
+end
+
+options.heighttitlebar  = 0.05+0.03*nrows;
+options.sameaxes        = sameaxes;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Generate text to show next to observations 
+% By default Index, TAD, DV
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if showText,
+    options.nameText        = 'nameText';
+    options.textFontsize    = 8;
+    dataPlot.nameText = cell(length(dataPlot),1);
+    for k=1:length(dataObs),
+        dataPlot.nameText{k} = sprintf('  IX%d (%g,%g)',dataPlot.INDEX(k),dataPlot.TAD(k),dataPlot.DV(k));
+    end
+end
+
+if ~isempty(titlefontsize),
+    options.titlefontsize = titlefontsize;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Do the plotting
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBPOPplottrellis(dataPlot,nameGroup,nameX,nameY,options)
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/02_DataExploration/SBPOPexploreSummaryStats.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/02_DataExploration/SBPOPexploreSummaryStats.m
new file mode 100644
index 0000000000000000000000000000000000000000..101f3b64eb9b6012e3f34d39d1bfb9641ee3ca32
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/02_DataExploration/SBPOPexploreSummaryStats.m
@@ -0,0 +1,189 @@
+function [] = SBPOPexploreSummaryStats(data,covNames,catNames,filename)
+% [DESCRIPTION]
+% This function produces summary statistics for the provided dataset
+% and displays the results in a table in the MATLAB window. If a filename
+% is provdided, the results are also exported to this file. The data need
+% to be provided, following the standard dataspec, defined in the help to
+% the function SBPOPcheckDataFormat, so please look there for more
+% information.   
+%
+% THIS ANALYSIS IS OBVIOUSLY ONLY SUITED FOR NON-TIMEVARYING COVARIATES!
+%
+% [SYNTAX]
+% [] = SBPOPexploreSummaryStats(data,covNames,catNames)
+% [] = SBPOPexploreSummaryStats(data,covNames,catNames,filename)
+%
+% [INPUT]
+% data:         MATLAB PKPD dataset in standard data spec format  
+% covNames:     Cell-array with the names of the continuous covariates, as
+%               defined in the dataset
+% catNames:     Cell-array with the names of the categorical covariates, as
+%               defined in the dataset
+% filename:     String with filename / path for export of information in
+%               same format as displayed in command window. If not defined,
+%               then no file will be created.
+%
+% [OUTPUT]
+% Table output in MATLAB window and in file if desired.
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 11th May 2010
+%
+% [TOOLBOXES USED]
+% Statistics Toolbox
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin==3,
+    filename = '';
+end
+
+%% ===Prepare output folder and file
+if ~isempty(filename),
+    [folder,dummy] = fileparts(filename);
+    if ~isempty(folder),
+        mkdir(folder)
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check cov and catnames
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isa(data,'dataset'),
+    error('First input argument is not a MATLAB dataset.');
+end
+% SBPOPcheckDataFormat(data);
+datanames = get(data,'VarNames');
+for k=1:length(covNames),
+    if isempty(strmatchSB(covNames{k},datanames,'exact')), error('The dataset does not contain the covariate ''%s''.',covNames{k}); end    
+end
+for k=1:length(catNames),
+    if isempty(strmatchSB(catNames{k},datanames,'exact')), error('The dataset does not contain the covariate ''%s''.',catNames{k}); end    
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get first record of each subject
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+allID = unique(data.ID);
+datafirst = dataset();
+for k=1:length(allID),
+    IDkindex = find(data.ID==allID(k));
+    datafirstk = data(IDkindex(1),:);
+    datafirst = [datafirst; datafirstk];
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run through continuous covariates and determine statistics
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+table = {'Name','N','mean','std','min','Q1','median','Q3','max'};
+for k=1:length(covNames),
+    covName = covNames{k};
+	covValues = eval(sprintf('datafirst.%s;',covName));
+    % Remove NaNs if present
+    nanINDEX = find(isnan(covValues));
+    covValues(nanINDEX) = [];
+    % Determine several measures of the covariate values
+    Nk = length(covValues);
+    meank = mean(covValues);
+    stdk = std(covValues);
+    maxk = max(covValues);
+    Q3k = quantile(covValues,0.75);
+    mediank = quantile(covValues,0.5);
+    Q1k = quantile(covValues,0.25);
+    mink = min(covValues);
+    % Report the results
+    table = [table; {covName, Nk, meank, stdk, mink, Q1k, mediank, Q3k, maxk}];
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Report continuous covariate stats
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+textContinuous = sprintf('Continuous covariates\n');
+textContinuous = sprintf('%s=====================\n',textContinuous);
+if isempty(covNames),
+    textContinuous = sprintf('%sNo continuous covariates defined.\n\n',textContinuous);
+else
+    x = sprintf('%10s',table{1,:});
+    textContinuous = sprintf('%s%s\n',textContinuous,x);
+    for k=2:size(table,1),
+        x = sprintf('%10s',table{k,1});
+        y = sprintf('%10.3g',table{k,2:end});
+        textContinuous = sprintf('%s%s%s\n',textContinuous,x,y);
+    end
+end
+disp(textContinuous);
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run through categorical covariates and determine statistics
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+textcategorical = sprintf('\nCategorical covariates\n');
+textcategorical = sprintf('%s======================\n',textcategorical);
+if isempty(catNames),
+    textcategorical = sprintf('%sNo categorical covariates defined.\n\n',textcategorical);
+else
+    for k=1:length(catNames),
+        catName = catNames{k};
+        catValues = eval(sprintf('datafirst.%s;',catName));
+        % Remove NaNs if present
+        nanINDEX = find(isnan(catValues));
+        catValues(nanINDEX) = [];
+        % Determine number of levels present
+        levels = unique(catValues);
+        % Determine number of subjects per level
+        Nlevels = [];
+        for k2=1:length(levels),
+            Nlevels(end+1) = length(find(catValues == levels(k2)));
+        end
+        % Report the results
+        table = {'Name','N','Levels'};
+        for k2=1:length(levels),
+            table{end+1} = sprintf('%d',levels(k2));
+        end
+        table{2,1} = catName;
+        table{2,2} = length(catValues);
+        table{2,3} = length(levels);
+        for k2=1:length(levels),
+            table{2,3+k2} = sprintf('%d',Nlevels(k2));
+        end
+        
+        % Report the table
+        x = sprintf('%10s',table{1,:});
+        y = sprintf('%10s%10d%10d',table{2,1},table{2,2},table{2,3});
+        z = sprintf('%10s',table{2,4:end});
+        textcategoricalk = sprintf('%s\n%s%s\n',x,y,z);
+        textcategorical = sprintf('%s\n%s',textcategorical,textcategoricalk);
+    end
+end
+disp(textcategorical);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Export results to file if filename defined
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(filename),
+    fid = fopen([filename '.txt'],'w');
+    fprintf(fid,'%s\n%s\n\n',textContinuous,textcategorical);
+    fclose(fid);
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/03_DataCleaning/SBPOPcleanBLOQdata.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/03_DataCleaning/SBPOPcleanBLOQdata.m
new file mode 100644
index 0000000000000000000000000000000000000000..2e0cf0e574f026fd7041140be494c9036425014d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/03_DataCleaning/SBPOPcleanBLOQdata.m
@@ -0,0 +1,122 @@
+function [datanew] = SBPOPcleanBLOQdata(data,FLAG_LLOQ,filename)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle LLOQ in the desired way 
+%
+% FLAG_LLOQ = 0: remove LLOQ data
+% FLAG_LLOQ = 1: use CENS=1 and add LLOQ into DV
+% FLAG_LLOQ = 2: use CENS=0, remove all but first LLOQ value, set DV to LLOQ/2
+%
+% Do this for all records that have LLOQ information available.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+if nargin==2,
+    filename = '';
+end
+
+%% Copy dataset
+datanew     = data;
+
+%% Find all NAMEs which have LLOQ information
+handleNames = unique(datanew.NAME(~isnan(datanew.LLOQ)));
+
+%% Create a CENS column in the dataset (all 0)
+datanew.CENS = zeros(length(datanew),1);
+
+%% Find all records that are BLOQ for all names that have LLOQ information
+ixBLOQ = [];
+for k=1:length(handleNames),
+    ixBLOQ = [ixBLOQ(:); find(datanew.DV < datanew.LLOQ & strcmp(datanew.NAME,handleNames{k}))];
+end
+
+%% Update CENS column with 1 for the BLOQ records
+datanew.CENS(ixBLOQ) = 1;
+
+%% Handle the different approaches for BLOQ handling
+if FLAG_LLOQ==0,
+    % REMOVE all BLOQ data
+    % Get the BLOQ data
+    dataBLLOQ = datanew(datanew.CENS==1,:);
+    % Remove the BLOQ data
+    datanew(datanew.CENS==1,:) = [];
+    % Save the removed data in the output path
+    if ~isempty(filename),
+        SBPOPexportCSVdataset(dataBLLOQ,[filename '.csv']);
+    end
+    disp('The following BLOQ data were removed:');
+    disp('=====================================');
+    dataBLLOQ
+    
+elseif FLAG_LLOQ==1,
+    % Use CENS as in Monolix with LLOQ in DV
+    datanew.DV(ixBLOQ) = datanew.LLOQ(ixBLOQ);
+    text = sprintf('The BLOQ PK data were kept and the DV values were set to LLOQ, CENS=1');
+    disp(text);
+    if ~isempty(filename),
+        fid = fopen([filename '.txt'],'w');
+        fprintf(fid,'%s\n',text);
+        fclose(fid);
+    end
+    
+elseif FLAG_LLOQ==2,
+    % Set DV below LLOQ values to 0.5*LLOQ and remove subsequent ones
+    % A CENS column will be present in the dataset but not used (all 0)
+    % Find LLOQ values
+    
+    % Set all DV values with CENS=1 to LLOQ/2
+    datanew.DV(datanew.CENS==1) = datanew.LLOQ(datanew.CENS==1)/2;
+    % Now we only need to remove the consecutive LLOQ records for each readout
+   
+    dataRemoved = dataset();
+    dataDVset   = dataset();
+    datanew2    = datanew;
+    
+    % Cycle through each NAME with LLOQ info
+    for k00=1:length(handleNames),
+        % Get NAME data
+        dataNAME   = datanew2(strcmp(datanew2.NAME,handleNames{k00}),:);
+        % Get data without NAME
+        dataNONAME = datanew2(~strcmp(datanew2.NAME,handleNames{k00}),:);
+        % Get empty dataset to collect handled NAME data
+        dataNAMEhandled = dataset();
+        
+        % Cycle through each subject in data with NAME
+        allID = unique(dataNAME.ID);
+        
+        for k=1:length(allID),
+            datak       = dataNAME(dataNAME.ID==allID(k),:);
+            % Check if BLOQ available
+            ix_BLOQ = find(datak.CENS);
+            if ~isempty(ix_BLOQ),
+                % See if consecutive readouts available - if yes then remove all subsequent ones
+                delta = [NaN; diff(ix_BLOQ)];
+                ix_consequtive = ix_BLOQ(delta==1);
+                % Save records to be removed
+                dataRemoved = [dataRemoved; datak(ix_consequtive,:)];
+                % Save records for which DV set to LLOQ/2
+                dataDVset = [dataDVset; datak(ix_BLOQ(find(delta~=1)),:)];
+                % Remove records
+                datak(ix_consequtive,:) = [];
+            end
+            % Combine again the NAME data after handling
+            dataNAMEhandled = [dataNAMEhandled; datak];
+        end
+        
+        % Combine again dataNAMEhandled with dataNONAME
+        datanew2 = [dataNONAME; dataNAMEhandled];
+    end
+    % Sort
+    datanew = sortrows(datanew2,{'ID','TIME','TYPE','SUBTYPE'});
+    % Reset CENS column to 0
+    datanew.CENS(1:end) = 0;
+    if ~isempty(filename),
+        % Save the removed data in the output path
+        SBPOPexportCSVdataset(dataRemoved,[filename '_REMOVED.csv']);
+        SBPOPexportCSVdataset(dataDVset,[filename '_LLOQ2.csv']);
+    end
+    disp('The following BLOQ data were removed:');
+    disp('=====================================');
+    dataRemoved
+    disp('The following BLOQ data obtained DV=LLOQ/2:');
+    disp('===========================================');
+    dataDVset
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/03_DataCleaning/SBPOPcleanImputeCovariates.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/03_DataCleaning/SBPOPcleanImputeCovariates.m
new file mode 100644
index 0000000000000000000000000000000000000000..310cb9f6f84338f0641b48654e915422509ca233
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/03_DataCleaning/SBPOPcleanImputeCovariates.m
@@ -0,0 +1,231 @@
+function [datanew] = SBPOPcleanImputeCovariates(data,covNames,catNames,catImputationValues,filename)
+% [DESCRIPTION]
+% This function does imputation of missing covariates. Continuous covs will
+% be imputed by the median and missing categorical covariates will be set
+% to "catImputationValues". 
+%
+% Important assumption: If cov is missing in first record for a subject,
+% then it is missing for all records in a subject. The function will check
+% that the dataset complies with the SBPOP standard for clinical datasets.
+%
+% The data need to be provided, following the standard dataspec, defined in
+% the help to the function SBPOPcheckDataFormat, so please look there for
+% more information.   
+% 
+% [SYNTAX]
+% [datanew] = SBPOPcleanImputeCovariates(data,covNames,catNames,catImputationValues)
+% [datanew] = SBPOPcleanImputeCovariates(data,covNames,catNames,catImputationValues,filename)
+%
+% [INPUT]
+% data:         MATLAB PKPD dataset in standard data spec format  
+% covNames:     Cell-array with names of continuous covariates
+% catNames:     Cell-array with names of categorical covariates
+% catImputationValues:     Vector with same length as catNames, specifying
+%               the imputation values for these categorical covariates (if
+%               needed)
+% filename:     String with filename / path for export of information in
+%               same format as displayed in command window. If not defined,
+%               then no file will be created.
+%
+% [OUTPUT]
+% datanew:      Dataset as input "data" but with imputed covariates
+%
+% [ASSUMPTIONS]
+% Important assumption: If cov is missing in first record for a subject, then 
+% it is missing for all records in a subject.
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 10th May 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MODESIM, MATLAB R2009a
+%
+% [KEYWORDS]
+% MATLAB, SBPOP, datacleaning, covariate, imputation, impute
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle optional input argument
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin==4,
+    filename = '';
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check cov and catnames
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+datanames = get(data,'VarNames');
+for k=1:length(covNames),
+    if isempty(strmatchSB(covNames{k},datanames,'exact')), error('The dataset does not contain the covariate ''%s''.',covNames{k}); end    
+end
+for k=1:length(catNames),
+    if isempty(strmatchSB(catNames{k},datanames,'exact')), error('The dataset does not contain the covariate ''%s''.',catNames{k}); end    
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check catImputationValues
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if length(catImputationValues) ~= length(catNames),
+    error('Length of catImputationValues needs to be same as length of catNames.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Remember original dataset
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+datanew = data;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get first record of each subject
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+allID = unique(data.ID);
+datafirst = dataset();
+for k=1:length(allID),
+    IDkindex = find(data.ID==allID(k));
+    datafirstk = data(IDkindex(1),:);
+    datafirst = [datafirst; datafirstk];
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run through continuous covariates and determine medians and replace them
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+textCovs = '';
+for k=1:length(covNames),
+    % Get median based on single entries in subjects (datafirst)
+	covValues  = datafirst.(covNames{k});
+    covMedian  = nanmedian(covValues);
+    if isnan(covMedian),
+        error('Covariate "%s" seems not to have any information for any subject. Please check your dataset.',covNames{k});
+    end
+    % Replace NaN by median in full dataset (datanew)
+    % First find NaNs in datanew cov values
+    covValuesAll = datanew.(covNames{k});
+    nanIndicesAll = find(isnan(covValuesAll));
+    covValuesAll(nanIndicesAll) = covMedian;
+    % Add changed cov values to dataset
+    datanew.(covNames{k}) = covValuesAll(:);
+    % Get some stats
+    IDmissing = unique(data.ID(nanIndicesAll));
+    nrIDmissing = length(IDmissing);
+    nrIDtotal = length(unique(data.ID));
+    % Report the stats
+    if ~isempty(nanIndicesAll),
+        textCovs = sprintf('%s\tCovariate "%s" missing in the following %d subjects:\n',textCovs,covNames{k},nrIDmissing);
+        textCovs = sprintf('%s\t  Total number of subjects: %d\n',textCovs,nrIDtotal);
+        textCovs = sprintf('%s\t  Imputed to median: %g\n',textCovs,covMedian);
+        textCovs = sprintf('%s\n',textCovs);
+        textCovs = sprintf('%s            STYSID1A             ID\n',textCovs);
+        textCovs = sprintf('%s            -------------------------------------\n',textCovs);
+        for k2=1:nrIDmissing,
+            STYSID1A = data.STYSID1A(data.ID==IDmissing(k2));
+            STYSID1A = STYSID1A{1};
+            textCovs = sprintf('%s            %s%s%8d\n',textCovs,STYSID1A,char(32)*ones(1,20-length(STYSID1A)),IDmissing(k2));
+        end
+        textCovs = sprintf('%s\n',textCovs);
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run through categorical covariates and check if NaN present
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+textCats = '';
+for k=1:length(catNames),
+    % Find the non-defined categorical covariates
+	catValues = data.(catNames{k});
+    nanIndices = find(isnan(catValues));
+    % Replace NaN values by catImputationValues(k) element
+    catValues(nanIndices) = catImputationValues(k);
+    % Add changed cat values to dataset
+    datanew.(catNames{k}) = catValues;
+    % Get some stats
+    IDmissing = unique(data.ID(nanIndices));
+    nrIDmissing = length(IDmissing);
+    nrIDtotal = length(unique(data.ID));
+    % Report the stats
+    if ~isempty(nanIndices),
+        textCats = sprintf('%s\tCategorical covariate "%s" is missing for the following %d subjects:\n',textCats,catNames{k},nrIDmissing);
+        textCats = sprintf('%s\t  Total number of subjects: %d\n',textCats,nrIDtotal);
+        textCats = sprintf('%s\t  Imputed to value "%d".\n',textCats,catImputationValues(k));
+        textCats = sprintf('%s\n',textCats);
+        textCats = sprintf('%s            STYSID1A             ID\n',textCats);
+        textCats = sprintf('%s            -------------------------------------\n',textCats);
+        for k2=1:nrIDmissing,
+            STYSID1A = data.STYSID1A(data.ID==IDmissing(k2));
+            STYSID1A = STYSID1A{1};
+            textCats = sprintf('%s            %s%s%8d\n',textCats,STYSID1A,char(32)*ones(1,20-length(STYSID1A)),IDmissing(k2));
+        end
+        textCats = sprintf('%s\n',textCats);
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Display results in command window
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf('\tImputation of continuous covariates:\n');
+fprintf('\t====================================\n\n');
+if isempty(textCovs),
+    fprintf('\tNo imputation done.\n');
+else
+    disp(textCovs);
+end
+fprintf('\n\tImputation of categorical covariates:\n');
+fprintf('\t=====================================\n\n');
+if isempty(textCats),
+    fprintf('\tNo imputation done.\n');
+else
+    disp(textCats);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Export results to file if filename defined
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(filename),
+    % Create output folder if not yet existing
+    [p,f,e] = fileparts(filename);
+    warning off
+    mkdir(p);
+    warning on
+    
+    % Write out the file
+    fid = fopen([strrep(filename,'.txt','') '.txt'],'w');
+    fprintf(fid,'\tImputation of continuous covariates:\n');
+    fprintf(fid,'\t====================================\n\n');
+    if isempty(textCovs),
+        fprintf(fid,'\tNo imputation done.\n');
+    else
+        fprintf(fid,'%s\n',textCovs);
+    end
+    fprintf(fid,'\n\tImputation of categorical covariates:\n');
+    fprintf(fid,'\t=====================================\n\n');
+    if isempty(textCats),
+        fprintf(fid,'\tNo imputation done.\n');
+    else
+        fprintf(fid,'%s\n',textCats);
+    end
+    fclose(fid);
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/03_DataCleaning/SBPOPcleanRemoveFewObsSubjects.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/03_DataCleaning/SBPOPcleanRemoveFewObsSubjects.m
new file mode 100644
index 0000000000000000000000000000000000000000..5fde519ff874d72777865978737e9c6712131712
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/03_DataCleaning/SBPOPcleanRemoveFewObsSubjects.m
@@ -0,0 +1,179 @@
+function [datanew] = SBPOPcleanRemoveFewObsSubjects(data,Nobs,type,filename)
+% [DESCRIPTION]
+% This function removes all subjects from the dataset which do have <= Nobs
+% observation records from TYPE "type" with MDV=0.
+% 
+% The data need to be provided, following the standard dataspec, defined in
+% the help to the function SBPOPcheckDataFormat, so please look there for
+% more information.   
+%
+% [SYNTAX]
+% [datanew] = SBPOPcleanRemoveFewObsSubjects(data,Nobs,type)
+% [datanew] = SBPOPcleanRemoveFewObsSubjects(data,Nobs,type,filename)
+%
+% [INPUT]
+% data:         MATLAB PKPD dataset in standard data spec format  
+% Nobs:         All subjects from the dataset which do have <= Nobs
+%               observation records from TYPE "type" with MDV=0 are removed.
+% type:         Numeric value specifying the TYPE of observation to
+%               consider (only needed for PK) or string with name in NAME
+%               column in dataset (for PD).
+% filename:     String with filename / path for export of information in
+%               same format as displayed in command window. If not defined,
+%               then no file will be created.
+%
+% [OUTPUT]
+% datanew:      dataset with removed subjects. 
+%               Additionally, in the workspace it will be written out which 
+%               subject (IDs) have been removed.
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 9th May 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MODESIM, MATLAB R2009a
+%
+% [KEYWORDS]
+% MATLAB, SBPOP, dataexploration, datacleaning
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle optional input argument
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin==3,
+    filename = '';
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle numeric or string "type" input argument
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isnumeric(type),
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Cycle through the different subjects and collect the IDs to be removed
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    allID = unique(data.ID);
+    removeID = [];
+    for k=1:length(allID),
+        % Get subject dataset
+        datak = data(data.ID==allID(k),:);
+        % Find all observation records (TYPE==type) which are (MDV==0)
+        observationIndices = find(((datak.TYPE==type).*(datak.MDV==0)));
+        if length(observationIndices) <= Nobs,
+            removeID(end+1) = datak.ID(1);
+        end
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Remove the IDs
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    datanew = data;
+    for k=1:length(removeID),
+        datanew(datanew.ID==removeID(k),:) = [];
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Create text output (type dependent)
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    text = '';
+    text = sprintf('The function "SBPOPcleanRemoveFewObsSubjects" has removed the following %d subjects (IDs shown):\n',length(removeID));
+    text = sprintf('%s(Settings: removing subjects with not more than %d observations of TYPE=%d)\n',text,Nobs,type);
+        
+else
+    % type is string and assumed to be a name in the NAME column
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Cycle through the different subjects and collect the IDs to be removed
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    allID = unique(data.ID);
+    removeID = [];
+    for k=1:length(allID),
+        % Get subject dataset
+        datak = data(data.ID==allID(k),:);
+        % Find all observation records (NAME==type) which are (MDV==0)
+        observationIndices = find((strcmp(datak.NAME,type).*(datak.MDV==0)));
+        if length(observationIndices) <= Nobs,
+            removeID(end+1) = datak.ID(1);
+        end
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Remove the IDs
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    datanew = data;
+    for k=1:length(removeID),
+        datanew(datanew.ID==removeID(k),:) = [];
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Create text output (type dependent)
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    text = '';
+    text = sprintf('The function "SBPOPcleanRemoveFewObsSubjects" has removed the following %d subjects (IDs shown):\n',length(removeID));
+    text = sprintf('%s(Settings: removing subjects with not more than %d observations of NAME=%s)\n',text,Nobs,type);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Finalize text
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+text = sprintf('%s=================================================================================================\n',text);
+text = sprintf('%s    STYSID1A             ID            TRT\n',text);
+text = sprintf('%s-------------------------------------------------------------------------------------------------\n',text);
+textID = '';
+for k=1:length(removeID),
+    STYSID1A = data.STYSID1A(data.ID==removeID(k));
+    STYSID1A = STYSID1A{1};
+    TRT      = data.TRT(data.ID==removeID(k));
+    TRT      = TRT(1);
+    textID = sprintf('%s    %s%s%8d    %8d\n',textID,STYSID1A,char(32)*ones(1,20-length(STYSID1A)),removeID(k),TRT);
+end
+text = sprintf('%s%s\n',text,textID);
+text = sprintf('%s================================================================================================\n',text);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Show output in command window
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+disp(text);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Export results to file if filename defined
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(filename),
+    % Create output folder if not yet existing
+    [p,f,e] = fileparts(filename);
+    warning off
+    mkdir(p);
+    warning on
+    
+    fid = fopen([strrep(filename,'.txt','') '.txt'],'w');
+    fprintf(fid,'%s\n\n',text);
+    fclose(fid);
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/03_DataCleaning/SBPOPcleanRemovePlaceboSubjects.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/03_DataCleaning/SBPOPcleanRemovePlaceboSubjects.m
new file mode 100644
index 0000000000000000000000000000000000000000..f7198c0ae1f30d2cf598793e917ee5fb01a236f6
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/03_DataCleaning/SBPOPcleanRemovePlaceboSubjects.m
@@ -0,0 +1,141 @@
+function [datanew] = SBPOPcleanRemovePlaceboSubjects(data,filename)
+% [DESCRIPTION]
+% This function simply removes all subjects which only received 0 doses or
+% no doses at all. Dose records defined by TYPE=0.
+% 
+% The data need to be provided, following the standard dataspec, defined in
+% the help to the function SBPOPcheckDataFormat, so please look there for
+% more information.   
+%
+% [SYNTAX]
+% [datanew] = SBPOPcleanRemovePlaceboSubjects(data)
+% [datanew] = SBPOPcleanRemovePlaceboSubjects(data,filename)
+%
+% [INPUT]
+% data:         MATLAB PKPD dataset in standard data spec format  
+% filename:     String with filename / path for export of information in
+%               same format as displayed in command window. If not defined,
+%               then no file will be created.
+%
+% [OUTPUT]
+% datanew:      dataset with removed placebo (TRT==0) subjects. 
+%
+% [ASSUMPTIONS]
+% The input dataset needs to follow the SBPOP specification for clinical data. 
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 9th May 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MODESIM, MATLAB R2009a
+%
+% [KEYWORDS]
+% MATLAB, SBPOP, dataexploration, datacleaning
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle optional input argument
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin==1,
+    filename = '';
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get info about placebo subjects and create datanew dataset without them
+% Placebo subjects defined by
+% - subjects without dose records (TYPE=0)
+% - subjects with AMT=0 for TYPE=0
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+placeboIDs = [];
+allID = unique(data.ID);
+datanew = dataset();
+for k=1:length(allID),
+    datak = data(data.ID==allID(k),:);
+    PLACEBO = 0;
+    ix_TYPE0 = find(datak.TYPE==0);
+    if isempty(ix_TYPE0),
+        % No dose record available
+        PLACEBO = 1;
+    elseif sum(abs(datak.AMT(ix_TYPE0))) == 0,
+        % Only 0 doses
+        PLACEBO = 1;
+    end        
+    if PLACEBO,
+        placeboIDs = [placeboIDs allID(k)];
+    else
+        datanew = [datanew; datak];
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Prepare user info text about placebo patients
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create text output
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+text = '';
+text = sprintf('The function "SBPOPcleanRemovePlaceboSubjects" has removed the following %d subjects:\n',length(placeboIDs));
+text = sprintf('%s(Settings: removing subjects NO dose records (TYPE=0) or NO non-zero AMT entry in dose records)\n',text);
+text = sprintf('%s=================================================================================================\n',text);
+text = sprintf('%s    STYSID1A             ID            TRT\n',text);
+text = sprintf('%s-------------------------------------------------------------------------------------------------\n',text);
+textID = '';
+for k=1:length(placeboIDs),
+    STYSID1A = data.STYSID1A(data.ID==placeboIDs(k));
+    STYSID1A = STYSID1A{1};
+    TRT      = data.TRT(data.ID==placeboIDs(k));
+    TRT      = TRT(1);
+    textID = sprintf('%s    %s%s%8d    %8d\n',textID,STYSID1A,char(32)*ones(1,20-length(STYSID1A)),placeboIDs(k),TRT);
+end
+if isempty(placeboIDs),
+    textID = sprintf('No placebo subjects present.');
+end
+text = sprintf('%s%s\n',text,textID);
+text = sprintf('%s=================================================================================================\n',text);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Show output in command window
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+disp(text);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Export results to file if filename defined
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(filename),
+    % Create output folder if not yet existing
+    [p,f,e] = fileparts(filename);
+    warning off
+    mkdir(p);
+    warning on
+        
+    fid = fopen([strrep(filename,'.txt','') '.txt'],'w');
+    fprintf(fid,'%s\n\n',text);
+    fclose(fid);
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/03_DataCleaning/SBPOPcleanRemoveRecordsSUBJECTs.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/03_DataCleaning/SBPOPcleanRemoveRecordsSUBJECTs.m
new file mode 100644
index 0000000000000000000000000000000000000000..97d09f1e19f397155f42deb80947d0a8783583a0
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/03_DataCleaning/SBPOPcleanRemoveRecordsSUBJECTs.m
@@ -0,0 +1,175 @@
+function [datanew] = SBPOPcleanRemoveRecordsSUBJECTs(data,removeSUBJECT,removeREC,filename)
+% [DESCRIPTION]
+% This function removes defined subjects (by STYSID1A) and records (by index of
+% the row in which the record is located).The user needs to provide the
+% information about subjects and records to remove in the input arguments.
+% 
+% The data need to be provided, following the standard dataspec, defined in
+% the help to the function SBPOPcheckDataFormat, so please look there for
+% more information.   
+%
+% [SYNTAX]
+% [datanew] = SBPOPcleanRemoveRecordsSUBJECTs(data,removeSUBJECT,removeREC)
+% [datanew] = SBPOPcleanRemoveRecordsSUBJECTs(data,removeSUBJECT,removeREC,filename)
+%
+% [INPUT]
+% data:         MATLAB PKPD dataset in standard data spec format  
+% removeSUBJECT:  Cell-matrix with 2 columns. First column contains the
+%                 STYSID1A unique identifiers of the subjects to be removed
+%                 from the dataset. The second column contains strings,
+%                 which define the reason why this subject is removed.
+% removeREC:    Cell-matrix with 2 columns. First column contains the indices
+%               of the records to be removed from the dataset. The second
+%               column contains strings, which define the reason why this
+%               record is removed.
+% filename:     String with filename / path for export of information in
+%               same format as displayed in command window. If not defined,
+%               then no file will be created.
+%
+% [OUTPUT]
+% datanew:      dataset with removed subjects and records. 
+%               Additionally, in the workspace it will be written out which 
+%               subjects and records have been removed, including the
+%               reason why.
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 9th May 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MODESIM, MATLAB R2009a
+%
+% [KEYWORDS]
+% MATLAB, SBPOP, dataexploration, datacleaning
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle optional input argument
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin==3,
+    filename = '';
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine indexes and IDs based on the input
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(removeSUBJECT),
+    removeSUBJECT_index  = removeSUBJECT(:,1);
+else
+    removeSUBJECT_index = [];
+end
+if ~isempty(removeREC),
+    removeREC_index = cell2mat(removeREC(:,1));
+else
+    removeREC_index = [];
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Make copy of data to be used as output argument
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+datanew = data;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Remove identified records (first)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+datanew(removeREC_index,:) = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Remove identified subjects (second)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(removeSUBJECT_index),
+    datanew(strcmp(datanew.STYSID1A,removeSUBJECT_index{k}),:) = [];
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Prepare output text - removed records
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(removeREC_index),
+    textRecs = '';
+    textRecs = sprintf('%sThe following N=%d records have been removed:\n',textRecs,length(removeREC));
+    textRecs = sprintf('%s=============================================\n\n',textRecs);
+    textRecs = sprintf('%s    INDEX      STYSID1A              ID             DV      TIME       TAD    TYPE    REASON\n',textRecs);
+    for k=1:length(removeREC_index),
+        STYSID1A = data.STYSID1A(data.ID==data.ID(removeREC_index(k)));
+        STYSID1A = STYSID1A{1};
+        textRecs = sprintf('%s   %6d      %s%s  %6d  %8.3g  %8.3g  %8.3g  %6d    %s\n', ...
+            textRecs,...
+            removeREC_index(k),...
+            STYSID1A, ...
+            char(32)*ones(1,20-length(STYSID1A)), ...
+            data.ID(removeREC_index(k)),...
+            data.DV(removeREC_index(k)),...
+            data.TIME(removeREC_index(k)),...
+            data.TAD(removeREC_index(k)),...
+            data.TYPE(removeREC_index(k)),...
+            removeREC{k,2});
+    end
+else
+    textRecs = 'No records removed by function SBPOPcleanRemoveRecordsIDs.';
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Prepare output text - removed SUBJECTs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(removeSUBJECT_index),
+    textIDs = '';
+    textIDs = sprintf('%sThe following N=%d SUBJECTs have been removed:\n',textIDs,length(removeSUBJECT_index));
+    textIDs = sprintf('%s=========================================\n\n',textIDs);
+    textIDs = sprintf('%s    STYSID1A            ID          REASON\n',textIDs);
+    for k=1:length(removeSUBJECT_index),
+        ID = data.ID(strcmp(data.STYSID1A,removeSUBJECT_index{k}));
+        IDtext = num2str(ID(1));
+        
+        textIDs = sprintf('%s    %s%s%s%s%s\n',textIDs,removeSUBJECT_index{k},char(32)*ones(1,20-length(removeSUBJECT_index{k})),IDtext,char(32)*ones(1,20-length(removeSUBJECT_index{k})),removeSUBJECT{k,2});
+    end
+else
+    textIDs = 'No subjects removed by function SBPOPcleanRemoveRecordsIDs.';
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Show output in command window
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+disp(textRecs);
+disp(textIDs);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Export results to file if filename defined
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(filename),
+    % Create output folder if not yet existing
+    [p,f,e] = fileparts(filename);
+    warning off
+    mkdir(p);
+    warning on
+        
+    fid = fopen([strrep(filename,'.txt','') '.txt'],'w');
+    fprintf(fid,'%s\n%s\n\n',textRecs,textIDs);
+    fclose(fid);
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/03_DataCleaning/SBPOPhandleSameTimeObservationRecords.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/03_DataCleaning/SBPOPhandleSameTimeObservationRecords.m
new file mode 100644
index 0000000000000000000000000000000000000000..90867ae5381c66940a942f809691b7c6a24f4e75
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/03_DataCleaning/SBPOPhandleSameTimeObservationRecords.m
@@ -0,0 +1,99 @@
+function [dataChanged] = SBPOPhandleSameTimeObservationRecords(data)
+% [DESCRIPTION]
+% Both due to clinical database issues and programming issues it might
+% happen that similar records in a dataset might have exactly the same time
+% of assessment / administration. Normally, this should be solved during
+% data cleaning and validation before making its way into the modeling
+% dataset. However, it might still happen and modeling might not want to
+% wait until the final data cleaning has happened - because then modeling
+% is typically to late to impact any decisions. 
+%
+% For PK modeling such records typically are not an issue. However, for PD
+% modeling where the dataset is augmented by regression parameters
+% (concentration or PK parameters) this poses a problem, since the
+% estimation software does see two regression variable assignments at the
+% same time point and does not know what to do - and in the case of Monolix
+% fails with an error.
+% 
+% This function here solves that in a very simple way. If the same time is
+% detected more than once for the same TYPE in a subject, then these times
+% are very slighlty changed by adding a tiny random noise to these time
+% points.
+%
+% This is not a function that should be used for regulatory modeling - for
+% exploratory modeling, however, it is fine.
+%
+% The function will do this for records of all TYPES!
+%
+% If for a certain TYPE for a certain ID same times appear, the whole time
+% vector for this type in this ID will be added with random noise of a
+% standard deviation of 0.001, corresponding to std of 3.6 seconds if time
+% unit is hours and 86 seconds if time unit is days. So no problem.
+% 
+% [SYNTAX]
+% [dataChanged] = SBPOPhandleSameTimeObservationRecords(data)
+%
+% [INPUT]
+% data:         MATLAB dataset in the standard SBPOP format
+%
+% [OUTPUT]
+% Changed dataset (if needed). 
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 24th February 2013
+%
+% [PLATFORM]
+% Windows, Unix, MATLAB
+%
+% [TOOLBOXES USED]
+% Statistics Toolbox
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle uniqueness of TIME per ID and TYPE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+allID = unique(data.ID);
+dataChanged = dataset();
+for k=1:length(allID),
+    datak = data(data.ID==allID(k),:);
+    allTYPE = unique(datak.TYPE);
+    for k2=1:length(allTYPE),
+        datakk2 = datak(datak.TYPE==allTYPE(k2),:);
+        % Get TIME 
+        TIME = datakk2.TIME;
+        % Check it
+        if ~(length(TIME) == length(unique(TIME))),
+            ABSCHANGE       = 0.001; % 3.6 seconds if timeunit = hour, 86 seconds if time unit is day
+            TIMEpert        = TIME + ABSCHANGE*randn(size(TIME));
+            datakk2.TIME    = TIMEpert;
+        end
+        % Collect data
+        dataChanged = [dataChanged; datakk2];
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Sort changed dataset to get time vector ascending
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dataChanged = sortrows(dataChanged,{'ID','TIME','TYPE'});
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/05_ModelBuilding/SBPOPcreateNLMEmodelGENcode.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/05_ModelBuilding/SBPOPcreateNLMEmodelGENcode.m
new file mode 100644
index 0000000000000000000000000000000000000000..ebfa5bf7351a437b707984d9452ff1bf29be7977
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/05_ModelBuilding/SBPOPcreateNLMEmodelGENcode.m
@@ -0,0 +1,358 @@
+function SBPOPcreateNLMEmodelGENcode(modelPath,dosingPath,dataPath,projectPath)
+% SBPOPcreateNLMEmodelGENcode: generates code that can be used to generate 
+% a NONMEM or MONOLIX NLME project. This code is simply displayed in the 
+% command window and can be adapted according to the needs.
+%
+% It will take all parameters in the model that are set to <estimate> and 
+% create the needed structures. It will also check for regression parameters 
+% and handle them accordingly. 
+%
+% [SYNTAX]
+% SBPOPcreateNLMEmodelGENcode(modelPath,dosingPath,dataPath,projectPath)
+%
+% modelPath: 	 Path to the SBmodel file to use 
+% dosingPath: 	 Path to the SBPOPdosing scheme to use
+% dataPath:      Path to the CSV dataset to use 
+% projectPath:   Path to the folder in which to create the project
+% 
+% [OUTPUT]
+% The output is done in the command window as text.
+% - Text generated to create the project - also printed in the command window to be copied and pasted
+% - Text generated to create the algorithm settings - also printed in the command window to be copied and pasted
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+
+% Information:
+% ============
+% Copyright (c) 2015 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Define algorithm text
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+textAlgorithm = '';
+textAlgorithm = sprintf('%s\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%',textAlgorithm);
+textAlgorithm = sprintf('%s\n%%%% Algorithm generation code template',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% Below you can find code that is required to set-up algorithm',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% settings for NLME model fits for both NONMEM and MONOLIX.',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% It covers the most important ones, which will lead to reasonable',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% results in most cases.',textAlgorithm);
+textAlgorithm = sprintf('%s\n%%',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% The different parts are commented to explain what can be edited, etc.',textAlgorithm);
+textAlgorithm = sprintf('%s\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%',textAlgorithm);
+textAlgorithm = sprintf('%s\n',textAlgorithm);
+
+textAlgorithm = sprintf('%s\nalgorithm                       = [];',textAlgorithm);
+textAlgorithm = sprintf('%s\n',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% General settings',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% ================',textAlgorithm);
+textAlgorithm = sprintf('%s\n',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% Six digit number, defining the SEED of the random generators.',textAlgorithm);
+textAlgorithm = sprintf('%s\nalgorithm.SEED                  = 123456;',textAlgorithm);
+textAlgorithm = sprintf('%s\n',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% K1 and K2 need to be defined big enough to ensure that the convergence',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% trajectories are reasonably stable (only needed for SAEM).',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% 200 for K2 is fine in most cases. 500-2000 for K1 is reasonable.',textAlgorithm);
+textAlgorithm = sprintf('%s\nalgorithm.K1                    = 500;',textAlgorithm);
+textAlgorithm = sprintf('%s\nalgorithm.K2                    = 200;',textAlgorithm);
+textAlgorithm = sprintf('%s\n',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% NRCHAINS can be increased in the case that few subjects only available in',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% the dataset.',textAlgorithm);
+textAlgorithm = sprintf('%s\nalgorithm.NRCHAINS              = 1;',textAlgorithm);
+textAlgorithm = sprintf('%s\n',textAlgorithm);
+
+textAlgorithm = sprintf('%s\n%% NONMEM specific settings',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% ========================',textAlgorithm);
+textAlgorithm = sprintf('%s\n',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% Please choose the NONMEM algorithm you want to use for the parameter ',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% estimation. "SAEM" works just fine, while the older algorithms',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% "FOCE" and "FOCEI" are not the most robust ones. The use of "FO" should',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% be avoided.',textAlgorithm);
+textAlgorithm = sprintf('%s\nalgorithm.METHOD                = ''SAEM'';  %% ''SAEM'' (default) or ''FO'', ''FOCE'', ''FOCEI''',textAlgorithm);
+textAlgorithm = sprintf('%s\n',textAlgorithm);
+
+textAlgorithm = sprintf('%s\n%% ITS=1 performs an iterative two stage parameter estimation before the main',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% algorithm. If this improves the results can be debated ... but it might give',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% you a good feeling to do something cool ... if you do not want that, than',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% set ITS=0.',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% ITS_ITERATIONS defines the number of ITS iterations. 10 is just fine ...',textAlgorithm);
+textAlgorithm = sprintf('%s\nalgorithm.ITS                   = 1;',textAlgorithm);
+textAlgorithm = sprintf('%s\nalgorithm.ITS_ITERATIONS        = 10;',textAlgorithm);
+textAlgorithm = sprintf('%s\n',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% IMPORTANCESAMPLING=1 is needed only in the case when "SAEM" is used as',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% parameter estimation method. It will after the main estimation calculate the ',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% true objective function value that is needed for OFV bean-counting ...',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% IMP_ITERATIONS defines the number of IMP iterations. Avoid large numbers ...',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% 5-20 is typically just fine. ',textAlgorithm);
+textAlgorithm = sprintf('%s\nalgorithm.IMPORTANCESAMPLING    = 1;',textAlgorithm);
+textAlgorithm = sprintf('%s\nalgorithm.IMP_ITERATIONS        = 5;',textAlgorithm);
+textAlgorithm = sprintf('%s\n',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% MAXEVAL is used for the "FO", "FOCE", and "FOCEI" algorithms and determines ',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% the maximum number of objective function evaluations that are performed.',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% 9999 is the default value and if the optimum has not been reached by then, ',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% then you have problems with your model anyway.',textAlgorithm);
+textAlgorithm = sprintf('%s\nalgorithm.MAXEVAL               = 9999;',textAlgorithm);
+textAlgorithm = sprintf('%s\n',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% Please read the NONMEM manual what this means ... in modern programming languages ',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% this option would not be needed ...',textAlgorithm);
+textAlgorithm = sprintf('%s\nalgorithm.SIGDIGITS             = 3;',textAlgorithm);
+textAlgorithm = sprintf('%s\n',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% MONOLIX specific settings',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% =========================',textAlgorithm);
+textAlgorithm = sprintf('%s\n',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% LLsetting defines if the objective function value is determined by linearization ',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% or by importance sampling. If your model runs fast, you might consider ',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% "importantsampling". For large datasets and if ODE models are needed, the time',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% for calculation of the objective function might get prohibitively long. Then',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% use "linearization". I use "linearization" most of the time.',textAlgorithm);
+textAlgorithm = sprintf('%s\nalgorithm.LLsetting             = ''linearization'';   %% or ''linearization'' (default) or ''importantsampling''',textAlgorithm);
+textAlgorithm = sprintf('%s\n',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% FIMsetting defines if the Fischer Information Matrix is determined by "stochasticApproximation" (slow)',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% or by "linearization". "linearization" is fine in all cases, involving continuous readouts. ',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% The standard errors are calculated reasonably close to "stochasticApproximation" and the PKPD reviewers',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% at the health authorities will anyway want a bootstrap to be done => Do not waste time with ',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% calculating the Fischer Information Matrix with stochastic approximation, unless the model requires it.',textAlgorithm);
+textAlgorithm = sprintf('%s\nalgorithm.FIMsetting            = ''linearization'';   %% ''linearization'' (default) or ''stochasticApproximation''',textAlgorithm);
+textAlgorithm = sprintf('%s\n',textAlgorithm);
+textAlgorithm = sprintf('%s\n%% INDIVparametersetting: Just keep this setting --- it is just fine and leads to what you want in almost all cases.',textAlgorithm);
+textAlgorithm = sprintf('%s\nalgorithm.INDIVparametersetting = ''conditionalMode''; %% ''conditionalMode'' (default) ... others not considered for now',textAlgorithm);
+textAlgorithm = sprintf('%s\n',textAlgorithm);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Add covariate information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+textCovariates = '';
+textCovariates = sprintf('%s\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%',textCovariates);
+textCovariates = sprintf('%s\n%%%% Define names of covariates',textCovariates);
+textCovariates = sprintf('%s\n%% If not done previously, please define below the names of the continuous',textCovariates);
+textCovariates = sprintf('%s\n%% and categorical covariates that you want to consider in the model and which',textCovariates);
+textCovariates = sprintf('%s\n%% are available in your dataset.',textCovariates);
+textCovariates = sprintf('%s\n%%',textCovariates);
+textCovariates = sprintf('%s\n%% Please note that these covariates are not allowed to vary over time.',textCovariates);
+textCovariates = sprintf('%s\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%',textCovariates);
+textCovariates = sprintf('%s\n',textCovariates);
+textCovariates = sprintf('%s\n%% "covNames" needs to contain the names of the CONTINUOUS covariates of',textCovariates);
+textCovariates = sprintf('%s\n%% interest in the dataset. Please exchange the names that are available with the',textCovariates);
+textCovariates = sprintf('%s\n%% names of covariates in your dataset.',textCovariates);
+textCovariates = sprintf('%s\ncovNames = {''WT0'' ''AGE0'' ''BMI0''};',textCovariates);
+textCovariates = sprintf('%s\n',textCovariates);
+textCovariates = sprintf('%s\n%% "catNames" needs to contain the names of the CATEGORICAL covariates of',textCovariates);
+textCovariates = sprintf('%s\n%% interest in the dataset. Please exchange the names that are available with the',textCovariates);
+textCovariates = sprintf('%s\n%% names of covariates in your dataset.',textCovariates);
+textCovariates = sprintf('%s\ncatNames = {''SEX'',''OBESE''};',textCovariates);
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Generate information for the model generation text
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% Get model and dosing
+model       = SBmodel(modelPath);
+dosing      = SBPOPdosing(dosingPath);
+
+% merge model
+moddos      = mergemoddosSBPOP(model,dosing);
+
+% Determine model estimation info
+modelinfo   = basicmodelparsingSBPOP(moddos);
+
+% Constructing relative path from project to data
+% Assumptions: 
+% - modeling dataset located in "Data" folder, 
+% - model somewhere in the "Models" folder hierarchy
+% - Structure with Models, Data, Scripts, Output used
+nStepsProject = length(strfind(projectPath,'/'));
+dataRelPathFromProject = '';
+for k=1:nStepsProject,
+    dataRelPathFromProject = sprintf('%s../',dataRelPathFromProject);
+end
+dataRelPathFromProject = [dataRelPathFromProject 'Data'];
+
+% Get data file parts
+[~,data_f,data_ext] = fileparts(dataPath);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Define model generation text
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+textModel = '';
+textModel = sprintf('%s\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%',textModel);
+textModel = sprintf('%s\n%%%% Model generation code template',textModel);
+textModel = sprintf('%s\n%% Below you can find code that is required to generate either a MONOLIX or',textModel);
+textModel = sprintf('%s\n%% NONMEM project, based on your selection of the model, the dosing, the',textModel);
+textModel = sprintf('%s\n%% data and the location of the project folder to be created.',textModel);
+textModel = sprintf('%s\n%%',textModel);
+textModel = sprintf('%s\n%% The different parts are commented to explain what can be edited, etc.',textModel);
+textModel = sprintf('%s\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%',textModel);
+textModel = sprintf('%s\n',textModel);
+
+textModel = sprintf('%s\n%% Load the model',textModel);
+textModel = sprintf('%s\nmodel                           = SBmodel(''%s'');',textModel,modelPath);
+textModel = sprintf('%s\n',textModel);
+textModel = sprintf('%s\n%% Define the regression parameters',textModel);
+textModel = sprintf('%s\n%% They need to appear in the same order in the model and in the dataset (at least for MONOLIX)',textModel);
+textModel = sprintf('%s\nregressionParameters            = {',textModel);
+regressionParametersText = sprintf('''%s'' ',modelinfo.param_reg.name);
+textModel = sprintf('%s%s};',textModel,regressionParametersText(1:end-1));
+textModel = sprintf('%s\n',textModel);
+textModel = sprintf('%s\n%% Analyze the dataset to determine which column is what... this is done automatically',textModel);
+textModel = sprintf('%s\n%% and typically it is always correct :-)',textModel);
+textModel = sprintf('%s\ndata                            = SBPOPloadCSVdataset(''%s'');',textModel,dataPath);
+textModel = sprintf('%s\ndataheader_MONOLIX              = SBPOPgetMonolixDataHeader(data,covNames,catNames,regressionParameters);',textModel);
+textModel = sprintf('%s\ndataheader_NONMEM               = SBPOPgetNONMEMdataHeader(data,covNames,catNames,regressionParameters);',textModel);
+textModel = sprintf('%s\n',textModel);
+textModel = sprintf('%s\n%% If you want to use MONOLIX, then assign dataheader_MONOLIX to dataheader,',textModel);
+textModel = sprintf('%s\n%% otherwise if NONMEM, then dataheader_NONMEM',textModel);
+textModel = sprintf('%s\ndataheader                      = dataheader_MONOLIX;',textModel);
+textModel = sprintf('%s\n',textModel);
+textModel = sprintf('%s\n%% Load the dosing scheme',textModel);
+textModel = sprintf('%s\ndosing                          = SBPOPdosing(''%s'');',textModel,dosingPath);
+textModel = sprintf('%s\n',textModel);
+textModel = sprintf('%s\n%% Define the data information for the generation of the MONOLIX or NONMEM',textModel);
+textModel = sprintf('%s\n%% project',textModel);
+textModel = sprintf('%s\ndataFIT                         = [];',textModel);
+textModel = sprintf('%s\n%% dataRelPathFromProject needs to be the relative path from the project',textModel);
+textModel = sprintf('%s\n%% folder to be created to the folder in which the dataset is located',textModel);
+textModel = sprintf('%s\n%% This needs to be checked carefully --- automatic generation of this path is challenging,',textModel);
+textModel = sprintf('%s\n%% or at least I have not spent enoug time on it yet.',textModel);
+textModel = sprintf('%s\ndataFIT.dataRelPathFromProject  = ''%s'';',textModel,dataRelPathFromProject);
+textModel = sprintf('%s\ndataFIT.dataHeaderIdent         = dataheader;',textModel);
+textModel = sprintf('%s\ndataFIT.dataFileName            = ''%s%s'';',textModel,data_f,data_ext);
+textModel = sprintf('%s\n',textModel);
+textModel = sprintf('%s\n%% Below we define options for what to estimate, how, etc.',textModel);
+textModel = sprintf('%s\noptions                         = [];',textModel);
+textModel = sprintf('%s\n',textModel);
+textModel = sprintf('%s\n%% These are the parameter names which are defined to be <estimate> ...',textModel);
+textModel = sprintf('%s\n%%                                  ',textModel);
+paramEstimation = {modelinfo.param_est.name};
+x = {};
+for k=1:length(modelinfo.param_est),
+    x{k} = sprintf('%s%s',modelinfo.param_est(k).name,char(32*ones(1,max(8-length(modelinfo.param_est(k).name),2))));
+end
+paramEstimationText = sprintf('%s',x{:});
+textModel = sprintf('%s%s',textModel,strtrim(paramEstimationText));
+
+textModel = sprintf('%s\n%% Initial guesses for the population mean parameters (fixed effects)',textModel);
+textModel = sprintf('%s\noptions.POPvalues0              = [',textModel);
+paramValuesText = '';
+for k=1:length(modelinfo.param_est),
+    y = sprintf('%1.3g%s',modelinfo.param_est(k).value0);
+    z = char(32*ones(1,length(x{k})-length(y)));
+    paramValuesText = sprintf('%s%s%s',paramValuesText,y,z);
+end
+textModel = sprintf('%s%s];',textModel,paramValuesText);
+
+textModel = sprintf('%s\n%% Vector defining what to estimate. A 0 means that this parameter is kept',textModel);
+textModel = sprintf('%s\n%% fixed on the initial guess. A 1 means that this parameter is estimated.',textModel);
+textModel = sprintf('%s\noptions.POPestimate             = [',textModel);
+paramValuesText = '';
+for k=1:length(modelinfo.param_est),
+    z = char(32*ones(1,length(x{k})-1));
+    paramValuesText = sprintf('%s1%s',paramValuesText,z);
+end
+textModel = sprintf('%s%s];',textModel,paramValuesText);
+
+textModel = sprintf('%s\n%% Initial guesses for the variability of this parameter in the population (random effects)',textModel);
+textModel = sprintf('%s\noptions.IIVvalues0              = [',textModel);
+paramValuesText = '';
+for k=1:length(modelinfo.param_est),
+    z = char(32*ones(1,length(x{k})-3));
+    paramValuesText = sprintf('%s0.5%s',paramValuesText,z);
+end
+textModel = sprintf('%s%s];',textModel,paramValuesText);
+
+textModel = sprintf('%s\n%% Vector defining what to estimate. A 0 means that the random effect for this parameter is not estimated (kept on 0)',textModel);
+textModel = sprintf('%s\n%% A 1 means that this parameter is estimated. A 2 means this parameter is',textModel);
+textModel = sprintf('%s\n%% kept fixed on its initial guess.',textModel);
+textModel = sprintf('%s\noptions.IIVestimate             = [',textModel);
+paramValuesText = '';
+for k=1:length(modelinfo.param_est),
+    z = char(32*ones(1,length(x{k})-1));
+    paramValuesText = sprintf('%s1%s',paramValuesText,z);
+end
+textModel = sprintf('%s%s];',textModel,paramValuesText);
+
+textModel = sprintf('%s\n%% Definition of the distribution of the interinvidiual parameters.',textModel);
+textModel = sprintf('%s\n%% ''L'' means: log normal',textModel);
+textModel = sprintf('%s\n%% ''N'' means: normal',textModel);
+textModel = sprintf('%s\n%% ''G'' means: logit normal',textModel);
+textModel = sprintf('%s\noptions.IIVdistribution         = {',textModel);
+paramValuesText = '';
+for k=1:length(modelinfo.param_est),
+    z = char(32*ones(1,length(x{k})-3));
+    paramValuesText = sprintf('%s''L''%s',paramValuesText,z);
+end
+textModel = sprintf('%s%s};',textModel,paramValuesText);
+
+textModel = sprintf('%s\n',textModel);
+
+textModel = sprintf('%s\n%% Definition of error models',textModel);
+textModel = sprintf('%s\noptions.errorModels             = ''',textModel);
+paramValuesText = '';
+for k=1:length(modelinfo.outputs),
+    paramValuesText = sprintf('%scomb1,',paramValuesText);
+end
+textModel = sprintf('%s%s'';',textModel,paramValuesText(1:end-1));
+
+textModel = sprintf('%s\noptions.errorParam0             = [',textModel);
+paramValuesText = '';
+for k=1:length(modelinfo.outputs),
+    paramValuesText = sprintf('%s1,0.3,',paramValuesText);
+end
+textModel = sprintf('%s%s];',textModel,paramValuesText(1:end-1));
+
+textModel = sprintf('%s\n',textModel);
+
+textModel = sprintf('%s\n%% Definition of covariance and covariate models',textModel);
+textModel = sprintf('%s\noptions.covarianceModel         = '''';',textModel);
+textModel = sprintf('%s\noptions.covariateModel          = '''';',textModel);
+textModel = sprintf('%s\n',textModel);
+
+textModel = sprintf('%s\n%% Robustness analysis. If Ntests>1 then Ntests models will be generated in the project folder,',textModel);
+textModel = sprintf('%s\n%% each starting from randomly selected initial guesses (based on std_noise_setting).',textModel);
+textModel = sprintf('%s\noptions.Ntests                  = 1;',textModel);
+textModel = sprintf('%s\noptions.std_noise_setting       = 0;',textModel);
+textModel = sprintf('%s\n',textModel);
+
+textModel = sprintf('%s\n%% Assignment of algorithm options',textModel);
+textModel = sprintf('%s\noptions.algorithm               = algorithm;',textModel);
+textModel = sprintf('%s\n',textModel);
+
+textModel = sprintf('%s\n%% Defnition of where to store the NLME project files',textModel);
+textModel = sprintf('%s\nprojectPath                     = ''%s'';',textModel,projectPath);
+textModel = sprintf('%s\n',textModel);
+
+textModel = sprintf('%s\n%% Run the function that creates the project files and run the model',textModel);
+textModel = sprintf('%s\n%% =================================================================',textModel);
+textModel = sprintf('%s\n',textModel);
+textModel = sprintf('%s\n%% For MONOLIX use:',textModel);
+textModel = sprintf('%s\nSBPOPcreateMONOLIXproject(model,dosing,dataFIT,projectPath,options)',textModel);
+textModel = sprintf('%s\nSBPOPrunMONOLIXproject(projectPath)',textModel);
+textModel = sprintf('%s\n',textModel);
+textModel = sprintf('%s\n%% For NONMEM use:',textModel);
+textModel = sprintf('%s\nSBPOPcreateNONMEMproject(model,dosing,dataFIT,projectPath,options)',textModel);
+textModel = sprintf('%s\nSBPOPrunNONMEMproject(projectPath)',textModel);
+textModel = sprintf('%s\n',textModel);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Output
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+clc; 
+disp(textAlgorithm);
+disp(textCovariates);
+disp(textModel);
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/06_ModelFitAnalysis/SBPOPfitanalysisETAvsCOV.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/06_ModelFitAnalysis/SBPOPfitanalysisETAvsCOV.m
new file mode 100644
index 0000000000000000000000000000000000000000..b0c8c2ec16afa2030cd9c5776e04ea85b4bf91eb
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/06_ModelFitAnalysis/SBPOPfitanalysisETAvsCOV.m
@@ -0,0 +1,104 @@
+function [] = SBPOPfitanalysisETAvsCOV(data,projectPath,covNames,catNames,options)
+% [DESCRIPTION]
+% This function is used to plot the individual variations over covariates
+% and categorical covariates. It can be used for a first assessment which
+% variables could be potentially interesting covariates in the model.
+%
+% For the analysis of the categorical covariates information from the
+% modeling dataset is used. This means that if transformations of
+% categorical covariates have been done in the model, the generated
+% information is of no big use (this is the case only for categorical
+% covariates).
+%
+% Whiskers on the boxplot define the 5th and 95th percentiles of the plotted data.
+%
+% [SYNTAX]
+% [] = SBPOPfitanalysisETAvsCOV(data,projectPath,covNames,catNames)
+% [] = SBPOPfitanalysisETAvsCOV(data,projectPath,covNames,catNames,options)
+%
+% [INPUT]
+% data:         Analysis dataset used for the Monolix Fit (needed to get
+%               information about categorical covariates). For NONMEM it
+%               can be kept empty.
+% projectPath:  Path to a NONMEM or MONOLIX project folder. 
+% covNames:     Cell-array with names of continuous covariates
+% catNames:     Cell-array with names of categorical covariates
+% options:      MATLAB structure with plotting optins:
+%                   
+%                   options.corrcoeffThreshold: number between 0 and 1. If
+%                          correlation above this value, then data plotted in red.
+%                          (default: 0.3)
+%                   options.filename:   If a filename is provided, then the results are exported
+%                                       into a postscript (windows) or PDf (unix) document with this name.
+%                   options.labels: enables adding ID labels next to each
+%                                   value. Helps identifying outliers that
+%                                   could drive the correlation.
+%
+% [OUTPUT]
+% Plots, ETAs over covariates
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 15th April 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MATLAB R2009a, MATLAB
+%
+% [KEYWORDS]
+% MATLAB, SBPOP, covariate search, covariate
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+if nargin==4,
+    options = [];
+end
+
+if isMONOLIXfitSBPOP(projectPath),
+    % Warn the user about potential issues with categorical data
+    disp('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
+    disp('SBPOPfitanalysisETAvsCOV: For the analysis of the categorical');
+    disp('covariates information from the modeling dataset is used. This means');
+    disp('that if transformations of categorical covariates have been done in');
+    disp('the model, the generated information might not be of use (this is');
+    disp('the case only for categorical covariates).');
+    disp('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
+    
+    fitanalysisETAvsCOVmonolixSBPOP(data,projectPath,covNames,catNames,options)    
+elseif isNONMEMfitSBPOP(projectPath),
+    % Tell the used that the provided data is not going to be used!
+    disp('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
+    disp('SBPOPfitanalysisETAvsCOV: For NONMEM projects the provided data is');
+    disp('not going to be used. All information present in the project.eta file.');
+    disp('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
+
+    fitanalysisETAvsCOVnonmemSBPOP([],projectPath,covNames,catNames,options)    
+else
+    error('Unknown project type.');
+end
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/06_ModelFitAnalysis/SBPOPfitanalysisGOFplots.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/06_ModelFitAnalysis/SBPOPfitanalysisGOFplots.m
new file mode 100644
index 0000000000000000000000000000000000000000..7e9751e54da478856787d674c79b805fc5819fc8
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/06_ModelFitAnalysis/SBPOPfitanalysisGOFplots.m
@@ -0,0 +1,437 @@
+function [] = SBPOPfitanalysisGOFplots(projectPath,outputNumber,options)
+% [DESCRIPTION]
+% This function produces several plots that can be used for checking the 
+% goodness of fit. 
+%
+% [SYNTAX]
+% [] = SBPOPfitanalysisGOFplots(projectPath)
+% [] = SBPOPfitanalysisGOFplots(projectPath,outputNumber)
+% [] = SBPOPfitanalysisGOFplots(projectPath,outputNumber,options)
+%
+% [INPUT]
+% projectPath:  Path to a NONMEM or MONOLIX project folder. The results of the
+%               model run need to be stored in a "RESULTS" folder in this
+%               path. 
+% outputNumber: Number of the output in the model to consider for plotting
+%               If not specified, then output number 1 is assumed (or if
+%               only single output in model, then this is used)
+% options:      MATLAB structure with plotting optins:
+%                   
+%                   options.filename:   If a filename is provided, then the results are exported
+%                                       into a postscript (windows) or PDf (unix) document with this name.
+%
+% [OUTPUT]
+% Plots or PDF/PS file
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 16th April 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MATLAB R2009a, MATLAB
+%
+% [KEYWORDS]
+% MATLAB, SBPOP, DV, PRED, IPRED, diagnostic, plot, individual fits
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try outputNumber = outputNumber;            catch, outputNumber = 1;    end
+try filename     = options.filename;        catch, filename = '';       end
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% If filename then remove old file
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(filename),
+    startNewPrintFigureSBPOP(filename);
+    % also create path if not yet created
+    [p,f,e] = fileparts(filename);
+    warning off
+    mkdir(p);
+    warning on
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle NONMEM/MONOLIX
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isMONOLIXfitSBPOP(projectPath),
+    predictions = parseMONOLIXpredictionsSBPOP(projectPath,outputNumber);
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Get the data
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    data        = dataset();
+    data.TIME   = predictions.time;
+    data.DV     = predictions.(['y' num2str(outputNumber)]);
+    data.popPred   = predictions.popPred;
+    data.indPred_mode  = predictions.indPred_mode;
+    data.meanWRes  = predictions.meanWRes;
+    data.indWRes_mode  = predictions.indWRes_mode;
+    data.NPDE   = predictions.NPDE;
+
+    IWRES   = 'indWRes_mode';
+    IPRED   = 'indPred_mode';
+    PRED    = 'popPred';
+    PWRES   = 'meanWRes';
+    TIME    = 'TIME';
+
+elseif isNONMEMfitSBPOP(projectPath),
+    predictions = parseNONMEMpredictionsSBPOP(projectPath,outputNumber);
+    
+    % Get the right name for PRED
+    ph    = parseProjectHeaderNONMEMSBPOP(projectPath);
+    PRED  = ph.RESIDUAL_NAMES_ORIG{strmatchSB('XPRED',ph.RESIDUAL_NAMES_USED)};
+    PWRES = ph.RESIDUAL_NAMES_ORIG{strmatchSB('XWRES',ph.RESIDUAL_NAMES_USED)};
+    TIME  = 'TIME2';
+    IPRED = 'IPRED';
+    IWRES = 'IWRES';
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Get the data
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    data            = dataset();
+    data.(TIME)     = predictions.TIME2;
+    data.DV         = predictions.DV;
+    data.(PRED)     = predictions.XPRED;
+    data.(IPRED)    = predictions.IPRED;
+    data.(PWRES)    = predictions.XWRES;
+    data.(IWRES)    = predictions.IWRES;
+    data.NPDE       = predictions.NPDE;
+else
+    error('Unknown project type.');
+end
+
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DV vs. (I)PRED: linear
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+nameX       = 'DV';
+nameY       = {PRED IPRED};
+optionsPlot                     = [];
+optionsPlot.logX                = 0;
+optionsPlot.logY                = 0;
+optionsPlot.sameaxes            = 1;
+optionsPlot.squareaxes          = 1;
+optionsPlot.showregressionline  = 1; 
+optionsPlot.showslope1line      = 1;
+optionsPlot.markersize          = 10;
+optionsPlot.linecolor           = 0.2*[1 1 1];
+optionsPlot.slope1linecolor     = [1 0 0];
+optionsPlot.axescolor           = 0.2*[1 1 1];
+SBPOPplotXY(data,nameX,nameY,optionsPlot)
+if ~isempty(filename),
+    printFigureSBPOP(gcf,filename);
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DV vs. (I)PRED: log
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+nameX       = 'DV';
+nameY       = {PRED IPRED};
+optionsPlot                     = [];
+optionsPlot.logX                = 1;
+optionsPlot.logY                = 1;
+optionsPlot.sameaxes            = 1;
+optionsPlot.squareaxes          = 1;
+optionsPlot.showregressionline  = 1; 
+optionsPlot.showslope1line      = 1;
+optionsPlot.markersize          = 10;
+optionsPlot.linecolor           = 0.2*[1 1 1];
+optionsPlot.slope1linecolor     = [1 0 0];
+optionsPlot.axescolor           = 0.2*[1 1 1];
+SBPOPplotXY(data,nameX,nameY,optionsPlot);
+if ~isempty(filename),
+    printFigureSBPOP(gcf,filename);
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PWRES/IWRES/NPDE vs TIME
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+nameX       = TIME;
+nameY       = {PWRES IWRES 'NPDE'};
+optionsPlot                     = [];
+optionsPlot.logX                = 0;
+optionsPlot.logY                = 0;
+optionsPlot.showmedian           = 1;
+optionsPlot.NbinsMedian          = 20;
+optionsPlot.showregressionline  = 1; 
+optionsPlot.nrows               = 3;
+optionsPlot.ncols               = 1;
+optionsPlot.sameaxes            = 0;
+optionsPlot.showzeroLines       = 1;
+optionsPlot.zeroLinescolor      = [0 0 0];
+optionsPlot.markersize          = 10;
+optionsPlot.heighttitlebar      = 0.08;
+optionsPlot.linecolor           = 0.2*[1 1 1];
+optionsPlot.axescolor           = 0.2*[1 1 1];
+SBPOPplotXY(data,nameX,nameY,optionsPlot)
+if ~isempty(filename),
+    printFigureSBPOP(gcf,filename);
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PWRES/IWRES/NPDE vs TIME - logX
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+nameX       = TIME;
+nameY       = {PWRES IWRES 'NPDE'};
+optionsPlot                     = [];
+optionsPlot.logX                = 1;
+optionsPlot.logY                = 0;
+optionsPlot.showmedian           = 1;
+optionsPlot.NbinsMedian          = 20;
+optionsPlot.showregressionline  = 1; 
+optionsPlot.nrows               = 3;
+optionsPlot.ncols               = 1;
+optionsPlot.sameaxes            = 0;
+optionsPlot.showzeroLines       = 1;
+optionsPlot.zeroLinescolor      = [0 0 0];
+optionsPlot.markersize          = 10;
+optionsPlot.heighttitlebar      = 0.08;
+optionsPlot.linecolor           = 0.2*[1 1 1];
+optionsPlot.axescolor           = 0.2*[1 1 1];
+SBPOPplotXY(data,nameX,nameY,optionsPlot)
+if ~isempty(filename),
+    printFigureSBPOP(gcf,filename);
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PWRES/IWRES/NPDE vs PRED
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+nameX       = PRED;
+nameY       = {PWRES, IWRES, 'NPDE'};
+optionsPlot                     = [];
+optionsPlot.logX                = 0;
+optionsPlot.logY                = 0;
+optionsPlot.showmedian           = 1;
+optionsPlot.NbinsMedian          = 20;
+optionsPlot.showregressionline  = 1; 
+optionsPlot.nrows               = 3;
+optionsPlot.ncols               = 1;
+optionsPlot.sameaxes            = 0;
+optionsPlot.showzeroLines       = 1;
+optionsPlot.markersize          = 10;
+optionsPlot.zeroLinescolor      = [0 0 0];
+optionsPlot.heighttitlebar      = 0.08;
+optionsPlot.linecolor           = 0.2*[1 1 1];
+optionsPlot.axescolor           = 0.2*[1 1 1];
+SBPOPplotXY(data,nameX,nameY,optionsPlot)
+if ~isempty(filename),
+    printFigureSBPOP(gcf,filename);
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PWRES/IWRES/NPDE vs PRED - logX
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+nameX       = PRED;
+nameY       = {PWRES, IWRES, 'NPDE'};
+optionsPlot                     = [];
+optionsPlot.logX                = 1;
+optionsPlot.logY                = 0;
+optionsPlot.showmedian           = 1;
+optionsPlot.NbinsMedian          = 20;
+optionsPlot.showregressionline  = 1; 
+optionsPlot.nrows               = 3;
+optionsPlot.ncols               = 1;
+optionsPlot.sameaxes            = 0;
+optionsPlot.showzeroLines       = 1;
+optionsPlot.markersize          = 10;
+optionsPlot.zeroLinescolor      = [0 0 0];
+optionsPlot.heighttitlebar      = 0.08;
+optionsPlot.linecolor           = 0.2*[1 1 1];
+optionsPlot.axescolor           = 0.2*[1 1 1];
+SBPOPplotXY(data,nameX,nameY,optionsPlot)
+if ~isempty(filename),
+    printFigureSBPOP(gcf,filename);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Histogram of WRES, compared to normal distribution
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+optionsPlot = [];
+optionsPlot.show2lines = 1;
+optionsPlot.stdNorm    = 1;
+optionsPlot.names      = {PWRES};
+SBPOPplotHistogram(data.(PWRES),optionsPlot)
+set(gcf,'Color',[1 1 1]);
+if ~isempty(filename),
+    printFigureSBPOP(gcf,filename);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Histogram of IWRES, compared to normal distribution
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+optionsPlot = [];
+optionsPlot.show2lines = 1;
+optionsPlot.stdNorm    = 1;
+optionsPlot.names      = {IWRES};
+SBPOPplotHistogram(data.(IWRES),optionsPlot)
+set(gcf,'Color',[1 1 1]);
+if ~isempty(filename),
+    printFigureSBPOP(gcf,filename);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Histogram of NPDE, compared to normal distribution
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+optionsPlot = [];
+optionsPlot.show2lines = 1;
+optionsPlot.stdNorm    = 1;
+optionsPlot.names      = {'NPDE'};
+SBPOPplotHistogram(data.NPDE,optionsPlot)
+set(gcf,'Color',[1 1 1]);
+if ~isempty(filename),
+    printFigureSBPOP(gcf,filename);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% QQPlot of WRES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+optionsPlot = [];
+optionsPlot.names      = {PWRES};
+SBPOPplotQQ(data.(PWRES),optionsPlot);
+grid on;
+set(gcf,'Color',[1 1 1]);
+if ~isempty(filename),
+    printFigureSBPOP(gcf,filename);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% QQPlot of IWRES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+optionsPlot = [];
+optionsPlot.names      = {IWRES};
+SBPOPplotQQ(data.(IWRES),optionsPlot);
+grid on;
+set(gcf,'Color',[1 1 1]);
+if ~isempty(filename),
+    printFigureSBPOP(gcf,filename);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% QQPlot of NPDE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+optionsPlot = [];
+optionsPlot.names      = {'NPDE'};
+SBPOPplotQQ(data.NPDE,optionsPlot);
+grid on;
+set(gcf,'Color',[1 1 1]);
+if ~isempty(filename),
+    printFigureSBPOP(gcf,filename);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% PDF plot of WRES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+figure;
+% Plot normal distribution
+x = linspace(-4,4,1000);
+y = normpdf(x,0,1);
+plot(x,y,'b--','LineWidth',2); hold on
+% Plot empirical distribution
+if max(length(data.(PWRES))/100) < 10,
+    nrbinsuse = 10;
+else
+    nrbinsuse = round(length(data.(PWRES))/100);
+end
+[n,x] = hist(data.(PWRES),nrbinsuse);
+plot(x,n/max(n)*max(y),'r-','LineWidth',2); 
+% Axis etc
+axis([-4 4 0 0.5]);
+grid on;
+title(sprintf('PDF of %s vs. Standard Normal',PWRES),'FontSize',14,'FontWeight','bold','Interpreter','none');
+ylabel('PDF','FontSize',14,'Interpreter','none');
+xlabel(PWRES,'FontSize',14,'Interpreter','none');
+set(gca,'FontSize',12);
+if ~isempty(filename),
+    printFigureSBPOP(gcf,filename);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% PDF plot of IWRES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+figure;
+% Plot normal distribution
+x = linspace(-4,4,1000);
+y = normpdf(x,0,1);
+plot(x,y,'b--','LineWidth',2); hold on
+% Plot empirical distribution
+if max(length(data.(IWRES))/100) < 10,
+    nrbinsuse = 10;
+else
+    nrbinsuse = round(length(data.(IWRES))/100);
+end
+[n,x] = hist(data.(IWRES),nrbinsuse);
+plot(x,n/max(n)*max(y),'r-','LineWidth',2); 
+% Axis etc
+axis([-4 4 0 0.5]);
+grid on;
+title(sprintf('PDF of %s vs. Standard Normal',IWRES),'FontSize',14,'FontWeight','bold','Interpreter','none');
+ylabel('PDF','FontSize',14,'Interpreter','none');
+xlabel(IWRES,'FontSize',14,'Interpreter','none');
+set(gca,'FontSize',12);
+if ~isempty(filename),
+    printFigureSBPOP(gcf,filename);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% PDF plot of NPDE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+figure;
+% Plot normal distribution
+x = linspace(-4,4,1000);
+y = normpdf(x,0,1);
+plot(x,y,'b--','LineWidth',2); hold on
+% Plot empirical distribution
+if max(length(data.NPDE)/100) < 10,
+    nrbinsuse = 10;
+else
+    nrbinsuse = round(length(data.NPDE)/100);
+end
+[n,x] = hist(data.NPDE,nrbinsuse);
+plot(x,n/max(n)*max(y),'r-','LineWidth',2); 
+% Axis etc
+axis([-4 4 0 0.5]);
+grid on;
+title('PDF of NPDE vs. Standard Normal','FontSize',14,'FontWeight','bold','Interpreter','none');
+ylabel('PDF','FontSize',14,'Interpreter','none');
+xlabel('NPDE','FontSize',14,'Interpreter','none');
+set(gca,'FontSize',12);
+if ~isempty(filename),
+    printFigureSBPOP(gcf,filename);
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PS2PDF
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(filename),
+    convert2pdfSBPOP(filename);
+    close all;
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/06_ModelFitAnalysis/SBPOPfitanalysisGeneralPlots.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/06_ModelFitAnalysis/SBPOPfitanalysisGeneralPlots.m
new file mode 100644
index 0000000000000000000000000000000000000000..8d8a8444a07cc99faa496c434ef125117da77e64
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/06_ModelFitAnalysis/SBPOPfitanalysisGeneralPlots.m
@@ -0,0 +1,143 @@
+function [] = SBPOPfitanalysisGeneralPlots(outputNumber,data,projectPath,covNames,catNames,options)
+% [DESCRIPTION]
+% This function is a wrapper for different fit analysis functions. Calling 
+% - SBPOPfitanalysisIndividualFits
+% - SBPOPfitanalysisGOFplots
+% - SBPOPfitanalysisRandomEffects
+% - SBPOPfitanalysisETAvsCOV
+% - SBPOPfitanalysisOutlierDetection
+%
+% The SBPOP standard clinical data structure is assumed and checked.
+%
+% This function is applicable for models with any number of outputs but it
+% only produces the results for one output at a time. The user needs to
+% provide the number of this output in the model in the variable
+% "outputNumber".
+% 
+% [SYNTAX]
+% [] = SBPOPfitanalysisGeneralPlots(outputNumber,data,projectPath,covNames,catNames)
+% [] = SBPOPfitanalysisGeneralPlots(outputNumber,data,projectPath,covNames,catNames,options)
+%
+% [INPUT]
+% outputNumber: Number of the output in the model to generate the plots for
+% data:         Analysis dataset used for the NONMEM or MONOLIX Fit (needed to get
+%               information about categorical covariates)
+% projectPath:  Path to a NONMEM or MONOLIX project folder. 
+% covNames:     Cell-array with names of continuous covariates
+% catNames:     Cell-array with names of categorical covariates
+% options:      MATLAB structure with additional options
+%
+%               options.basefilename: path and base part of the filenames where
+%                                 outputs are exported to. Default: 'fit_analysis'
+%               options.PWRESthresholdOutlier: Threshold for |PWRES| (default value: 5)
+%                                 above which an observation will be considered an outlier
+%
+% [OUTPUT]
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 9th May 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MODESIM, MATLAB R2009a
+%
+% [KEYWORDS]
+% MATLAB, SBPOP, dataexploration, datacleaning
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; wSBPOPfitanalysisGeneralPlots(outputNumber,data,projectPath,covNames,catNames,options)ithout even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle options
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try basefilename = options.basefilename;                            catch, basefilename = 'fit_analysis'; end; %#ok<*CTCH>
+try PWRESthresholdOutlier   = options.PWRESthresholdOutlier;        catch, PWRESthresholdOutlier = 5;                     end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create output folder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[p,f,e] = fileparts(basefilename);
+warning off
+mkdir(p);
+warning on
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run SBPOPfitanalysisIndividualFits - linear
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+filename = [basefilename '_01_Individual_Fits_linearY'];
+options = [];
+options.logY = 0;
+options.Nrows = 5;
+options.Ncols = 5;
+options.filename = filename;
+SBPOPfitanalysisIndividualFits(projectPath,outputNumber,options)
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run SBPOPfitanalysisIndividualFits - log
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+filename = [basefilename '_02_Individual_Fits_logY'];
+options = [];
+options.logY = 1;
+options.Nrows = 5;
+options.Ncols = 5;
+options.filename = filename;
+SBPOPfitanalysisIndividualFits(projectPath,outputNumber,options)
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run SBPOPfitanalysisGOFplots
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+filename = [basefilename '_03_GOF_plots'];
+options = [];
+options.filename = filename;
+SBPOPfitanalysisGOFplots(projectPath,outputNumber,options)
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run SBPOPfitanalysisRandomEffects
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+filename = [basefilename '_04_Random_Effects'];
+options = [];
+options.filename = filename;
+SBPOPfitanalysisRandomEffects(projectPath,options)
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run SBPOPfitanalysisETAvsCOV
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+filename = [basefilename '_05_ETAvsCOV'];
+options = [];
+options.filename = filename;
+options.corrcoeffThreshold = 0.3;
+SBPOPfitanalysisETAvsCOV(data,projectPath,covNames,catNames,options)
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run SBPOPfitanalysisOutlierDetection
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+filename = [basefilename '_06_OutlierDetection.txt'];
+options = [];
+options.filename = filename;
+options.PWRESthresholdOutlier = PWRESthresholdOutlier;
+SBPOPfitanalysisOutlierDetection(projectPath,outputNumber,options)
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/06_ModelFitAnalysis/SBPOPfitanalysisIndividualFits.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/06_ModelFitAnalysis/SBPOPfitanalysisIndividualFits.m
new file mode 100644
index 0000000000000000000000000000000000000000..a06fc4795a4358858d98c4c3ee7995752122bf5f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/06_ModelFitAnalysis/SBPOPfitanalysisIndividualFits.m
@@ -0,0 +1,189 @@
+function [] = SBPOPfitanalysisIndividualFits(projectPath,outputNumber,options)
+% [DESCRIPTION]
+% This function plots individual fits and population prediction against
+% observed data over time. Per ID a single plot is done. The number of
+% plots per page can be selected.
+% The plots can additionally be exported to a postscript document (windows) 
+% or PDF (unix).  
+%
+% [SYNTAX]
+% [] = SBPOPfitanalysisIndividualFits(projectPath)
+% [] = SBPOPfitanalysisIndividualFits(projectPath,outputNumber)
+% [] = SBPOPfitanalysisIndividualFits(projectPath,outputNumber,options)
+%
+% [INPUT]
+% projectPath:  Path to a NONMEM or MONOLIX project folder. The results of the
+%               model run need to be stored in a "RESULTS" folder in this
+%               path. 
+% outputNumber: Number of the output in the model to consider for plotting
+%               If not specified, then output number 1 is assumed (or if
+%               only single output in model, then this is used)
+% options:      MATLAB structure with plotting options:
+%                   
+%                   options.logY:       =1: semilogy plot, =0, linear plot (default: 0)
+% 					options.sameaxes:   =1: plot on same Y-axes (default: 0)
+%                   options.filename:   If a filename is provided, then the results are exported
+%                                       into a postscript (windows) or PDf (unix) document with this name.
+%                   options.Nrows:      Number of rows of plots per figure (default: 5)
+%                   options.Ncols:      Number of columns of plots per figure (default: 5)
+%                   options.color:      0=no color, 1=color (default: 1)
+%
+% [OUTPUT]
+% Per ID a single plot is done.
+% The plots can additionally be exported to a postscript document (windows) 
+% or PDF (unix).  
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 16th April 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MATLAB R2009a, MATLAB
+%
+% [KEYWORDS]
+% MATLAB, SBPOP, DV, PRED, IPRED, diagnostic, plot, individual fits
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+ 
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try outputNumber = outputNumber;            catch, outputNumber = 1;    end
+try logY         = options.logY;            catch, logY = 0;            end
+try sameaxes     = options.sameaxes;        catch, sameaxes = 0;        end
+try Nrows        = options.Nrows;           catch, Nrows = 5;           end
+try Ncols        = options.Ncols;           catch, Ncols = 5;           end
+try color        = options.color;           catch, color = 1;           end
+try filename     = options.filename;        catch, filename = '';       end
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle NONMEM/MONOLIX
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isMONOLIXfitSBPOP(projectPath),
+    predictions = parseMONOLIXpredictionsSBPOP(projectPath,outputNumber);
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Prepare the data
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Get observations
+    dataY       = dataset;
+    dataY.ID    = predictions.ID;
+    dataY.TIME  = predictions.time;
+    dataY.DV    = eval(['predictions.y' num2str(outputNumber)]);
+    dataY.group = 3*ones(length(dataY),1);
+    % Get population prediction (popPred)
+    dataP       = dataset;
+    dataP.ID    = predictions.ID;
+    dataP.TIME  = predictions.time;
+    dataP.DV    = predictions.popPred;
+    dataP.group = 1*ones(length(dataP),1);
+    % Get individual prediction (indPred_mode)
+    dataI       = dataset;
+    dataI.ID    = predictions.ID;
+    dataI.TIME  = predictions.time;
+    dataI.DV    = predictions.indPred_mode;
+    dataI.group = 2*ones(length(dataI),1);
+    % Combine the data for plotting
+    data = [dataY; dataP; dataI];
+
+    PRED = 'popPred';
+    IPRED = 'indPred_mode';
+    
+elseif isNONMEMfitSBPOP(projectPath),
+    predictions = parseNONMEMpredictionsSBPOP(projectPath,outputNumber);
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Prepare the data
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Get observations
+    dataY       = dataset;
+    dataY.ID    = predictions.ID;
+    dataY.TIME  = predictions.TIME2;
+    dataY.DV    = predictions.DV;
+    dataY.group = 3*ones(length(dataY),1);
+    % Get population prediction (popPred)
+    dataP       = dataset;
+    dataP.ID    = predictions.ID;
+    dataP.TIME  = predictions.TIME2;
+    dataP.DV    = predictions.XPRED;
+    dataP.group = 1*ones(length(dataP),1);
+    % Get individual prediction (indPred_mode)
+    dataI       = dataset;
+    dataI.ID    = predictions.ID;
+    dataI.TIME  = predictions.TIME2;
+    dataI.DV    = predictions.IPRED;
+    dataI.group = 2*ones(length(dataI),1);
+    % Combine the data for plotting
+    data = [dataY; dataP; dataI];
+    
+    % Get the right name for PRED
+    ph = parseProjectHeaderNONMEMSBPOP(projectPath);
+    PRED = ph.RESIDUAL_NAMES_ORIG{strmatchSB('XPRED',ph.RESIDUAL_NAMES_USED)};
+    
+    IPRED = 'IPRED';
+    
+else
+    error('Unknown project type.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Plot the data
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+nameGroup = 'ID';
+nameX     = 'TIME';
+nameY     = 'DV';
+
+optionsPlot                     = [];
+optionsPlot.logY                = logY;
+optionsPlot.nrows               = Nrows;
+optionsPlot.ncols               = Ncols;
+optionsPlot.nameSubGroup        = 'group';
+optionsPlot.nameColorGroup      = 'group';
+optionsPlot.showmarkers         = 1;
+optionsPlot.markersize          = 10;
+optionsPlot.linecolorsCustom    = [1 0 0; 0 0 1;0 0 0];
+optionsPlot.linetypesCustom     = {'--','o-','x'};
+optionsPlot.linewidth           = 2;
+optionsPlot.sameaxes            = sameaxes;
+optionsPlot.xlabelText          = 'Time';
+optionsPlot.ylabelText          = sprintf('Output %d (x: OBS, --: %s, o-: =%s)', outputNumber,PRED,IPRED);
+optionsPlot.heighttitlebar      = 0.12;
+optionsPlot.showlegend          = 0;
+optionsPlot.ylabelfirstonly     = 1;
+optionsPlot.filename            = filename;
+
+SBPOPplottrellis(data,nameGroup,nameX,nameY,optionsPlot)
+
+
+
+
+
+
+
+    
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/06_ModelFitAnalysis/SBPOPfitanalysisOutlierDetection.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/06_ModelFitAnalysis/SBPOPfitanalysisOutlierDetection.m
new file mode 100644
index 0000000000000000000000000000000000000000..b2b9fba2cd249b196a414e73b2fe3415054d5bcb
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/06_ModelFitAnalysis/SBPOPfitanalysisOutlierDetection.m
@@ -0,0 +1,157 @@
+function [] = SBPOPfitanalysisOutlierDetection(projectPath,outputNumber,options)
+% [DESCRIPTION]
+% This function considers PWRES and searches for outliers and displays info
+% about them.
+%
+% [SYNTAX]
+% [] = SBPOPfitanalysisOutlierDetection(projectPath)
+% [] = SBPOPfitanalysisOutlierDetection(projectPath,outputNumber)
+% [] = SBPOPfitanalysisOutlierDetection(projectPath,outputNumber,options)
+%
+% [INPUT]
+% projectPath:  Path to a NONMEM or MONOLIX project folder. The results of the
+%               model run need to be stored in a "RESULTS" folder in this
+%               path. 
+% outputNumber: Number of the output in the model to consider for plotting
+%               If not specified, then output number 1 is assumed (or if
+%               only single output in model, then this is used)
+% options:      MATLAB structure with plotting optins:
+%                   
+%                   options.PWRESthresholdOutlier: Threshold for |PWRES| (default value: 5)
+%                                       above which an observation will be considered an outlier
+%                   options.filename:   If a filename is provided, then the results are exported
+%                                       into a text file
+%
+% [OUTPUT]
+% Plots or PDF/PS file
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 16th April 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MATLAB R2009a, MATLAB
+%
+% [KEYWORDS]
+% MATLAB, SBPOP, DV, PRED, IPRED, diagnostic, plot, individual fits
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try outputNumber            = outputNumber;                         catch, outputNumber = 1;                end %#ok<*CTCH,*ASGSL>
+try PWRESthresholdOutlier   = options.PWRESthresholdOutlier;        catch, PWRESthresholdOutlier = 5;       end
+try filename                = options.filename;                     catch, filename = '';                   end
+    
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle NONMEM/MONOLIX
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isMONOLIXfitSBPOP(projectPath),
+    predictions = parseMONOLIXpredictionsSBPOP(projectPath,outputNumber);
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Get ID and PWRES and |PWRES|
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    X           = dataset();
+    X.ID        = predictions.ID;
+    X.TIME      = predictions.time;
+    X.DV        = eval(['predictions.y' num2str(outputNumber)]);
+    X.PWRES     = predictions.meanWRes;
+    X.absPWRES  = abs(predictions.meanWRes);
+  
+    PWRES   = 'meanWRes';
+    TIME    = 'TIME';
+
+elseif isNONMEMfitSBPOP(projectPath),
+    predictions = parseNONMEMpredictionsSBPOP(projectPath,outputNumber);
+    
+    % Get the right name for PRED
+    ph    = parseProjectHeaderNONMEMSBPOP(projectPath);
+    PWRES = ph.RESIDUAL_NAMES_ORIG{strmatchSB('XWRES',ph.RESIDUAL_NAMES_USED)};
+    TIME  = 'TIME2';
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Get ID and PWRES and |PWRES|
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    X           = dataset();
+    X.ID        = predictions.ID;
+    X.TIME      = predictions.TIME2;
+    X.DV        = predictions.DV;
+    X.PWRES     = predictions.XWRES;
+    X.absPWRES  = abs(predictions.XWRES);
+       
+else
+    error('Unknown project type.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Sort after |PWRES|
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+Y = sortrows(X,'absPWRES','descend');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Remove the ones below threshold for |PWRES|
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+Z = Y(Y.absPWRES>PWRESthresholdOutlier,:);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create report
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+textReport = '';
+textReport = sprintf('%s----------------------------------------------------------------------\n',textReport);
+textReport = sprintf('%sOutlier Detection |%s|>%g\n',textReport,PWRES,PWRESthresholdOutlier);
+textReport = sprintf('%s----------------------------------------------------------------------\n',textReport);
+if isempty(Z),
+    textReport = sprintf('%sNo outliers have been detected.\n\n',textReport);
+else
+    W = sortrows(Z,{'ID','TIME'});
+    allID = unique(W.ID);
+    for k=1:length(allID),
+        Wk = W(W.ID==allID(k),:);
+        textReport = sprintf('%s\n\tOutliers in ID: %d',textReport,allID(k));
+        textReport = sprintf('%s\n\t--------------------------------------\n',textReport);
+        textReport = sprintf('%s\t      %s          DV       %s\n',textReport,TIME,PWRES);
+        
+        for k2=1:length(Wk),
+            textReport = sprintf('%s\t%10.10g  %10.10g  %10.3g\n',textReport,Wk.TIME(k2),Wk.DV(k2),Wk.PWRES(k2));
+        end
+    end
+end
+disp(textReport);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Export file if filename given
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(filename),
+    fid = fopen([strrep(filename,'.txt','') '.txt'],'w');
+    fprintf(fid,'%s',textReport);
+    fclose(fid);
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/06_ModelFitAnalysis/SBPOPfitanalysisProjectsFolderInfo.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/06_ModelFitAnalysis/SBPOPfitanalysisProjectsFolderInfo.m
new file mode 100644
index 0000000000000000000000000000000000000000..ff988509910327a74887aaadefc8176bdb81f5ae
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/06_ModelFitAnalysis/SBPOPfitanalysisProjectsFolderInfo.m
@@ -0,0 +1,655 @@
+function [RESULTS] = SBPOPfitanalysisProjectsFolderInfo(modelProjectsFolder,FitInfoOutputFolder)
+% [DESCRIPTION]
+% This function reads the fit result information of the NONMEM or MONOLIX fits in the 
+% specified folder. Each fit needs to be in an own folder,
+% following the standard that SBPOP uses. It generates several different
+% tables that allow to compare the different model fit results.
+%
+% This function is applicable for models with any number of outputs but it
+% only produces the results for one output at a time. The user needs to
+% provide the number of this output in the model in the variable
+% "outputNumber".
+% 
+% [SYNTAX]
+% [RESULTS] = SBPOPfitanalysisProjectsFolderInfo(modelProjectsFolder,FitInfoOutputFolder)
+%
+% [INPUT]
+% modelProjectsFolder:      Path to a folder with MONOLIX or NONMEM project folders
+%                           to generate the result tables for.
+% FitInfoOutputFolder:      Path to the folder in which to generate the output files
+%
+% [OUTPUT]
+% Text files in folder of interest.
+% RESULTS output argument contains information about all the fits for
+% postprocessing
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 9th May 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MODESIM, MATLAB R2009a
+%
+% [KEYWORDS]
+% MATLAB, SBPOP, dataexploration, datacleaning
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get the projects to run in the folder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+projects = dir([modelProjectsFolder '/*']);
+% Remove . and ..
+ix_dot = strmatchSB('.',{projects.name});
+projects(ix_dot) = [];
+% Remove files
+projects(find(~[projects.isdir])) = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create the output folder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+warning off; %#ok<*WNOFF>
+% try rmdir(FitInfoOutputFolder,'s'); catch, end; 
+mkdir(FitInfoOutputFolder);
+warning on; %#ok<*WNON>
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Read the estimation results
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+RESULTS = [];
+for k=1:length(projects),
+    try
+        if isMONOLIXfitSBPOP([modelProjectsFolder '/' projects(k).name]),
+            x = parseMONOLIXresultsSBPOP([modelProjectsFolder '/' projects(k).name]);
+            y = sampleMONOLIXpopulationParametersSBPOP(x,0,1);
+            RESULTS(k).NONMEM = 0;
+        elseif isNONMEMfitSBPOP([modelProjectsFolder '/' projects(k).name]),
+            % Do request back transformed parameter and standard error
+            % values for the rawparameters fixed effects and the
+            % parameters.values.
+            transformFlag = 1;
+            x = parseNONMEMresultsSBPOP([modelProjectsFolder '/' projects(k).name],transformFlag);
+            y = sampleNONMEMpopulationParametersSBPOP(x,0,1);
+            RESULTS(k).NONMEM = 1;
+        else
+            error('Unknown project type.');
+        end
+        
+        % Collect results
+        RESULTS(k).model                            = projects(k).name;
+        RESULTS(k).OBJ                              = x.objectivefunction.OBJ;
+        RESULTS(k).AIC                              = x.objectivefunction.AIC;
+        RESULTS(k).BIC                              = x.objectivefunction.BIC;
+        RESULTS(k).parameternames                   = x.parameters.names;
+        RESULTS(k).parametervalues                  = x.parameters.values;
+        RESULTS(k).stderrors                        = x.parameters.stderrors;
+        RESULTS(k).correlationmatrixRandomEffects   = y.randomEffects.correlationmatrix;
+        RESULTS(k).rawParameterInfo                 = x.rawParameterInfo;
+    catch
+        % It might happen that some model was not run ...
+        % Collect results
+        RESULTS(k).model                            = projects(k).name;
+        RESULTS(k).OBJ                              = NaN;
+        RESULTS(k).AIC                              = NaN;
+        RESULTS(k).BIC                              = NaN;
+        RESULTS(k).parameternames                   = {};
+        RESULTS(k).parametervalues                  = [];
+        RESULTS(k).stderrors                        = NaN;
+        RESULTS(k).correlationmatrixRandomEffects   = [];
+        RESULTS(k).rawParameterInfo                 = [];
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Sort the estimation results after the BIC
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ranking_var = sortrows([[1:length(projects)]' [RESULTS.BIC]'],2); %#ok<*NBRAK>
+RANKING = ranking_var(:,1);
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Process the RESULT information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine all available fixed effect parameters in the models
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ALLfixEffectNames = {};
+for k=1:length(RESULTS),
+    if ~isempty(RESULTS(k).rawParameterInfo),
+        fek = RESULTS(k).rawParameterInfo.fixedEffects.names;
+        ALLfixEffectNames = [ALLfixEffectNames setdiff(fek,ALLfixEffectNames)];
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine all available error model parameters in the models
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ALLerrorNames = {};
+for k=1:length(RESULTS),
+    if ~isempty(RESULTS(k).rawParameterInfo),
+        fek = RESULTS(k).rawParameterInfo.errorParameter.names;
+        ALLerrorNames = [ALLerrorNames setdiff(fek,ALLerrorNames)];
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get maximum length of projectnames
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+maxProjectNameLength = cellmaxlengthSBPOP({RESULTS.model});
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create the parameter information table
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Open file for writing it out
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fidInfo = fopen([FitInfoOutputFolder '/fitInfoParameters.txt'],'w');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Write out metrics table
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fidInfo,'===================================================================================================================================================================================================================================\n');
+fprintf(fidInfo,'MODEL%s   round(BIC)   NaN_RSE   maxRSE(fixedE)      maxRSE(randE)    max(randE)     maxRSE(corr)    max(|corr|)\n',char(32*ones(1,maxProjectNameLength-5)));
+fprintf(fidInfo,'===================================================================================================================================================================================================================================\n');
+for k=1:length(RESULTS),
+    ranked_k = RANKING(k);
+    
+    if ~isempty(RESULTS(ranked_k).rawParameterInfo),
+        maxfixedrse    = max(round(RESULTS(ranked_k).rawParameterInfo.fixedEffects.rse));
+        maxomegarse    = max(round(RESULTS(ranked_k).rawParameterInfo.randomEffects.rse));
+        maxomegaparval = max(RESULTS(ranked_k).rawParameterInfo.randomEffects.values);
+        maxcorrrse     = max(round(RESULTS(ranked_k).rawParameterInfo.correlation.rse));
+        maxcorrparval  = max(abs(RESULTS(ranked_k).rawParameterInfo.correlation.values));
+    else
+        maxfixedrse    = NaN;
+        maxomegarse    = NaN;
+        maxomegaparval = NaN;
+        maxcorrrse     = NaN;
+        maxcorrparval  = NaN;
+    end
+    zz = RESULTS(ranked_k).rawParameterInfo;
+    if ~isempty(zz),
+        NaN_RSE = sum(isnan([zz.fixedEffects.rse zz.randomEffects.rse zz.errorParameter.rse zz.covariate.rse zz.correlation.rse]).*...
+            [zz.fixedEffects.estimated zz.randomEffects.estimated zz.errorParameter.estimated zz.covariate.estimated zz.correlation.estimated]);
+    else
+        NaN_RSE = NaN;
+    end
+    
+    if isempty(maxcorrrse),
+        maxcorrrse     = '-';
+        maxcorrparval  = '-';
+    end
+    
+    fprintf(fidInfo,'%s%s      %s       %d      %8.3g           %8.3g           %s       %s          %s\n', ...
+        RESULTS(ranked_k).model, ...
+        char(32*ones(1,maxProjectNameLength-length(RESULTS(ranked_k).model))), ...
+        preFillCharSB(round(RESULTS(ranked_k).BIC),7,' ')   , ...
+        NaN_RSE, ...
+        round(maxfixedrse), ...
+        round(maxomegarse), ...
+        preFillCharSB(sprintf('%6.3g',maxomegaparval),5,' '), ...
+        preFillCharSB(maxcorrrse,6,' '), ...
+        preFillCharSB(maxcorrparval,5,' '));
+
+end
+fprintf(fidInfo,'\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Display FIXED EFFECTS VALUES and ERROR MODEL VALUES 
+% Estimated and non-estimated parameter values shown. 
+% Non-estimated get postfix (FIX).
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fidInfo,'===================================================================================================================================================================================================================================\n');
+fprintf(fidInfo,'Estimated FIXED EFFECT PARAMETERS and ERROR MODEL PARAMETERS\n');
+fprintf(fidInfo,'===================================================================================================================================================================================================================================\n');
+fprintf(fidInfo,'-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n');
+fprintf(fidInfo,'MODEL%s   round(BIC)',char(32*ones(1,maxProjectNameLength-5)));
+
+ALLNAMES = [ALLfixEffectNames ALLerrorNames];
+for k=1:length(ALLNAMES),
+    fprintf(fidInfo,'%s',preFillCharSB(ALLNAMES{k},16,' '));
+end
+fprintf(fidInfo,'\n');
+fprintf(fidInfo,'-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n');
+
+for k=1:length(RESULTS),
+    ranked_k = RANKING(k);
+    if ~isempty(RESULTS(ranked_k).rawParameterInfo),
+        % Get model specific parameter names and values
+        modelNAMES   = [RESULTS(ranked_k).rawParameterInfo.fixedEffects.names RESULTS(ranked_k).rawParameterInfo.errorParameter.names];
+        modelVALUES  = [RESULTS(ranked_k).rawParameterInfo.fixedEffects.values RESULTS(ranked_k).rawParameterInfo.errorParameter.values];
+modelESTIMATED  = [RESULTS(ranked_k).rawParameterInfo.fixedEffects.estimated RESULTS(ranked_k).rawParameterInfo.errorParameter.estimated];
+        
+        % Sort the parameter values into the correct location
+        allValues    = NaN(1,length(ALLNAMES));
+allEstimated = zeros(1,length(ALLNAMES));
+        for kx=1:length(modelNAMES),
+            ix              = strmatchSB(modelNAMES{kx},ALLNAMES,'exact');
+            allValues(ix)   = modelVALUES(kx);
+allEstimated(ix) = modelESTIMATED(kx);            
+        end
+        
+        % Print headline with parameter names
+        fprintf(fidInfo,'%s%s      %s', ...
+            RESULTS(ranked_k).model, ...
+            char(32*ones(1,maxProjectNameLength-length(RESULTS(ranked_k).model))), ...
+            preFillCharSB(round(RESULTS(ranked_k).BIC),7,' '));
+        
+        % Print fixed effect parameter values, except if it is NaN ... since then the parameter is not in the model.
+        for k2=1:length(ALLNAMES),
+if allEstimated(k2),
+                fprintf(fidInfo,'%16.3g',allValues(k2));
+else
+                if ~isnan(allValues(k2)),
+                    fprintf(fidInfo,'%10.3g (FIX)',allValues(k2));
+                else
+                    fprintf(fidInfo,'               -');
+                end
+            end
+            
+        end
+        fprintf(fidInfo,'\n');
+    end
+end
+fprintf(fidInfo,'\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Display FIXED EFFECTS REL STDERRORS and ERROR MODEL PARAMETERS
+% If not estimated then - otherwise value and if fixed then (FIX)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fidInfo,'===================================================================================================================================================================================================================================\n');
+fprintf(fidInfo,'RELATIVE STANDARD ERRORS of estimated FIXED EFFECT PARAMETERS and ERROR MODEL PARAMETERS (IN PERCENT)\n');
+fprintf(fidInfo,'Standard errors for fixed effects approximated by sampling - since MU referencing used.\n');
+fprintf(fidInfo,'===================================================================================================================================================================================================================================\n');
+fprintf(fidInfo,'-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n');
+fprintf(fidInfo,'MODEL%s   round(BIC)',char(32*ones(1,maxProjectNameLength-5)));
+
+ALLNAMES = [ALLfixEffectNames ALLerrorNames];
+for k=1:length(ALLNAMES),
+    fprintf(fidInfo,'%s',preFillCharSB(['rse(' ALLNAMES{k} ')'],16,' '));
+end
+fprintf(fidInfo,'\n');
+fprintf(fidInfo,'-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n');
+
+for k=1:length(RESULTS),
+    ranked_k = RANKING(k);
+    if ~isempty(RESULTS(ranked_k).rawParameterInfo),
+        % Get model specific parameter names and values
+        modelNAMES   = [RESULTS(ranked_k).rawParameterInfo.fixedEffects.names RESULTS(ranked_k).rawParameterInfo.errorParameter.names];
+        modelVALUES  = [RESULTS(ranked_k).rawParameterInfo.fixedEffects.rse RESULTS(ranked_k).rawParameterInfo.errorParameter.rse];
+modelESTIMATED  = [RESULTS(ranked_k).rawParameterInfo.fixedEffects.estimated RESULTS(ranked_k).rawParameterInfo.errorParameter.estimated];
+        
+        % Sort the parameter values into the correct location
+        allValues    = NaN(1,length(ALLNAMES));
+allEstimated = zeros(1,length(ALLNAMES));
+        for kx=1:length(modelNAMES),
+            ix              = strmatchSB(modelNAMES{kx},ALLNAMES,'exact');
+            allValues(ix)   = modelVALUES(kx);
+allEstimated(ix) = modelESTIMATED(kx);            
+        end
+
+        % Print headline with parameter names
+        fprintf(fidInfo,'%s%s      %s', ...
+            RESULTS(ranked_k).model, ...
+            char(32*ones(1,maxProjectNameLength-length(RESULTS(ranked_k).model))), ...
+            preFillCharSB(round(RESULTS(ranked_k).BIC),7,' '));
+        
+        % Print fixed effect parameter values 
+        for k2=1:length(ALLNAMES),
+if allEstimated(k2),
+                fprintf(fidInfo,'%16.3g',allValues(k2));
+            else
+                fprintf(fidInfo,'               -');
+            end
+            
+        end
+        fprintf(fidInfo,'\n');
+    end
+end
+fprintf(fidInfo,'\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Display RANDOM EFFECTS VALUES 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fidInfo,'===================================================================================================================================================================================================================================\n');
+fprintf(fidInfo,'Estimated RANDOM EFFECT PARAMETERS\n');
+fprintf(fidInfo,'===================================================================================================================================================================================================================================\n');
+fprintf(fidInfo,'-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n');
+fprintf(fidInfo,'MODEL%s   round(BIC)',char(32*ones(1,maxProjectNameLength-5)));
+for k=1:length(ALLfixEffectNames),
+    fprintf(fidInfo,'%s',preFillCharSB(['om(' ALLfixEffectNames{k} ')'],16,' '));
+end
+fprintf(fidInfo,'\n');
+fprintf(fidInfo,'-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n');
+
+for k=1:length(RESULTS),
+    ranked_k = RANKING(k);
+    if ~isempty(RESULTS(ranked_k).rawParameterInfo),
+        % Get model specific parameter names and values
+        modelNAMES   = RESULTS(ranked_k).rawParameterInfo.fixedEffects.names;    % Needs to be fixed effect names
+        modelVALUES  = RESULTS(ranked_k).rawParameterInfo.randomEffects.values;  % Needs to be random effect values
+modelESTIMATED  = RESULTS(ranked_k).rawParameterInfo.randomEffects.estimated;
+        
+        % Sort the parameter values into the correct location
+        allValues    = NaN(1,length(ALLfixEffectNames));
+allEstimated = zeros(1,length(ALLNAMES));            
+        for kx=1:length(modelNAMES),
+            ix              = strmatchSB(modelNAMES{kx},ALLfixEffectNames,'exact');
+            allValues(ix)   = modelVALUES(kx);
+allEstimated(ix) = modelESTIMATED(kx);            
+        end
+
+        % Print headline with parameter names
+        fprintf(fidInfo,'%s%s      %s', ...
+            RESULTS(ranked_k).model, ...
+            char(32*ones(1,maxProjectNameLength-length(RESULTS(ranked_k).model))), ...
+            preFillCharSB(round(RESULTS(ranked_k).BIC),7,' '));
+        
+        % Print fixed effect parameter values 
+        for k2=1:length(ALLfixEffectNames),
+if allEstimated(k2) == 1,
+                fprintf(fidInfo,'%16.3g',allValues(k2));
+elseif allEstimated(k2) == 2,
+                fprintf(fidInfo,'%10.3g (FIX)',allValues(k2));
+            else
+                fprintf(fidInfo,'               -');
+            end
+            
+        end
+        fprintf(fidInfo,'\n');
+    end
+end
+fprintf(fidInfo,'\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Display RANDOM EFFECTS REL STDERRORS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fidInfo,'===================================================================================================================================================================================================================================\n');
+fprintf(fidInfo,'RELATIVE STANDARD ERRORS of estimated RANDOM EFFECT PARAMETERS (IN PERCENT)\n');
+fprintf(fidInfo,'===================================================================================================================================================================================================================================\n');
+fprintf(fidInfo,'-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n');
+fprintf(fidInfo,'MODEL%s   round(BIC)',char(32*ones(1,maxProjectNameLength-5)));
+for k=1:length(ALLfixEffectNames),
+    fprintf(fidInfo,'%s',preFillCharSB(['rseom(' ALLfixEffectNames{k} ')'],16,' '));
+end
+fprintf(fidInfo,'\n');
+fprintf(fidInfo,'-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n');
+
+for k=1:length(RESULTS),
+    ranked_k = RANKING(k);
+    if ~isempty(RESULTS(ranked_k).rawParameterInfo),
+        % Get model specific parameter names and values
+        modelNAMES   = RESULTS(ranked_k).rawParameterInfo.fixedEffects.names;    % Needs to be fixed effect names
+        modelVALUES  = RESULTS(ranked_k).rawParameterInfo.randomEffects.rse;     % Needs to be random effect values
+modelESTIMATED  = RESULTS(ranked_k).rawParameterInfo.randomEffects.estimated;
+        
+        % Sort the parameter values into the correct location
+        allValues    = NaN(1,length(ALLfixEffectNames));
+allEstimated = zeros(1,length(ALLNAMES));
+        for kx=1:length(modelNAMES),
+            ix              = strmatchSB(modelNAMES{kx},ALLfixEffectNames,'exact');
+            allValues(ix)   = modelVALUES(kx);
+allEstimated(ix) = modelESTIMATED(kx);            
+        end
+
+        % Print headline with parameter names
+        fprintf(fidInfo,'%s%s      %s', ...
+            RESULTS(ranked_k).model, ...
+            char(32*ones(1,maxProjectNameLength-length(RESULTS(ranked_k).model))), ...
+            preFillCharSB(round(RESULTS(ranked_k).BIC),7,' '));
+        
+        % Print fixed effect parameter values 
+        for k2=1:length(ALLfixEffectNames),
+if allEstimated(k2)==1,
+                fprintf(fidInfo,'%16.3g',allValues(k2));
+            else
+                fprintf(fidInfo,'               -');
+            end
+            
+        end
+        fprintf(fidInfo,'\n');
+    end
+end
+fprintf(fidInfo,'\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Close file and display results in command window
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fclose(fidInfo);
+disp(fileread([FitInfoOutputFolder '/fitInfoParameters.txt']));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create the covariance information table
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Open file for writing it out
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fidInfo = fopen([FitInfoOutputFolder '/fitInfoCovariances.txt'],'w');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Write out metrics table
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fidInfo,'===================================================================================================================================================================================================================================\n');
+fprintf(fidInfo,'MODEL%s   round(BIC)   NaN_RSE   maxRSE(fixedE)      maxRSE(randE)    max(randE)     maxRSE(corr)    max(|corr|)\n',char(32*ones(1,maxProjectNameLength-5)));
+fprintf(fidInfo,'===================================================================================================================================================================================================================================\n');
+for k=1:length(RESULTS),
+    ranked_k = RANKING(k);
+    
+    if ~isempty(RESULTS(ranked_k).rawParameterInfo),
+        maxfixedrse    = max(round(RESULTS(ranked_k).rawParameterInfo.fixedEffects.rse));
+        maxomegarse    = max(round(RESULTS(ranked_k).rawParameterInfo.randomEffects.rse));
+        maxomegaparval = max(RESULTS(ranked_k).rawParameterInfo.randomEffects.values);
+        maxcorrrse     = max(round(RESULTS(ranked_k).rawParameterInfo.correlation.rse));
+        maxcorrparval  = max(abs(RESULTS(ranked_k).rawParameterInfo.correlation.values));
+    else
+        maxfixedrse    = NaN;
+        maxomegarse    = NaN;
+        maxomegaparval = NaN;
+        maxcorrrse     = NaN;
+        maxcorrparval  = NaN;
+    end
+    zz = RESULTS(ranked_k).rawParameterInfo;
+    if ~isempty(zz),
+        NaN_RSE = sum(isnan([zz.fixedEffects.rse zz.randomEffects.rse zz.errorParameter.rse zz.covariate.rse zz.correlation.rse]).*...
+            [zz.fixedEffects.estimated zz.randomEffects.estimated zz.errorParameter.estimated zz.covariate.estimated zz.correlation.estimated]);
+    else
+        NaN_RSE = NaN;
+    end
+    
+    if isempty(maxcorrrse),
+        maxcorrrse     = '-';
+        maxcorrparval  = '-';
+    end
+    
+    fprintf(fidInfo,'%s%s      %s       %d      %8.3g           %8.3g           %s       %s          %s\n', ...
+        RESULTS(ranked_k).model, ...
+        char(32*ones(1,maxProjectNameLength-length(RESULTS(ranked_k).model))), ...
+        preFillCharSB(round(RESULTS(ranked_k).BIC),7,' ')   , ...
+        NaN_RSE, ...
+        round(maxfixedrse), ...
+        round(maxomegarse), ...
+        preFillCharSB(sprintf('%6.3g',maxomegaparval),5,' '), ...
+        preFillCharSB(maxcorrrse,6,' '), ...
+        preFillCharSB(maxcorrparval,5,' '));
+
+end
+fprintf(fidInfo,'\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Display covariance/correlation matrices
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fidInfo,'==================================================================================================================================================================================================================================\n'); 
+fprintf(fidInfo,'MODEL               round(BIC)       Covariance setting\n') ;
+fprintf(fidInfo,'-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n');
+fprintf(fidInfo,'       Correlation matrices for all fits\n') ;
+fprintf(fidInfo,'==================================================================================================================================================================================================================================\n'); 
+fprintf(fidInfo,'\n') ;
+for k=1:length(RESULTS),
+    ranked_k = RANKING(k);
+    if ~isempty(RESULTS(ranked_k).rawParameterInfo),
+        xparam = sprintf('%s,',RESULTS(ranked_k).rawParameterInfo.fixedEffects.names{:});
+        fprintf(fidInfo,'%s         %g     (%s)\n', ...
+            RESULTS(ranked_k).model, ...
+            round(RESULTS(ranked_k).BIC), ...
+            xparam(1:end-1));
+        fprintf(fidInfo,'-----------------------------------------------------\n');
+        
+        corrmatrix = RESULTS(ranked_k).correlationmatrixRandomEffects;
+        if max(max(abs(corrmatrix-eye(size(corrmatrix))))) > eps,
+            for k2=1:size(corrmatrix,1),
+                row = corrmatrix(k2,:);
+                fprintf(fidInfo,'%8.5g',row);
+                fprintf(fidInfo,'\n');
+            end
+        else
+            fprintf(fidInfo,'Diagonal covariance matrix only\n');
+        end
+        fprintf(fidInfo,'\n');
+    end
+end
+fprintf(fidInfo,'\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Close file and display results in command window
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fclose(fidInfo);
+disp(fileread([FitInfoOutputFolder '/fitInfoCovariances.txt']));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create the covariate information table
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Open file for writing it out
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fidInfo = fopen([FitInfoOutputFolder '/fitInfoCovariates.txt'],'w');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Write out metrics table
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fidInfo,'===================================================================================================================================================================================================================================\n');
+fprintf(fidInfo,'MODEL%s   round(BIC)   NaN_RSE   maxRSE(fixedE)      maxRSE(randE)    max(randE)     maxRSE(corr)    max(|corr|)\n',char(32*ones(1,maxProjectNameLength-5)));
+fprintf(fidInfo,'===================================================================================================================================================================================================================================\n');
+for k=1:length(RESULTS),
+    ranked_k = RANKING(k);
+    
+    if ~isempty(RESULTS(ranked_k).rawParameterInfo),
+        maxfixedrse    = max(round(RESULTS(ranked_k).rawParameterInfo.fixedEffects.rse));
+        maxomegarse    = max(round(RESULTS(ranked_k).rawParameterInfo.randomEffects.rse));
+        maxomegaparval = max(RESULTS(ranked_k).rawParameterInfo.randomEffects.values);
+        maxcorrrse     = max(round(RESULTS(ranked_k).rawParameterInfo.correlation.rse));
+        maxcorrparval  = max(abs(RESULTS(ranked_k).rawParameterInfo.correlation.values));
+    else
+        maxfixedrse    = NaN;
+        maxomegarse    = NaN;
+        maxomegaparval = NaN;
+        maxcorrrse     = NaN;
+        maxcorrparval  = NaN;
+    end
+    zz = RESULTS(ranked_k).rawParameterInfo;
+    if ~isempty(zz),
+        NaN_RSE = sum(isnan([zz.fixedEffects.rse zz.randomEffects.rse zz.errorParameter.rse zz.covariate.rse zz.correlation.rse]).*...
+            [zz.fixedEffects.estimated zz.randomEffects.estimated zz.errorParameter.estimated zz.covariate.estimated zz.correlation.estimated]);
+    else
+        NaN_RSE = NaN;
+    end
+    
+    if isempty(maxcorrrse),
+        maxcorrrse     = '-';
+        maxcorrparval  = '-';
+    end
+    
+    fprintf(fidInfo,'%s%s      %s       %d      %8.3g           %8.3g           %s       %s          %s\n', ...
+        RESULTS(ranked_k).model, ...
+        char(32*ones(1,maxProjectNameLength-length(RESULTS(ranked_k).model))), ...
+        preFillCharSB(round(RESULTS(ranked_k).BIC),7,' ')   , ...
+        NaN_RSE, ...
+        round(maxfixedrse), ...
+        round(maxomegarse), ...
+        preFillCharSB(sprintf('%6.3g',maxomegaparval),5,' '), ...
+        preFillCharSB(maxcorrrse,6,' '), ...
+        preFillCharSB(maxcorrparval,5,' '));
+
+end
+fprintf(fidInfo,'\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Display covariate information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fidInfo,'==================================================================================================================================================================================================================================\n'); 
+fprintf(fidInfo,'MODEL               round(BIC)       Covariate setting\n') ;
+fprintf(fidInfo,'==================================================================================================================================================================================================================================\n'); 
+fprintf(fidInfo,'\n') ;
+for k=1:length(RESULTS),
+    ranked_k = RANKING(k);
+    fprintf(fidInfo,'%s         Value         95%% confidence interval\n', ...
+        RESULTS(ranked_k).model);
+    fprintf(fidInfo,'-------------------------------------------------------------------------\n');
+
+    if ~isempty(RESULTS(ranked_k).rawParameterInfo),
+        if ~isempty(RESULTS(ranked_k).rawParameterInfo.covariate.names),
+            info = RESULTS(ranked_k).rawParameterInfo.covariate;
+            for k2=1:length(info.names),
+                covName   = info.names{k2};
+                covValue  = info.values(k2);
+                covSTDERR = info.stderr(k2);
+                alpha = 0.05;
+                nFoldStdDev = norminv(1-alpha/2,0,1);
+                covValueDn  = round(1000*(covValue-nFoldStdDev*covSTDERR))/1000;
+                covValueUp  = round(1000*(covValue+nFoldStdDev*covSTDERR))/1000;
+                if covValueDn*covValueUp > 0,
+                    signResult = 'X';
+                else
+                    signResult = '';
+                end
+                fprintf(fidInfo,'%s          %s         [%s,%s] %s\n', ...
+                    preFillCharSB(covName,20,' '), ...
+                    preFillCharSB(covValue,8,' '), ...
+                    preFillCharSB(covValueDn,8,' '), ...
+                    preFillCharSB(covValueUp,8,' '), ...
+                    signResult);
+            end
+        else
+            fprintf(fidInfo,'No covariates estimated\n');
+        end
+    else
+        fprintf(fidInfo,'Fit produced no output - if you want, run this fit manually to see why.\n');
+    end
+    fprintf(fidInfo,'\n');
+end
+fprintf(fidInfo,'\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Close file and display results in command window
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fclose(fidInfo);
+disp(fileread([FitInfoOutputFolder '/fitInfoCovariates.txt']));
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/06_ModelFitAnalysis/SBPOPfitanalysisProjectsFolderPlots.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/06_ModelFitAnalysis/SBPOPfitanalysisProjectsFolderPlots.m
new file mode 100644
index 0000000000000000000000000000000000000000..98fc6ee226aa0327ba6cc33a61336e24466efc23
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/06_ModelFitAnalysis/SBPOPfitanalysisProjectsFolderPlots.m
@@ -0,0 +1,109 @@
+function [] = SBPOPfitanalysisProjectsFolderPlots(outputNumber,modelProjectsFolder,analysisDatasetFile,covNames,catNames,FitanalysisPlotsFolder)
+% [DESCRIPTION]
+% This function is a wrapper for SBPOPfitanalysisGeneral and produces fit
+% analysis assessments for all MONOLIX or NONMEM projects within a specified folder.
+% The different plots produced are done using the following functions:
+% - SBPOPfitanalysisIndividualFits
+% - SBPOPfitanalysisGOFplots
+% - SBPOPfitanalysisRandomEffects
+% - SBPOPfitanalysisETAvsCOV
+% - SBPOPfitanalysisOutlierDetection
+%
+% The SBPOP standard clinical data structure is assumed and checked.
+%
+% This function is applicable for models with any number of outputs but it
+% only produces the results for one output at a time. The user needs to
+% provide the number of this output in the model in the variable
+% "outputNumber".
+% 
+% [SYNTAX]
+% [] = SBPOPfitanalysisProjectsFolderPlots(outputNumber,modelProjectsFolder,analysisDatasetFile,covNames,catNames,FitanalysisPlotsFolder)
+%
+% [INPUT]
+% outputNumber:             Number of the output in the model to generate the plots for
+% modelProjectsFolder:      Path to a folder with NONMEM or MONOLIX project folders
+%                           to generate the fit analysis results for.
+% analysisDatasetFile:      Path to the analysis datafile that has been used for
+%                           the modeling. All model runs need to have used the same
+%                           analysis dataset!
+% covNames:                 Cell-array with names of continuous covariates
+% catNames:                 Cell-array with names of categorical covariates
+% FitanalysisPlotsFolder:   Path to the folder in which to generate the output files
+%
+% [OUTPUT]
+% PS (Windows) or PDF (Unix) files with the relevant fit analysis results
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 9th May 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MODESIM, MATLAB R2009a
+%
+% [KEYWORDS]
+% MATLAB, SBPOP, dataexploration, datacleaning
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get the projects to run in the folder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+projects = dir([modelProjectsFolder '/*']);
+% Remove . and ..
+ix_dot = strmatchSB('.',{projects.name});
+projects(ix_dot) = [];
+% Remove files
+projects(find(~[projects.isdir])) = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Load the data used for analysis
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+datacontents = SBPOPloadCSVdataset(analysisDatasetFile);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Clean the output folder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+warning off; %#ok<*WNOFF>
+try rmdir(FitanalysisPlotsFolder,'s'); catch, end; mkdir(FitanalysisPlotsFolder);
+warning on; %#ok<*WNON>
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Do the fit analysis plots - use parfor to allow for parallel generation
+% of the results if parallel toolbox available
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+parfor k=1:length(projects),
+    try
+        k
+        projectPath = [modelProjectsFolder '/' projects(k).name];
+        optionsFA = [];
+        optionsFA.basefilename = [FitanalysisPlotsFolder '/' projects(k).name '_'];
+        SBPOPfitanalysisGeneralPlots(outputNumber,datacontents,projectPath,covNames,catNames,optionsFA);
+    catch
+    end
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/06_ModelFitAnalysis/SBPOPfitanalysisRandomEffects.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/06_ModelFitAnalysis/SBPOPfitanalysisRandomEffects.m
new file mode 100644
index 0000000000000000000000000000000000000000..d322b39900c6101548883f4cb037ca4285deecbc
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/06_ModelFitAnalysis/SBPOPfitanalysisRandomEffects.m
@@ -0,0 +1,172 @@
+function [] = SBPOPfitanalysisRandomEffects(projectPath,options)
+% [DESCRIPTION]
+% This function plots information about the random effects in different
+% ways. Whiskers on the boxplots indicate the 5th and 95th percentile of the plotted data.
+%
+% [SYNTAX]
+% [] = SBPOPfitanalysisRandomEffects(projectPath)
+% [] = SBPOPfitanalysisRandomEffects(projectPath,options)
+%
+% [INPUT]
+% projectPath:  Path to a Monolix project folder. The results of the
+%               Monolix run need to be stored in a "RESULTS" folder in this
+%               path. The file "indiv_eta.txt" needs to be present in
+%               this RESULTS folder.
+% options:      MATLAB structure with plotting optins:
+%                   
+%                   options.filename:   If a filename is provided, then the results are exported
+%                                       into a postscript (windows) or PDf (unix) document with this name.
+%
+% [OUTPUT]
+% Plots or PDF/PS file
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 16th April 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MATLAB R2009a, MATLAB
+%
+% [KEYWORDS]
+% MATLAB, SBPOP, DV, PRED, IPRED, diagnostic, plot, individual fits
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try filename     = options.filename;        catch, filename = '';       end
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% If filename then remove old file
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(filename),
+    startNewPrintFigureSBPOP(filename);
+    % also create path if not yet created
+    [p,f,e] = fileparts(filename);
+    warning off
+    mkdir(p);
+    warning on
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle NONMEM/MONOLIX
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isMONOLIXfitSBPOP(projectPath),
+    [ dataeta, OMEGA, OMEGAnames ] = parseMONOLIXetasSBPOP( projectPath );
+elseif isNONMEMfitSBPOP(projectPath),
+    [ dataeta, OMEGA, OMEGAnames ] = parseNONMEMetasSBPOP( projectPath );
+else
+    error('Unknown project type.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine shrinkaqge in percent
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+eta_shrinkage_percent = 100*(1-std(double(dataeta))./OMEGA);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Remove the NaNs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ix = find(~isnan(eta_shrinkage_percent));
+OMEGA_est                   = OMEGA(ix);
+OMEGAnames_est              = OMEGAnames(ix);
+dataeta_est                 = dataeta(:,ix);
+eta_shrinkage_percent_est   = eta_shrinkage_percent(ix);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Plot the etas and the shrinkage
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+figure;
+Netas = length(OMEGAnames_est);
+Nrows = ceil(sqrt(Netas));
+Ncols = ceil(Netas/Nrows);
+for k2=1:Netas,
+    subplot(Nrows,Ncols,k2);
+    % Plot histogram
+    [N,X] = hist(double(dataeta_est(:,k2)));
+    bar(X,N/max(N),'FaceColor',0.5*[1 1 1]); hold on
+    % Adjust X-axis to some reasonable setting
+    axis([-5*OMEGA_est(k2) 5*OMEGA_est(k2) get(gca,'YLim')]);
+    % Plot gaussian with estimated population std
+    XLim = get(gca,'XLim');
+    x = linspace(XLim(1),XLim(2),100);
+    y = normpdf(x,0,OMEGA_est(k2));
+    plot(x,y./max(y),'Color',[0.7 0 0],'LineWidth',2);
+    % Axes
+    title(sprintf('eta_%s',OMEGAnames_est{k2}),'FontSize',14,'Interpreter','none')
+    set(gca,'FontSize',12);
+    if k2==1,
+        legend('Individual ETAs','Population distribution');
+    end
+    % Print the shrinkage
+    text(XLim(1)+(XLim(2)-XLim(1))*0.05,0.75,sprintf('Shrinkage: %1.2g%%',eta_shrinkage_percent_est(k2)),'FontSize',12,'FontWeight','bold');
+end
+set(gcf,'Color',[1 1 1]);
+if ~isempty(filename),
+    printFigureSBPOP(gcf,filename);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Boxplot for random effects
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+figure
+% Use 5th and 95th percentile for plotting the whiskers on the boxplot
+SBPOPboxplot([5 95],0,double(dataeta_est),'labels',strcat('eta_',OMEGAnames_est),'Colors',0.4*[1 1 1],'jitter',0.5); hold on;
+set(gcf,'Color',[1 1 1]);
+plot(get(gca,'XLim'),[0 0],'k-');
+title('Random Effects - Boxplot','FontSize',12,'Interpreter','none');
+
+grid on;
+if ~isempty(filename),
+    printFigureSBPOP(gcf,filename);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Joint distribution of random effects
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+figure
+options = [];
+options.names = {};
+for k=1:length(OMEGAnames_est),
+    options.names{k} = ['eta_' OMEGAnames_est{k}];
+end
+SBPOPplotpairwiseCorr(dataeta_est,options)
+set(gcf,'Color',[1 1 1]);
+if ~isempty(filename),
+    printFigureSBPOP(gcf,filename);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PS2PDF
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(filename),
+    convert2pdfSBPOP(filename);
+    close all;
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/07_CovariateAssessment/SBPOPcovariateAssessmentUncertainty.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/07_CovariateAssessment/SBPOPcovariateAssessmentUncertainty.m
new file mode 100644
index 0000000000000000000000000000000000000000..36898a27cdef0d508de34c773996a95434589b96
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/07_CovariateAssessment/SBPOPcovariateAssessmentUncertainty.m
@@ -0,0 +1,515 @@
+function [] = SBPOPcovariateAssessmentUncertainty(pathNLMEproject,analysisDataset,options)
+% [DESCRIPTION]
+% This function assesses the changes that a covariates introduces on the
+% model parameters, relative to a reference individual. Uncertainty in the
+% estimated fixed effect parameters and covariate coefficients is
+% considered.
+%
+% Per model parameter that is changed by covariates, one plot is done.
+% Showing the uncertainty range for the parameter and the impact of the
+% covariates on this parameter. The horizontal lines correspond to the 95%
+% confidence intervals.
+%
+% [SYNTAX]
+% [] = SBPOPcovariateAssessmentUncertainty(pathNLMEproject,analysisDataset)
+% [] = SBPOPcovariateAssessmentUncertainty(pathNLMEproject,analysisDataset,options)
+%
+% [INPUT]
+% pathNLMEproject:   Relative path to the NONMEM or MONOLIX project
+%                                   folder for which to assess the
+%                                   covariates.
+% analysisDataset:                  Matlab dataset with analysis data - or
+%                                   relative path including filename to the
+%                                   analysis dataset which was used to fit
+%                                   the model.
+% options:     Matlab structure with optional information
+%       options.filename:           output filename with path (default: '')
+%       options.Nsamples:           How many samples should be taken from
+%                                   the uncertainty distributions. This
+%                                   number should be much larger than the
+%                                   number of individuals in the analysis
+%                                   dataset, so the covariate information
+%                                   in the dataset is well sampled.
+%                                   (default: 100000)
+%       options.ClinicalRelevanceFactor: Used to plot a grey box around the
+%                                   nominal value "1" - can be used to
+%                                   assess clinical relevance - or just for
+%                                   quick visual assessment of potential
+%                                   relevance (default: 0.2 (20%))
+%
+% [OUTPUT]
+% Output of one figure per parameter.
+% If filename specified, then output written to file as PS (windows) or PDF
+% (unix).
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 9th March, 2013
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+% Handle optional arguments
+try filename = options.filename; catch, filename = ''; end
+try ClinicalRelevanceFactor = options.ClinicalRelevanceFactor; catch, ClinicalRelevanceFactor=0.2; end
+try Nsamples = options.Nsamples; catch, Nsamples = 100000; end
+
+%% Handle analysis dataset input argument
+if ischar(analysisDataset),
+    % Load dataset
+    data = SBPOPloadCSVdataset(analysisDataset);
+elseif isa(analysisDataset,'dataset'),
+    data = analysisDataset;
+else
+    error('Incorrect input for "analysisDataset" argument.');
+end
+    
+%% Load info from NLME fit to get covariate information
+if isMONOLIXfitSBPOP(pathNLMEproject),
+    x = parseMONOLIXresultsSBPOP(pathNLMEproject);
+    % Remove the non-estimated covariates
+    ix_remove = find(x.rawParameterInfo.covariate.estimated == 0);
+    x.rawParameterInfo.covariate.estimated(ix_remove) = [];
+    x.rawParameterInfo.covariate.names(ix_remove) = [];
+    x.rawParameterInfo.covariate.rse(ix_remove) = [];
+    x.rawParameterInfo.covariate.stderr(ix_remove) = [];
+    x.rawParameterInfo.covariate.values(ix_remove) = [];    
+    y = sampleMONOLIXpopulationParametersSBPOP(x,0,0);
+elseif isNONMEMfitSBPOP(pathNLMEproject),
+    transformFLAG = 1;
+    x = parseNONMEMresultsSBPOP(pathNLMEproject,transformFLAG);
+    % Remove the non-estimated covariates
+    ix_remove = find(x.rawParameterInfo.covariate.estimated == 0);
+    x.rawParameterInfo.covariate.estimated(ix_remove) = [];
+    x.rawParameterInfo.covariate.names(ix_remove) = [];
+    x.rawParameterInfo.covariate.rse(ix_remove) = [];
+    x.rawParameterInfo.covariate.stderr(ix_remove) = [];
+    x.rawParameterInfo.covariate.values(ix_remove) = [];
+    y = sampleNONMEMpopulationParametersSBPOP(x,0,0);
+else
+    error('Unknown project type.');
+end
+
+%% Get covariate estimates and standard errors to compute the 5%/95% CI
+info = x.rawParameterInfo.covariate;
+covariateInfo = [];
+covariateInfo.Names             = {};
+covariateInfo.ParameterName     = {};
+covariateInfo.CovariateName     = {};
+covariateInfo.betaValue         = []; 
+covariateInfo.betaStderror      = []; 
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handling MONOLIX crap changes from version to version ...
+% This time ... from 4.3.2 to 4.3.3
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(y.covariates.categorical),
+    for k2=1:length(y.covariates.categorical(k).covariates),
+        name   = y.covariates.categorical(k).covariates{k2};
+        values = y.covariates.categorical(k).information(k2).categories;
+        for k3=1:length(values),
+            old = [name num2str(values(k3))];
+            new = [name '_' num2str(values(k3))];
+            info.names = strrep(info.names,old,new);
+        end
+    end
+end
+  
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle issue in Monolix 4.3.2 and 4.3.3
+% Unfortunately the Monolix developers come up with different ideas version to version again ...
+% ... and typically it does not really make sense ... anyway!
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(info.names),
+    % Handle issues in Monolix 4.3.2 and 4.3.3 ... if no "(" present
+    if isempty(strfind(info.names{k},'(')),
+        ix = strfind(info.names{k},'_');
+        info.names{k}(ix(end-1)) = '(';
+        info.names{k}(end+1) = ')';
+    end
+end
+
+for k2=1:length(info.names),
+    % Get parametername and covariate name for the parameter estimate
+    xx = strrep(info.names{k2},'beta_','');
+    xx = strrep(xx,'t_','');
+    xx = strrep(xx,')','');
+    xx = explodePCSB(xx,'(','#','$');
+    covariateInfo.Names{k2}             = info.names{k2};
+    covariateInfo.ParameterName{k2}     = xx{1};
+    covariateInfo.CovariateName{k2}     = xx{2};
+    covariateInfo.betaValue(k2)         = info.values(k2);
+    covariateInfo.betaStderror(k2)      = info.stderr(k2);
+end
+                
+%% Get parameter names and values
+parameterInfo           = [];
+parameterInfo.Names     = x.rawParameterInfo.fixedEffects.names;
+parameterInfo.Values    = x.rawParameterInfo.fixedEffects.values;
+parameterInfo.Stderror  = x.rawParameterInfo.fixedEffects.stderr;
+
+% Handle issue in Monolix 4.3.2
+parameterInfo.Names     = regexprep(parameterInfo.Names,'_pop\>','');
+
+%% Get expanded and matched THETA values
+covariateInfo.ParameterValues = [];
+for k=1:length(covariateInfo.ParameterName),
+    ix = strmatchSB(covariateInfo.ParameterName{k},parameterInfo.Names,'exact');
+    covariateInfo.ParameterValues(k) = parameterInfo.Values(ix);
+    covariateInfo.ParameterStderror(k) = parameterInfo.Stderror(ix);
+end
+
+%% Determine the covariates names
+covNames = {};
+for k=1:length(y.covariates.continuous),
+	covNames = [covNames y.covariates.continuous(k).covariates];
+end
+covNames = unique(covNames);
+catNames = {};
+for k=1:length(y.covariates.categorical),
+	catNames = [catNames y.covariates.categorical(k).covariates];
+end
+catNames = unique(catNames);
+
+%% Get info vector defining cov or cat
+covariateInfo.TypeCov = [];
+for k=1:length(covariateInfo.CovariateName),
+    ix = strmatchSB(covariateInfo.CovariateName{k},covNames,'exact');
+    if ~isempty(ix),
+        covariateInfo.TypeCov(k) = 1;
+    else
+        covariateInfo.TypeCov(k) = 0;
+    end
+end
+
+%% Get transformation functions for parameters
+covariateInfo.IndivTransF = {};
+covariateInfo.IndivTransFinv = {};
+for k=1:length(covariateInfo.ParameterName),
+    ix = strmatchSB(covariateInfo.ParameterName{k},y.randomEffects.names,'exact');
+    covariateInfo.IndivTransF{k} = y.randomEffects.transformation{ix};
+    covariateInfo.IndivTransFinv{k} = y.randomEffects.inv_transformation{ix};
+end
+
+%% Get transformation functions for covariates
+covariateInfo.COVtrans = {};
+aaa = [y.covariates.continuous.covariates];
+bbb = [y.covariates.continuous.transformation];
+for k=1:length(covariateInfo.CovariateName),
+    if covariateInfo.TypeCov(k) == 0,
+        % Categorical
+        covariateInfo.COVtrans{k} = [];
+    else
+        % Continuous
+        ix = strmatch(covariateInfo.CovariateName{k},aaa,'exact');
+        covariateInfo.COVtrans{k} = bbb{ix(1)}.formula;
+    end
+end
+
+%% Get info from dataset about continuous and categorical covariates
+allID = unique(data.ID);
+covValuesALL = [];
+catValuesALL = [];
+for k=1:length(allID),
+    datak = data(data.ID==allID(k),:);
+    row = datak(1,:);
+    covValuesRow = [];
+    for k2=1:length(covNames),
+        covValuesRow(k2) = row.(covNames{k2});
+    end
+    covValuesALL = [covValuesALL; covValuesRow];
+    catValuesRow = [];
+    for k2=1:length(catNames),
+        catValuesRow(k2) = row.(catNames{k2});
+    end
+    catValuesALL = [catValuesALL; catValuesRow];
+end
+
+%% Get info about the 5 and 95% quantiles of the continuous covariates
+quantileCOV_05 = quantile(covValuesALL,0.05);
+quantileCOV_95 = quantile(covValuesALL,0.95);
+covariateInfo.covQuantile_05 = NaN(1,length(covariateInfo.CovariateName));
+covariateInfo.covQuantile_95 = NaN(1,length(covariateInfo.CovariateName));
+% Add these info into covariateInfo structure
+for k=1:length(covariateInfo.CovariateName),
+    for k2=1:length(covNames),
+        % Find covname in structure - positions
+        ix = strmatchSB(covNames{k2},covariateInfo.CovariateName,'exact');
+        covariateInfo.covQuantile_05(ix) = quantileCOV_05(k2);
+        covariateInfo.covQuantile_95(ix) = quantileCOV_95(k2);
+    end
+end
+
+%% Determine median for cov and unique elements for cat
+medianCov = nanmedian(covValuesALL);
+catElements = {};
+for k=1:length(catNames),
+    catElements{k} = unique(catValuesALL(:,k));
+end
+
+%% Determine reference subjects properties
+referenceSubject = [];
+referenceSubject.covNames = covNames;
+referenceSubject.covValues = medianCov;
+referenceSubject.catNames = catNames;
+referenceSubject.catValues = [];
+for k=1:length(catNames),
+    dummy = unique(covariateInfo.CovariateName);
+    ix = strmatchSB(catNames{k},dummy);
+    number = [];
+    for k2=1:length(ix),
+        % find last occurrence of "_" then take the things behind that
+        ix2 = strfind(dummy{ix(k2)},'_');
+        number(k2) = str2num(dummy{ix(k2)}(ix2(end)+1:end));
+    end
+    % Get reference element
+    referenceSubject.catValues(k) = setdiff(catElements{k},number);
+end
+
+%% Sample parameters from uncertainty distribution (assume normal distribution)
+% No need to consider correlations because each parameter is considered
+% independently of the others
+covariateInfo.ParameterSampled = [];
+covariateInfo.ParameterSampledNormalized = [];
+for k=1:length(covariateInfo.ParameterValues),
+    covariateInfo.ParameterSampled(:,k) = covariateInfo.ParameterValues(ones(1,Nsamples),k)+covariateInfo.ParameterStderror(k)*randn(Nsamples,1);
+    covariateInfo.ParameterSampledNormalized(:,k) = covariateInfo.ParameterSampled(:,k)/covariateInfo.ParameterValues(k);
+end
+
+%% Sample betas from uncertainty distribution (assume normal distribution)
+covariateInfo.betaSampled = [];
+for k=1:length(covariateInfo.betaValue),
+    covariateInfo.betaSampled(:,k) = covariateInfo.betaValue(ones(1,Nsamples),k)+covariateInfo.betaStderror(k)*randn(Nsamples,1);
+end
+
+%% Transform the covariates in the dataset - all values - continuous only
+covariateInfo.covariateDataTransformed = NaN(Nsamples,length(covariateInfo.CovariateName));
+covariateInfo.covariateData = NaN(Nsamples,length(covariateInfo.CovariateName));
+for k=1:length(covariateInfo.CovariateName),
+    if covariateInfo.TypeCov(k) == 1,
+        % Continuous
+        ix = strmatch(covariateInfo.CovariateName{k},covNames,'exact');
+        covValuesk = covValuesALL(:,ix);
+        covValuesTransformedk = eval(strrep(covariateInfo.COVtrans{k},'cov','covValuesk'));
+        % Sample Nsamples from the covValuesTransformedk data - uniform sampling
+        ix2 = ceil(length(covValuesTransformedk)*rand(1,Nsamples));
+        covariateInfo.covariateDataTransformed(:,k) = covValuesTransformedk(ix2);
+        covariateInfo.covariateData(:,k) = covValuesk(ix2);
+    end 
+end    
+
+%% Transform the 5% and 95% quantiles of the continuous covariates
+covariateInfo.covQuantile_05_Transformed = NaN(1,length(covariateInfo.CovariateName));
+covariateInfo.covQuantile_95_Transformed = NaN(1,length(covariateInfo.CovariateName));
+for k=1:length(covariateInfo.CovariateName),
+    if covariateInfo.TypeCov(k) == 1,
+        % Continuous
+        covariateInfo.covQuantile_05_Transformed(k) = eval(strrep(covariateInfo.COVtrans{k},'cov','covariateInfo.covQuantile_05(k)'));
+        covariateInfo.covQuantile_95_Transformed(k) = eval(strrep(covariateInfo.COVtrans{k},'cov','covariateInfo.covQuantile_95(k)'));
+    end 
+end    
+
+%% Calculate mu - same for all - for sampled parameters
+covariateInfo.mu = [];
+for k=1:length(covariateInfo.ParameterName),
+    covariateInfo.mu(:,k) = eval(strrep(covariateInfo.IndivTransFinv{k},'psi','covariateInfo.ParameterSampled(:,k)'));
+end
+
+%% Handle covariates to determine the range of the parameters when using the sampling, normalized by the point
+% estimate for the reference subject (population mean)
+covariateInfo.ParamValueRangeNormalized = NaN(Nsamples,length(covariateInfo.TypeCov));
+for k=1:length(covariateInfo.TypeCov),
+    if covariateInfo.TypeCov(k) == 0,
+        covariatePHIcategorical = covariateInfo.mu(:,k)+covariateInfo.betaSampled(:,k);
+        covariatePSIcategorical = eval(strrep(covariateInfo.IndivTransF{k},'phi','covariatePHIcategorical'));
+        covariateInfo.ParamValueRangeNormalized(:,k) = covariatePSIcategorical/covariateInfo.ParameterValues(k);
+    else
+        covariatePHIcontinuous = covariateInfo.mu(:,k) + covariateInfo.betaSampled(:,k).*covariateInfo.covariateDataTransformed(:,k);
+        covariatePSIcontinuous = eval(strrep(covariateInfo.IndivTransF{k},'phi','covariatePHIcontinuous'));
+        covariateInfo.ParamValueRangeNormalized(:,k) = covariatePSIcontinuous/covariateInfo.ParameterValues(k);
+    end
+end
+
+%% Determine the range of the parameters for 5/95% quantiles of continuous covariates
+% estimate for the reference subject (population mean)
+covariateInfo.ParamValueRangeNormalized_05 = NaN(Nsamples,length(covariateInfo.TypeCov));
+covariateInfo.ParamValueRangeNormalized_95 = NaN(Nsamples,length(covariateInfo.TypeCov));
+for k=1:length(covariateInfo.TypeCov),
+    if covariateInfo.TypeCov(k) == 1,
+        % Only for continuous covariates
+        covariatePHIcontinuous_05 = covariateInfo.mu(:,k) + covariateInfo.betaSampled(:,k).*covariateInfo.covQuantile_05_Transformed(:,k);
+        covariatePHIcontinuous_95 = covariateInfo.mu(:,k) + covariateInfo.betaSampled(:,k).*covariateInfo.covQuantile_95_Transformed(:,k);
+        covariatePSIcontinuous_05 = eval(strrep(covariateInfo.IndivTransF{k},'phi','covariatePHIcontinuous_05'));
+        covariatePSIcontinuous_95 = eval(strrep(covariateInfo.IndivTransF{k},'phi','covariatePHIcontinuous_95'));
+        covariateInfo.ParamValueRangeNormalized_05(:,k) = covariatePSIcontinuous_05/covariateInfo.ParameterValues(k);
+        covariateInfo.ParamValueRangeNormalized_95(:,k) = covariatePSIcontinuous_95/covariateInfo.ParameterValues(k);
+    end
+end
+
+%% Prepare output to file
+if ~isempty(filename),
+    [p,f,e] = fileparts(filename);
+    warning off;
+    mkdir(p);
+    warning on;
+    startNewPrintFigureSBPOP(filename);
+end
+
+%% Plot the results
+% Do one figure per paramter
+parametersPlot = unique(covariateInfo.ParameterName);
+for k=1:length(parametersPlot),
+    parameter = parametersPlot{k};
+    % Get indices which to handle
+    ix = strmatchSB(parameter,covariateInfo.ParameterName,'exact');
+    % Open figure
+    handle = figure(k); clf;
+    % Create the data to plot
+    % Start with handling the sampled parameter - but use only first samples (ix(1))...
+    plotData = covariateInfo.ParameterSampledNormalized(:,ix(1));
+    plotData = plotData(:);
+    groupData = ones(length(plotData),1);
+    colorData = ones(length(plotData),1);
+    PlotData_changeWhiskers = plotData(:);
+    
+    % Now handle all the covariate data on this parameter
+    count = 1;
+    for k2=1:length(ix),
+        
+        % If continuous then also add the 05/95% quantile information
+        if covariateInfo.TypeCov(ix(k2)) == 1,
+            % Whole covariate range
+            plotData  = [plotData; covariateInfo.ParamValueRangeNormalized(:,ix(k2))];
+            groupData = [groupData; (count+1)*ones(length(covariateInfo.ParamValueRangeNormalized(:,ix(k2))),1)];
+            colorData = [colorData; 2*ones(length(covariateInfo.ParamValueRangeNormalized(:,ix(k2))),1)];
+            PlotData_changeWhiskers = [PlotData_changeWhiskers covariateInfo.ParamValueRangeNormalized(:,ix(k2))];
+            count     = count+1;
+
+            % 5% quantile
+            plotData  = [plotData; covariateInfo.ParamValueRangeNormalized_05(:,ix(k2))];
+            groupData = [groupData; (count+1)*ones(length(covariateInfo.ParamValueRangeNormalized_05(:,ix(k2))),1)];
+            colorData = [colorData; 3*ones(length(covariateInfo.ParamValueRangeNormalized_05(:,ix(k2))),1)];
+            PlotData_changeWhiskers = [PlotData_changeWhiskers covariateInfo.ParamValueRangeNormalized_05(:,ix(k2))];
+            count     = count+1;
+    
+            % 95% quantile
+            plotData  = [plotData; covariateInfo.ParamValueRangeNormalized_95(:,ix(k2))];
+            groupData = [groupData; (count+1)*ones(length(covariateInfo.ParamValueRangeNormalized_95(:,ix(k2))),1)];
+            colorData = [colorData; 3*ones(length(covariateInfo.ParamValueRangeNormalized_95(:,ix(k2))),1)];
+            PlotData_changeWhiskers = [PlotData_changeWhiskers covariateInfo.ParamValueRangeNormalized_95(:,ix(k2))];
+            count     = count+1;
+        else
+            % Categorical covariate element
+            plotData  = [plotData; covariateInfo.ParamValueRangeNormalized(:,ix(k2))];
+            groupData = [groupData; (count+1)*ones(length(covariateInfo.ParamValueRangeNormalized(:,ix(k2))),1)];
+            colorData = [colorData; 4*ones(length(covariateInfo.ParamValueRangeNormalized(:,ix(k2))),1)];
+            PlotData_changeWhiskers = [PlotData_changeWhiskers covariateInfo.ParamValueRangeNormalized(:,ix(k2))];
+            count     = count+1;
+        end
+    end
+    
+    % Add 20% box
+    YLimMin = 0.5;
+    YLimMax = 0.5+length(unique(groupData));
+    SBPOPplotfill([1-ClinicalRelevanceFactor 1+ClinicalRelevanceFactor],YLimMin*[1 1],YLimMax*[1 1],0.9*[1 1 1],1,0.9*[1 1 1]); hold on;
+    
+    % Plot data
+    SBPOPboxplot([2.5 97.5],1,plotData,groupData,'plotstyle','traditional','orientation','horizontal','boxstyle','filled','colorgroup',colorData,'symbol','','colors',[1 0 0; 0 0 0; 0.5*[1 1 1]; [0 0 0.5]]);
+    
+    % Need to define before boxplot to place the ticks correctly
+    axis square;
+    axis ij;
+
+    % Add line at X=1
+    hold on;
+    YLim = get(gca,'YLim');
+    plot([1 1],YLim,'k--');
+   
+    % Set Ylabels
+    ylabeltext = {};
+    % Parameter
+    ylabeltext{1} = ['Typical ' parameter];
+    
+    % Covariates
+    count = 1;
+    for k2=1:length(ix),
+        if covariateInfo.TypeCov(ix(k2)) == 1,
+            % Handle continuous covariate
+            % Get min and max values for covariate
+            minCov = min(covariateInfo.covariateData(:,ix(k2)));
+            maxCov = max(covariateInfo.covariateData(:,ix(k2)));
+            % Overall cov range effect on parameter
+            ylabeltext{1+count} = sprintf('%s (%g-%g)',covariateInfo.CovariateName{ix(k2)},minCov,maxCov);
+            count = count + 1;
+            
+            % 5% cov quantile effect on parameter
+            ylabeltext{1+count} = sprintf('%s (%g)',covariateInfo.CovariateName{ix(k2)},covariateInfo.covQuantile_05(ix(k2)));
+            count = count + 1;
+
+            % 95% cov quantile effect on parameter
+            ylabeltext{1+count} = sprintf('%s (%g)',covariateInfo.CovariateName{ix(k2)},covariateInfo.covQuantile_95(ix(k2)));
+            count = count + 1;
+        else
+            % Handle categorical covariate
+            ix2 = strfind(covariateInfo.CovariateName{ix(k2)},'_');
+            covcatName  = covariateInfo.CovariateName{ix(k2)}(1:ix2(end)-1);
+            covcatGroup = covariateInfo.CovariateName{ix(k2)}(ix2(end)+1:end);
+            ylabeltext{1+count} = sprintf('%s = %s',covcatName,covcatGroup);
+            count = count + 1;
+        end
+    end
+    
+    % Add yticklabeltext
+    set(gca,'YTick',[1:count+1]);
+    set(gca,'YTickLabel',ylabeltext);
+    set(gca,'YGrid','on')
+    
+    % Add xlabel etc.
+    xlabel('Change in parameter relative to reference individual','FontSize',12);
+    set(gca,'FontSize',12)
+    % Add title text with reference individual
+    titleText = sprintf('Covariate effects on parameter %s\nTypical individual:\n',parameter);
+    xxtext = '';
+    for k2=1:length(referenceSubject.covNames),
+        xxtext = sprintf('%s%s=%g, ',xxtext,referenceSubject.covNames{k2},referenceSubject.covValues(k2));
+    end
+    titleText = sprintf('%s%s, ',titleText,xxtext(1:end-2));
+    xxtext = '';
+    for k2=1:length(referenceSubject.catNames),
+        xxtext = sprintf('%s%s=%g, ',xxtext,referenceSubject.catNames{k2},referenceSubject.catValues(k2));
+    end
+    titleText = sprintf('%s%s',titleText,xxtext(1:end-2));
+    title(titleText,'FontSize',12,'FontWeight','bold','Interpreter','none');
+    
+%     XLim = get(gca,'XLim');
+%     YLim = get(gca,'YLim');
+%     text(XLim(2),YLim(1),sprintf('Boxplot ticks: %g%%,25%%,50%%,75%%,%g%%',perc(1),perc(2)),'FontSize',10,'HorizontalAlign','right','VerticalAlign','bottom');
+    ylabel(sprintf('Covariate distribution in dataset (min/max, 5%%/95%%) & Nominal\n \n '),'FontSize',12);
+    
+    % Export to figure if wanted
+    if ~isempty(filename),
+        printFigureSBPOP(gcf,filename);
+        close(handle);
+    end
+end
+
+% Stop figure export
+if ~isempty(filename),
+    convert2pdfSBPOP(filename);
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/07_CovariateAssessment/SBPOPcovariateChangeAssessment.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/07_CovariateAssessment/SBPOPcovariateChangeAssessment.m
new file mode 100644
index 0000000000000000000000000000000000000000..02ad479ba04788eea960a5017470b6d575915dcb
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/07_CovariateAssessment/SBPOPcovariateChangeAssessment.m
@@ -0,0 +1,224 @@
+function [] = SBPOPcovariateChangeAssessment(pathNLMEproject,analysisDataset,options)
+% [DESCRIPTION]
+% This function assesses the changes that a covariates introduces on the
+% model parameters, based on the contents of the dataset. For continuous
+% covariates the 5% and 95% quantiles of the covariate values in the
+% dataset are used. For categorical all values are considered.
+%
+% This function does NOT take the uncertainty in the estimated covariate
+% coefficients into account. Only point estimates are used. Please make
+% sure you run this function only on statistically significant covariates.
+%
+% [SYNTAX]
+% [] = SBPOPcovariateChangeAssessment(pathNLMEproject,analysisDataset)
+% [] = SBPOPcovariateChangeAssessment(pathNLMEproject,analysisDataset,options)
+%
+% [INPUT]
+% pathNLMEproject:   Relative path to the NLME(NONMEM or MONOLIX) project
+%                                   folder for which to assess the
+%                                   covariates.
+% analysisDataset:                  Matlab dataset with analysis data - or
+%                                   relative path including filename to the
+%                                   analysis dataset which was used to fit
+%                                   the model.
+% options:     Matlab structure with optional information
+%       options.filename:           output filename with path (default: 'covariateAssessment.txt')
+%
+% [OUTPUT]
+% Output on command window.
+% Additionally, the results are written to a file.
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 9th March, 2013
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+% Handle optional arguments
+try filename = options.filename; catch, filename = 'covariateAssessment.txt'; end
+
+% Handle analysis dataset input argument
+if ischar(analysisDataset),
+    % Load dataset
+    data = SBPOPloadCSVdataset(analysisDataset);
+elseif isa(analysisDataset,'dataset'),
+    data = analysisDataset;
+else
+    error('Incorrect input for "analysisDataset" argument.');
+end
+    
+%% Load info from NLME fit to get covariate information
+if isMONOLIXfitSBPOP(pathNLMEproject),
+    x = parseMONOLIXresultsSBPOP(pathNLMEproject);
+    y = sampleMONOLIXpopulationParametersSBPOP(x,0,0);
+elseif isNONMEMfitSBPOP(pathNLMEproject),
+    transformFLAG = 1;
+    x = parseNONMEMresultsSBPOP(pathNLMEproject,transformFLAG);
+    y = sampleNONMEMpopulationParametersSBPOP(x,0,0);
+else
+    error('Unknown project type.');
+end
+
+% Store population estimates
+POPestimates = y.fixedEffects.values;
+POPnames     = y.fixedEffects.names;
+
+% Determine the covariates to assess
+covNames = {};
+for k=1:length(y.covariates.continuous),
+	covNames = [covNames y.covariates.continuous(k).covariates];
+end
+covNames = unique(covNames);
+catNames = {};
+for k=1:length(y.covariates.categorical),
+	catNames = [catNames y.covariates.categorical(k).covariates];
+end
+catNames = unique(catNames);
+
+% Get info from dataset about the 5 and 95% quantiles of the continuous covariates and the levels of the categorical ones
+allID = unique(data.ID);
+covValuesALL = [];
+catValuesALL = [];
+for k=1:length(allID),
+    datak = data(data.ID==allID(k),:);
+    row = datak(1,:);
+    covValuesRow = [];
+    for k2=1:length(covNames),
+        covValuesRow(k2) = row.(covNames{k2});
+    end
+    covValuesALL = [covValuesALL; covValuesRow];
+    catValuesRow = [];
+    for k2=1:length(catNames),
+        catValuesRow(k2) = row.(catNames{k2});
+    end
+    catValuesALL = [catValuesALL; catValuesRow];
+end
+covQuantiles5_95 = quantile(covValuesALL,[0.05 0.95]);
+% Need to transpose covQuantiles5_95 if only single covariate
+if length(covNames)==1,
+	covQuantiles5_95 = covQuantiles5_95(:);
+end
+
+% Now consider the continuous covariates and determine changes from 5 to 95%
+COVinfoStructure = [];
+for k=1:length(covNames),
+    covName     = covNames{k};
+    covValues   = covQuantiles5_95(:,k);
+    Nsamples    = length(covValues);
+    FLAG_SAMPLE = 3;
+    output = SBPOPsampleNLMEfitParam( pathNLMEproject, FLAG_SAMPLE, Nsamples, covName, covValues, {}, []);
+    % Collect output
+    COVinfoStructure(k).name = covName;
+    COVinfoStructure(k).quantiles_5_95 = covQuantiles5_95(:,k);
+    COVinfoStructure(k).paramnames = POPnames;
+    COVinfoStructure(k).parameterCOV = output.parameterValuesPopulation;
+    z = output.parameterValuesPopulation;
+    zdelta1 = 100*(z(1,:)-POPestimates)./POPestimates;
+    zdelta2 = 100*(z(2,:)-POPestimates)./POPestimates;
+    COVinfoStructure(k).parameterCOVrelchange = [zdelta1; zdelta2];
+end
+
+CATinfoStructure = [];
+for k=1:length(catNames),
+    catName     = catNames{k};
+    catValues   = unique(catValuesALL(:,k));
+    Nsamples    = length(catValues);
+    FLAG_SAMPLE = 3;
+    output = SBPOPsampleNLMEfitParam( pathNLMEproject, FLAG_SAMPLE, Nsamples, {}, [], catName, catValues);
+    % Collect output
+    CATinfoStructure(k).name = catName;
+    CATinfoStructure(k).values = catValues;
+    CATinfoStructure(k).paramnames = POPnames;
+    CATinfoStructure(k).parameterCAT = output.parameterValuesPopulation;
+    z = output.parameterValuesPopulation;
+    zdelta = [];
+    for k2=1:length(catValues),
+        zdeltak = 100*(z(k2,:)-POPestimates)./POPestimates;
+        zdelta = [zdelta; zdeltak];
+    end
+    CATinfoStructure(k).parameterCATrelchange = zdelta;
+end
+
+
+% Handle filename and if available, create output folder
+if ~isempty(filename),
+    [p,f] = fileparts(filename);
+    warning off;
+    mkdir(p);
+    warning on
+    fid = fopen(filename,'w');
+end
+
+
+% Display results for continuous covariates
+for k=1:length(COVinfoStructure),
+    name                = COVinfoStructure(k).name;
+    range90             = COVinfoStructure(k).quantiles_5_95(:)';
+    paramnames          = COVinfoStructure(k).paramnames;
+    values90            = COVinfoStructure(k).parameterCOV;
+    relChangePercent    = COVinfoStructure(k).parameterCOVrelchange;
+    
+    fprintf(fid,'Assessment of covariate "%s" effect on PK parameters\n',name);
+    fprintf(fid,'=========================================================\n');
+    fprintf(fid,'Range of values in dataset [5%%, 95%% quantiles]: [%g, %g]\n',range90(1),range90(2));
+    fprintf(fid,'\n');
+    fprintf(fid,'           Parameter     Population estimate     Value at 5%% quantile    Value at 95%% quantile   Max absolute relative change from population estimate in %% (rounded)\n');
+    for k2=1:length(paramnames),
+        fprintf(fid,'%s           %6.3g                  %6.3g                  %6.3g                  %6.3g\n', ...
+            preFillCharSB(paramnames{k2},20,' '), ...
+            POPestimates(k2), ...
+            values90(1,k2), ...
+            values90(2,k2), ...
+            round(max(abs(relChangePercent(:,k2)))));
+    end
+    fprintf(fid,'\n');
+    fprintf(fid,'\n');
+end
+
+% Display results for categorical covariates
+for k=1:length(CATinfoStructure),
+    name                = CATinfoStructure(k).name;
+    valuesCAT           = CATinfoStructure(k).values;
+    paramnames          = CATinfoStructure(k).paramnames;
+    values              = CATinfoStructure(k).parameterCAT;
+    relChangePercent    = CATinfoStructure(k).parameterCATrelchange;
+    
+    fprintf(fid,'Assessment of covariate "%s" effect on PK parameters\n',name);
+    fprintf(fid,'=========================================================\n');
+    fprintf(fid,'Available values in dataset: ');
+    fprintf(fid,'%d  ',valuesCAT);
+    fprintf(fid,'\n');
+    fprintf(fid,'\n');
+    fprintf(fid,'           Parameter     Population estimate     Max absolute relative change from population estimate in %% (rounded)\n');
+    for k2=1:length(paramnames),
+        fprintf(fid,'%s           %6.3g                  %6.3g\n', ...
+            preFillCharSB(paramnames{k2},20,' '), ...
+            POPestimates(k2), ...
+            round(max(abs(relChangePercent(:,k2)))));
+    end
+    fprintf(fid,'\n');
+    fprintf(fid,'\n');
+end
+
+if ~isempty(filename),
+    fclose(fid)
+    contents = fileread(filename);
+    disp(contents);
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/07_CovariateAssessment/SBPOPscm.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/07_CovariateAssessment/SBPOPscm.m
new file mode 100644
index 0000000000000000000000000000000000000000..2c1f9b17ba156afb29516acf5252376bdf5af0bd
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/07_CovariateAssessment/SBPOPscm.m
@@ -0,0 +1,1144 @@
+function [] = SBPOPscm(TOOL,optionsSCM,model,dosing,data,projectPath,options)
+% SBPOPscm: Stepwise covariate search, using forward inclusion / backward
+% elimination. Decision can be made based on objective function value or confidence interval
+% of estimated covariate coefficients.
+%
+% Two modes/types of search:
+%   - type='OBJ': Behaves like the traditional PsN SCM, considering the
+%                 objective function value.
+%   - type='P':   Considers the probabilities that estimated covariate
+%                 coefficients are different from 0. In each forward step
+%                 the covariate coefficient is retained that is most
+%                 statistically significant.
+%
+% Although the algorithm is in principle applicable to categorical
+% covariates with more than 2 categories, it does not really make sense and
+% might introduce to many parameters that are not significant. A better
+% approach is to get the modeler to think a little more and reduce the
+% number of categories to 2. Covariates with multiple categories can be
+% assessed after the SCM has been done by adding them one at a time.
+%
+% This function here will only allow for categorical covariates with 2
+% categories - not more.
+%
+% USAGE:
+% ======
+% SBPOPscm(TOOL,optionsSCM,model,dosing,data,projectPath,options)
+%
+% Input arguments model, dosing, data, options are identical to the ones
+% documented in SBPOPcreateNONMEMproject and SBPOPcreateMONOLIXproject and
+% are not repeated here.
+%
+% If covariateModel is defined in modeltest, then these covariates are
+% included by default and are not subject to the SCM algorithm.
+%
+% TOOL:         'NONMEM' or 'MONOLIX'
+% projectPath:  Path to which all the generated NLME projects will be saved
+%
+% In case NONMEM/SAEM is used it will be checked that IMPORTANCESAMPLING
+% option is set to 1, in order to determine the true objective function
+% that is suitable for statistical testing.
+%
+% optionsSCM: structure with optional settings for the covariate search.
+%   optionsSCM.type:            Define if decisions based on objective function value or based on
+%                               probability that covariate coefficients are different from 0.
+%                               'OBJ' or 'P' (default: 'OBJ'). For categorical covariates with multiple
+%                               levels the delta OFV is adjusted and for 'P' the lowest p-value is used.
+%   optionsSCM.outputPath:      Path where to store the log file (default: projectPath)
+%
+%   optionsSCM.N_PROCESSORS_PAR:     Number of parallel model runs (default: 1)
+%   optionsSCM.N_PROCESSORS_SINGLE:  Number of processors to parallelize single run (if NONMEM and MONOLIX allow for it) (default: 1)
+%
+%   optionsSCM.p_forward:       p-value for forward inclusion step (default: 0.05)
+%                               Either for OFV or for probability that 0 included in CI for covariate coefficient.
+%   optionsSCM.p_backward:      p-value for forward inclusion step (default: 0.001)
+%                               Either for OFV or for probability that 0 included in CI for covariate coefficient.
+%   optionsSCM.covariateTests:  cell-array with parameter/covariate combinations to test
+%                               First element in each sub-array is the parameter name,
+%                               following are the covariates to test.
+%                               Example:
+%                                          {
+%                                             {'EMAX','WT0','SEX','HT0','ETHN'}
+%                                             {'EC50','WT0','SEX','HT0','ETHN'}
+%                                             {'fS'  ,'WT0','SEX','HT0','ETHN'}
+%                                           }
+%                               If not specified or empty, then all covariates will be
+%                               tested on all parameters.
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+%
+% This program is Free Open Source Software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Check TOOL definition
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~strcmpi(TOOL,'nonmem') && ~strcmpi(TOOL,'monolix'),
+    error('Please select as first input argument either ''NONMEM'' or ''MONOLIX''');
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle optionsSCM
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try p_forward           = optionsSCM.p_forward;            catch, p_forward              = 0.05;         end
+try p_backward          = optionsSCM.p_backward;           catch, p_backward             = 0.001;        end
+try covariateTests      = optionsSCM.covariateTests;       catch, covariateTests         = {};           end
+try outputPath          = optionsSCM.outputPath;           catch, outputPath             = projectPath;  end
+try type                = optionsSCM.type;                 catch, type                   = 'OBJ';        end
+try N_PROCESSORS_PAR    = optionsSCM.N_PROCESSORS_PAR;     catch, N_PROCESSORS_PAR       = 1;            end
+try N_PROCESSORS_SINGLE = optionsSCM.N_PROCESSORS_SINGLE;  catch, N_PROCESSORS_SINGLE    = 1;            end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Get previously defined covariate model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get fixed covariate model
+try covariateModel          = options.covariateModel;               catch, covariateModel        = ''; end
+try covariateModelValues    = options.covariateModelValues;         catch, covariateModelValues  = {}; end
+try COVestimate             = options.COVestimate;                  catch, COVestimate           = {}; end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Create the projectFolder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try rmdir(projectPath,'s'); catch end
+mkdir(projectPath);
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Load dataset to assess number of categorical elements
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+oldpath = pwd();
+cd(projectPath);
+dataContents = SBPOPloadCSVdataset([data.dataRelPathFromProject '/' data.dataFileName]);
+cd(oldpath);
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Change some paths
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+data.dataRelPathFromProject = ['../' data.dataRelPathFromProject];
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Create the BASE model (MODEL_00) and load header
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+BASEmodelFolder = [projectPath '/MODEL_BASE'];
+if strcmpi(TOOL,'nonmem')
+    % Check if IMP set to 1
+    if strcmpi(options.algorithm.METHOD,'saem') && options.algorithm.IMPORTANCESAMPLING == 0,
+        error('When using NONMEM/SAEM, please set the options.algorithm.IMPORTANCESAMPLING=1.');
+    end
+    SBPOPcreateNONMEMproject(model,dosing,data,BASEmodelFolder,options);
+    projectInfo = parseProjectHeaderNONMEMSBPOP(BASEmodelFolder);
+elseif strcmpi(TOOL,'monolix'),
+    SBPOPcreateMONOLIXproject(model,dosing,data,BASEmodelFolder,options);
+    projectInfo = parseProjectHeaderMONOLIXSBPOP(BASEmodelFolder);
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Get param cov and cat
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+parNames    = projectInfo.PARAMNAMES;
+covNames    = projectInfo.COVNAMES;
+catNames    = projectInfo.CATNAMES;
+covcatNames = [covNames catNames];
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% If list of covariates empty then generate it
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(covariateTests)
+    covariateTests = cell(length(parNames),1);
+    for k1=1:length(parNames),
+        cTk{1} = parNames{k1};
+        for k2=1:length(covcatNames),
+            cTk{k2+1} = covcatNames{k2};
+        end
+        covariateTests{k1} = cTk(:)';
+    end
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Get covariate list for parameters and covariate names
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+covSearch = [];
+covSearch.paramNamesTest  = {};
+covSearch.covcatNamesTest = {};
+% Get param and covcat names from covariateTests
+for k1=1:length(covariateTests),
+    for k2=2:length(covariateTests{k1}),
+        covSearch.paramNamesTest{end+1}  = covariateTests{k1}{1};
+        covSearch.covcatNamesTest{end+1} = covariateTests{k1}{k2};
+    end
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Check covariate list for parameters and covariate names
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(covSearch.paramNamesTest),
+    ix = strmatchSB(covSearch.paramNamesTest{k},parNames,'exact');
+    if isempty(ix),
+        error('Parameter %s is not estimated in the model.',covSearch.paramNamesTest{k});
+    end
+end
+
+for k=1:length(covSearch.covcatNamesTest),
+    ix = strmatchSB(covSearch.covcatNamesTest{k},covcatNames,'exact');
+    if isempty(ix),
+        error('Covariate %s is not present in the dataset.',covSearch.covcatNamesTest{k});
+    end
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine structural covariate information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+covStructural = [];
+covStructural.paramNames  = {};
+covStructural.covcatNames = {};
+covStructural.value       = [];
+covStructural.estimate    = [];
+terms = strrep(strrep(explodePCSB(covariateModel,',','{','}'),'{',''),'}','');
+for k=1:length(terms),
+    x = explodePCSB(terms{k});
+    for k2=2:length(x),
+        covStructural.paramNames{end+1} = x{1};
+        covStructural.covcatNames{end+1} = x{k2};
+        if isempty(covariateModelValues),
+            covStructural.value(end+1) = 0.1;
+        else
+            covStructural.value(end+1) = covariateModelValues{k}(k2-1);
+        end
+        if isempty(COVestimate),
+            covStructural.estimate(end+1) = 1;
+        else
+            covStructural.estimate(end+1) = COVestimate{k}(k2-1);
+        end
+    end
+    
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Remove structural covariates from covSearch
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ix_remove = [];
+for k=1:length(covStructural.paramNames),
+    par = covStructural.paramNames{k};
+    cov = covStructural.covcatNames{k};
+    ix1 = strmatchSB(par,covSearch.paramNamesTest,'exact');
+    ix2 = strmatchSB(cov,covSearch.covcatNamesTest,'exact');
+    if ~isempty(intersect(ix1,ix2)),
+        ix_remove(end+1) = intersect(ix1,ix2);
+    end
+end
+if ~isempty(ix_remove),
+    covSearch.paramNamesTest(ix_remove) = [];
+    covSearch.covcatNamesTest(ix_remove) = [];
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine delta Objective functions required for covariates
+% DF: 1 for continuous, N-1 for categorical
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(covSearch.covcatNamesTest),
+    % Check if categorical
+    if ~isempty(strmatchSB(covSearch.covcatNamesTest{k},covNames,'exact')),
+        % Continuous covariate
+        N_DF = 1;
+    else
+        % Categorical covariate
+        N_categories = length(unique(dataContents.(covSearch.covcatNamesTest{k})));
+        if N_categories > 2,
+            error('Categorical covariate "%s" has more than 2 categories - this is not allowed.',covSearch.covcatNamesTest{k});
+            N_DF = length(unique(dataContents.(covSearch.covcatNamesTest{k}))) - 1;
+        end
+    end
+    covSearch.delta_forward(k)   = chi2inv(1-p_forward,N_DF);
+    covSearch.delta_backward(k)  = chi2inv(1-p_backward,N_DF);
+end
+
+% For later
+covSearchBackUp = covSearch;
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Open report file
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+mkdir(outputPath);
+fid = fopen([outputPath '/SCMlogfile.txt'],'w');
+
+fprintf(fid,'****************************************************************************\n');
+fprintf(fid,'* Covariate search using forward inclusion and backward elimination method *\n');
+fprintf(fid,'****************************************************************************\n');;
+fprintf(fid,'p-value forward:      %g\n',p_forward);
+fprintf(fid,'p-value backward:     %g\n',p_backward);
+fprintf(fid,'\n');
+if strcmpi(type,'P'),
+    fprintf(fid,'Decisions based on probability of CI of covariate coefficient including 0.\n');
+elseif strcmpi(type,'OBJ'),
+    fprintf(fid,'Decisions based on delta objective function.\n');
+else
+    error('Incorrect definition of "type"');
+end
+fprintf(fid,'\n');
+
+fprintf(fid,'************************************\n');
+fprintf(fid,'* RUNNING BASE MODEL (MODEL_BASE)  *\n');
+fprintf(fid,'************************************\n');
+fprintf(fid,'\n');
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Run the BASE model (MODEL_BASE)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+BASEmodelFolder = [projectPath '/MODEL_BASE'];
+if strcmpi(TOOL,'nonmem')
+    SBPOPrunNONMEMproject(BASEmodelFolder,N_PROCESSORS_SINGLE);
+    RESULTS = parseNONMEMresultsSBPOP(BASEmodelFolder,1);
+elseif strcmpi(TOOL,'monolix'),
+    SBPOPrunMONOLIXproject(BASEmodelFolder,N_PROCESSORS_SINGLE);
+    RESULTS = parseMONOLIXresultsSBPOP(BASEmodelFolder);
+end
+close all; drawnow();
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Get OFV and optimal parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+BASE_OFV            = RESULTS.objectivefunction.OBJ;
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Update options with optimal BASE model parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+options.POPvalues0  = RESULTS.rawParameterInfo.fixedEffects.values;
+options.IIVvalues0  = RESULTS.rawParameterInfo.randomEffects.values;
+options.errorParam0 = RESULTS.rawParameterInfo.errorParameter.values;
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Update data path again for the level models
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+data.dataRelPathFromProject = ['../' data.dataRelPathFromProject];
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Forward inclusion
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'************************************\n');
+fprintf(fid,'* FORWARD INCLUSION                *\n');
+fprintf(fid,'************************************\n');
+fprintf(fid,'\n');
+
+OLD_OFV                 = BASE_OFV;
+covariatesForward       = {};
+%%%
+covariateModelValuesForward = {};
+COVestimateForward          = {};
+%%%
+countModel              = 1;
+Nmaxmodels              = (length(covSearch.covcatNamesTest)^2-length(covSearch.covcatNamesTest))/2+length(covSearch.covcatNamesTest);
+continueForwardSearch   = 1;
+levelCount              = 1;
+levelModel              = '';
+ForwardModelName        = BASEmodelFolder;
+ModelNameAll            = {};
+
+while continueForwardSearch,
+    fprintf(fid,'* Level %d: ',levelCount);
+    
+    % Run through remaining parameter/covariate combinations
+    % Generate all models first and then run all at once
+    covariatesTestForward = {};
+    %%%
+    covariateModelValuesTESTForward = {};
+    COVestimateTESTForward          = {};
+    %%%
+    covariateModelAll     = {};
+    for k1=1:length(covSearch.paramNamesTest),
+        
+        % Reset covariate setting to previous level
+        covariatesTest = covariatesForward;
+        %%%
+        covariateModelValues = covariateModelValuesForward;
+        COVestimate = COVestimateForward;
+        %%%
+        
+        % Get new parameter/covariate combination to test
+        param = covSearch.paramNamesTest{k1};
+        cov   = covSearch.covcatNamesTest{k1};
+        delta = covSearch.delta_forward(k1);
+        
+        %%%
+        value = 0.1; % Setting default value to 0.1 (NONMEM does not allow 0)
+        
+        % Build covariate test structure and covariateModelValues and COVestimate
+        ix = [];
+        for k2=1:length(covariatesTest),
+            if strcmp(covariatesTest{k2}{1},param),
+                ix = k2;
+            end
+        end
+        if isempty(ix),
+            covariatesTest{end+1}{1} = param;
+            covariatesTest{end}{2} = cov;
+            covariateModelValues{end+1} = value;
+            COVestimate{end+1} = 1;
+        else
+            covariatesTest{ix}{end+1} = cov;
+            covariateModelValues{ix}(end+1) = value;
+            COVestimate{ix}(end+1) = 1;
+        end
+        covariatesTest = covariatesTest(:);
+        %%%
+        
+        % Save for later
+        covariatesTestForward{k1} = covariatesTest;
+        %%%
+        covariateModelValuesTESTForward{k1} = covariateModelValues;
+        COVestimateTESTForward{k1}          = COVestimate;
+        %%%
+        
+        % Convert to required format
+        covariateModel                      = '';
+        for k3=1:size(covariatesTest,1),
+            if ~isempty(covariatesTest{k3}),
+                text                        = sprintf('%s,',covariatesTest{k3}{:});
+                covariateModel              = [covariateModel '{' text(1:end-1) '},'];
+            end
+        end
+        covariateModel                      = covariateModel(1:end-1);
+        covariateModelAll{k1}               = covariateModel;
+        
+        % Determine COVestimate and covariateModelValues
+        COVestimate = {};
+        covariateModelValues = {};
+        for k3=1:size(covariatesTest,1),
+            COVestimate{k3} = ones(1,length(covariatesTest{k3})-1);
+            covariateModelValues{k3} = 0.1*ones(1,length(covariatesTest{k3})-1);
+        end
+        
+        % Add structural covariates to covariate model
+        for k3=1:length(covStructural.paramNames),
+            param    = covStructural.paramNames{k3};
+            cov      = covStructural.covcatNames{k3};
+            value    = covStructural.value(k3);
+            estimate = covStructural.estimate(k3);
+            % Find where to add
+            ix = [];
+            for k4=1:size(covariatesTest,1),
+                if strcmp(param,covariatesTest{k4}{1}),
+                    ix = k4;
+                    break;
+                end
+            end
+            if ~isempty(ix),
+                % add info
+                covariatesTest{ix}{end+1} = cov;
+                covariateModelValues{ix}(end+1) = value;
+                COVestimate{ix}(end+1) = estimate;
+            else
+                % new param
+                covariatesTest{end+1}{1} = param;
+                covariatesTest{end}{2} = cov;
+                covariateModelValues{end+1}(1) = value;
+                COVestimate{end+1}(1) = estimate;
+            end
+            covariatesTest = covariatesTest(:);
+        end
+        
+        % Convert to required format for the search things
+        covariateModel                      = '';
+        for k3=1:size(covariatesTest,1),
+            if ~isempty(covariatesTest{k3}),
+                text                        = sprintf('%s,',covariatesTest{k3}{:});
+                covariateModel              = [covariateModel '{' text(1:end-1) '},'];
+            end
+        end
+        covariateModel                      = covariateModel(1:end-1);
+        
+        % Set covariateModel
+        options.covariateModel              = covariateModel;
+        options.covariateModelValues        = covariateModelValues;
+        options.COVestimate                 = COVestimate;
+        
+        % Create model
+        ModelName                           = sprintf('MODEL_%s',preFillCharSB(countModel,length(num2str(Nmaxmodels)),'0'));
+        FolderName                          = [projectPath sprintf('/FW_LEVEL_%d',levelCount)];
+        ModelFolder                         = [FolderName '/' ModelName];
+        ModelNameAll{k1}                    = ModelFolder;
+        if strcmpi(TOOL,'nonmem')
+            SBPOPcreateNONMEMproject(model,dosing,data,ModelFolder,options);
+        elseif strcmpi(TOOL,'monolix'),
+            SBPOPcreateMONOLIXproject(model,dosing,data,ModelFolder,options);
+        end
+        countModel                          = countModel + 1;
+    end
+    
+    % Write out level base cov model
+    fprintf(fid,'"%s"\n',levelModel);
+    fprintf(fid,'\n');
+    
+    % Run the level models - do not create GoF plots
+    SBPOPrunNLMEprojectFolder(FolderName,N_PROCESSORS_PAR,N_PROCESSORS_SINGLE,1);
+    
+    % Read the results
+    LEVEL_RESULTS = SBPOPfitanalysisProjectsFolderInfo(FolderName,FolderName);
+    
+    % Determine significance in different ways, defined by "type"
+    LEVEL_SIGNIFICANCE = [];
+    % Get OBJ
+    LEVEL_OBJ = [LEVEL_RESULTS.OBJ];
+    
+    % Handle P or OBJ type
+    if strcmpi(type,'OBJ'),
+        % BASED ON OBJECTIVE FUNCTION VALUE
+        % Print out info and determine significance
+        for k1=1:length(covSearch.paramNamesTest),
+            fprintf(fid,'%s (%s on %s): DeltaOFV=%g Goal>=%g ... ',LEVEL_RESULTS(k1).model,covSearch.covcatNamesTest{k1},covSearch.paramNamesTest{k1},OLD_OFV-LEVEL_OBJ(k1),covSearch.delta_forward(k1));
+            if OLD_OFV-LEVEL_OBJ(k1) >= covSearch.delta_forward(k1),
+                LEVEL_SIGNIFICANCE(k1) = 1;
+                fprintf(fid,'significant');
+            else
+                LEVEL_SIGNIFICANCE(k1) = 0;
+                fprintf(fid,'not significant');
+            end
+            fprintf(fid,'\n');
+        end
+        fprintf(fid,'\n');
+        
+        % Determine which covariate leads to the largest drop in OBJ
+        [xdummyx,ixBEST] = max(OLD_OFV-LEVEL_OBJ);
+        
+    else
+        % BASED ON ESTIMATED COVARIATE COEFFICIENTS
+        LEVEL_PVALUES = Inf(1,length(covSearch.paramNamesTest));
+        % Get covariate estimate informations for the current fit
+        for k1=1:length(covSearch.paramNamesTest),
+            param = covSearch.paramNamesTest{k1};
+            cov   = covSearch.covcatNamesTest{k1};
+            for k2=1:length(LEVEL_RESULTS(k1).rawParameterInfo.covariate.names),
+                xxx = strrep(LEVEL_RESULTS(k1).rawParameterInfo.covariate.names{k2},'(','_');
+                xxx = strrep(xxx,')','_');
+                test1 = strfind(xxx,['_' param '_']);
+                test2 = strfind(xxx,['_' cov]);
+                if ~isempty(test1) && ~isempty(test2),
+                    % Yes, this was a tested covariate
+                    % Calculate the p-value
+                    mu = LEVEL_RESULTS(k1).rawParameterInfo.covariate.values(k2);
+                    sigma = LEVEL_RESULTS(k1).rawParameterInfo.covariate.stderr(k2);
+                    p = min(normcdf(0,abs(mu),abs(sigma))*2);
+                    LEVEL_PVALUES(k1) = min(p,LEVEL_PVALUES(k1)); % Minimum handles multiple levels categorical covs
+                end
+            end
+        end
+        for k1=1:length(LEVEL_PVALUES),
+            fprintf(fid,'%s (%s on %s): P=%g Goal<=%g ... ',LEVEL_RESULTS(k1).model,covSearch.covcatNamesTest{k1},covSearch.paramNamesTest{k1},LEVEL_PVALUES(k1),p_forward);
+            if LEVEL_PVALUES(k1)<=p_forward,
+                LEVEL_SIGNIFICANCE(k1) = 1;
+                fprintf(fid,'significant');
+            else
+                LEVEL_SIGNIFICANCE(k1) = 0;
+                fprintf(fid,'not significant');
+            end
+            fprintf(fid,'\n');
+        end
+        fprintf(fid,'\n');
+        
+        % Determine which covariate leads to the lowest p-value
+        [xdummyx,ixBEST] = min(LEVEL_PVALUES);
+    end
+    
+    % If none significant then stop forward inclusion here
+    if sum(LEVEL_SIGNIFICANCE) == 0,
+        continueForwardSearch = 0;
+    else
+        % Message
+        fprintf(fid,'\n');
+        fprintf(fid,'Retained covariate for next level: %s on %s\n',covSearch.covcatNamesTest{ixBEST},covSearch.paramNamesTest{ixBEST});
+        fprintf(fid,'\n');
+        % Setup for new level
+        OLD_OFV = LEVEL_OBJ(ixBEST);
+        % Update options with optimal model parameters from last run
+        options.POPvalues0  = LEVEL_RESULTS(ixBEST).rawParameterInfo.fixedEffects.values;
+        options.IIVvalues0  = LEVEL_RESULTS(ixBEST).rawParameterInfo.randomEffects.values;
+        options.errorParam0 = LEVEL_RESULTS(ixBEST).rawParameterInfo.errorParameter.values;
+        % Remove covariate from search
+        covSearch.covcatNamesTest(ixBEST) = [];
+        covSearch.delta_forward(ixBEST)  = [];
+        covSearch.delta_backward(ixBEST)  = [];
+        covSearch.paramNamesTest(ixBEST)  = [];
+        % Set new base covariates
+        covariatesForward = covariatesTestForward{ixBEST};
+        
+        %%%
+        covariateModelValuesForward = covariateModelValuesTESTForward{ixBEST};
+        COVestimateForward = COVestimateTESTForward{ixBEST};
+        
+        % Update estimated covariate coefficient for next level - with all new
+        % estimates!
+        covInfo = LEVEL_RESULTS(ixBEST).rawParameterInfo.covariate;
+        
+        for k1x = 1:length(covariatesForward),
+            paramUpdate = covariatesForward{k1x}{1};
+            for k2x = 2:length(covariatesForward{k1x}),
+                covUpdate = covariatesForward{k1x}{k2x};
+                % Find parameter and covariate
+                matchIX = [];
+                for kkkx=1:length(covInfo.names),
+                    ixParam = strfind(covInfo.names{kkkx},paramUpdate);
+                    ixCov = strfind(covInfo.names{kkkx},covUpdate);
+                    if ~isempty(ixParam) && ~isempty(ixCov),
+                        matchIX(end+1) = kkkx;
+                    end
+                end
+                if length(matchIX) ~= 1,
+                    error('Problem with getting covariate coefficient value.');
+                end
+                % Get the estimated value
+                value = covInfo.values(matchIX);
+                % Add value to covariateModelValuesForward
+                ix = [];
+                for k2=1:length(covariatesForward),
+                    if strcmp(covariatesForward{k2}{1},paramUpdate),
+                        ix = k2;
+                    end
+                end
+                covariateModelValuesForward{ix}(strmatchSB(covUpdate,covariatesForward{ix},'exact')-1) = value;
+            end
+        end
+        %%%
+        
+        
+        levelModel = covariateModelAll{ixBEST};
+        ForwardModelName = ModelNameAll{ixBEST};
+        levelCount = levelCount+1;
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get forward results
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+FORWARD_OFV = OLD_OFV;
+forwardModel = levelModel;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Report forward model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+fprintf(fid,'************************************\n');
+fprintf(fid,'* FORWARD MODEL RESULTS            *\n');
+fprintf(fid,'************************************\n');
+fprintf(fid,'\n');
+
+fprintf(fid,'Forward model:             %s\n',ForwardModelName);
+fprintf(fid,'Covariates:                %s\n',forwardModel);
+fprintf(fid,'Objective function value:  %g\n',FORWARD_OFV);
+fprintf(fid,'\n');
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Backward elimination
+% Handle P and OBJ differently
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'************************************\n');
+fprintf(fid,'* BACKWARD ELIMINATION             *\n');
+fprintf(fid,'************************************\n');
+fprintf(fid,'\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create covSearch structure for backward search
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+covSearchBackward = covSearchBackUp;
+ix_keep = [];
+for k1=1:size(covariatesForward),
+    param = covariatesForward{k1}{1};
+    for k2=2:length(covariatesForward{k1}),
+        cov = covariatesForward{k1}{k2};
+        ix_keep(end+1) = intersect(strmatchSB(param,covSearchBackward.paramNamesTest,'exact'),strmatchSB(cov,covSearchBackward.covcatNamesTest,'exact'));
+    end
+end
+covSearchBackward.covcatNamesTest = covSearchBackward.covcatNamesTest(ix_keep);
+covSearchBackward.paramNamesTest = covSearchBackward.paramNamesTest(ix_keep);
+covSearchBackward.delta_forward = covSearchBackward.delta_forward(ix_keep);
+covSearchBackward.delta_backward = covSearchBackward.delta_backward(ix_keep);
+
+%%%
+% Add parameter values
+for k1=1:length(covSearchBackward.paramNamesTest),
+    paramName = covSearchBackward.paramNamesTest{k1};
+    covName   = covSearchBackward.covcatNamesTest{k1};
+    for k2=1:size(covariatesForward),
+        if strcmp(paramName,covariatesForward{k2}{1}),
+            ix = k2;
+            break;
+        end
+    end
+    ix2 = strmatchSB(covName,covariatesForward{ix}(2:end),'exact');
+    value = covariateModelValuesForward{ix}(ix2);
+    covSearchBackward.value(k1) = value;
+end
+%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Do the search
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+covariateModelAll  = {};
+levelCount         = 1;
+countModel         = 1;
+BackwardModelName  = ForwardModelName;
+ModelNameAll       = {};
+
+% Check if backward search needed
+if ~isempty(covariatesForward),
+    continueBackwardSearch = 1;
+else
+    continueBackwardSearch = 0;
+end
+
+if strcmpi(type,'OBJ'),
+    % OBJ:  Start with FORWARD_OFV and remove one by one ... until deltaOFV>... for
+    
+    while continueBackwardSearch,
+        fprintf(fid,'* Level %d: ',levelCount);
+        
+        % Run through remaining parameter/covariate combinations
+        % Generate all models first and then run all at once
+        
+        for k1=1:length(covSearchBackward.paramNamesTest),
+            
+            % Reset covariate setting to previous level
+            covariatesTest = covSearchBackward;
+            
+            % Remove parameter to test
+            %%%
+            param = covariatesTest.paramNamesTest;
+            cov   = covariatesTest.covcatNamesTest;
+            value = covariatesTest.value;
+            param(k1) = [];
+            cov(k1)   = [];
+            value(k1) = [];
+            %%%
+            
+            % Build covariate test structure
+            x = unique(param);
+            covTestStructure = {};
+            %%%
+            covariateModelValues = cell(1,length(x));
+            COVestimate = cell(1,length(x));
+            %%%
+            
+            for k2=1:length(x),
+                covTestStructure{k2}{1} = x{k2};
+            end
+            covTestStructure = covTestStructure(:);
+            for k2=1:length(param),
+                ix = strmatchSB(param{k2},x,'exact');
+                covTestStructure{ix}{end+1} = cov{k2};
+                %%%
+                covariateModelValues{ix}(end+1) = value(k2);
+                COVestimate{ix}(end+1) = 1;
+                %%%
+                
+            end
+            
+            % Convert to required format
+            covariateModel                      = '';
+            for k3=1:size(covTestStructure,1),
+                if ~isempty(covTestStructure{k3}),
+                    text                        = sprintf('%s,',covTestStructure{k3}{:});
+                    covariateModel              = [covariateModel '{' text(1:end-1) '},'];
+                end
+            end
+            covariateModel                      = covariateModel(1:end-1);
+            covariateModelAll{k1}               = covariateModel;
+            
+            % Add structural covariates to covariate model
+            for k3=1:length(covStructural.paramNames),
+                param    = covStructural.paramNames{k3};
+                cov      = covStructural.covcatNames{k3};
+                value    = covStructural.value(k3);
+                estimate = covStructural.estimate(k3);
+                % Find where to add
+                ix = [];
+                for k4=1:size(covTestStructure,1),
+                    if strcmp(param,covTestStructure{k4}{1}),
+                        ix = k4;
+                        break;
+                    end
+                end
+                if ~isempty(ix),
+                    % add info
+                    covTestStructure{ix}{end+1} = cov;
+                    covariateModelValues{ix}(end+1) = value;
+                    COVestimate{ix}(end+1) = estimate;
+                else
+                    % new param
+                    covTestStructure{end+1}{1} = param;
+                    covTestStructure{end}{2} = cov;
+                    covariateModelValues{end+1}(1) = value;
+                    COVestimate{end+1}(1) = estimate;
+                end
+                covTestStructure = covTestStructure(:);
+            end
+            
+            % Convert to required format for the search things
+            covariateModel                      = '';
+            for k3=1:size(covTestStructure,1),
+                if ~isempty(covTestStructure{k3}),
+                    text                        = sprintf('%s,',covTestStructure{k3}{:});
+                    covariateModel              = [covariateModel '{' text(1:end-1) '},'];
+                end
+            end
+            covariateModel                      = covariateModel(1:end-1);
+            
+            % Set covariateModel
+            options.covariateModel              = covariateModel;
+            options.covariateModelValues        = covariateModelValues;
+            options.COVestimate                 = COVestimate;
+            
+            % Create model
+            ModelName                           = sprintf('MODEL_%s',preFillCharSB(countModel,length(num2str(Nmaxmodels)),'0'));
+            FolderName                          = [projectPath sprintf('/BW_LEVEL_%d',levelCount)];
+            ModelFolder                         = [FolderName '/' ModelName];
+            ModelNameAll{k1}                    = ModelFolder;
+            if strcmpi(TOOL,'nonmem')
+                SBPOPcreateNONMEMproject(model,dosing,data,ModelFolder,options);
+            elseif strcmpi(TOOL,'monolix'),
+                SBPOPcreateMONOLIXproject(model,dosing,data,ModelFolder,options);
+            end
+            countModel                          = countModel + 1;
+        end
+        
+        % Write out level base cov model
+        fprintf(fid,'"%s"\n',levelModel);
+        fprintf(fid,'\n');
+        
+        % Run the level models - do not create GoF plots
+        SBPOPrunNLMEprojectFolder(FolderName,N_PROCESSORS_PAR,N_PROCESSORS_SINGLE,1);
+        
+        % Read the results
+        LEVEL_RESULTS = SBPOPfitanalysisProjectsFolderInfo(FolderName,FolderName);
+        
+        % Determine significance in different ways, defined by "type"
+        LEVEL_SIGNIFICANCE = [];
+        % Get OBJ
+        LEVEL_OBJ = [LEVEL_RESULTS.OBJ];
+        
+        % Print out info and determine significance
+        for k1=1:length(covSearchBackward.paramNamesTest),
+            fprintf(fid,'%s (%s on %s): DeltaOFV=%g Goal>=%g ... ',LEVEL_RESULTS(k1).model,covSearchBackward.covcatNamesTest{k1},covSearchBackward.paramNamesTest{k1},-OLD_OFV+LEVEL_OBJ(k1),covSearchBackward.delta_backward(k1));
+            if -OLD_OFV+LEVEL_OBJ(k1) >= covSearchBackward.delta_backward(k1),
+                LEVEL_SIGNIFICANCE(k1) = 1;
+                fprintf(fid,'significant');
+            else
+                LEVEL_SIGNIFICANCE(k1) = 0;
+                fprintf(fid,'not significant');
+            end
+            fprintf(fid,'\n');
+        end
+        fprintf(fid,'\n');
+        
+        % Determine which covariate leads to the largest increase in OBJ
+        [xdummyx,ixBEST] = min(-OLD_OFV+LEVEL_OBJ);
+        
+        % If all significant then stop backward elimination here
+        if sum(LEVEL_SIGNIFICANCE~=1) == 0,
+            continueBackwardSearch = 0;
+        else
+            % Message
+            fprintf(fid,'\n');
+            fprintf(fid,'Removed covariate for next level: %s on %s\n',covSearchBackward.covcatNamesTest{ixBEST},covSearchBackward.paramNamesTest{ixBEST});
+            fprintf(fid,'\n');
+            % Setup for new level
+            OLD_OFV = LEVEL_OBJ(ixBEST);
+            % Update options with optimal model parameters from last run
+            options.POPvalues0  = LEVEL_RESULTS(ixBEST).rawParameterInfo.fixedEffects.values;
+            options.IIVvalues0  = LEVEL_RESULTS(ixBEST).rawParameterInfo.randomEffects.values;
+            options.errorParam0 = LEVEL_RESULTS(ixBEST).rawParameterInfo.errorParameter.values;
+            % Remove covariate from search
+            covSearchBackward.covcatNamesTest(ixBEST) = [];
+            covSearchBackward.delta_forward(ixBEST)  = [];
+            covSearchBackward.delta_backward(ixBEST)  = [];
+            covSearchBackward.paramNamesTest(ixBEST)  = [];
+            levelModel = covariateModelAll{ixBEST};
+            levelCount = levelCount+1;
+            BackwardModelName = ModelNameAll{ixBEST};
+            %%%
+            % Update values in covSearchBackward to estimated ones in best model
+            covInfo = LEVEL_RESULTS(ixBEST).rawParameterInfo.covariate;
+            
+            for k1x = 1:length(covSearchBackward.paramNamesTest),
+                paramUpdate = covSearchBackward.paramNamesTest{k1x};
+                covUpdate   = covSearchBackward.covcatNamesTest{k1x};
+                
+                % Find parameter and covariate
+                matchIX = [];
+                for kkkx=1:length(covInfo.names),
+                    ixParam = strfind(covInfo.names{kkkx},paramUpdate);
+                    ixCov = strfind(covInfo.names{kkkx},covUpdate);
+                    if ~isempty(ixParam) && ~isempty(ixCov),
+                        matchIX(end+1) = kkkx;
+                    end
+                end
+                if length(matchIX) ~= 1,
+                    error('Problem with getting covariate coefficient value.');
+                end
+                % Get the estimated value
+                value = covInfo.values(matchIX);
+                % Add value to covSearchBackward
+                covSearchBackward.value(k1x) = value;
+            end
+            %%%
+        end
+        
+        if  isempty(covSearchBackward.paramNamesTest),
+            continueBackwardSearch = 0;
+        end
+    end
+else
+    % P:    Remove largest of the p-values>p_backward then rerun until all p-values<=p_backward
+    
+    while continueBackwardSearch,
+        if  isempty(covSearchBackward.paramNamesTest),
+            continueBackwardSearch = 0;
+            break
+        end
+        
+        % Get all P values for the last model
+        if strcmpi(TOOL,'nonmem')
+            RESULTS = parseNONMEMresultsSBPOP(BackwardModelName,1);
+        elseif strcmpi(TOOL,'monolix'),
+            RESULTS = parseMONOLIXresultsSBPOP(BackwardModelName);
+        end
+        P_VALUES = Inf(1,length(covSearchBackward.paramNamesTest));
+        for k1=1:length(covSearchBackward.paramNamesTest),
+            param = covSearchBackward.paramNamesTest{k1};
+            cov   = covSearchBackward.covcatNamesTest{k1};
+            for k2=1:length(RESULTS.rawParameterInfo.covariate.names),
+                xxx = strrep(RESULTS.rawParameterInfo.covariate.names{k2},'(','_');
+                xxx = strrep(xxx,')','_');
+                test1 = strfind(xxx,['_' param '_']);
+                test2 = strfind(xxx,['_' cov]);
+                if ~isempty(test1) && ~isempty(test2),
+                    % Yes, this was a tested covariate
+                    % Calculate the p-value
+                    mu = RESULTS.rawParameterInfo.covariate.values(k2);
+                    sigma = RESULTS.rawParameterInfo.covariate.stderr(k2);
+                    p = min(normcdf(0,abs(mu),abs(sigma))*2);
+                    P_VALUES(k1) = min(p,P_VALUES(k1)); % Minimum handles multiple levels categorical covs
+                end
+            end
+        end
+        
+        % Check if all P values <= p_backward
+        if sum(P_VALUES > p_backward) ~= 0,
+            continueBackwardSearch = 1;
+            
+            % Message
+            fprintf(fid,'* Level %d: "%s"\n',levelCount,levelModel);
+            fprintf(fid,'\n');
+            
+            for k1=1:length(covSearchBackward.paramNamesTest),
+                fprintf(fid,'%s on %s: P=%g Goal<=%g ... ',covSearchBackward.covcatNamesTest{k1},covSearchBackward.paramNamesTest{k1},P_VALUES(k1),p_backward);
+                if P_VALUES(k1)<=p_backward,
+                    fprintf(fid,'significant');
+                else
+                    fprintf(fid,'not significant');
+                end
+                fprintf(fid,'\n');
+            end
+            
+            % Remove the largest P_value
+            [xdummyx,ix_remove] = max(P_VALUES);
+            
+            % Message
+            fprintf(fid,'\n');
+            fprintf(fid,'Removed covariate for next level: %s on %s\n',covSearchBackward.covcatNamesTest{ix_remove},covSearchBackward.paramNamesTest{ix_remove});
+            fprintf(fid,'\n');
+            
+            % Remove covariate
+            covSearchBackward.paramNamesTest(ix_remove) = [];
+            covSearchBackward.covcatNamesTest(ix_remove) = [];
+            covSearchBackward.delta_forward(ix_remove) = [];
+            covSearchBackward.delta_backward(ix_remove) = [];
+            %%%
+            covSearchBackward.value(ix_remove) = [];
+            %%%
+            
+            % Build covariate test structure
+            x = unique(covSearchBackward.paramNamesTest);
+            covTestStructure = {};
+            %%%
+            covariateModelValues = cell(1,length(x));
+            COVestimate = cell(1,length(x));
+            %%%
+            for k2=1:length(x),
+                covTestStructure{k2}{1} = x{k2};
+            end
+            covTestStructure = covTestStructure(:);
+            for k2=1:length(covSearchBackward.paramNamesTest),
+                ix = strmatchSB(covSearchBackward.paramNamesTest{k2},x,'exact');
+                covTestStructure{ix}{end+1} = covSearchBackward.covcatNamesTest{k2};
+                %%%
+                covariateModelValues{ix}(end+1) = covSearchBackward.value(k2);
+                COVestimate{ix}(end+1) = 1;
+                %%%
+            end
+            
+            % Convert to required format
+            covariateModel                      = '';
+            for k3=1:size(covTestStructure,1),
+                if ~isempty(covTestStructure{k3}),
+                    text                        = sprintf('%s,',covTestStructure{k3}{:});
+                    covariateModel              = [covariateModel '{' text(1:end-1) '},'];
+                end
+            end
+            covariateModel                      = covariateModel(1:end-1);
+            
+            % Add structural covariates to covariate model
+            for k3=1:length(covStructural.paramNames),
+                param    = covStructural.paramNames{k3};
+                cov      = covStructural.covcatNames{k3};
+                value    = covStructural.value(k3);
+                estimate = covStructural.estimate(k3);
+                % Find where to add
+                ix = [];
+                for k4=1:size(covTestStructure,1),
+                    if strcmp(param,covTestStructure{k4}{1}),
+                        ix = k4;
+                        break;
+                    end
+                end
+                if ~isempty(ix),
+                    % add info
+                    covTestStructure{ix}{end+1} = cov;
+                    covariateModelValues{ix}(end+1) = value;
+                    COVestimate{ix}(end+1) = estimate;
+                else
+                    % new param
+                    covTestStructure{end+1}{1} = param;
+                    covTestStructure{end}{2} = cov;
+                    covariateModelValues{end+1}(1) = value;
+                    COVestimate{end+1}(1) = estimate;
+                end
+                covTestStructure = covTestStructure(:);
+            end
+            
+            % Convert to required format for the search things
+            covariateModel                      = '';
+            for k3=1:size(covTestStructure,1),
+                if ~isempty(covTestStructure{k3}),
+                    text                        = sprintf('%s,',covTestStructure{k3}{:});
+                    covariateModel              = [covariateModel '{' text(1:end-1) '},'];
+                end
+            end
+            covariateModel                      = covariateModel(1:end-1);
+            
+            % Set covariateModel
+            options.covariateModel              = covariateModel;
+            options.covariateModelValues        = covariateModelValues;
+            options.COVestimate                 = COVestimate;
+            
+            
+            % Create model
+            ModelName                           = sprintf('MODEL_%s',preFillCharSB(countModel,length(num2str(Nmaxmodels)),'0'));
+            FolderName                          = [projectPath sprintf('/BW_LEVEL_%d',levelCount)];
+            ModelFolder                         = [FolderName '/' ModelName];
+            if strcmpi(TOOL,'nonmem')
+                SBPOPcreateNONMEMproject(model,dosing,data,ModelFolder,options);
+            elseif strcmpi(TOOL,'monolix'),
+                SBPOPcreateMONOLIXproject(model,dosing,data,ModelFolder,options);
+            end
+            countModel                          = countModel + 1;
+            
+            % Run the model - do not create GoF plots
+            SBPOPrunNLMEprojectFolder(FolderName,N_PROCESSORS_PAR,N_PROCESSORS_SINGLE,1);
+            
+            % Read information
+            LEVEL_RESULTS = SBPOPfitanalysisProjectsFolderInfo(FolderName,FolderName);
+            OLD_OFV = LEVEL_RESULTS.OBJ;
+            
+            % Define things for next level
+            options.POPvalues0  = LEVEL_RESULTS.rawParameterInfo.fixedEffects.values;
+            options.IIVvalues0  = LEVEL_RESULTS.rawParameterInfo.randomEffects.values;
+            options.errorParam0 = LEVEL_RESULTS.rawParameterInfo.errorParameter.values;
+            levelModel = covariateModel;
+            levelCount = levelCount+1;
+            BackwardModelName = ModelFolder;
+            %%%
+            % Update values in covSearchBackward to estimated ones in best model
+            covInfo = LEVEL_RESULTS.rawParameterInfo.covariate;
+            
+            for k1x = 1:length(covSearchBackward.paramNamesTest),
+                paramUpdate = covSearchBackward.paramNamesTest{k1x};
+                covUpdate   = covSearchBackward.covcatNamesTest{k1x};
+                
+                % Find parameter and covariate
+                matchIX = [];
+                for kkkx=1:length(covInfo.names),
+                    ixParam = strfind(covInfo.names{kkkx},paramUpdate);
+                    ixCov = strfind(covInfo.names{kkkx},covUpdate);
+                    if ~isempty(ixParam) && ~isempty(ixCov),
+                        matchIX(end+1) = kkkx;
+                    end
+                end
+                if length(matchIX) ~= 1,
+                    error('Problem with getting covariate coefficient value.');
+                end
+                % Get the estimated value
+                value = covInfo.values(matchIX);
+                % Add value to covSearchBackward
+                covSearchBackward.value(k1x) = value;
+            end
+            %%%
+        else
+            continueBackwardSearch = 0;
+            
+            % Message
+            fprintf(fid,'* Level %d: "%s"\n',levelCount,levelModel);
+            fprintf(fid,'\n');
+            
+            for k1=1:length(covSearchBackward.paramNamesTest),
+                fprintf(fid,'%s on %s: P=%g Goal<=%g ... ',covSearchBackward.covcatNamesTest{k1},covSearchBackward.paramNamesTest{k1},P_VALUES(k1),p_backward);
+                if P_VALUES(k1)<=p_backward,
+                    fprintf(fid,'significant');
+                else
+                    fprintf(fid,'not significant');
+                end
+                fprintf(fid,'\n');
+            end
+            fprintf(fid,'\n');
+            
+        end
+        
+    end
+    
+    
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get backward results
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+BACKWARD_OFV = OLD_OFV;
+backwardModel = levelModel;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Report backward model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+fprintf(fid,'************************************\n');
+fprintf(fid,'* BACKWARD MODEL RESULTS           *\n');
+fprintf(fid,'************************************\n');
+fprintf(fid,'\n');
+
+fprintf(fid,'Backward model:            %s\n',BackwardModelName);
+fprintf(fid,'Covariates:                "%s"\n',backwardModel);
+fprintf(fid,'Objective function value:  %g\n',BACKWARD_OFV);
+fprintf(fid,'\n');
+
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Close report file
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fclose(fid);
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/08_ModelComparison/SBPOPcompareModels.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/08_ModelComparison/SBPOPcompareModels.m
new file mode 100644
index 0000000000000000000000000000000000000000..0bbc1a8bd0fe9c41245bbc8de766cb2efae93fc0
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/08_ModelComparison/SBPOPcompareModels.m
@@ -0,0 +1,389 @@
+function [] = SBPOPcompareModels(projectFolders,models,output,dosing,obsTimes,options,covNames,catNames,data)
+% [DESCRIPTION]
+% This function allows to compare the structural models for different
+% estimation results from NLME(NONMEM or MONOLIX). Useful for model selection when GOF
+% plots and other assessments suggest models are behaving very similar.
+%
+% The same structural model can be compared to several fits where this
+% model has been used. Alternatively, different structural model and
+% respective fits can be compared. In this case as many structural models
+% need to be defined as NLME(NONMEM or MONOLIX) project folders. Same order.
+%
+% It is not a VPC. The user just provides the structural model and the
+% dosing scheme to simulate. Along with parameter fits (all parameters need
+% to be in the fit but can be switched off by setting them to 0 etc.)
+%
+% Additionally, the user needs to provide a time vector for the
+% observations, the variable name in the model to compare. Etc.
+% 
+% A plot is returned, comparing the models.
+%
+% Idea: use clinically relevant dosing schedule and observation points. If
+% models do look similar, then no clinically relevant difference might be
+% present. Not only PK but also PD might be of interest! It's just a
+% supporting function and does not mean that the user can switch of the
+% brain ;-)
+%
+% [SYNTAX]
+% [] = SBPOPcompareModels(projectFolders,models,output,dosing,obsTimes)
+% [] = SBPOPcompareModels(projectFolders,models,output,dosing,obsTimes,options)
+% [] = SBPOPcompareModels(projectFolders,models,output,dosing,obsTimes,options,covNames,catNames,data)
+%
+% [INPUT]
+% projectFolders:   Cell-array with the names of the NLME(NONMEM or MONOLIX) project
+%                   folders for which to compare the models. The elements
+%                   need to include the full/relative path to the models
+% models:           Either a single structural model fitting to all the
+%                   NLME(NONMEM or MONOLIX) fits, defined in the projectFolders argument.
+%                   Or a cell-array with as many SBmodels as entries in the
+%                   projectFolders argument. In this case each model will
+%                   be paired with the corresponding NLME(NONMEM or MONOLIX) project. Same
+%                   order needs to be used.
+% output:           String with the name of the model variable to compare
+%                   In the case of multiple models the same output name
+%                   needs to be present.
+% dosing:           Dosing scheme to simulate the model for.In the case of
+%                   multiple models the same dosings need to be applicable.
+% obsTimes:         Observation times to compare the models at
+% covNames:         Cell-array with continous covariate names to take into
+%                   account (only done if the modelfit uses these)
+% catNames:         Cell-array with categorical covariate names to take into
+%                   account (only done if the modelfit uses these)
+% data:             MATLAB dataset which was used for model fitting. Standard
+%                   SBPOP dataset is assumed. The columns with the
+%                   specified covariate names have to exist
+%                   Alternatively, the path to the datafile can be
+%                   specified
+%
+% options:          Matlab structure with optional information
+%       options.N_PROCESSORS:       Number of processors for parallel computation (default: 1)
+%
+%                                   If N_PROCESSORS>1 then parallel nodes are requested via the matlabpool
+%                                   command. N_PROCESSORS models will then be run in parallel.
+%
+%
+%       options.Nsim                Number of samples from IIV
+%                                   distributions (default: 100). If
+%                                   Nsim=1 it will be set to Nsim=2 - that
+%                                   small values anyway dont really make
+%                                   sense but Nsim=1 would be messy and
+%                                   lead to an error
+%       options.quantiles           Vector with quantiles to compute for
+%                                   comparison (does only make sense if
+%                                   Nsim reasonably large) (default: [0.05 0.95])
+%       options.logY                =1: log Y axis, =0: linear Y axis
+%       options.minY                Lower limit for Y-axis, e.g. LLOQ for PK
+%       options.plotData            =0 no (by default); =1 yes
+%       options.optionsIntegrator   options for the integration.
+%                                   By default: abstol=1e-6, reltol=1e-6
+%
+% [OUTPUT]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 4th April, 2013
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle options
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try Nsim                        = options.Nsim;                 catch, Nsim                     = 100;              end
+try quantiles                   = options.quantiles;            catch, quantiles                = [0.05 0.95];      end
+try logY                        = options.logY;                 catch, logY                     = 1;                end
+try minY                        = options.minY;                 catch, minY                     = [];               end
+try plotData                    = options.plotData;             catch, plotData                 = 0;                end
+try optionsIntegrator           = options.optionsIntegrator;    catch, optionsIntegrator        = [];               end
+
+try optionsIntegrator.abstol    = optionsIntegrator.abstol;     catch, optionsIntegrator.abstol = 1e-6;             end
+try optionsIntegrator.reltol    = optionsIntegrator.reltol;     catch, optionsIntegrator.reltol = 1e-6;             end
+
+try covNames                    = covNames;                     catch, covNames                 = {};               end
+try catNames                    = catNames;                     catch, catNames                 = {};               end
+try data                        = data;                         catch, data                     = [];               end
+
+try N_PROCESSORS                = options.N_PROCESSORS;         catch, N_PROCESSORS             = 1;                end
+
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle single/multiple models
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~iscell(models),
+    % Create models variable as cell-array with as many entries as projectFolders
+    model = models;
+    models = {};
+    for k=1:length(projectFolders),
+        models{k} = model;
+    end
+    MULTIPLE_STRUCTURAL_MODELS = 0;
+else
+    % Check that same number of models and projects
+    if length(models) ~= length(projectFolders),
+        error('Number of provided models (if more than 1) need to be the same as number of NLME(NONMEM or MONOLIX) fits in projectFolders.');
+    end
+    % Check if SBmodels or chars - and convert if needed
+    modeldefs = models;
+    models = {};
+    for k=1:length(modeldefs),
+        if ischar(modeldefs{k}),
+            models{k} = SBmodel(modeldefs{k});
+        elseif isSBmodel(modeldefs{k}),
+            models{k} = modeldefs{k};
+        else
+            error('Unknown model definition.');
+        end
+    end
+    MULTIPLE_STRUCTURAL_MODELS = 1;
+end
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle data
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ischar(data),
+    % If not provided as dataset, then load it
+    data = SBPOPloadCSVdataset(data);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Adjust Nsim if needed
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if Nsim==1,
+    Nsim = 2;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle logY
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if logY==1,
+    plotType = 'semilogy';
+else
+    plotType = 'plot';
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get colors
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[colors,lines]  = getcolorsSBPOP();
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Merge model and create MEX model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+moddos = {};
+mexMODEL = {};
+for k=1:length(models),
+    moddos{k} = mergemoddosSBPOP(models{k},dosing);
+    SBPDmakeMEXmodel(moddos{k},['mexModel_' num2str(k)]);
+    mexMODEL{k} = ['mexModel_' num2str(k)];
+    rehash
+    feval(mexMODEL{k});
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check cov / cat / data
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(covNames) && isempty(data),
+    error('Continuous covariate names provided but no data to get the covariates from.');
+end
+if ~isempty(catNames) && isempty(data),
+    error('Categorical covariate names provided but no data to get the covariates from.');
+end
+if isempty(catNames) && isempty(covNames) && ~isempty(data),
+    error('Data for covariates was provided but no covariate names.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% If data and covariates provided, sample from the covariates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(data),
+    dataCOV = dataset();
+    dataCAT = dataset();
+    allID = unique(data.ID);
+    firstRowData = dataset();
+    for k=1:length(allID),
+        datak = data(data.ID==allID(k),:);
+        firstRowData = [firstRowData; datak(1,:)];
+    end
+    for k=1:length(covNames),
+        dataCOV.(covNames{k}) = firstRowData.(covNames{k});
+    end
+    for k=1:length(catNames),
+        dataCAT.(catNames{k}) = firstRowData.(catNames{k});
+    end
+    NdataSubjects = length(dataCOV);
+    sampleCovariateDosingIX = ceil(NdataSubjects*rand(1,Nsim));
+    if ~isempty(dataCOV),
+        COVvaluesSampled = double(dataCOV(sampleCovariateDosingIX,:));
+    else
+        COVvaluesSampled = [];
+        covNames = {};
+    end
+    if ~isempty(dataCAT),
+        CATvaluesSampled = double(dataCAT(sampleCovariateDosingIX,:));
+    else
+        CATvaluesSampled = [];
+        catNames = {};
+    end        
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Sample parameters for all models
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+parametersALL   = {};
+% If no data is provided
+if isempty(data),
+    % Data was not provided, do not consider covariates!
+    for k=1:length(projectFolders),
+        parametersALL{k} = SBPOPsampleNLMEfitParam(projectFolders{k},0,Nsim);
+    end
+else
+    % Data was provided! Do consider covariates
+    for k=1:length(projectFolders),
+        parametersALL{k} = SBPOPsampleNLMEfitParam(projectFolders{k},0,Nsim, covNames, COVvaluesSampled, catNames, CATvaluesSampled );
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check that parameters in all fits are available in the models
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if MULTIPLE_STRUCTURAL_MODELS == 0,
+    % single model, multiple fits
+    modelparamnames = SBparameters(moddos{1});
+    for k=1:length(parametersALL),
+        paramNamesFit = parametersALL{k}.parameterNames;
+        for k2=1:length(paramNamesFit),
+            ix = strmatchSB(paramNamesFit{k2}, modelparamnames, 'exact');
+            if isempty(ix),
+                error('SBPOPcompareModels: Parameters provided in the fit results ("projectFolders") need to be present in the structural model ("model").');
+            end
+        end
+    end
+else
+    % multiple models, multiple fits
+    for k0=1:length(moddos),
+        modelparamnames = SBparameters(moddos{k0});
+        paramNamesFit   = parametersALL{k0}.parameterNames;
+        for k2=1:length(paramNamesFit),
+            ix = strmatchSB(paramNamesFit{k2}, modelparamnames, 'exact');
+            if isempty(ix),
+                error('SBPOPcompareModels: Parameters provided in the fit results ("projectFolders") need to be present in the structural model ("model").');
+            end
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Request processors
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if N_PROCESSORS>1,
+    try
+        eval(sprintf('matlabpool %d',N_PROCESSORS));
+    catch
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Simulate all models for all samples
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+quantileInfoALL_sampled = {};
+medianInfoALL_sampled = {};
+for k=1:length(projectFolders),
+    disp(sprintf('Simulating individual parameters for model %d from %d ...',k,length(projectFolders)));
+    parameters = parametersALL{k};
+    paramNames = parameters.parameterNames;
+    % Get space for simulation results
+    outputALL  = NaN(length(obsTimes),Nsim);
+    parfor k2=1:Nsim,
+        paramValuesIndiv = parameters.parameterValuesIndividual(k2,:);
+        % Need to adjust the Tlag_input2 parameter in case it is 1e-10 => set to 0
+        ix = strmatchSB('Tlag_input2',paramNames);
+        if paramValuesIndiv(ix) < 2e-10,
+            paramValuesIndiv(ix) = 0;
+        end        
+        % Simulate the model
+        simres = SBPOPsimdosing(mexMODEL{k},dosing,obsTimes,[],paramNames,paramValuesIndiv,optionsIntegrator);    
+        % Get output
+        outputALL(:,k2) = simres.variablevalues(:,variableindexSB(moddos{k},output));
+    end
+    % Get the statistics
+    quantileInfoALL_sampled{k} = quantile(outputALL',quantiles);
+    medianInfoALL_sampled{k} = quantile(outputALL',0.5);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Release processors
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try
+    if matlabpool('size')>1,
+        matlabpool close
+    end
+catch
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Remove mexModel
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+clear mex
+for k=1:length(mexMODEL),
+    delete([mexMODEL{k} '.' mexext]);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Plot the results
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+figure(1); clf;
+legendText = {};
+for k=1:length(projectFolders),
+    % Plot population mean
+    feval(plotType,obsTimes,medianInfoALL_sampled{k},lines{k},'Color',colors(k,:),'LineWidth',3); hold on
+    % create legend text
+    legendText{end+1} = sprintf('%s, Median',projectFolders{k});
+
+    % Plot sampled results
+    quantileInfo = quantileInfoALL_sampled{k};
+    for k2=1:length(quantiles),
+        % Plot quantiles for sampling
+        feval(plotType,obsTimes,quantileInfo(k2,:),lines{k},'Color',colors(k,:)); hold on
+        % create legend text
+        legendText{end+1} = sprintf('%s, Quantile: %g',projectFolders{k},quantiles(k2));
+    end
+end
+legend(legendText,'Location','best','Interpreter','none');
+set(gca,'FontSize',12);
+grid on;
+xlabel('Time','FontSize',14);
+ylabel(output,'FontSize',14,'Interpreter','none');
+title('Comparison of different models','FontSize',14,'Interpreter','none');
+
+% Overlay the data
+if plotData,
+    plot(data.TIME,data.DV,'o','MarkerFaceColor','k'); hold on
+end
+
+% Pre-specified limits for Y-axis
+YLim = get(gca,'YLim');
+if ~isempty(minY),
+    axis([min(obsTimes) max(obsTimes) minY YLim(2)]);
+else
+    axis([min(obsTimes) max(obsTimes) get(gca,'YLim')]);
+end
+
+legend(legendText,'Location','best','Interpreter','none');
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/09_InformationContent/SBPOPassessInformationContent.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/09_InformationContent/SBPOPassessInformationContent.m
new file mode 100644
index 0000000000000000000000000000000000000000..11113332e7a5f2fddca655a28ac57232446ff963
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/09_InformationContent/SBPOPassessInformationContent.m
@@ -0,0 +1,258 @@
+function [] = SBPOPassessInformationContent(projectFolder,model,output,dosings,obsTimes,options)
+% [DESCRIPTION]
+% This function allows to predict the information content in data of (a)
+% future studies, given the planned dosing and observation schedule.
+%
+% It is simply based on sensitivity analysis wrt to changes in the model
+% parameters and correlation of the sensitivity trajectories.
+%
+% Assessed will be the impact of changes in single model parameters on the
+% readout at given observation times. The mean of these predicted
+% observations will be calculated and normalized sensitivities plotted as
+% barplot. Additionally, the correlation matrix of the normalized
+% sensitivities will be plotted for the parameters that have an impact on
+% the readout of more than a user definable threshold.
+%
+% What is this function good for?
+% If you have densly sampled data from Phase II studies and get a load of
+% sparsly sampled Phase III data in. Then this function might support you
+% in the selection of the parameters that you want to consider for
+% refitting on all data together. 
+%
+% Covariates, random effects, residual errors are NOT taken into account!
+% Population mean estimates of parameters are used!
+%
+% [SYNTAX]
+% [] = SBPOPassessInformationContent(projectFolder,model,output,dosings,obsTimes)
+% [] = SBPOPassessInformationContent(projectFolder,model,output,dosings,obsTimes,options)
+%
+% [INPUT]
+% projectFolder:    String with the name of the NLME(NONMEM or MONOLIX) project folder for
+%                   which to do the analysis. Needs to include the path to the 
+% 					project folder
+% model:            Structural model fitting to the NLME(NONMEM or MONOLIX) fits to use for
+%                   the simulation  
+% output:           Cell-array with measured output names (model variables)
+% dosings:          Cell-array with dosing schemes to simulate the model for
+%                   This allows to consider more than one future study
+% obsTimes:         Cell-array with Observation times to compare the models
+%                   at. Each entry in the cell-array corresponds to the
+%                   same entry in the "dosings" argument. Thus dosings and
+%                   obsTimes cell-arrays should have the same length
+% options:          Matlab structure with optional information
+%       options.pertSize            Relative parameter perturbations are
+%                                   used. (default: 10%)
+%       options.sensThreshold       Sensitivity threshold to select the
+%                                   parameters that have a significant
+%                                   impact on the output for subsequent
+%                                   correlation analysis. Default is 10%.
+%                                   As example, 10% means that when
+%                                   perturbing a parameter by x%, a
+%                                   significant perturbation of the output
+%                                   is considered to be a change of more
+%                                   than x/10 percent (plus or minus).
+%       options.optionsIntegrator   options for the integration.
+%                                   By default: abstol=1e-6, reltol=1e-6
+%       options.filename            Path and filename for export of figures
+%                                   to PS (Windows) or PDF (Unix). If not
+%                                   defined or empty, the figures will only
+%                                   be plotted 
+%
+% [OUTPUT]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 5th April, 2013
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle options
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try optionsIntegrator   = options.optionsIntegrator;    catch, optionsIntegrator    = [];               end
+try pertSize            = options.pertSize;             catch, pertSize             = 10;               end
+try sensThreshold       = options.sensThreshold;        catch, sensThreshold        = 10;               end
+try filename            = options.filename;             catch, filename             = '';               end
+
+try optionsIntegrator.abstol = optionsIntegrator.abstol; catch, optionsIntegrator.abstol = 1e-6;         end
+try optionsIntegrator.reltol = optionsIntegrator.reltol; catch, optionsIntegrator.reltol = 1e-6;         end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle multiple dosings / obsTimes
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~iscell(dosings),
+    dosings = {dosings};
+end
+if ~iscell(obsTimes),
+    obsTimes = {obsTimes};
+end
+if length(dosings) ~= length(obsTimes),
+    error('Number of provided dosing scenarios and number of provided observation time vectors need to match.');
+end
+
+if ~iscell(output),
+    output = {output};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Generate moddos and MEX model
+% Use one dosing ... need to be the same structure, only different times
+% and doses are allowed
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+moddos      = mergemoddosSBPOP(model,dosings{1});
+mexModel    = makeTempMEXmodelSBPD(moddos);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Get population parameters for model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+parameters = SBPOPsampleNLMEfitParam(projectFolder,0,0);
+paramNames  = parameters.parameterNames;
+paramValues = parameters.parameterValuesPopulation;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Check that parameters in all fits are available in the model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modelparamnames = SBparameters(moddos);
+for k2=1:length(paramNames),
+    ix = strmatchSB(paramNames{k2}, modelparamnames, 'exact');
+    if isempty(ix),
+        error('SBPOPassessInformationContent: Parameters provided in the fit results ("projectFolder") need to be present in the structural model ("model").');
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Simulate nominal PK parameters for all provided dosing schemes and 
+% concatenate results 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
+output_nominal = [];
+for k=1:length(dosings),
+    y = SBPOPsimdosing(mexModel,dosings{k},obsTimes{k},[],paramNames,paramValues,optionsIntegrator);
+    for k2=1:length(output),
+        output_nominal_k = y.variablevalues(:,variableindexSB(moddos,output{k2}));
+        output_nominal = [output_nominal(:); output_nominal_k(:)];
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Simulate single perturbed parameters (use all parameters in the model)
+% for all provided dosing schemes and concatenate results 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output_pert    = [];
+for k=1:length(paramNames),
+    % Get parameter to perturb and new value
+    paramName               = paramNames{k};
+    paramValuePert          = paramValues(k)*(1+pertSize/100);
+    % Construct new full perturbed parameter vector
+    paramValues_Pert        = paramValues;
+    paramValues_Pert(k)     = paramValuePert;
+    
+    % Simulate all dosing scenarios
+    output_pert_k = [];
+    for k2=1:length(dosings),
+        y                   = SBPOPsimdosing(mexModel,dosings{k2},obsTimes{k2},[],paramNames,paramValues_Pert,optionsIntegrator);
+        for k3=1:length(output),
+            output_pert_k2      = y.variablevalues(:,variableindexSB(moddos,output{k3}));
+            output_pert_k       = [output_pert_k(:); output_pert_k2(:)];
+        end
+    end
+
+    % Collect output
+    output_pert             = [output_pert output_pert_k];
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Calculate sensitivity trajectories
+% Normalize by perturbation size
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Expand output_nominal
+output_nominal_expanded = output_nominal(:,ones(1,length(paramNames)));
+% Normalized sensitivity
+Sn = 100*(output_pert - output_nominal_expanded)./output_nominal_expanded/pertSize*100;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Calculate metric
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+meanSensitivity   = nanmean(abs(Sn));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Prepare output to file if needed
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(filename),
+    [p,f] = fileparts(filename);
+    % Create output folder if not yet existing
+    warning off;
+    mkdir(p);
+    warning on
+    % Start the file
+    startNewPrintFigureSBPOP(filename);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Display sensitivities
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+figure(1); clf
+bar([1:length(meanSensitivity)],meanSensitivity);
+paramNamesPlot = paramNames;
+paramNamesPlot{10} = 'ka';
+paramNamesPlot{11} = 'Tlag';
+set(gca,'XTickLabel',paramNamesPlot)
+grid on;
+set(gca,'FontSize',12)
+xlabel('PK Parameters','FontSize',14);
+ylabel('Normalized sensitivities [%]','FontSize',14);
+if ~isempty(filename),
+    printFigureSBPOP(gcf,filename)
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Assess correlation of the most important parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ix_important        = find(abs(meanSensitivity) >= sensThreshold);
+param_corr_Names    = paramNames(ix_important);
+X = [];
+for k=1:length(param_corr_Names),
+    ix = strmatchSB(param_corr_Names{k},paramNames,'exact');
+    X(:,k) = Sn(:,ix);
+end
+corr_param = abs(corr(X,'type','Pearson','rows','pairwise','tail','both'))
+
+% Plot results
+figure(2); clf;
+pcolor([corr_param zeros(length(corr_param),1); zeros(1,length(corr_param)) 0])
+axis square;
+colorbar('EastOutside');
+set(gca,'XTick',[1.5:length(param_corr_Names)+0.5]);
+set(gca,'XTickLabel',param_corr_Names);
+set(gca,'YTick',[1.5:length(param_corr_Names)+0.5]);
+set(gca,'YTickLabel',param_corr_Names);
+colormap('Bone');
+set(gca,'FontSize',12)
+title('Predicted correlations of parameters with significant impact','FontSize',14,'Interpreter','none');
+if ~isempty(filename),
+    printFigureSBPOP(gcf,filename)
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Close export to file
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(filename),
+    convert2pdfSBPOP(filename);
+    close all
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/10_VPC/SBPOPcreateStratifiedVPC.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/10_VPC/SBPOPcreateStratifiedVPC.m
new file mode 100644
index 0000000000000000000000000000000000000000..376253d33e8fea861cb8a6bd8b602a4119f0d037
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/10_VPC/SBPOPcreateStratifiedVPC.m
@@ -0,0 +1,233 @@
+function [] = SBPOPcreateStratifiedVPC(projectFolder,model,dosing,output,output_YTYPE,covNames,catNames,data,groupName,regressionVariables,options)
+% [DESCRIPTION]
+% This function creates a stratified VPC for a given model on a given
+% dataset. The data is expected to contain the column "groupName" that is 
+% used for stratification. The doses and dosing schedule and the covariates
+% are obtained from the dataset. 
+%
+% Assumption: ADM=1: IV, ADM=2: 1st order absorption
+% 
+% THIS FUNCTION NEEDS CHANGE IF V2 of model building is used!!!
+%
+% [SYNTAX]
+% [] = SBPOPcreateStratifiedVPC(projectFolder,model,dosing,output,output_YTYPE,covNames,catNames,data,groupName,regressionVariables)
+% [] = SBPOPcreateStratifiedVPC(projectFolder,model,dosing,output,output_YTYPE,covNames,catNames,data,groupName,regressionVariables,options)
+%
+% [INPUT]
+% projectFolder:    Cell-array with the name of the Monolix project folder.
+%                   Needs to include the full path to the folder.
+% model:            Structural model fitting to the Monolix fit to use for
+%                   the simulation  
+% dosing:           Template dosing object to define what type of dosing
+%                   the model does expect. So far only ADM type 1 (IV) and
+%                   ADM type 2 (first order absorption) is supported. First
+%                   order absorption can be coded explicitly in the model
+%                   or implicitly, therefor a dosing scheme needs to be
+%                   provided. INPUT1 always needs to be infusion. INPUT2
+%                   can be ABSORPTION1 if coded implicitly or BOLUS if
+%                   coded explicitly.  
+% output:           String with the name of the model variable to compare
+% output_YTYPE:     YTYPE number of considered observation in dataset
+% covNames:         Cell-array with names of continuous covariates. Only 
+%                   the ones used in the model will be considered 
+% catNames:         Cell-array with names of categorical covariates. Only 
+%                   the ones used in the model will be considered 
+% data:             Dataset for the VPC - covariates will be sampled from
+%                   this dataset
+% groupName:        The name of the column after which to stratify the VPC.
+%                   The entries of the column need to be numeric and
+%                   ideally should be unique for same dosing regimen 
+% regressionVariables: Cell-array with names of regression parameters that
+%                   are defined in the dataset and which need to be passed
+%                   to the model. These parameters will also be sampled.
+%
+% options:          Matlab structure with optional information
+%       options.filename            Filename, including path, for
+%                                   generated output PS (windows) or PDF
+%                                   (unix) file (default: VPC.ps/pdf in
+%                                   current folder)
+%       options.N_PROCESSORS:       Number of processors for parallel computation (default: 1)
+%
+%                                   If N_PROCESSORS>1 then parallel nodes are requested via the matlabpool
+%                                   command. N_PROCESSORS models will then be run in parallel.
+%
+%       options.NTRIALS             Number of TRIALS to simulate to
+%                                   determine simulation quantiles and
+%                                   confidence intervals. (default: 100).  
+%       options.quantiles           Vector with quantiles to compute for
+%                                   comparison (does only make sense if
+%                                   Nsim reasonably large) (default: [0.05 0.95])
+%       options.logY                =1: log Y axis, =0: linear Y axis
+%       options.optionsIntegrator   options for the integration.
+%                                   By default: abstol=1e-6, reltol=1e-6
+%       options.plotIndivLines      =1: Connect individual data points with
+%                                   lines (default: 0)
+%       options.showDataQuantiles   =1: Show lines for the observation
+%                                   quantiles (default: 0)
+%       options.numbins             Number of bins for the calculation of
+%                                   the observation quantiles
+%       options.binTIMElow          Vector with lower bound for binning to
+%                                   calculate data quantiles. If defined it
+%                                   is used instead of numbins
+%       options.bins_mean           Vector with center values of bins to
+%                                   calculate data quantiles. If defined it 
+%                                   is used instead of numbins
+%       options.bins_lookaround     Vector with values for positive and
+%                                   negative "lookaround" for quantile
+%                                   calculation 
+%       options.quantileLogX        =0: use numbins bins for quantile
+%                                   calculation, spaced uniformly over
+%                                   LINEAR x-axis 
+%                                   =1: use numbins bins for quantile
+%                                   calculation, spaced uniformly over
+%                                   LOG x-axis (negative times will be
+%                                   ignored)
+%       options.nTimePoints         Number time points to simulate - spaced
+%                                   equidistantly (default: 100)
+%                                   If obsTimes defined, nTimePoints not
+%                                   used.
+%       options.obsTimes            Vector with time points to simulate. 
+%                                   If obsTimes defined, nTimePoints not
+%                                   used. Max time of simulation is last
+%                                   observation + a small delta
+%       options.dataexportPath      Path to where to export the
+%                                   simulations. For simplicity saved as 
+%                                   "TRT identifier.mat" file. Not exported
+%                                   if path undefined or '' (default)
+%
+% [OUTPUT]
+% Figures, exported to PS (Windows) or PDF (Unix) in a file that can be
+% user selected or by default VPC.ps/pdf in the current folder.
+%
+% simulatedData: The Nsim individual simulations at the obsTimes timepoints
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 8th April, 2013
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get options needed for this function and handle defaults
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try filename        = options.filename;          catch, filename         = 'VPC';    end
+try dataexportPath  = options.dataexportPath;    catch, dataexportPath   = '';       end
+try N_PROCESSORS    = options.N_PROCESSORS;      catch, N_PROCESSORS     = 1;        end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get data header
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+header = get(data,'VarNames');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle missing TINF column
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(strmatchSB('TINF',header,'exact')),
+    if ~isempty(strmatchSB('RATE',header,'exact')),
+        data.TINF = data.AMT./data.RATE;
+        data.TINF(isnan(data.TINF)) = 0;
+        data.TINF(isinf(abs(data.TINF))) = 0;
+    else
+        error('Please ensure that either a RATE or a TINF column present in the VPC data.');
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Start output figure and create potential output folder if non existant
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[p,f,e] = fileparts(filename);
+warning off
+mkdir(p);
+warning on
+startNewPrintFigureSBPOP(filename);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create potential dataexportPath if non existent
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(dataexportPath),
+    try rmdir(dataexportPath,'s'); catch, end; mkdir(dataexportPath);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Request processors
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if N_PROCESSORS>1,
+    try
+        eval(sprintf('matlabpool %d',N_PROCESSORS));
+    catch
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run it
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+allGroups = unique(data.(groupName));
+
+for k=1:length(allGroups),
+    sprintf('%s: %d',groupName,allGroups(k));
+    
+    % Stratify by provided groupName
+    dataVPC = data(data.(groupName)==allGroups(k),:);
+    
+    % Set titleText
+    options.titleText = sprintf('%s: %d',groupName,allGroups(k));
+
+    % If not more than 1 subject, then do not do the VPC
+    if length(unique(dataVPC.ID))>1,
+        % If not more than 1 observations present then do not do the VPC
+        dataOBS = dataVPC(dataVPC.YTYPE==output_YTYPE,:);
+        if length(dataOBS) > 1,
+            % Generate the VPC for single group
+            simulatedData = SBPOPcreateVPC(projectFolder,model,dosing,output,output_YTYPE,covNames,catNames,regressionVariables,dataVPC,options);
+        else
+            figure(1); clf;
+            title(sprintf('%s: %d - has not more than 1 observation => VPC omitted.',groupName,allGroups(k)),'Interpreter','none');
+        end    
+    else
+        figure(1); clf;
+        title(sprintf('%s: %d - has not more than 1 subject => VPC omitted.',groupName,allGroups(k)),'Interpreter','none');
+    end
+    
+    % Print the figure
+    printFigureSBPOP(gcf,filename);
+    % Save the simulated data as MAT file if desired
+    if ~isempty(dataexportPath),
+        datafile = [dataexportPath '/simData_' groupName '_' num2str(allGroups(k))];
+        save(datafile,'simulatedData');
+    end
+    
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Release processors
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try
+    if matlabpool('size')>1,
+        matlabpool close
+    end
+catch
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Finalize the figure creation
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+convert2pdfSBPOP(filename);
+close all
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/10_VPC/SBPOPcreateVPC.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/10_VPC/SBPOPcreateVPC.m
new file mode 100644
index 0000000000000000000000000000000000000000..e2797659676e6d79ff5269de76345144981b432d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/10_VPC/SBPOPcreateVPC.m
@@ -0,0 +1,334 @@
+function [simulatedData] = SBPOPcreateVPC(projectFolder,model,dosing,output,outputTYPE,covNames,catNames,regressionVariables,data,options)
+% [DESCRIPTION]
+% This function creates a VPC for a given model on a given dataset. The 
+% data is already expected to be subgrouped. The doses and dosing schedule
+% and the covariates are obtained from the dataset.
+% Assumption: ADM=2: IV, ADM=1: 1st order absorption
+% 
+% [SYNTAX]
+% [simulatedData] = SBPOPcreateVPC(projectFolder,model,output,outputTYPE,covNames,catNames,dataVPC,options)
+%
+% [INPUT]
+% projectFolder:    Cell-array with the name of the Monolix project folder.
+%                   Needs to include the full path to the folder.
+% model:            Structural model fitting to the Monolix fit to use for
+%                   the simulation  
+% dosing:           Template dosing object to define what type of dosing
+%                   the model does expect. So far only ADM type 1 (IV) and
+%                   ADM type 2 (first order absorption) is supported. First
+%                   order absorption can be coded explicitly in the model
+%                   or implicitly, therefor a dosing scheme needs to be
+%                   provided. INPUT1 always needs to be infusion. INPUT2
+%                   can be ABSORPTION1 if coded implicitly or BOLUS if
+%                   coded explicitly.  
+% output:           String with the name of the model variable to compare
+% outputTYPE:       YTYPE number of considered observation in dataset
+% covNames:         Cell-array with names of continuous covariates. Only 
+%                   the ones used in the model will be considered 
+% catNames:         Cell-array with names of categorical covariates. Only 
+%                   the ones used in the model will be considered 
+% regressionVariables: Cell-array with names of regression parameters that
+%                   are defined in the dataset and which need to be passed
+%                   to the model. These parameters will also be sampled.
+% data:             Dataset for the VPC - covariates will be sampled from
+%                   this dataset
+%
+% options:          Matlab structure with optional information
+%       options.NTRIALS             Number of TRIALS to simulate to
+%                                   determine simulation quantiles and
+%                                   confidence intervals. (default: 100).  
+%       options.quantiles           Vector with quantiles to compute for
+%                                   comparison (does only make sense if
+%                                   Nsim reasonably large) (default: [0.05 0.95])
+%       options.logY                =1: log Y axis, =0: linear Y axis
+%       options.minY                numeric value for lower value of Y axis
+%       options.maxY                numeric value for upper value of Y axis
+%       options.optionsIntegrator   options for the integration.
+%                                   By default: abstol=1e-6, reltol=1e-6
+%       options.plotIndivLines      =1: Connect individual data points with
+%                                   lines (default: 0)
+%       options.showDataQuantiles   =1: Show lines for the observation
+%                                   quantiles (default: 0)
+%       options.numbins             Number of bins for the calculation of
+%                                   the observation quantiles
+%       options.bins_mean           Vector with center values of bins to
+%                                   calculate data quantiles. If defined it 
+%                                   is used instead of numbins
+%       options.bins_lookaround     Vector with values for positive and
+%                                   negative "lookaround" for quantile
+%                                   calculation 
+%       options.quantileLogX        =0: use numbins bins for quantile
+%                                   calculation, spaced uniformly over
+%                                   LINEAR x-axis 
+%                                   =1: use numbins bins for quantile
+%                                   calculation, spaced uniformly over
+%                                   LOG x-axis (negative times will be
+%                                   ignored)
+%       options.nTimePoints         Number time points to simulate - spaced
+%                                   equidistantly (default: 100)
+%                                   If obsTimes defined, nTimePoints not
+%                                   used.
+%       options.obsTimes            Vector with time points to simulate. 
+%                                   If obsTimes defined, nTimePoints not
+%                                   used. Max time of simulation is last
+%                                   observation + a small delta
+%
+% [OUTPUT]
+% A MATLAB figure
+%
+% simulatedData: The Nsim individual simulations at the obsTimes timepoints
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 8th April, 2013
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%% Handle optional values
+try quantiles = options.quantiles;                      catch, quantiles = [0.05 0.95];  options.quantiles = quantiles;  end %#ok<*CTCH>
+try numbins = options.numbins;                          catch, numbins = 15;                                             end
+try bins_mean = options.bins_mean;                      catch, bins_mean = [];                                           end
+try bins_lookaround = options.bins_lookaround;          catch, bins_lookaround = [];                                     end
+try quantileLogX = options.quantileLogX;                catch, quantileLogX = 0;                                         end
+try plotIndivLines = options.plotIndivLines;            catch, plotIndivLines = 0;                                       end
+try showDataQuantiles = options.showDataQuantiles;      catch, showDataQuantiles = 0;                                    end
+try titleText = options.titleText;                      catch, titleText = '';                                           end
+try nTimePoints = options.nTimePoints;                  catch, nTimePoints = 100;                                        end
+try obsTimes = options.obsTimes;                        catch, obsTimes = [];                                            end
+try logY = options.logY;                                catch, logY = [];                                                end
+try minY = options.minY;                                catch, minY = [];                                                end
+try maxY = options.maxY;                                catch, maxY = [];                                                end
+ 
+%% Define population / covariates to use - and regression variables
+% This is done based on the data and included subjects
+% But only on the subjects that received doses
+dataCOV = dataset();
+dataCAT = dataset();
+dataREGRESSION = dataset();
+
+allID = unique(data.ID);
+firstRowData = dataset();
+for k=1:length(allID),
+    datak = data(data.ID==allID(k),:);
+    firstRowData = [firstRowData; datak(1,:)];
+end
+for k=1:length(covNames),
+    dataCOV.(covNames{k}) = firstRowData.(covNames{k});
+end
+for k=1:length(catNames),
+    dataCAT.(catNames{k}) = firstRowData.(catNames{k});
+end
+for k=1:length(regressionVariables),
+    dataREGRESSION.(regressionVariables{k}) = firstRowData.(regressionVariables{k});
+end
+
+%% Determine the dosing schedules (order of dosing schedules matches the 
+% order of the covariates and for each dosing schedule the corresponding
+% set of covariates need to be used)
+allID = unique(data.ID);
+dataDOSING = [];
+for k=1:length(allID),
+    datak = data(data.ID == allID(k) & data.YTYPE==0,:);
+    if ~isempty(datak),
+        TIME_X = datak.TIME;
+        AMT_X  = datak.AMT;
+        ADM_X  = datak.ADM;
+        TINF_X = datak.TINF;
+    else
+        TIME_X = 0;
+        AMT_X  = 0;
+        ADM_X  = 1;
+        TINF_X = 1e-10;
+    end
+    
+    if k==1,
+        dataDOSING.TIME = TIME_X;
+        dataDOSING.DOSE = AMT_X;
+        dataDOSING.ADM  = ADM_X;
+        dataDOSING.TINF = datak.TINF;
+    else
+        dataDOSING(k).TIME = TIME_X;
+        dataDOSING(k).DOSE = AMT_X;
+        dataDOSING(k).ADM  = ADM_X;
+        dataDOSING(k).TINF = TINF_X;
+    end
+end
+
+%% Create dosing schemes
+% Check inputs in dosing scheme
+ds = struct(dosing);
+if length(ds.inputs) ~= length(unique(data.ADM)),
+    warning('Number of INPUTS in provided dosing scheme does not match number of unique non-zero ADM entries in the dataset.');
+end
+
+% Create the dosings based on the dataset info
+dosings = {};
+ALLOWED_ADM_IDENTIFIERS = [1 2 99];  % SC/ORAL, IV, PLACEBO
+for k=1:length(dataDOSING),
+    x = dataDOSING(k);
+    % Fill it with content for ADM values (2=INFUSION, 1=ABSORPTION1)
+    ds = struct(dosing);
+    % Cycle through the inputs and fill them with content
+    for k2=1:length(ds.inputs),
+        % Get the type of the input
+        type = ds.inputs(k2).type;
+        % Check if this input present in dataset
+        ix = find(x.ADM==ALLOWED_ADM_IDENTIFIERS(k2));
+        if strcmp(type,'INFUSION'),            
+            if ~isempty(ix),
+                % ADM type present in dataset => handle it
+                ds.inputs(k2).time = x.TIME(ix)';
+                ds.inputs(k2).Tlag = 0;
+                ds.inputs(k2).D    = x.DOSE(ix)';
+                ds.inputs(k2).parameters.value = x.TINF(ix)';
+                % Check if 0 TINF time (leads to error in simulation)
+                if ~isempty(find(ds.inputs(k2).parameters.value==0)),
+                    error('Infusion time TINF for some IV (ADM=2) doses is 0. This is not allowed.');
+                end
+            else
+                ds.inputs(k2).time = 0;
+                ds.inputs(k2).Tlag = 0;
+                ds.inputs(k2).D    = 0;
+                ds.inputs(k2).parameters.value = 1;
+            end
+        elseif strcmp(type,'ABSORPTION1'),
+            if ~isempty(ix),
+                % ADM type present in dataset => handle it
+                ds.inputs(k2).time = x.TIME(ix)';
+                ds.inputs(k2).Tlag = 0;
+                ds.inputs(k2).D    = x.DOSE(ix)';
+                ds.inputs(k2).parameters.value = ones(1,length(x.TIME(ix)));
+            else
+                ds.inputs(k2).time = 0;
+                ds.inputs(k2).Tlag = 0;
+                ds.inputs(k2).D    = 0;
+                ds.inputs(k2).parameters.value = 1;
+            end
+        elseif strcmp(type,'BOLUS'),
+            if ~isempty(ix),
+                % ADM type present in dataset => handle it
+                ds.inputs(k2).time = x.TIME(ix)';
+                ds.inputs(k2).Tlag = 0;
+                ds.inputs(k2).D    = x.DOSE(ix)';
+                ds.inputs(k2).parameters = [];
+            else
+                ds.inputs(k2).time = 0;
+                ds.inputs(k2).Tlag = 0;
+                ds.inputs(k2).D    = 0;
+                ds.inputs(k2).parameters = [];
+            end
+        else
+            error('INPUT type "%s", provided in dosing scheme, not yet handled.',type)
+        end
+    end
+    % Get dosing object
+    dosings{k} = SBPOPdosing(ds);
+end
+
+%% Get observation data of interest only
+dataOBS = data(data.YTYPE==outputTYPE & data.MDV==0,:);
+
+%% Create observation time vector
+minTIME     = min(dataOBS.TIME);
+maxTIME     = max(dataOBS.TIME);
+deltaTIME   = 1.05*(maxTIME-minTIME);
+if isempty(obsTimes),
+    obsTimes    = [minTIME:deltaTIME/(nTimePoints-1):minTIME+deltaTIME];
+else
+    % Adjust max observation time for simulation based on maxTIME
+    obsTimes(obsTimes>maxTIME) = [];
+    obsTimes(end+1) = minTIME+deltaTIME;
+end
+
+%% Produce simulation results
+[legendText,simulatedData] = simulateVPCSBPOP(projectFolder,model,output,obsTimes,dosings,covNames,catNames,dataCOV,dataCAT,regressionVariables,dataREGRESSION,options);
+
+%% Plot data markers
+plot(dataOBS.TIME, dataOBS.DV,'k.','MarkerSize',20,'Color',0.65*[1 1 1])
+legendText{end+1} = 'Observed data';
+
+%% Determine and plot data quantiles
+if showDataQuantiles,
+    % If quantileLogX == 1 => remove TIME values smaller than 0
+    if quantileLogX,
+        dataOBS(dataOBS.TIME<=0,:) = [];
+        warning('If logarithmic X-axis considered for binning, Samples with TIME<=0 will not be considered!');
+    end
+    
+    % Handle undefined low and high bin values
+    if isempty(bins_mean),
+        % Use numbins for binning
+        binningInfo = numbins;
+    else
+        binningInfo = {bins_mean,bins_lookaround};
+    end
+        
+    % Median
+    [xbin_median,ybin_median] = binnedquantilesSB(dataOBS.TIME,dataOBS.DV,0.5,binningInfo,quantileLogX);
+    plot(xbin_median, ybin_median, 'k--','LineWidth',2);
+    legendText{end+1} = 'Observed data - Median';
+    
+    % Defined quantiles
+    xbin_quantiles = {};
+    ybin_quantiles = {};
+    for k=1:length(quantiles),
+        [xbin,ybin] = binnedquantilesSB(dataOBS.TIME,dataOBS.DV,quantiles(k),binningInfo,quantileLogX);
+        plot(xbin, ybin, 'k--','LineWidth',2);
+        legendText{end+1} = sprintf('Observed data - Quantile: %g', quantiles(k));
+    end
+end
+
+%% Plot data lines
+if plotIndivLines,
+    allID = unique(data.ID); 
+    for k=1:length(allID), 
+        datak = dataOBS(dataOBS.ID==allID(k),:); 
+        plot(datak.TIME, datak.DV,'--','Color',0.7*[1 1 1]); 
+    end
+end
+
+%% Set axes
+YLim = get(gca,'YLim');
+minY_use = YLim(1);
+maxY_use = YLim(2);
+
+if ~isempty(minY),
+    minY_use = minY;
+end
+if ~isempty(maxY),
+    maxY_use = maxY;
+end
+axis([min(obsTimes) max(obsTimes) minY_use maxY_use]); 
+
+%% Set linlogY
+if logY,
+    set(gca,'YScale','log');
+else
+    set(gca,'YScale','linear');
+end
+
+%% Annotate plot
+legend(legendText,'Location','best','Interpreter','none');
+set(gca,'FontSize',10);
+grid on;
+xlabel(['Time [' strrep(dataOBS.TIME_UNIT{1},':::',' ') ']'],'FontSize',14,'Interpreter','none');
+ylabel([strrep(dataOBS.NAME{1},':::',' ') '[' strrep(dataOBS.UNIT{1},':::',' ') ']'],'FontSize',14,'Interpreter','none');
+title(titleText,'FontSize',16,'Interpreter','none');
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/10_VPC/auxiliary/simulateVPCSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/10_VPC/auxiliary/simulateVPCSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..e44ae607a2f09c8f5c72cfac137fef2475975124
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/10_VPC/auxiliary/simulateVPCSBPOP.m
@@ -0,0 +1,286 @@
+function [legendText,outputALL] = simulateVPCSBPOP(projectFolder,model,output,obsTimes,dosings,covNames,catNames,dataCOV,dataCAT,regressionVariables,dataREGRESSION,options)
+% [DESCRIPTION]
+% This function is an auxiliary function for VPC generation.
+%
+% [SYNTAX]
+% [legendText] = simulateVPCSBPOP(projectFolder,model,output,dosing,obsTimes,covNames,catNames,dataCOV,dataCAT,options)
+%
+% [INPUT]
+% projectFolder:    Cell-array with the name of the NLME(NONMEM or MONOLIX) project folder.
+%                   Needs to include the full path to this folder
+% model:            Structural model fitting to the Monolix fit to use for
+%                   the simulation  
+% output:           String with the name of the model variable to compare
+% obsTimes:         Observation times to use for plotting
+% dosings:          Cell-array with dosing schemes matching in order with
+%                   the dataCOV and dataCAT entries. For sampling each
+%                   corresponding dosing scheme, dataCOV and dataCAT will
+%                   be selected
+% covNames:         Cell-array with names of continuous covariates. Only 
+%                   the ones used in the model will be considered 
+% catNames:         Cell-array with names of categorical covariates. Only 
+%                   the ones used in the model will be considered 
+% dataCOV:          MATLAB dataset with continuous covariates in same
+%                   order as in covNames
+%                   From these, the Nsim covariate combinations will be
+%                   sampled using a uniform distribution
+% dataCAT:          MATLAB dataset with categorical covariates in same
+%                   order as in covNames
+%                   From these, the Nsim covariate combinations will be
+%                   sampled using a uniform distribution
+% regressionVariables: Cell-array with names of regression parameters that
+%                   are defined in the dataset and which need to be passed
+%                   to the model. These parameters will also be sampled.
+% dataREGRESSION:   MATLAB dataset with regression variable values in same
+%                   order as in regressionVariables
+%                   From these, the Nsim regression variable combinations
+%                   will be sampled using a uniform distribution
+%
+% options:          Matlab structure with optional information
+%       options.NTRIALS             Number of TRIALS to simulate to
+%                                   determine simulation quantiles and
+%                                   confidence intervals. (default: 100).  
+%       options.quantiles           Vector with quantiles to compute for
+%                                   comparison (does only make sense if
+%                                   Nsim reasonably large) (default: [0.05 0.95])
+%       options.logY                =1: log Y axis, =0: linear Y axis
+%       options.optionsIntegrator   options for the integration.
+%                                   By default: abstol=1e-6, reltol=1e-6
+%
+% [OUTPUT]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 4th April, 2013
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle options
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try NTRIALS             = options.NTRIALS;               catch, NTRIALS              = 100;              end %#ok<*CTCH>
+try quantiles           = options.quantiles;             catch, quantiles            = [0.05 0.95];      end
+try logY                = options.logY;                  catch, logY                 = 1;                end
+try optionsIntegrator   = options.optionsIntegrator;     catch, optionsIntegrator    = [];               end
+
+try optionsIntegrator.abstol = optionsIntegrator.abstol; catch, optionsIntegrator.abstol = 1e-6;         end
+try optionsIntegrator.reltol = optionsIntegrator.reltol; catch, optionsIntegrator.reltol = 1e-6;         end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine number of needed simulations
+% Nsim = NTRIALS*number of subjects in treatment arm
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+NdataSubjects = length(dosings);
+Nsim = NTRIALS*NdataSubjects;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Sample Nsim covariate and regression variable values from the provided information
+% Use uniform distribution for sampling
+% Also sample the corresponding dosings - needed to be sure to match
+% relative dosing (mg/kg, mg/m2, etc.)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+NdataSubjects = length(dosings);
+sampleCovariateDosingIX = ceil(NdataSubjects*rand(1,Nsim));
+if ~isempty(dataCOV),
+    COVvaluesSampled = double(dataCOV(sampleCovariateDosingIX,:));
+else
+    COVvaluesSampled = [];
+    covNames = {};
+end
+if ~isempty(dataCAT),
+    CATvaluesSampled = double(dataCAT(sampleCovariateDosingIX,:));
+else
+    CATvaluesSampled = [];
+    catNames = {};
+end
+if ~isempty(dataREGRESSION),
+    REGRESSIONvaluesSampled = double(dataREGRESSION(sampleCovariateDosingIX,:));
+else
+    REGRESSIONvaluesSampled = [];
+    regressionVariables = {};
+end
+DosingsSampled   = dosings(sampleCovariateDosingIX);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Merge model and create MEX model
+% Same general dosing scheme always - use first for merging
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+moddos          = mergemoddosSBPOP(model,DosingsSampled{1});
+SBPDmakeMEXmodel(moddos,'mexModel');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Get individual parameters for model simulation
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+parameters = SBPOPsampleNLMEfitParam(projectFolder,0,Nsim,  covNames, COVvaluesSampled, catNames, CATvaluesSampled);
+paramNames  = parameters.parameterNames;
+paramValuesInd = parameters.parameterValuesIndividual;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check that parameters in all fits are available in the model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modelparamnames = SBparameters(moddos);
+for k2=1:length(paramNames),
+    ix = strmatchSB(paramNames{k2}, modelparamnames, 'exact');
+    if isempty(ix),
+        error('simulateVPCSBPOP: Parameters provided in the fit results ("projectFolder") need to be present in the structural model ("model").');
+    end
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%
+% Simulate all models for all individual 
+% samples with individual dosing schemes
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+disp(sprintf('Simulating individual parameters ...')); %#ok<*DSPS>
+% Get space for simulation results
+outputALL  = NaN(length(obsTimes),Nsim);
+if ~isempty(regressionVariables),
+    paramChangeNames  = [paramNames regressionVariables];
+    paramChangeValues = [paramValuesInd REGRESSIONvaluesSampled]; 
+else
+    paramChangeNames = paramNames;    
+    paramChangeValues = paramValuesInd; 
+end
+FAILED = [];
+parfor k2=1:Nsim,
+    % Simulate the model
+    FAILEDk = 1;
+    while FAILEDk,
+        try
+            paramSimValues = paramChangeValues(k2,:);
+            % Need to adjust the Tlag_input1 parameter in case it is 1e-10 => set to 0
+            ix = strmatchSB('Tlag_input1',paramChangeNames);
+            if paramSimValues(ix) < 2e-10,
+                paramSimValues(ix) = 0;
+            end
+            % Simulate
+            simres = SBPOPsimdosing('mexModel',DosingsSampled{k2},obsTimes,[],paramChangeNames,paramSimValues,optionsIntegrator);
+            % Get output
+            outputALL(:,k2) = simres.variablevalues(:,variableindexSB(moddos,output));
+            %
+            FAILEDk = 0;
+        catch
+            outputALL(:,k2) = NaN(length(obsTimes),1);
+            disp(lasterr); %#ok<*LERR>
+            if strcmp(lasterr,sprintf('Error using mexModel\nCVODE Error: CV_ERR_FAILURE')),
+                disp('Please consider setting the absolute integration tolerance to more strict levels AND/OR remove PD readouts for excessive times after last dose!');
+            end
+            %
+            FAILEDk = 1;
+        end
+    end
+    FAILED(k2) = FAILEDk;
+end
+FAILED_number = sum(FAILED) %#ok<NASGU>
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%
+% Remove mexModel
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+clear mex
+delete(['mexModel.' mexext]);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get the statistics - and confidence intervals
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+outputALL = outputALL';
+median_all = [];
+quantile1_all = [];
+quantile2_all = [];
+for k=1:NTRIALS,
+    outputALLk = outputALL((k-1)*NdataSubjects+1:k*NdataSubjects,:);
+    mediank    = quantile(outputALLk,0.5);
+    quantile1k = quantile(outputALLk,min(quantiles));
+    quantile2k = quantile(outputALLk,max(quantiles));
+    
+    % collect
+    median_all = [median_all; mediank];
+    quantile1_all = [quantile1_all; quantile1k];
+    quantile2_all = [quantile2_all; quantile2k];
+end
+% Determine median overall and uncertainty bounds (10/90%)
+median_ALL_50 = quantile(median_all,0.5);
+median_ALL_10 = quantile(median_all,0.05);
+median_ALL_90 = quantile(median_all,0.95);
+
+quantile1_ALL_10 = quantile(quantile1_all,0.05);
+quantile1_ALL_90 = quantile(quantile1_all,0.95);
+
+quantile2_ALL_10 = quantile(quantile2_all,0.05);
+quantile2_ALL_90 = quantile(quantile2_all,0.95);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Plot the results
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+figure(1); clf;
+legendText = {};
+% Remove 0 values if logY
+if logY,
+    ix_zero = find(median_ALL_10==0);
+    obsTimes(ix_zero) = [];
+    quantile1_ALL_10(ix_zero) = [];
+    quantile1_ALL_90(ix_zero) = [];
+    quantile2_ALL_10(ix_zero) = [];
+    quantile2_ALL_90(ix_zero) = [];
+    median_ALL_10(ix_zero) = [];
+    median_ALL_90(ix_zero) = [];
+    median_ALL_50(ix_zero) = [];
+
+    ix_zero = find(quantile1_ALL_10==0);
+    obsTimes(ix_zero) = [];
+    quantile1_ALL_10(ix_zero) = [];
+    quantile1_ALL_90(ix_zero) = [];
+    quantile2_ALL_10(ix_zero) = [];
+    quantile2_ALL_90(ix_zero) = [];
+    median_ALL_10(ix_zero) = [];
+    median_ALL_90(ix_zero) = [];
+    median_ALL_50(ix_zero) = [];
+
+    ix_zero = find(quantile2_ALL_10==0);
+    obsTimes(ix_zero) = [];
+    quantile1_ALL_10(ix_zero) = [];
+    quantile1_ALL_90(ix_zero) = [];
+    quantile2_ALL_10(ix_zero) = [];
+    quantile2_ALL_90(ix_zero) = [];
+    median_ALL_10(ix_zero) = [];
+    median_ALL_90(ix_zero) = [];
+    median_ALL_50(ix_zero) = [];
+end
+% Plot quantiles
+SBPOPplotfill(obsTimes,quantile1_ALL_10,quantile1_ALL_90,[0.8 0.8 1],1,[0.8 0.8 1]); hold on
+SBPOPplotfill(obsTimes,quantile2_ALL_10,quantile2_ALL_90,[0.8 0.8 1],1,[0.8 0.8 1]); hold on
+SBPOPplotfill(obsTimes,median_ALL_10,median_ALL_90,[1 0.8 0.8],1,[1 0.8 0.8]); hold on
+% Plot population median
+plot(obsTimes,median_ALL_50,'-','Color',[1 0 0],'LineWidth',3); hold on
+% Create legend text
+legendText{end+1} = sprintf('Simulation - %1.2g quantile 90%%CI',min(quantiles));
+legendText{end+1} = sprintf('Simulation - %1.2g quantile 90%%CI',max(quantiles));
+legendText{end+1} = sprintf('Simulation - Median 90% CI');
+legendText{end+1} = sprintf('Simulation - Median');
+% Set linlogY
+if logY,
+    set(gca,'YScale','log');
+else
+    set(gca,'YScale','linear');
+end
+legend(legendText,'Location','best','Interpreter','none');
+set(gca,'FontSize',12);
+grid on;
+xlabel('Time','FontSize',14);
+ylabel(output,'FontSize',14,'Interpreter','none');
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/12_Other/SBPOPbootstrap.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/12_Other/SBPOPbootstrap.m
new file mode 100644
index 0000000000000000000000000000000000000000..f257da39c0d0be7f9ff916518a61f9c9dd906860
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/General/12_Other/SBPOPbootstrap.m
@@ -0,0 +1,325 @@
+function [] = SBPOPbootstrap(projectPath,bootstrapSettings)
+% SBPOPbootstrap: runs a bootstrap analysis on the provided NLME project folder.
+%
+% USAGE:
+% ======
+% SBPOPbootstrap(projectPath,bootstrapSettings)
+%
+% projectPath:      Path to the NONMEM or MONOLIX project that should be bootstrapped
+%
+% bootstrapSettings: structure with the following elements
+%   bootstrapSettings.path                  Path where to store the bootstrap projects (default: './BOOTSTRAPPATH')
+%   bootstrapSettings.outputpath            Path for storage of results (default: './BOOTSTRAPPATH') 
+%   bootstrapSettings.NSAMPLES              Number of bootstrap samples (default: 100)
+%   bootstrapSettings.GROUP                 String with group name to use for stratification (some column
+%                                           name in the dataset that contains categorical information).
+%                                           Can be set to '' (empty) if stratification not desired (default: '')
+%   bootstrapSettings.N_PROCESSORS_PAR:     Number of parallel model runs (default: 1)
+%   bootstrapSettings.N_PROCESSORS_SINGLE:  Number of processors to parallelize single run (if NONMEM and MONOLIX allow for it) (default: 1)
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+%
+% This program is Free Open Source Software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle bootstrap settings
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try bootstrappath           = bootstrapSettings.path;                   catch, bootstrappath         = './BOOTSTRAPPATH';    end
+try NSAMPLES                = bootstrapSettings.NSAMPLES;               catch, NSAMPLES              = 100;                  end
+try GROUP                   = bootstrapSettings.GROUP;                  catch, GROUP                 = '';                   end
+try outputpath              = bootstrapSettings.outputpath;             catch, outputpath            = bootstrappath;        end
+try N_PROCESSORS_PAR        = bootstrapSettings.N_PROCESSORS_PAR;       catch, N_PROCESSORS_PAR      = 1;                    end
+try N_PROCESSORS_SINGLE     = bootstrapSettings.N_PROCESSORS_SINGLE;    catch, N_PROCESSORS_SINGLE   = 1;                    end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check project type
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isNONMEMfitSBPOP(projectPath),
+    TOOL = 'NONMEM';
+    projectHeader = parseProjectHeaderNONMEMSBPOP(projectPath);
+    projectfile = 'project.nmctl';
+elseif isMONOLIXfitSBPOP(projectPath),
+    TOOL = 'MONOLIX';
+    projectHeader = parseProjectHeaderMONOLIXSBPOP(projectPath);
+    projectfile = 'project.mlxtran';
+else
+    error('Incorrect content of ''projectPath''');
+end
+   
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create bootstrap project folder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+oldpath = pwd;
+try, rmdir(bootstrappath,'s'); catch, end
+mkdir(bootstrappath); 
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create TEMPLATE project in bootstrappath
+% - Copying the projectPath without RESULTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+mkdir([bootstrappath '/TEMPLATE']);
+copyfile(projectPath,[bootstrappath '/TEMPLATE'])
+try rmdir([bootstrappath '/TEMPLATE/RESULTS'],'s'); catch end
+mkdir([bootstrappath '/TEMPLATE/RESULTS']);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Updating template project file with new data path and filename
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+oldpath = pwd();
+cd([bootstrappath '/TEMPLATE']);
+content = fileread(projectfile);
+% Replace the data path with './data.csv'
+content = strrep(content,projectHeader.DATA{1},'./data.csv');
+% Handle monolix thing extra
+[p,f,e] = fileparts(projectHeader.DATA{1});
+content = strrep(content,[p '/'],'.');
+content = strrep(content,p,'.');
+content = strrep(content,[f e],'data.csv');
+% Write out new control file
+fid     = fopen(projectfile,'w');
+fprintf(fid,'%s',content);
+fclose(fid);
+cd(oldpath);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Loading the original data
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+oldpath = pwd(); cd(projectPath);
+dataCSV = SBPOPloadCSVdataset(projectHeader.DATA{1});
+cd(oldpath);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check that 'ID' and 'GROUP' present as columns in the data
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+varNames = get(dataCSV,'VarNames');
+
+ix = strmatchSB('ID',varNames,'exact');
+if isempty(ix),
+    error('No ID column present in the dataset.');
+end
+
+if ~isempty(GROUP),
+    ix = strmatchSB(GROUP,varNames,'exact');
+    if isempty(ix),
+        error('The specified GROUP is not present as column in the dataset.');
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create model with nominal dataset - call it "_00" and use as reference
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+copyfile([bootstrappath '/TEMPLATE'],[bootstrappath '/MODEL_00'])
+SBPOPexportCSVdataset(dataCSV,[bootstrappath '/MODEL_00/data.csv']);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create all bootstrap models
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get processors
+N_PROCESSORS_NEEDED = min(N_PROCESSORS_PAR,NSAMPLES);
+killMATLABpool = 0;
+if N_PROCESSORS_NEEDED>1,
+    try
+        if matlabpool('size') == 0,
+            eval(sprintf('matlabpool %d',N_PROCESSORS_NEEDED));
+            killMATLABpool = 1;
+        end
+    catch
+    end
+end
+% Create models
+parfor k=1:NSAMPLES,
+    % Define path for model
+    modelpath = [bootstrappath sprintf('/MODEL_%s',preFillCharSB(k,length(num2str(NSAMPLES)),'0'))];
+    % Copy the template
+    copyfile([bootstrappath '/TEMPLATE'],modelpath);
+    % Resample the dataset
+    dataCSV_resampled = resampleDatasetSBPOP(dataCSV,'ID',GROUP);
+    % Export resampled dataset to folder
+    SBPOPexportCSVdataset(dataCSV_resampled,[modelpath '/data.csv']);
+end
+% Release processors
+try
+    if matlabpool('size')>1 && killMATLABpool==1,
+        matlabpool close
+    end
+catch
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Remove TEMPLATE folder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try rmdir([bootstrappath '/TEMPLATE'],'s'); catch end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run all the models
+% Do not produce GoF Plots for all fits!
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBPOPrunNLMEprojectFolder(bootstrappath,N_PROCESSORS_PAR,N_PROCESSORS_SINGLE,1);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Generate standard tables at defined location and get RESULTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+RESULTS = SBPOPfitanalysisProjectsFolderInfo(bootstrappath,outputpath);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get results
+% For fixed effects, random effects, correlations, covariates, error model
+% parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get parameter names
+fef_names = RESULTS(1).rawParameterInfo.fixedEffects.names;
+ref_names = RESULTS(1).rawParameterInfo.randomEffects.names;
+cor_names = RESULTS(1).rawParameterInfo.correlation.names;
+cov_names = RESULTS(1).rawParameterInfo.covariate.names;
+err_names = RESULTS(1).rawParameterInfo.errorParameter.names;
+
+% Get nominal values
+fef_value_nominal = RESULTS(1).rawParameterInfo.fixedEffects.values;
+ref_value_nominal = RESULTS(1).rawParameterInfo.randomEffects.values;
+cor_value_nominal = RESULTS(1).rawParameterInfo.correlation.values;
+cov_value_nominal = RESULTS(1).rawParameterInfo.covariate.values;
+err_value_nominal = RESULTS(1).rawParameterInfo.errorParameter.values;
+
+% Get nominal standard errors
+fef_stderr_nominal = RESULTS(1).rawParameterInfo.fixedEffects.stderr;
+ref_stderr_nominal = RESULTS(1).rawParameterInfo.randomEffects.stderr;
+cor_stderr_nominal = RESULTS(1).rawParameterInfo.correlation.stderr;
+cov_stderr_nominal = RESULTS(1).rawParameterInfo.covariate.stderr;
+err_stderr_nominal = RESULTS(1).rawParameterInfo.errorParameter.stderr;
+
+% Get bootstrap resulting values
+fef_value_resampled = NaN(length(RESULTS)-1,length(fef_value_nominal));
+ref_value_resampled = NaN(length(RESULTS)-1,length(ref_value_nominal));
+cor_value_resampled = NaN(length(RESULTS)-1,length(cor_value_nominal));
+cov_value_resampled = NaN(length(RESULTS)-1,length(cov_value_nominal));
+err_value_resampled = NaN(length(RESULTS)-1,length(err_value_nominal));
+
+for k=2:length(RESULTS),
+    if ~isempty(RESULTS(k).rawParameterInfo),
+        if ~isempty(RESULTS(k).rawParameterInfo.fixedEffects.values),
+            fef_value_resampled(k-1,:) = RESULTS(k).rawParameterInfo.fixedEffects.values;
+        end
+        if ~isempty(RESULTS(k).rawParameterInfo.randomEffects.values),
+            ref_value_resampled(k-1,:) = RESULTS(k).rawParameterInfo.randomEffects.values;
+        end
+        if ~isempty(RESULTS(k).rawParameterInfo.correlation.values),
+            cor_value_resampled(k-1,:) = RESULTS(k).rawParameterInfo.correlation.values;
+        end
+        if ~isempty(RESULTS(k).rawParameterInfo.covariate.values),
+            cov_value_resampled(k-1,:) = RESULTS(k).rawParameterInfo.covariate.values;
+        end
+        if ~isempty(RESULTS(k).rawParameterInfo.errorParameter.values),
+            err_value_resampled(k-1,:) = RESULTS(k).rawParameterInfo.errorParameter.values;
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Remove all crashed fits (defined by NaN)
+% Nominal fit not allowed to be crashed
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ix_crashed = find(isnan([RESULTS(2:end).OBJ]));
+fef_value_resampled(ix_crashed,:) = [];
+ref_value_resampled(ix_crashed,:) = [];
+cor_value_resampled(ix_crashed,:) = [];
+cov_value_resampled(ix_crashed,:) = [];
+err_value_resampled(ix_crashed,:) = [];
+NSAMPLES_NOT_CRASHED = size(fef_value_resampled,1);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Generate output for results
+% A figure with subplots will be done for each category.
+%  - Plotting histogram
+%  - Highlighting the 5% and 95% CI based on bootstraps
+%  - Plotting nominal point estimate and 5%/95% of CI
+%  - Textual representation of RSE based on nominal and bootstrap
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% Prepare output file
+filename = [outputpath '/bootstrap_plot_results'];
+startNewPrintFigureSBPOP(filename);
+
+names_all           = {fef_names,ref_names,cor_names,cov_names,err_names};
+value_nominal_all   = {fef_value_nominal, ref_value_nominal, cor_value_nominal, cov_value_nominal, err_value_nominal};
+stderr_nominal_all  = {fef_stderr_nominal, ref_stderr_nominal,cor_stderr_nominal,cov_stderr_nominal,err_stderr_nominal};
+value_resampled_all = {fef_value_resampled,ref_value_resampled,cor_value_resampled,cov_value_resampled,err_value_resampled};
+
+for kk=1:length(names_all),
+    
+    names           = names_all{kk};
+    value_nominal   = value_nominal_all{kk};
+    stderr_nominal  = stderr_nominal_all{kk};
+    value_resampled = value_resampled_all{kk};
+    
+    % Define number of bins
+    NBINS           = ceil(max(NSAMPLES_NOT_CRASHED/50,10));
+    
+    if length(names) > 0,
+        % Remove parameters with stderr=0 (not estimated)
+        ix = find(stderr_nominal==0);
+        names(ix) = [];
+        value_nominal(ix) = [];
+        stderr_nominal(ix) = [];
+        value_resampled(:,ix) = [];
+        
+        figure(kk); clf
+        ncols = ceil(sqrt(length(names)));
+        nrows = ceil(length(names)/ncols);
+        for k=1:length(names),
+            subplot(nrows,ncols,k);
+            % Plot histogram
+            [n,x] = hist(value_resampled(:,k),NBINS);
+            bar(x,n/NSAMPLES_NOT_CRASHED); hold on
+            XLim = get(gca,'XLim');
+            YLim = get(gca,'YLim');
+            set(gca,'YLim',YLim);
+            set(gca,'XLim',XLim);
+            % Plot median based on bootstrap
+            q = quantile(value_resampled(:,k),[0.05,0.5,0.95]);
+            plot(q(2)*[1 1],YLim,'-','LineWidth',3,'color',[0 0.7 0.7])
+            % Plot median based on nominal fit
+            plot(value_nominal(k)*[1 1],YLim,'r--','LineWidth',3);
+
+            % Plot 90% CI for bootstrap results
+            plot(q(1)*[1 1],YLim,'-','LineWidth',2,'color',[0 0.7 0.7])
+            plot(q(3)*[1 1],YLim,'-','LineWidth',2,'color',[0 0.7 0.7])
+
+            % Plot 90% CI for nominal fit results
+            plot((value_nominal(k)-1.96*stderr_nominal(k))*[1 1],YLim,'r--','LineWidth',2)
+            plot((value_nominal(k)+1.96*stderr_nominal(k))*[1 1],YLim,'r--','LineWidth',2)
+                    
+            % Increase YLim by 30%
+            YLim = [0 YLim(2)*1.3];
+            set(gca,'YLim',YLim);
+            
+            % Title
+            title(sprintf('%s',names{k}),'FontSize',14,'Interpreter','none');
+            % Determine CI for nominal and bootstrap
+            CI_nominal = [(value_nominal(k)-1.96*stderr_nominal(k)) (value_nominal(k)+1.96*stderr_nominal(k))];
+            textInfo = sprintf('Value, [90%% CI]:\nBT: %1.3g,[%1.3g,%1.3g]\nEST: %1.3g,[%1.3g,%1.3g]',q(2),q(1),q(3),value_nominal(k),CI_nominal(1),CI_nominal(2));
+            text(XLim(2),YLim(2),textInfo,'FontSize',10,'VerticalAlign','top','HorizontalAlign','right','Interpreter','none');
+            if k==1,
+                legend(sprintf('Distribution (N=%d)',NSAMPLES_NOT_CRASHED),'Bootstrap median, 90% CI','Model estimate, 90% CI','Location','SouthEast');
+            end
+            grid off;
+            set(gca,'FontSize',12)
+        end
+        printFigureSBPOP(gcf,filename);
+    end
+end
+
+convert2pdfSBPOP(filename)
+close all
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/_BASEfunctions/Analyze_PK_data.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/_BASEfunctions/Analyze_PK_data.m
new file mode 100644
index 0000000000000000000000000000000000000000..6e92fdaf8bda4ead0582b33bfc71de62a69563cf
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/_BASEfunctions/Analyze_PK_data.m
@@ -0,0 +1,52 @@
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Setup
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+clc; clear all; close all; restoredefaultpath();
+oldpath = pwd();
+cd('/home/schmihek/TOOLS/SBPOP PACKAGE');
+installSBPOPpackage
+cd(oldpath)
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Define dataset to use for analysis and output folder for results
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dataPath    = 'Example Data/Data Compound 3.csv';
+outputPath  = 'TEST3';
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% STEP1: Sanity check if general data format is correct
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+PopPK_checkData(dataPath);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% STEP2: Do some first plots
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+PopPK_exploreData(dataPath,outputPath)
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% STEP3: Do some simple popPK base model assessment
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+options                 = [];
+
+% If nonlinear elimination expected based on graphical exploration, then 
+% set the flag to 1. Otherwise set to 0
+options.NONLINEAR       = 0;
+
+% Define if 'NONMEM' or 'MONOLIX' should be used (better is MONOLIX, faster
+% is NONMEM)
+options.TOOL            = 'NONMEM';
+
+% If repetition of individual fits desired, please state the number of fits
+% to be performed. When using MONOLIX it is ok to take N_TESTS=1. If using
+% NONMEM it is very important to use more 5-10. NONMEM has huge problems to
+% estimate correctly the additive part of the residual error model.
+options.N_TESTS         = 1;
+
+% Run the model based PK analysis
+PopPK_baseModel(dataPath,outputPath,options)
+
+
+
+  
+ 
+ 
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/_BASEfunctions/PopPK_baseModel.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/_BASEfunctions/PopPK_baseModel.m
new file mode 100644
index 0000000000000000000000000000000000000000..6947c84afd9fd25d18049b7afb0077dc30cdc149
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/_BASEfunctions/PopPK_baseModel.m
@@ -0,0 +1,300 @@
+function [] = PopPK_baseModel( dataPath,outputPath,varargin )
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Handle input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+FLAG_ANTIBODY   = 0;
+NONLINEAR    	= 0;
+N_TESTS         = 1;
+TOOL            = 'MONOLIX';
+
+% Handle options
+if nargin >= 3,
+    options = varargin{1};
+    try FLAG_ANTIBODY   = options.FLAG_ANTIBODY;    catch; end
+    try NONLINEAR		= options.NONLINEAR;        catch; end
+    try TOOL            = options.TOOL;             catch; end
+    try 
+        N_TESTS         = options.N_TESTS;          
+    catch
+        % Set N_TESTS=5 by default (if not given otherwise) for NONMEM
+        if strcmp(TOOL,'NONMEM'), N_TESTS = 5; end
+    end
+end
+
+% Handle automatic or user-supplied covariate information
+if nargin < 4,
+    disp('No "covariateInfo" specified. Trying to identify general covariates.');
+    covariateInfo       = {
+                        % NAME          COVARIATE NAME      CONTINUOUS
+                        'Weight'        'WT0'                   1   
+                        'Height'        'HT0'                   1
+                        'Age'           'AGE0'                  1
+                        'BMI'           'BMI0'                  1
+                        'Gender'        'SEX'                   0 
+                        'Ethnicity'     'ETHN'                  0
+                        'Race'          'RACE'                  0
+                          };
+elseif nargin == 4,
+    covariateInfo = varargin{2};
+    if size(covariateInfo,2) ~= 3,
+        error('Please make sure to correctly define the "covariateInfo" input argument.');
+    end
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Load data
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% Augment the general dataset and get cov and cat names
+[dataAugmented,covNames,catNames] = SBPOPconvertGeneralDataFormat(dataPath,covariateInfo);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Data cleaning
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% Define default categorical covariate imputation values
+catImputationValues = 999*ones(size(catNames));
+
+% By default do not remove subjects
+removeSUBJECT  = {
+    % Unique subject identifier     Reason for removal of subject
+};
+
+% By default do not remove records
+removeREC = {
+    % Record number in dataset      Reason for removal
+};
+
+% By default only remove subjects with not more than one PK sample
+Nobs = 1;
+
+% By default remove all BLOQ data
+optionsDataCleaning                 = [];
+optionsDataCleaning.outputPath      = [outputPath '/Output/DataCleaning/'];
+optionsDataCleaning.FLAG_LLOQ       = 0; % Remove all LLOQ data by default
+
+% Do the cleaning
+dataCleaned = SBPOPcleanPopPKdata(dataAugmented,removeSUBJECT,removeREC,Nobs,covNames,catNames,catImputationValues,optionsDataCleaning);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Generate popPK modeling dataset
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+modelingDatasetFile = [outputPath '/Data/popPK_NLME_dataset.csv'];
+dataheaderNLME = SBPOPconvert2popPKdataset(dataCleaned,covNames,catNames,modelingDatasetFile);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Determine data information for different things
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+dataNLME = SBPOPloadCSVdataset(modelingDatasetFile);
+
+% Number of subjects
+Nsubjects = length(unique(dataNLME.ID));
+
+% IV data present
+FLAG_IV_data = ~isempty(find(dataNLME.ADM==2));
+
+% Absorption1 data present 
+FLAG_ABS1_data = ~isempty(find(dataNLME.ADM==1));
+
+% Get values of data - 5% quantile as starting guess for additive error
+ADD_ERROR_0 = quantile(dataNLME.DV(dataNLME.EVID==0),0.05);
+
+% Determine FACTOR_UNITS
+UNIT_DOSE = unique(dataNLME.UNIT(dataNLME.TYPE==0)); UNIT_DOSE = UNIT_DOSE{1};
+UNIT_CONC = unique(dataNLME.UNIT(dataNLME.TYPE==1)); UNIT_CONC = UNIT_CONC{1};
+if strcmp(lower(UNIT_DOSE),'mg') && strcmp(lower(UNIT_CONC),'ug/ml'),
+    FACTOR_UNITS = 1;
+elseif strcmp(lower(UNIT_DOSE),'ug') && strcmp(lower(UNIT_CONC),'ng/ml'),
+    FACTOR_UNITS = 1;
+elseif strcmp(lower(UNIT_DOSE),'mg') && strcmp(lower(UNIT_CONC),'ng/ml'),
+    FACTOR_UNITS = 1000;
+else
+    error('Incorrect definitions of dose and concentration units.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Define default settings for parameter estimation
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+optionsNLME                                 = [];                      
+
+optionsNLME.parameterEstimationTool         = TOOL;
+optionsNLME.N_PROCESSORS_PAR                = 10;
+optionsNLME.N_PROCESSORS_SINGLE             = 5;
+
+optionsNLME.algorithm.SEED                  = 123456;                  
+optionsNLME.algorithm.K1                    = 500;                    
+optionsNLME.algorithm.K2                    = 200;                     
+optionsNLME.algorithm.NRCHAINS              = ceil(100/Nsubjects);   
+
+% Set NONMEM specific options
+optionsNLME.algorithm.METHOD                = 'SAEM';
+optionsNLME.algorithm.ITS                   = 1;
+optionsNLME.algorithm.ITS_ITERATIONS        = 10;
+optionsNLME.algorithm.IMPORTANCESAMPLING    = 1;
+optionsNLME.algorithm.IMP_ITERATIONS        = 5;
+
+% Set MONOLIX specific options
+optionsNLME.algorithm.LLsetting             = 'linearization';     
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Define Fabs1 and ka estimation based on availability of ABS1 and IV data
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+if FLAG_ABS1_data,
+    EST_ka = 1;
+else
+    EST_ka = 0;
+end
+
+if FLAG_ABS1_data && FLAG_IV_data,
+    EST_Fabs1 = 1;
+    Fabs1     = 0.5;
+else
+    EST_Fabs1 = 0;
+    Fabs1     = 1;
+end    
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Run 1 compartmental distribution model (linear) to obtain initial guesses
+% Separate between antibody and not-antibody
+% No Tlag
+% Fabs1 and ka if needed
+% Linear elimination always, nonlinear only if desired
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+if ~FLAG_ANTIBODY || (FLAG_ANTIBODY && NONLINEAR),
+    % Change into a folder to allow for popPK workflow tools to work
+    oldpath = pwd();
+    cd([outputPath '/Data']);
+    
+    % Run a first simple model 
+    modeltest                           = [];
+    modeltest.numberCompartments        = 1;
+    modeltest.errorModels               = 'comb1';
+    modeltest.errorParam0               = [ADD_ERROR_0 0.3];
+    if ~NONLINEAR,
+        modeltest.saturableClearance    = 0;
+    else
+        modeltest.saturableClearance    = [0 1];
+    end        
+    modeltest.lagTime                   = 0;
+    modeltest.FACTOR_UNITS              = FACTOR_UNITS;
+    %                                       CL    Vc    Q1    Vp1    Q2    Vp2    Fiv    Fabs1      ka        Tlag_input1    VMAX    KM
+    if ~FLAG_ANTIBODY,
+        modeltest.POPvalues0            = [ 5     10    5     100    5     100    1      Fabs1      0.5       0.5             10      10];
+    else        
+        modeltest.POPvalues0            = [ 0.2   3     0.8   5      NaN   NaN    1      Fabs1      0.5       0.5             10      10];
+    end
+    modeltest.POPestimate               = [ 1     1     1     1      1     1      0      EST_Fabs1  EST_ka    0               1       1];
+    modeltest.IIVestimate               = [ 1     1     1     1      1     1      0      EST_Fabs1  EST_ka    0               1       1];
+    
+    optionsModelSpace                   = [];
+    optionsModelSpace.Ntests            = N_TESTS;
+    
+    [MODELINFO,RESULTS] = SBPOPbuildPopPKModelSpace('MODEL_00_INITIAL_GUESSES', modeltest, modelingDatasetFile, dataheaderNLME, optionsNLME, optionsModelSpace);
+
+    % Sort results by BIC
+    ranking_var         = sortrows([[1:length(RESULTS)]' [RESULTS.BIC]'],2); 
+    RANKING             = ranking_var(:,1);
+    RESULTS_ORDERD      = RESULTS(RANKING);
+    
+    % Define initial guesses
+    CL0                 =  RESULTS_ORDERD(1).rawParameterInfo.fixedEffects.values(1);
+    Vc0                 =  RESULTS_ORDERD(1).rawParameterInfo.fixedEffects.values(2);
+    Fabs10              =  RESULTS_ORDERD(1).rawParameterInfo.fixedEffects.values(8);
+    ka0                 =  RESULTS_ORDERD(1).rawParameterInfo.fixedEffects.values(9);
+    Tlag0               =  RESULTS_ORDERD(1).rawParameterInfo.fixedEffects.values(10);
+    try
+        VMAX0           =  RESULTS_ORDERD(1).rawParameterInfo.fixedEffects.values(11);
+        KM0             =  RESULTS_ORDERD(1).rawParameterInfo.fixedEffects.values(12);
+    catch
+        VMAX0           =  10;
+        KM0             =  10;
+    end
+    
+    %                       CL    Vc    Q1    Vp1    Q2    Vp2    Fiv    Fabs1      ka        Tlag_input1    VMAX    KM
+    if ~FLAG_ANTIBODY,
+        POPvalues0      = [ CL0   Vc0   CL0   10*Vc0 CL0   10*Vc0 1      Fabs10     ka0       Tlag0          VMAX0   KM0];
+    else
+        POPvalues0      = [ 0.2   3     0.8   3      0.8   3      1      Fabs10     ka0       Tlag0          VMAX0   KM0];
+    end
+    
+    % Get starting guesses for error model parameters
+    errorParam0         = abs(RESULTS_ORDERD(1).rawParameterInfo.errorParameter.values);
+    
+    % Change out of path
+    cd(oldpath);
+else
+    % Define starting guesses for antibody models
+    %                             CL    Vc    Q1    Vp1    Q2    Vp2    Fiv    Fabs1      ka        Tlag_input1    VMAX    KM
+    POPvalues0                = [ 0.2   3     0.8   3      0.8   3      1      0.5        0.5       0.5            1e-10   10];
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Now run the base models of interest
+% Separate between Antibody and other models
+%
+% Non-antibodies: 
+%   Run a 1,2,3 compartmental distribution model
+%   Additive/proportional error model
+%   Linear elimination and if desired also saturable elimination
+%   No lagtime for now
+%
+% Antibodies
+%   Run a 1,2 compartmental distribution model
+%   Additive/proportional error model
+%   Linear elimination and if desired also saturable elimination
+%   No lagtime for now
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% Change into a folder to allow for popPK workflow tools to work
+oldpath = pwd();
+cd([outputPath '/Data']);
+
+modeltest                           = [];
+if ~FLAG_ANTIBODY,
+    modeltest.numberCompartments    = [1 2 3];
+else
+    modeltest.numberCompartments    = [1 2];
+end
+modeltest.errorModels               = 'comb1';
+% Use previously determined error model parameters (crucial for NONMEM)
+modeltest.errorParam0               = errorParam0;
+if ~NONLINEAR,
+    modeltest.saturableClearance    = 0;
+else
+    modeltest.saturableClearance    = [0 1];
+end
+modeltest.lagTime                   = 0;
+modeltest.FACTOR_UNITS              = FACTOR_UNITS;
+%                                       CL    Vc    Q1    Vp1    Q2    Vp2    Fiv    Fabs1      ka        Tlag_input1    VMAX    KM
+% Use previously derived initial guesses
+modeltest.POPvalues0                = POPvalues0;
+modeltest.POPestimate               = [ 1     1     1     1      1     1      0      EST_Fabs1  EST_ka    0               1       1];
+modeltest.IIVestimate               = [ 1     1     1     1      1     1      0      EST_Fabs1  EST_ka    0               1       1];
+
+optionsModelSpace                   = [];
+optionsModelSpace.Ntests            = N_TESTS;
+
+[MODELINFO,RESULTS] = SBPOPbuildPopPKModelSpace('MODEL_01_BASE', modeltest, modelingDatasetFile, dataheaderNLME, optionsNLME, optionsModelSpace);
+
+% Change out of path
+cd(oldpath);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Load and display results 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+oldpath = pwd();
+cd([outputPath '/Output/FitAnalysis/MODEL_01_BASE']);
+
+edit fitInfoParameters.txt
+
+cd(oldpath);
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/_BASEfunctions/PopPK_checkData.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/_BASEfunctions/PopPK_checkData.m
new file mode 100644
index 0000000000000000000000000000000000000000..12583dcf0e1e58cd40cd4c8292308cda35000fd1
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/_BASEfunctions/PopPK_checkData.m
@@ -0,0 +1,12 @@
+function [] = PopPK_checkData( dataPath )
+% [SYNTAX]
+% [] = PopPK_checkData( dataPath )
+% dataPath: Path to the dataset in the general data format
+%
+% [OUTPUT]
+% If at least one of the required columns is not present an error will be
+% shown. Warnings might be shown for other detected things. No claim on
+% completeness of checks is done!
+
+% Sanity check if general data format is correct
+SBPOPcheckGeneralDataFormat(dataPath);
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/_BASEfunctions/PopPK_exploreData.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/_BASEfunctions/PopPK_exploreData.m
new file mode 100644
index 0000000000000000000000000000000000000000..982361cd8fc465b079c16da649d8c3cc2ee6b502
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/_BASEfunctions/PopPK_exploreData.m
@@ -0,0 +1,70 @@
+function [] = PopPK_exploreData( dataPath,outputPath,varargin )
+% [SYNTAX]
+% [] = PopPK_exploreData( dataPath,outputPath )
+% [] = PopPK_exploreData( dataPath,outputPath,covariateInfo )
+% dataPath:         Path to the dataset in the general data format
+% outputPath:       Path to where to write the exploratory plots and results
+% covariateInfo:    MATLAB cell-array, defining which readouts in the
+%                       general dataset should be added as time independent
+%                       covariates. The format for this argument is as
+%                       follows (documented by example):
+% 
+%                       covariateInfo = {
+%                           % NAME              USENAME      CONTINUOUS
+%                            'Gender'            'SEX'          0
+%                            'Age'               'AGE0'         1
+%                            'Bodyweight'        'WT0'          1
+%                            'Height'            'HT0'          1
+%                            'BMI'               'BMI0'         1
+%                       };
+%
+%                       The CONTINUOUS column is optional and will not be used in this 
+%                       function yet. It is used somewhere else to identify what the user
+%                       desires to use as continuous and what as categorical covariate.
+%
+%                       The values for the covariates will be determined as
+%                       follows:
+%                        - Use mean of BASEline assessments by default. 
+%                        - If BASE not defined then use mean of SCREEN assessments.
+%                        - BASE and SCREEN not defined then use mean of pre-first-dose assessments.
+%
+% [OUTPUT]
+% PDFs and text files are generated. Standard covariates are found automatically.
+% If desired, the user can define the covariates to use manually.
+
+% Handle automatic or user-supplied covariate information
+if nargin == 2,
+    disp('No "covariateInfo" specified. Trying to identify general covariates.');
+    covariateInfo       = {
+                        % NAME          COVARIATE NAME      CONTINUOUS
+                        'Weight'        'WT0'                   1   
+                        'Height'        'HT0'                   1
+                        'Age'           'AGE0'                  1
+                        'BMI'           'BMI0'                  1
+                        'Gender'        'SEX'                   0 
+                        'Ethnicity'     'ETHN'                  0
+                        'Race'          'RACE'                  0
+                          };
+elseif nargin == 3,
+    covariateInfo = varargin{1};
+    if size(covariateInfo,2) ~= 3,
+        error('Please make sure to correctly define the "covariateInfo" input argument.');
+    end
+else
+    error('Incorrect number of input arguments.');
+end
+
+% Get continuous and categorical covariate names
+covNames            = covariateInfo(find([covariateInfo{:,3}]==1),2);
+catNames            = covariateInfo(find([covariateInfo{:,3}]==0),2);
+
+% Augment the general dataset 
+dataAugmented       = SBPOPconvertGeneralDataFormat(dataPath,covariateInfo);
+
+% Define the options (just the output folder)
+options             = [];
+options.outputPath  = [outputPath '/Output/DataExploration'];
+
+% Run the PopPK graphical plots
+SBPOPexplorePopPKdata(dataAugmented,covNames,catNames,options)
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/00_Templates/EXAMPLE_01_PD_EXPLORATION.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/00_Templates/EXAMPLE_01_PD_EXPLORATION.m
new file mode 100644
index 0000000000000000000000000000000000000000..eea102f33e18d7c0bdd5845194474f867ce1af3f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/00_Templates/EXAMPLE_01_PD_EXPLORATION.m
@@ -0,0 +1,53 @@
+%% SCRIPT 01: for graphical exploration (no data included ... just code)
+%
+% In this script the data is explored and the dataset for fitting of the 
+% responder rates is built 
+
+%% ===Setup
+clc; clear all; close all; restoredefaultpath();
+path2SBPOP          = '../../../SBPOP_REV_1289';
+oldpath             = pwd; cd(path2SBPOP);      installSBPOPpackage();                  cd(oldpath);
+
+%% ===Data
+data = SBPOPloadCSVdataset('../Data/data.csv');
+
+%% ===Data exploration
+
+%% Continuous PD readouts
+NAMES               = {'ABC',   'XYZVAS'};
+BASELINENAMES       = {'ABC0',  'XYZ0'};
+COVARIATES          = {'AGE0','SEX','HT0','WT0','BMI0','CRP0'};
+TIMEPOINT_CHANGE    = 100;
+PD_IMPROVEMENT      = [-20 -40];  % in percent
+
+options             = [];
+options.filename    = '../Output/Graphical_Exploration/01_PD_data_continuous';
+options.fontsize    = 14;
+
+SBPOPgraphicalExplorationContinuousPD(data,NAMES,BASELINENAMES,COVARIATES,TIMEPOINT_CHANGE,PD_IMPROVEMENT,options)
+
+%% Categorical PD readouts (Responder Rates)
+NAMES               = {'MNO20','MNO40'};
+COVARIATES          = {'AGE0','SEX','HT0','WT0','BMI0','CRP0','ABC0','XYZ0'};
+
+options             = [];
+options.filename    = '../Output/Graphical_Exploration/02_PD_data_categorical';
+options.fontsize    = 14;
+
+SBPOPgraphicalExplorationResponderRatePD(data,NAMES,COVARIATES,options)
+
+%% Summary statistics
+covNames = {'ABC0','XYZ0','AGE0','HT0','WT0','BMI0','CRP0'};
+catNames = {'SEX'};
+SBPOPexploreSummaryStats(data,covNames,catNames,'../Output/Graphical_Exploration/03_Summary_Statistics')
+
+%% Covariate exploration
+covNames = {'ABC0','XYZ0','AGE0','HT0','WT0','BMI0','CRP0'};
+catNames = {'SEX'};
+SBPOPexploreCovariateCorrelations(data,covNames,catNames,'../Output/Graphical_Exploration/04_Covariate_Exploration')
+
+%% ===Generate dataset for optimization
+NAMES               = {'ABC',   'XYZVAS', 'MNO20', 'MNO40'};
+COVARIATES          = {'AGE0','SEX','HT0','WT0','BMI0','CRP0','ABC0','XYZ0'};
+SBPOPcreateDatasetMedianOptimization(data,NAMES,COVARIATES,'../Data/data_median_optimization.csv')
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/00_Templates/EXAMPLE_02_PDmedian_MODELING.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/00_Templates/EXAMPLE_02_PDmedian_MODELING.m
new file mode 100644
index 0000000000000000000000000000000000000000..1bb4c73fcfe13805fc221d5601a56a5bd23c3fc4
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/00_Templates/EXAMPLE_02_PDmedian_MODELING.m
@@ -0,0 +1,120 @@
+%% SCRIPT 02: for median modeling (no data included ... just code)
+%
+% The dataset for the optimization as been prepared in Graphical_Exploration_Example.m
+% and is stored in ../Data/data_median_optimization.csv
+%
+% Here in this example we will do it for a single model only ...
+%
+% Assumption: A PK model has been fitted previously and is available for
+% sampling of PK parameters. In case the PK model needs covariates, these
+% are taken from the model ... the names in the optimization dataset need
+% to be the same! FIT_PK could also be omitted if a KPD, etc. model is
+% estimated. 
+
+%% ===Setup
+clc; clear all; close all; restoredefaultpath();
+path2SBPOP          = '../../../SBPOP_REV_1289';
+oldpath             = pwd; cd(path2SBPOP);      installSBPOPpackageInitial();           cd(oldpath);
+
+%% ===Load data 
+data                = SBPOPloadCSVdataset('../Data/data_median_optimization.csv');
+
+%% ===Create dosing schemes for treatment arms that are in the dataset
+% The median modeling assumes nominal dosing.
+% All dosing schemes need to be based on the same structure!
+% Dosings do not need to be in the dataset ... that will be matched later.
+
+% Check the TRT groups that are in the dataaset
+% ---------------------------------------------
+unique(data.TRT)
+
+% Define the dosings for the TRT groups
+% -------------------------------------
+% PLACEBO  0
+dosing_0            = SBPOPcreateDOSING({'INFUSION','BOLUS'},   {0,0},              {0,0},                      {0.0833,[]});
+dosing_22011        = SBPOPcreateDOSING({'INFUSION','BOLUS'},   {[0.1 0.1]*1000,0}, {[0 21],0},                 {0.0833,[]});
+dosing_22012        = SBPOPcreateDOSING({'INFUSION','BOLUS'},   {[1 1]*1000,0},     {[0 21],0},                 {0.0833,[]});
+dosing_22013        = SBPOPcreateDOSING({'INFUSION','BOLUS'},   {[10 10]*1000,0},   {[0 21],0},                 {0.0833,[]});
+dosing_623011       = SBPOPcreateDOSING({'INFUSION','BOLUS'},   {0,75*1000},        {0,[0 1 2 3 4 8 12 16]*7},  {0.0833,[]});
+dosing_623012       = SBPOPcreateDOSING({'INFUSION','BOLUS'},   {0,150*1000},       {0,[0 1 2 3 4 8 12 16]*7},  {0.0833,[]});
+
+% Create a dosingInformation structure
+% ------------------------------------
+dosingInformation               = [];                         
+dosingInformation.TRT           = [0            22011               22012           22013           623011          623012       ];
+dosingInformation.dosings       = {dosing_0,    dosing_22011,       dosing_22012,   dosing_22013,   dosing_623011,  dosing_623012};
+dosingInformation.name          = {'Placebo',   '0.1mg/kg',         '1mg/kg',       '10mg/kg',      '75mg',         '150mg'};
+% Weight based contains 2 rows ... one for the first dosing (IV) and one for the second (SC)!
+% There could be more columns, depending on the number of inputs in the dosing schemes
+dosingInformation.weightBased   = [     0               1               1                   1           0                 0      
+                                        0               0               0                   0           0                 0      ];
+
+%% ===Define optimization options
+
+options                      = [];
+
+options.maxtime              = Inf;
+options.maxiter              = Inf;
+options.maxfunevals          = 400;
+options.OPTIMIZER            = 'simplexSB';
+options.N_BOOTSTRAP          = 120;
+options.N_PROCESSORS         = 8; 
+
+%% ===MODEL: MODEL_01_MNO20_40
+% Data to be used for fitting defined by what is present in the dataset.
+% Dosings need to be defined for each TRT but can also be defined for non present TRTs in the data
+dataUse = data;
+dataUse(dataUse.TRT==22011,:) = [];
+dataUse(dataUse.TRT==22012,:) = [];
+dataUse(dataUse.TRT==22013,:) = [];
+
+% Load the model to fit
+modelInformation                = [];
+modelInformation.model          = SBmodel('../Models/PKPD_model_MNO.txt');
+modelInformation.modelOutput    = {'RR_median_MNO20','RR_median_MNO40'};
+modelInformation.FIT_PK         = '../Models/PK_MODEL_FIT'; % could be undefined and then additional parameters provided in parameterInformation
+
+% Define parameters to estimate (names taken from the selected model)
+parameterInformation            = [];
+parameterInformation.names      = {'kout'    'EC50'    'EMAX'    'h'    'PLACEBO'};
+parameterInformation.values0    = [ 0.0612    20000     0.316     2.5    0.10    ];
+parameterInformation.estimate   = [  1        1         1         0      1       ];
+
+% Define information for data - allow for stratification
+dataInformation                 = [];
+dataInformation.data            = dataUse;
+dataInformation.names           = {'MNO20','MNO40'}; % Matches the modelOutput in the same order
+dataInformation.type            = 'categorical'; % Does RR fitting. 'continuous' does median fitting
+dataInformation.stratify        = {'','AGE0'}; % Stratification by covariates or none ('')
+
+% Define project folder
+projectfolder                   = '../Models/MEDIAN_MODELING/MODEL_01_MNO20_40';
+
+SBPOPrunMEDIANoptimization(projectfolder,modelInformation,dataInformation,parameterInformation,dosingInformation,options);
+
+
+%% ===MODEL: MODEL_02_XYZVAS
+dataUse = data;
+
+% Load the model to fit
+modelInformation                = [];
+modelInformation.model          = SBmodel('../Models/PKPD_model_XYZVAS.txt');
+modelInformation.modelOutput    = {'XYZVAS'};
+modelInformation.FIT_PK         = '../Models/PK_MODEL_FIT'; % could be undefined and then additional parameters provided in parameterInformation
+
+% Define parameters to estimate (names taken from the selected model)
+parameterInformation            = [];
+parameterInformation.names      = {'kout'    'EC50'    'EMAX'    'h'    'PLACEBO' 'BASELINE'};
+parameterInformation.values0    = [ 0.0612    15000     0.5      2.5    0.10         6.5];
+parameterInformation.estimate   = [  1        1         1         0      1            1];
+
+% Define information for data - allow for stratification
+dataInformation                 = [];
+dataInformation.data            = data;
+dataInformation.names           = {'XYZVAS'};   % Matches the modelOutput in the same order
+dataInformation.type            = 'continuous'; % Does median fitting
+dataInformation.stratify        = {'','AGE0'};  % This will run several different models ... stratified by covariates
+% Define project folder
+projectfolder                   = '../Models/MEDIAN_MODELING/MODEL_02_XYZVAS';
+
+SBPOPrunMEDIANoptimization(projectfolder,modelInformation,dataInformation,parameterInformation,dosingInformation,options);
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/04_DataConversion/SBPOPcreateDatasetMedianOptimization.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/04_DataConversion/SBPOPcreateDatasetMedianOptimization.m
new file mode 100644
index 0000000000000000000000000000000000000000..76700335b4a11eee7093f119030472850275c272
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/04_DataConversion/SBPOPcreateDatasetMedianOptimization.m
@@ -0,0 +1,87 @@
+function [] = SBPOPcreateDatasetMedianOptimization(data,NAMES,COVARIATES,filename)
+% [DESCRIPTION]
+% Generation of a dataset that can be used for the median optimization
+% approach. The dataset has a wide format and does not contain doses. Doses
+% will need to be handled separately by nominal dosing.
+%
+% [SYNTAX]
+% [] = SBPOPcreateDatasetMedianOptimization(dataClean,NAMES,COVARIATES,datafilename)
+%
+% [INPUT]
+% data:         Dataset in the generalized augmented format.
+% NAMES:        Cell-array with the names PD-readouts to consider - these
+%               will be added in columns in the wide format.
+% COVARIATES:   Cell-array with the names of covariates to keep in the
+%               data.
+% filename:     Filename with path for exporting the dataset file.
+%
+% [OUTPUT]
+% Data file, comma separated at specified location.
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 19th April 2013
+%
+% [PLATFORM]
+% Windows, Unix, MATLAB
+%
+% [TOOLBOXES USED]
+% Statistics Toolbox
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+%
+% This program is Free Open Source Software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%% ===Prepare output folder and file
+if ~isempty(filename),
+    folder = fileparts(filename);
+    if ~isempty(folder),
+        mkdir(folder)
+    end
+else
+    filename = 'data.csv';
+end
+
+%% ===Prepare data 
+
+%% Define columns of a reduced dataset
+col_names = [{'STYSID1A' 'ID' 'STUDY' 'TRT' 'NOMINAL_TIME' 'NAME' 'DV' 'DOSE'} COVARIATES];
+
+%% Get reduced dataset
+dataReduced = dataset();
+for k=1:length(col_names),
+    dataReduced.(col_names{k}) = data.(col_names{k});
+end
+
+%% Remove all NAMEs from the data that are not in NAMES
+allNAMEs = unique(dataReduced.NAME);
+for k=1:length(allNAMEs),
+    if ~ismember(allNAMEs{k},NAMES),
+        dataReduced(strcmp(dataReduced.NAME,allNAMEs{k}),:) = [];
+    end
+end
+
+%% ===Prepare wide dataset based on reduced dataset
+datawide = SBPOPdataset2wide(dataReduced,'ID','NOMINAL_TIME','NAME','DV');
+		
+%% ===Export dataset
+SBPOPexportCSVdataset(datawide,[strrep(filename,'.csv','') '.csv'])
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/04_DataConversion/getMedianModelingDataStructSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/04_DataConversion/getMedianModelingDataStructSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..dbaa441b0300f9eaefae53dec165f6de88535f8c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/04_DataConversion/getMedianModelingDataStructSBPOP.m
@@ -0,0 +1,508 @@
+function [dataFitMedian,dataRemovedNaNSettings] = getMedianModelingDataStructSBPOP(data,names,type,varargin)
+% [DESCRIPTION]
+% Function generates a datatructure that contains information about either
+% responder rates in TRT groups or median values of readouts in TRT groups.
+%
+% NOMINAL_TIME column is used for binning and needs to be available in the
+% provided data. 
+%
+% The result can be used for plotting or fitting of the RR/median responses.
+%
+% Handling of continuous covariates:
+% ----------------------------------
+% For the median modeling approach it is possible to specify a PK model
+% fit. If this model depends on continuous covariates, it does make sense
+% to obtain information about the median of these covariates in the
+% generated structure. When simulating the different treatment groups the
+% correct settings for the median covariates can be used.
+%
+% Handling of categorical covariates:
+% -----------------------------------
+% While continuous covariates are easy to handle (by their median),
+% categorial covariates are not really feasible to handle. However, since
+% the median modeling approach allows for stratification, categorical
+% covariates can be considered if only a single category is left.
+% This means that if a single category is left (by TRT group), then this
+% one will be recorded. If, however, multiple categories are left, the
+% reference value will be used and a warning displayed.
+%
+% [SYNTAX]
+% [dataFitMedian,dataRemovedNaNSettings] = getMedianModelingDataStructSBPOP(data,names,type)
+% [dataFitMedian,dataRemovedNaNSettings] = getMedianModelingDataStructSBPOP(data,names,type,covNames)
+% [dataFitMedian,dataRemovedNaNSettings] = getMedianModelingDataStructSBPOP(data,names,type,covNames,catNames,referenceCAT)
+% [dataFitMedian,dataRemovedNaNSettings] = getMedianModelingDataStructSBPOP(data,names,type,covNames,catNames,referenceCAT,regressionPARA,regressionDATA)
+%
+% [INPUT]
+% data:         dataset in wide format.  
+%               ID, TRT, NOMINAL time and the columns specified in "names"
+%               need to be present at least
+% names:        Cell-array with the names of readouts to consider.
+%               Categorical and continuous can not be mixed. Categorical
+%               are limited to values of 0 and 1. 
+% type:         string defining what to do. "categorical" will assume
+%               categorical data and calculate responder rates.
+%               "continuous" will calculate medians for the readouts.
+%
+% covNames:     Names of continuous covariates to generate median values
+% catNames:     Names of categorical covariates to generate values for
+%               In case of single category this value is taken, otherwise 
+%               the reference value
+% referenceCAT: Reference values for categorical covariates
+% regressionPARA: Cell-array with regression parameter names in model
+% regressionDATA: Cell-array with regression data column names in dataset
+%
+% [OUTPUT]
+% dataFitMedian: Matlab structure with the following contents:
+%     dataFitMedian.NAMES             = names; % Names of readouts
+%     dataFitMedian.TRT               = [];    % TRT codes in data
+%     dataFitMedian.NT                = {};    % All NOMINAL_TIME values in TRT group
+%     dataFitMedian.N                 = [];    % Total number of subjects in TRT group
+%     dataFitMedian.N_NT              = {};    % Number of subjects at NOMINAL_TIME with measurement per TRT
+%     dataFitMedian.DATA              = {};    % The data ... one element per TRT group, in each element one 
+%                                                row per names element and as many columns as nominal times in TRT group
+%                                                Responder rates (in %) for categorical, and medians for continuous readouts 
+%     dataFitMedian.DATA_STDERR       = {};    % Standard errors for the DATA to be used in cost function for median fitting
+%     dataFitMedian.DATA_STDERR_LOG   = {};    % Standard errors for the log transformed DATA to be used in cost function for median fitting
+%                                                NaN in case of categorical readouts
+%     dataFitMedian.covNames          = {};    % Cell-array with names of continuous covariates for which medians are calculated
+%     dataFitMedian.covValues         = [];    % Matrix (row: covariate in order of covNames) with median continuous covariate values for TRT groups
+%
+%     dataFitMedian.catNames          = {};    % Cell-array with names of categorical covariates for which values are determined
+%     dataFitMedian.catValues         = [];    % Matrix (row: covariate in order of catNames) with values for TRT groups
+%                                              % Reference group if multiple categories - value if single category 
+%
+% dataRemovedNaNSettings: Dataset with removed records from provided
+% datasets. All records are removed for which at least one of the "names"
+% has a NaN entry
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 21st April 2014
+%
+% [PLATFORM]
+% Windows, Unix, MATLAB
+%
+% [TOOLBOXES USED]
+% Statistics Toolbox
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+%
+% This program is Free Open Source Software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%% Handle variable input arguments
+covNames = {};
+catNames = {};
+referenceCAT = [];
+regressionPARA = {};
+regressionDATA = {};
+if nargin == 3,
+elseif nargin == 4,
+    covNames = varargin{1};
+elseif nargin == 6,
+    covNames = varargin{1};
+    catNames = varargin{2};
+    referenceCAT = varargin{3};
+elseif nargin == 8,
+    covNames = varargin{1};
+    catNames = varargin{2};
+    referenceCAT = varargin{3};
+    regressionPARA = varargin{4};
+    regressionDATA = varargin{5};
+else
+    error('Incorrect number of input arguments.');
+end
+
+%% Check input something
+if isempty(regressionPARA),
+    regressionPARA = {};
+end
+
+if isempty(regressionDATA),
+    regressionDATA = {};
+end
+
+if ischar(regressionPARA),
+    regressionPARA = {regressionPARA};
+end
+if ischar(regressionDATA),
+    regressionDATA = {regressionDATA};
+end
+
+if ischar(names),
+    names = {names};
+end
+if ischar(covNames),
+    covNames = {covNames};
+end
+if ischar(catNames),
+    catNames = {catNames};
+end
+
+if length(catNames) ~= length(referenceCAT),
+    error('Length of "catNames" and "referenceCAT" is not matching.');
+end
+
+if length(regressionPARA) ~= length(regressionDATA),
+    error('Length of "regressionPARA" and "regressionDATA" is not matching.');
+end
+
+
+%% Remove all records which contain NaN values in one of the names columns
+dataClean = data;
+for k=1:length(names),
+    dataRemovedNaNSettings = dataClean(isnan(dataClean.(names{k})),:);
+    dataClean(isnan(dataClean.(names{k})),:) = [];
+end
+
+%% If type=categorical, then require only two type of elements (0 and 1) in the names columns
+if strcmpi(type,'categorical'),
+    for k=1:length(names),
+        X = sort(unique(dataClean.(names{k})));
+        if length(X) > 2,
+            error('When considering categorical data (responder rates), the "names" columns only are allowed to contain 0 or 1.');
+        end
+        if max(X)>1 || min(X)<0,
+            error('When considering categorical data (responder rates), the "names" columns only are allowed to contain 0 or 1.');
+        end
+    end
+end
+
+%% Handle "categorical" type
+if strcmpi(type,'categorical'),
+    % Initialize output structure
+    dataFitMedian                   = [];
+    dataFitMedian.NAMES             = names; % Names of readouts
+    dataFitMedian.TRT               = [];    % TRT codes in data
+    dataFitMedian.NT                = {};    % all NOMINAL_TIME values in TRT
+    dataFitMedian.N                 = [];    % total number of subjects in TRT
+    dataFitMedian.N_NT              = {};    % number of subjects at NOMINAL_TIME with measurement per TRT
+    dataFitMedian.DATA              = {};    % data for fitting per TRT and NOMINAL_TIME 
+    dataFitMedian.DATA_STDERR       = {};    % stderr for the data per TRT and NOMINAL_TIME
+    dataFitMedian.DATA_STDERR_LOG   = {};    % stderr for the log transformed data per TRT and NOMINAL_TIME
+    
+    % Determine all available TRT groups
+    allTRT                          = unique(dataClean.TRT);     % All treatment groups
+    dataFitMedian.TRT               = allTRT(:)';               % Collect info in output structure
+    
+    % Cycle through all TRT groups and collect the information
+    for k=1:length(allTRT),
+        % Get data for TRT group only
+        datak                       = dataClean(dataClean.TRT==allTRT(k),:);
+        
+        % Get all NOMINAL_TIME values for TRT group
+        allNT                       = unique(datak.NOMINAL_TIME);
+        dataFitMedian.NT{k}         = allNT;                % Collect info in output structure
+        
+        % Get total number of subjects per TRT group
+        N                           = length(unique(datak.ID));
+        dataFitMedian.N(k)          = N;                    % Collect info in output structure
+        
+        % Initialize some variables to collect information for each nominal
+        % time point
+        N_RESPONSE_NT               = NaN(length(names),length(allNT)); % Sum of responders based on the categorical data (1=response, 0=no response)
+        N_NT                        = []; % Number of patients in TRT group at NT
+        
+        % Cycle through the nominal time points and collect information
+        for k2=1:length(allNT),
+            datak2                  = datak(datak.NOMINAL_TIME==allNT(k2),:);
+            
+            if ~isempty(datak2),
+                N_NT(k2)                    = length(unique(datak2.ID));
+                % Get number of responders for each NAMES in current TRT and NT
+                for k3=1:length(names),
+                    N_RESPONSE_NT(k3,k2)    = sum(datak2.(names{k3})==1);
+                end
+            else
+                N_NT(k2)                    = 0;
+                for k3=1:length(names),
+                    N_RESPONSE_NT(k3,k2)    = NaN;
+                end
+            end
+        end
+        
+        % Calculate Responder Rates in percent for TRT group over
+        % NOMINAL_TIME. RAW RR ... in the sense of no imputation!
+        % Also calculate standard error for RR
+        RR                          = NaN(length(names),length(allNT));
+        STDERR_RR                   = NaN(length(names),length(allNT));
+        for k3=1:length(names),
+            p                       = N_RESPONSE_NT(k3,:)./N_NT;
+            RR(k3,:)                = 100*p;
+            STDERR_RR(k3,:)         = max(100*sqrt(p.*(1-p)./N_NT),1);
+        end
+        
+        % Collect information
+        dataFitMedian.N_NT{k}            = N_NT;
+        dataFitMedian.DATA{k}            = RR;
+        dataFitMedian.DATA_STDERR{k}     = STDERR_RR;
+        % Log transformed undefined for RR!
+        dataFitMedian.DATA_STDERR_LOG{k} = NaN(length(names),length(allNT));
+    end
+    
+    
+elseif strcmpi(type,'continuous'),
+    %% Handle "continuous" type
+    % Initialize output structure
+    dataFitMedian                   = [];
+    dataFitMedian.NAMES             = names; % Names of readouts
+    dataFitMedian.TRT               = [];    % TRT codes in data
+    dataFitMedian.NT                = {};    % all NOMINAL_TIME values in TRT
+    dataFitMedian.N                 = [];    % total number of subjects in TRT
+    dataFitMedian.N_NT              = {};    % number of subjects at NOMINAL_TIME with measurement per TRT
+    dataFitMedian.DATA              = {};    % data for fitting per TRT and NOMINAL_TIME - this will be the median values
+    dataFitMedian.DATA_STDERR       = {};    % stderr for the data per TRT and NOMINAL_TIME
+    dataFitMedian.DATA_STDERR_LOG   = {};    % stderr for the log transformed data per TRT and NOMINAL_TIME
+
+    % Determine all available TRT groups
+    allTRT                          = unique(dataClean.TRT);     % All treatment groups
+    dataFitMedian.TRT               = allTRT(:)';                % Collect info in output structure
+    
+    % Cycle through all TRT groups and collect the information
+    for k=1:length(allTRT),
+        % Get data for TRT group only
+        datak                       = dataClean(dataClean.TRT==allTRT(k),:);
+        
+        % Get all NOMINAL_TIME values for TRT group
+        allNT                       = unique(datak.NOMINAL_TIME);
+        dataFitMedian.NT{k}         = allNT;                % Collect info in output structure
+        
+        % Get total number of subjects per TRT group
+        N                           = length(unique(datak.ID));
+        dataFitMedian.N(k)          = N;                    % Collect info in output structure
+        
+        % Initialize some variables to collect information for each nominal time point
+        MEDIAN_RESPONSE_NT          = NaN(length(names),length(allNT)); 
+        STDERR_RESPONSE_NT          = NaN(length(names),length(allNT)); 
+        STDERR_LOG_RESPONSE_NT      = NaN(length(names),length(allNT)); 
+        N_NT                        = []; % Number of patients in TRT group at NT
+        
+        % Cycle through the nominal time points and collect information
+        for k2=1:length(allNT),
+            datak2                  = datak(datak.NOMINAL_TIME==allNT(k2),:);
+            
+            if ~isempty(datak2),
+                N_NT(k2)            = length(unique(datak2.ID));
+                % Get number of responders for each NAMES in current TRT and NT
+                for k3=1:length(names),
+                    MEDIAN_RESPONSE_NT(k3,k2)     = nanmedian(datak2.(names{k3}));
+                    STDERR_RESPONSE_NT(k3,k2)     = nanstd(datak2.(names{k3}))/sqrt(N_NT(k2));
+                    STDERR_LOG_RESPONSE_NT(k3,k2) = nanstd(log(datak2.(names{k3})))/sqrt(N_NT(k2));
+                end
+            else
+                N_NT(k2)                    = 0;
+                for k3=1:length(names),
+                    MEDIAN_RESPONSE_NT(k3,k2)     = NaN;
+                    STDERR_RESPONSE_NT(k3,k2)     = NaN;                    
+                    STDERR_LOG_RESPONSE_NT(k3,k2) = NaN;                    
+                end
+            end
+        end
+        
+        % Handle 0 STDERROR things
+        % If zero then set to median of others. If all zero then set all to 1
+        % Do it rowwise
+        for k2=1:size(STDERR_RESPONSE_NT,1)
+            row = STDERR_RESPONSE_NT(k2,:);
+            % Check if all zero
+            if sum(abs(row))==0,
+                row = ones(1,length(row));
+            else
+                row(row==0) = median(row(row~=0));
+            end
+            STDERR_RESPONSE_NT(k2,:) = row;
+        end
+        
+        % Do same for STDERR_LOG_RESPONSE_NT
+        for k2=1:size(STDERR_LOG_RESPONSE_NT,1)
+            row = STDERR_LOG_RESPONSE_NT(k2,:);
+            % Check if all zero
+            if sum(abs(row))==0,
+                row = ones(1,length(row));
+            else
+                row(row==0) = median(row(row~=0));
+            end
+            STDERR_LOG_RESPONSE_NT(k2,:) = row;
+        end
+        
+        % Collect information
+        dataFitMedian.N_NT{k}            = N_NT;
+        dataFitMedian.DATA{k}            = MEDIAN_RESPONSE_NT;
+        dataFitMedian.DATA_STDERR{k}     = STDERR_RESPONSE_NT;
+        dataFitMedian.DATA_STDERR_LOG{k} = STDERR_LOG_RESPONSE_NT;
+    end
+else
+    error('Incorrect "type" definition.');
+end
+
+%% Finally, need to add the covariate information into the median data structure
+% Handling of continuous covariates:
+% ----------------------------------
+% For the median modeling approach it is possible to specify a PK model
+% fit. If this model depends on continuous covariates, it does make sense
+% to obtain information about the median of these covariates in the
+% generated structure. When simulating the different treatment groups the
+% correct settings for the median covariates can be used.
+%
+% Handling of categorical covariates:
+% -----------------------------------
+% While continuous covariates are easy to handle (by their median),
+% categorial covariates are not really feasible to handle. However, since
+% the median modeling approach allows for stratification, categorical
+% covariates can be considered if only a single category is left.
+% This means that if a single category is left (by TRT group), then this
+% one will be recorded. If, however, multiple categories are left, the
+% reference value will be used and a warning displayed.
+
+
+%% Handle continuous covariates
+% Median for continuous covariates
+
+% Check if all covariates in dataset that are passed in covNames
+% If not, then provide an error!
+errorText = '';
+for k=1:length(covNames),
+    if isempty(strmatchSB(covNames{k},get(data,'VarNames'),'exact')),
+        errorText = sprintf('%sCovariate "%s" not in dataset. Please provide it!\n',errorText,covNames{k});
+    end
+end
+if ~isempty(errorText),
+    error(errorText);
+end
+
+% Get TRT groups
+allTRT                      = unique(dataClean.TRT);
+
+% Initialize variable to store median values
+medianCovValues             = NaN(length(covNames),length(allTRT));
+
+% Cycle through all TRT groups and get median CovValues
+for k=1:length(allTRT),
+    % Get TRT group
+    datak = dataClean(dataClean.TRT==allTRT(k),:);
+    % Get first rows only
+    allID = unique(datak.ID);
+    data2k = dataset();
+    for k2=1:length(allID),
+        datak2 = datak(datak.ID==allID(k2),:);
+        data2k = [data2k; datak2(1,:)];
+    end
+    % Get median covariate values for TRT group
+    for k2=1:length(covNames),
+        medianCovValues(k2,k) = nanmedian(data2k.(covNames{k2}));
+    end
+end
+
+% Add to structure
+dataFitMedian.covNames = covNames;
+dataFitMedian.covValues = medianCovValues;
+
+%% Handle categorical covariates
+% Reference if multiple cat categories
+% Value if single category
+
+% Check if all covariates in dataset that are passed in catNames
+% If not, then provide an error!
+errorText = '';
+for k=1:length(catNames),
+    if isempty(strmatchSB(catNames{k},get(data,'VarNames'),'exact')),
+        errorText = sprintf('%sCovariate "%s" not in dataset. Please provide it!\n',errorText,catNames{k});
+    end
+end
+if ~isempty(errorText),
+    error(errorText);
+end
+
+% Get TRT groups
+allTRT                      = unique(dataClean.TRT);
+
+% Initialize variable to store median values
+catValues                   = NaN(length(catNames),length(allTRT));
+
+% Cycle through all TRT groups and get median CovValues
+for k=1:length(allTRT),
+    % Get TRT group
+    datak = dataClean(dataClean.TRT==allTRT(k),:);
+    % Get first rows only
+    allID = unique(datak.ID);
+    data2k = dataset();
+    for k2=1:length(allID),
+        datak2 = datak(datak.ID==allID(k2),:);
+        data2k = [data2k; datak2(1,:)];
+    end
+    % Get cat values for TRT group
+    for k2=1:length(catNames),
+        % Check if single category
+        x = unique(data2k.(catNames{k2}));
+        if length(x) == 1,
+            catValues(k2,k) = x;
+        else
+            disp(sprintf('Multiple categories present for "%s" => using reference value for this covariate.',catNames{k2}));
+            catValues(k2,k) = referenceCAT(k2);
+        end
+    end
+end
+
+% Add to structure
+dataFitMedian.catNames = catNames;
+dataFitMedian.catValues = catValues;
+
+%% Handle regression parameters
+% Get unique median of regression values from dataset
+
+% Check if all regressionDATA in dataset 
+% If not, then provide an error!
+errorText = '';
+for k=1:length(regressionDATA),
+    if isempty(strmatchSB(regressionDATA{k},get(data,'VarNames'),'exact')),
+        errorText = sprintf('%sRegression data "%s" not in dataset. Please provide it!\n',errorText,regressionDATA{k});
+    end
+end
+if ~isempty(errorText),
+    error(errorText);
+end
+
+% Get TRT groups
+allTRT                      = unique(dataClean.TRT);
+
+% Initialize variable to store median values
+medianRegressionValues      = NaN(length(regressionDATA),length(allTRT));
+
+% Cycle through all TRT groups and get median Regression values
+for k=1:length(allTRT),
+    % Get TRT group
+    datak = dataClean(dataClean.TRT==allTRT(k),:);
+    % Get first rows only
+    allID = unique(datak.ID);
+    data2k = dataset();
+    for k2=1:length(allID),
+        datak2 = datak(datak.ID==allID(k2),:);
+        data2k = [data2k; datak2(1,:)];
+    end
+    % Get median covariate values for TRT group
+    for k2=1:length(regressionDATA),
+        medianRegressionValues(k2,k) = nanmedian(data2k.(regressionDATA{k2}));
+    end
+end
+
+% Add to structure
+dataFitMedian.regressionNames = regressionPARA;
+dataFitMedian.regressionValues = medianRegressionValues;
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/05_ModelBuilding/SBPOPrunMEDIANoptimization.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/05_ModelBuilding/SBPOPrunMEDIANoptimization.m
new file mode 100644
index 0000000000000000000000000000000000000000..d30e292e138b8b16e213ca69751e2fb609b23138
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/05_ModelBuilding/SBPOPrunMEDIANoptimization.m
@@ -0,0 +1,299 @@
+function [ output ] = SBPOPrunMEDIANoptimization(projectfolder,modelInformation,dataInformation,parameterInformation,dosingInformation,varargin)
+% SBPOPrunMEDIANoptimization: Performs the median optimization, allowing to
+% use a structural PK, PKPD, KPD, etc model and estimate its parameters to
+% fit the median of the considered readouts in each treatment groups (if
+% continuous readouts) - or the responder rates in each treatment groups
+% (if categorical readout).
+%
+% Costfunction: 
+%   - Weighted sum of squares
+%   - Weighting by (stderr(mean observation))^2
+%   - Allowing for user defined weight per TRT group which is multiplied to 
+%     the cost function for the TRT groups
+%
+% USAGE:
+% ======
+% SBPOPrunMEDIANoptimization(projectfolder,modelInformation,dataInformation,parameterInformation,dosingInformation)        
+% SBPOPrunMEDIANoptimization(projectfolder,modelInformation,dataInformation,parameterInformation,dosingInformation,options)        
+%
+% projectfolder:        string with the path where to store the model runs / logfiles / results
+%
+% modelInformation:     structure with information about the structural model
+%   modelInformation.model:         Structural model as SBmodel object
+%   modelInformation.modelOutput:   Cell-array with names of SBmodel variables that are the outputs 
+%                                   of the model and compared to the data
+%   modelInformation.FIT_PK:        Project path to a potential PK model (NONMEM or MONOLIX), allowing to take parameters 
+%                                   (population mean parameters adjusted by median covariate information in 
+%                                   considered treatment groups). Useful when performing PKPD modeling using the median 
+%                                   approach. The structural model needs to contain the parameters and the structural elements
+%                                   from the FIT_PK model. Can be left empty ''. In this case the non-estimated parameters 
+%                                   from the model are defined only in the structural SBmodel. (default: '')
+%   modelInformation.regressionPARA:Cell-array, defining the parameters to define by regression variables. Same order as in 
+%                                   dataInformation.regressionDATA.
+% 
+% dataInformation:      structure with information about the data to be used for fitting the model
+%   dataInformation.data:           MATLAB dataset in a wide format. Needs to contain the columns ID, TRT, and NOMINAL_TIME.
+%                                   Additionally columns containing covariates of interest and the data readouts of interest.
+%                                   Such a dataset is easiest generated using the function "SBPOPcreateDatasetMedianOptimization".
+%   dataInformation.names:          Cell-array with names of the columns that contain the data to be used for fitting (same order
+%                                   as the corresponding model outputs in "modelInformation.modelOutput").
+%   dataInformation.type:           'categorical': does responder-rate fitting, 'continuous': does median fitting
+%   dataInformation.stratify:       Cell array with stratification settings. Element '' means no stratification. The other 
+%                                   elements need to be names of covariates that are in the dataset - either categorical or 
+%                                   continuous. Dataset is then split in half based on median value and estimation repeated for 
+%                                   upper and lower stratified dataset. (default: {''})!
+%   dataInformation.regressionDATA: Cell-array with names of regression parameters in the data to pass to the model.
+%                                   Same order as in modelInformation.regressionPARA.
+%
+% parameterInformation: structure with information about the parameters to be estimated
+%   parameterInformation.names:     Cell-array with parameter names to be estimated
+%   parameterInformation.values0:   Vector with initial guesses for the estimation (default: taken from the model)
+%                                   (default: values in SBmodel)
+%   parameterInformation.estimate:  Vector with entries 1 (estimated) and 0 (not estimated - kept on initial guess)
+%                                   (default: all estimated)
+%   parameterInformation.trans:     Cell-array with transformation information of parameter search space ('N': normal 'L': lognormal)
+%                                   (default: all 'L' - ensuring positive values)
+%
+% dosingInformation:	structure with information about the nominal treatment group dosings
+%   dosingInformation.TRT:          Vector with treatment group identifiers to be used in optimization
+%                                   TRT groups are optimized if dosings AND data are available - otherwise ignored!
+%                                   It will be checked that for each TRT in the data a dosing definition is present. Otherwise error!
+%   dosingInformation.dosings:      Cell-array defining nominal dosings for each treatment group
+%   dosingInformation.name:         Cell-array defining names for each treatment group
+%   dosingInformation.weightBased:  Matrix with as many rows as dosing inputs in the model and as many columns as treatment groups.
+%                                   A "0" entry defines fixed dosing and a "1" entry defines weight based dosing.
+%                                   If weight based dosing is used, the dataInformation.data dataset needs to contain a WT0 column.
+%   dosingInformation.TRTweighting: Vector with cost function weights for each TRT group. By default all "1".
+%                                   Can be used to increase the weight of specific TRT groups is desired.
+%
+% options:              structure with optional information regarding the parameter estimation
+%   options.maxtime:                Maximum time of single optimization run (default: Inf)
+%   options.maxiter:                Maximum number of iterations in single optimization run (default: Inf)
+%   options.maxfunevals:            Maximum number of costfunction evaluations in single optimization run (default: 100*number of estimated parameters)
+%   options.OPTIMIZER:              String with name of optimization function to be used (default: 'simplexSB')
+%   options.N_BOOTSTRAP:            Number of bootstraps to perform (default: 50)
+%                                   If N_BOOTSTRAP>1 then data is resampled
+%   options.LOG_TRANSFORM:          Flag defining log transformation of the data (1: log transformed, 0: untransformed (default))
+%                                   This has no impact on the dataset. The transformation is handled internally.
+%   options.SEED:                   Random seed to be used (default: 123456)
+%   options.N_PROCESSORS:           Number of processors to use for parallelization (default: 1)
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%% Define default output
+output = [];
+
+%% Handle variable input arguments
+options = [];
+if nargin==5,
+elseif nargin == 6,
+    options = varargin{1};
+else
+    error('Incorrect number of input arguments.');
+end
+
+%% Check and process input arguments
+[projectfolder,modelInformation,dataInformation,parameterInformation,dosingInformation,options,COVCAT_INFORMATION] = ...
+    checkProcessMedianModelingInputsSBPOP(projectfolder, ...
+    modelInformation, dataInformation,parameterInformation,dosingInformation,options);
+
+%% Check log transform and categorical ... only allow log transform of data in case
+% of continuous readouts
+if strcmpi(dataInformation.type,'categorical') && options.LOG_TRANSFORM==1,
+    error('Log transformed data can not be used for categorical readouts.');
+end
+
+%% Request processors
+killMATLABpool = 0;
+if options.N_PROCESSORS>1,
+    try
+        if matlabpool('size') == 0,
+            eval(sprintf('matlabpool %d',options.N_PROCESSORS));
+            killMATLABpool = 1;
+        end
+    catch
+    end
+end
+
+%% Set the SEED
+setseedSBPOP(123456)
+
+%% Determine number of estimated parameters
+NparamEstimated = sum(parameterInformation.estimate);
+
+%% Set high and low bounds for estimation of parameters
+% Set high and low bounds for the optimization to +Inf and -Inf to allow
+% for consideration of the whole range for estimation (transformation of
+% parameters will be used)
+options.lowbounds            = -Inf*ones(1,NparamEstimated);
+options.highbounds           = Inf*ones(1,NparamEstimated);
+
+%% Create the main project folder
+% Additional folders might be created later on
+if exist(projectfolder)==7,
+    result = input('The project folder already exists. Do you want to overwrite it? (Y,N): ','s');
+    if strcmpi(result,'y'),
+        while exist(projectfolder) == 7
+            try rmdir(projectfolder,'s'); catch end
+            pause(0.5)
+        end
+    else
+        disp('SBPOPrunMEDIANoptimization aborted. Please change the name of the projectfolder and continue.');
+        return
+    end
+end
+% Create project folder
+mkdir(projectfolder);
+
+%% Create mexModel for the simulation and determination of the cost function
+% It is created in the folder where the function is invoked ... this is easier when handling parallel computation.
+% At the end of the optimization it is removed again.
+moddos                      = mergemoddosSBPOP(modelInformation.model,dosingInformation.dosings{1});
+[xdummyx,mexModel]                = fileparts(tempname);
+SBPDmakeMEXmodel(moddos,mexModel);
+
+%%  Cycle through the different stratifications
+
+for kStratify=1:length(dataInformation.stratify),
+    stratificationSetting = dataInformation.stratify{kStratify};
+    % Empty ('') means no stratification
+    if isempty(stratificationSetting),
+        stratificationSetting = '';
+    end
+    
+    % Decide if no stratification or stratification ... in the latter case
+    % two runs need to be made. One lower and one upper
+    if isempty(stratificationSetting),
+        stratificationRanges = {''};
+    else
+        % Assume dealing with continuous then use median of categorical
+        % with 2 values ... then use mean.
+        stratificationRanges = {'lower','upper'};
+    end
+    
+    %% Cycle through stratification ranges and handle them independently
+    for kStratifyRange=1:length(stratificationRanges),
+        stratificationRange = stratificationRanges{kStratifyRange};
+        
+        %% Create subfolder for stratified run in project folder
+        if ~isempty(stratificationSetting),
+            projectfolder_stratified = [projectfolder '/' stratificationSetting '_' stratificationRange];
+        else
+            projectfolder_stratified = [projectfolder '/ALLDATA'];
+        end            
+        mkdir(projectfolder_stratified);
+        
+        %% Create logfiles folder
+        mkdir([projectfolder_stratified '/logfiles']);
+        
+        %% Create stratified dataset
+        [dataStratified,stratificationTHRESHOLD] = createStratifiedDatasetSBPOP(dataInformation.data,'ID',stratificationSetting,stratificationRange);
+
+        % Report what it is doing
+        if isempty(stratificationSetting),
+            disp('Handling the ALLDATA case (no stratification).');
+        else
+            if strcmpi(stratificationRange,'lower'),
+                disp(sprintf('Handling a stratified case: %s <= %g',stratificationSetting,stratificationTHRESHOLD));
+            else
+                disp(sprintf('Handling a stratified case: %s > %g',stratificationSetting,stratificationTHRESHOLD));
+            end
+        end
+        
+        %% Get memory to store results for single runs
+        % We need to check later what information we want to store ... for now its
+        % as it is.
+        RUN_ALL             = NaN(options.N_BOOTSTRAP,1);
+        OUTPUTopt_ALL       = cell(options.N_BOOTSTRAP,1);
+        
+        % Run the estimations - allow for parallel execution if desired
+        parfor kBOOTSTRAP=1:options.N_BOOTSTRAP,
+            
+            % Resample data if N_BOOTSTRAP>1
+            if options.N_BOOTSTRAP>1,
+                % Use "ID" as unique subject identifier
+                % Use "TRT" as grouping variable to keep structure for TRT
+                dataresample = resampleDatasetSBPOP(dataStratified,'ID','TRT');
+            else
+                dataresample = dataStratified; % Do not resample if N_BOOTSTRAP=1
+            end
+                        
+            % Convert to datastructure for fitting
+            % Include median continuous covariate information in the structure and categorical covariate information
+            % for the covariates that the PK model requires (if specified)
+            % Also WT0 needs to be present if weight based dosing in dosing schemes.
+            [dataFit,~] = getMedianModelingDataStructSBPOP(dataresample,dataInformation.names,dataInformation.type,COVCAT_INFORMATION.covNames,COVCAT_INFORMATION.catNames,COVCAT_INFORMATION.referenceCAT,modelInformation.regressionPARA,dataInformation.regressionDATA);
+
+            % Run the optimization
+            [Xopt,OUTPUTopt] = optimizeModelMedianSBPOP(kBOOTSTRAP,projectfolder_stratified,mexModel,modelInformation,dataFit,parameterInformation,dosingInformation,options);
+                            
+            % Collect results of optimization
+            RUN_ALL(kBOOTSTRAP)           = kBOOTSTRAP;
+            OUTPUTopt_ALL{kBOOTSTRAP}     = OUTPUTopt;
+        end
+        
+        % Combine results in structure
+        run_results                             = [];
+        
+        % Add all input arguments to results structure
+        run_results.projectfolder               = projectfolder;
+        run_results.projectfolder_stratified    = projectfolder_stratified;
+        run_results.modelInformation            = modelInformation;
+        run_results.dataInformation             = dataInformation;
+        run_results.parameterInformation        = parameterInformation;
+        run_results.dosingInformation           = dosingInformation;
+        run_results.options                     = options;
+        
+        % Add additional information that is run independent
+        run_results.dataOriginalStratified              = dataStratified;
+        run_results.dataOriginalStratifiedMedian        = getMedianModelingDataStructSBPOP(dataStratified,dataInformation.names,dataInformation.type,COVCAT_INFORMATION.covNames,COVCAT_INFORMATION.catNames,COVCAT_INFORMATION.referenceCAT,modelInformation.regressionPARA,dataInformation.regressionDATA);
+        run_results.stratificationSetting.NAME          = stratificationSetting;
+        run_results.stratificationSetting.RANGE         = stratificationRange;
+        run_results.stratificationSetting.THRESHOLD     = stratificationTHRESHOLD;
+        
+        % Add info to a dataset that are different from run to run
+        run_results.run_information                 = dataset();
+        run_results.run_information.RUN             = RUN_ALL;
+        run_results.run_information.OUTPUTopt       = OUTPUTopt_ALL;
+        
+        % Save result dataset in LOGfolder path
+        save([projectfolder_stratified '/run_results.data'],'run_results');
+        
+        % Post-process results for single fit
+        SBPOPassessConvergenceMedian(projectfolder_stratified)
+        SBPOPcontributionTRTcostMedian(projectfolder_stratified)
+        SBPOPbootstrapFitsMedian(projectfolder_stratified)
+        SBPOPuncertaintyDistributionMedian(projectfolder_stratified)
+        if options.N_BOOTSTRAP > 1,
+            SBPOPvpcMedianBootstrapParam(projectfolder_stratified)
+            SBPOPvpcMedianSampledParam(projectfolder_stratified,min(5*options.N_BOOTSTRAP,1000))
+        end
+    end % kStratifyRange
+end % kStratify
+
+%% Delete mex model
+clear mex
+delete([mexModel '.' mexext]);
+
+% Release processors
+try
+    if matlabpool('size')>1 && killMATLABpool==1,
+        matlabpool close
+    end
+catch
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/05_ModelBuilding/auxiliary/checkProcessMedianModelingInputsSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/05_ModelBuilding/auxiliary/checkProcessMedianModelingInputsSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..20eeb5c420201f4c9ba9361a4f3b35d94f4bcde7
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/05_ModelBuilding/auxiliary/checkProcessMedianModelingInputsSBPOP.m
@@ -0,0 +1,236 @@
+function [projectfolder,modelInformation,dataInformation,parameterInformation,dosingInformation,options,COVCAT_INFORMATION] = checkProcessMedianModelingInputsSBPOP(projectfolder,modelInformation,dataInformation,parameterInformation,dosingInformation,options)
+% Auxiliary function for SBPOPrunMEDIANoptimization to check and process the input arguments
+
+%% Handle and check model information
+try modelInformation.model;             catch, error('Please define "modelInformation.model".'); end
+try modelInformation.modelOutput;       catch, error('Please define "modelInformation.modelOutput".'); end
+try modelInformation.FIT_PK;            catch, modelInformation.FIT_PK = ''; end
+try modelInformation.regressionPARA;    catch, modelInformation.regressionPARA = ''; end
+
+if ischar(modelInformation.model),
+    modelInformation.model = SBmodel(modelInformation.model);
+end
+if ~isSBmodel(modelInformation.model),
+    error('"modelInformation.model" is not an SBmodel.');
+end
+if ischar(modelInformation.modelOutput),
+    modelInformation.modelOutput = {modelInformation.modelOutput};
+end
+variables = SBvariables(modelInformation.model);
+for k=1:length(modelInformation.modelOutput),
+    ix = strmatchSB(modelInformation.modelOutput{k},variables,'exact');
+    if isempty(ix),
+        error('"%s" is not a variable in the model.',modelInformation.modelOutput{k});
+    end
+end
+% Parse covariate information from potential FIT_PK model
+COVCAT_INFORMATION = [];
+[COVCAT_INFORMATION.covNames, COVCAT_INFORMATION.catNames, COVCAT_INFORMATION.referenceCAT] = getCovariateInformationSBPOP(modelInformation.FIT_PK);
+
+% Check regressionPARA
+if ischar(modelInformation.regressionPARA) && ~isempty(modelInformation.regressionPARA),
+    modelInformation.regressionPARA = {modelInformation.regressionPARA};
+end
+
+% Check if regressionPARA in model
+parameters = SBparameters(modelInformation.model);
+for k=1:length(modelInformation.regressionPARA),
+    ix = strmatchSB(modelInformation.regressionPARA{k},parameters,'exact');
+    if isempty(ix),
+        error('Regression parameter %s is not in the model.',modelInformation.regressionPARA{k});
+    end
+end
+
+%% Handle and check data information
+try dataInformation.data;               catch, error('Please define "dataInformation.data".');   end
+try dataInformation.names;              catch, error('Please define "dataInformation.names".');  end
+try dataInformation.type;               catch, error('Please define "dataInformation.type".');   end
+try dataInformation.stratify;           catch, dataInformation.stratify = {''};                  end
+try dataInformation.regressionDATA;     catch, dataInformation.regressionDATA = ''; end
+
+if ischar(dataInformation.names),
+    dataInformation.names = {dataInformation.names};
+end
+if ischar(dataInformation.stratify),
+    dataInformation.stratify = {dataInformation.stratify};
+end
+if ischar(dataInformation.data),
+    dataInformation.data = SBPOPloadCSVdataset(dataInformation.data);
+end
+if ~strcmp(class(dataInformation.data),'dataset'),
+    error('"dataInformation.data" should be a dataset.');
+end
+% Check column names
+varnames = get(dataInformation.data,'VarNames');    
+% ID, TRT, NOMINAL_TIME
+if isempty(strmatchSB('ID',varnames,'exact')),
+    error('"dataInformation.data" does not contain an ID column.');
+end
+if isempty(strmatchSB('TRT',varnames,'exact')),
+    error('"dataInformation.data" does not contain a TRT column.');
+end
+if isempty(strmatchSB('NOMINAL_TIME',varnames,'exact')),
+    error('"dataInformation.data" does not contain a NOMINAL_TIME column.');
+end
+% Check dataInformation.names
+if length(dataInformation.names) ~= length(modelInformation.modelOutput),
+    error('Different number of dataInformation.names and modelInformation.modelOutput.');
+end
+for k=1:length(dataInformation.names),
+    if isempty(strmatchSB(dataInformation.names{k},varnames,'exact')),
+        error('"dataInformation.data" does not contain a %s column.',dataInformation.names{k});
+    end
+end
+% Check covariates
+covcatNames = [COVCAT_INFORMATION.covNames COVCAT_INFORMATION.catNames];
+for k=1:length(covcatNames),
+    if isempty(strmatchSB(covcatNames{k},varnames,'exact')),
+        error('"dataInformation.data" does not contain a %s column (covariate in FIT_PK).',covcatNames{k});
+    end
+end
+% Check type
+if ~strcmpi(dataInformation.type,'continuous') && ~strcmpi(dataInformation.type,'categorical'),
+    error('Incorrect definition of "dataInformation.type".');
+end
+% Check stratify ... check that elements either empty of available in dataset as columns
+for k=1:length(dataInformation.stratify),
+    x = dataInformation.stratify{k};
+    if ~isempty(x),
+        ix = strmatchSB(x,varnames,'exact');
+        if isempty(ix),
+            error('Stratification variable "%s" not in dataset.',x);
+        end
+    end
+end
+
+% Check regressionDATA
+if ischar(dataInformation.regressionDATA) && ~isempty(dataInformation.regressionDATA),
+    dataInformation.regressionDATA = {dataInformation.regressionDATA};
+end
+
+% Check if regressionDATA in dataset
+for k=1:length(dataInformation.regressionDATA),
+    ix = strmatchSB(dataInformation.regressionDATA{k},varnames,'exact');
+    if isempty(ix),
+        error('Regression data %s is not in the dataset.',dataInformation.regressionDATA{k});
+    end
+end
+
+% check lengths
+if length(dataInformation.regressionDATA) ~= length(modelInformation.regressionPARA),
+    error('Different number of regression parameters in model and in dataset.');
+end
+
+%% Check parameterInformation
+try parameterInformation.names;         catch, error('Please define "parameterInformation.names".');     end
+try parameterInformation.values0;       catch, parameterInformation.values0 = [];                        end
+try parameterInformation.estimate;      catch, parameterInformation.estimate = [];                       end
+try parameterInformation.trans;         catch, parameterInformation.trans = {};                          end
+        
+if isempty(parameterInformation.values0),
+    parameterInformation.values0 = SBparameters(modelInformation.model,parameterInformation.names);
+    parameterInformation.values0 = parameterInformation.values0(:)';
+end
+
+if isempty(parameterInformation.estimate),
+    parameterInformation.estimate = ones(1,length(parameterInformation.names));
+end
+
+if isempty(parameterInformation.trans),
+    parameterInformation.trans = cell(1,length(parameterInformation.names));
+    parameterInformation.trans(1:end) = {'L'}';
+end
+
+if length(parameterInformation.names) ~= length(parameterInformation.values0),
+    error('Different lengths of parameterInformation.names and parameterInformation.values0.');
+end
+if length(parameterInformation.names) ~= length(parameterInformation.estimate),
+    error('Different lengths of parameterInformation.names and parameterInformation.estimate.');
+end
+if length(parameterInformation.names) ~= length(parameterInformation.trans),
+    error('Different lengths of parameterInformation.names and parameterInformation.trans.');
+end
+
+if length(parameterInformation.values0) ~= length(parameterInformation.estimate),
+    error('Different lengths of parameterInformation.values0 and parameterInformation.estimate.');
+end
+if length(parameterInformation.values0) ~= length(parameterInformation.trans),
+    error('Different lengths of parameterInformation.values0 and parameterInformation.trans.');
+end
+
+if length(parameterInformation.estimate) ~= length(parameterInformation.trans),
+    error('Different lengths of parameterInformation.estimate and parameterInformation.trans.');
+end
+
+%% Check dosingInformation
+try dosingInformation.TRT;          catch, error('Please define "dosingInformation.TRT".');          end
+try dosingInformation.dosings;      catch, error('Please define "dosingInformation.dosings".');      end
+try dosingInformation.name;         catch, error('Please define "dosingInformation.name".');         end
+try dosingInformation.weightBased;  catch, error('Please define "dosingInformation.weightBased".');  end
+try dosingInformation.TRTweighting; catch, dosingInformation.TRTweighting = ones(1,length(dosingInformation.TRT));  end
+
+% Check length of dosingInformation.TRTweighting
+if length(dosingInformation.TRTweighting) ~= length(dosingInformation.TRT),
+    error('dosingInformation.TRTweighting needs to have same length as dosingInformation.TRT.');
+end
+
+% Check that for each TRT in the data a dosing definition is present. Otherwise error
+TRTdata = unique(dataInformation.data.TRT);
+for k=1:length(TRTdata),
+    ix = find(dosingInformation.TRT == TRTdata(k), 1);
+    if isempty(ix),
+        error('No dosingInformation for TRT=%d in dataInformation.data.',TRTdata(k));
+    end
+end
+
+% Handle cell-arrays
+if isSBPOPdosing(dosingInformation.dosings),
+    dosingInformation.dosings = {dosingInformation.dosings};
+end
+if ischar(dosingInformation.name),
+    dosingInformation.name = {dosingInformation.name};
+end
+
+% Check size of dosingInformation.weightBased
+ds = struct(dosingInformation.dosings{1});
+Ninputs = length(ds.inputs);
+if size(dosingInformation.weightBased,1) ~= Ninputs,
+    error('dosingInformation.weightBased requires %d rows - one for each input in the dosing schemes.',Ninputs);
+end
+if size(dosingInformation.weightBased,2) ~= length(dosingInformation.TRT),
+    error('dosingInformation.weightBased requires %d columns - one for each TRT group.',length(dosingInformation.TRT));
+end
+
+% Check that all dosings have same structure
+dstypes1 = {ds.inputs.type};
+for k=1:length(dosingInformation.dosings),
+    dsk = struct(dosingInformation.dosings{k});
+    dstypesk = {dsk.inputs.type};
+    if length(dstypes1) ~= length(dstypesk),
+        error('Not all dosings have same input types.');
+    end
+    for k2=1:length(dstypes1),
+        if ~strcmp(dstypes1{k2},dstypesk{k2}),
+            error('Not all dosings have same input types.');
+        end            
+    end
+end
+
+% Check weight based dosing .. if present then add WT0 to required covariates but only if present in dataset. Otherwise error
+if sum(sum(dosingInformation.weightBased)) > 0,
+    % Check if WT0 in dataset
+    if isempty(strmatchSB('WT0',varnames,'exact')),
+        error('Weight based dosing present but no "WT0" column with weight information in the dataset.');
+    end
+    COVCAT_INFORMATION.covNames = unique([{'WT0'} COVCAT_INFORMATION.covNames]);
+end
+
+%% Handle options
+try options.maxtime;            catch, options.maxtime = Inf;                                        end
+try options.maxiter;            catch, options.maxiter = Inf;                                        end
+try options.maxfunevals;        catch, options.maxfunevals = 100*sum(parameterInformation.estimate); end
+try options.OPTIMIZER;          catch, options.OPTIMIZER = 'simplexSB';                              end 
+try options.N_BOOTSTRAP;        catch, options.N_BOOTSTRAP = 50;                                     end
+try options.LOG_TRANSFORM;      catch, options.LOG_TRANSFORM = 0;                                    end
+try options.SEED;               catch, options.SEED = 123456;                                        end
+try options.N_PROCESSORS;       catch, options.N_PROCESSORS = 1;                                     end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/05_ModelBuilding/auxiliary/costFunctionMedianSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/05_ModelBuilding/auxiliary/costFunctionMedianSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..1c40c63ac10338af4a295c4664f57b1e712ec1d6
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/05_ModelBuilding/auxiliary/costFunctionMedianSBPOP.m
@@ -0,0 +1,162 @@
+function [ COST, OUTPUT] = costFunctionMedianSBPOP( Xtrans , varargin)
+% costFunctionMedianSBPOP: default costfunction for the median modeling approach,
+% called by optimizeModelMedianSBPOP.
+%
+% No further documentation, since auxiliary to SBPOPrunMEDIANoptimization
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+global simulationTRTinfo 
+
+%% Determine index of estimated parameters
+ix_estimated = find(simulationTRTinfo(1).parameterInformation.estimate);
+
+%% Transform the transformed parameters Xtrans into the correct range
+X = invtransformXparametersSBPOP(Xtrans,simulationTRTinfo(1).parameterInformation.trans(ix_estimated));
+
+%% Get the parameter names and values which are considered by the median modeling (estimated or kept fixed)
+% Estimated parameters need to be set to the X value, not estimated ones kept on their initial value
+paramNames      = simulationTRTinfo(1).parameterInformation.names;          
+paramValues     = simulationTRTinfo(1).parameterInformation.values0;         
+% Set estimated parameters to their values in "X"
+paramValues(ix_estimated) = X; 
+    
+%% Cycle through the different treatment groups
+for kTRT = 1:length(simulationTRTinfo),
+    
+    %% Get simulation info structure for TRT group
+    simInfo = simulationTRTinfo(kTRT);
+
+    %% Add the PK parameters, if present, to the parameter names and values (might be different per TRT group due to covariates)
+    paramNamesSimulate  = [paramNames  simInfo.PKparamNames];
+    paramValuesSimulate = [paramValues simInfo.PKparamValues];
+    
+    %% Add the regression parameters
+    paramNamesSimulate  = [paramNames  simInfo.regressionNames];
+    paramValuesSimulate = [paramValues simInfo.regressionValues(:)'];
+    
+    %% Get dosing information 
+    dosing_sim = simInfo.DOSING;
+    
+    % Handle weight based dosing
+    %   Check if weight based dosing and then change the dose
+    %   Check for each input in the dosing scheme
+    ds = struct(dosing_sim);
+    for kx = 1:length(ds.inputs),
+        if simInfo.WEIGHTBASED(kx),
+            ds.inputs(kx).D = ds.inputs(kx).D*simInfo.WEIGHT;
+        end    
+    end
+    dosing_sim = SBPOPdosing(ds);
+    
+    %% Initialize results variable
+    NR_SIMTIMES = length(simInfo.SIMTIME);
+    NR_OUTPUTS  = length(simInfo.modelInformation.modelOutput);
+	SIMULATION_VALUES = Inf(NR_OUTPUTS,NR_SIMTIMES);
+    
+    %% Simulate
+    try
+        simres = SBPOPsimdosing(simInfo.mexModel,dosing_sim,simInfo.SIMTIME,[],paramNamesSimulate,paramValuesSimulate);
+        
+        % Read out the results
+        for kres=1:length(simInfo.modelInformation.modelOutput),
+            SIMULATION_VALUES(kres,:) = simres.variablevalues(:,variableindexSB(simInfo.moddos,simInfo.modelInformation.modelOutput{kres}))';
+        end
+    catch %#ok<CTCH>
+        disp(lasterr)  %#ok<LERR>
+        disp('Simulation error. Handled by large OFV');
+    end
+
+    % Save simulated median RR
+    simulationTRTinfo(kTRT).SIMULATION_VALUES = SIMULATION_VALUES;
+end
+
+%% Determine error and cost
+% Use weighted least square ... weighted by the standarderror of the mean
+% for each time point. TRT groups are just added together. Should be Chi2 - after
+% discussion with statisticians. Will include some user definable TRT weighting.
+DV   = {};
+PRED = {};
+WRES = {};
+RES  = {};
+TIME = {};
+TRT  = [];
+COST_TRT = [];
+
+try
+    for kTRT = 1:length(simulationTRTinfo),
+        simInfo = simulationTRTinfo(kTRT);
+
+        % Save DV and PRED
+        DV{kTRT}     = simInfo.REFERENCE_DATA;
+        PRED{kTRT}   = simInfo.SIMULATION_VALUES;
+        TIME{kTRT}   = simInfo.SIMTIME;
+        TRT(kTRT)    = simInfo.TRT;
+        
+        % Determine differences between reference and simulation 
+        % And weight by standard error
+        if ~simInfo.options.LOG_TRANSFORM,
+            % No transformation
+            % Calculate difference
+            diff = simInfo.REFERENCE_DATA-simInfo.SIMULATION_VALUES;
+            % Weighting difference by standard error of the observations
+            weighted_diff = diff./simInfo.REFERENCE_DATA_STDERR;
+        else
+            % Log transformation of data and simulation results
+            % Determine offset in case of 0 elements are present ... as 1000th of maximum values
+            offset = max([simInfo.REFERENCE_DATA(:); simInfo.SIMULATION_VALUES(:)])/1000;
+            diff = log(simInfo.REFERENCE_DATA+offset)-log(simInfo.SIMULATION_VALUES+offset);
+            % Weighting difference by standard error of the log of the observations
+            weighted_diff = diff./simInfo.REFERENCE_DATA_STDERR_LOG;
+            % For categorical data this will give NaN, but it is already checked that 
+            % with categorical (responder rate) data log tranformation can not be used (leading to an error message).
+        end
+
+        % Save RES and WRES
+        RES{kTRT}  = diff;
+        WRES{kTRT} = weighted_diff;
+        
+        % Calculate sum of squared weighted error and multiply with TRTweighting
+        WSOSerror = simInfo.TRTweighting*sum(sum(weighted_diff.^2));
+        
+        % Collect cost per treatment to use as output argument
+        COST_TRT = [COST_TRT WSOSerror];
+    end
+    COST = sum(COST_TRT);
+catch
+    COST = Inf;
+    COST_TRT = NaN;
+end
+
+%% Provide some output on the screen and save in log text
+textxx = sprintf('\tCost=%1.5g%sX=[%s]',COST,char(32*ones(1,12-length(sprintf('%1.5g',COST)))),sprintf('%g ',X));
+simulationTRTinfo(1).logText = [simulationTRTinfo(1).logText char(10) textxx];
+
+%% Generate output argument
+OUTPUT = [];
+OUTPUT.X = X;
+OUTPUT.COST = COST;
+OUTPUT.parameterNames  = paramNames;
+OUTPUT.parameterValues = paramValues;
+OUTPUT.TRT = TRT;
+OUTPUT.COST_TRT = COST_TRT;
+OUTPUT.DV = DV;
+OUTPUT.PRED = PRED;
+OUTPUT.RES  = RES;
+OUTPUT.WRES = WRES;
+OUTPUT.TIME = TIME;
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/05_ModelBuilding/auxiliary/invtransformXparametersSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/05_ModelBuilding/auxiliary/invtransformXparametersSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..e4ee69c24ee61dc05ea4a9482770689b7b29a395
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/05_ModelBuilding/auxiliary/invtransformXparametersSBPOP.m
@@ -0,0 +1,19 @@
+function [ X ] = invtransformXparametersSBPOP( xtrans, transformation )
+% Transforms parameters for the optimization from the "normal" domain into
+% the real one. Used only in the median fitting approach.
+%
+% Handle normal, lognormal, and logitnormal transformation.
+
+X = NaN(1,length(xtrans));
+
+for k=1:length(xtrans),
+    if strcmpi(transformation{k},'N'),
+        X(k) = xtrans(k);
+    elseif strcmpi(transformation{k},'L'),
+        X(k) = exp(xtrans(k));
+    elseif strcmpi(transformation{k},'G'),
+        X(k) = exp(xtrans(k))/(1+exp(xtrans(k)));
+    end
+end
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/05_ModelBuilding/auxiliary/optimizeModelMedianSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/05_ModelBuilding/auxiliary/optimizeModelMedianSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..ea29a55867ef75bb95515578ad1813e7cc4ae5b2
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/05_ModelBuilding/auxiliary/optimizeModelMedianSBPOP.m
@@ -0,0 +1,132 @@
+function [Xopt,OUTPUTopt] = optimizeModelMedianSBPOP(kBOOTSTRAP,projectfolder_stratified,mexModel,modelInformation,dataFit,parameterInformation,dosingInformation,options)
+% optimizeModelMedianSBPOP: Auxiliary and interface function between SBPOPrunMEDIANoptimization and the 
+% costfunction costFunctionMedianSBPOP. For each bootstrap this function is evaluated and handles the parameter optimization
+% of a single run.
+%
+% No further documentation, since auxiliary to SBPOPrunMEDIANoptimization
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%% Set global parameters needed for optimization
+global simulationTRTinfo 
+
+%% Get moddos ... use a dosing object from dosingInformation - any can be taken since all are supposed to have the same structure
+moddos = mergemoddosSBPOP(modelInformation.model,dosingInformation.dosings{1});
+
+%% Generate simulation information for the different TRT groups that are present in the dataset
+% Important: there can be as many dosing TRT definitions as one wants but only TRT groups that are present in the data 
+% are considered for estimation.
+simulationTRTinfo = [];
+
+% Cycle through the data TRTs
+for kTRT_data = 1:length(dataFit.TRT),
+    
+    % Find the index of the corresponding TRT in the dosingInformation
+    ixTRT_dosing                                              = find(dosingInformation.TRT==dataFit.TRT(kTRT_data));
+    
+    % Construct simulationTRTinfo structure. Each element for one TRT group
+    simulationTRTinfo(kTRT_data).TRT                        = dataFit.TRT(kTRT_data);                          % TRT code
+    simulationTRTinfo(kTRT_data).TRTNAME                    = dosingInformation.name{ixTRT_dosing};            % Corresponding TRT NAME from dosingInformation
+    simulationTRTinfo(kTRT_data).N                          = dataFit.N(kTRT_data);                            % Number of patients in TRT group
+    simulationTRTinfo(kTRT_data).SIMTIME                    = dataFit.NT{kTRT_data}(:)';                       % Nominal times to use for simulation    
+    simulationTRTinfo(kTRT_data).DOSING                     = dosingInformation.dosings{ixTRT_dosing};         % Dosing object for trial
+    simulationTRTinfo(kTRT_data).WEIGHTBASED                = dosingInformation.weightBased(:,ixTRT_dosing);   % Flag if weight based dosing (1) or not (0)
+    simulationTRTinfo(kTRT_data).REFERENCE_DATA             = dataFit.DATA{kTRT_data};                         % Reference data for cost function determination
+    simulationTRTinfo(kTRT_data).REFERENCE_DATA_STDERR      = dataFit.DATA_STDERR{kTRT_data};                  % Reference stderr data for weighting of cost function 
+    simulationTRTinfo(kTRT_data).REFERENCE_DATA_STDERR_LOG  = dataFit.DATA_STDERR_LOG{kTRT_data};              % Reference stderr on log transformed data for weighting of cost function 
+    simulationTRTinfo(kTRT_data).modelInformation           = modelInformation;                                % Pass the model information
+    simulationTRTinfo(kTRT_data).moddos                     = moddos;                                          % Pass moddos for readout of variables later
+    simulationTRTinfo(kTRT_data).mexModel                   = mexModel;                                        % Pass the name of the mex model
+    simulationTRTinfo(kTRT_data).parameterInformation       = parameterInformation;                            % Pass the parameter information
+    simulationTRTinfo(kTRT_data).options                    = options;                                         % Optimizer options
+    simulationTRTinfo(kTRT_data).TRTweighting               = dosingInformation.TRTweighting(ixTRT_dosing);    % Optimizer options
+    simulationTRTinfo(kTRT_data).regressionNames            = dataFit.regressionNames;                         % Add regression parameters
+    simulationTRTinfo(kTRT_data).regressionValues           = dataFit.regressionValues(:,kTRT_data);           % Add regression parameters
+    
+    % Check if WEIGHTBASED dosing in this TRT group and in this case define the median weight
+    if sum(simulationTRTinfo(kTRT_data).WEIGHTBASED) > 0,
+        % Get the median weight for weight based dosing
+        simulationTRTinfo(kTRT_data).WEIGHT                 = dataFit.covValues(strmatchSB(dataFit.covNames,'WT0','exact'),kTRT_data);
+    else
+        % Assign NaN
+        simulationTRTinfo(kTRT_data).WEIGHT                 = NaN;                                         
+    end
+    
+    % If FIT_PK is defined, then sample PK parameters - also taking covariates as well into account as feasible with this approach.
+    if ~isempty(modelInformation.FIT_PK),
+        % Do not take into account uncertainty (FLAG: 3)
+        % Sample 1 time only
+        % Consider covariates
+        PKparam = SBPOPsampleNLMEfitParam(modelInformation.FIT_PK,3,1,dataFit.covNames,dataFit.covValues(:,kTRT_data)',dataFit.catNames,dataFit.catValues(:,kTRT_data)');
+        % Need to check in the model and remove the PK parameters that are
+        % not present in the model
+        PKparamNotInModel = setdiff(PKparam.parameterNames,SBparameters(moddos));
+        ix_remove_PKparam = [];
+        for kPKparam=1:length(PKparamNotInModel),
+            ix_remove_PKparam = [ix_remove_PKparam strmatchSB(PKparamNotInModel{kPKparam},PKparam.parameterNames)];
+        end
+        PKparam.parameterNames(ix_remove_PKparam) = [];
+        PKparam.parameterValuesPopulation(ix_remove_PKparam) = [];
+        simulationTRTinfo(kTRT_data).PKparamNames        = PKparam.parameterNames;
+        simulationTRTinfo(kTRT_data).PKparamValues       = PKparam.parameterValuesPopulation;
+    else
+        simulationTRTinfo(kTRT_data).PKparamNames        = {};
+        simulationTRTinfo(kTRT_data).PKparamValues       = [];
+    end
+end
+
+%% Initialize log text
+simulationTRTinfo(1).logText = '';
+
+%% Handle the interface to the optimization function
+% 1) Obtain initial guesses for the parameters to be estimated
+% 2) Transform the parameters if desired (based on parameterInformation.trans)
+% 3) Perform the optimization using the costfunction
+% 4) Backtransforming the parameters if needed (based on parameterInformation.trans)
+% 5) Evaluation of the costfunction for the optimal parameters to obtain the following information
+%       - optimal cost
+%       - parameter names (all, including the not optimized ones)
+%       - parameter values (all, including the not optimized ones)
+%       - TRT group code
+%       - DV
+%       - PRED
+%       - TIME
+% 6) Save the log text for the estimation 
+
+% 1) Determine initial guess vector X0 based on provided parameter values and flags about which parameters to estimate
+X0 = parameterInformation.values0(parameterInformation.estimate==1);
+
+% 2) Transform the initial guesses based on parameter transformation
+X0_trans = transformXparametersSBPOP(X0,parameterInformation.trans(find(parameterInformation.estimate)));
+
+% 3) Run the optimization
+Xopt_trans = feval(options.OPTIMIZER,'costFunctionMedianSBPOP',X0_trans,options);
+
+% 4) Inverse transform the optimal parameters
+Xopt = invtransformXparametersSBPOP(Xopt_trans,parameterInformation.trans(find(parameterInformation.estimate)));
+
+% 5) Run the costfunction at optimized point to obtain some additional information
+[costOpt, OUTPUTopt]   = costFunctionMedianSBPOP(Xopt_trans,1);
+
+% 6) Save log text
+fid = fopen(sprintf([projectfolder_stratified '/logfiles/RUN_%d.log'],kBOOTSTRAP),'w');
+fprintf(fid,'%s',simulationTRTinfo(1).logText);
+fclose(fid);
+
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/05_ModelBuilding/auxiliary/transformXparametersSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/05_ModelBuilding/auxiliary/transformXparametersSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..6b38a4e0f09308e59d0a644ff27ccfb5e306f559
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/05_ModelBuilding/auxiliary/transformXparametersSBPOP.m
@@ -0,0 +1,25 @@
+function [ xtrans ] = transformXparametersSBPOP( X, transformation )
+% Transforms parameters for the optimization in the "normal" domain.
+% Used only in the median fitting approach.
+%
+% Handle normal, lognormal, and logitnormal transformation.
+
+xtrans = NaN(1,length(X));
+
+for k=1:length(X),
+    if strcmpi(transformation{k},'N'),
+        xtrans(k) = X(k);
+    elseif strcmpi(transformation{k},'L'),
+        xtrans(k) = log(X(k));
+    elseif strcmpi(transformation{k},'G'),
+        if X(k) >= 1,
+            xtrans(k) = 30;
+        elseif X(k) <= -1,
+            xtrans(k) = -30;
+        else
+            xtrans(k) = log(X(k)/(1-X(k)));
+        end
+    end
+end
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/06_ModelFitAnalysis/SBPOPassessConvergenceMedian.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/06_ModelFitAnalysis/SBPOPassessConvergenceMedian.m
new file mode 100644
index 0000000000000000000000000000000000000000..238776a54c94c3d42ae9febe9650b394829ea84c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/06_ModelFitAnalysis/SBPOPassessConvergenceMedian.m
@@ -0,0 +1,129 @@
+function [] = SBPOPassessConvergenceMedian(projectfolder)
+% SBPOPassessConvergenceMedian: Load the convergence information from a 
+% provided median modeling project folder and plot the trajectories for parameters,
+% and costfunction.
+%
+% USAGE:
+% ======
+% SBPOPassessConvergenceMedian(projectfolder)       
+%
+% projectfolder:        string with the path where the model results are stored 
+%                       (e.g.: logfiles folder, run_results.data, ...)
+%
+% Results are generated as PDF file and stored in the projectfolder as 
+% "OUTPUT_01_Convergence.pdf".
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+% Read run results MAT file
+run_results = load([projectfolder '/run_results.data'],'-mat'); run_results = run_results.run_results;
+
+% Read folder with logfiles
+x = dir([projectfolder '/logfiles/*.log']);
+
+% Get OFV and parameter data to assess convergence from the logfiles
+OFV_ALL = [];
+PARAMETERS_ALL = {};
+for k=1:sum(run_results.parameterInformation.estimate),
+    PARAMETERS_ALL{k} = [];
+end
+
+for k=1:length(x),
+    contents = fileread([projectfolder '/logfiles/' x(k).name]);
+    contents = strrep(contents,'Cost=','');
+    contents = strrep(contents,'X=[','');
+    contents = strrep(contents,']','');
+    contents = ['[' strtrim(contents) ']'];
+    values   = eval(contents);
+
+    nrelements  = min(run_results.options.maxfunevals,size(values,1));
+    
+    OFV         = NaN(length(1:run_results.options.maxfunevals),1);
+    OFV(1:nrelements) = values(1:nrelements,1);
+    OFV_normalized = OFV/OFV(1);
+    OFV_ALL  = [OFV_ALL OFV_normalized(:)];
+    
+    PARAMETERS = NaN(length(1:run_results.options.maxfunevals),size(values,2)-1);
+    PARAMETERS(1:nrelements,:) = values(1:nrelements,2:end);
+    
+    for k2=1:size(PARAMETERS,2),
+        PARAMETERS_ALL{k2} = [PARAMETERS_ALL{k2} PARAMETERS(1:run_results.options.maxfunevals,k2)];
+    end
+end
+
+% Start output
+filename = [projectfolder '/OUTPUT_01_Convergence'];
+startNewPrintFigureSBPOP(filename);
+
+% Do plot of OFV to assess convergence
+figure(1); clf
+plot(OFV_ALL); hold on
+grid on;
+title('Normalized OFV','FontSize',16,'Interpreter','none');
+xlabel('# cost function evaluation','FontSize',16);
+set(gca,'FontSize',14);
+set(gca,'YLim',[0 1.5]);
+printFigureSBPOP(gcf,filename);   
+
+% Do plot parameter trajectories - also for convergence
+figure(2); clf
+nrows = ceil(sqrt(sum(run_results.parameterInformation.estimate)));
+ncols = ceil(size(PARAMETERS,2)/nrows);
+PDparamNames_plot = run_results.parameterInformation.names(find(run_results.parameterInformation.estimate));
+for k2=1:sum(run_results.parameterInformation.estimate),
+    subplot(nrows,ncols,k2);
+    plot(PARAMETERS_ALL{k2}); hold on
+    grid on;
+    title(PDparamNames_plot{k2},'FontSize',14,'Interpreter','none');
+    xlabel('# cost function evaluation','FontSize',14);
+    set(gca,'FontSize',12);
+end
+printFigureSBPOP(gcf,filename);   
+
+%% Do plot median parameter trajectory and 5% and 95% quantiles
+if run_results.options.N_BOOTSTRAP > 1,
+    figure(3); clf
+    nrows = ceil(sqrt(sum(run_results.parameterInformation.estimate)));
+    ncols = ceil(size(PARAMETERS,2)/nrows);
+    PDparamNames_plot = run_results.parameterInformation.names(find(run_results.parameterInformation.estimate));
+    for k2=1:sum(run_results.parameterInformation.estimate),
+        subplot(nrows,ncols,k2);
+        plot(median(PARAMETERS_ALL{k2}'),'k','LineWidth',3); hold on
+        ranges      = [90 75 50 25];
+        colorfactor = [0.95 0.85 0.75 0.65];
+        legendText = {'Median'};
+        for kplot=1:length(ranges)
+            qlow = (1-ranges(kplot)/100)/2;
+            qhigh = 1-(1-ranges(kplot)/100)/2;
+            SBPOPplotfill(1:run_results.options.maxfunevals,quantile(PARAMETERS_ALL{k2}',qlow),quantile(PARAMETERS_ALL{k2}',qhigh),colorfactor(kplot)*[1 1 1],1,colorfactor(kplot)*[1 1 1]); hold on
+            legendText{end+1} = sprintf('%d %%',ranges(kplot));
+        end
+        plot(median(PARAMETERS_ALL{k2}'),'k','LineWidth',3); hold on
+        grid on;
+        title(PDparamNames_plot{k2},'FontSize',14,'Interpreter','none');
+        xlabel('# cost function evaluation','FontSize',14);
+        set(gca,'FontSize',12);
+        if k2==1,
+            legend(legendText,'Location','SouthEast')
+        end
+    end
+    printFigureSBPOP(gcf,filename);
+end
+
+convert2pdfSBPOP(filename);
+close all
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/06_ModelFitAnalysis/SBPOPbootstrapFitsMedian.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/06_ModelFitAnalysis/SBPOPbootstrapFitsMedian.m
new file mode 100644
index 0000000000000000000000000000000000000000..9cfe44f73621651a641702a0b749a84003437ae0
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/06_ModelFitAnalysis/SBPOPbootstrapFitsMedian.m
@@ -0,0 +1,94 @@
+function [] = SBPOPbootstrapFitsMedian(projectfolder)
+% SBPOPindividualFitsMedian: Plot the individual results from each bootstrap (DV and PRED over TIME)
+%
+% USAGE:
+% ======
+% SBPOPindividualFitsMedian(projectfolder)       
+%
+% projectfolder:        string with the path where the model results are stored 
+%                       (e.g.: logfiles folder, run_results.data, ...)
+%
+% Results are generated as PDF file and stored in the projectfolder as 
+% "OUTPUT_03_bootstrap_fits.pdf".
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%% Read tun results
+run_results = load([projectfolder '/run_results.data'],'-mat'); run_results = run_results.run_results;
+
+% get colors
+colors = getcolorsSBPOP();
+
+filename = [projectfolder '/OUTPUT_03_bootstrap_fits'];
+startNewPrintFigureSBPOP(filename);
+
+for k=1:length(run_results.run_information),
+    DV   = run_results.run_information.OUTPUTopt{k}.DV;
+    PRED = run_results.run_information.OUTPUTopt{k}.PRED;
+    TIME = run_results.run_information.OUTPUTopt{k}.TIME;
+    TRT  = run_results.run_information.OUTPUTopt{k}.TRT;
+    
+    % Determine min and max NT
+    DVcheck = [];
+    PREDcheck = [];
+    TIMEcheck = [];
+    for kcheck=1:length(TRT),
+        DVcheck     = [DVcheck; DV{kcheck}(:)];
+        PREDcheck   = [PREDcheck; PRED{kcheck}(:)];
+        TIMEcheck   = [TIMEcheck; TIME{kcheck}(:)];
+    end
+    minX = min(TIMEcheck);
+    maxX = max(TIMEcheck);
+    minY = min([DVcheck; PREDcheck]);
+    maxY = max([DVcheck; PREDcheck]);
+    
+    figure(4); clf;
+    nrows = ceil(sqrt(length(TRT)));
+    ncols = ceil(length(TRT)/nrows);
+    for k2=1:length(TRT),
+        DVk2    = DV{k2};
+        PREDk2  = PRED{k2};
+        TIMEk2  = TIME{k2};
+        TRTk2   = TRT(k2);
+        
+        figure(4);
+        subplot(nrows,ncols,k2);
+        legendText = {};
+        for k3=1:size(DVk2,1),
+            plot(TIMEk2,DVk2(k3,:),'x--','MarkerSize',12','LineWidth',2,'Color',colors(k3,:)); hold on;
+            plot(TIMEk2,PREDk2(k3,:),'-','LineWidth',2,'Color',colors(k3,:));
+            legendText{end+1} = sprintf('DV %s',run_results.dataInformation.names{k3});
+            legendText{end+1} = sprintf('PRED %s',run_results.modelInformation.modelOutput{k3});
+        end
+        grid on;
+        axis([minX maxX minY maxY]);
+        
+        if k2==mod((k)-1,length(TRT))+1,
+            h = legend(legendText,'Location','best');
+            set(h,'FontSize',10);
+            set(h,'Interpreter','none');
+        end
+
+        ix = find(run_results.dosingInformation.TRT==TRT(k2));
+        title(sprintf('%s (RUN %d)',run_results.dosingInformation.name{ix},k),'FontSize',12,'Interpreter','none');
+    end
+    printFigureSBPOP(gcf,filename)
+end
+
+convert2pdfSBPOP(filename)
+close(4)
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/06_ModelFitAnalysis/SBPOPcontributionTRTcostMedian.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/06_ModelFitAnalysis/SBPOPcontributionTRTcostMedian.m
new file mode 100644
index 0000000000000000000000000000000000000000..7815e0830428de47e986fb13a2eca150980321b2
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/06_ModelFitAnalysis/SBPOPcontributionTRTcostMedian.m
@@ -0,0 +1,64 @@
+function [] = SBPOPcontributionTRTcostMedian(projectfolder)
+% SBPOPcontributionTRTcostMedian: Assess contribution of different TRT groups to the optimal cost 
+%
+% USAGE:
+% ======
+% SBPOPcontributionTRTcostMedian(projectfolder)       
+%
+% projectfolder:        string with the path where the model results are stored 
+%                       (e.g.: logfiles folder, run_results.data, ...)
+%
+% Results are generated as PNG file and stored in the projectfolder as 
+% "OUTPUT_02_contribution_TRT_total_cost.png".
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%% Read tun results
+run_results = load([projectfolder '/run_results.data'],'-mat'); run_results = run_results.run_results;
+
+%% Get contributions to cost function
+COST_TRT = [];
+for k=1:length(run_results.run_information.OUTPUTopt),
+    COST_TRT = [COST_TRT; run_results.run_information.OUTPUTopt{k}.COST_TRT];
+end
+COST_TRT = abs(COST_TRT);
+
+%% Get TRT names
+TRTnames = {};
+allTRT = run_results.run_information.OUTPUTopt{1}.TRT;
+for k=1:length(allTRT),
+    TRTnames{k} = run_results.dosingInformation.name{find(run_results.dosingInformation.TRT==allTRT(k))};
+end
+
+%% Plot the mean 
+figure(1); clf;
+mean_Y = 100*mean(COST_TRT,1)/sum(mean(COST_TRT,1));
+if run_results.options.N_BOOTSTRAP>1,
+    std_Y  = 100*std(COST_TRT)/sum(mean(COST_TRT));
+else
+    std_Y = zeros(1,length(mean_Y));
+end
+SBbarplotErrors(mean_Y, std_Y);
+grid on;
+set(gca,'XTickLabel',TRTnames)
+set(gca,'FontSize',12);
+ylabel('Contribution to total cost [%]','FontSize',14)
+title('Contribution of TRT groups total cost','FontSize',14,'Interpreter','none')
+legend('Mean','Standard deviation');
+printFigureSBPOP(gcf,[projectfolder '/OUTPUT_02_contribution_TRT_total_cost'],'png');
+close all
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/06_ModelFitAnalysis/SBPOPcreateAllFitAssessmentsMedian.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/06_ModelFitAnalysis/SBPOPcreateAllFitAssessmentsMedian.m
new file mode 100644
index 0000000000000000000000000000000000000000..7161ea17340e0a158d6f47d0a7d26d48af1d3178
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/06_ModelFitAnalysis/SBPOPcreateAllFitAssessmentsMedian.m
@@ -0,0 +1,43 @@
+function [] = SBPOPcreateAllFitAssessmentsMedian(projectfolder,NSAMPLES_VPC)
+% SBPOPcreateAllFitAssessmentsMedian: This function generates all currently 
+% available GoF and fit assessment plots for the median modeling
+%
+% USAGE:
+% ======
+% SBPOPcreateAllFitAssessmentsMedian(projectfolder)
+% SBPOPcreateAllFitAssessmentsMedian(projectfolder,NSAMPLES_VPC)
+% 
+% projectfolder:    path to the project folder (including the stratification path)
+% NSAMPLES_VPC:     number of samples when simulating from the parametric
+%                   parameter distribution (Default: 500)
+%
+% Output: The output is stored in the projectfolder as PDF, PNG and TXT files
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+if nargin==1,
+    NSAMPLES_VPC = 500;
+end
+
+SBPOPassessConvergenceMedian(projectfolder)
+SBPOPcontributionTRTcostMedian(projectfolder)
+SBPOPbootstrapFitsMedian(projectfolder)
+SBPOPuncertaintyDistributionMedian(projectfolder)
+SBPOPvpcMedianBootstrapParam(projectfolder)
+SBPOPvpcMedianSampledParam(projectfolder,NSAMPLES_VPC)
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/06_ModelFitAnalysis/SBPOPgetParametersMedian.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/06_ModelFitAnalysis/SBPOPgetParametersMedian.m
new file mode 100644
index 0000000000000000000000000000000000000000..64d2f8cdd324c0ea6432285119dbeb32ed316462
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/06_ModelFitAnalysis/SBPOPgetParametersMedian.m
@@ -0,0 +1,49 @@
+function [ parameters, parameters_TRANS ] = SBPOPgetParametersMedian( projectfolder )
+% SBPOPgetParametersMedian: Reads the parameter estimates from the bootstraps 
+% from a PDmedian project folder. Returned are the transformed and the 
+% untransformed parameters as datasets.
+%
+% Only the estimated parameters are returned. Fixed ones are not considered.
+%
+% USAGE:
+% ======
+% [ parameters, parameters_TRANS ] = SBPOPgetParametersMedian( projectfolder )
+%
+% projectfolder:        string with the path where the model results are stored 
+%                       (e.g.: logfiles folder, run_results.data, ...)
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%% Read tun results
+run_results = load([projectfolder '/run_results.data'],'-mat'); run_results = run_results.run_results;
+
+%% Read in parameters from bootstraps and transform them
+parameters_bootstrap_all = [];
+parameters_bootstrap_all_TRANS = [];
+for k=1:length(run_results.run_information),
+    parameters                          = run_results.run_information.OUTPUTopt{k}.X;
+    parameters_bootstrap_all            = [parameters_bootstrap_all; parameters];
+    parameters_trans                    = transformXparametersSBPOP(parameters,run_results.parameterInformation.trans(find(run_results.parameterInformation.estimate)));
+    parameters_bootstrap_all_TRANS      = [parameters_bootstrap_all_TRANS; parameters_trans];
+end
+
+parameters = mat2datasetSB(parameters_bootstrap_all,run_results.parameterInformation.names(find(run_results.parameterInformation.estimate)));
+parameters_TRANS = mat2datasetSB(parameters_bootstrap_all_TRANS,run_results.parameterInformation.names(find(run_results.parameterInformation.estimate)));
+
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/06_ModelFitAnalysis/SBPOPuncertaintyDistributionMedian.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/06_ModelFitAnalysis/SBPOPuncertaintyDistributionMedian.m
new file mode 100644
index 0000000000000000000000000000000000000000..656ea28a7418e2b87a4040e31508176d24f5ff56
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/06_ModelFitAnalysis/SBPOPuncertaintyDistributionMedian.m
@@ -0,0 +1,142 @@
+function [] = SBPOPuncertaintyDistributionMedian(projectfolder)
+% SBPOPuncertaintyDistributionMedian: Plot parameter uncertainty distribution 
+% and correlations. Determine statistics.
+%
+% USAGE:
+% ======
+% SBPOPuncertaintyDistributionMedian(projectfolder)       
+%
+% projectfolder:        string with the path where the model results are stored 
+%                       (e.g.: logfiles folder, run_results.data, ...)
+%
+% Results are generated as PDF file and stored in the projectfolder as 
+% "OUTPUT_04_parameter_distributions.pdf". Additionally a table with the
+% parameter values and their correlations (both transformed and un-transformed) 
+% is generated as: OUTPUT_05_Parameter_Values.txt
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%% Read tun results
+run_results = load([projectfolder '/run_results.data'],'-mat'); run_results = run_results.run_results;
+
+%% Read in parameters from bootstraps (getting normal and transformed values)
+[parameters_bootstrap_all, parameters_bootstrap_all_TRANS] = SBPOPgetParametersMedian( projectfolder );
+
+%% Start figure
+filename = [projectfolder '/OUTPUT_04_parameter_distributions'];
+startNewPrintFigureSBPOP(filename);
+
+%% Define number of bins for histograms
+NBINS = max(5,0.1*run_results.options.N_BOOTSTRAP);
+
+%% Plot histograms of parameters
+figure(1); clf;
+N_paramEstimates = size(parameters_bootstrap_all,2);
+nrows = ceil(sqrt(N_paramEstimates));
+ncols = ceil(N_paramEstimates/nrows);
+PDparamNamesEst = get(parameters_bootstrap_all,'VarNames');
+for k=1:N_paramEstimates,
+    subplot(nrows,ncols,k);
+    hist(double(parameters_bootstrap_all(:,k)),NBINS);
+    title(PDparamNamesEst{k},'FontSize',14,'Interpreter','none');
+    grid on;
+end
+printFigureSBPOP(gcf,filename);
+
+%% Plot histograms of transformed parameters
+figure(1); clf;
+N_paramEstimates = size(parameters_bootstrap_all,2);
+nrows = ceil(sqrt(N_paramEstimates));
+ncols = ceil(N_paramEstimates/nrows);
+% Rename parameters
+PDparamNamesEst_trans = {};
+transInfo = run_results.parameterInformation.trans(find(run_results.parameterInformation.estimate));
+for k=1:length(PDparamNamesEst),
+    if strcmp(transInfo{k},'N'),
+        PDparamNamesEst_trans{k} = PDparamNamesEst{k};
+    elseif strcmp(transInfo{k},'L'),
+        PDparamNamesEst_trans{k} = ['log(' PDparamNamesEst{k} ')'];
+    elseif strcmp(transInfo{k},'G'),
+        PDparamNamesEst_trans{k} = ['logit(' PDparamNamesEst{k} ')'];
+    end
+end
+for k=1:N_paramEstimates,
+    subplot(nrows,ncols,k);
+    hist(double(parameters_bootstrap_all_TRANS(:,k)),20);
+    title(PDparamNamesEst_trans{k},'FontSize',14,'Interpreter','none');
+    grid on;    
+end
+printFigureSBPOP(gcf,filename);
+
+%% Plot correlation information for parameters
+gplotmatrix(double(parameters_bootstrap_all),[],[],[],[],[],[],[],PDparamNamesEst,PDparamNamesEst);
+printFigureSBPOP(gcf,filename);
+
+%% Plot correlation information for transformed parameters
+gplotmatrix(double(parameters_bootstrap_all_TRANS),[],[],[],[],[],[],[],PDparamNamesEst_trans,PDparamNamesEst_trans);
+printFigureSBPOP(gcf,filename);
+
+%% Close figure
+convert2pdfSBPOP(filename)
+
+%% Calculate mean, median, stderror and RSE of mean
+median_param = median(double(parameters_bootstrap_all),1);
+mean_param   = mean(double(parameters_bootstrap_all),1);
+if run_results.options.N_BOOTSTRAP>1,
+    stderr_param    = std(double(parameters_bootstrap_all))/sqrt(run_results.options.N_BOOTSTRAP);
+else
+    stderr_param    = zeros(1,length(median_param));
+end
+RSEmean_param = 100*stderr_param./mean_param;
+% Determine correlation of untransformed parameters
+corrx = num2str(round(100*corr(double(parameters_bootstrap_all)))/100);
+% Get parameter names
+PDparamNamesEst = get(parameters_bootstrap_all,'VarNames');
+
+% Write out the results in a table
+fid = fopen([projectfolder '/OUTPUT_05_Parameter_Values.txt'],'w');
+fprintf(fid,'==================================================================\n');
+fprintf(fid,'=                     Parameter estimates                        =\n');
+fprintf(fid,'==================================================================\n');
+fprintf(fid,'\n');
+text = sprintf('Parameter       MEDIAN      MEAN        STD         RSE(MEAN)\n');
+text = sprintf('%s------------------------------------------------------------------',text);
+for k=1:sum(run_results.parameterInformation.estimate),
+    text = sprintf('%s\n%s %s%1.3g%s%1.3g%s%1.3g%s%1.3g%%',text,...
+        PDparamNamesEst{k},...
+        char(32*ones(1,15-length(PDparamNamesEst{k}))),...
+        median_param(k),...
+        char(32*ones(1,12-length(sprintf('%1.3g',median_param(k))))),...
+        mean_param(k),...
+        char(32*ones(1,12-length(sprintf('%1.3g',mean_param(k))))),...
+        stderr_param(k),...
+        char(32*ones(1,12-length(sprintf('%1.3g',stderr_param(k))))),...
+        RSEmean_param(k));
+end
+fprintf(fid,'%s',text);
+
+text = fprintf(fid,'\n\nCorrelations\n------------------------------------------------------------------\n');
+
+for k=1:size(corrx,1),
+    fprintf(fid,'%s\n',corrx(k,:));
+end
+
+
+fclose(fid);
+
+close all
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/06_ModelFitAnalysis/SBPOPvpcMedianBootstrapParam.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/06_ModelFitAnalysis/SBPOPvpcMedianBootstrapParam.m
new file mode 100644
index 0000000000000000000000000000000000000000..edef1bf09645cc8e2f4a600a9817cfedb0a6de63
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/06_ModelFitAnalysis/SBPOPvpcMedianBootstrapParam.m
@@ -0,0 +1,268 @@
+function [] = SBPOPvpcMedianBootstrapParam(projectfolder)
+% SBPOPvpcMedianBootstrapParam: Generate a VPC based on the bootstrap parameters
+%
+% USAGE:
+% ======
+% SBPOPvpcMedianBootstrapParam(projectfolder)       
+%
+% projectfolder:        string with the path where the model results are stored 
+%                       (e.g.: logfiles folder, run_results.data, ...)
+%
+% Results are generated as PDF file and stored in the projectfolder as 
+% "OUTPUT_06_VPC_bootstrapParameters.pdf". 
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%% Read tun results
+run_results = load([projectfolder '/run_results.data'],'-mat'); run_results = run_results.run_results;
+
+%% Get colors
+colors = getcolorsSBPOP();
+
+%% Get the original data structure for the median fitting
+DATAmedian = run_results.dataOriginalStratifiedMedian;
+
+%% Produce MEX model
+moddos                          = mergemoddosSBPOP(run_results.modelInformation.model,run_results.dosingInformation.dosings{1});
+mexModelName                    = 'mexModel_VPC';
+SBPDmakeMEXmodel(moddos,mexModelName);
+
+%% Get PD parameters from bootstrap
+parameterNames  = run_results.run_information.OUTPUTopt{1}.parameterNames;   
+parameterValues = [];
+for k=1:length(run_results.run_information),
+    parameterValues = [parameterValues; run_results.run_information.OUTPUTopt{k}.parameterValues];
+end
+NSIM = length(run_results.run_information);
+
+%% Get allTRTs that were in the fit
+allTRT = DATAmedian.TRT;
+
+%% Simulate
+PK_ALL_TRT          = {};
+READOUTS_ALL_TRT    = {};
+SIMTIME_TRT         = {};
+
+parfor kTRT = 1:length(allTRT),
+    
+    % Get treatment info
+    TRT = allTRT(kTRT);
+    
+    % Get index in dosingInfomation
+    ix = find(run_results.dosingInformation.TRT==TRT);
+       
+    % Get default simulation parameters 
+    paramNamesSim  = [parameterNames];
+    paramValuesSim = [parameterValues];
+    
+    % Sample PK population parameters (include median covariate information)
+    if ~isempty(run_results.modelInformation.FIT_PK),
+        PKparam = SBPOPsampleNLMEfitParam(run_results.modelInformation.FIT_PK,3,1,DATAmedian.covNames,DATAmedian.covValues(:,kTRT)',DATAmedian.catNames,DATAmedian.catValues(:,kTRT)');
+        % Need to check in the model and remove the PK parameters that ae
+        % not present in the model
+        PKparamNotInModel = setdiff(PKparam.parameterNames,SBparameters(moddos));
+        ix_remove_PKparam = [];
+        for kPKparam=1:length(PKparamNotInModel),
+            ix_remove_PKparam = [ix_remove_PKparam strmatchSB(PKparamNotInModel{kPKparam},PKparam.parameterNames)];
+        end
+        PKparam.parameterNames(ix_remove_PKparam) = [];
+        PKparam.parameterValuesPopulation(ix_remove_PKparam) = [];
+        
+        % Combine PK and PD parameters
+        paramNamesSim  = [paramNamesSim   PKparam.parameterNames];
+        paramValuesSim = [paramValuesSim  PKparam.parameterValuesPopulation(ones(1,NSIM),:)];
+    end
+    
+    % Add regression parameters
+    paramNamesSim  = [paramNamesSim run_results.dataOriginalStratifiedMedian.regressionNames];
+    regvalues = run_results.dataOriginalStratifiedMedian.regressionValues(:,kTRT)';
+    paramValuesSim = [paramValuesSim  regvalues(ones(1,NSIM),:)];
+    
+    % Get dosing information 
+    dosing_sim          = run_results.dosingInformation.dosings{ix};
+    
+    % Handle weight based dosing
+    %   Check if weight based dosing and then change the dose
+    %   Check for each input in the dosing scheme
+    ds = struct(dosing_sim);
+    for kx = 1:length(ds.inputs),
+        if run_results.dosingInformation.weightBased(kx,ix),
+            medianWEIGHT = DATAmedian.covValues(strmatchSB(DATAmedian.covNames,'WT0','exact'),kTRT);
+            ds.inputs(kx).D = ds.inputs(kx).D*medianWEIGHT;
+        end    
+    end
+    dosing_sim = SBPOPdosing(ds);
+        
+    % Define SIMTIME
+    SIMTIME = unique([0; run_results.dataOriginalStratifiedMedian.NT{kTRT}]);
+    SIMTIME = linspace(min(SIMTIME),max(SIMTIME),100);
+    
+    % Simulate
+    PK_ALL = NaN(length(SIMTIME),NSIM);
+    READOUTS_ALL = cell(1,length(run_results.modelInformation.modelOutput));
+    for kx=1:length(run_results.modelInformation.modelOutput),
+        READOUTS_ALL{kx} = NaN(length(SIMTIME),NSIM);
+    end
+    for kSIM=1:NSIM,
+        kSIM
+        try
+            simres = SBPOPsimdosing(mexModelName,dosing_sim,SIMTIME,[],paramNamesSim,paramValuesSim(kSIM,:));
+            
+            % Get the PK ... assume Cc is the one.
+            if ~isempty(variableindexSB(moddos,'Cc')),
+                PK_ALL(:,kSIM) = simres.variablevalues(:,variableindexSB(moddos,'Cc'));
+            end
+            
+            % Get the other readouts
+            for kx=1:length(run_results.modelInformation.modelOutput),
+                READOUTS_ALL{kx}(:,kSIM) = simres.variablevalues(:,variableindexSB(moddos,run_results.modelInformation.modelOutput{kx}));
+            end
+        catch
+        end
+    end
+   
+    PK_ALL_TRT{kTRT}            = PK_ALL;
+    READOUTS_ALL_TRT{kTRT}      = READOUTS_ALL;
+    SIMTIME_TRT{kTRT} = SIMTIME;    
+end
+
+%% start output
+filename = [projectfolder '/OUTPUT_06_VPC_bootstrapParameters'];
+startNewPrintFigureSBPOP(filename)
+
+%% Plot PK results
+if ~isempty(variableindexSB(moddos,'Cc')),
+    % Get max and min conc
+    PKx = [];
+    for k=1:length(PK_ALL_TRT),
+        PKx = [PKx; PK_ALL_TRT{k}(:)];
+    end
+    PKx(PKx==0) = [];
+    minPK = min(PKx);
+    maxPK = max(PKx);
+    
+    figure(1); clf;
+    nrows = ceil(sqrt(length(PK_ALL_TRT)));
+    ncols = ceil(length(PK_ALL_TRT)/nrows);
+    PK_X = [];
+    for kTRT=1:length(PK_ALL_TRT),
+        PK_X  = [PK_X; PK_ALL_TRT{kTRT}(:)];
+    end
+    minY = min(log10(PK_X));
+    maxY = max(log10(PK_X));
+    for kTRT=1:length(allTRT),
+        subplot(nrows,ncols,kTRT);
+        PK_TRT  = PK_ALL_TRT{kTRT};
+        SIMTIME  = SIMTIME_TRT{kTRT};
+        plot(SIMTIME,log10(nanmedian(PK_TRT')),'k-','LineWidth',2)
+        % Annotate
+        if kTRT>length(PK_ALL_TRT)-ncols,
+            xlabel('Time')
+        end
+        if mod(kTRT,ncols) == 1,
+            ylabel('Conc')
+        end
+        grid on;
+        set(gca,'YTick',[0 1 2 3 4 5 6]);
+        set(gca,'YTickLabel',10.^get(gca,'YTick'));
+        set(gca,'XLim',[min(SIMTIME) max(SIMTIME)]);
+        set(gca,'YLim',[log10(minPK) log10(maxPK)]);
+        
+        % Get treatment name
+        ix = find(run_results.dosingInformation.TRT==allTRT(kTRT));
+        title(run_results.dosingInformation.name{ix},'Interpreter','none');
+    end
+    printFigureSBPOP(gcf,filename)
+end
+
+%% Plot Readout results
+SIMTIME_X = [];
+RO_Y = [];
+for k=1:length(PK_ALL_TRT),
+    SIMTIME_X = [SIMTIME_X SIMTIME_TRT{k}];
+    for kRO=1:length(run_results.modelInformation.modelOutput),
+        RO_Y      = [RO_Y; READOUTS_ALL_TRT{k}{kRO}(:)]; 
+    end
+end
+
+%%
+for kRO = 1:length(run_results.modelInformation.modelOutput),
+    
+    figure(kRO+1); clf;
+    nrows = ceil(sqrt(length(PK_ALL_TRT)));
+    ncols = ceil(length(PK_ALL_TRT)/nrows);
+
+    for kTRT=1:length(allTRT),
+        subplot(nrows,ncols,kTRT);
+        
+        RO_TRT = READOUTS_ALL_TRT{kTRT}{kRO};
+        SIMTIME = SIMTIME_TRT{kTRT};
+        
+        % Plot the data
+        data = run_results.dataOriginalStratifiedMedian.DATA{kTRT}(kRO,:);
+        time = run_results.dataOriginalStratifiedMedian.NT{kTRT};
+        plot(time,data,'.-','MarkerSize',25,'Color',0.3*[1 1 1]); hold on
+
+        plot(SIMTIME,nanmedian(RO_TRT'),'-','LineWidth',2,'Color',0.8*colors(kRO,:)); hold on
+        
+        ranges      = [90 75 50 25];
+        colorfactor = [0.65 0.5 0.35 0.2];
+        legendText = {'Observations',sprintf('Simulated median (N=%d)',run_results.options.N_BOOTSTRAP)};
+        for kplot=1:length(ranges)
+            qlow = (1-ranges(kplot)/100)/2;
+            qhigh = 1-(1-ranges(kplot)/100)/2;
+            SBPOPplotfill(SIMTIME,quantile(RO_TRT',qlow),quantile(RO_TRT',qhigh),min(colorfactor(kplot)+colors(kRO,:),1),1,min(colorfactor(kplot)+colors(kRO,:),1)); hold on;
+            legendText{end+1} = sprintf('%d %% CI',ranges(kplot));
+        end
+        
+        plot(SIMTIME,nanmedian(RO_TRT'),'-','LineWidth',2,'Color',0.8*colors(kRO,:)); hold on
+        
+        % Plot errorbars on data
+        data_stderr = run_results.dataOriginalStratifiedMedian.DATA_STDERR{kTRT}(kRO,:);
+        errorbar(time,data,data_stderr,'Color',0.3*[1 1 1])
+        
+        % Annotate
+        if kTRT>length(PK_ALL_TRT)-ncols,
+            xlabel('Time')
+        end
+        if mod(kTRT,ncols) == 1,
+            ylabel(sprintf('%s',run_results.dataInformation.names{kRO}),'Interpreter','none')
+        end
+        grid on;
+        set(gca,'XLim',[min(SIMTIME_X) max(SIMTIME_X)]);
+        set(gca,'YLim',[min(RO_Y)*0.9 max(RO_Y)*1.1]);
+        ix = find(run_results.dosingInformation.TRT==allTRT(kTRT));
+        title(run_results.dosingInformation.name{ix},'Interpreter','none');
+        
+        % Plot the data
+        data = run_results.dataOriginalStratifiedMedian.DATA{kTRT}(kRO,:);
+        time = run_results.dataOriginalStratifiedMedian.NT{kTRT};
+        plot(time,data,'.-','MarkerSize',25,'Color',0.3*[1 1 1]);
+    end
+    % Add legend
+    subplot(nrows,ncols,1);
+    legend(legendText,'Location','NorthEast')
+    printFigureSBPOP(gcf,filename)
+end
+%%
+convert2pdfSBPOP(filename);
+close all
+
+% Delete mex file
+clear mex
+delete([mexModelName '.' mexext]);
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/06_ModelFitAnalysis/SBPOPvpcMedianSampledParam.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/06_ModelFitAnalysis/SBPOPvpcMedianSampledParam.m
new file mode 100644
index 0000000000000000000000000000000000000000..0628864f6bb0c82451097ee00245e3bbbe1de554
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/06_ModelFitAnalysis/SBPOPvpcMedianSampledParam.m
@@ -0,0 +1,318 @@
+function [] = SBPOPvpcMedianSampledParam(projectfolder,varargin)
+% SBPOPvpcMedianSampledParam: Do VPC based on sampled parameters from the 
+% uncertainty distribution. Use transformed parameters to determine the 
+% distribution to sample from. Transformed parameters ensure better results
+% e.g. due to correct sign etc.
+%
+% For sampling, the mean, the std, and the correlation between the parameters are used.
+%
+% USAGE:
+% ======
+% SBPOPvpcMedianSampledParam(projectfolder)       
+% SBPOPvpcMedianSampledParam(projectfolder,NSAMPLES)       
+%
+% projectfolder:        string with the path where the model results are stored 
+%                       (e.g.: logfiles folder, run_results.data, ...)
+% NSAMPLES:             Number of samples to simulate for the VPC (default: 200)
+%
+% Results are generated as PDF file and stored in the projectfolder as 
+% "OUTPUT_07_VPC_sampledParameters.pdf". 
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%% Handle variable input arguments
+NSAMPLES = 200;
+if nargin == 2,
+    NSAMPLES = varargin{1};
+end
+
+%% Read tun results
+run_results = load([projectfolder '/run_results.data'],'-mat'); run_results = run_results.run_results;
+
+%% Get colors
+colors = getcolorsSBPOP();
+
+%% Get the original data structure for the median fitting
+DATAmedian = run_results.dataOriginalStratifiedMedian;
+
+%% Produce MEX model
+moddos                          = mergemoddosSBPOP(run_results.modelInformation.model,run_results.dosingInformation.dosings{1});
+mexModelName                    = 'mexModel_VPC';
+SBPDmakeMEXmodel(moddos,mexModelName);
+
+%% Get PD parameters from bootstrap and sample from the distribution
+% Only get the estimated ones (not the fixed ones)
+[xdummyx, parameters_bootstrap_all_TRANS] = SBPOPgetParametersMedian(projectfolder);
+% Get names and numeric values
+parameterNames = get(parameters_bootstrap_all_TRANS,'VarNames');
+parameters_bootstrap_all_TRANS = double(parameters_bootstrap_all_TRANS);
+% Use the transformed parameters for the sampling!
+
+% Determine the distribution of the parameterValues and sample from it
+mean_PD  = mean(parameters_bootstrap_all_TRANS);
+std_PD   = std(parameters_bootstrap_all_TRANS);
+corr_PD  = corr(parameters_bootstrap_all_TRANS);
+sigma_PD = std_PD'*std_PD;
+% Handle non pos-semidefinite sigma_PD
+[eigV,eigD] = eig(sigma_PD);
+if min(diag(eigD)) > -1e-3,
+    % It is not positive semidefinite, but the smallest eigenvalue
+    % is so close to zero that we are going to put it on zero
+    eigD(eigD<0) = 0;
+    sigma_PD = eigV*eigD*inv(eigV);
+    disp('Covariance matrix not positive semidefinite. Smallest eigenvalue is closer to 0 than -1e-3 => making it positive semidefinite.');
+end
+cov_PD   = corr_PD.*sigma_PD;
+parameterValuesSAMPLED_TRANS = mvnrnd(mean_PD,cov_PD,NSAMPLES);
+
+% Inverse transform the sampled parameters
+parameterValuesSAMPLED = [];
+for k=1:NSAMPLES,
+    parameterValuesSAMPLED = [parameterValuesSAMPLED; invtransformXparametersSBPOP(parameterValuesSAMPLED_TRANS(k,:),run_results.parameterInformation.trans(find(run_results.parameterInformation.estimate)))];
+end
+
+% Add missing not estimated parameters
+parameterNamesAdd   = run_results.parameterInformation.names(find(~run_results.parameterInformation.estimate));
+parameterValuesAdd  = run_results.parameterInformation.values0(find(~run_results.parameterInformation.estimate));
+
+parameterNames          = [parameterNames parameterNamesAdd];
+parameterValuesSAMPLED  = [parameterValuesSAMPLED parameterValuesAdd(ones(1,size(parameterValuesSAMPLED,1)),:)];
+
+% Assign sampled PD parameters to the parameters used
+parameterValues = parameterValuesSAMPLED;
+NSIM = NSAMPLES;
+
+%% Get allTRTs that were in the fit
+allTRT = DATAmedian.TRT;
+        
+%% Simulate
+PK_ALL_TRT          = {};
+READOUTS_ALL_TRT    = {};
+SIMTIME_TRT         = {};
+
+parfor kTRT = 1:length(allTRT),
+    
+    % Get treatment info
+    TRT                                         = allTRT(kTRT);
+    
+    % Get index in dosingInfomation
+    ix                                          = find(run_results.dosingInformation.TRT==TRT);
+       
+    % Get default simulation parameters 
+    paramNamesSim  = [parameterNames];
+    paramValuesSim = [parameterValues];
+    
+    % Sample PK population parameters (include median covariate information)
+    if ~isempty(run_results.modelInformation.FIT_PK),
+        PKparam = SBPOPsampleNLMEfitParam(run_results.modelInformation.FIT_PK,3,1,DATAmedian.covNames,DATAmedian.covValues(:,kTRT)',DATAmedian.catNames,DATAmedian.catValues(:,kTRT)');
+        % Need to check in the model and remove the PK parameters that ae
+        % not present in the model
+        PKparamNotInModel = setdiff(PKparam.parameterNames,SBparameters(moddos));
+        ix_remove_PKparam = [];
+        for kPKparam=1:length(PKparamNotInModel),
+            ix_remove_PKparam = [ix_remove_PKparam strmatchSB(PKparamNotInModel{kPKparam},PKparam.parameterNames)];
+        end
+        PKparam.parameterNames(ix_remove_PKparam) = [];
+        PKparam.parameterValuesPopulation(ix_remove_PKparam) = [];
+        
+        % Combine PK and PD parameters
+        paramNamesSim  = [paramNamesSim   PKparam.parameterNames];
+        paramValuesSim = [paramValuesSim  PKparam.parameterValuesPopulation(ones(1,NSIM),:)];
+    end
+    
+    % Add regression parameters
+    paramNamesSim  = [paramNamesSim run_results.dataOriginalStratifiedMedian.regressionNames];
+    regvalues = run_results.dataOriginalStratifiedMedian.regressionValues(:,kTRT)';
+    paramValuesSim = [paramValuesSim  regvalues(ones(1,NSIM),:)];
+    
+    % Get dosing information 
+    dosing_sim          = run_results.dosingInformation.dosings{ix};
+    
+    % Handle weight based dosing
+    %   Check if weight based dosing and then change the dose
+    %   Check for each input in the dosing scheme
+    ds = struct(dosing_sim);
+    for kx = 1:length(ds.inputs),
+        if run_results.dosingInformation.weightBased(kx,ix),
+            medianWEIGHT = DATAmedian.covValues(strmatchSB(DATAmedian.covNames,'WT0','exact'),kTRT);
+            ds.inputs(kx).D = ds.inputs(kx).D*medianWEIGHT;
+        end    
+    end
+    dosing_sim = SBPOPdosing(ds);
+        
+    % Define SIMTIME
+    SIMTIME = unique([0; run_results.dataOriginalStratifiedMedian.NT{kTRT}]);
+    SIMTIME = linspace(min(SIMTIME),max(SIMTIME),100);
+    
+    % Simulate
+    PK_ALL = NaN(length(SIMTIME),NSIM);
+    READOUTS_ALL = cell(1,length(run_results.modelInformation.modelOutput));
+    for kx=1:length(run_results.modelInformation.modelOutput),
+        READOUTS_ALL{kx} = NaN(length(SIMTIME),NSIM);
+    end
+    for kSIM=1:NSIM,
+        kSIM
+        try
+            simres = SBPOPsimdosing(mexModelName,dosing_sim,SIMTIME,[],paramNamesSim,paramValuesSim(kSIM,:));
+            
+            % Get the PK ... assume Cc is the one.
+            if ~isempty(variableindexSB(moddos,'Cc')),
+                PK_ALL(:,kSIM) = simres.variablevalues(:,variableindexSB(moddos,'Cc'));
+            end
+            
+            % Get the other readouts
+            for kx=1:length(run_results.modelInformation.modelOutput),
+                READOUTS_ALL{kx}(:,kSIM) = simres.variablevalues(:,variableindexSB(moddos,run_results.modelInformation.modelOutput{kx}));
+            end
+        catch
+        end
+    end
+   
+    PK_ALL_TRT{kTRT}            = PK_ALL;
+    READOUTS_ALL_TRT{kTRT}      = READOUTS_ALL;
+    SIMTIME_TRT{kTRT} = SIMTIME;    
+end
+
+%% start output
+filename = [projectfolder '/OUTPUT_07_VPC_sampledParameters'];
+startNewPrintFigureSBPOP(filename)
+
+%% Plot PK results
+if ~isempty(variableindexSB(moddos,'Cc')),
+    % Get max and min conc
+    PKx = [];
+    for k=1:length(PK_ALL_TRT),
+        PKx = [PKx; PK_ALL_TRT{k}(:)];
+    end
+    PKx(PKx==0) = [];
+    minPK = min(PKx);
+    maxPK = max(PKx);
+
+    figure(1); clf;
+    nrows = ceil(sqrt(length(PK_ALL_TRT)));
+    ncols = ceil(length(PK_ALL_TRT)/nrows);
+    PK_X = [];
+    for kTRT=1:length(PK_ALL_TRT),
+        PK_X  = [PK_X; PK_ALL_TRT{kTRT}(:)];
+    end
+    minY = min(log10(PK_X));
+    maxY = max(log10(PK_X));
+    for kTRT=1:length(allTRT),
+        subplot(nrows,ncols,kTRT);
+        PK_TRT  = PK_ALL_TRT{kTRT};
+        SIMTIME  = SIMTIME_TRT{kTRT};
+        plot(SIMTIME,log10(nanmedian(PK_TRT')),'k-','LineWidth',2)
+        % Annotate
+        if kTRT>length(PK_ALL_TRT)-ncols,
+            xlabel('Time')
+        end
+        if mod(kTRT,ncols) == 1,
+            ylabel('Conc')
+        end
+        grid on;
+        set(gca,'YTick',[0 1 2 3 4 5 6]);
+        set(gca,'YTickLabel',10.^get(gca,'YTick'));
+        set(gca,'XLim',[min(SIMTIME) max(SIMTIME)]);
+        set(gca,'YLim',[log10(minPK) log10(maxPK)]);
+        
+        % Get treatment name
+        ix = find(run_results.dosingInformation.TRT==allTRT(kTRT));
+        title(run_results.dosingInformation.name{ix},'Interpreter','none');
+    end
+    printFigureSBPOP(gcf,filename)
+end
+
+%% Plot Readout results
+SIMTIME_X = [];
+RO_Y = [];
+for k=1:length(allTRT),
+    SIMTIME_X = [SIMTIME_X SIMTIME_TRT{k}];
+    for kRO=1:length(run_results.modelInformation.modelOutput),
+        RO_Y      = [RO_Y; READOUTS_ALL_TRT{k}{kRO}(:)]; 
+    end
+end
+% Postprocess RO_Y
+RO_Y(isnan(RO_Y)) = [];
+RO_Y = [min(RO_Y) min(max(RO_Y),median(RO_Y)*10)];
+
+for kRO = 1:length(run_results.modelInformation.modelOutput),
+    
+    figure(kRO+1); clf;
+    nrows = ceil(sqrt(length(PK_ALL_TRT)));
+    ncols = ceil(length(PK_ALL_TRT)/nrows);
+
+    for kTRT=1:length(PK_ALL_TRT),
+        subplot(nrows,ncols,kTRT);
+        
+        RO_TRT = READOUTS_ALL_TRT{kTRT}{kRO};
+        SIMTIME = SIMTIME_TRT{kTRT};
+        
+        % Plot the data
+        data = run_results.dataOriginalStratifiedMedian.DATA{kTRT}(kRO,:);
+        time = run_results.dataOriginalStratifiedMedian.NT{kTRT};
+        plot(time,data,'.-','MarkerSize',25,'Color',0.3*[1 1 1]); hold on
+
+        plot(SIMTIME,nanmedian(RO_TRT'),'-','LineWidth',2,'Color',0.8*colors(kRO,:)); hold on
+        
+        ranges      = [90 75 50 25];
+        colorfactor = [0.65 0.5 0.35 0.2];
+        legendText = {'Observations',sprintf('Simulated median (N=%d)',NSAMPLES)};
+        for kplot=1:length(ranges)
+            qlow = (1-ranges(kplot)/100)/2;
+            qhigh = 1-(1-ranges(kplot)/100)/2;
+            SBPOPplotfill(SIMTIME,quantile(RO_TRT',qlow),quantile(RO_TRT',qhigh),min(colorfactor(kplot)+colors(kRO,:),1),1,min(colorfactor(kplot)+colors(kRO,:),1)); hold on;
+            legendText{end+1} = sprintf('%d %% CI',ranges(kplot));
+        end
+        
+        plot(SIMTIME,nanmedian(RO_TRT'),'-','LineWidth',2,'Color',0.8*colors(kRO,:)); hold on
+        
+        % Plot errorbars on data
+        data_stderr = run_results.dataOriginalStratifiedMedian.DATA_STDERR{kTRT}(kRO,:);
+        errorbar(time,data,data_stderr,'Color',0.3*[1 1 1])
+        
+        % Annotate
+        if kTRT>length(PK_ALL_TRT)-ncols,
+            xlabel('Time')
+        end
+        if mod(kTRT,ncols) == 1,
+            ylabel(sprintf('%s',run_results.dataInformation.names{kRO}),'Interpreter','none')
+        end
+        grid on;
+        set(gca,'XLim',[min(SIMTIME_X) max(SIMTIME_X)]);
+        set(gca,'YLim',[min(RO_Y)*0.9 max(RO_Y)*1.1]);
+        ix = find(run_results.dosingInformation.TRT==allTRT(kTRT));
+        title(run_results.dosingInformation.name{ix},'Interpreter','none');
+        
+        % Plot the data
+        data = run_results.dataOriginalStratifiedMedian.DATA{kTRT}(kRO,:);
+        time = run_results.dataOriginalStratifiedMedian.NT{kTRT};
+        plot(time,data,'.-','MarkerSize',25,'Color',0.3*[1 1 1]);
+    end
+    % Add legend
+    subplot(nrows,ncols,1);
+    legend(legendText,'Location','NorthEast')
+    printFigureSBPOP(gcf,filename)
+end
+
+convert2pdfSBPOP(filename);
+close all
+
+% Delete mex file
+clear mex
+delete([mexModelName '.' mexext]);
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/11_Simulation/SBPOPsimulationMedianBootstrapParam.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/11_Simulation/SBPOPsimulationMedianBootstrapParam.m
new file mode 100644
index 0000000000000000000000000000000000000000..d2f5052aaea09ddf7b585b4cfc9f573bff9d3557
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/11_Simulation/SBPOPsimulationMedianBootstrapParam.m
@@ -0,0 +1,355 @@
+function [] = SBPOPsimulationMedianBootstrapParam(projectfolder,dosingInformation,data,SIMTIME,filename)
+% SBPOPsimulationMedianBootstrapParam: Similar function as "SBPOPvpcMedianBootstrapParam"
+% The difference to the VPC is that additional dosing schemes can be
+% simulated. If data available then it is plotted. If not then just
+% simulation. Additionally, a plot is generated, comparing the median/responder rate
+% results without uncertainty for the different provided dosing schemes.
+%
+% dosingInformation is not used from the run_results of the
+% project but from the user provided input argument. 
+%
+% The data is not used from the run_results, but from the provided input
+% argument. Same transformations will be done as specified in the
+% run_results.
+%
+% Simulations based on bootstrap parameter estimates.
+%
+% USAGE:
+% ======
+% SBPOPsimulationMedianBootstrapParam(projectfolder,dosingInformation,data,SIMTIME,filename)   
+%
+% projectfolder:        string with the path where the model results are stored 
+%                       (e.g.: logfiles folder, run_results.data, ...)
+% dosingInformation:	structure with information about the nominal treatment group dosings
+%   dosingInformation.TRT:          Vector with treatment group identifiers to be used in optimization
+%                                   TRT groups are optimized if dosings AND data are available - otherwise ignored!
+%                                   It will be checked that for each TRT in the data a dosing definition is present. Otherwise error!
+%   dosingInformation.dosings:      Cell-array defining nominal dosings for each treatment group
+%   dosingInformation.name:         Cell-array defining names for each treatment group
+%   dosingInformation.weightBased:  Matrix with as many rows as dosing inputs in the model and as many columns as treatment groups.
+%                                   A "0" entry defines fixed dosing and a "1" entry defines weight based dosing.
+%                                   If weight based dosing is used, the dataInformation.data dataset needs to contain a WT0 column.
+%
+% data:                 Matlab dataset in the median modeling format
+% SIMTIME:              Time vector for the simulations
+% filename:             Path, including name for the generated PDF
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%% Read tun results
+run_results = load([projectfolder '/run_results.data'],'-mat'); run_results = run_results.run_results;
+
+%% Get colors
+colors = getcolorsSBPOP();
+
+%% Get covariate information
+% Parse covariate information from potential FIT_PK model
+COVCAT_INFORMATION = [];
+[COVCAT_INFORMATION.covNames, COVCAT_INFORMATION.catNames, COVCAT_INFORMATION.referenceCAT] = getCovariateInformationSBPOP(run_results.modelInformation.FIT_PK);
+% Check weight based dosing .. if present then add WT0 to required covariates but only if present in dataset. Otherwise error
+if sum(sum(dosingInformation.weightBased)) > 0,
+    % Check if WT0 in dataset
+    if isempty(strmatchSB('WT0',get(data,'VarNames'),'exact')),
+        error('Weight based dosing present but no "WT0" column with weight information in the dataset.');
+    end
+    COVCAT_INFORMATION.covNames = unique([{'WT0'} COVCAT_INFORMATION.covNames]);
+end
+
+%% Determine regression things
+regressionPARA = run_results.modelInformation.regressionPARA;
+regressionDATA = run_results.dataInformation.regressionDATA;
+
+%% Transform the data (stratification and median calculation)
+[dataStratified,stratificationTHRESHOLD] = createStratifiedDatasetSBPOP(data,'ID',run_results.stratificationSetting.NAME,run_results.stratificationSetting.RANGE);
+DATAmedian = getMedianModelingDataStructSBPOP(dataStratified,run_results.dataInformation.names,run_results.dataInformation.type,COVCAT_INFORMATION.covNames,COVCAT_INFORMATION.catNames,COVCAT_INFORMATION.referenceCAT,regressionPARA,regressionDATA);
+
+%% Produce MEX model
+moddos                          = mergemoddosSBPOP(run_results.modelInformation.model,run_results.dosingInformation.dosings{1});
+mexModelName                    = 'mexModel_simulation';
+SBPDmakeMEXmodel(moddos,mexModelName);
+
+%% Get PD parameters from bootstrap
+parameterNames  = run_results.run_information.OUTPUTopt{1}.parameterNames;   
+parameterValues = [];
+for k=1:length(run_results.run_information),
+    parameterValues = [parameterValues; run_results.run_information.OUTPUTopt{k}.parameterValues];
+end
+NSIM = length(run_results.run_information);
+
+%% Get allTRTs for which dosings are defined - since we want to simulate all provided dosings!
+allTRT = dosingInformation.TRT;
+        
+%% Simulate all TRTs that were in the dosingInformation
+PK_ALL_TRT          = {};
+READOUTS_ALL_TRT    = {};
+SIMTIME_TRT         = {};
+
+parfor kTRT = 1:length(allTRT),
+    % kTRT is relative to dosingInformation!
+    
+    % Get treatment info
+    TRT                                         = allTRT(kTRT);
+    
+    % Get index in the DATAmedian
+    ixTRT_DATAmedian                            = find(DATAmedian.TRT==TRT);
+       
+    % Get default simulation parameters 
+    paramNamesSim  = [parameterNames];
+    paramValuesSim = [parameterValues];
+    
+    % Sample PK population parameters (include median covariate information)
+    if ~isempty(run_results.modelInformation.FIT_PK),
+        % For TRT groups not present in the data, no covariate information is availabel but might be needed for the sampling of the PK model.
+        % In this case (identified by isempty(ixTRT_DATAmedian), the median of the covariates is used across the provided data.
+        if ~isempty(ixTRT_DATAmedian),
+            PKparam = SBPOPsampleNLMEfitParam(run_results.modelInformation.FIT_PK,3,1,DATAmedian.covNames,DATAmedian.covValues(:,ixTRT_DATAmedian)',DATAmedian.catNames,DATAmedian.catValues(:,ixTRT_DATAmedian)');
+        else
+            covValues = nanmedian(DATAmedian.covValues')';
+            catValues = nanmedian(DATAmedian.catValues')'; % Also median for cat values ...
+            PKparam = SBPOPsampleNLMEfitParam(run_results.modelInformation.FIT_PK,3,1,DATAmedian.covNames,covValues,DATAmedian.catNames,catValues);
+        end
+        % Need to check in the model and remove the PK parameters that ae
+        % not present in the model
+        PKparamNotInModel = setdiff(PKparam.parameterNames,SBparameters(moddos));
+        ix_remove_PKparam = [];
+        for kPKparam=1:length(PKparamNotInModel),
+            ix_remove_PKparam = [ix_remove_PKparam strmatchSB(PKparamNotInModel{kPKparam},PKparam.parameterNames)];
+        end
+        PKparam.parameterNames(ix_remove_PKparam) = [];
+        PKparam.parameterValuesPopulation(ix_remove_PKparam) = [];
+        
+        % Combine PK and PD parameters
+        paramNamesSim  = [paramNamesSim   PKparam.parameterNames];
+        paramValuesSim = [paramValuesSim  PKparam.parameterValuesPopulation(ones(1,NSIM),:)];
+    end
+    
+    % Add regression parameters
+    % For TRT groups not present in the data, no regression information is available but might be needed
+    % In this case (identified by isempty(ixTRT_DATAmedian), the median of the regression information is used across the provided data.
+    paramNamesSim  = [paramNamesSim DATAmedian.regressionNames];
+    if ~isempty(ixTRT_DATAmedian),
+        regvalues = DATAmedian.regressionValues(:,ixTRT_DATAmedian)';
+    else
+        regvalues = nanmedian(DATAmedian.regressionValues')';
+    end        
+    paramValuesSim = [paramValuesSim  regvalues(ones(1,NSIM),:)];
+    
+    % Get dosing information and handle weight based dosing
+    dosing_sim          = dosingInformation.dosings{kTRT};
+    
+    % Handle weight based dosing
+    %   Check if weight based dosing and then change the dose
+    %   Check for each input in the dosing scheme
+    ds = struct(dosing_sim);
+    for kx = 1:length(ds.inputs),
+        if dosingInformation.weightBased(kx,kTRT),
+            medianWEIGHT = DATAmedian.covValues(strmatchSB(DATAmedian.covNames,'WT0','exact'),ixTRT_DATAmedian);
+            ds.inputs(kx).D = ds.inputs(kx).D*medianWEIGHT;
+        end    
+    end
+    dosing_sim = SBPOPdosing(ds);
+        
+    % Simulate
+    PK_ALL = NaN(length(SIMTIME),NSIM);
+    READOUTS_ALL = cell(1,length(run_results.modelInformation.modelOutput));
+    for kx=1:length(run_results.modelInformation.modelOutput),
+        READOUTS_ALL{kx} = NaN(length(SIMTIME),NSIM);
+    end
+    for kSIM=1:NSIM,
+        kSIM
+        try
+            simres = SBPOPsimdosing(mexModelName,dosing_sim,SIMTIME,[],paramNamesSim,paramValuesSim(kSIM,:));
+            
+            % Get the PK ... assume Cc is the one.
+            if ~isempty(variableindexSB(moddos,'Cc')),
+                PK_ALL(:,kSIM) = simres.variablevalues(:,variableindexSB(moddos,'Cc'));
+            end
+            
+            % Get the other readouts
+            for kx=1:length(run_results.modelInformation.modelOutput),
+                READOUTS_ALL{kx}(:,kSIM) = simres.variablevalues(:,variableindexSB(moddos,run_results.modelInformation.modelOutput{kx}));
+            end
+        catch
+        end
+    end
+   
+    PK_ALL_TRT{kTRT}            = PK_ALL;
+    READOUTS_ALL_TRT{kTRT}      = READOUTS_ALL;
+    SIMTIME_TRT{kTRT} = SIMTIME;    
+end
+
+%% start output
+startNewPrintFigureSBPOP(filename)
+
+%% Plot PK results
+figure(1); clf;
+nrows = ceil(sqrt(length(allTRT)));
+ncols = ceil(length(allTRT)/nrows);
+PK_X = [];
+for kTRT=1:length(allTRT),
+    PK_X  = [PK_X; PK_ALL_TRT{kTRT}(:)];
+end
+minY = min(log10(PK_X));
+maxY = max(log10(PK_X));
+for kTRT=1:length(allTRT),
+    subplot(nrows,ncols,kTRT);
+    PK_TRT  = PK_ALL_TRT{kTRT};
+    SIMTME  = SIMTIME_TRT{kTRT};
+    plot(SIMTIME,log10(nanmedian(PK_TRT')),'k-','LineWidth',2)
+    % Annotate
+    if kTRT>length(allTRT)-ncols,
+        xlabel('Time')
+    end
+    if mod(kTRT,ncols) == 1,
+        ylabel('Conc')
+    end
+    grid on;
+    set(gca,'YTick',[0 1 2 3 4 5 6]);
+    set(gca,'YTickLabel',10.^get(gca,'YTick'));
+    set(gca,'XLim',[min(SIMTIME) max(SIMTIME)]);
+    set(gca,'YLim',[minY maxY]);
+    
+    % Get treatment name
+    title(dosingInformation.name{kTRT},'Interpreter','none');
+end
+printFigureSBPOP(gcf,filename)
+
+%% Plot Readout results with uncertainty - one plot per TRT
+SIMTIME_X = [];
+RO_Y = [];
+for k=1:length(PK_ALL_TRT),
+    SIMTIME_X = [SIMTIME_X SIMTIME_TRT{kTRT}];
+    for kRO=1:length(run_results.modelInformation.modelOutput),
+        RO_Y      = [RO_Y; READOUTS_ALL_TRT{kTRT}{kRO}(:)]; 
+    end
+end
+
+
+for kRO = 1:length(run_results.modelInformation.modelOutput),
+    
+    figure(kRO+1); clf;
+    nrows = ceil(sqrt(length(PK_ALL_TRT)));
+    ncols = ceil(length(PK_ALL_TRT)/nrows);
+
+    for kTRT=1:length(allTRT),
+        subplot(nrows,ncols,kTRT);
+        
+        RO_TRT = READOUTS_ALL_TRT{kTRT}{kRO};
+        SIMTIME = SIMTIME_TRT{kTRT};
+        
+        % Plot the data if available
+        % Get index in the DATAmedian
+        ixTRT_DATAmedian = find(DATAmedian.TRT==allTRT(kTRT));
+        if ~isempty(ixTRT_DATAmedian),
+            data = DATAmedian.DATA{ixTRT_DATAmedian}(kRO,:);
+            time = DATAmedian.NT{ixTRT_DATAmedian};
+            plot(time,data,'.-','MarkerSize',25,'Color',0.3*[1 1 1]); hold on
+        else
+            plot(-Inf,-Inf,'.-','MarkerSize',25,'Color',0.3*[1 1 1]); hold on
+        end
+        
+        plot(SIMTIME,nanmedian(RO_TRT'),'b-','LineWidth',2,'Color',0.8*colors(kRO,:)); hold on
+        
+        ranges      = [90 75 50 25];
+        colorfactor = [0.65 0.5 0.35 0.2];
+        legendText = {'Observations',sprintf('Simulated median (N=%d)',run_results.options.N_BOOTSTRAP)};
+        for kplot=1:length(ranges)
+            qlow = (1-ranges(kplot)/100)/2;
+            qhigh = 1-(1-ranges(kplot)/100)/2;
+            SBPOPplotfill(SIMTIME,quantile(RO_TRT',qlow),quantile(RO_TRT',qhigh),min(colorfactor(kplot)+colors(kRO,:),1),1,min(colorfactor(kplot)+colors(kRO,:),1)); hold on;
+            legendText{end+1} = sprintf('%d %% CI',ranges(kplot));
+        end
+        
+        plot(SIMTIME,nanmedian(RO_TRT'),'b-','LineWidth',2,'Color',0.8*colors(kRO,:)); hold on
+        
+        % Annotate
+        if kTRT>length(PK_ALL_TRT)-ncols,
+            xlabel('Time')
+        end
+        if mod(kTRT,ncols) == 1,
+            ylabel(sprintf('%s',run_results.dataInformation.names{kRO}),'Interpreter','none')
+        end
+        grid on;
+        set(gca,'XLim',[min(SIMTIME_X) max(SIMTIME_X)]);
+        set(gca,'YLim',[min(RO_Y)*0.9 max(RO_Y)*1.1]);
+        title(dosingInformation.name{kTRT},'Interpreter','none');
+        
+        % Plot the data if available
+        % Get index in the DATAmedian
+        ixTRT_DATAmedian = find(DATAmedian.TRT==allTRT(kTRT));
+        if ~isempty(ixTRT_DATAmedian),
+            data = DATAmedian.DATA{ixTRT_DATAmedian}(kRO,:);
+            time = DATAmedian.NT{ixTRT_DATAmedian};
+            plot(time,data,'.-','MarkerSize',25,'Color',0.3*[1 1 1]); hold on
+            % Plot errorbars on data
+            data_stderr = DATAmedian.DATA_STDERR{ixTRT_DATAmedian}(kRO,:);
+            errorbar(time,data,data_stderr,'Color',0.3*[1 1 1])
+        end
+    end
+    % Add legend
+    subplot(nrows,ncols,1);
+    legend(legendText,'Location','NorthEast')
+    printFigureSBPOP(gcf,filename)
+end
+
+%% Plot Readout results without uncertainty - compare all TRTs in a single plot ... no data plotting
+SIMTIME_X = [];
+RO_Y = [];
+for k=1:length(PK_ALL_TRT),
+    SIMTIME_X = [SIMTIME_X SIMTIME_TRT{kTRT}];
+    for kRO=1:length(run_results.modelInformation.modelOutput),
+        RO_Y      = [RO_Y; READOUTS_ALL_TRT{kTRT}{kRO}(:)]; 
+    end
+end
+
+for kRO = 1:length(run_results.modelInformation.modelOutput),
+    figure(kRO+1); clf;
+    legendText = {};
+    for kTRT=1:length(allTRT),
+        RO_TRT = READOUTS_ALL_TRT{kTRT}{kRO};
+        SIMTIME = SIMTIME_TRT{kTRT};
+        plot(SIMTIME,nanmedian(RO_TRT'),'b-','LineWidth',3,'Color',colors(kTRT,:)); hold on
+        legendText{kTRT} = sprintf('%s (median)',dosingInformation.name{kTRT});
+    end
+    
+    % Annotate
+    if kTRT>length(PK_ALL_TRT)-ncols,
+        xlabel('Time')
+    end
+    if mod(kTRT,ncols) == 1,
+        ylabel(sprintf('%s',run_results.dataInformation.names{kRO}),'Interpreter','none')
+    end
+    grid on;
+    set(gca,'XLim',[min(SIMTIME_X) max(SIMTIME_X)]);
+    set(gca,'YLim',[min(RO_Y)*0.9 max(RO_Y)*1.1]);
+    set(gca,'FontSize',12);
+    xlabel('Time','FontSize',14)
+    ylabel(run_results.dataInformation.names{kRO},'FontSize',14,'Interpreter','none');
+    title('Comparison of median responses for all TRT groups','FontSize',14,'Interpreter','none')
+    
+    legend(legendText,'Location','NorthEast')
+    printFigureSBPOP(gcf,filename)
+end
+
+%%
+convert2pdfSBPOP(filename);
+close all
+
+% Delete mex file
+clear mex
+delete([mexModelName '.' mexext]);
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/11_Simulation/SBPOPsimulationMedianSampledParam.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/11_Simulation/SBPOPsimulationMedianSampledParam.m
new file mode 100644
index 0000000000000000000000000000000000000000..405a22b51ddf8f96dd2e52dc2811b0d89a71ca5d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/mPDtoolbox/11_Simulation/SBPOPsimulationMedianSampledParam.m
@@ -0,0 +1,396 @@
+function [] = SBPOPsimulationMedianSampledParam(projectfolder,dosingInformation,data,SIMTIME,filename,NSAMPLES)
+% SBPOPsimulationMedianSampledParam: Similar function as "SBPOPvpcMedianSampledParam"
+% The difference to the VPC is that additional dosing schemes can be
+% simulated. If data available then it is plotted. If not then just
+% simulation. Additionally, a plot is generated, comparing the median/responder rate
+% results without uncertainty for the different provided dosing schemes.
+%
+% dosingInformation is not used from the run_results of the
+% project but from the user provided input argument. 
+%
+% The data is not used from the run_results, but from the provided input
+% argument. Same transformations will be done as specified in the
+% run_results.
+%
+% Simulations based on sampled parameters from estimated parameter distributions.
+%
+% USAGE:
+% ======
+% SBPOPsimulationMedianSampledParam(projectfolder,dosingInformation,data,SIMTIME,filename)   
+% SBPOPsimulationMedianSampledParam(projectfolder,dosingInformation,data,SIMTIME,filename,NSAMPLES)   
+%
+% projectfolder:        string with the path where the model results are stored 
+%                       (e.g.: logfiles folder, run_results.data, ...)
+% dosingInformation:	structure with information about the nominal treatment group dosings
+%   dosingInformation.TRT:          Vector with treatment group identifiers to be used in optimization
+%                                   TRT groups are optimized if dosings AND data are available - otherwise ignored!
+%                                   It will be checked that for each TRT in the data a dosing definition is present. Otherwise error!
+%   dosingInformation.dosings:      Cell-array defining nominal dosings for each treatment group
+%   dosingInformation.name:         Cell-array defining names for each treatment group
+%   dosingInformation.weightBased:  Matrix with as many rows as dosing inputs in the model and as many columns as treatment groups.
+%                                   A "0" entry defines fixed dosing and a "1" entry defines weight based dosing.
+%                                   If weight based dosing is used, the dataInformation.data dataset needs to contain a WT0 column.
+%
+% data:                 Matlab dataset in the median modeling format
+% SIMTIME:              Time vector for the simulations
+% filename:             Path, including name for the generated PDF
+% NSAMPLES:             Number of samples to simulate (default: 200)  
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%% Handle variable input arguments
+if nargin == 5,
+    NSAMPLES = 200;
+end
+
+%% Read tun results
+run_results = load([projectfolder '/run_results.data'],'-mat'); run_results = run_results.run_results;
+
+%% Get colors
+colors = getcolorsSBPOP();
+
+%% Get covariate information
+% Parse covariate information from potential FIT_PK model
+COVCAT_INFORMATION = [];
+[COVCAT_INFORMATION.covNames, COVCAT_INFORMATION.catNames, COVCAT_INFORMATION.referenceCAT] = getCovariateInformationSBPOP(run_results.modelInformation.FIT_PK);
+% Check weight based dosing .. if present then add WT0 to required covariates but only if present in dataset. Otherwise error
+if sum(sum(dosingInformation.weightBased)) > 0,
+    % Check if WT0 in dataset
+    if isempty(strmatchSB('WT0',get(data,'VarNames'),'exact')),
+        error('Weight based dosing present but no "WT0" column with weight information in the dataset.');
+    end
+    COVCAT_INFORMATION.covNames = unique([{'WT0'} COVCAT_INFORMATION.covNames]);
+end
+
+%% Determine regression things
+regressionPARA = run_results.modelInformation.regressionPARA;
+regressionDATA = run_results.dataInformation.regressionDATA;
+
+%% Transform the data (stratification and median calculation)
+[dataStratified,stratificationTHRESHOLD] = createStratifiedDatasetSBPOP(data,'ID',run_results.stratificationSetting.NAME,run_results.stratificationSetting.RANGE);
+DATAmedian = getMedianModelingDataStructSBPOP(dataStratified,run_results.dataInformation.names,run_results.dataInformation.type,COVCAT_INFORMATION.covNames,COVCAT_INFORMATION.catNames,COVCAT_INFORMATION.referenceCAT,regressionPARA,regressionDATA);
+
+%% Produce MEX model
+moddos                          = mergemoddosSBPOP(run_results.modelInformation.model,run_results.dosingInformation.dosings{1});
+mexModelName                    = 'mexModel_simulation';
+SBPDmakeMEXmodel(moddos,mexModelName);
+
+%% Get PD parameters from bootstrap and sample from the distribution
+% Use the transformed parameters for the sampling!
+parameterNames  = run_results.parameterInformation.names(find(run_results.parameterInformation.estimate));
+parameters_bootstrap_all = [];
+parameters_bootstrap_all_TRANS = [];
+for k=1:length(run_results.run_information),
+    parameters                          = run_results.run_information.OUTPUTopt{k}.X;
+    parameters_bootstrap_all            = [parameters_bootstrap_all; parameters];
+    parameters_trans                    = transformXparametersSBPOP(parameters,run_results.parameterInformation.trans(find(run_results.parameterInformation.estimate)));
+    parameters_bootstrap_all_TRANS      = [parameters_bootstrap_all_TRANS; parameters_trans];
+end
+
+% Determine the distribution of the parameterValues and sample from it
+mean_PD  = mean(parameters_bootstrap_all_TRANS);
+std_PD   = std(parameters_bootstrap_all_TRANS);
+corr_PD  = corr(parameters_bootstrap_all_TRANS);
+sigma_PD = std_PD'*std_PD;
+% Handle non pos-semidefinite sigma_PD
+[eigV,eigD] = eig(sigma_PD);
+if min(diag(eigD)) > -1e-3,
+    % It is not positive semidefinite, but the smallest eigenvalue
+    % is so close to zero that we are going to put it on zero
+    eigD(eigD<0) = 0;
+    sigma_PD = eigV*eigD*inv(eigV);
+    disp('Covariance matrix not positive semidefinite. Smallest eigenvalue is closer to 0 than -1e-3 => making it positive semidefinite.');
+end
+cov_PD   = corr_PD.*sigma_PD;
+parameterValuesSAMPLED_TRANS = mvnrnd(mean_PD,cov_PD,NSAMPLES);
+
+% Inverse transform the sampled parameters
+parameterValuesSAMPLED = [];
+for k=1:NSAMPLES,
+    parameterValuesSAMPLED = [parameterValuesSAMPLED; invtransformXparametersSBPOP(parameterValuesSAMPLED_TRANS(k,:),run_results.parameterInformation.trans(find(run_results.parameterInformation.estimate)))];
+end
+
+% Add missing not estimated parameters
+parameterNamesAdd   = run_results.parameterInformation.names(find(~run_results.parameterInformation.estimate));
+parameterValuesAdd  = run_results.parameterInformation.values0(find(~run_results.parameterInformation.estimate));
+
+parameterNames          = [parameterNames parameterNamesAdd];
+parameterValuesSAMPLED  = [parameterValuesSAMPLED parameterValuesAdd(ones(1,size(parameterValuesSAMPLED,1)),:)];
+
+% Assign sampled PD parameters to the parameters used
+parameterValues = parameterValuesSAMPLED;
+NSIM = NSAMPLES;
+
+%% Get allTRTs for which dosings are defined - since we want to simulate all provided dosings!
+allTRT = dosingInformation.TRT;
+        
+%% Simulate all TRTs that were in the dosingInformation
+PK_ALL_TRT          = {};
+READOUTS_ALL_TRT    = {};
+SIMTIME_TRT         = {};
+
+parfor kTRT = 1:length(allTRT),
+    % kTRT is relative to dosingInformation!
+    
+    % Get treatment info
+    TRT                                         = allTRT(kTRT);
+    
+    % Get index in the DATAmedian
+    ixTRT_DATAmedian                            = find(DATAmedian.TRT==TRT);
+       
+    % Get default simulation parameters 
+    paramNamesSim  = [parameterNames];
+    paramValuesSim = [parameterValues];
+    
+    % Sample PK population parameters (include median covariate information)
+    if ~isempty(run_results.modelInformation.FIT_PK),
+        if ~isempty(ixTRT_DATAmedian),
+            PKparam = SBPOPsampleNLMEfitParam(run_results.modelInformation.FIT_PK,3,1,DATAmedian.covNames,DATAmedian.covValues(:,ixTRT_DATAmedian)',DATAmedian.catNames,DATAmedian.catValues(:,ixTRT_DATAmedian)');
+        else
+            covValues = nanmedian(DATAmedian.covValues')';
+            catValues = nanmedian(DATAmedian.catValues')'; % Also median for cat values ...
+            PKparam = SBPOPsampleNLMEfitParam(run_results.modelInformation.FIT_PK,3,1,DATAmedian.covNames,covValues,DATAmedian.catNames,catValues);
+        end
+        % Need to check in the model and remove the PK parameters that ae
+        % not present in the model
+        PKparamNotInModel = setdiff(PKparam.parameterNames,SBparameters(moddos));
+        ix_remove_PKparam = [];
+        for kPKparam=1:length(PKparamNotInModel),
+            ix_remove_PKparam = [ix_remove_PKparam strmatchSB(PKparamNotInModel{kPKparam},PKparam.parameterNames)];
+        end
+        PKparam.parameterNames(ix_remove_PKparam) = [];
+        PKparam.parameterValuesPopulation(ix_remove_PKparam) = [];
+        
+        % Combine PK and PD parameters
+        paramNamesSim  = [paramNamesSim   PKparam.parameterNames];
+        paramValuesSim = [paramValuesSim  PKparam.parameterValuesPopulation(ones(1,NSIM),:)];
+    end
+    
+    % Add regression parameters
+    paramNamesSim  = [paramNamesSim DATAmedian.regressionNames];
+    if ~isempty(ixTRT_DATAmedian),
+        regvalues = DATAmedian.regressionValues(:,ixTRT_DATAmedian)';
+    else
+        regvalues = nanmedian(DATAmedian.regressionValues')';
+    end        
+    paramValuesSim = [paramValuesSim  regvalues(ones(1,NSIM),:)];
+        
+    % Get dosing information and handle weight based dosing
+    dosing_sim          = dosingInformation.dosings{kTRT};
+    
+    % Handle weight based dosing
+    %   Check if weight based dosing and then change the dose
+    %   Check for each input in the dosing scheme
+    ds = struct(dosing_sim);
+    for kx = 1:length(ds.inputs),
+        if dosingInformation.weightBased(kx,kTRT),
+            medianWEIGHT = DATAmedian.covValues(strmatchSB(DATAmedian.covNames,'WT0','exact'),ixTRT_DATAmedian);
+            ds.inputs(kx).D = ds.inputs(kx).D*medianWEIGHT;
+        end    
+    end
+    dosing_sim = SBPOPdosing(ds);
+        
+    % Simulate
+    PK_ALL = NaN(length(SIMTIME),NSIM);
+    READOUTS_ALL = cell(1,length(run_results.modelInformation.modelOutput));
+    for kx=1:length(run_results.modelInformation.modelOutput),
+        READOUTS_ALL{kx} = NaN(length(SIMTIME),NSIM);
+    end
+    for kSIM=1:NSIM,
+        kSIM
+        try
+            simres = SBPOPsimdosing(mexModelName,dosing_sim,SIMTIME,[],paramNamesSim,paramValuesSim(kSIM,:));
+            
+            % Get the PK ... assume Cc is the one.
+            if ~isempty(variableindexSB(moddos,'Cc')),
+                PK_ALL(:,kSIM) = simres.variablevalues(:,variableindexSB(moddos,'Cc'));
+            end
+            
+            % Get the other readouts
+            for kx=1:length(run_results.modelInformation.modelOutput),
+                READOUTS_ALL{kx}(:,kSIM) = simres.variablevalues(:,variableindexSB(moddos,run_results.modelInformation.modelOutput{kx}));
+            end
+        catch
+        end
+    end
+   
+    PK_ALL_TRT{kTRT}            = PK_ALL;
+    READOUTS_ALL_TRT{kTRT}      = READOUTS_ALL;
+    SIMTIME_TRT{kTRT} = SIMTIME;    
+end
+
+%% start output
+startNewPrintFigureSBPOP(filename)
+
+%% Plot PK results
+figure(1); clf;
+nrows = ceil(sqrt(length(allTRT)));
+ncols = ceil(length(allTRT)/nrows);
+PK_X = [];
+for kTRT=1:length(allTRT),
+    PK_X  = [PK_X; PK_ALL_TRT{kTRT}(:)];
+end
+minY = min(log10(PK_X));
+maxY = max(log10(PK_X));
+for kTRT=1:length(allTRT),
+    subplot(nrows,ncols,kTRT);
+    PK_TRT  = PK_ALL_TRT{kTRT};
+    SIMTME  = SIMTIME_TRT{kTRT};
+    plot(SIMTIME,log10(nanmedian(PK_TRT')),'k-','LineWidth',2)
+    % Annotate
+    if kTRT>length(allTRT)-ncols,
+        xlabel('Time','Interpreter','none')
+    end
+    if mod(kTRT,ncols) == 1,
+        ylabel('Conc','Interpreter','none')
+    end
+    grid on;
+    set(gca,'YTick',[0 1 2 3 4 5 6]);
+    set(gca,'YTickLabel',10.^get(gca,'YTick'));
+    set(gca,'XLim',[min(SIMTIME) max(SIMTIME)]);
+    set(gca,'YLim',[minY maxY]);
+    
+    % Get treatment name
+    title(dosingInformation.name{kTRT},'Interpreter','none');
+end
+printFigureSBPOP(gcf,filename)
+
+%% Plot Readout results with uncertainty - one plot per TRT
+SIMTIME_X = [];
+RO_Y = [];
+for k=1:length(PK_ALL_TRT),
+    SIMTIME_X = [SIMTIME_X SIMTIME_TRT{kTRT}];
+    for kRO=1:length(run_results.modelInformation.modelOutput),
+        RO_Y      = [RO_Y; READOUTS_ALL_TRT{kTRT}{kRO}(:)]; 
+    end
+end
+
+
+for kRO = 1:length(run_results.modelInformation.modelOutput),
+    
+    figure(kRO+1); clf;
+    nrows = ceil(sqrt(length(PK_ALL_TRT)));
+    ncols = ceil(length(PK_ALL_TRT)/nrows);
+
+    for kTRT=1:length(allTRT),
+        subplot(nrows,ncols,kTRT);
+        
+        RO_TRT = READOUTS_ALL_TRT{kTRT}{kRO};
+        SIMTIME = SIMTIME_TRT{kTRT};
+        
+        % Plot the data if available
+        % Get index in the DATAmedian
+        ixTRT_DATAmedian = find(DATAmedian.TRT==allTRT(kTRT));
+        if ~isempty(ixTRT_DATAmedian),
+            data = DATAmedian.DATA{ixTRT_DATAmedian}(kRO,:);
+            time = DATAmedian.NT{ixTRT_DATAmedian};
+            plot(time,data,'.-','MarkerSize',25,'Color',0.3*[1 1 1]); hold on
+        else
+            plot(-Inf,-Inf,'.-','MarkerSize',25,'Color',0.3*[1 1 1]); hold on
+        end
+        
+        plot(SIMTIME,nanmedian(RO_TRT'),'b-','LineWidth',2,'Color',0.8*colors(kRO,:)); hold on
+
+        ranges      = [90 75 50 25];
+        colorfactor = [0.65 0.5 0.35 0.2];
+        legendText = {'Observations',sprintf('Simulated median (N=%d)',NSAMPLES)};
+        for kplot=1:length(ranges)
+            qlow = (1-ranges(kplot)/100)/2;
+            qhigh = 1-(1-ranges(kplot)/100)/2;
+            SBPOPplotfill(SIMTIME,quantile(RO_TRT',qlow),quantile(RO_TRT',qhigh),min(colorfactor(kplot)+colors(kRO,:),1),1,min(colorfactor(kplot)+colors(kRO,:),1)); hold on;
+            legendText{end+1} = sprintf('%d %% CI',ranges(kplot));
+        end
+        
+        plot(SIMTIME,nanmedian(RO_TRT'),'b-','LineWidth',2,'Color',0.8*colors(kRO,:)); hold on
+                
+        % Annotate
+        if kTRT>length(PK_ALL_TRT)-ncols,
+            xlabel('Time','Interpreter','none')
+        end
+        if mod(kTRT,ncols) == 1,
+            ylabel(sprintf('%s',run_results.dataInformation.names{kRO}),'Interpreter','none')
+        end
+        grid on;
+        set(gca,'XLim',[min(SIMTIME_X) max(SIMTIME_X)]);
+        set(gca,'YLim',[min(RO_Y)*0.9 max(RO_Y)*1.1]);
+        title(dosingInformation.name{kTRT},'Interpreter','none');
+        
+        % Plot the data if available
+        % Get index in the DATAmedian
+        ixTRT_DATAmedian = find(DATAmedian.TRT==allTRT(kTRT));
+        if ~isempty(ixTRT_DATAmedian),
+            data = DATAmedian.DATA{ixTRT_DATAmedian}(kRO,:);
+            time = DATAmedian.NT{ixTRT_DATAmedian};
+            plot(time,data,'.-','MarkerSize',25,'Color',0.3*[1 1 1]); hold on
+            % Plot errorbars on data
+            data_stderr = DATAmedian.DATA_STDERR{ixTRT_DATAmedian}(kRO,:);
+            errorbar(time,data,data_stderr,'Color',0.3*[1 1 1])
+        end
+    end
+    % Add legend
+    subplot(nrows,ncols,1);
+    legend(legendText,'Location','NorthEast')
+    printFigureSBPOP(gcf,filename)
+end
+
+%% Plot Readout results without uncertainty - compare all TRTs in a single plot ... no data plotting
+SIMTIME_X = [];
+RO_Y = [];
+for k=1:length(PK_ALL_TRT),
+    SIMTIME_X = [SIMTIME_X SIMTIME_TRT{kTRT}];
+    for kRO=1:length(run_results.modelInformation.modelOutput),
+        RO_Y      = [RO_Y; READOUTS_ALL_TRT{kTRT}{kRO}(:)]; 
+    end
+end
+
+for kRO = 1:length(run_results.modelInformation.modelOutput),
+    figure(kRO+1); clf;
+    legendText = {};
+    for kTRT=1:length(allTRT),
+        RO_TRT = READOUTS_ALL_TRT{kTRT}{kRO};
+        SIMTIME = SIMTIME_TRT{kTRT};
+        plot(SIMTIME,nanmedian(RO_TRT'),'b-','LineWidth',3,'Color',colors(kTRT,:)); hold on
+        legendText{kTRT} = sprintf('%s (median)',dosingInformation.name{kTRT});
+    end
+    
+    % Annotate
+    if kTRT>length(PK_ALL_TRT)-ncols,
+        xlabel('Time')
+    end
+    if mod(kTRT,ncols) == 1,
+        ylabel(sprintf('%s',run_results.dataInformation.names{kRO}),'Interpreter','none')
+    end
+    grid on;
+    set(gca,'XLim',[min(SIMTIME_X) max(SIMTIME_X)]);
+    set(gca,'YLim',[min(RO_Y)*0.9 max(RO_Y)*1.1]);
+    set(gca,'FontSize',12);
+    xlabel('Time','FontSize',14)
+    ylabel(run_results.dataInformation.names{kRO},'FontSize',14,'Interpreter','none');
+    title('Comparison of median responses for all TRT groups','FontSize',14,'Interpreter','none')
+    
+    legend(legendText,'Location','NorthEast')
+    printFigureSBPOP(gcf,filename)
+end
+
+%%
+convert2pdfSBPOP(filename);
+close all
+
+% Delete mex file
+clear mex
+delete([mexModelName '.' mexext]);
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/00_Templates/EXAMPLE_01_PD_EXPLORATION.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/00_Templates/EXAMPLE_01_PD_EXPLORATION.m
new file mode 100644
index 0000000000000000000000000000000000000000..8466608a82f0e07628527eb2dae4d4abdcc0b030
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/00_Templates/EXAMPLE_01_PD_EXPLORATION.m
@@ -0,0 +1,58 @@
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Just an example / template script for graphical exploration of PD
+% Note, this code will not run as is - it is more a reminder of things to do
+% and not to have to type everything from scratch.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%% Setup
+clc; clear all; close all; restoredefaultpath();
+path2SBPOP          = 'SBPOP PACKAGE';
+oldpath             = pwd; cd(path2SBPOP);      installSBPOPpackageInitial();           cd(oldpath);
+
+%% Load data (generalized dataset format)
+data = SBPOPloadCSVdataset('../Data/data.csv');
+
+%% Define covariates to be considered
+covNames = {'WT0','XYZ0'};
+catNames = {'STUDY' 'TRT'};
+
+%% Continuous PD readouts
+NAMES               = {'XYZ'};
+BASELINENAMES       = {'XYZ0'};
+COVARIATES          = [covNames catNames];
+
+TIMEPOINT_CHANGE    = 100;
+PD_IMPROVEMENT      = [-20 -40];  % in percent
+
+options             = [];
+options.filename    = '../Output/Graphical_Exploration/01_PD_data_continuous';
+options.fontsize    = 14;
+
+SBPOPgraphicalExplorationContinuousPD(data,NAMES,BASELINENAMES,COVARIATES,TIMEPOINT_CHANGE,PD_IMPROVEMENT,options)
+
+%% Some custom data cleaning ...
+dataClean = data;
+
+%% Continuous PD readouts - cleaned
+NAMES               = {'XYZ'};
+BASELINENAMES       = {'XYZ0'};
+COVARIATES          = [covNames catNames];
+
+TIMEPOINT_CHANGE    = 100;
+PD_IMPROVEMENT      = [-20 -40];  % in percent
+
+options             = [];
+options.filename    = '../Output/Graphical_Exploration/02_PD_data_continuous_cleaned';
+options.fontsize    = 14;
+
+SBPOPgraphicalExplorationContinuousPD(dataClean,NAMES,BASELINENAMES,COVARIATES,TIMEPOINT_CHANGE,PD_IMPROVEMENT,options)
+
+%% Summary statistics
+SBPOPexploreSummaryStats(dataX,covNames,catNames,'../Output/Graphical_Exploration/05_Summary_Statistics')
+
+%% Covariate exploration
+SBPOPexploreCovariateCorrelations(dataX,covNames,catNames,'../Output/Graphical_Exploration/06_Covariate_Exploration')
+
+%% Export cleaned and combined dataset for further PKPD modeling
+SBPOPexportCSVdataset(dataX,'../Data/data_cleaned.csv')
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/00_Templates/EXAMPLE_02_MODEL_PD.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/00_Templates/EXAMPLE_02_MODEL_PD.m
new file mode 100644
index 0000000000000000000000000000000000000000..7a831f8a15eca303268a5c8f4b310a6f44afa479
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/00_Templates/EXAMPLE_02_MODEL_PD.m
@@ -0,0 +1,155 @@
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% PD model development
+% Note, this code will not run as is - it is more a reminder of things to do
+% and not to have to type everything from scratch.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%% Setup
+clc; clear all; close all; restoredefaultpath();
+
+path2SBPOP          = 'SBPOP PACKAGE';
+oldpath             = pwd; cd(path2SBPOP);      installSBPOPpackageInitial();           cd(oldpath);
+
+%% Load data
+data        = SBPOPloadCSVdataset('../Data/data_cleaned.csv');
+dataPlacebo = SBPOPloadCSVdataset('../Data/data_cleaned_PLACEBO.csv');
+
+%% Definition of general settings
+covNames            = {'WT0','XYZ0'};
+catNames            = {'STUDY' 'TRT'};
+catImputationValues = [ 999     999 ];
+
+PD_NAME             = 'XYZ';
+
+%% Data cleaning
+removeSUBJECT       = {};
+removeREC           = {};
+Nobs                = 1;
+options             = [];
+options.FLAG_LLOQ   = 0;
+options.outputPath  = '../Output/DataCleaning/All/';
+datacleaned = SBPOPcleanPopPDdata(data,PD_NAME,removeSUBJECT,removeREC,Nobs,covNames,catNames,catImputationValues,options);
+
+options.outputPath  = '../Output/DataCleaning/Placebo/';
+dataPlacebocleaned = SBPOPcleanPopPDdata(dataPlacebo,PD_NAME,removeSUBJECT,removeREC,Nobs,covNames,catNames,catImputationValues,options);
+
+%% Data exploration
+options                     = [];
+options.outputPath          = '../Output/Graphical_Exploration/All';
+options.plotIndividualData  = 0;
+options.plotStratifiedData  = 1;
+options.plotCovariateData   = 1;
+SBPOPexplorePopPDdata(datacleaned,7,covNames,catNames,options)
+
+options                     = [];
+options.outputPath          = '../Output/Graphical_Exploration/Placebo';
+options.plotIndividualData  = 0;
+options.plotStratifiedData  = 1;
+options.plotCovariateData   = 1;
+SBPOPexplorePopPDdata(dataPlacebocleaned,7,covNames,catNames,options)
+
+%% Convert to modeling datasets
+model                       = SBmodel('../Models/PKPDmodel_01.txt');
+dosing                      = SBPOPdosing('../Models/PKPDdosing.dos');
+pathNLMEproject             = '../Models/MODEL_01_PK_NONMEM/FITMODEL_01_PK_NONMEM_006';
+
+analysisDataset             = '../Data/popPKPD.csv';
+dataheader                  = SBPOPconvert2popPDparametersDataset(model,dosing,pathNLMEproject,datacleaned,PD_NAME,covNames,catNames,analysisDataset)
+
+analysisDatasetPlacebo      = '../Data/popPKPD_placebo.csv';
+dataheader_placebo          = SBPOPconvert2popPDparametersDataset(model,dosing,pathNLMEproject,dataPlacebocleaned,PD_NAME,covNames,catNames,analysisDatasetPlacebo)
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% PLACEBO MODELING
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+model                                   = SBmodel('../Models/PKPDmodel_01.txt');
+dosing                                  = SBPOPdosing('../Models/PKPDdosing.dos');
+regressionNames                         = {'Fabs1' 'CL' 'Vc' 'Q1' 'Vp1' 'ka'};
+
+dataFIT                                 = [];
+dataFIT.dataRelPathFromProject          = '../../../Data';
+dataFIT.dataHeaderIdent                 = SBPOPgetNONMEMdataHeader(SBPOPloadCSVdataset('../Data/popPKPD_placebo.csv'),covNames,catNames,regressionNames)
+dataFIT.dataFileName                    = 'popPKPD_placebo.csv';
+
+optionsFIT                              = [];
+
+%                                             BASELINE      kout      fS        EMAX    EC50    hill
+optionsFIT.POPvalues0                   = [      5          0.01      0.1       0.6     50      8   ];
+optionsFIT.POPestimate                  = [      1          1         1         0       0       0   ];
+optionsFIT.IIVvalues0                   = [      1          0         1         0       0       0   ];
+optionsFIT.IIVestimate                  = [      1          0         1         0       0       0   ];
+optionsFIT.IIVdistribution              = {     'N'        'L'       'N'       'L'     'L'     'L'  };
+optionsFIT.errorModels                  = 'const';   % additive only
+optionsFIT.covarianceModel              = '';
+optionsFIT.covariateModel               = '';
+
+optionsFIT.algorithm.SEED               = 123456;
+optionsFIT.algorithm.K1                 = 500;
+optionsFIT.algorithm.K2                 = 200;
+optionsFIT.algorithm.NRCHAINS           = 1;
+optionsFIT.algorithm.METHOD             = 'SAEM';
+optionsFIT.algorithm.ITS                = 1;
+optionsFIT.algorithm.IMPORTANCESAMPLING = 1;
+
+projectPath                             = '../Models/MODEL_02_PD_PLACEBO/FIT_01';
+
+SBPOPcreateNONMEMproject(model,dosing,dataFIT,projectPath,optionsFIT)
+SBPOPrunNONMEMproject(projectPath,'nmfe72',10)
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% COMPLETE MODELING
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% First model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+model                                   = SBmodel('../Models/PKPDmodel_01.txt');
+dosing                                  = SBPOPdosing('../Models/PKPDdosing.dos');
+regressionNames                         = {'Fabs1' 'CL' 'Vc' 'Q1' 'Vp1' 'ka'};
+
+dataFIT                                 = [];
+dataFIT.dataRelPathFromProject          = '../../../Data';
+dataFIT.dataHeaderIdent                 = SBPOPgetNONMEMdataHeader(SBPOPloadCSVdataset('../Data/popPKPD.csv'),covNames,catNames,regressionNames)
+dataFIT.dataFileName                    = 'popPKPD.csv';
+
+optionsFIT                              = [];
+
+%                                             BASELINE      kout      fS        EMAX    EC50    hill
+optionsFIT.POPvalues0                   = [      4.8        0.03      0.15      0.3     12      3   ];
+optionsFIT.POPestimate                  = [      1          1         0         0       1       0   ];
+optionsFIT.IIVvalues0                   = [      1.1        0         0.21      0       1       0   ];
+optionsFIT.IIVestimate                  = [      1          0         2         0       1       0   ];
+optionsFIT.IIVdistribution              = {     'N'        'L'       'N'       'L'     'L'     'L'  };
+optionsFIT.errorModels                  = 'const';   % additive only
+optionsFIT.covarianceModel              = '';
+optionsFIT.covariateModel               = '';
+
+optionsFIT.algorithm.SEED               = 123456;
+optionsFIT.algorithm.K1                 = 500;
+optionsFIT.algorithm.K2                 = 200;
+optionsFIT.algorithm.NRCHAINS           = 1;
+optionsFIT.algorithm.METHOD             = 'SAEM';
+optionsFIT.algorithm.ITS                = 1;
+optionsFIT.algorithm.IMPORTANCESAMPLING = 1;
+
+projectPath                             = '../Models/MODEL_03_PD/FIT_01';
+
+SBPOPcreateNONMEMproject(model,dosing,dataFIT,projectPath,optionsFIT)
+SBPOPrunNONMEMproject(projectPath,'nmfe72',20)
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Summary of results 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+SBPOPfitanalysisProjectsFolderInfo('../Models/MODEL_03_PD','../Output/FitAnalysis/MODEL_03_PD')
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% VPCs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+dataVPC                                 = SBPOPloadCSVdataset('../Data/popPKPD.csv');
+
+projectFolder                           = '../Models/MODEL_03_PD/FIT_01';
+VPC( projectFolder, dataVPC, 5 )
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/00_Templates/Useful models/PKPDdosing.dos b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/00_Templates/Useful models/PKPDdosing.dos
new file mode 100644
index 0000000000000000000000000000000000000000..95702b772719aab6f5ad8bc3443009522b31993c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/00_Templates/Useful models/PKPDdosing.dos	
@@ -0,0 +1,17 @@
+********** DOSING NAME
+Dosing
+
+********** DOSING NOTES
+
+********** INPUT1
+type:   BOLUS
+time:   [0 1 2 3 4 8 12 16 20 24 28 32]*7           % time for first application or all applications (scalar or vector)
+D:      150            % dose (scalar or vector)
+
+********** INPUT2
+type:   INFUSION
+time:   0            % time for first application or all applications (scalar or vector)
+D:      0            % dose (scalar or vector)
+Tinf:   1            % Infusion rate (required)
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/00_Templates/Useful models/PKPDmodel_01.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/00_Templates/Useful models/PKPDmodel_01.txt
new file mode 100644
index 0000000000000000000000000000000000000000..64d9fbd49d58f6a763decc7efb6cee799c864322
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/00_Templates/Useful models/PKPDmodel_01.txt	
@@ -0,0 +1,70 @@
+********** MODEL NAME
+PKPDmodel_01
+
+********** MODEL NOTES
+Units:
+======
+Dose:			 mg
+Time:   		 days
+Concentration:   ug/ml
+Ouput:  		 PD
+
+********** MODEL STATES
+
+% PK model
+d/dt(Ad)    		= -ka*Ad + Fabs1*INPUT1 
+d/dt(Ac)    		=  ka*Ad - CL/Vc*Ac - Q1/Vc*Ac + Q1/Vp1*Ap1 + INPUT2   
+d/dt(Ap1)   		=                   	   + Q1/Vc*Ac - Q1/Vp1*Ap1 
+
+% PD model 
+d/dt(PD)    		= kin - kout*(1+DRUG_EFFECT)*PD 
+
+PD(0) 				= BASELINE
+
+********** MODEL PARAMETERS
+
+Fabs1          		= 0.8606     % <regression>   
+CL          		= 0.183      % <regression>   
+Vc          		= 3.561      % <regression>             
+Q1          		= 0.388      % <regression>   
+Vp1         		= 2.469      % <regression>   
+ka           		= 0.2481     % <regression>   
+
+% Disease model
+BASELINE    		= 4.9    	 % <estimate>
+kout                = 0.0265     % <estimate>
+fS                  = 0.15       % <estimate>
+
+% Drug effect model 
+EMAX                = 0.3012     % <estimate>
+EC50                = 20         % <estimate>
+hill                = 3          % <estimate>
+
+********** MODEL VARIABLES
+
+% Disease model
+kin 				= kout*BASELINE
+MAXTIME             = max(time,0)
+PD_S                = fS*BASELINE*(1-exp(-kout*MAXTIME))
+
+% Drug effect model
+Cc 					= Ac/Vc
+DRUG_EFFECT  		= EMAX*Cc^hill/(Cc^hill+EC50^hill)
+
+% Output
+PD_sim              = max(PD-PD_S,0)
+
+% Fitting output (untransformed)
+OUTPUT1             = PD_sim
+
+********** MODEL REACTIONS
+
+
+********** MODEL FUNCTIONS
+
+
+********** MODEL EVENTS
+
+
+********** MODEL MATLAB FUNCTIONS
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/00_Templates/Useful models/PKPDmodel_02.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/00_Templates/Useful models/PKPDmodel_02.txt
new file mode 100644
index 0000000000000000000000000000000000000000..fa7012ace72ee3a956aa22c303c64175eb6ae216
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/00_Templates/Useful models/PKPDmodel_02.txt	
@@ -0,0 +1,71 @@
+********** MODEL NAME
+PKPDmodel_02
+
+********** MODEL NOTES
+Units:
+======
+Dose:			 mg
+Time:   		 days
+Concentration:   ug/ml
+Ouput:  		 PD
+
+********** MODEL STATES
+
+% PK model
+d/dt(Ad)    		= -ka*Ad + Fabs1*INPUT1 
+d/dt(Ac)    		=  ka*Ad - CL/Vc*Ac - Q1/Vc*Ac + Q1/Vp1*Ap1 + INPUT2   
+d/dt(Ap1)   		=                   	   + Q1/Vc*Ac - Q1/Vp1*Ap1 
+
+% PD model 
+d/dt(PD)    		= kin - kout*(1+DRUG_EFFECT)*PD 
+
+PD(0) 				= BASELINE
+
+********** MODEL PARAMETERS
+
+Fabs1          		= 1     % <regression>   
+CL          		= 1     % <regression>   
+Vc          		= 1     % <regression>             
+Q1          		= 1     % <regression>   
+Vp1         		= 1     % <regression>   
+ka           		= 1     % <regression>   
+
+% Disease model
+BASELINE    		= 20 	% <estimate>
+kout                = 0.03  % <estimate>
+fS                  = 0.1   % <estimate>
+kS                  = 0.02  % <estimate>
+
+% Drug effect model 
+EMAX                = 0.95  % <estimate>
+EC50                = 5000  % <estimate>
+hill                = 2     % <estimate>
+
+********** MODEL VARIABLES
+
+% Disease model
+kin 				= kout*BASELINE
+MAXTIME             = max(time,0)
+PD_S                = fS*BASELINE*(1-exp(-kS*MAXTIME))
+
+% Drug effect model
+Cc 					= Ac/Vc
+DRUG_EFFECT  		= EMAX*Cc^hill/(Cc^hill+EC50^hill)
+
+% Output
+PD_sim              = max(PD-PD_S,0)
+
+% Fitting output (untransformed)
+OUTPUT1             = PD_sim
+
+********** MODEL REACTIONS
+
+
+********** MODEL FUNCTIONS
+
+
+********** MODEL EVENTS
+
+
+********** MODEL MATLAB FUNCTIONS
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/02_DataExploration/SBPOPexplorePopPDdata.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/02_DataExploration/SBPOPexplorePopPDdata.m
new file mode 100644
index 0000000000000000000000000000000000000000..c45751bcf4bbe68001d66e0597cdbd36e9bbab33
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/02_DataExploration/SBPOPexplorePopPDdata.m
@@ -0,0 +1,234 @@
+function [] = SBPOPexplorePopPDdata(data,TYPE_NAME,covNames,catNames,options)
+% [DESCRIPTION]
+% This function allows to plot standard data exploration plots focusing on
+% a popPD analysis. The data need to be provided, following the standard
+% dataspec, defined in the help to the function SBPOPcheckDataFormat, so
+% please look there for more information.  
+%
+% [SYNTAX]
+% [] = SBPOPexplorePopPDdata(data,TYPE,covNames,catNames)
+% [] = SBPOPexplorePopPDdata(data,TYPE,covNames,catNames,options)
+% [] = SBPOPexplorePopPDdata(data,NAME,covNames,catNames)
+% [] = SBPOPexplorePopPDdata(data,NAME,covNames,catNames,options)
+%
+% [INPUT]
+% data:         MATLAB PKPD dataset in standard data spec format  
+% TYPE:         Numeric value, determining the TYPE to be plotted. TYPE
+%               should be a value from the elements in the TYPE column.
+%               Standard assumes dose record has TYPE 0 and PK observation 
+%               record has TYPE=1, all other things are up to you.
+%               IMPORTANT: It assumes that a single SUBTYPE value is present
+%               in the dataset. This will be checked. 
+% NAME:         Instead of a TYPE the NAME of the component to plot can be
+%               specified as a string. NAME needs to be the name as entered 
+%               in the NAME column of the dataset.
+% covNames:     Cell-array with the names of the continuous covariates, as
+%               defined in the dataset
+% catNames:     Cell-array with the names of the categorical covariates, as
+%               defined in the dataset
+% options:      MATLAB structure with additional options
+%
+%               options.color:    =0: use black and white where necessary,
+%                                 =1: use color (default)
+%               options.outputPath: path where
+%                                 outputs are exported to. Default:
+%                                 '../Output/DataExploration/';
+%               options.plotIndividualData: =1: yes (default), =0: no
+%               options.plotStratifiedData: =1: yes (default), =0: no
+%               options.plotCovariateData:  =1: yes (default), =0: no
+%
+% [OUTPUT]
+% Several PDF documents with plots. The names of the
+% files tell what is shown. also a summary statistic of the data as an
+% exported file. Covariate information, etc.
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 15th April 2013
+%
+% [PLATFORM]
+% Windows, Unix, MATLAB
+%
+% [TOOLBOXES USED]
+% Statistics Toolbox
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+%
+% This program is Free Open Source Software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isa(data,'dataset'),
+    error('First input argument is not a MATLAB dataset.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% If dataset empty then return
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(data),
+    disp('Empty dataset.');
+    return;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBPOPcheckDataFormat(data);
+datanames = get(data,'VarNames');
+for k=1:length(covNames),
+    if isempty(strmatchSB(covNames{k},datanames,'exact')), error('The dataset does not contain the covariate ''%s''.',covNames{k}); end
+end
+for k=1:length(catNames),
+    if isempty(strmatchSB(catNames{k},datanames,'exact')), error('The dataset does not contain the covariate ''%s''.',catNames{k}); end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if TYPE or NAME
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isnumeric(TYPE_NAME),
+    % Check if single SUBTYPE value
+    if length(unique(data.SUBTYPE(data.TYPE==TYPE_NAME))) > 1,
+        error('For this TYPE several SUBTYPE values are present.');
+    end
+    FLAG_TYPE = 1;
+else
+    % Check if name present
+    if ~ismember(TYPE_NAME,unique(data.NAME)),
+        error('Specified NAME not present in the dataset.');
+    end
+    FLAG_TYPE = 0;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle options
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try outputPath          = [options.outputPath '/'];     catch, outputPath           = '../Output/DataExploration/';     end; %#ok<*CTCH>
+try color               = options.color;                catch, color                = 1;                                end; %#ok<*CTCH>
+try plotIndividualData  = options.plotIndividualData;   catch, plotIndividualData   = 1;                                end; %#ok<*CTCH>
+try plotStratifiedData  = options.plotStratifiedData;   catch, plotStratifiedData   = 1;                                end; %#ok<*CTCH>
+try plotCovariateData   = options.plotCovariateData;    catch, plotCovariateData    = 1;                                end; %#ok<*CTCH>
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create output folder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[p,f,e] = fileparts(outputPath);
+warning off
+mkdir(p);
+warning on
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get colors etc - for color=0 option (only in plots where it is needed)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[colors,lines,dots,bwcolors] = getcolorsSBPOP();
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Export individual data - summary - linear Y axis
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dataPlot            = data;
+options             = [];
+filename            = [outputPath '01_individual_PD_data_summary_linearY'];
+options.logY        = 0;
+options.showDose    = 0;
+options.showText    = 0;
+options.nIDperPage  = 36;
+options.sameaxes    = 1;
+options.nameGroup   = 'STYSID1A';
+SBPOPexploreIndivData(dataPlot,TYPE_NAME,filename,options)
+    
+if plotIndividualData,
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Export individual data - 1 page per ID - linear Y axis 
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    dataPlot            = data;
+    filename            = [outputPath '02_individual_PD_data_SINGLE_linearY'];
+    options             = [];
+    options.logY        = 0;
+    options.showDose    = 1;
+    options.showText    = 1;
+    options.nIDperPage  = 1;
+    options.sameaxes    = 0;
+    options.nameGroup   = 'STYSID1A';
+    SBPOPexploreIndivData(dataPlot,TYPE_NAME,filename,options)
+end
+
+if plotStratifiedData,
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Assessment of data availability
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    filename    = [outputPath '03_data_availability'];
+    startNewPrintFigureSBPOP(filename);
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Assessment of data availability TRT/STUDY
+    % Get PK data
+    if FLAG_TYPE,
+        dataPlot    = data(data.TYPE==TYPE_NAME,:);
+    else
+        dataPlot  = data(strcmp(data.NAME,TYPE_NAME),:);
+    end
+
+    % Do the plot
+    nameGroupX              = 'TRT';
+    nameGroupY              = 'STUDY';
+    nameY                   = 'DV';
+    nameX                   = 'TIME';
+    options                 = [];
+    options.nameSubGroup    = 'ID';
+    options.nameColorGroup  = 'ID';
+    options.linetype        = '--';
+    options.linewidth       = 1;
+    options.xlabelText      = sprintf('Time [%s]',dataPlot.TIME_UNIT{1});
+    nY                      = length(unique(dataPlot.(nameGroupY)));
+    options.ylabelText      = {};
+    for k=1:nY, options.ylabelText{k} = ''; end
+    if nY==1,
+        options.ylabelText{1} = sprintf('%s [%s]',dataPlot.NAME{1},dataPlot.UNIT{1});
+    else
+        options.ylabelText{floor(nY/2)} = sprintf('%s [%s]',dataPlot.NAME{1},dataPlot.UNIT{1});
+    end
+    options.logY            = 0;
+    options.sameaxes        = 1;
+    if ~color,
+        options.showmarkers      = 1;
+        options.linecolorsCustom = bwcolors;
+        options.markersize       = 3;
+    end
+    options.maxlegendentries = 20;
+    options.heighttitlebarX = 0.12;
+    SBPOPplotfacetgrid(dataPlot,nameX,nameY,nameGroupX,nameGroupY,options)
+    printFigureSBPOP(gcf,filename);
+    close(gcf);
+    convert2pdfSBPOP(filename);
+end
+
+if plotCovariateData,
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Summary statistics covariates
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    filename    = [outputPath '04_summary_statistics'];
+    SBPOPexploreSummaryStats(data,covNames,catNames,filename);
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Graphical exploration of covariates
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    filename    = [outputPath '05_covariates_relationship'];
+    SBPOPexploreCovariateCorrelations(data,covNames,catNames,filename);
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/02_DataExploration/SBPOPgraphicalExplorationContinuousPD.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/02_DataExploration/SBPOPgraphicalExplorationContinuousPD.m
new file mode 100644
index 0000000000000000000000000000000000000000..7c6e8fe3d62b2cd1e3fd8d0a3c36e7ad27f9d54c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/02_DataExploration/SBPOPgraphicalExplorationContinuousPD.m
@@ -0,0 +1,1740 @@
+function [] = SBPOPgraphicalExplorationContinuousPD(data,NAMES,BASELINENAMES,COVARIATES,TIMEPOINT_CHANGE,PD_IMPROVEMENT,options)
+% Function for some general exploration of several continuous PD readouts.
+%
+% Several plots are generated in a PDF:
+%
+% * Nominal time vs. actual time
+% * Rate of missing observations over time by TRT group
+% * More detailed assessment of individual missing observations and
+%   corresponding response levels
+% * Response levels (absolute) by TRT group over nominal time - median and standard errors
+% * Response levels (absolute and relative to baseline) by TRT group over nominal time - median only
+% * Response levels for each TRT group (median and 90% range) over nominal
+%   time. Absolute and relative change from baseline in %
+% * Individual profiles for each TRT group over actual time. Absolute and
+%   relative change from baseline in %
+% * Histograms of PD readouts at baseline and at a user defined timepoint.
+% * Histograms of absolute and relative change of PD readouts at a user
+%   defined timepoint
+% * Correlation of absolute and relative change of PD readouts at a user
+%   defined timepoint with baseline values
+% * Correlation of absolute and relative change of PD readouts at a user
+%   defined timepoint with covariates
+% * Medians (relative change from baseline) of stratified time course data over nominal time. 
+%   Stratification by covariates (upper and lower 50%)
+% * Medians (abslute values) of stratified time course data over nominal time. 
+%   Stratification by covariates (upper and lower 50%)
+% 
+% IMPORTANT: Records with NaN values for NOMINAL_TIME are removed from the analysis
+%
+% Assumptions:
+% 
+% * The dataset is in the generalized data format and augmented at least
+%   with covariate columns and ID column
+% * For each continuous readout of interest, a corresponding baseline
+%   column should be available
+%
+% USAGE:
+% ======
+% SBPOPgraphicalExplorationContinuousPD(data,NAMES,BASELINENAMES,COVARIATES,TIMEPOINT_CHANGE,PD_IMPROVEMENT)
+% SBPOPgraphicalExplorationContinuousPD(data,NAMES,BASELINENAMES,COVARIATES,TIMEPOINT_CHANGE,PD_IMPROVEMENT,options)
+%
+% data:                 dataset in augemented generalized dataset format    
+% NAMES:                cell-array with names of PD readouts to consider
+%                       (names based on NAME column in dataset)
+% BASELINENAMES:        cell-array with names of baseline columns for PD
+%                       readouts to consider (same order) as NAMES
+% COVARIATES:           cell-array with covariates to consider (columns in
+%                       augmented dataset)
+% TIMEPOINT_CHANGE:     Can be left empty ([]). Otherwise:
+%                       Time in the TIME_UNIT in the dataset at which the
+%                       absolute and relative changes from baseline should
+%                       be determined and displayed. Time is based on
+%                       NOMINAL_TIME. Value does not need to exactly match a
+%                       value in the dataset. The first value >= the
+%                       provided one will be used
+% PD_IMPROVEMENT:       Can be left empty ([]). Otherwise:
+%                       Scalar or vector with two values. Can be positive
+%                       or negative. Values indicate some user defined
+%                       thresholds and if the response is better than the
+%                       thresholds a different color will be used when
+%                       plotting the missing observation plots. If two
+%                       values are specified then the second should
+%                       correspond to the threshold of a better response.
+% options:              matlab structure with additional optional
+%                       information:
+%
+%       options.MIN_Y_ABS: Vector with the same length as NAMES to specify
+%                          the minimum Y axes for absolute plots
+%       options.MAX_Y_ABS: Vector with the same length as NAMES to specify
+%                          the maximum Y axes for absolute plots
+%       options.MIN_Y_REL: Vector with the same length as NAMES to specify
+%                          the minimum Y axes for relative plots
+%       options.MAX_Y_REL: Vector with the same length as NAMES to specify
+%                          the maximum Y axes for relative plots
+%       options.filename:  String with path and filename for the output
+%                          PDF. Default: 'PD_exploration_output'
+%       options.fontsize:  Fontsize for the annotation of the plots
+%                          (default: 12)
+
+
+% Information:
+% ============
+% Copyright (C) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+%% ===Handle variable input arguments
+MIN_Y_ABS       = [];
+MAX_Y_ABS       = [];
+MIN_Y_REL       = [];
+MAX_Y_REL       = [];
+filename        = 'PD_exploration_output';
+fontsize        = 12;
+if nargin == 7,
+    try, MIN_Y_ABS=options.MIN_Y_ABS;           catch, end
+    try, MAX_Y_ABS=options.MAX_Y_ABS;           catch, end
+    try, MIN_Y_REL=options.MIN_Y_REL;           catch, end
+    try, MAX_Y_REL=options.MAX_Y_REL;           catch, end
+    try, filename=options.filename;             catch, end
+    try, fontsize=options.fontsize;             catch, end
+end
+
+%% Rename inputs
+PDreadout       = NAMES;
+PDreadout_BASE  = BASELINENAMES;
+
+%% ===Prepare data
+% We keep only the most important columns
+% STYSID1A, ID, TIME, NOMINAL_TIME, NAME, DV, TRT, the passed BASELINENAMES and COVARIATES
+%
+% Furthermore, only the TYPES are kept that correspond to the NAMES
+
+%% Remove all NAMEs from the data that are not in NAMES
+allNAMEs = unique(data.NAME);
+for k=1:length(allNAMEs),
+    
+    if ~ismember(allNAMEs{k},NAMES),
+        data(strcmp(data.NAME,allNAMEs{k}),:) = [];
+    end
+end
+
+%% Copy standard columns
+data2                   = dataset();
+data2.STYSID1A          = data.STYSID1A;
+data2.ID                = data.ID;
+data2.TIME              = data.TIME;
+data2.NOMINAL_TIME      = data.NOMINAL_TIME;
+data2.NAME              = data.NAME;
+data2.DV                = data.DV;
+data2.TRT               = data.TRT;
+%data2.STUDY             = data.STUDY; % Not needed
+
+%% Copy BASELINENAMES and COVARIATES
+for k=1:length(BASELINENAMES),
+    data2.(BASELINENAMES{k}) = data.(BASELINENAMES{k});
+end
+for k=1:length(COVARIATES),
+    data2.(COVARIATES{k}) = data.(COVARIATES{k});
+end
+    
+%% Check if NOMINAL_TIME contains NaN .. if yes then big warning
+if ~isempty(find(isnan(data2.NOMINAL_TIME))),
+    disp('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
+    disp('The dataset contains NaN in NOMINAL_TIME!!! This should NOT happen.');
+    disp('Please check with the programmer ...');
+    disp('For the purpose of this analysis the records with NOMINAL_TIME NaN will be removed.');
+    disp('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
+end 
+data2(isnan(data2.NOMINAL_TIME),:) = [];
+
+%% Prepare wide dataset
+datawide = SBPOPdataset2wide(data2,'ID','NOMINAL_TIME','NAME','DV');
+
+%% ===Get colors
+colors = getcolorsSBPOP();
+
+%% ===Prepare output folder and file
+if ~isempty(filename),
+    [folder,file] = fileparts(filename);
+    if ~isempty(folder),
+        mkdir(folder)
+    end
+    startNewPrintFigureSBPOP(filename); 
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% ===Plot TIME vs. NOMINAL_TIME
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Checking if TIME and NOMINAL_TIME match reasonably
+figure(1); clf
+allTRT = unique(datawide.TRT);
+legendText = {};
+for k=1:length(allTRT),  
+    datax = datawide(datawide.TRT==allTRT(k),:);
+    plot(datax.TIME,datax.NOMINAL_TIME,'.','MarkerSize',25,'Color',colors(k,:)); hold on
+    legendText{k} = sprintf('TRT: %d',allTRT(k));
+end
+grid on;
+xlabel('TIME','FontSize',14,'Interpreter','none')
+ylabel('NOMINAL_TIME','FontSize',14,'Interpreter','none')
+title('Comparison between TIME and NOMINAL_TIME','FontSize',16,'Interpreter','none')
+set(gca,'FontSize',12)
+legend(legendText,'Location','Best')
+if ~isempty(filename),
+    printFigureSBPOP(gcf,filename)
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% === Assess missing observations per TRT for each PD readout
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% Get nrows and ncols
+nrows = ceil(sqrt(length(allTRT)));
+ncols = ceil(length(allTRT)/nrows);
+
+figure(1); clf;
+for k=1:length(PDreadout),
+    allTRT = unique(datawide.TRT);
+    for k2=1:length(allTRT),
+        datak = datawide(datawide.TRT==allTRT(k2),:);
+        % Determine max number of patients in TRT
+        N_TRT = length(unique(datak.ID));
+        % Determine number of patients at NT samples
+        N_TRT_NT = [];
+        allNT = unique(datak.NOMINAL_TIME);
+        for k3=1:length(allNT),
+            datak3 = datak(datak.NOMINAL_TIME==allNT(k3),:);
+            N_TRT_NT = [N_TRT_NT length(unique(datak3.ID))];
+        end
+        % Determine relative change
+        NmissingRel = -100*(N_TRT_NT-N_TRT)/N_TRT;
+    
+        % Plot
+        subplot(nrows,ncols,k2);
+        plot(allNT,NmissingRel,'Color',colors(k,:),'LineWidth',2); hold on
+        grid on
+        
+        % If in last row then add xlabel
+        if k2>length(allTRT)-ncols,
+            xlabel('Nominal Time','FontSize',fontsize,'Interpreter','none');
+        end
+        % If in first column add ylabel
+        if mod(k2+ncols,ncols*2) == 1 || length(allTRT)==1,
+            ylabel(sprintf('Missing observations [%%]'),'FontSize',fontsize,'Interpreter','none');
+        end
+        
+        axis([min(allNT) max(allNT) 0 max(max(NmissingRel),1)    ]);
+        
+        % Add title in figure
+        XLim = get(gca,'XLim');
+        YLim = get(gca,'YLim');
+        text(mean(XLim),max(YLim),sprintf('TRT: %d\nNmax=%d',allTRT(k2),N_TRT),'HorizontalAlign','Center','VerticalAlign','top','FontSize',fontsize,'FontWeight','bold','Interpreter','none')
+        
+    end
+end
+if ~isempty(filename),
+    printFigureSBPOP(gcf,filename)
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Assess missing observations / drop outs more in details
+% Only plotted for the FIRST PDreadout! Otherwise to much info.
+% Please make sure the most important readout is used ...
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+allTRT = unique(datawide.TRT);
+
+for k = 1:length(allTRT),
+    datak = datawide(datawide.TRT==allTRT(k),:);
+    
+    % Get nominal times for this TRT groups
+    NT_TRT = unique(datak.NOMINAL_TIME);
+    
+    % Determine missing IDs at each nominal time point
+    MISSING_OVER_TIME = {};
+    allID = unique(datak.ID);
+    for k2=1:length(NT_TRT),
+        datak2 = datak(datak.NOMINAL_TIME==NT_TRT(k2),:);
+        IDs_NT = unique(datak2.ID);
+        MISSING_OVER_TIME{k2} = setdiff(allID,IDs_NT);
+    end
+    
+    % Determine all IDs that are at least once missing
+    allIDmissing = [];
+    for k2=1:length(MISSING_OVER_TIME),
+        allIDmissing = [allIDmissing; MISSING_OVER_TIME{k2}];
+    end
+    allIDmissing = unique(allIDmissing);
+    
+    if ~isempty(allIDmissing),
+        
+        % Determine if visit done or not
+        VISIT_DONE = zeros(length(allIDmissing),length(NT_TRT));
+        % Cycle through subjects
+        for k2=1:length(allIDmissing),
+            datak2 = datak(datak.ID==allIDmissing(k2),:);
+            % Cycle through time points (NT)
+            for k3=1:length(NT_TRT),
+                datakk3 = datak2(datak2.NOMINAL_TIME==NT_TRT(k3),:);
+                
+                if ~isempty(datakk3),
+                    % Get PD readout of first PD value only
+                    PD_readout_value = datakk3.(PDreadout{1});
+                    
+                    % Get PD baseline of first PD value only
+                    PD_readout_base = datakk3.(PDreadout_BASE{1});
+                    
+                    % Determine relative change from baseline
+                    CHANGE = 100*(PD_readout_value-PD_readout_base)./PD_readout_base;
+                    
+                    % If change better than user specified value (need to take care
+                    % of sign)
+                    if isempty(PD_IMPROVEMENT),
+                        % Possible to have PD_IMPROVEMENT empty if not needed.
+                        if ~isnan(PD_readout_value),
+                            VISIT_DONE(k2,k3) = 1;
+                        end
+                    elseif length(PD_IMPROVEMENT) == 1,
+                        if PD_IMPROVEMENT>0 && CHANGE>=PD_IMPROVEMENT,
+                            VISIT_DONE(k2,k3) = 2;
+                        elseif PD_IMPROVEMENT<=0 && CHANGE<=PD_IMPROVEMENT,
+                            VISIT_DONE(k2,k3) = 2;
+                        elseif ~isnan(PD_readout_value),
+                            VISIT_DONE(k2,k3) = 1;
+                        end
+                    elseif length(PD_IMPROVEMENT) == 2,
+                        if PD_IMPROVEMENT(1)>0,
+                            if CHANGE>=PD_IMPROVEMENT(2),
+                                VISIT_DONE(k2,k3) = 3;
+                            elseif CHANGE>=PD_IMPROVEMENT(1),
+                                VISIT_DONE(k2,k3) = 2;
+                            elseif ~isnan(PD_readout_value),
+                                VISIT_DONE(k2,k3) = 1;
+                            end
+                        else
+                            if PD_IMPROVEMENT(1)<=0
+                                if CHANGE<=PD_IMPROVEMENT(2),
+                                    VISIT_DONE(k2,k3) = 3;
+                                elseif CHANGE<=PD_IMPROVEMENT(1),
+                                    VISIT_DONE(k2,k3) = 2;
+                                elseif ~isnan(PD_readout_value),
+                                    VISIT_DONE(k2,k3) = 1;
+                                end
+                            end
+                        end
+                    else
+                        error('PD_IMPROVEMENT can max have two elements.');
+                    end
+                end
+            end
+        end
+        Y = sortrows([allIDmissing sum(VISIT_DONE>=1,2) VISIT_DONE],2);
+        figure(1); clf
+        for k2=1:length(allIDmissing),
+            IDk = Y(k2,1);
+            datak = Y(k2,3:end);
+            TIMEk = NT_TRT(find(datak==0));
+            if ~isempty(TIMEk), plot(TIMEk,k2,'rx','MarkerSize',20,'LineWidth',2); hold on; end
+            TIMEk = NT_TRT(find(datak==1));
+            if ~isempty(TIMEk), plot(TIMEk,k2,'k.','MarkerSize',25); hold on; end
+            TIMEk = NT_TRT(find(datak==2));
+            if ~isempty(TIMEk), plot(TIMEk,k2,'b.','MarkerSize',25); hold on; end
+            TIMEk = NT_TRT(find(datak==3));
+            if ~isempty(TIMEk), plot(TIMEk,k2,'g.','MarkerSize',25); hold on; end
+        end
+        xlabel('Nominal Time','FontSize',14,'Interpreter','none');
+        set(gca,'YTick',[1:length(allIDmissing)]);
+        set(gca,'YTickLabel',Y(:,1));
+        set(gca,'FontSize',12);
+        grid on
+        if ~isempty(PD_IMPROVEMENT),
+            PD_IMPROVEMENT_string = strtrim(sprintf('%g ',PD_IMPROVEMENT));
+            title(sprintf('Missing observations assessment\nTRT: %d\n(Based on %s assessment)\n(Improvement settings: [%s] percent)',allTRT(k),PDreadout{1},PD_IMPROVEMENT_string),'FontSize',16,'Interpreter','none')
+        else
+            title(sprintf('Missing observations assessment\nTRT: %d\n(Based on %s assessment)',allTRT(k),PDreadout{1}),'FontSize',16,'Interpreter','none')
+        end
+        YLim = get(gca,'YLim');
+        set(gca,'YLim',[YLim(1)-0.5 YLim(2)+0.5])
+        
+        if ~isempty(filename),
+            printFigureSBPOP(gcf,filename)
+        end
+    end
+end
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% ===Plot median absolute PD readouts ... one per figure all TRTs in same plot - with errorbars
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+MEDIANdata = getMedianModelingDataStructSBPOP(datawide,PDreadout,'continuous');
+
+% Determine min and max NT
+NT = [];
+for k=1:length(MEDIANdata.NT),
+    NT = [NT; MEDIANdata.NT{k}];
+end
+minNT = min(NT);
+maxNT = max(NT);
+
+for k=1:length(MEDIANdata.NAMES),
+    figure(k); clf;
+    
+    legendText = {};
+    for kTRT=1:length(MEDIANdata.TRT),
+        plot(MEDIANdata.NT{kTRT},MEDIANdata.DATA{kTRT}(k,:),'.-','Color',colors(kTRT,:),'LineWidth',3,'MarkerSize',20); hold on
+        legendText{kTRT} = sprintf('TRT: %d',MEDIANdata.TRT(kTRT));
+    end
+
+    % error bars
+    for kTRT=1:length(MEDIANdata.TRT),
+        errorbar(MEDIANdata.NT{kTRT}',MEDIANdata.DATA{kTRT}(k,:),MEDIANdata.DATA_STDERR{kTRT}(k,:),'Color',colors(kTRT,:),'LineWidth',2); hold on
+    end
+    
+    title(sprintf('Median %s with standard errors',MEDIANdata.NAMES{k}),'FontSize',fontsize+2,'Interpreter','none');
+    xlabel('Nominal Time','FontSize',fontsize,'Interpreter','none');
+    ylabel(sprintf('Absolute %s',MEDIANdata.NAMES{k}),'FontSize',fontsize,'Interpreter','none');
+    set(gca,'FontSize',fontsize-2);
+    grid on;
+    set(gca,'XLim',[minNT maxNT]);
+    h = legend(legendText,'Location','NorthEast');
+    set(h,'FontSize',fontsize);
+    if ~isempty(filename),
+        printFigureSBPOP(gcf,filename)
+    end    
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% ===Plot median absolute PD readouts ... one per figure all TRTs in same plot - WITHOUT errorbars
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+MEDIANdata = getMedianModelingDataStructSBPOP(datawide,PDreadout,'continuous');
+
+% Determine min and max NT
+NT = [];
+for k=1:length(MEDIANdata.NT),
+    NT = [NT; MEDIANdata.NT{k}];
+end
+minNT = min(NT);
+maxNT = max(NT);
+
+for k=1:length(MEDIANdata.NAMES),
+    figure(k); clf;
+    
+    legendText = {};
+    for kTRT=1:length(MEDIANdata.TRT),
+        plot(MEDIANdata.NT{kTRT},MEDIANdata.DATA{kTRT}(k,:),'.-','Color',colors(kTRT,:),'LineWidth',3,'MarkerSize',20); hold on
+        legendText{kTRT} = sprintf('TRT: %d',MEDIANdata.TRT(kTRT));
+    end
+
+    title(sprintf('Median %s (absolute)',MEDIANdata.NAMES{k}),'FontSize',fontsize+2,'Interpreter','none');
+    xlabel('Nominal Time','FontSize',fontsize,'Interpreter','none');
+    ylabel(sprintf('Absolute %s',MEDIANdata.NAMES{k}),'FontSize',fontsize,'Interpreter','none');
+    set(gca,'FontSize',fontsize-2);
+    grid on;
+    set(gca,'XLim',[minNT maxNT]);
+    h = legend(legendText,'Location','NorthEast');
+    set(h,'FontSize',fontsize);
+    if ~isempty(filename),
+        printFigureSBPOP(gcf,filename)
+    end    
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% ===Plot median relative PD readouts ... one per figure all TRTs in same plot - WITHOUT errorbars
+% Only plot if baseline is not 0
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+for k=1:length(PDreadout),
+    dataPD = datawide;
+    
+    % Remove NaN things
+    dataPD(isnan(dataPD.(PDreadout{k})),:) = [];
+    dataPD(isnan(dataPD.(PDreadout_BASE{k})),:) = [];
+    dataPD(isnan(dataPD.NOMINAL_TIME),:) = [];
+    
+    % Get treatment code
+    allTRT = unique(dataPD.TRT);
+    
+    % Check if baseline is 0 and only plot if it is not
+    if dataPD.(PDreadout_BASE{k})(1) ~= 0,
+        figure(1); clf
+        
+        % Get relative change from baseline
+        dataPD.([PDreadout{k} '_rel_change']) = 100*(dataPD.(PDreadout{k})-dataPD.(PDreadout_BASE{k}))./dataPD.(PDreadout_BASE{k});
+        
+        % Plot for all TRT
+        legendText = {};
+        for k2=1:length(allTRT),
+            dataPDTRT = dataPD(dataPD.TRT==allTRT(k2),:);
+            allNT = unique(dataPDTRT.NOMINAL_TIME); allNT(isnan(allNT)) = [];
+            binningInfo = {allNT,ones(1,length(allNT))};
+            
+            % Calculate median relative change from baseline
+            [xbin1,median_REL] = binnedquantilesSB(dataPDTRT.NOMINAL_TIME,dataPDTRT.([PDreadout{k} '_rel_change']),0.5,binningInfo,0);
+            
+            plot(xbin1,median_REL,'.-','Color',colors(k2,:),'LineWidth',3,'MarkerSize',20); hold on;
+            
+            grid on
+            
+            set(gca,'XLim',[min(0,min(dataPD.NOMINAL_TIME)) max(dataPD.NOMINAL_TIME)]);
+            set(gca,'FontSize',fontsize-2);
+            
+            title(sprintf('Median %s (relative to baseline)',PDreadout{k}),'FontSize',fontsize+2,'Interpreter','none');
+            
+            xlabel('Nominal Time','FontSize',fontsize,'Interpreter','none');
+            ylabel(sprintf('Relative change %s [%%baseline]',PDreadout{k}),'FontSize',fontsize,'Interpreter','none');
+            legendText{k2} = sprintf('TRT: %d',MEDIANdata.TRT(k2));
+        end
+        h = legend(legendText,'Location','NorthEast');
+        set(h,'FontSize',fontsize);
+        
+        if ~isempty(filename),
+            printFigureSBPOP(gcf,filename)
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Absolute PD - NOMINAL TIME / Median+Range
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(PDreadout),
+    figure(1); clf
+    dataPD = datawide;
+
+    % Remove NaN things
+    dataPD(isnan(dataPD.(PDreadout{k})),:) = [];
+    dataPD(isnan(dataPD.NOMINAL_TIME),:) = [];
+    
+    % Get treatment code
+    allTRT = unique(dataPD.TRT);
+    
+    % Get nrows and ncols
+    nrows = ceil(sqrt(length(allTRT)));
+    ncols = ceil(length(allTRT)/nrows);
+    
+    % Plot for all TRT
+    for k2=1:length(allTRT),
+        dataPDTRT = dataPD(dataPD.TRT==allTRT(k2),:);
+        allNT = unique(dataPDTRT.NOMINAL_TIME); allNT(isnan(allNT)) = [];
+        binningInfo = {allNT,ones(1,length(allNT))};
+        
+        % Calculate median absolute
+        [xbin,median_ABS] = binnedquantilesSB(dataPDTRT.NOMINAL_TIME,dataPDTRT.(PDreadout{k}),0.5,binningInfo,0);
+        % Calculate 5%Q absolute
+        [xbin,q05_ABS] = binnedquantilesSB(dataPDTRT.NOMINAL_TIME,dataPDTRT.(PDreadout{k}),0.05,binningInfo,0);
+        % Calculate 95%Q absolute
+        [xbin,q95_ABS] = binnedquantilesSB(dataPDTRT.NOMINAL_TIME,dataPDTRT.(PDreadout{k}),0.95,binningInfo,0);
+        
+        subplot(nrows,ncols,k2);
+        plot(xbin,median_ABS,'k-','LineWidth',3); hold on;
+        SBPOPplotfill(xbin(:)',q05_ABS(:)',q95_ABS(:)',0.8*[1 1 1],1); hold on
+        plot(xbin,median_ABS,'k-','LineWidth',3); hold on;
+        grid on
+        
+        for kt=1:length(allNT),
+            N_TRT_NT = length(unique(dataPDTRT.ID(dataPDTRT.NOMINAL_TIME==allNT(kt))));
+            
+            
+            text(allNT(kt),median_ABS(kt)*1.03,sprintf('N=%d',N_TRT_NT),'FontSize',fontsize,'Interpreter','none')
+        end
+        
+        % axes
+        set(gca,'XLim',[min(dataPD.NOMINAL_TIME) max(dataPD.NOMINAL_TIME)]);
+        if ~isempty(MIN_Y_ABS) && ~isempty(MAX_Y_ABS),
+            set(gca,'YLim',[MIN_Y_ABS(k),MAX_Y_ABS(k)]);
+        else
+            YLim = get(gca,'YLim');
+            set(gca,'YLim',YLim);
+        end
+        
+        % If in last row then add xlabel
+        if k2>length(allTRT)-ncols,
+            xlabel('Nominal Time','FontSize',fontsize,'Interpreter','none');
+        end
+        % If in first column add ylabel
+        if mod(k2+ncols,ncols*2) == 1 || length(allTRT)==1,
+            ylabel(sprintf('Absolute %s',PDreadout{k}),'FontSize',fontsize,'Interpreter','none');
+        end
+        
+        % Add title in figure
+        XLim = get(gca,'XLim');
+        YLim = get(gca,'YLim');
+        text(mean(XLim),max(YLim),sprintf('TRT: %d',allTRT(k2)),'HorizontalAlign','Center','VerticalAlign','top','FontSize',fontsize,'FontWeight','bold','Interpreter','none')
+    end
+    subplot(nrows,ncols,1);
+    legend('Median','90% range','Location','Best')
+    if ~isempty(filename),
+        printFigureSBPOP(gcf,filename)
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Absolute PD - TIME / Individual plots
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(PDreadout),
+    figure(1); clf
+    dataPD = datawide;
+
+    % Remove NaN things
+    dataPD(isnan(dataPD.(PDreadout{k})),:) = [];
+    dataPD(isnan(dataPD.TIME),:) = [];
+    
+    % Get treatment code
+    allTRT = unique(dataPD.TRT);
+    
+    % Get nrows and ncols
+    nrows = ceil(sqrt(length(allTRT)));
+    ncols = ceil(length(allTRT)/nrows);
+    
+    % Plot for all TRT
+    for k2=1:length(allTRT),
+        dataPDTRT = dataPD(dataPD.TRT==allTRT(k2),:);
+
+        subplot(nrows,ncols,k2);
+
+        allID = unique(dataPDTRT.ID);
+        for k3=1:length(allID),
+            datak3 = dataPDTRT(dataPDTRT.ID==allID(k3),:);
+            
+            plot(datak3.TIME,datak3.(PDreadout{k}),'.-','LineWidth',1,'MarkerSize',15,'Color',0.7*[1 1 1]); hold on;
+        end
+        grid on
+        
+        % axes
+        set(gca,'XLim',[0 max(dataPD.NOMINAL_TIME)]);
+        if ~isempty(MIN_Y_ABS) && ~isempty(MAX_Y_ABS),
+            set(gca,'YLim',[MIN_Y_ABS(k),MAX_Y_ABS(k)]);
+        else
+            YLim = get(gca,'YLim');
+            set(gca,'YLim',YLim);
+        end
+            
+
+        % If in last row then add xlabel
+        if k2>length(allTRT)-ncols,
+            xlabel('Actual Time','FontSize',fontsize,'Interpreter','none');
+        end
+        % If in first column add ylabel
+        if mod(k2+ncols,ncols*2) == 1 || length(allTRT)==1,
+            ylabel(sprintf('Absolute %s',PDreadout{k}),'FontSize',fontsize,'Interpreter','none');
+        end
+                
+        % Add title in figure
+        XLim = get(gca,'XLim');
+        YLim = get(gca,'YLim');
+        text(mean(XLim),max(YLim),sprintf('TRT: %d',allTRT(k2)),'HorizontalAlign','Center','VerticalAlign','top','FontSize',fontsize,'FontWeight','bold','Interpreter','none')
+        
+    end
+    subplot(nrows,ncols,1);
+    legend('Median','90% range','Location','Best')
+    if ~isempty(filename),
+        printFigureSBPOP(gcf,filename)
+    end
+end
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Relative PD - only if baseline not 0
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(PDreadout),
+    dataPD = datawide;
+    
+    % Remove NaN things
+    dataPD(isnan(dataPD.(PDreadout{k})),:) = [];
+    dataPD(isnan(dataPD.(PDreadout_BASE{k})),:) = [];
+    dataPD(isnan(dataPD.NOMINAL_TIME),:) = [];
+    
+    % Get treatment code
+    allTRT = unique(dataPD.TRT);
+    
+
+    if dataPD.(PDreadout_BASE{k})(1) ~=0,
+        figure(1); clf
+        
+        % Get relative change from baseline
+        dataPD.([PDreadout{k} '_rel_change']) = 100*(dataPD.(PDreadout{k})-dataPD.(PDreadout_BASE{k}))./dataPD.(PDreadout_BASE{k});
+        
+        % Get nrows and ncols
+        nrows = ceil(sqrt(length(allTRT)));
+        ncols = ceil(length(allTRT)/nrows);
+        
+        % Plot for all TRT
+        for k2=1:length(allTRT),
+            dataPDTRT = dataPD(dataPD.TRT==allTRT(k2),:);
+            allNT = unique(dataPDTRT.NOMINAL_TIME); allNT(isnan(allNT)) = [];
+            binningInfo = {allNT,ones(1,length(allNT))};
+            
+            % Calculate median relative change from baseline
+            [xbin1,median_REL] = binnedquantilesSB(dataPDTRT.NOMINAL_TIME,dataPDTRT.([PDreadout{k} '_rel_change']),0.5,binningInfo,0);
+            % Calculate 5%Q relative change from baseline
+            [xbin2,q05_REL] = binnedquantilesSB(dataPDTRT.NOMINAL_TIME,dataPDTRT.([PDreadout{k} '_rel_change']),0.05,binningInfo,0);
+            % Calculate 95%Q relative change from baseline
+            [xbin3,q95_REL] = binnedquantilesSB(dataPDTRT.NOMINAL_TIME,dataPDTRT.([PDreadout{k} '_rel_change']),0.95,binningInfo,0);
+            
+            subplot(nrows,ncols,k2);
+            try
+                plot(xbin1,median_REL,'k-','LineWidth',3); hold on;
+                SBPOPplotfill(xbin1(:)',q05_REL(:)',q95_REL(:)',0.8*[1 1 1],1); hold on
+                plot(xbin1,median_REL,'k-','LineWidth',3); hold on;
+            catch
+                plot(xbin1,median_REL,'k-','LineWidth',3); hold on;
+                plot(xbin2,q05_REL,'k-','LineWidth',2); hold on;
+                plot(xbin3,q95_REL,'k-','LineWidth',2); hold on;
+            end
+            grid on
+            
+            for kt=1:length(allNT),
+                N_TRT_NT = length(unique(dataPDTRT.ID(dataPDTRT.NOMINAL_TIME==allNT(kt))));
+                text(allNT(kt),median_REL(kt)*1.03,sprintf('N=%d',N_TRT_NT),'Interpreter','none')
+            end
+            
+            % axes
+            set(gca,'XLim',[0 max(dataPD.NOMINAL_TIME)]);
+            if ~isempty(MIN_Y_REL) && ~isempty(MAX_Y_REL),
+                set(gca,'YLim',[MIN_Y_REL(k),MAX_Y_REL(k)]);
+            else
+                YLim = get(gca,'YLim');
+                set(gca,'YLim',YLim);
+            end
+            
+            % If in last row then add xlabel
+            if k2>length(allTRT)-ncols,
+                xlabel('Nominal Time','FontSize',fontsize,'Interpreter','none');
+            end
+            % If in first column add ylabel
+            if mod(k2+ncols,ncols*2) == 1 || length(allTRT)==1,
+                ylabel(sprintf('Relative change %s [%%baseline]',PDreadout{k}),'FontSize',fontsize,'Interpreter','none');
+            end
+            % Add title in figure
+            XLim = get(gca,'XLim');
+            YLim = get(gca,'YLim');
+            text(mean(XLim),max(YLim),sprintf('TRT: %d',allTRT(k2)),'HorizontalAlign','Center','VerticalAlign','top','FontSize',fontsize,'FontWeight','bold','Interpreter','none')
+            
+        end
+        subplot(nrows,ncols,1);
+        legend('Median','90% range','Location','Best')
+        if ~isempty(filename),
+            printFigureSBPOP(gcf,filename)
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Relative PD - TIME / Individual plots - if baseline not 0
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(PDreadout),
+    dataPD = datawide;
+
+    % Remove NaN things
+    dataPD(isnan(dataPD.(PDreadout{k})),:) = [];
+    dataPD(isnan(dataPD.(PDreadout_BASE{k})),:) = [];
+    dataPD(isnan(dataPD.NOMINAL_TIME),:) = [];
+    
+    % Get treatment code
+    allTRT = unique(dataPD.TRT);
+    
+    if dataPD.(PDreadout_BASE{k})(1) ~=0,
+        figure(1); clf
+        % Get relative change from baseline
+        dataPD.([PDreadout{k} '_rel_change']) = 100*(dataPD.(PDreadout{k})-dataPD.(PDreadout_BASE{k}))./dataPD.(PDreadout_BASE{k});
+        
+        % Get nrows and ncols
+        nrows = ceil(sqrt(length(allTRT)));
+        ncols = ceil(length(allTRT)/nrows);
+        
+        % Plot for all TRT
+        for k2=1:length(allTRT),
+            dataPDTRT = dataPD(dataPD.TRT==allTRT(k2),:);
+            
+            subplot(nrows,ncols,k2);
+            
+            allID = unique(dataPDTRT.ID);
+            for k3=1:length(allID),
+                datak3 = dataPDTRT(dataPDTRT.ID==allID(k3),:);
+                
+                plot(datak3.TIME,datak3.([PDreadout{k} '_rel_change']),'.-','LineWidth',1,'MarkerSize',15,'Color',0.7*[1 1 1]); hold on;
+            end
+            grid on
+            
+            % axes
+            set(gca,'XLim',[0 max(dataPD.NOMINAL_TIME)]);
+            if ~isempty(MIN_Y_ABS) && ~isempty(MAX_Y_ABS),
+                set(gca,'YLim',[MIN_Y_REL(k),MAX_Y_REL(k)]);
+            else
+                YLim = get(gca,'YLim');
+                set(gca,'YLim',YLim);
+            end
+            
+            % If in last row then add xlabel
+            if k2>length(allTRT)-ncols,
+                xlabel('Actual Time','FontSize',fontsize,'Interpreter','none');
+            end
+            % If in first column add ylabel
+            if mod(k2+ncols,ncols*2) == 1 || length(allTRT)==1,
+                ylabel(sprintf('Relative change %s [%%baseline]',PDreadout{k}),'FontSize',fontsize,'Interpreter','none');
+            end
+            % Add title in figure
+            XLim = get(gca,'XLim');
+            YLim = get(gca,'YLim');
+            text(mean(XLim),max(YLim),sprintf('TRT: %d',allTRT(k2)),'HorizontalAlign','Center','VerticalAlign','top','FontSize',fontsize,'FontWeight','bold','Interpreter','none')
+            
+        end
+        subplot(nrows,ncols,1);
+        legend('Median','90% range','Location','Best')
+        if ~isempty(filename),
+            printFigureSBPOP(gcf,filename)
+        end
+    end
+end
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% ===Plot distribution of data at baseline and at user specified time point
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%% Start plotting baseline values
+for k=1:length(PDreadout),
+    figure(1); clf
+    dataPD = datawide;
+
+    % Remove NaN things
+    dataPD(isnan(dataPD.(PDreadout_BASE{k})),:) = [];
+    
+    % Get treatment code
+    allTRT = unique(dataPD.TRT);
+    
+    % Get nrows and ncols
+    nrows = ceil(sqrt(length(allTRT)));
+    ncols = ceil(length(allTRT)/nrows);
+    
+    % Plot for all TRT
+    for k2=1:length(allTRT),
+        dataPDTRT = dataPD(dataPD.TRT==allTRT(k2),:);
+
+        subplot(nrows,ncols,k2);
+
+        allID = unique(dataPDTRT.ID);
+        BASE  = [];
+        for k3=1:length(allID),
+            datak3 = dataPDTRT(dataPDTRT.ID==allID(k3),:);
+            BASE = [BASE datak3.(PDreadout_BASE{k})(1)];
+        end
+        [n,x] = hist(BASE);
+        bar(x,n)
+        grid on
+        
+        % If in last row then add xlabel
+        if k2>length(allTRT)-ncols,
+            xlabel(sprintf('%s BASELINE',PDreadout{k}),'FontSize',fontsize,'Interpreter','none');
+        end
+        
+        YLim = get(gca,'YLim');
+        set(gca,'YLim',YLim);
+        XLim = get(gca,'XLim');
+        set(gca,'XLim',XLim);
+
+        
+        % Add title in figure
+        XLim = get(gca,'XLim');
+        YLim = get(gca,'YLim');
+        text(mean(XLim),max(YLim),sprintf('TRT: %d',allTRT(k2)),'HorizontalAlign','Center','VerticalAlign','top','FontSize',fontsize,'FontWeight','bold','Interpreter','none')
+        
+        
+    end
+    if ~isempty(filename),
+        printFigureSBPOP(gcf,filename)
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Plot at user defined timepoint - if time point defined
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(TIMEPOINT_CHANGE),
+    % Assume first NOMINAL_TIMEPOINT >= the user defined one
+    for k=1:length(PDreadout),
+        figure(1); clf
+        dataPD = datawide;
+        
+        % Remove NaN things
+        dataPD(isnan(dataPD.(PDreadout_BASE{k})),:) = [];
+        
+        % Get treatment code
+        allTRT = unique(dataPD.TRT);
+        
+        % Get nrows and ncols
+        nrows = ceil(sqrt(length(allTRT)));
+        ncols = ceil(length(allTRT)/nrows);
+        
+        % Plot for all TRT
+        for k2=1:length(allTRT),
+            dataPDTRT = dataPD(dataPD.TRT==allTRT(k2),:);
+            
+            subplot(nrows,ncols,k2);
+            
+            allID = unique(dataPDTRT.ID);
+            BASE  = [];
+            TIME_VALUE = [];
+            for k3=1:length(allID),
+                datak3 = dataPDTRT(dataPDTRT.ID==allID(k3),:);
+                BASE = [BASE datak3.(PDreadout_BASE{k})(1)];
+                ix = find(datak3.NOMINAL_TIME>=TIMEPOINT_CHANGE);
+                if ~isempty(ix),
+                    TIME_VALUE = [TIME_VALUE datak3.(PDreadout{k})(ix(1))];
+                else
+                    TIME_VALUE = [TIME_VALUE NaN];
+                end
+            end
+            [n,x] = hist(TIME_VALUE);
+            bar(x,n)
+            grid on
+            
+            % If in last row then add xlabel
+            if k2>length(allTRT)-ncols,
+                xlabel(sprintf('%s (TIME~%g)',PDreadout{k},TIMEPOINT_CHANGE),'FontSize',fontsize,'Interpreter','none');
+            end
+            
+            YLim = get(gca,'YLim');
+            set(gca,'YLim',YLim);
+            XLim = get(gca,'XLim');
+            set(gca,'XLim',XLim);
+            
+            % Add title in figure
+            XLim = get(gca,'XLim');
+            YLim = get(gca,'YLim');
+            text(mean(XLim),max(YLim),sprintf('TRT: %d',allTRT(k2)),'HorizontalAlign','Center','VerticalAlign','top','FontSize',fontsize,'FontWeight','bold','Interpreter','none')
+            
+        end
+        if ~isempty(filename),
+            printFigureSBPOP(gcf,filename)
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% ===Plot change from baseline - absolute and relative
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Absolute change at user defined time point (if time point is defined)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(TIMEPOINT_CHANGE),
+    for k=1:length(PDreadout),
+        figure(1); clf
+        dataPD = datawide;
+        
+        % Remove NaN things
+        dataPD(isnan(dataPD.(PDreadout_BASE{k})),:) = [];
+        
+        % Get treatment code
+        allTRT = unique(dataPD.TRT);
+        
+        % Get nrows and ncols
+        nrows = ceil(sqrt(length(allTRT)));
+        ncols = ceil(length(allTRT)/nrows);
+        
+        % Plot for all TRT
+        for k2=1:length(allTRT),
+            dataPDTRT = dataPD(dataPD.TRT==allTRT(k2),:);
+            
+            subplot(nrows,ncols,k2);
+            
+            allID = unique(dataPDTRT.ID);
+            BASE  = [];
+            TIME_VALUE = [];
+            for k3=1:length(allID),
+                datak3 = dataPDTRT(dataPDTRT.ID==allID(k3),:);
+                BASE = [BASE datak3.(PDreadout_BASE{k})(1)];
+                ix = find(datak3.NOMINAL_TIME>=TIMEPOINT_CHANGE);
+                if ~isempty(ix),
+                    TIME_VALUE = [TIME_VALUE datak3.(PDreadout{k})(ix(1))];
+                else
+                    TIME_VALUE = [TIME_VALUE NaN];
+                end
+            end
+            % Absolute Change
+            CHANGE = TIME_VALUE-BASE;
+            [n,x] = hist(CHANGE);
+            bar(x,n)
+            grid on
+            
+            % If in last row then add xlabel
+            if k2>length(allTRT)-ncols,
+                xlabel(sprintf('%s (TIME~%g)\nAbsolute change',PDreadout{k},TIMEPOINT_CHANGE),'FontSize',fontsize,'Interpreter','none');
+            end
+            
+            YLim = get(gca,'YLim');
+            set(gca,'YLim',YLim);
+            XLim = get(gca,'XLim');
+            set(gca,'XLim',XLim);
+            
+            % Add title in figure
+            XLim = get(gca,'XLim');
+            YLim = get(gca,'YLim');
+            text(mean(XLim),max(YLim),sprintf('TRT: %d',allTRT(k2)),'HorizontalAlign','Center','VerticalAlign','top','FontSize',fontsize,'FontWeight','bold','Interpreter','none')
+            
+        end
+        if ~isempty(filename),
+            printFigureSBPOP(gcf,filename)
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Relative change from baseline in percent at user defined time point (if defined)
+% If baseline not 0
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(TIMEPOINT_CHANGE),
+    for k=1:length(PDreadout),
+        dataPD = datawide;
+        
+        % Remove NaN things
+        dataPD(isnan(dataPD.(PDreadout_BASE{k})),:) = [];
+        
+        % Get treatment code
+        allTRT = unique(dataPD.TRT);
+        
+        % Get nrows and ncols
+        nrows = ceil(sqrt(length(allTRT)));
+        ncols = ceil(length(allTRT)/nrows);
+        
+        if dataPD.(PDreadout_BASE{k})(1) ~=0,
+            figure(1); clf
+            
+            % Plot for all TRT
+            for k2=1:length(allTRT),
+                dataPDTRT = dataPD(dataPD.TRT==allTRT(k2),:);
+                
+                subplot(nrows,ncols,k2);
+                
+                allID = unique(dataPDTRT.ID);
+                BASE  = [];
+                TIME_VALUE = [];
+                for k3=1:length(allID),
+                    datak3 = dataPDTRT(dataPDTRT.ID==allID(k3),:);
+                    BASE = [BASE datak3.(PDreadout_BASE{k})(1)];
+                    ix = find(datak3.NOMINAL_TIME>=TIMEPOINT_CHANGE);
+                    if ~isempty(ix),
+                        TIME_VALUE = [TIME_VALUE datak3.(PDreadout{k})(ix(1))];
+                    else
+                        TIME_VALUE = [TIME_VALUE NaN];
+                    end
+                end
+                % Relative Change
+                CHANGE = 100*(TIME_VALUE-BASE)./BASE;
+                [n,x] = hist(CHANGE);
+                bar(x,n)
+                grid on
+                
+                % If in last row then add xlabel
+                if k2>length(allTRT)-ncols,
+                    xlabel(sprintf('%s (TIME~%g)\nRelative change [%%baseline]',PDreadout{k},TIMEPOINT_CHANGE),'FontSize',fontsize,'Interpreter','none');
+                end
+                
+                YLim = get(gca,'YLim');
+                set(gca,'YLim',YLim);
+                XLim = get(gca,'XLim');
+                set(gca,'XLim',XLim);
+                
+                % Add title in figure
+                XLim = get(gca,'XLim');
+                YLim = get(gca,'YLim');
+                text(mean(XLim),max(YLim),sprintf('TRT: %d',allTRT(k2)),'HorizontalAlign','Center','VerticalAlign','top','FontSize',fontsize,'FontWeight','bold','Interpreter','none')
+                
+            end
+            if ~isempty(filename),
+                printFigureSBPOP(gcf,filename)
+            end
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Assess if change depends on baseline or covariates (absolute and relative change)
+% Do that at TIMEPOINT_CHANGE for all TRT groups at the same time
+% Do only if TIMEPOINT_CHANGE defined
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(TIMEPOINT_CHANGE),
+    %% First keep only the TIMEPOINT_CHANGE values
+    allID = unique(datawide.ID);
+    dataTIMEPOINT_CHANGE = dataset();
+    for k=1:length(allID),
+        datak = datawide(datawide.ID==allID(k),:);
+        ix = find(datak.NOMINAL_TIME>=TIMEPOINT_CHANGE);
+        if ~isempty(ix),
+            dataTIMEPOINT_CHANGE = [dataTIMEPOINT_CHANGE; datak(ix(1),:)];
+        end
+    end
+    
+    %% Absolute changes vs. BASELINE
+    nrows = ceil(sqrt(length(PDreadout)));
+    ncols = ceil(length(PDreadout)/nrows);
+    
+    figure(1); clf;
+    for k=1:length(PDreadout),
+        datak = dataTIMEPOINT_CHANGE;
+        datak(isnan(datak.(PDreadout_BASE{k})),:) = [];
+        datak(isnan(datak.(PDreadout{k})),:) = [];
+        subplot(nrows,ncols,k);
+        CHANGE = datak.(PDreadout{k})-datak.(PDreadout_BASE{k});
+        plot(datak.(PDreadout_BASE{k}),CHANGE,'.','MarkerSize',20)
+        [corr_v,corr_p] = corr(datak.(PDreadout_BASE{k}),CHANGE);
+        
+        xlabel(PDreadout_BASE{k},'FontSize',fontsize)
+        ylabel(sprintf('Absolute change',PDreadout{k},TIMEPOINT_CHANGE),'FontSize',fontsize,'Interpreter','none');
+        
+        YLim = get(gca,'YLim');
+        set(gca,'YLim',YLim);
+        XLim = get(gca,'XLim');
+        set(gca,'XLim',XLim);
+        
+        % Add title in figure
+        XLim = get(gca,'XLim');
+        YLim = get(gca,'YLim');
+        text(mean(XLim),max(YLim),sprintf('Absolute change %s (time~%g)\nvs. %s baseline\nCORR=%1.3g (p=%1.3g)',PDreadout{k},TIMEPOINT_CHANGE,PDreadout{k},corr_v,corr_p),'Interpreter','none','HorizontalAlign','Center','VerticalAlign','top','FontSize',fontsize,'FontWeight','bold')
+        
+        grid on
+    end
+    if ~isempty(filename),
+        printFigureSBPOP(gcf,filename)
+    end
+    
+    %% Relative changes vs. BASELINE
+    % If baseline not 0
+    nrows = ceil(sqrt(length(PDreadout)));
+    ncols = ceil(length(PDreadout)/nrows);
+    
+    figure(1); clf;
+    doPrintFigure = 0;
+    for k=1:length(PDreadout),
+        datak = dataTIMEPOINT_CHANGE;
+        datak(isnan(datak.(PDreadout_BASE{k})),:) = [];
+        datak(isnan(datak.(PDreadout{k})),:) = [];
+
+        if datak.(PDreadout_BASE{k})(1)~=0,
+            doPrintFigure = 1;
+            subplot(nrows,ncols,k);
+            CHANGE = 100*(datak.(PDreadout{k})-datak.(PDreadout_BASE{k}))./datak.(PDreadout_BASE{k});
+            plot(datak.(PDreadout_BASE{k}),CHANGE,'.','MarkerSize',20)
+            [corr_v,corr_p] = corr(datak.(PDreadout_BASE{k}),CHANGE);
+            
+            xlabel(PDreadout_BASE{k},'FontSize',fontsize,'Interpreter','none')
+            ylabel(sprintf('Relative change',PDreadout{k},TIMEPOINT_CHANGE),'FontSize',fontsize,'Interpreter','none');
+            
+            YLim = get(gca,'YLim');
+            set(gca,'YLim',YLim);
+            XLim = get(gca,'XLim');
+            set(gca,'XLim',XLim);
+            
+            % Add title in figure
+            XLim = get(gca,'XLim');
+            YLim = get(gca,'YLim');
+            text(mean(XLim),max(YLim),sprintf('Relative change %s (time~%g)\nvs. %s baseline\nCORR=%1.3g (p=%1.3g)',PDreadout{k},TIMEPOINT_CHANGE,PDreadout{k},corr_v,corr_p),'Interpreter','none','HorizontalAlign','Center','VerticalAlign','top','FontSize',fontsize,'FontWeight','bold')
+            
+            grid on
+        end
+    end
+    if ~isempty(filename) && doPrintFigure==1,
+        printFigureSBPOP(gcf,filename)
+    end
+    
+    %% Absolute changes vs. COVARIATES
+    nrows = ceil(sqrt(length(PDreadout)));
+    ncols = ceil(length(PDreadout)/nrows);
+    
+    for k0=1:length(COVARIATES),
+        figure(1); clf;
+        for k=1:length(PDreadout),
+            datak = dataTIMEPOINT_CHANGE;
+            datak(isnan(datak.(PDreadout_BASE{k})),:) = [];
+            datak(isnan(datak.(PDreadout{k})),:) = [];
+            subplot(nrows,ncols,k);
+            CHANGE = datak.(PDreadout{k})-datak.(PDreadout_BASE{k});
+            plot(datak.(COVARIATES{k0}),CHANGE,'.','MarkerSize',20)
+            
+            XX = [datak.(COVARIATES{k0}) CHANGE];
+            ixnan = find(isnan(XX(:,1)));
+            XX(ixnan,:) = [];
+            ixnan = find(isnan(XX(:,2)));
+            XX(ixnan,:) = [];
+            
+            [corr_v,corr_p] = corr(XX(:,1),XX(:,2));
+            
+            xlabel(COVARIATES{k0},'FontSize',fontsize,'Interpreter','none')
+            ylabel(sprintf('Absolute change',PDreadout{k},TIMEPOINT_CHANGE),'FontSize',fontsize,'Interpreter','none');
+            
+            YLim = get(gca,'YLim');
+            set(gca,'YLim',YLim);
+            XLim = get(gca,'XLim');
+            set(gca,'XLim',XLim);
+            
+            % Add title in figure
+            XLim = get(gca,'XLim');
+            YLim = get(gca,'YLim');
+            text(mean(XLim),max(YLim),sprintf('Absolute change %s (time~%g)\nvs. %s\nCORR=%1.3g (p=%1.3g)',PDreadout{k},TIMEPOINT_CHANGE,COVARIATES{k0},corr_v,corr_p),'Interpreter','none','HorizontalAlign','Center','VerticalAlign','top','FontSize',fontsize,'FontWeight','bold')
+            
+            grid on
+        end
+        if ~isempty(filename),
+            printFigureSBPOP(gcf,filename)
+        end
+    end
+    
+    %% Relative changes vs. COVARIATES
+    % If baseline not 0
+    nrows = ceil(sqrt(length(PDreadout)));
+    ncols = ceil(length(PDreadout)/nrows);
+    
+    for k0=1:length(COVARIATES),
+        figure(1); clf;
+        doPrintFigure = 0;
+
+        for k=1:length(PDreadout),
+            datak = dataTIMEPOINT_CHANGE;
+            datak(isnan(datak.(PDreadout_BASE{k})),:) = [];
+            datak(isnan(datak.(PDreadout{k})),:) = [];
+
+            if datak.(PDreadout_BASE{k})(1) ~= 0,
+                doPrintFigure = 1;
+
+                subplot(nrows,ncols,k);
+                CHANGE = 100*(datak.(PDreadout{k})-datak.(PDreadout_BASE{k}))./datak.(PDreadout_BASE{k});
+                plot(datak.(COVARIATES{k0}),CHANGE,'.','MarkerSize',20)
+                
+                XX = [datak.(COVARIATES{k0}) CHANGE];
+                XX(find(isnan(XX(:,1))),:) = [];
+                XX(find(isinf(XX(:,1))),:) = [];
+                XX(find(isnan(XX(:,2))),:) = [];
+                XX(find(isinf(XX(:,2))),:) = [];
+                [corr_v,corr_p] = corr(XX(:,1),XX(:,2));
+                
+                xlabel(COVARIATES{k0},'FontSize',fontsize,'Interpreter','none')
+                ylabel(sprintf('Relative change',PDreadout{k},TIMEPOINT_CHANGE),'FontSize',fontsize,'Interpreter','none');
+                
+                YLim = get(gca,'YLim');
+                set(gca,'YLim',YLim);
+                XLim = get(gca,'XLim');
+                set(gca,'XLim',XLim);
+                
+                % Add title in figure
+                XLim = get(gca,'XLim');
+                YLim = get(gca,'YLim');
+                text(mean(XLim),max(YLim),sprintf('Relative change %s (time~%g)\nvs. %s\nCORR=%1.3g (p=%1.3g)',PDreadout{k},TIMEPOINT_CHANGE,COVARIATES{k0},corr_v,corr_p),'Interpreter','none','HorizontalAlign','Center','VerticalAlign','top','FontSize',fontsize,'FontWeight','bold')
+                
+                grid on
+            end
+        end
+        if ~isempty(filename) && doPrintFigure==1,
+            printFigureSBPOP(gcf,filename)
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% ===Plot median absolute PD readouts ... one per figure all TRTs in same plot - WITHOUT errorbars
+% Stratify by covariates (median) and produce one plot left and one plot right
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine threshold value to separate the analysis with
+% Handle also categorical covariates (2 values ONLY)
+for kcov=1:length(COVARIATES),
+    allID = unique(datawide.ID);
+    covariate_all = [];
+    for kid=1:length(allID),
+        datak = datawide(datawide.ID==allID(kid),:);
+        covariate_all = [covariate_all datak.(COVARIATES{kcov})(1)];
+    end
+    % Check if more than one values
+    if length(unique(covariate_all)) > 2,
+        threshold = nanmedian(covariate_all);
+    else
+        threshold = nanmean(unique(covariate_all));
+    end
+    % Get below and above dataset
+    data_below = datawide(datawide.(COVARIATES{kcov})<=threshold,:);
+    data_above = datawide(datawide.(COVARIATES{kcov})>threshold,:);
+
+    MEDIANdata_all   = getMedianModelingDataStructSBPOP(datawide,PDreadout,'continuous');
+    MEDIANdata_below = getMedianModelingDataStructSBPOP(data_below,PDreadout,'continuous');
+    MEDIANdata_above = getMedianModelingDataStructSBPOP(data_above,PDreadout,'continuous');
+
+    % Determine min and max NT 
+    NT = [];
+    for k=1:length(MEDIANdata_all.NT),
+        NT = [NT; MEDIANdata_all.NT{k}];
+    end
+    minNT = min(NT);
+    maxNT = max(NT);
+    
+    % Determine min and max NT for each readout
+    minMaxDataNames = {};
+    for k=1:length(MEDIANdata_below.NAMES),
+        DATA = [];
+        for k2=1:length(MEDIANdata_below.DATA),
+            DATA = [DATA MEDIANdata_below.DATA{k2}(k,:)];
+        end
+        for k2=1:length(MEDIANdata_above.DATA),
+            DATA = [DATA MEDIANdata_above.DATA{k2}(k,:)];
+        end
+        minDATA = min(DATA);
+        maxDATA = max(DATA);
+        minMaxDataNames{k} = [minDATA maxDATA];
+    end
+
+    % Plot for all NAMES and for each covariate one figure with 2 panels
+    for k=1:length(MEDIANdata_below.NAMES),
+        % get minDATA and maxDATA
+        minDATA = minMaxDataNames{k}(1);
+        maxDATA = minMaxDataNames{k}(2);
+        
+        % Open figure
+        figure(1); clf;
+        
+        % Plot data below
+        subplot(1,2,1);
+        legendText = {};
+        for kTRT=1:length(MEDIANdata_below.TRT),
+            plot(MEDIANdata_below.NT{kTRT},MEDIANdata_below.DATA{kTRT}(k,:),'.-','Color',colors(kTRT,:),'LineWidth',3,'MarkerSize',20); hold on
+            legendText{kTRT} = sprintf('TRT: %d',MEDIANdata_below.TRT(kTRT));
+        end
+        title(sprintf('Stratified Median %s (absolute)\n(%s<=%g)',MEDIANdata_below.NAMES{k},COVARIATES{kcov},threshold),'FontSize',fontsize+2,'Interpreter','none');
+        xlabel('Nominal Time','FontSize',fontsize,'Interpreter','none');
+        ylabel(sprintf('Absolute %s',MEDIANdata_below.NAMES{k}),'FontSize',fontsize,'Interpreter','none');
+        set(gca,'FontSize',fontsize-2);
+        grid on;
+        set(gca,'XLim',[minNT maxNT]);
+        set(gca,'YLim',[minDATA maxDATA]);
+        h = legend(legendText,'Location','NorthEast');
+        set(h,'FontSize',fontsize);
+        
+        % Plot data above
+        subplot(1,2,2);
+        legendText = {};
+        for kTRT=1:length(MEDIANdata_above.TRT),
+            plot(MEDIANdata_above.NT{kTRT},MEDIANdata_above.DATA{kTRT}(k,:),'.-','Color',colors(kTRT,:),'LineWidth',3,'MarkerSize',20); hold on
+            legendText{kTRT} = sprintf('TRT: %d',MEDIANdata_above.TRT(kTRT));
+        end
+        title(sprintf('Stratified Median %s (absolute)\n(%s>%g)',MEDIANdata_above.NAMES{k},COVARIATES{kcov},threshold),'FontSize',fontsize+2,'Interpreter','none');
+        xlabel('Nominal Time','FontSize',fontsize,'Interpreter','none');
+        ylabel(sprintf('Absolute %s',MEDIANdata_above.NAMES{k}),'FontSize',fontsize,'Interpreter','none');
+        set(gca,'FontSize',fontsize-2);
+        grid on;
+        set(gca,'XLim',[minNT maxNT]);
+        set(gca,'YLim',[minDATA maxDATA]);
+        h = legend(legendText,'Location','NorthEast'); 
+        set(h,'FontSize',fontsize);
+
+        if ~isempty(filename),
+            printFigureSBPOP(gcf,filename)
+        end    
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% ===Plot median relative PD readouts ... one per figure all TRTs in same plot - WITHOUT errorbars
+% Stratify by covariates (median) and produce one plot left and one plot right
+% Only plot if baseline not 0
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine threshold value to separate the analysis with
+% Handle also categorical covariates (2 values ONLY)
+for kcov=1:length(COVARIATES),
+    allID = unique(datawide.ID);
+    covariate_all = [];
+    for kid=1:length(allID),
+        datak = datawide(datawide.ID==allID(kid),:);
+        covariate_all = [covariate_all datak.(COVARIATES{kcov})(1)];
+    end
+    % Check if more than one values
+    if length(unique(covariate_all)) > 2,
+        threshold = nanmedian(covariate_all);
+    else
+        threshold = nanmean(unique(covariate_all));
+    end
+    
+    % Manipulate the data to become relative values
+    dataPD = datawide;
+    % Remove NaN things
+    for k=1:length(PDreadout),
+        dataPD(isnan(dataPD.(PDreadout{k})),:) = [];
+        dataPD(isnan(dataPD.(PDreadout_BASE{k})),:) = [];
+        dataPD(isnan(dataPD.NOMINAL_TIME),:) = [];
+    end
+    % Determine relative values to baseline - in %
+    for k=1:length(PDreadout),
+        dataPD.(PDreadout{k}) = 100*(dataPD.(PDreadout{k})-dataPD.(PDreadout_BASE{k}))./dataPD.(PDreadout_BASE{k});
+    end
+    
+    % Get below and above dataset
+    data_below = dataPD(dataPD.(COVARIATES{kcov})<=threshold,:);
+    data_above = dataPD(dataPD.(COVARIATES{kcov})>threshold,:);
+
+    MEDIANdata_all   = getMedianModelingDataStructSBPOP(dataPD,PDreadout,'continuous');
+    MEDIANdata_below = getMedianModelingDataStructSBPOP(data_below,PDreadout,'continuous');
+    MEDIANdata_above = getMedianModelingDataStructSBPOP(data_above,PDreadout,'continuous');
+
+    % Determine min and max NT 
+    NT = [];
+    for k=1:length(MEDIANdata_all.NT),
+        NT = [NT; MEDIANdata_all.NT{k}];
+    end
+    minNT = min(NT);
+    maxNT = max(NT);
+    
+    % Determine min and max NT for each readout
+    minMaxDataNames = {};
+    for k=1:length(MEDIANdata_below.NAMES),
+        DATA = [];
+        for k2=1:length(MEDIANdata_below.DATA),
+            DATA = [DATA MEDIANdata_below.DATA{k2}(k,:)];
+        end
+        for k2=1:length(MEDIANdata_above.DATA),
+            DATA = [DATA MEDIANdata_above.DATA{k2}(k,:)];
+        end
+        minDATA = min(DATA);
+        maxDATA = max(DATA);
+        minMaxDataNames{k} = [minDATA maxDATA];
+    end
+
+    % Plot for all NAMES and for each covariate one figure with 2 panels
+    for k=1:length(MEDIANdata_below.NAMES),
+        % get minDATA and maxDATA
+        minDATA = minMaxDataNames{k}(1);
+        maxDATA = minMaxDataNames{k}(2);
+        
+        % Open figure
+        figure(1); clf;
+        
+        % Plot data below
+        subplot(1,2,1);
+        legendText = {};
+        for kTRT=1:length(MEDIANdata_below.TRT),
+            plot(MEDIANdata_below.NT{kTRT},MEDIANdata_below.DATA{kTRT}(k,:),'.-','Color',colors(kTRT,:),'LineWidth',3,'MarkerSize',20); hold on
+            legendText{kTRT} = sprintf('TRT: %d',MEDIANdata_below.TRT(kTRT));
+        end
+        title(sprintf('Stratified Median %s (relative)\n(%s<=%g)',MEDIANdata_below.NAMES{k},COVARIATES{kcov},threshold),'FontSize',fontsize+2,'Interpreter','none');
+        xlabel('Nominal Time','FontSize',fontsize,'Interpreter','none');
+        ylabel(sprintf('Relative change %s [%%baseline]',MEDIANdata_below.NAMES{k}),'FontSize',fontsize,'Interpreter','none');
+        set(gca,'FontSize',fontsize-2);
+        grid on;
+        if ~isinf(minDATA) && ~isinf(maxDATA) && ~isnan(minDATA) && ~isnan(maxDATA),
+            set(gca,'XLim',[minNT maxNT]);
+            set(gca,'YLim',[minDATA maxDATA]);
+        end
+        h = legend(legendText,'Location','NorthEast');
+        set(h,'FontSize',fontsize);
+        
+        % Plot data above
+        subplot(1,2,2);
+        legendText = {};
+        for kTRT=1:length(MEDIANdata_above.TRT),
+            plot(MEDIANdata_above.NT{kTRT},MEDIANdata_above.DATA{kTRT}(k,:),'.-','Color',colors(kTRT,:),'LineWidth',3,'MarkerSize',20); hold on
+            legendText{kTRT} = sprintf('TRT: %d',MEDIANdata_above.TRT(kTRT));
+        end
+        title(sprintf('Stratified Median %s (relative)\n(%s>%g)',MEDIANdata_above.NAMES{k},COVARIATES{kcov},threshold),'FontSize',fontsize+2,'Interpreter','none');
+        xlabel('Nominal Time','FontSize',fontsize,'Interpreter','none');
+        ylabel(sprintf('Relative change %s [%%baseline]',MEDIANdata_above.NAMES{k}),'FontSize',fontsize,'Interpreter','none');
+        set(gca,'FontSize',fontsize-2);
+        grid on;
+        doPrintFigure = 0;
+        if ~isinf(minDATA) && ~isinf(maxDATA) && ~isnan(minDATA) && ~isnan(maxDATA),
+            set(gca,'XLim',[minNT maxNT]);
+            set(gca,'YLim',[minDATA maxDATA]);
+            doPrintFigure = 1;
+        end
+        h = legend(legendText,'Location','NorthEast'); 
+        set(h,'FontSize',fontsize);
+
+        if ~isempty(filename) && doPrintFigure==1,
+            printFigureSBPOP(gcf,filename)
+        end    
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% ===Median curves (ABSOLUTE change) over nominal time for each TRT group stratified by covariates (>median, <=median)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for kcov=1:length(COVARIATES),
+    % Determine threshold value to separate the analysis with
+    % Handle also categorical covariates (2 values ONLY)
+    allID = unique(datawide.ID);
+    covariate_all = [];
+    for kid=1:length(allID),
+        datak = datawide(datawide.ID==allID(kid),:);
+        covariate_all = [covariate_all datak.(COVARIATES{kcov})(1)];
+    end
+    % Check if more than one values
+    if length(unique(covariate_all)) > 2,
+        threshold = nanmedian(covariate_all);
+    else
+        threshold = nanmean(unique(covariate_all));
+    end
+    % Generate the two RR datasets (below and above threshold)
+    RR_dummy = getMedianModelingDataStructSBPOP(datawide,NAMES,'continuous');
+    RR_below = getMedianModelingDataStructSBPOP(datawide(datawide.(COVARIATES{kcov})<=threshold,:),NAMES,'continuous');
+    RR_above = getMedianModelingDataStructSBPOP(datawide(datawide.(COVARIATES{kcov})>threshold,:),NAMES,'continuous');
+    
+    % Determine min and max NT
+    NT = [];
+    DATA = [];
+    for k=1:length(RR_below.NT),
+        NT = [NT; RR_below.NT{k}];
+        for k2=1:length(RR_above.NAMES),
+            DATA = [DATA; RR_below.DATA{k}(k2,:)'];
+        end
+    end
+    for k=1:length(RR_above.NT),
+        NT = [NT; RR_above.NT{k}];
+        for k2=1:length(RR_above.NAMES),
+            DATA = [DATA; RR_above.DATA{k}(k2,:)'];
+        end
+    end
+    minNT = min(NT);
+    maxNT = max(NT);
+    minDATA = min(DATA);
+    maxDATA = max(DATA);
+    
+    % Plot results
+    figure(1); clf;
+    
+    % All possible TRT groups
+    allTRT = unique(datawide.TRT);
+    
+    % Get nrows and ncols
+    nrows = ceil(sqrt(length(RR_dummy.TRT)));
+    ncols = ceil(length(RR_dummy.TRT)/nrows);
+
+    % Save maximum subject info
+    N_TRT_below = zeros(1,length(allTRT));
+    N_TRT_above = zeros(1,length(allTRT));
+    
+    % Plot RR_below first
+    for k=1:length(RR_below.TRT),
+        % Determine the index of the subplot
+        ix = find(allTRT==RR_below.TRT(k));
+        subplot(nrows,ncols,ix);
+        % Plot the data
+        for k3=1:length(RR_below.NAMES),
+            plot(RR_below.NT{k},RR_below.DATA{k}(k3,:),'o-','Color',colors(k3,:),'LineWidth',2,'MarkerSize',12); hold on
+        end
+        % Save the number of subjects
+        N_TRT_below(ix) = RR_below.N(k);
+    end
+    
+    % Plot RR_above then
+    for k=1:length(RR_above.TRT),
+        % Determine the index of the subplot
+        ix = find(allTRT==RR_above.TRT(k));
+        subplot(nrows,ncols,ix);
+        % Plot the data
+        for k3=1:length(RR_above.NAMES),
+            plot(RR_above.NT{k},RR_above.DATA{k}(k3,:),'x--','Color',0.75*colors(k3,:),'LineWidth',2,'MarkerSize',12); hold on
+        end
+        % Save the number of subjects
+        N_TRT_above(ix) = RR_above.N(k);        
+    end
+    
+    for k=1:length(allTRT),
+        subplot(nrows,ncols,k);
+        
+        % axes
+        set(gca,'XLim',[minNT maxNT]);
+        set(gca,'YLim',[minDATA maxDATA]);
+
+        grid on;
+        
+        % If in last row then add xlabel
+        if k>length(allTRT)-ncols,
+            xlabel('Nominal Time','FontSize',fontsize,'Interpreter','none');
+        end
+        % If in first column add ylabel
+        if mod(k+ncols,ncols*2) == 1 || length(allTRT)==1,
+            ylabel(sprintf('Absolute values'),'FontSize',fontsize,'Interpreter','none');
+        end
+        
+        % Add title in figure
+        XLim = get(gca,'XLim');
+        YLim = get(gca,'YLim');
+        text(mean(XLim),max(YLim),sprintf('TRT: %d (stratified by %s)\nN(<=%g): %d, N(>%g): %d',allTRT(k),COVARIATES{kcov},threshold,N_TRT_below(k),threshold,N_TRT_above(k)),'HorizontalAlign','Center','VerticalAlign','top','FontSize',fontsize,'FontWeight','bold','Interpreter','none')
+        
+        % legend
+        if k==1,
+            legendText = {};
+            for k3=1:length(PDreadout),
+                legendText{end+1} = sprintf('%s (%s<=%g)',PDreadout{k3},COVARIATES{kcov},threshold);
+            end
+            for k3=1:length(PDreadout),
+                legendText{end+1} = sprintf('%s (%s>%g)',PDreadout{k3},COVARIATES{kcov},threshold);
+            end
+            legend(legendText,'Location','Best','Interpreter','none');
+        end
+        
+        % Line at 0
+        plot(XLim,[0 0],'k--');
+        
+    end
+    if ~isempty(filename),
+        printFigureSBPOP(gcf,filename)
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% ===Median curves (relative change from first measurement) over nominal time for each TRT group stratified by covariates (>median, <=median)
+% Only do this if baseline not 0
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for kcov=1:length(COVARIATES),
+    % Determine threshold value to separate the analysis with
+    % Handle also categorical covariates (2 values ONLY)
+    allID = unique(datawide.ID);
+    covariate_all = [];
+    for kid=1:length(allID),
+        datak = datawide(datawide.ID==allID(kid),:);
+        covariate_all = [covariate_all datak.(COVARIATES{kcov})(1)];
+    end
+    % Check if more than one values
+    if length(unique(covariate_all)) > 2,
+        threshold = nanmedian(covariate_all);
+    else
+        threshold = nanmean(unique(covariate_all));
+    end
+    
+    % Create a datawide dataset with values as rel changes from baseline
+    % and use this in the plotting ...
+    datawide_rel = datawide;
+    for kx=1:length(NAMES),
+        datawide_rel.(NAMES{kx}) = 100*( datawide_rel.(NAMES{kx}) - datawide_rel.(BASELINENAMES{kx}) ) ./ datawide_rel.(BASELINENAMES{kx});
+    end
+
+    % Generate the two RR datasets (below and above threshold)
+    RR_dummy = getMedianModelingDataStructSBPOP(datawide_rel,NAMES,'continuous');
+    RR_below = getMedianModelingDataStructSBPOP(datawide_rel(datawide_rel.(COVARIATES{kcov})<=threshold,:),NAMES,'continuous');
+    RR_above = getMedianModelingDataStructSBPOP(datawide_rel(datawide_rel.(COVARIATES{kcov})>threshold,:),NAMES,'continuous');
+    
+    % Determine min and max NT
+    NT = [];
+    DATA = [];
+    for k=1:length(RR_below.NT),
+        NT = [NT; RR_below.NT{k}];
+        for k2=1:length(RR_above.NAMES),
+            DATA = [DATA; RR_below.DATA{k}(k2,:)'];
+        end
+    end
+    for k=1:length(RR_above.NT),
+        NT = [NT; RR_above.NT{k}];
+        for k2=1:length(RR_above.NAMES),
+            DATA = [DATA; RR_above.DATA{k}(k2,:)'];
+        end
+    end
+    minNT = min(NT);
+    maxNT = max(NT);
+    minDATA = min(DATA);
+    maxDATA = max(DATA);
+    
+    % Plot results
+    doPrintFigure = 0;
+    figure(1); clf;
+    
+    % All possible TRT groups
+    allTRT = unique(datawide_rel.TRT);
+    
+    % Get nrows and ncols
+    nrows = ceil(sqrt(length(RR_dummy.TRT)));
+    ncols = ceil(length(RR_dummy.TRT)/nrows);
+
+    % Save maximum subject info
+    N_TRT_below = zeros(1,length(allTRT));
+    N_TRT_above = zeros(1,length(allTRT));
+    
+    % Plot RR_below first
+    for k=1:length(RR_below.TRT),
+        % Determine the index of the subplot
+        ix = find(allTRT==RR_below.TRT(k));
+        
+        % Plot the data
+        for k3=1:length(RR_below.NAMES),
+            if ~isinf(RR_below.DATA{k}(k3,1)),
+                doPrintFigure = 1;
+            end
+            subplot(nrows,ncols,ix);
+            plot(RR_below.NT{k},RR_below.DATA{k}(k3,:),'o-','Color',colors(k3,:),'LineWidth',2,'MarkerSize',12); hold on
+        end
+        % Save the number of subjects
+        N_TRT_below(ix) = RR_below.N(k);
+    end
+    
+    % Plot RR_above then
+    for k=1:length(RR_above.TRT),
+        % Determine the index of the subplot
+        ix = find(allTRT==RR_above.TRT(k));
+        subplot(nrows,ncols,ix);
+        % Plot the data
+        for k3=1:length(RR_above.NAMES),
+            plot(RR_above.NT{k},RR_above.DATA{k}(k3,:),'x--','Color',0.75*colors(k3,:),'LineWidth',2,'MarkerSize',12); hold on
+        end
+        % Save the number of subjects
+        N_TRT_above(ix) = RR_above.N(k);        
+    end
+    
+    for k=1:length(allTRT),
+        subplot(nrows,ncols,k);
+        
+        % axes
+        set(gca,'XLim',[minNT maxNT]);
+        if ~isinf(minDATA) && ~isinf(maxDATA) && ~isnan(minDATA) && ~isnan(maxDATA),
+            set(gca,'YLim',[minDATA maxDATA]);
+        end
+
+        grid on;
+        
+        % If in last row then add xlabel
+        if k>length(allTRT)-ncols,
+            xlabel('Nominal Time','FontSize',fontsize,'Interpreter','none');
+        end
+        % If in first column add ylabel
+        if mod(k+ncols,ncols*2) == 1 || length(allTRT)==1,
+            ylabel(sprintf('Relative change [%%baseline]'),'FontSize',fontsize,'Interpreter','none');
+        end
+        
+        % Add title in figure
+        XLim = get(gca,'XLim');
+        YLim = get(gca,'YLim');
+        text(mean(XLim),max(YLim),sprintf('TRT: %d (stratified by %s)\nN(<=%g): %d, N(>%g): %d',allTRT(k),COVARIATES{kcov},threshold,N_TRT_below(k),threshold,N_TRT_above(k)),'HorizontalAlign','Center','VerticalAlign','top','FontSize',fontsize,'FontWeight','bold','Interpreter','none')
+        
+        % legend
+        if k==1,
+            legendText = {};
+            for k3=1:length(PDreadout),
+                legendText{end+1} = sprintf('%s (%s<=%g)',PDreadout{k3},COVARIATES{kcov},threshold);
+            end
+            for k3=1:length(PDreadout),
+                legendText{end+1} = sprintf('%s (%s>%g)',PDreadout{k3},COVARIATES{kcov},threshold);
+            end
+            legend(legendText,'Location','Best','Interpreter','none');
+        end
+        
+        % Line at 0
+        plot(XLim,[0 0],'k--');
+        
+    end
+    if ~isempty(filename) && doPrintFigure==1,
+        printFigureSBPOP(gcf,filename)
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% ===Convert output to PDF
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(filename),
+    close all
+    convert2pdfSBPOP(filename);
+end
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/02_DataExploration/SBPOPgraphicalExplorationResponderRatePD.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/02_DataExploration/SBPOPgraphicalExplorationResponderRatePD.m
new file mode 100644
index 0000000000000000000000000000000000000000..a6dbc3ed9c35dd599f9ea55362435549aca69020
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/02_DataExploration/SBPOPgraphicalExplorationResponderRatePD.m
@@ -0,0 +1,576 @@
+function [] = SBPOPgraphicalExplorationResponderRatePD(data,NAMES,COVARIATES,options)
+% Function for some general exploration of several continuous PD readouts.
+%
+% Several plots are generated in a PDF:
+%
+% * Nominal time vs. actual time
+% * Rate of missing observations over time
+% * More detailed assessment of individual missing observations and
+%   corresponding response levels
+% * Responder rates over nominal time for each TRT group
+% * Responder rates over nominal time for each TRT group stratified by
+%   covariates (>median, <=median)
+% 
+% IMPORTANT: Records with NaN values for NOMINAL_TIME are removed from the analysis
+%
+% Assumptions:
+% 
+% * The dataset is in the generalized data format and augmented at least
+%   with covariate columns and ID column
+% * For each continuous readout of interest, a corresponding baseline
+%   column should be available
+%
+% USAGE:
+% ======
+% SBPOPgraphicalExplorationContinuousPD(data,NAMES,BASELINENAMES,COVARIATES,TIMEPOINT_CHANGE,PD_IMPROVEMENT)
+% SBPOPgraphicalExplorationContinuousPD(data,NAMES,BASELINENAMES,COVARIATES,TIMEPOINT_CHANGE,PD_IMPROVEMENT,options)
+%
+% data:                 dataset in augemented generalized dataset format    
+% NAMES:                cell-array with names of PD readouts to consider
+%                       (names based on NAME column in dataset)
+%                       Note that the readouts should be categorial (0 o 1
+%                       and correspond to some response no or yes). If
+%                       several are available then ideally they should be
+%                       ordered by level of response ... for example
+%                       PASI50, PASI75. Should not have more than 2
+%                       elements. PASIxy could be handled by the continous
+%                       function ... here this function is more for
+%                       categoricla readouts without simple link to
+%                       continuous (e.g. ASAS20 and ASAS40).
+% COVARIATES:           cell-array with covariates to consider (columns in
+%                       augmented dataset)
+% options:              matlab structure with additional optional
+%                       information:
+%
+%       options.filename:  String with path and filename for the output
+%                          PDF. Default: 'PD_exploration_output'
+%       options.fontsize:  Fontsize for the annotation of the plots
+%                          (default: 12)
+
+% Information:
+% ============
+% Copyright (C) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%% ==Simple checks
+if length(NAMES)>2,
+    error('NAMES can take at maximum 2 elements.');
+end
+
+%% ===Handle variable input arguments
+filename        = 'PD_exploration_output';
+fontsize        = 12;
+if nargin > 3,
+    try, filename=options.filename;             catch, end
+    try, fontsize=options.fontsize;             catch, end
+end
+
+%% Rename inputs
+PDreadout       = NAMES;
+
+%% ===Prepare data
+% We keep only the most important columns
+% STYSID1A, ID, TIME, NOMINAL_TIME, NAME, DV, TRT, the passed BASELINENAMES and COVARIATES
+%
+% Furthermore, only the TYPES are kept that correspond to the NAMES
+
+%% Remove all NAMEs from the data that are not in NAMES
+allNAMEs = unique(data.NAME);
+for k=1:length(allNAMEs),
+    
+    if ~ismember(allNAMEs{k},NAMES),
+        data(strcmp(data.NAME,allNAMEs{k}),:) = [];
+    end
+end
+
+%% Copy standard columns
+data2                   = dataset();
+data2.STYSID1A          = data.STYSID1A;
+data2.ID                = data.ID;
+data2.TIME              = data.TIME;
+data2.NOMINAL_TIME      = data.NOMINAL_TIME;
+data2.NAME              = data.NAME;
+data2.DV                = data.DV;
+data2.TRT               = data.TRT;
+% data2.STUDY             = data.STUDY; % Not needed
+
+%% Copy COVARIATES
+for k=1:length(COVARIATES),
+    data2.(COVARIATES{k}) = data.(COVARIATES{k});
+end
+    
+%% Check if NOMINAL_TIME contains NaN .. if yes then big warning
+if ~isempty(find(isnan(data2.NOMINAL_TIME))),
+    disp('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
+    disp('The dataset contains NaN in NOMINAL_TIME!!! This should NOT happen.');
+    disp('Please check with the programmer ...');
+    disp('For the purpose of this analysis the records with NOMINAL_TIME NaN will be removed.');
+    disp('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
+end 
+data2(isnan(data2.NOMINAL_TIME),:) = [];
+
+%% Prepare wide dataset
+datawide = SBPOPdataset2wide(data2,'ID','NOMINAL_TIME','NAME','DV');
+
+%% ===Get colors
+colors = getcolorsSBPOP();
+
+%% ===Prepare output folder and file
+if ~isempty(filename),
+    [folder,file] = fileparts(filename);
+    if ~isempty(folder),
+        mkdir(folder)
+    end
+    startNewPrintFigureSBPOP(filename); 
+end
+
+%% ===Plot TIME vs. NOMINAL_TIME
+% Checking if TIME and NOMINAL_TIME match reasonably
+figure(1); clf
+allTRT = unique(datawide.TRT);
+legendText = {};
+for k=1:length(allTRT),  
+    datax = datawide(datawide.TRT==allTRT(k),:);
+    plot(datax.TIME,datax.NOMINAL_TIME,'.','MarkerSize',25,'Color',colors(k,:)); hold on
+    legendText{k} = sprintf('TRT: %d',allTRT(k));
+end
+grid on;
+xlabel('TIME','FontSize',14,'Interpreter','none')
+ylabel('NOMINAL_TIME','FontSize',14,'Interpreter','none')
+title('Comparison between TIME and NOMINAL_TIME','FontSize',16,'Interpreter','none')
+set(gca,'FontSize',12)
+legend(legendText,'Location','Best')
+if ~isempty(filename),
+    printFigureSBPOP(gcf,filename)
+end
+
+%% === Assess missing observations per TRT for each PD readout
+
+% Get nrows and ncols
+nrows = ceil(sqrt(length(allTRT)));
+ncols = ceil(length(allTRT)/nrows);
+
+figure(1); clf;
+for k=1:length(PDreadout),
+    allTRT = unique(datawide.TRT);
+    for k2=1:length(allTRT),
+        datak = datawide(datawide.TRT==allTRT(k2),:);
+        % Determine max number of patients in TRT
+        N_TRT = length(unique(datak.ID));
+        % Determine number of patients at NT samples
+        N_TRT_NT = [];
+        allNT = unique(datak.NOMINAL_TIME);
+        for k3=1:length(allNT),
+            datak3 = datak(datak.NOMINAL_TIME==allNT(k3),:);
+            N_TRT_NT = [N_TRT_NT length(unique(datak3.ID))];
+        end
+        % Determine relative change
+        NmissingRel = -100*(N_TRT_NT-N_TRT)/N_TRT;
+    
+        % Plot
+        subplot(nrows,ncols,k2);
+        plot(allNT,NmissingRel,'Color',colors(k,:),'LineWidth',2); hold on
+        grid on
+        
+        % If in last row then add xlabel
+        if k2>length(allTRT)-ncols,
+            xlabel('Nominal Time','FontSize',fontsize,'Interpreter','none');
+        end
+        % If in first column add ylabel
+        if mod(k2+ncols,ncols*2) == 1 || length(allTRT)==1,
+            ylabel(sprintf('Missing observations [%%]'),'FontSize',fontsize,'Interpreter','none');
+        end
+        
+        axis([min(allNT) max(allNT) 0 max(max(NmissingRel),1)    ]);
+        
+        % Add title in figure
+        XLim = get(gca,'XLim');
+        YLim = get(gca,'YLim');
+        text(mean(XLim),max(YLim),sprintf('TRT: %d\nNmax=%d',allTRT(k2),N_TRT),'HorizontalAlign','Center','VerticalAlign','top','FontSize',fontsize,'FontWeight','bold')
+        
+    end
+end
+if ~isempty(filename),
+    printFigureSBPOP(gcf,filename)
+end
+
+%% Assess missing observations / drop outs more in details
+% Only plotted for the FIRST PDreadout! Otherwise to much info.
+% Please make sure the most important readout is used ...
+
+allTRT = unique(datawide.TRT);
+
+for k = 1:length(allTRT),
+    datak = datawide(datawide.TRT==allTRT(k),:);
+    
+    % Get nominal times for this TRT groups
+    NT_TRT = unique(datak.NOMINAL_TIME);
+    
+    % Determine missing IDs at each nominal time point
+    MISSING_OVER_TIME = {};
+    allID = unique(datak.ID);
+    for k2=1:length(NT_TRT),
+        datak2 = datak(datak.NOMINAL_TIME==NT_TRT(k2),:);
+        IDs_NT = unique(datak2.ID);
+        MISSING_OVER_TIME{k2} = setdiff(allID,IDs_NT);
+    end
+    
+    % Determine all IDs that are at least once missing
+    allIDmissing = [];
+    for k2=1:length(MISSING_OVER_TIME),
+        allIDmissing = [allIDmissing; MISSING_OVER_TIME{k2}];
+    end
+    allIDmissing = unique(allIDmissing);
+
+    % Determine if visit done or not
+    VISIT_DONE = zeros(length(allIDmissing),length(NT_TRT));
+    % Cycle through subjects
+    for k2=1:length(allIDmissing),
+        datak2 = datak(datak.ID==allIDmissing(k2),:);
+        % Cycle through time points (NT)
+        for k3=1:length(NT_TRT),
+            datakk3 = datak2(datak2.NOMINAL_TIME==NT_TRT(k3),:);
+            
+            if ~isempty(datakk3),
+                % Get all PD readouts - assume first is weaker than the
+                % next ... etc. and both are simply categorical!
+                PD_readout_value = [];
+                for k4=1:length(PDreadout),
+                    PD_readout_value(k4) = datakk3.(PDreadout{k4});
+                end
+                
+                % Check if at least on of the readout measured
+                if ~isempty(find(~isnan(PD_readout_value))),
+                    % Visit has certainly been done
+                    VISIT_DONE(k2,k3) = 1;
+                    
+                    % Check if first level achieved
+                    if length(PD_readout_value) == 1,
+                        if PD_readout_value,
+                            % Visit done and first level of response achieved
+                            VISIT_DONE(k2,k3) = 2;
+                        end
+                    elseif length(PD_readout_value) == 2,
+                        if ~isnan(PD_readout_value(1)),
+                            if PD_readout_value(1),
+                                % Visit done and first level of response achieved
+                                VISIT_DONE(k2,k3) = 2;
+                            end 
+                        end
+                        if ~isnan(PD_readout_value(2)),
+                            if PD_readout_value(2),
+                                % Visit done and first level of response achieved
+                                VISIT_DONE(k2,k3) = 3;
+                            end 
+                        end
+                    else
+                        error('NAMES should not have more than 2 elements.');
+                    end
+                end
+            end
+        end
+    end
+    Y = sortrows([allIDmissing sum(VISIT_DONE>=1,2) VISIT_DONE],2);
+    figure(1); clf
+    % plot for legend purposes
+    plot(0,-10,'rx','MarkerSize',20,'LineWidth',2); hold on;
+    plot(0,-10,'k.','MarkerSize',25);
+    plot(0,-10,'b.','MarkerSize',25);
+    plot(0,-10,'g.','MarkerSize',25);
+    
+    for k2=1:length(allIDmissing),
+        IDk = Y(k2,1);
+        datak = Y(k2,3:end);
+        TIMEk = NT_TRT(find(datak==0));
+        if ~isempty(TIMEk), plot(TIMEk,k2,'rx','MarkerSize',20,'LineWidth',2); hold on; end
+        TIMEk = NT_TRT(find(datak==1));
+        if ~isempty(TIMEk), plot(TIMEk,k2,'k.','MarkerSize',25); hold on; end
+        TIMEk = NT_TRT(find(datak==2));
+        if ~isempty(TIMEk), plot(TIMEk,k2,'b.','MarkerSize',25); hold on; end
+        TIMEk = NT_TRT(find(datak==3));
+        if ~isempty(TIMEk), plot(TIMEk,k2,'g.','MarkerSize',25); hold on; end
+    end
+    xlabel('Nominal Time','FontSize',14,'Interpreter','none');
+    set(gca,'YTick',[1:length(allIDmissing)]);
+    set(gca,'YTickLabel',Y(:,1));
+    set(gca,'FontSize',12);
+    grid on
+    title(sprintf('Missing observations assessment\nTRT: %d',allTRT(k)),'FontSize',16,'Interpreter','none')
+    
+    YLim = get(gca,'YLim');
+    if YLim(2)<0
+        YLim(2) = 1;
+    end
+    set(gca,'YLim',[0.5 YLim(2)+0.5])
+    
+    % Legend
+    legend({'Missed observation','Observation', PDreadout{:}},'Location','EastOutside')
+    
+    if ~isempty(filename),
+        printFigureSBPOP(gcf,filename)
+    end
+end    
+
+%% ===Responder rates - one figure per name - all TRT groups in one subplot - errorbars
+
+% Get responder rate information
+RRdata = getMedianModelingDataStructSBPOP(datawide,NAMES,'categorical');
+
+% Determine min and max NT
+NT = [];
+for k=1:length(RRdata.NT),
+    NT = [NT; RRdata.NT{k}];
+end
+minNT = min(NT);
+maxNT = max(NT);
+
+for k=1:length(RRdata.NAMES),
+    figure(1); clf;
+    
+    legendText = {};
+    for kTRT=1:length(RRdata.TRT),
+        plot(RRdata.NT{kTRT},RRdata.DATA{kTRT}(k,:),'.-','Color',colors(kTRT,:),'LineWidth',2); hold on
+        legendText{kTRT} = sprintf('TRT: %d',RRdata.TRT(kTRT));
+    end
+    
+    % error bars
+    for kTRT=1:length(RRdata.TRT),
+        errorbar(RRdata.NT{kTRT}',RRdata.DATA{kTRT}(k,:),RRdata.DATA_STDERR{kTRT}(k,:),'Color',colors(kTRT,:),'LineWidth',2); hold on
+    end
+    
+    title(RRdata.NAMES{k},'FontSize',fontsize+2,'Interpreter','none');
+    xlabel('Nominal Time','FontSize',fontsize,'Interpreter','none');
+    ylabel('Observed responder rates [%]','FontSize',fontsize,'Interpreter','none');
+    set(gca,'FontSize',fontsize-2);
+    grid on;
+    set(gca,'XLim',[minNT maxNT]);
+    h = legend(legendText,'Location','NorthWest');
+    if ~isempty(filename),
+        printFigureSBPOP(gcf,filename)
+    end    
+end
+
+%% ===Responder rates - one figure per name - all TRT groups in one subplot - NO errorbars
+
+% Get responder rate information
+RRdata = getMedianModelingDataStructSBPOP(datawide,NAMES,'categorical');
+
+% Determine min and max NT
+NT = [];
+for k=1:length(RRdata.NT),
+    NT = [NT; RRdata.NT{k}];
+end
+minNT = min(NT);
+maxNT = max(NT);
+
+for k=1:length(RRdata.NAMES),
+    figure(1); clf;
+    
+    legendText = {};
+    for kTRT=1:length(RRdata.TRT),
+        plot(RRdata.NT{kTRT},RRdata.DATA{kTRT}(k,:),'.-','Color',colors(kTRT,:),'LineWidth',2); hold on
+        legendText{kTRT} = sprintf('TRT: %d',RRdata.TRT(kTRT));
+    end
+    
+    title(RRdata.NAMES{k},'FontSize',fontsize+2,'Interpreter','none');
+    xlabel('Nominal Time','FontSize',fontsize,'Interpreter','none');
+    ylabel('Observed responder rates [%]','FontSize',fontsize,'Interpreter','none');
+    set(gca,'FontSize',fontsize-2);
+    grid on;
+    set(gca,'XLim',[minNT maxNT]);
+    h = legend(legendText,'Location','NorthWest');
+    if ~isempty(filename),
+        printFigureSBPOP(gcf,filename)
+    end    
+end
+
+%% ===Responder rates over nominal time for each TRT group
+
+%% Get responder rate information
+RRdata = getMedianModelingDataStructSBPOP(datawide,NAMES,'categorical');
+
+%% Plot the information
+figure(1); clf
+
+% Get nrows and ncols
+nrows = ceil(sqrt(length(RRdata.TRT)));
+ncols = ceil(length(RRdata.TRT)/nrows);
+
+% Determine min and max NT
+NT = [];
+for k=1:length(RRdata.NT),
+    NT = [NT; RRdata.NT{k}];
+end
+minNT = min(NT);
+maxNT = max(NT);
+
+% Determine min and max RR
+RR = [];
+for k=1:length(RRdata.DATA),
+    RR = [RR; RRdata.DATA{k}(:)];
+end
+minRR = min(RR);
+maxRR = max(RR);
+
+
+for k=1:length(RRdata.TRT),
+    subplot(nrows,ncols,k);
+    for k3=1:length(RRdata.NAMES),
+        plot(RRdata.NT{k},RRdata.DATA{k}(k3,:),'.-','Color',colors(k3,:),'LineWidth',2); hold on
+    end
+    for kt=1:length(RRdata.NT{k}),
+        text(RRdata.NT{k}(kt),mean(RRdata.DATA{k}(:,kt)),sprintf('N=%d',RRdata.N_NT{k}(kt)),'FontSize',fontsize)
+    end
+    grid on;
+    
+    % error bars
+    for k3=1:length(RRdata.NAMES),
+        errorbar(RRdata.NT{k}',RRdata.DATA{k}(k3,:),RRdata.DATA_STDERR{k}(k3,:),'Color',colors(k3,:),'LineWidth',2); hold on
+    end
+    
+    % axes
+    set(gca,'XLim',[minNT maxNT]);
+    set(gca,'YLim',[minRR maxRR+5]);
+
+    if k==1,
+        legend(PDreadout,'Location','Best');
+    end
+    
+    % If in last row then add xlabel
+    if k>length(allTRT)-ncols,
+        xlabel('Nominal Time','FontSize',fontsize,'Interpreter','none');
+    end
+    % If in first column add ylabel
+    if mod(k+ncols,ncols*2) == 1 || length(allTRT)==1,
+        ylabel(sprintf('Observed responder Rates [%%]'),'FontSize',fontsize,'Interpreter','none');
+    end
+    
+    % Add title in figure
+    XLim = get(gca,'XLim');
+    YLim = get(gca,'YLim');
+    text(mean(XLim),max(YLim),sprintf('TRT: %d',allTRT(k)),'HorizontalAlign','Center','VerticalAlign','top','FontSize',fontsize,'FontWeight','bold')
+end
+if ~isempty(filename),
+    printFigureSBPOP(gcf,filename)
+end
+
+
+%% ===Responder rates over nominal time for each TRT group stratified by covariates (>median, <=median)
+
+for kcov=1:length(COVARIATES),
+    % Determine threshold value to separate the analysis with
+    % Handle also categorical covariates (2 values ONLY)
+    allID = unique(datawide.ID);
+    covariate_all = [];
+    for kid=1:length(allID),
+        datak = datawide(datawide.ID==allID(kid),:);
+        covariate_all = [covariate_all datak.(COVARIATES{kcov})(1)];
+    end
+    % Check if more than one values
+    if length(unique(covariate_all)) > 2,
+        threshold = nanmedian(covariate_all);
+    else
+        threshold = nanmean(unique(covariate_all));
+    end
+    % Generate the two RR datasets (below and above threshold)
+    RR_below = getMedianModelingDataStructSBPOP(datawide(datawide.(COVARIATES{kcov})<=threshold,:),NAMES,'categorical');
+    RR_above = getMedianModelingDataStructSBPOP(datawide(datawide.(COVARIATES{kcov})>threshold,:),NAMES,'categorical');
+
+    % Plot results
+    figure(1); clf;
+    
+    % All possible TRT groups
+    allTRT = unique(datawide.TRT);
+    
+    % Get nrows and ncols
+    nrows = ceil(sqrt(length(RRdata.TRT)));
+    ncols = ceil(length(RRdata.TRT)/nrows);
+
+    % Save maximum subject info
+    N_TRT_below = zeros(1,length(allTRT));
+    N_TRT_above = zeros(1,length(allTRT));
+    
+    % Plot RR_below first
+    for k=1:length(RR_below.TRT),
+        % Determine the index of the subplot
+        ix = find(allTRT==RR_below.TRT(k));
+        subplot(nrows,ncols,ix);
+        % Plot the data
+        for k3=1:length(RR_below.NAMES),
+            plot(RR_below.NT{k},RR_below.DATA{k}(k3,:),'o-','Color',colors(k3,:),'LineWidth',2,'MarkerSize',12); hold on
+        end
+        % Save the number of subjects
+        N_TRT_below(ix) = RR_below.N(k);
+    end
+    
+    % Plot RR_above then
+    for k=1:length(RR_above.TRT),
+        % Determine the index of the subplot
+        ix = find(allTRT==RR_above.TRT(k));
+        subplot(nrows,ncols,ix);
+        % Plot the data
+        for k3=1:length(RR_above.NAMES),
+            plot(RR_above.NT{k},RR_above.DATA{k}(k3,:),'x--','Color',0.75*colors(k3,:),'LineWidth',2,'MarkerSize',12); hold on
+        end
+        % Save the number of subjects
+        N_TRT_above(ix) = RR_above.N(k);        
+    end
+    
+    for k=1:length(allTRT),
+        subplot(nrows,ncols,k);
+        
+        % axes
+        set(gca,'XLim',[minNT maxNT]);
+        set(gca,'YLim',[0 100]);
+
+        grid on;
+        
+        % If in last row then add xlabel
+        if k>length(allTRT)-ncols,
+            xlabel('Nominal Time','FontSize',fontsize,'Interpreter','none');
+        end
+        % If in first column add ylabel
+        if mod(k+ncols,ncols*2) == 1 || length(allTRT)==1,
+            ylabel(sprintf('Observed responder Rates [%%]'),'FontSize',fontsize,'Interpreter','none');
+        end
+        
+        % Add title in figure
+        XLim = get(gca,'XLim');
+        YLim = get(gca,'YLim');
+        text(mean(XLim),max(YLim),sprintf('TRT: %d (stratified by %s)\nN(<=%g): %d, N(>%g): %d',allTRT(k),COVARIATES{kcov},threshold,N_TRT_below(k),threshold,N_TRT_above(k)),'HorizontalAlign','Center','VerticalAlign','top','FontSize',fontsize,'FontWeight','bold')
+        
+        % legend
+        if k==1,
+            legendText = {};
+            for k3=1:length(PDreadout),
+                legendText{end+1} = sprintf('%s (%s<=%g)',PDreadout{k3},COVARIATES{kcov},threshold);
+            end
+            for k3=1:length(PDreadout),
+                legendText{end+1} = sprintf('%s (%s>%g)',PDreadout{k3},COVARIATES{kcov},threshold);
+            end
+            legend(legendText,'Location','Best');
+        end
+    end
+    if ~isempty(filename),
+        printFigureSBPOP(gcf,filename)
+    end
+end
+
+%% ===Convert output to PDF
+if ~isempty(filename),
+    close all
+    convert2pdfSBPOP(filename);
+end
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/03_DataCleaning/SBPOPcleanPopPDdata.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/03_DataCleaning/SBPOPcleanPopPDdata.m
new file mode 100644
index 0000000000000000000000000000000000000000..51840f65beb9631099ff7848fd625f924bcc26aa
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/03_DataCleaning/SBPOPcleanPopPDdata.m
@@ -0,0 +1,205 @@
+function [datanew] = SBPOPcleanPopPDdata(data,PD_NAME,removeSUBJECT,removeREC,Nobs,covNames,catNames,catImputationValues,options)
+% [DESCRIPTION]
+% This function is a wrapper for different cleaning functions. Calling 
+% - SBPOPcleanRemoveRecordsIDs
+% - SBPOPcleanRemoveFewObsSubjects
+% - SBPOPcleanImputeCovariates
+%
+% The data need to be provided, following the standard dataspec, defined in
+% the help to the function SBPOPcheckDataFormat, so please look there for
+% more information.   
+% 
+% [SYNTAX]
+% [datanew] = SBPOPcleanPopPDdata(data,PD_NAME,removeSUBJECT,removeREC,Nobs,covNames,catNames,catImputationValues)
+% [datanew] = SBPOPcleanPopPDdata(data,PD_NAME,removeSUBJECT,removeREC,Nobs,covNames,catNames,catImputationValues,options)
+%
+% [INPUT]
+% data:         MATLAB PKPD dataset in standard data spec format  
+% PD_NAME:      Name of the PD readout of interest in the dataset (NAME
+%               column)
+% removeSUBJECT:  Cell-matrix with 2 columns. First column contains the
+%                 STYSID1A unique identifiers of the subjects to be removed
+%                 from the dataset. The second column contains strings,
+%                 which define the reason why this subject is removed.
+% removeREC:    Cell-matrix with 2 columns. First column contains the indices
+%               of the records to be removed from the dataset. The second
+%               column contains strings, which define the reason why this
+%               record is removed.
+% Nobs:         All subjects from the dataset which do have <= Nobs
+%               observation records with MDV=0 are removed.
+% covNames:     Cell-array with names of continuous covariates
+% catNames:     Cell-array with names of categorical covariates
+% catImputationValues:     Vector with same length as catNames, specifying
+%               the imputation values for these categorical covariates (if
+%               needed)
+% options:      MATLAB structure with additional options
+%
+%               options.FLAG_LLOQ:   =0: remove BLLOQ, 
+%                                    =1: keep LLOQ data use CENS=1 and DV=LLOQ
+%                                    =2: keep LLOQ data, DV=LLOQ/2, CENS=0, remove all but first LLOQ in suite                                      
+%                                        data (default: 0)
+%               options.outputPath:  path where
+%                                    outputs are exported to. Default:
+%                                    '../Output/DataCleaning/';
+%
+% [OUTPUT]
+% datanew:      cleaned dataset 
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 9th May 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MODESIM, MATLAB R2009a
+%
+% [KEYWORDS]
+% MATLAB, SBPOP, dataexploration, datacleaning
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBPOPcheckDataFormat(data);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle options
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try outputPath              = [options.outputPath '/'];     catch, outputPath = '../Output/DataCleaning/';  end; %#ok<*CTCH>
+try FLAG_LLOQ               = options.FLAG_LLOQ;            catch, FLAG_LLOQ = 0;                           end; %#ok<*CTCH>
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create output folder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[p,f,e] = fileparts(outputPath);
+warning off
+try rmdir(p,'s'); catch, end; mkdir(p);
+warning on
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run SBPOPcleanRemoveRecordsSUBJECTs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+filename = [outputPath '01_Data_Cleaning_Manual.txt'];
+datanew = SBPOPcleanRemoveRecordsSUBJECTs(data,removeSUBJECT,removeREC,filename);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run SBPOPcleanRemoveFewObsSubjects
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+type = PD_NAME;
+filename = [outputPath '02_Data_Cleaning_Few_Observations.txt'];
+datanew = SBPOPcleanRemoveFewObsSubjects(datanew,Nobs,type,filename);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle LLOQ in the desired way (neglect ULOQ for now) - ONLY PK data!
+% FLAG_LLOQ = 0: remove LLOQ data
+% FLAG_LLOQ = 1: use CENS=1 and add LLOQ into DV
+% FLAG_LLOQ = 2: use CENS=0, remove all but first LLOQ value, set DV to LLOQ/2
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% Create a CENS column 
+datanew.CENS            = zeros(length(datanew),1);
+ixLLOQ                  = find(datanew.DV < datanew.LLOQ & strcmp(datanew.NAME,PD_NAME));
+datanew.CENS(ixLLOQ)    = 1;
+
+if FLAG_LLOQ==0,
+    % REMOVE all LLOQ PK data
+    % Get the BLOQ data
+    dataBLLOQ = datanew(datanew.CENS==1,:);
+    % Remove the BLOQ data
+    datanew(datanew.CENS==1,:) = [];
+    % Save the removed data in the output path
+    datafilenameBLLOQ = [outputPath '03_removed_BLLOQ_data.csv'];
+    SBPOPexportCSVdataset(dataBLLOQ,datafilenameBLLOQ);
+    disp('The following BLOQ data were removed:');
+    disp('=====================================');
+    dataBLLOQ
+elseif FLAG_LLOQ==1,
+    % Use CENS as in Monolix with LLOQ in DV
+    datanew.DV(ixLLOQ) = datanew.LLOQ(ixLLOQ);
+    disp('The BLOQ PK data were kept and the DV values were set to LLOQ, CENS=1');
+    disp('=====================================================================');
+elseif FLAG_LLOQ==2,
+    % Set DV for readout below LLOQ values to 0.5*LLOQ and remove subsequent ones
+    % A CENS column will be present in the dataset but not used (all 0)
+    % Find LLOQ PD values
+    % Cycle through each subject
+    allID = unique(datanew.ID);
+    dataX = dataset();
+    dataRemoved = dataset();
+    dataDVset   = dataset();
+    for k=1:length(allID),
+        datak       = datanew(datanew.ID==allID(k),:);
+        dataPD      = datak(strcmp(datanew.NAME,PD_NAME),:);
+        dataNOTPD   = datak(~strcmp(datanew.NAME,PD_NAME),:);
+        % Check if PD BLOQ available
+        ix_PD_LLOQ = find(dataPD.CENS);
+        if ~isempty(ix_PD_LLOQ),
+            dataPDold = dataPD;
+            % Set DV to half the LLOQ value
+            dataPD.DV(ix_PD_LLOQ) = 0.5*dataPD.LLOQ(ix_PD_LLOQ);
+            % See if consecutive readouts available - if yes then remove all subsequent ones
+            delta = [NaN; diff(ix_PD_LLOQ)];
+            ix_consequtive = ix_PD_LLOQ(find(delta==1));
+            % Save records to be removed
+            dataRemoved = [dataRemoved; dataPDold(ix_consequtive,:)];
+            % Save records for which DV set to LLOQ/2
+            dataDVset = [dataDVset; dataPDold(ix_PD_LLOQ(find(delta~=1)),:)];
+            
+            % Remove records
+            dataPD(ix_consequtive,:) = [];
+        end
+        % Combine
+        datak = [dataPD; dataNOTPD];
+        dataX = [dataX; datak];
+    end
+    % Sort
+    datanew = sortrows(dataX,{'ID','TIME','TYPE','SUBTYPE'});
+    % Reset CENS column to 0
+    datanew.CENS(1:end) = 0;
+    % Save the removed data in the output path
+    datafilenameBLLOQ_REMOVED = [outputPath '03_removed_consequtive_BLLOQ_data.csv'];
+    SBPOPexportCSVdataset(dataRemoved,datafilenameBLLOQ_REMOVED);
+    datafilenameBLLOQ_DVset = [outputPath '03_DVset_BLLOQ_data.csv'];
+    SBPOPexportCSVdataset(dataDVset,datafilenameBLLOQ_DVset);
+    disp('The following BLOQ PD data were removed:');
+    disp('========================================');
+    dataRemoved
+    disp('The following BLOQ PD data obtained DV=LLOQ/2:');
+    disp('==============================================');
+    dataDVset
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run SBPOPcleanImputeCovariates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+filename = [outputPath '04_Covariate_Imputation.txt'];
+datanew  = SBPOPcleanImputeCovariates(datanew,covNames,catNames,catImputationValues,filename);
+
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/04_DataConversion/SBPOPconvert2popPDparametersDatasetMONOLIX.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/04_DataConversion/SBPOPconvert2popPDparametersDatasetMONOLIX.m
new file mode 100644
index 0000000000000000000000000000000000000000..0a473850554972b99231fa778bb565a8c961edec
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/04_DataConversion/SBPOPconvert2popPDparametersDatasetMONOLIX.m
@@ -0,0 +1,263 @@
+function [dataheader_output] = SBPOPconvert2popPDparametersDatasetMONOLIX(model,dosing,pathNLMEproject,data,PD_NAME,covNames,catNames,regressionParameters,analysisDataset)
+% [DESCRIPTION]
+% This function converts the given dataset in "data" into a popPD dataset
+% where the individual PK parameters are given, to be used as regression
+% parameters.
+% The datapopPD dataset will contain a subset of the columns in the
+% original dataset, sufficient to perform a popPD analysis. 
+% Dose records (TYPE=0) are kept to be able to simulate the PK.
+%
+% 0 dose records are kept - this is the only difference to the NONMEM
+% version of this function.
+% 
+% The data need to be provided, following the standard dataspec, defined in
+% the help to the function SBPOPcheckDataFormat, so please look there for
+% more information.   
+%
+% Additional removals:
+% Since NONMEM crashes when dose records with AMT=0 are present in the
+% dataset, these are removed.
+%
+% [SYNTAX]
+% [dataheader_output] = SBPOPconvert2popPDparametersDataset(model,dosing,pathNLMEproject,data,PD_NAME,covNames,catNames,analysisDataset)
+%
+% [INPUT]
+% model:        SBmodel: PKPD model to be used for simulation / estimation
+%               - only used to check the parameters in the fit results. 
+% dosing:       SBPOPdosing scheme that will be used for simulation.
+% pathNLMEproject: Path to the NLME(NONMEM or MONOLIX) PK fit to get the
+%                                 individual parameters from 
+% data:         MATLAB PKPD dataset in standard data spec format  
+% PD_NAME:      The unique name (column NAME), specifying which
+%               PD readout is to be modeled and kept in the PD dataset
+%               Can be cell-array - with multiple PD readouts ... they will
+%               get sequential YTYPE values, starting from 1.
+% covNames:     Cell-array with names of continuous covariates
+% catNames:     Cell-array with names of categorical covariates
+% analysisDataset:    Filename, including path for saving the popPD dataset
+%                     as CSV file. 
+% regressionParameters: Cell-array with regression parameters to keep in
+%               the dataset.
+%
+% [OUTPUT]
+% dataheader_output:            Data header for Monolix or NONMEM fits
+%                               placebo models only will not contain
+%                               regression variables 
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 9th May 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MODESIM, MATLAB R2009a
+%
+% [KEYWORDS]
+% MATLAB, SBPOP, dataexploration, datacleaning
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+if ~iscell(regressionParameters),
+    regressionParameters = {regressionParameters};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get population parameters (for placebo subjects)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+param                   = SBPOPsampleNLMEfitParam(pathNLMEproject,0,0);
+ParameterNamesFIT       = param.parameterNames;
+PopParameterValues      = param.parameterValuesPopulation;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check that the parameters  in the fit result also are in the model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+moddos                  = mergemoddosSBPOP(model,dosing);
+paramModdos             = SBparameters(moddos);
+IXparametersNotInModel  = [];
+for k=1:length(ParameterNamesFIT),
+    ix = strmatchSB(ParameterNamesFIT{k},paramModdos,'exact');
+    if isempty(ix),
+        warning(sprintf('Parameter "%s" available in the fit results but not in the PK model. This parameter will be neglected.\n\tPlease make sure that this does make sense!',ParameterNamesFIT{k}));
+        IXparametersNotInModel(end+1) = k;
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get individual PK parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isMONOLIXfitSBPOP(pathNLMEproject),
+    indiv_param = parseMONOLIXindivparamSBPOP(pathNLMEproject,length(ParameterNamesFIT));
+elseif isNONMEMfitSBPOP(pathNLMEproject),
+    indiv_param = parseNONMEMindivparamSBPOP(pathNLMEproject,length(ParameterNamesFIT));
+else
+    error('Unknown project type.');
+end
+% Remove parameters that are not in the model
+indiv_param(:,IXparametersNotInModel+1) = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Remove parameters from the names and population things if needed (after having gotten the individual PK parameters)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ParameterNamesFIT(IXparametersNotInModel) = [];
+PopParameterValues(IXparametersNotInModel) = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Reorder ParameterNamesFIT and PopParameterValues according to their appearance in the model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ixuse = [];
+ixuse2 = [];
+for k=1:length(paramModdos),
+    ix = strmatchSB(paramModdos{k},ParameterNamesFIT,'exact');
+    if ~isempty(ix),
+        ixuse(end+1) = ix;
+        ixuse2(end+1) = strmatchSB(ParameterNamesFIT{ix},ParameterNamesFIT,'exact');
+    end
+end
+ParameterNamesFIT = ParameterNamesFIT(ixuse);
+PopParameterValues = PopParameterValues(ixuse2);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Remove all but dose and PD of interest records from the dataset
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~iscell(PD_NAME),
+    PD_NAME = {PD_NAME};
+end
+allNAME = unique(data.NAME);
+for k=1:length(allNAME),
+    ix = strmatchSB(allNAME{k},PD_NAME,'exact');
+    if isempty(ix),
+        data(data.TYPE~=0 & strcmp(data.NAME,allNAME{k}),:) = [];
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create dataset with PK parameters - for placebo subjects use population parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% Add population parameters for all
+dataPKparam = data;
+for k=1:length(ParameterNamesFIT),
+    dataPKparam.(ParameterNamesFIT{k}) = PopParameterValues(k)*ones(length(dataPKparam),1);
+end
+
+% Add individual parameters for subjects where estimates have been made
+allID = unique(dataPKparam.ID);
+dataPKparamFilled = dataset();
+for k=1:length(allID),
+    datak = dataPKparam(dataPKparam.ID==allID(k),:);
+    % Check if ID available in indiv_param
+    ix = find(indiv_param.ID==allID(k));
+    % If available then enter the values
+    if ~isempty(ix),
+        indiv_param_k = indiv_param(ix,2:end);
+        pnames = get(indiv_param_k,'VarNames');
+        for k2=1:length(pnames),
+            datak.(pnames{k2}) = indiv_param_k.(pnames{k2})(1)*ones(length(datak),1);
+        end
+    end
+    % Combine again
+    dataPKparamFilled = [dataPKparamFilled; datak];
+end
+dataPKparam = dataPKparamFilled;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add YTYPE column
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dataPKparam.YTYPE = NaN(length(dataPKparam),1);
+dataPKparam.YTYPE(dataPKparam.TYPE==0) = 0;         % Dose
+for k=1:length(PD_NAME),
+    dataPKparam.YTYPE(strcmp(data.NAME,PD_NAME{k})) = k;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define initial structure of popPD dataset
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+varNames = {'STUDY' 'ID' 'TIME' 'TIMEPOS' 'TIME_UNIT' 'TYPE' 'SUBTYPE' 'NAME' 'DV' 'UNIT' 'DV' 'MDV' 'EVID' 'CENS' 'AMT'  'ADM' 'RATE' 'DOSE' 'TRT' 'YTYPE'};
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add covariates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+varNames = [varNames covNames(:)' catNames(:)'];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Reorder regression parameters as in the model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+regressors = [ParameterNamesFIT(:)' regressionParameters];
+orderthing = [];
+for k=1:length(regressors)
+    ix = strmatchSB(regressors{k},paramModdos,'exact');
+    orderthing = [orderthing; ix k];
+end
+xxx = sortrows(orderthing,1);
+regressors = regressors(xxx(:,2));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add Regressor names
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+varNames = [varNames regressors]; 
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create popPK dataset in defined structure
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+datapopPD = dataset();
+for k=1:length(varNames),
+    datapopPD.(varNames{k}) = dataPKparam.(varNames{k});
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Generate MONOLIX or NONMEM header
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+regressionNames = [regressionParameters ParameterNamesFIT];
+if isMONOLIXfitSBPOP(pathNLMEproject),
+    dataheader_output = SBPOPgetMonolixDataHeader(datapopPD,covNames,catNames,regressionNames);
+else
+    dataheader_output = SBPOPgetNONMEMdataHeader(datapopPD,covNames,catNames,regressionNames);
+end    
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Export datasets
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[p,f,e] = fileparts(analysisDataset);
+filename = [p '/' f '.csv'];
+warning off
+mkdir(p);
+warning on
+% All data
+SBPOPexportCSVdataset(datapopPD,filename);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Load dataset as text,
+% exchange spaces to ":::" and save as text
+% Then NONMEM can handle chars in columns ... for UNIT, TIME_UNIT, NAME
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+content = fileread(filename);
+content = strrep(content,' ',':::');
+fid = fopen(filename,'w');
+fprintf(fid,'%s',content);
+fclose(fid);
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/04_DataConversion/SBPOPconvert2popPDparametersDatasetNONMEM.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/04_DataConversion/SBPOPconvert2popPDparametersDatasetNONMEM.m
new file mode 100644
index 0000000000000000000000000000000000000000..dc072eaf27276cb82b71fc279f187db64fdaa1ba
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPDtoolbox/04_DataConversion/SBPOPconvert2popPDparametersDatasetNONMEM.m
@@ -0,0 +1,251 @@
+function [dataheader_output] = SBPOPconvert2popPDparametersDatasetNONMEM(model,dosing,pathNLMEproject,data,PD_NAME,covNames,catNames,analysisDataset)
+% [DESCRIPTION]
+% This function converts the given dataset in "data" into a popPD dataset
+% where the individual PK parameters are given, to be used as regression
+% parameters.
+% The datapopPD dataset will contain a subset of the columns in the
+% original dataset, sufficient to perform a popPD analysis. 
+% Dose records (TYPE=0) are kept to be able to simulate the PK.
+% 
+% 0 dose records are removed - this is the only difference to the MONOLIX
+% version of this function.
+% 
+% The data need to be provided, following the standard dataspec, defined in
+% the help to the function SBPOPcheckDataFormat, so please look there for
+% more information.   
+%
+% Additional removals:
+% Since NONMEM crashes when dose records with AMT=0 are present in the
+% dataset, these are removed.
+%
+% [SYNTAX]
+% [dataheader_output] = SBPOPconvert2popPDparametersDataset(model,dosing,pathNLMEproject,data,PD_NAME,covNames,catNames,analysisDataset)
+%
+% [INPUT]
+% model:        SBmodel: PKPD model to be used for simulation / estimation
+%               - only used to check the parameters in the fit results. 
+% dosing:       SBPOPdosing scheme that will be used for simulation.
+% pathNLMEproject: Path to the NLME(NONMEM or MONOLIX) PK fit to get the
+%                                 individual parameters from 
+% data:         MATLAB PKPD dataset in standard data spec format  
+% PD_NAME:      The unique name (column NAME), specifying which
+%               PD readout is to be modeled and kept in the PD dataset
+%               Can be cell-array - with multiple PD readouts ... they will
+%               get sequential YTYPE values, starting from 1.
+% covNames:     Cell-array with names of continuous covariates
+% catNames:     Cell-array with names of categorical covariates
+% analysisDataset:    Filename, including path for saving the popPD dataset
+%                     as CSV file. 
+%
+% [OUTPUT]
+% dataheader_output:            Data header for Monolix or NONMEM fits
+%                               placebo models only will not contain
+%                               regression variables 
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 9th May 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MODESIM, MATLAB R2009a
+%
+% [KEYWORDS]
+% MATLAB, SBPOP, dataexploration, datacleaning
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get population parameters (for placebo subjects)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+param                   = SBPOPsampleNLMEfitParam(pathNLMEproject,0,0);
+ParameterNamesFIT       = param.parameterNames;
+PopParameterValues      = param.parameterValuesPopulation;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check that the parameters  in the fit result also are in the model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+moddos                  = mergemoddosSBPOP(model,dosing);
+paramModdos             = SBparameters(moddos);
+IXparametersNotInModel  = [];
+for k=1:length(ParameterNamesFIT),
+    ix = strmatchSB(ParameterNamesFIT{k},paramModdos,'exact');
+    if isempty(ix),
+        warning(sprintf('Parameter "%s" available in the fit results but not in the PK model. This parameter will be neglected.\n\tPlease make sure that this does make sense!',ParameterNamesFIT{k}));
+        IXparametersNotInModel(end+1) = k;
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get individual PK parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isMONOLIXfitSBPOP(pathNLMEproject),
+    indiv_param = parseMONOLIXindivparamSBPOP(pathNLMEproject,length(ParameterNamesFIT));
+elseif isNONMEMfitSBPOP(pathNLMEproject),
+    indiv_param = parseNONMEMindivparamSBPOP(pathNLMEproject,length(ParameterNamesFIT));
+else
+    error('Unknown project type.');
+end
+% Remove parameters that are not in the model
+indiv_param(:,IXparametersNotInModel+1) = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Remove parameters from the names and population things if needed (after having gotten the individual PK parameters)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ParameterNamesFIT(IXparametersNotInModel) = [];
+PopParameterValues(IXparametersNotInModel) = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Reorder ParameterNamesFIT and PopParameterValues according to their appearance in the model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ixuse = [];
+ixuse2 = [];
+for k=1:length(ParameterNamesFIT),
+    ix = strmatchSB(paramModdos{k},ParameterNamesFIT,'exact');
+    if ~isempty(ix),
+        ixuse(end+1) = ix;
+        ixuse2(end+1) = strmatchSB(ParameterNamesFIT{ix},ParameterNamesFIT,'exact');
+    end
+end
+ParameterNamesFIT = ParameterNamesFIT(ixuse);
+PopParameterValues = PopParameterValues(ixuse2);
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Remove all but dose and PD of interest records from the dataset
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~iscell(PD_NAME),
+    PD_NAME = {PD_NAME};
+end
+allNAME = unique(data.NAME);
+for k=1:length(allNAME),
+    ix = strmatchSB(allNAME{k},PD_NAME,'exact');
+    if isempty(ix),
+        data(data.TYPE~=0 & strcmp(data.NAME,allNAME{k}),:) = [];
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Remove 0 dose records
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+data(data.EVID==1 & data.AMT==0,:) = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create dataset with PK parameters - for placebo subjects use population parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% Add population parameters for all
+dataPKparam = data;
+for k=1:length(ParameterNamesFIT),
+    dataPKparam.(ParameterNamesFIT{k}) = PopParameterValues(k)*ones(length(dataPKparam),1);
+end
+
+% Add individual parameters for subjects where estimates have been made
+allID = unique(dataPKparam.ID);
+dataPKparamFilled = dataset();
+for k=1:length(allID),
+    datak = dataPKparam(dataPKparam.ID==allID(k),:);
+    % Check if ID available in indiv_param
+    ix = find(indiv_param.ID==allID(k));
+    % If available then enter the values
+    if ~isempty(ix),
+        indiv_param_k = indiv_param(ix,2:end);
+        pnames = get(indiv_param_k,'VarNames');
+        for k2=1:length(pnames),
+            datak.(pnames{k2}) = indiv_param_k.(pnames{k2})(1)*ones(length(datak),1);
+        end
+    end
+    % Combine again
+    dataPKparamFilled = [dataPKparamFilled; datak];
+end
+dataPKparam = dataPKparamFilled;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add YTYPE column
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dataPKparam.YTYPE = NaN(length(dataPKparam),1);
+dataPKparam.YTYPE(dataPKparam.TYPE==0) = 0;         % Dose
+for k=1:length(PD_NAME),
+    dataPKparam.YTYPE(strcmp(data.NAME,PD_NAME{k})) = k;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define initial structure of popPD dataset
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+varNames = {'STUDY' 'ID' 'TIME' 'TIMEPOS' 'TIME_UNIT' 'TYPE' 'SUBTYPE' 'NAME' 'DV' 'UNIT' 'DV' 'MDV' 'EVID' 'CENS' 'AMT'  'ADM' 'RATE' 'DOSE' 'TRT' 'YTYPE'};
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add covariates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+varNames = [varNames covNames(:)' catNames(:)'];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add parameter names
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+varNames = [varNames ParameterNamesFIT(:)']; 
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create popPK dataset in defined structure
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+datapopPD = dataset();
+for k=1:length(varNames),
+    datapopPD.(varNames{k}) = dataPKparam.(varNames{k});
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Generate MONOLIX or NONMEM header
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+regressionNames = ParameterNamesFIT;
+if isMONOLIXfitSBPOP(pathNLMEproject),
+    dataheader_output = SBPOPgetMonolixDataHeader(datapopPD,covNames,catNames,regressionNames);
+else
+    dataheader_output = SBPOPgetNONMEMdataHeader(datapopPD,covNames,catNames,regressionNames);
+end    
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Export datasets
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[p,f,e] = fileparts(analysisDataset);
+filename = [p '/' f '.csv'];
+warning off
+mkdir(p);
+warning on
+% All data
+SBPOPexportCSVdataset(datapopPD,filename);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Load dataset as text,
+% exchange spaces to ":::" and save as text
+% Then NONMEM can handle chars in columns ... for UNIT, TIME_UNIT, NAME
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+content = fileread(filename);
+content = strrep(content,' ',':::');
+fid = fopen(filename,'w');
+fprintf(fid,'%s',content);
+fclose(fid);
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/00_popPKproject/SBPOPcreatePopPKproject.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/00_popPKproject/SBPOPcreatePopPKproject.m
new file mode 100644
index 0000000000000000000000000000000000000000..ce3a28d309552677c68f15a84f14086f2306be3b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/00_popPKproject/SBPOPcreatePopPKproject.m
@@ -0,0 +1,63 @@
+function [] = SBPOPcreatePopPKproject(projectName)
+% [DESCRIPTION]
+% This function will setup a popPK project template for the user to work
+% in. Just call this function in a folder of your choice, where you want to
+% create the project and get started.
+%
+% [SYNTAX]
+% [] = SBPOPcreatePopPKproject(projectName)
+%
+% [INPUT]
+% projectName:  Name of the project folder which is going to be created.
+%
+% [OUTPUT]
+% None.
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 18th June 2014
+%
+% [PLATFORM]
+% Windows, Unix, MATLAB
+%
+% [TOOLBOXES USED]
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if the folder exists already
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if exist([pwd '/' projectName])==7,
+    error('The folder "%s" exists already.',projectName);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create the project folder structure
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+mkdir(projectName);
+mkdir([projectName '/Scripts']);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Copy templates into the project folder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+copyfile(which('template_popPK_workflow.m'),[projectName '/Scripts']);
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/00_popPKproject/templates/template_popPK_workflow.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/00_popPKproject/templates/template_popPK_workflow.m
new file mode 100644
index 0000000000000000000000000000000000000000..b9a028a3497f53c03d5a8b0c2ab9dc74ccfab7ab
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/00_popPKproject/templates/template_popPK_workflow.m
@@ -0,0 +1,412 @@
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Template for population PK analysis using SBPOP with NONMEM or MONOLIX
+%
+% No real documentation of the popPK workflow. Just a collection of code
+% pieces to get the popPK workflow started.
+%
+% In order to obtain a good introduction into the popPK workflow, please
+% have a look at the following paper (and its supplementary material):
+%
+% Schmidt H, Radivojevic A (2014) Enhancing population pharmacokinetic
+% modeling efficiency and quality using an integrated workflow, Journal of
+% Pharmacokinetics and Pharmacodynamics.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%% === Initial preparations for the popPK workflow
+
+clc;                        % Clear command window
+clear all;                  % Clear workspace from all defined variables
+close all;                  % Close all figures
+restoredefaultpath();       % Clear all user installed toolboxes
+
+% Installation of SBPOP
+PATH_SBPOP              = '~/STUFF/SBPOP PACKAGE EXPORT'; oldpath = pwd(); cd(PATH_SBPOP); installSBPOPpackageInitial; cd(oldpath);
+
+% SBPAR needed for parallel execution in MATLAB. If your cluster is setup
+% that you can obtain nodes by calling "matlabpool N", then you do not need
+% SBPAR and can remove this line!
+PATH_SBPAR              = '~/STUFF/SBPAR'; oldpath = pwd(); cd(PATH_SBPAR); installSBPAR; cd(oldpath);
+
+%% === Loading, checking and converting the original dataset
+
+% Load the data in the generalized dataset format
+dataGeneral = SBPOPloadCSVdataset('../Data/DataSet_Example_x.csv');
+
+% Check consistency of data
+SBPOPcheckGeneralDataFormat(dataGeneral);
+ 
+%% Convert the general dataset format to an augmented format
+
+covariateInfo = {
+    % NAME              USENAME      
+    'Gender'            'SEX'
+    'Age'               'AGE0'
+    'Bodyweight'        'WT0'
+    'Height'            'HT0'
+    'BMI'               'BMI0'
+};
+data = SBPOPconvertGeneralDataFormat(dataGeneral,covariateInfo);
+
+%% Save the augmented format
+
+SBPOPexportCSVdataset(data,'../Data/DataSet_Example_x_Augmented.csv');
+ 
+%% Define the covariate names
+
+covNames = {'AGE0'    'HT0'      'WT0'     'BMI0'};
+catNames = {'SEX'     'STUDY'    'TRT'};
+
+
+%% === Graphical exploration 
+
+optionsGraphicalExploration                     = [];
+optionsGraphicalExploration.color               = 1;
+optionsGraphicalExploration.outputPath          = '../Output/01_DataExploration_uncleaned_data/';
+ 
+SBPOPexplorePopPKdata(data,covNames,catNames,optionsGraphicalExploration)
+ 
+%% Custom data exploration
+ 
+%% === Data Cleaning 
+
+catImputationValues                     = [  1        9999      9999];
+
+removeSUBJECT  = {
+    % Unique subject identifier     Reason for removal of subject
+    'X3401_0100_0009'               'Confirmed very different PK as for all other subjects.'
+};
+ 
+removeREC = {
+    % Record number in dataset      Reason for removal
+     268                            'Confirmed outlier'
+     860                            'Confirmed outlier'
+     1548                           'Confirmed outlier'
+     2002                           'Confirmed outlier - might be trough sampled post dose'
+};
+ 
+Nobs = 1;
+ 
+optionsDataCleaning                 = [];
+ 
+optionsDataCleaning.outputPath      = '../Output/02_DataCleaning/';
+ 
+%   - FLAG_LLOQ = 1: use CENS=1 and add LLOQ into DV 
+%   - FLAG_LLOQ = 2: use CENS=0, remove all but first LLOQ value, set DV to LLOQ/2
+optionsDataCleaning.FLAG_LLOQ       = 0; % Remove all LLOQ data
+ 
+dataCleaned = SBPOPcleanPopPKdata(data,removeSUBJECT,removeREC,Nobs,covNames,catNames,catImputationValues,optionsDataCleaning);
+  
+%% Repeat the general graphical exploration of data on the cleaned dataset
+
+optionsGraphicalExploration                     = [];
+optionsGraphicalExploration.color               = 1;
+optionsGraphicalExploration.outputPath          = '../Output/03_DataExploration_cleaned_data/';
+ 
+SBPOPexplorePopPKdata(dataCleaned,covNames,catNames,optionsGraphicalExploration)
+ 
+%% === Conversion of data to popPK analysis dataset
+
+modelingDatasetFile = '../Data/popPK_modeling_NLME.csv';
+ 
+dataheaderNLME = SBPOPconvert2popPKdataset(dataCleaned,covNames,catNames,modelingDatasetFile);
+ 
+%% === PopPK model building
+
+%% Setting up the options for the parameter estimation software
+
+optionsNLME                                 = [];                      
+
+optionsNLME.parameterEstimationTool         = 'NONMEM';
+optionsNLME.N_PROCESSORS_PAR                = 10;
+optionsNLME.N_PROCESSORS_SINGLE             = 5;
+
+optionsNLME.algorithm.SEED                  = 123456;                  
+optionsNLME.algorithm.K1                    = 500;                    
+optionsNLME.algorithm.K2                    = 200;                     
+optionsNLME.algorithm.NRCHAINS              = 1;                       
+
+% Set NONMEM specific options
+optionsNLME.algorithm.METHOD                = 'SAEM';
+optionsNLME.algorithm.ITS                   = 1;
+optionsNLME.algorithm.ITS_ITERATIONS        = 10;
+optionsNLME.algorithm.IMPORTANCESAMPLING    = 1;
+optionsNLME.algorithm.IMP_ITERATIONS        = 5;
+
+% Set MONOLIX specific options
+optionsNLME.algorithm.LLsetting             = 'linearization';     
+
+%% Generation of a first model to determine reasonable initial guesses
+
+modeltest                           = [];                               
+modeltest.numberCompartments        = 2;                            
+modeltest.errorModels               = 'comb1';  
+modeltest.saturableClearance        = 1;         
+modeltest.lagTime                   = 0;                              
+modeltest.FACTOR_UNITS              = 1;
+%                                       CL    Vc    Q1    Vp1    Q2    Vp2    Fiv    Fabs1    ka    Tlag_input1    VMAX    KM
+modeltest.POPvalues0                = [ 5     10    5     100    5     100    1      1        1     0.5            10      10];
+modeltest.POPestimate               = [ 1     1     1     1      1     1      0      0        1     1               1       1];
+modeltest.IIVestimate               = [ 1     1     1     1      1     1      0      0        1     1               1       1];
+ 
+optionsModelSpace                   = [];
+optionsModelSpace.buildModelsOnly   = 1;
+ 
+optionsNLME.parameterEstimationTool = 'MONOLIX';
+
+SBPOPbuildPopPKModelSpace('MODEL_0_INITIAL_GUESSES', modeltest, modelingDatasetFile, dataheaderNLME, optionsNLME, optionsModelSpace);
+
+% This model can be loaded into the Monolix GUI and evaluated to assess the
+% initial guesses, K1, K2, etc. Information gathered in this way can be
+% used in the following step to have better informed initial guesses.
+
+%% === Base model building
+modeltest                           = [];                             
+modeltest.numberCompartments        = [2];                          
+modeltest.errorModels               = {'const' 'comb1'};        
+modeltest.saturableClearance        = [0];                   
+modeltest.lagTime                   = [0]; 
+modeltest.FACTOR_UNITS              = 1;
+%                                       CL    Vc    Q1    Vp1    Q2    Vp2    Fiv    Fabs1    ka    Tlag_input1    VMAX    KM
+modeltest.POPvalues0                = [ 10    100   10    500    10    500    1      1        1     0.5            10      10];
+modeltest.POPestimate               = [ 1     1     1     1      1     1      0      0        1     1               0       0];
+modeltest.IIVestimate               = [ 1     1     1     1      1     1      0      0        1     1               0       0];
+modeltest.IIVvalues0                = [ 0.5   0.5   0.5   0.5    0.5   0.5    0.5    0.5      0.5   0.5             0.5     0.5];
+
+% This is how to run it using MONOLIX
+optionsNLME.parameterEstimationTool = 'MONOLIX';
+SBPOPbuildPopPKModelSpace('MODEL_1_BASE_MONOLIX', modeltest, modelingDatasetFile, dataheaderNLME, optionsNLME);
+
+% This is how to run using NONMEM
+optionsNLME.parameterEstimationTool = 'NONMEM';
+optionsNLME.algorithm.METHOD        = 'SAEM';
+SBPOPbuildPopPKModelSpace('MODEL_1_BASE_NONMEM', modeltest, modelingDatasetFile, dataheaderNLME, optionsNLME);
+
+%% Compare 2 and 3 cpt models as example
+projectFolders          = {'../Models/MODEL_1_BASE_MONOLIX/FITMODEL_1_BASE_MONOLIX_003','../Models/MODEL_1_BASE_MONOLIX/FITMODEL_1_BASE_MONOLIX_007'};
+dosing                  = SBPOPcreateDOSING({'BOLUS','INFUSION'},{100 100},{0 48:24:500},{0.001 2});
+obsTimes                = [0:0.5:600];
+options                 = [];
+options.N_PROCESSORS    = 10;
+SBPOPcomparePopPKmodels(projectFolders,FACTOR_UNITS,dosing,obsTimes,options);
+
+%% Robustness analysis of BASE model
+modeltest                           = [];                             
+modeltest.numberCompartments        = 2;                          
+modeltest.errorModels               = {'comb1'};        
+modeltest.saturableClearance        = 0;                   
+modeltest.lagTime                   = 0; 
+modeltest.FACTOR_UNITS              = 1;
+%                                       CL    Vc    Q1    Vp1    Q2    Vp2    Fiv    Fabs1    ka    Tlag_input1    VMAX    KM
+modeltest.POPvalues0                = [ 23    209   23    2100   10    500    1      1        2.08  0.5            10      10];
+modeltest.POPestimate               = [ 1     1     1     1      1     1      0      0        1     1               0       0];
+modeltest.IIVestimate               = [ 1     1     1     1      1     1      0      0        1     1               0       0];
+modeltest.IIVvalues0                = [0.5    0.5   0.5   0.5    0.5   0.5    0.5    0.5      0.5   0.5             0.5   0.5];
+ 
+optionsModelSpace                   = [];
+optionsModelSpace.Ntests            = 10;
+optionsModelSpace.std_noise_setting = 0.5;
+ 
+% This is how to run it using MONOLIX
+optionsNLME.parameterEstimationTool         = 'MONOLIX';
+SBPOPbuildPopPKModelSpace('MODEL_2_BASE_ROBUSTNESS_MONOLIX', modeltest, modelingDatasetFile, dataheaderNLME, optionsNLME, optionsModelSpace);
+ 
+% This is how to run using NONMEM
+optionsNLME.parameterEstimationTool         = 'NONMEM';
+optionsNLME.algorithm.METHOD                = 'SAEM';
+SBPOPbuildPopPKModelSpace('MODEL_2_BASE_ROBUSTNESS_NONMEM', modeltest, modelingDatasetFile, dataheaderNLME, optionsNLME, optionsModelSpace);
+
+%% === Covariate model building
+modeltest                           = [];                             
+modeltest.numberCompartments        = 2;                          
+modeltest.errorModels               = {'comb1'};        
+modeltest.saturableClearance        = 0;                   
+modeltest.lagTime                   = 0; 
+modeltest.FACTOR_UNITS              = 1;
+%                                       CL    Vc    Q1    Vp1    Q2    Vp2    Fiv    Fabs1    ka    Tlag_input1    VMAX    KM
+modeltest.POPvalues0                = [ 23    209   23    2100   10    500    1      1        2.08  0.5            10      10];
+modeltest.POPestimate               = [ 1     1     1     1      1     1      0      0        1     1               0       0];
+modeltest.IIVestimate               = [ 1     1     1     1      1     1      0      0        1     1               0       0];
+modeltest.IIVvalues0                = [0.5    0.5   0.5   0.5    0.5   0.5    0.5    0.5      0.5   0.5             0.5   0.5];
+ 
+modeltest.covariateModels           = {''
+                                       '{CL,SEX,AGE0,WT0}, {Vc,SEX,AGE0,WT0}, {Q1,SEX,AGE0,WT0}, {Vp1,SEX,AGE0,WT0}'
+                                      };
+ 
+% This is how to run it using MONOLIX
+optionsNLME.parameterEstimationTool         = 'MONOLIX';
+SBPOPbuildPopPKModelSpace('MODEL_3_COVARIATE_MONOLIX', modeltest, modelingDatasetFile, dataheaderNLME, optionsNLME);
+ 
+% This is how to run using NONMEM
+optionsNLME.parameterEstimationTool         = 'NONMEM';
+optionsNLME.algorithm.METHOD                = 'SAEM';
+SBPOPbuildPopPKModelSpace('MODEL_3_COVARIATE_NONMEM', modeltest, modelingDatasetFile, dataheaderNLME, optionsNLME);
+
+%% Refinement of covariate model
+modeltest                           = [];                             
+modeltest.numberCompartments        = 2;                          
+modeltest.errorModels               = {'comb1'};        
+modeltest.saturableClearance        = 0;                   
+modeltest.lagTime                   = 0; 
+modeltest.FACTOR_UNITS              = 1;
+%                                       CL    Vc    Q1    Vp1    Q2    Vp2    Fiv    Fabs1    ka    Tlag_input1    VMAX    KM
+modeltest.POPvalues0                = [ 23    209   23    2100   10    500    1      1        2.08  0.5            10      10];
+modeltest.POPestimate               = [ 1     1     1     1      1     1      0      0        1     1               0       0];
+modeltest.IIVestimate               = [ 1     1     1     1      1     1      0      0        1     1               0       0];
+modeltest.IIVvalues0                = [0.5    0.5   0.5   0.5    0.5   0.5    0.5    0.5      0.5   0.5             0.5   0.5];
+ 
+modeltest.covariateModels           = {''
+                                       '{CL,SEX,AGE0,WT0}, {Vc,WT0}'
+                                       '{CL,SEX,AGE0,WT0}, {Vc,SEX,AGE0,WT0}, {Q1,SEX,AGE0,WT0}, {Vp1,SEX,AGE0,WT0}'
+                                      };
+                                  
+% This is how to run it using MONOLIX
+optionsNLME.parameterEstimationTool         = 'MONOLIX';
+SBPOPbuildPopPKModelSpace('MODEL_4_COVARIATE_REFINEMENT_MONOLIX', modeltest, modelingDatasetFile, dataheaderNLME, optionsNLME);
+ 
+% This is how to run using NONMEM
+optionsNLME.parameterEstimationTool         = 'NONMEM';
+optionsNLME.algorithm.METHOD                = 'SAEM';
+SBPOPbuildPopPKModelSpace('MODEL_4_COVARIATE_REFINEMENT_NONMEM', modeltest, modelingDatasetFile, dataheaderNLME, optionsNLME);
+
+%% Assessing "clinical relevance" of identified covariates
+FIT_PATH            = '../Models/MODEL_4_COVARIATE_REFINEMENT_MONOLIX/FITMODEL_4_COVARIATE_REFINEMENT_MONOLIX_003';
+options             = [];
+options.filename    = '../Output/FitAnalysis/MODEL_4_COVARIATE_REFINEMENT_MONOLIX/Covariate_Assessment_fullCovariateModel';
+SBPOPcovariateAssessmentUncertainty(FIT_PATH, modelingDatasetFile,options)
+ 
+FIT_PATH            = '../Models/MODEL_4_COVARIATE_REFINEMENT_MONOLIX/FITMODEL_4_COVARIATE_REFINEMENT_MONOLIX_002';
+options             = [];
+options.filename    = '../Output/FitAnalysis/MODEL_4_COVARIATE_REFINEMENT_MONOLIX/Covariate_Assessment_reducedCovariateModel';
+SBPOPcovariateAssessmentUncertainty(FIT_PATH, modelingDatasetFile,options)
+ 
+%% Robustness analysis of COVARIATE model
+modeltest                           = [];                             
+modeltest.numberCompartments        = 2;                          
+modeltest.errorModels               = {'comb1'};        
+modeltest.saturableClearance        = 0;                   
+modeltest.lagTime                   = 0; 
+modeltest.FACTOR_UNITS              = 1;
+%                                       CL    Vc    Q1    Vp1    Q2    Vp2    Fiv    Fabs1    ka    Tlag_input1    VMAX    KM
+modeltest.POPvalues0                = [ 23    209   23    2100   10    500    1      1        2.08  0.5            10      10];
+modeltest.POPestimate               = [ 1     1     1     1      1     1      0      0        1     1               0       0];
+modeltest.IIVestimate               = [ 1     1     1     1      1     1      0      0        1     1               0       0];
+modeltest.IIVvalues0                = [0.5    0.5   0.5   0.5    0.5   0.5    0.5    0.5      0.5   0.5             0.5   0.5];
+ 
+modeltest.covariateModels           = '{CL,SEX,AGE0,WT0}, {Vc,WT0}';
+ 
+optionsModelSpace                   = [];
+optionsModelSpace.Ntests            = 20;
+optionsModelSpace.std_noise_setting = 0.5;
+optionsModelSpace.createGOFplots    = 1;
+ 
+% This is how to run it using MONOLIX
+optionsNLME.parameterEstimationTool         = 'MONOLIX';
+SBPOPbuildPopPKModelSpace('MODEL_5_COVARIATE_ROBUSTNESS_MONOLIX', modeltest, modelingDatasetFile, dataheaderNLME, optionsNLME, optionsModelSpace);
+
+% This is how to run using NONMEM
+optionsNLME.parameterEstimationTool         = 'NONMEM';
+optionsNLME.algorithm.METHOD                = 'SAEM';
+SBPOPbuildPopPKModelSpace('MODEL_5_COVARIATE_ROBUSTNESS_NONMEM', modeltest, modelingDatasetFile, dataheaderNLME, optionsNLME, optionsModelSpace);
+
+%% === Covariance model building
+modeltest                           = [];                             
+modeltest.numberCompartments        = 2;                          
+modeltest.errorModels               = {'comb1'};        
+modeltest.saturableClearance        = 0;                   
+modeltest.lagTime                   = 0; 
+modeltest.FACTOR_UNITS              = 1;
+%                                       CL    Vc    Q1    Vp1    Q2    Vp2    Fiv    Fabs1    ka    Tlag_input1    VMAX    KM
+modeltest.POPvalues0                = [ 23    209   23    2100   10    500    1      1        2.08  0.5            10      10];
+modeltest.POPestimate               = [ 1     1     1     1      1     1      0      0        1     1               0       0];
+modeltest.IIVestimate               = [ 1     1     1     1      1     1      0      0        1     1               0       0];
+modeltest.IIVvalues0                = [0.5    0.5   0.5   0.5    0.5   0.5    0.5    0.5      0.5   0.5             0.5   0.5];
+modeltest.covariateModels           = '{CL,SEX,AGE0,WT0}, {Vc,WT0}';
+ 
+modeltest.covarianceModels          = {''
+                                       '{ka,CL,Vc,Q1,Vp1}'
+                                       '{CL,Vc,Q1,Vp1}'
+                                       '{CL,Vc},{Q1,Vp1}'
+                                       '{CL,Vc}'
+                                       };
+ 
+optionsModelSpace                   = [];
+optionsModelSpace.Ntests            = 5;
+optionsModelSpace.std_noise_setting = 0.5;
+optionsModelSpace.createGOFplots    = 1;
+ 
+% This is how to run it using MONOLIX
+optionsNLME.parameterEstimationTool         = 'MONOLIX';
+SBPOPbuildPopPKModelSpace('MODEL_6_COVARIANCE_ROBUSTNESS_MONOLIX', modeltest, modelingDatasetFile, dataheaderNLME, optionsNLME, optionsModelSpace);
+ 
+% This is how to run using NONMEM
+optionsNLME.parameterEstimationTool         = 'NONMEM';
+optionsNLME.algorithm.METHOD                = 'SAEM';
+SBPOPbuildPopPKModelSpace('MODEL_6_COVARIANCE_ROBUSTNESS_NONMEM', modeltest, modelingDatasetFile, dataheaderNLME, optionsNLME, optionsModelSpace);
+
+%% === Select final model
+modeltest                           = [];
+modeltest.numberCompartments        = 2;                          
+modeltest.errorModels               = {'comb1'};        
+modeltest.saturableClearance        = 0;                   
+modeltest.lagTime                   = 0; 
+modeltest.FACTOR_UNITS              = 1;
+%                                       CL    Vc    Q1    Vp1    Q2    Vp2    Fiv    Fabs1    ka    Tlag_input1    VMAX    KM
+modeltest.POPvalues0                = [ 23    209   23    2100   10    500    1      1        2.08  0.5            10      10];
+modeltest.POPestimate               = [ 1     1     1     1      1     1      0      0        1     1               0       0];
+modeltest.IIVestimate               = [ 1     1     1     1      1     1      0      0        1     1               0       0];
+modeltest.IIVvalues0                = [0.5    0.5   0.5   0.5    0.5   0.5    0.5    0.5      0.5   0.5             0.5   0.5];
+modeltest.covariateModels           = '{CL,SEX,AGE0,WT0}, {Vc,WT0}';
+modeltest.covarianceModels          = '{ka,CL,Vc,Q1,Vp1}';
+ 
+% This is how to run it using MONOLIX
+optionsNLME.parameterEstimationTool         = 'MONOLIX';
+SBPOPbuildPopPKModelSpace('MODEL_7_FINAL_MONOLIX', modeltest, modelingDatasetFile, dataheaderNLME, optionsNLME);
+ 
+% This is how to run using NONMEM
+optionsNLME.parameterEstimationTool         = 'NONMEM';
+optionsNLME.algorithm.METHOD                = 'SAEM';
+SBPOPbuildPopPKModelSpace('MODEL_7_FINAL_NONMEM', modeltest, modelingDatasetFile, dataheaderNLME, optionsNLME);
+ 
+%% === Generation of VPCs for final model
+ 
+%% Generate stratified VPC 
+dataVPC                     = SBPOPloadCSVdataset(modelingDatasetFile);
+
+projectFolder               = '../Models/MODEL_7_FINAL_MONOLIX/FITMODEL_7_FINAL_MONOLIX_001';
+ 
+FACTOR_UNITS                = 1;
+
+options                     = [];
+options.filename            = '../Output/FitAnalysis/MODEL_7_FINAL_MONOLIX/VPC';
+options.logY                = 1;
+options.showDataQuantiles   = 1;
+options.bins_mean           = [ 0.083 0.25  0.5    1    2    4    8   12       23.917   24   48       95.917   96  168 191.92       287.92       383.92       479.92       480.08 480.5          481          482          484          488       503.92       599.92          696          792  960];
+options.bins_lookaround     = 0.05*ones(1,length(options.bins_mean));
+options.nTimePoints         = 1000;
+options.N_PROCESSORS        = 10;
+
+SBPOPcreatePopPKstratifiedVPC(projectFolder,modeltest.FACTOR_UNITS,dataVPC,covNames,catNames,options)
+
+%% Generate stratified VPC - dose normalized
+dataVPC                     = SBPOPloadCSVdataset(modelingDatasetFile);
+dataVPC(dataVPC.TIME<0,:)   = [];
+dataVPC.DV(dataVPC.TYPE==1) = dataVPC.DV(dataVPC.TYPE==1)./dataVPC.DOSE(dataVPC.TYPE==1);
+dataVPC.AMT(dataVPC.TYPE==0) = 1;
+
+projectFolder               = '../Models/MODEL_7_FINAL_MONOLIX/FITMODEL_7_FINAL_MONOLIX_001';
+
+options                     = [];
+options.filename            = '../Output/FitAnalysis/MODEL_7_FINAL_MONOLIX/VPC_dose_normalized';
+options.logY                = 1;
+options.showDataQuantiles   = 1;
+options.bins_mean           = [ 0.083 0.25  0.5    1    2    4    8   12       23.917   24   48       95.917   96  168 191.92       287.92       383.92       479.92       480.08 480.5          481          482          484          488       503.92       599.92          696          792  960];
+options.bins_lookaround     = 0.05*ones(1,length(options.bins_mean));
+options.nTimePoints         = 500;
+options.N_PROCESSORS        = 10;
+
+options.groupName           = 'STUDY';
+ 
+SBPOPcreatePopPKstratifiedVPC(projectFolder,modeltest.FACTOR_UNITS,dataVPC,covNames,catNames,options)
+ 
+ 
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/02_DataExploration/SBPOPexplorePopPKdata.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/02_DataExploration/SBPOPexplorePopPKdata.m
new file mode 100644
index 0000000000000000000000000000000000000000..aa11def2fc73c769c50623ae436aa2e5d680f9e6
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/02_DataExploration/SBPOPexplorePopPKdata.m
@@ -0,0 +1,752 @@
+function [] = SBPOPexplorePopPKdata(data,covNames,catNames,options,varargin)
+% [DESCRIPTION]
+% This function allows to plot standard data exploration plots focusing on
+% a popPK analysis. The data need to be provided, following the standard
+% dataspec, defined in the help to the function SBPOPcheckDataFormat, so
+% please look there for more information.  
+%
+% ASSUMPTIONS:
+% - PK data have TYPE=1 in the dataset.
+% - The function tests if several SUBTYPE items are present and report an error if this is the case.
+%
+% [SYNTAX]
+% [] = SBPOPexplorePopPKdata(data,covNames,catNames)
+% [] = SBPOPexplorePopPKdata(data,covNames,catNames,options,NAME)
+%
+% [INPUT]
+% data:         MATLAB PKPD dataset in standard data spec format  
+% covNames:     Cell-array with the names of the continuous covariates, as
+%               defined in the dataset
+% catNames:     Cell-array with the names of the categorical covariates, as
+%               defined in the dataset
+% NAME: 		allows to plot instead of PK (TYPE=1) a specific readout defined by "NAME" in the 
+%               NAME column of the dataset
+% options:      MATLAB structure with additional options
+%
+
+%               options.color:    =0: use black and white where necessary,
+%                                 =1: use color (default)
+%               options.outputPath: path where
+%                                 outputs are exported to. Default:
+%                                 '../Output/DataExploration/';
+%               options.plotIndividualData: =1: yes (default), =0: no
+%               options.plotStratifiedData: =1: yes (default), =0: no
+%               options.plotCovariateData:  =1: yes (default), =0: no
+%
+% [OUTPUT]
+% Several PS (windows) or PDF (unix) documents with plots. The names of the
+% files tell what is shown. also a summary statistic of the data as an
+% exported file. Covariate information, etc.
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 15th February 2013
+%
+% [PLATFORM]
+% Windows, Unix, MATLAB
+%
+% [TOOLBOXES USED]
+% Statistics Toolbox
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+%
+% This program is Free Open Source Software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isa(data,'dataset'),
+    error('First input argument is not a MATLAB dataset.');
+end
+
+datanames = get(data,'VarNames');
+ix_remove = [];
+for k=1:length(covNames),
+    if isempty(strmatchSB(covNames{k},datanames,'exact')), 
+        disp(sprintf('The dataset does not contain the covariate ''%s''. It is removed from the analysis.',covNames{k})); 
+        ix_remove(end+1) = k;
+    end
+end
+covNames(ix_remove) = [];
+
+ix_remove = [];
+for k=1:length(catNames),
+    if isempty(strmatchSB(catNames{k},datanames,'exact')), 
+        disp(sprintf('The dataset does not contain the covariate ''%s''. It is removed from the analysis.',catNames{k})); 
+        ix_remove(end+1) = k;
+    end
+end
+catNames(ix_remove) = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle options
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try outputPath          = [options.outputPath '/'];     catch, outputPath           = '../Output/DataExploration/';     end; %#ok<*CTCH>
+try color               = options.color;                catch, color                = 1;                                end; %#ok<*CTCH>
+try plotIndividualData  = options.plotIndividualData;   catch, plotIndividualData   = 1;                                end; %#ok<*CTCH>
+try plotStratifiedData  = options.plotStratifiedData;   catch, plotStratifiedData   = 1;                                end; %#ok<*CTCH>
+try plotCovariateData   = options.plotCovariateData;    catch, plotCovariateData    = 1;                                end; %#ok<*CTCH>
+
+if nargin==5,
+    type = varargin{1};
+else
+    type = 1;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check number of subtype elements ...
+% PK toolbox assumes PK: TYPE=1 and only one SUBTYPE available
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if type==1,
+    ST = unique(data.SUBTYPE(data.TYPE==1));
+    if length(ST) > 1,
+        error('TYPE=1 records have more than a single SUBTYPE => not allowed for popPK workflow.');
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create output folder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[p,f,e] = fileparts(outputPath);
+warning off
+mkdir(p);
+warning on
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get colors etc
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[colors,lines,dots,bwcolors] = getcolorsSBPOP();
+
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Export individual data - summary - linear Y axis
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    filename            = [outputPath '01_individual_PK_data_summary_linearY'];
+    options             = [];
+    options.logY        = 0;
+    options.showDose    = 0;
+    options.showText    = 0;
+    options.nIDperPage  = 36;
+    options.sameaxes    = 1;
+    options.nameGroup   = 'STYSID1A';
+    options.titlefontsize = 8;
+    SBPOPexploreIndivData(data,type,filename,options)
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Export individual data - summary - log Y axis
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    filename            = [outputPath '02_individual_PK_data_summary_logY'];
+    options             = [];
+    options.logY        = 1;
+    options.showDose    = 0;
+    options.showText    = 0;
+    options.nIDperPage  = 36;
+    options.sameaxes    = 1;
+    options.nameGroup   = 'STYSID1A';
+    options.titlefontsize = 8;
+    SBPOPexploreIndivData(data,type,filename,options)
+    
+if plotIndividualData,
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Export individual data - 1 page per ID - linear Y axis
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    filename            = [outputPath '03_individual_PK_data_SINGLE_linearY'];
+    options             = [];
+    options.logY        = 0;
+    options.showDose    = 1;
+    options.showText    = 1;
+    options.nIDperPage  = 1;
+    options.sameaxes    = 0;
+    options.nameGroup   = 'STYSID1A';
+    SBPOPexploreIndivData(data,type,filename,options)
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Export individual data - 1 page per ID - log Y axis
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    filename            = [outputPath '04_individual_PK_data_SINGLE_logY'];
+    options             = [];
+    options.logY        = 1;
+    options.showDose    = 1;
+    options.showText    = 1;
+    options.nIDperPage  = 1;
+    options.sameaxes    = 0;
+    options.nameGroup   = 'STYSID1A';
+    SBPOPexploreIndivData(data,type,filename,options)
+end
+
+if plotStratifiedData,
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Assessment of data availability
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    filename    = [outputPath '05_data_availability'];
+    startNewPrintFigureSBPOP(filename);
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Assessment of data availability TRT/STUDY
+    % Get PK data
+    if isnumeric(type),
+        dataPlot                    = data(data.TYPE==1,:);
+    else
+        dataPlot                    = data(strcmp(data.NAME,type),:);
+    end        
+    
+    % Do the plot
+    nameGroupX                  = 'TRT';
+    nameGroupY                  = 'STUDY';
+    nameY                       = 'DV';
+    nameX                       = 'TIME';
+    options                     = [];
+    options.nameSubGroup        = 'ID';
+    options.linetype            = '--';
+    options.linewidth           = 1;
+    options.xlabelText          = sprintf('Time [%s]',dataPlot.TIME_UNIT{1});
+    nY                          = length(unique(dataPlot.(nameGroupY)));
+    options.ylabelText          = {};
+    for k=1:nY, options.ylabelText{k} = ''; end
+    if nY==1,
+        options.ylabelText{1}   = sprintf('%s [%s]',dataPlot.NAME{1},dataPlot.UNIT{1});
+    else
+        options.ylabelText{floor(nY/2)} = sprintf('%s [%s]',dataPlot.NAME{1},dataPlot.UNIT{1});
+    end
+    options.logY                = 1;
+    options.sameaxes            = 1;
+    options.linecolor           = 0.2*[1 1 1];
+    options.axescolor           = 0.2*[1 1 1];
+    options.maxlegendentries    = 20;
+    options.titlefontsize       = 8;
+    options.labeltextsize       = 8;
+    options.ticklabeltextsize   = 8;
+    
+    SBPOPplotfacetgrid(dataPlot,nameX,nameY,nameGroupX,nameGroupY,options)
+    printFigureSBPOP(gcf,filename);
+    close(gcf);
+    
+    convert2pdfSBPOP(filename);
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Checking dose nonlinearity - considering different - lin Y axis
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    filename    = [outputPath '06_assessment_dose_normalized'];
+    startNewPrintFigureSBPOP(filename);
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Checking dose nonlinearity - considering different STUDY - lin Y axis
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Get PK data
+    if isnumeric(type),
+        dataPlot                    = data(data.TYPE==1,:);
+    else
+        dataPlot                    = data(strcmp(data.NAME,type),:);
+    end        
+        
+
+    % Dose normalize the PK data
+    % If DOSE==0 then use DV values instead of DVnorm. Should happen only
+    % for pre first dose values and there the PK should be 0 anyway.
+    DOSE = dataPlot.DOSE; DOSE(DOSE==0) = 1;
+    dataPlot.DVnorm = dataPlot.DV./DOSE;
+    
+    % Do the plot
+    nameGroup   = 'STUDY';
+    nameY       = 'DVnorm';
+    nameX       = 'TIME';
+    options     = [];
+    options.linewidth = 1;
+    options.nameSubGroup    = 'ID';
+    options.nameColorGroup  = 'TRT';
+    options.xlabelText = sprintf('Time [%s]',dataPlot.TIME_UNIT{1});
+    options.ylabelText = sprintf('(DOSE NORMALIZED) %s',dataPlot.NAME{1});
+    options.ylabelfirstonly = 1;
+    options.logY            = 0;
+    options.showmedian       = 1;
+    options.NbinsMedian      = 20;
+    options.sameaxes        = 0;
+    options.linetype        = '.';
+    options.medianlinewidth  = 2;
+    options.axescolor       = 0.2*[1 1 1];
+    if ~color,
+        options.showmarkers      = 1;
+        options.linecolorsCustom = bwcolors;
+        options.markersize       = 8;
+        options.linetypesCustom  = dots;
+    end
+    options.maxlegendentries = 20;
+    SBPOPplottrellis(dataPlot,nameGroup,nameX,nameY,options)
+    printFigureSBPOP(gcf,filename);
+    close(gcf);
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Checking dose nonlinearity - considering different STUDY - log Y axis
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Get PK data
+    if isnumeric(type),
+        dataPlot                    = data(data.TYPE==1,:);
+    else
+        dataPlot                    = data(strcmp(data.NAME,type),:);
+    end        
+   
+
+    % Dose normalize the PK data
+    % If DOSE==0 then use DV values instead of DVnorm. Should happen only
+    % for pre first dose values and there the PK should be 0 anyway.
+    DOSE = dataPlot.DOSE; DOSE(DOSE==0) = 1;
+    dataPlot.DVnorm = dataPlot.DV./DOSE;
+    
+    % Do the plot
+    nameGroup   = 'STUDY';
+    nameY       = 'DVnorm';
+    nameX       = 'TIME';
+    options     = [];
+    options.linewidth = 1;
+    options.nameSubGroup    = 'ID';
+    options.nameColorGroup  = 'TRT';
+    options.xlabelText = sprintf('Time [%s]',dataPlot.TIME_UNIT{1});
+    options.ylabelText = sprintf('(DOSE NORMALIZED) %s',dataPlot.NAME{1});
+    options.ylabelfirstonly = 1;
+    options.logY            = 1;
+    options.showmedian       = 1;
+    options.NbinsMedian      = 20;
+    options.sameaxes        = 0;
+    options.linetype        = '.';
+    options.medianlinewidth  = 2;
+    options.axescolor       = 0.2*[1 1 1];
+    if ~color,
+        options.showmarkers      = 1;
+        options.linecolorsCustom = bwcolors;
+        options.markersize       = 8;
+        options.linetypesCustom  = dots;
+    end
+    options.maxlegendentries = 20;
+    SBPOPplottrellis(dataPlot,nameGroup,nameX,nameY,options)
+    printFigureSBPOP(gcf,filename);
+    close(gcf);
+    
+    convert2pdfSBPOP(filename);
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Assessment of data availability - over TAD
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    filename    = [outputPath '07_data_availability_over_TAD'];
+    startNewPrintFigureSBPOP(filename);
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Assessment of data availability TRT/STUDY
+    % Get PK data
+    if isnumeric(type),
+        dataPlot                    = data(data.TYPE==1,:);
+    else
+        dataPlot                    = data(strcmp(data.NAME,type),:);
+    end        
+
+    
+    % Do the plot
+    nameGroupX  = 'TRT';
+    nameGroupY  = 'STUDY';
+    nameY       = 'DV';
+    nameX       = 'TAD';
+    options     = [];
+    options.nameSubGroup    = 'ID';
+    options.linetype = '--';
+    options.linewidth = 1;
+    
+    options.xlabelText = sprintf('TAD [%s]',dataPlot.TIME_UNIT{1});
+    nY = length(unique(dataPlot.(nameGroupY)));
+    options.ylabelText = {};
+    for k=1:nY, options.ylabelText{k} = ''; end
+    if nY==1,
+        options.ylabelText{1} = sprintf('%s [%s]',dataPlot.NAME{1},dataPlot.UNIT{1});
+    else
+        options.ylabelText{floor(nY/2)} = sprintf('%s [%s]',dataPlot.NAME{1},dataPlot.UNIT{1});
+    end
+    options.logY                = 1;
+    options.sameaxes            = 1;
+    options.linecolor           = 0.2*[1 1 1];
+    options.axescolor           = 0.2*[1 1 1];
+    options.maxlegendentries    = 20;
+    options.titlefontsize       = 8;
+    options.labeltextsize       = 8;
+    options.ticklabeltextsize   = 8;
+    
+    SBPOPplotfacetgrid(dataPlot,nameX,nameY,nameGroupX,nameGroupY,options)
+    printFigureSBPOP(gcf,filename);
+    close(gcf);
+    
+    convert2pdfSBPOP(filename);
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Checking dose nonlinearity - considering different  - lin Y axis
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    filename    = [outputPath '08_assessment_dose_normalized_over_TAD'];
+    startNewPrintFigureSBPOP(filename);
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Checking dose nonlinearity - considering different STUDY - lin Y axis
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Get PK data
+    if isnumeric(type),
+        dataPlot                    = data(data.TYPE==1,:);
+    else
+        dataPlot                    = data(strcmp(data.NAME,type),:);
+    end        
+     
+
+    % Dose normalize the PK data
+    % If DOSE==0 then use DV values instead of DVnorm. Should happen only
+    % for pre first dose values and there the PK should be 0 anyway.
+    DOSE = dataPlot.DOSE; DOSE(DOSE==0) = 1;
+    dataPlot.DVnorm = dataPlot.DV./DOSE;
+    
+    % Do the plot
+    nameGroup   = 'STUDY';
+    nameY       = 'DVnorm';
+    nameX       = 'TAD';
+    options     = [];
+    options.nameSubGroup    = 'ID';
+    options.nameColorGroup  = 'TRT';
+    options.xlabelText = sprintf('TAD [%s]',dataPlot.TIME_UNIT{1});
+    options.ylabelText = sprintf('(DOSE NORMALIZED) %s',dataPlot.NAME{1});
+    options.ylabelfirstonly = 1;
+    options.logY            = 0;
+    options.showmedian       = 1;
+    options.NbinsMedian      = 20;
+    options.sameaxes        = 0;
+    options.linetype        = '.';
+    options.medianlinewidth  = 2;
+    options.axescolor       = 0.2*[1 1 1];
+    if ~color,
+        options.showmarkers      = 1;
+        options.linecolorsCustom = bwcolors;
+        options.markersize       = 8;
+        options.linetypesCustom  = dots;
+    end
+    options.maxlegendentries = 20;
+    SBPOPplottrellis(dataPlot,nameGroup,nameX,nameY,options)
+    printFigureSBPOP(gcf,filename);
+    close(gcf);
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Checking dose nonlinearity - considering different STUDY - log Y axis
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Get PK data
+    if isnumeric(type),
+        dataPlot                    = data(data.TYPE==1,:);
+    else
+        dataPlot                    = data(strcmp(data.NAME,type),:);
+    end        
+
+    % Dose normalize the PK data
+    % If DOSE==0 then use DV values instead of DVnorm. Should happen only
+    % for pre first dose values and there the PK should be 0 anyway.
+    DOSE = dataPlot.DOSE; DOSE(DOSE==0) = 1;
+    dataPlot.DVnorm = dataPlot.DV./DOSE;
+    
+    % Do the plot
+    nameGroup   = 'STUDY';
+    nameY       = 'DVnorm';
+    nameX       = 'TAD';
+    options     = [];
+    options.nameSubGroup    = 'ID';
+    options.nameColorGroup  = 'TRT';
+    options.xlabelText = sprintf('TAD [%s]',dataPlot.TIME_UNIT{1});
+    options.ylabelText = sprintf('(DOSE NORMALIZED) %s',dataPlot.NAME{1});
+    options.ylabelfirstonly = 1;
+    options.logY            = 1;
+    options.showmedian       = 1;
+    options.NbinsMedian      = 20;
+    options.sameaxes        = 0;
+    options.linetype        = '.';
+    options.medianlinewidth  = 2;
+    options.axescolor       = 0.2*[1 1 1];
+    if ~color,
+        options.showmarkers      = 1;
+        options.linecolorsCustom = bwcolors;
+        options.markersize       = 8;
+        options.linetypesCustom  = dots;
+    end
+    options.maxlegendentries = 20;
+    SBPOPplottrellis(dataPlot,nameGroup,nameX,nameY,options)
+    printFigureSBPOP(gcf,filename);
+    close(gcf);
+    
+    convert2pdfSBPOP(filename);
+end
+
+
+
+if plotCovariateData,
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Summary statistics covariates
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    filename    = [outputPath '09_summary_statistics'];
+    SBPOPexploreSummaryStats(data,covNames,catNames,filename)
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Graphical exploration of covariates
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    if ~isempty(covNames),
+        filename    = [outputPath '10_covariates_relationship'];
+        startNewPrintFigureSBPOP(filename);
+        
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%
+        % Correlation of continuous covariates
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%
+        dataPlot = dataset();
+        allID = unique(data.ID);
+        for k=1:length(allID),
+            datak = data(data.ID==allID(k),:);
+            dataPlot = [dataPlot; datak(1,:)];
+        end
+        dataPlotcovcont = dataset();
+        for k=1:length(covNames),
+            dataPlotcovcont.(covNames{k}) = dataPlot.(covNames{k});
+        end
+        figure; clf;
+        SBPOPplotpairwiseCorr(dataPlotcovcont);
+        set(gcf,'color',[1 1 1]);
+        printFigureSBPOP(gcf,filename);
+        close(gcf);
+        
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%
+        % Correlation of continuous and categorical covariates
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%
+        if ~isempty(catNames),
+            dataPlotcovcontcat = dataPlotcovcont;
+            for k=1:length(catNames),
+                dataPlotcovcontcat.(catNames{k}) = dataPlot.(catNames{k});
+            end
+            SBPOPplotCovarianceCat(dataPlotcovcontcat,covNames,catNames);
+        end
+        set(gcf,'color',[1 1 1]);
+        printFigureSBPOP(gcf,filename);
+        close(gcf);
+        
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%
+        % Histograms of continuous covariates
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%
+        for k=1:length(covNames),
+            hist(dataPlotcovcont.(covNames{k}));
+            xlabel(covNames{k},'FontSize',18,'Interpreter','none')
+            ylabel('Numbers','FontSize',18,'Interpreter','none')
+            set(gcf,'color',[1 1 1]);
+            grid on
+            printFigureSBPOP(gcf,filename);
+            close(gcf);
+        end
+        
+        convert2pdfSBPOP(filename);
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Graphical exploration of potential covariate effect on PK
+    % We only look at dose normalized information
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    
+    % Get PK data
+    if isnumeric(type),
+        dataPlot                    = data(data.TYPE==1,:);
+    else
+        dataPlot                    = data(strcmp(data.NAME,type),:);
+    end               
+
+    % Dose normalize the PK data
+    % If DOSE==0 then use DV values instead of DVnorm. Should happen only
+    % for pre first dose values and there the PK should be 0 anyway.
+    DOSE = dataPlot.DOSE; DOSE(DOSE==0) = 1;
+    dataPlot.DVnorm = dataPlot.DV./DOSE;
+    
+    % Determine median values for the continuous covariates
+    allID = unique(dataPlot.ID);
+    covValues = [];
+    for k=1:length(allID),
+        datak = dataPlot(dataPlot.ID==allID(k),:);
+        row   = datak(1,:);
+        covValuesRow = NaN(1,length(covNames));
+        for k2=1:length(covNames),
+            covValuesRow(k2) = row.(covNames{k2});
+        end
+        covValues = [covValues; covValuesRow];
+    end
+    medianCovValues = nanmedian(covValues,1);
+    
+    % Create additional categorical columns for each continuous covariate to
+    % identify >=median or <median which then is used to plot
+    newCatCovNames = {};
+    for k=1:length(covNames),
+        newCatCovName  = ['ABOVE_MEDIAN_' covNames{k}];
+        newCatCovNames{k} = newCatCovName;
+        dataPlot.(newCatCovName) = NaN(length(dataPlot),1);
+        dataPlot.(newCatCovName)(dataPlot.(covNames{k})>=medianCovValues(k)) = 1;
+        dataPlot.(newCatCovName)(dataPlot.(covNames{k})<medianCovValues(k))  = 0;
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%
+    % Start the plotting for continuous covariates
+    %%%%%%%%%%%%%%%%%%%%%
+    filename    = [outputPath '11_assessment_continuous_covariate_effect_TAD'];
+    startNewPrintFigureSBPOP(filename);
+    
+    for k=1:length(covNames),
+        
+        % Need to remove records with NaN data in the assessed covariate column
+        dataPlotCov = dataPlot;
+        dataPlotCov(isnan(dataPlotCov.(newCatCovNames{k})),:) = [];
+        
+        % Only plot if not empty (can happen with many NaNs)
+        if ~isempty(dataPlotCov)
+            % Do the plot by STUDY - linear axis
+            nameGroup               = 'STUDY';
+            nameY                   = 'DVnorm';
+            nameX                   = 'TAD';
+            options                 = [];
+            options.linewidth       = 1;
+            options.nameSubGroup    = 'ID';
+            options.nameColorGroup  = newCatCovNames{k};
+            options.xlabelText      = sprintf('TAD [%s]',dataPlotCov.TIME_UNIT{1});
+            options.ylabelText      = sprintf('(DOSE NORMALIZED) %s',dataPlotCov.NAME{1});
+            options.ylabelfirstonly = 1;
+            options.logY            = 0;
+            options.showmedian      = 1;
+            options.NbinsMedian     = 20;
+            options.sameaxes        = 0;
+            options.linetype        = '.';
+            options.medianlinewidth = 2;
+            options.axescolor       = [0.2 0.2 0.2];
+            if ~color,
+                options.showmarkers      = 1;
+                options.linecolorsCustom = bwcolors;
+                options.markersize       = 8;
+                options.linetypesCustom  = dots;
+            end
+            options.maxlegendentries = 20;
+            SBPOPplottrellis(dataPlotCov,nameGroup,nameX,nameY,options)
+            printFigureSBPOP(gcf,filename);
+            close(gcf);
+            
+            % Do the plot by STUDY - log axis
+            nameGroup               = 'STUDY';
+            nameY                   = 'DVnorm';
+            nameX                   = 'TAD';
+            options                 = [];
+            options.linewidth       = 1;
+            options.nameSubGroup    = 'ID';
+            options.nameColorGroup  = newCatCovNames{k};
+            options.xlabelText      = sprintf('TAD [%s]',dataPlotCov.TIME_UNIT{1});
+            options.ylabelText      = sprintf('(DOSE NORMALIZED) %s',dataPlotCov.NAME{1});
+            options.ylabelfirstonly = 1;
+            options.logY            = 1;
+            options.showmedian      = 1;
+            options.NbinsMedian     = 20;
+            options.sameaxes        = 0;
+            options.linetype        = '.';
+            options.medianlinewidth = 2;
+            options.axescolor       = [0.2 0.2 0.2];
+            if ~color,
+                options.showmarkers      = 1;
+                options.linecolorsCustom = bwcolors;
+                options.markersize       = 8;
+                options.linetypesCustom  = dots;
+            end
+            options.maxlegendentries = 20;
+            SBPOPplottrellis(dataPlotCov,nameGroup,nameX,nameY,options)
+            printFigureSBPOP(gcf,filename);
+            close(gcf);
+        end
+    end
+    if ~isempty(covNames),
+        convert2pdfSBPOP(filename);
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%
+    % Then plotting for categorical covariates
+    %%%%%%%%%%%%%%%%%%%%%
+    filename    = [outputPath '12_assessment_categorical_covariate_effect_TAD'];
+    startNewPrintFigureSBPOP(filename);
+    
+    for k=1:length(catNames),
+        
+        % Need to remove records with NaN data in the assessed covariate column
+        dataPlotCov = dataPlot;
+        dataPlotCov(isnan(dataPlotCov.(catNames{k})),:) = [];
+        
+        % Only plot if not empty (can happen with many NaNs)
+        if ~isempty(dataPlotCov)
+            
+            % Do the plot by STUDY - linear axis
+            nameGroup               = 'STUDY';
+            nameY                   = 'DVnorm';
+            nameX                   = 'TAD';
+            options                 = [];
+            options.linewidth       = 1;
+            options.nameSubGroup    = 'ID';
+            options.nameColorGroup  = catNames{k};
+            options.xlabelText      = sprintf('TAD [%s]',dataPlotCov.TIME_UNIT{1});
+            options.ylabelText      = sprintf('(DOSE NORMALIZED) %s',dataPlotCov.NAME{1});
+            options.ylabelfirstonly = 1;
+            options.logY            = 0;
+            options.showmedian      = 1;
+            options.NbinsMedian     = 20;
+            options.sameaxes        = 0;
+            options.linetype        = '.';
+            options.medianlinewidth = 2;
+            options.axescolor       = [0.2 0.2 0.2];
+            if ~color,
+                options.showmarkers      = 1;
+                options.linecolorsCustom = bwcolors;
+                options.markersize       = 8;
+                options.linetypesCustom  = dots;
+            end
+            options.maxlegendentries = 20;
+            SBPOPplottrellis(dataPlotCov,nameGroup,nameX,nameY,options)
+            printFigureSBPOP(gcf,filename);
+            close(gcf);
+            
+            % Do the plot by STUDY - log axis
+            nameGroup               = 'STUDY';
+            nameY                   = 'DVnorm';
+            nameX                   = 'TAD';
+            options                 = [];
+            options.linewidth       = 1;
+            options.nameSubGroup    = 'ID';
+            options.nameColorGroup  = catNames{k};
+            options.xlabelText      = sprintf('TAD [%s]',dataPlotCov.TIME_UNIT{1});
+            options.ylabelText      = sprintf('(DOSE NORMALIZED) %s',dataPlotCov.NAME{1});
+            options.ylabelfirstonly = 1;
+            options.logY            = 1;
+            options.showmedian      = 1;
+            options.NbinsMedian     = 20;
+            options.sameaxes        = 0;
+            options.linetype        = '.';
+            options.medianlinewidth = 2;
+            options.axescolor       = [0.2 0.2 0.2];
+            if ~color,
+                options.showmarkers      = 1;
+                options.linecolorsCustom = bwcolors;
+                options.markersize       = 8;
+                options.linetypesCustom  = dots;
+            end
+            options.maxlegendentries = 20;
+            SBPOPplottrellis(dataPlotCov,nameGroup,nameX,nameY,options)
+            printFigureSBPOP(gcf,filename);
+            close(gcf);
+        end
+    end
+    if ~isempty(catNames),
+        convert2pdfSBPOP(filename);
+    end    
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/03_DataCleaning/SBPOPcleanPopPKdata.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/03_DataCleaning/SBPOPcleanPopPKdata.m
new file mode 100644
index 0000000000000000000000000000000000000000..53d22ccb4cb3989c2a119671c0bd19398781b2b7
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/03_DataCleaning/SBPOPcleanPopPKdata.m
@@ -0,0 +1,211 @@
+function [datanew] = SBPOPcleanPopPKdata(data,removeSUBJECT,removeREC,Nobs,covNames,catNames,catImputationValues,options)
+% [DESCRIPTION]
+% This function is a wrapper for different cleaning functions. Calling 
+% - SBPOPcleanRemoveRecordsSUBJECTs
+% - SBPOPcleanRemovePlaceboSubjects
+% - SBPOPcleanRemoveFewObsSubjects
+% - SBPOPcleanImputeCovariates
+%
+% The data need to be provided, following the standard dataspec, defined in
+% the help to the function SBPOPcheckDataFormat, so please look there for
+% more information.   
+% 
+% [SYNTAX]
+% [datanew] = SBPOPcleanPopPKdata(data,removeSUBJECT,removeREC,nObs,covNames,catNames,catImputationValues)
+% [datanew] = SBPOPcleanPopPKdata(data,removeSUBJECT,removeREC,nObs,covNames,catNames,catImputationValues,options)
+%
+% [INPUT]
+% data:           MATLAB PKPD dataset in standard data spec format  
+% removeSUBJECT:  Cell-matrix with 2 columns. First column contains the
+%                 STYSID1A unique identifiers of the subjects to be removed
+%                 from the dataset. The second column contains strings,
+%                 which define the reason why this subject is removed.
+% removeREC:      Cell-matrix with 2 columns. First column contains the indices
+%                 of the records to be removed from the dataset. The second
+%                 column contains strings, which define the reason why this
+%                 record is removed.
+% Nobs:           All subjects from the dataset which do have <= Nobs
+%                 observation records from TYPE=1 (PK observations) with MDV=0 are removed.
+% covNames:       Cell-array with names of continuous covariates
+% catNames:       Cell-array with names of categorical covariates
+% catImputationValues:     Vector with same length as catNames, specifying
+%                 the imputation values for these categorical covariates (if
+%                 needed)
+% options:        MATLAB structure with additional options
+%
+%                 options.FLAG_LLOQ:   =0: remove BLLOQ, =1: keep LLOQ data use CENS=1 and DV=LLOQ
+%                                      =2: keep LLOQ data, DV=LLOQ/2, CENS=0, remove all but first LLOQ in suite                                      
+%                                      data (default: 0)
+%                 options.keepPlacebo: =0: do not keep placebo subjects, =1: do keep (default: 0)
+%                 options.removeFewObjects: =1: do remove subjects with few observations, =0: do not remove them (default: 1)
+%                 options.outputPath:  path where
+%                                      outputs are exported to. Default:
+%                                      '../Output/DataCleaning/';
+%
+% [OUTPUT]
+% datanew:        cleaned dataset 
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 9th May 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MODESIM, MATLAB R2009a
+%
+% [KEYWORDS]
+% MATLAB, SBPOP, dataexploration, datacleaning
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle options
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try outputPath  			= [options.outputPath '/']; 	catch, outputPath = '../Output/DataCleaning/';  end; %#ok<*CTCH>
+try FLAG_LLOQ               = options.FLAG_LLOQ;            catch, FLAG_LLOQ = 0;                           end; %#ok<*CTCH>
+try keepPlacebo 			= options.keepPlacebo;          catch, keepPlacebo = 0;                         end; %#ok<*CTCH>
+try removeFewObjects 		= options.removeFewObjects;     catch, removeFewObjects = 1;                    end; %#ok<*CTCH>
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create output folder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[p,f,e] = fileparts(outputPath);
+warning off
+mkdir(p);
+warning on
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run SBPOPcleanRemoveRecordsSUBJECTs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+filename = [outputPath '01_Data_Cleaning_Manual.txt'];
+datanew = SBPOPcleanRemoveRecordsSUBJECTs(data,removeSUBJECT,removeREC,filename);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run SBPOPcleanRemovePlaceboSubjects
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~keepPlacebo, 
+	% remove placebo patients
+	filename = [outputPath '02_Data_Cleaning_Placebo_Subjects.txt'];
+	datanew = SBPOPcleanRemovePlaceboSubjects(datanew,filename);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle LLOQ in the desired way (neglect ULOQ for now) - ONLY PK data!
+% FLAG_LLOQ = 0: remove LLOQ data
+% FLAG_LLOQ = 1: use CENS=1 and add LLOQ into DV
+% FLAG_LLOQ = 2: use CENS=0, remove all but first LLOQ value, set DV to LLOQ/2
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% Create a CENS column 
+datanew.CENS = zeros(length(datanew),1);
+ixLLOQ = find(datanew.DV < datanew.LLOQ & datanew.TYPE==1);
+datanew.CENS(ixLLOQ) = 1;
+
+if FLAG_LLOQ==0,
+    % REMOVE all LLOQ PK data
+    % Get the BLOQ data
+    dataBLLOQ = datanew(datanew.CENS==1,:);
+    % Remove the BLOQ data
+    datanew(datanew.CENS==1,:) = [];
+    % Save the removed data in the output path
+    datafilenameBLLOQ = [outputPath '03_removed_BLLOQ_data.csv'];
+    SBPOPexportCSVdataset(dataBLLOQ,datafilenameBLLOQ);
+    disp('The following BLOQ data were removed:');
+    disp('=====================================');
+    dataBLLOQ
+elseif FLAG_LLOQ==1,
+    % Use CENS as in Monolix with LLOQ in DV
+    datanew.DV(ixLLOQ) = datanew.LLOQ(ixLLOQ);
+    disp('The BLOQ PK data were kept and the DV values were set to LLOQ, CENS=1');
+    disp('=====================================================================');
+elseif FLAG_LLOQ==2,
+    % Set DV for PK below LLOQ values to 0.5*LLOQ and remove subsequent ones
+    % A CENS column will be present in the dataset but not used (all 0)
+    % Find LLOQ PK values
+    % Cycle through each subject
+    allID = unique(datanew.ID);
+    dataX = dataset();
+    dataRemoved = dataset();
+    dataDVset   = dataset();
+    for k=1:length(allID),
+        datak       = datanew(datanew.ID==allID(k),:);
+        dataPK      = datak(datak.TYPE==1,:);
+        dataNOTPK   = datak(datak.TYPE~=1,:);
+        % Check if PK BLOQ available
+        ix_PK_LLOQ = find(dataPK.CENS);
+        if ~isempty(ix_PK_LLOQ),
+            dataPKold = dataPK;
+            % Set DV to half the LLOQ value
+            dataPK.DV(ix_PK_LLOQ) = 0.5*dataPK.LLOQ(ix_PK_LLOQ);
+            % See if consecutive readouts available - if yes then remove all subsequent ones
+            delta = [NaN; diff(ix_PK_LLOQ)];
+            ix_consequtive = ix_PK_LLOQ(find(delta==1));
+            % Save records to be removed
+            dataRemoved = [dataRemoved; dataPKold(ix_consequtive,:)];
+            % Save records for which DV set to LLOQ/2
+            dataDVset = [dataDVset; dataPKold(ix_PK_LLOQ(find(delta~=1)),:)];
+            
+            % Remove records
+            dataPK(ix_consequtive,:) = [];
+        end
+        % Combine
+        datak = [dataPK; dataNOTPK];
+        dataX = [dataX; datak];
+    end
+    % Sort
+    datanew = sortrows(dataX,{'ID','TIME','TYPE','SUBTYPE'});
+    % Reset CENS column to 0
+    datanew.CENS(1:end) = 0;
+    % Save the removed data in the output path
+    datafilenameBLLOQ_REMOVED = [outputPath '03_removed_consequtive_BLLOQ_data.csv'];
+    SBPOPexportCSVdataset(dataRemoved,datafilenameBLLOQ_REMOVED);
+    datafilenameBLLOQ_DVset = [outputPath '03_DVset_BLLOQ_data.csv'];
+    SBPOPexportCSVdataset(dataDVset,datafilenameBLLOQ_DVset);
+    disp('The following BLOQ PK data were removed:');
+    disp('========================================');
+    dataRemoved
+    disp('The following BLOQ PK data obtained DV=LLOQ/2:');
+    disp('==============================================');
+    dataDVset
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run SBPOPcleanRemoveFewObsSubjects
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if removeFewObjects,
+	type = 1; % PK is TYPE=1
+	filename = [outputPath '04_Data_Cleaning_Few_Observations.txt'];
+	datanew = SBPOPcleanRemoveFewObsSubjects(datanew,Nobs,type,filename);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run SBPOPcleanImputeCovariates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+filename = [outputPath '05_Covariate_Imputation.txt'];
+datanew  = SBPOPcleanImputeCovariates(datanew,covNames,catNames,catImputationValues,filename);
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/04_DataConversion/SBPOPconvert2popPKdataset.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/04_DataConversion/SBPOPconvert2popPKdataset.m
new file mode 100644
index 0000000000000000000000000000000000000000..274aabda98cf06137ef2889e8356db24c53b4766
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/04_DataConversion/SBPOPconvert2popPKdataset.m
@@ -0,0 +1,162 @@
+function [dataheader,datapopPK] = SBPOPconvert2popPKdataset(data,covNames,catNames,filename)
+% [DESCRIPTION]
+% This function converts the given dataset in "data" into a popPK dataset.
+% The datapopPK dataset will contain a subset of the columns in the
+% original dataset, sufficient to perform a popPK analysis. All records
+% that are not of TYPE=0 (dose) or TYPE=1 (PK) will be removed. A YTYPE
+% column will be added.
+% 
+% The data need to be provided, following the standard dataspec, defined in
+% the help to the function SBPOPcheckDataFormat, so please look there for
+% more information.   
+%
+% Additional removals:
+% Since NONMEM crashes when dose records with AMT=0 are present in the
+% dataset, these are removed.
+%
+% [SYNTAX]
+% [dataheader,datapopPK] = SBPOPconvert2popPKdataset(data,covNames,catNames)
+% [dataheader,datapopPK] = SBPOPconvert2popPKdataset(data,covNames,catNames,filename)
+%
+% [INPUT]
+% data:         MATLAB PKPD dataset in standard data spec format  
+% covNames:     Cell-array with names of continuous covariates
+% catNames:     Cell-array with names of categorical covariates
+% filename:     Filename, including path for saving the popPK dataset as
+%               CSV file. If not specified, then not exported to file.
+%
+% [OUTPUT]
+% dataheader:           Data header (Monolix style, but also used for NONMEM project generation)
+% datapopPK:            PopPK dataset
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 9th May 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MODESIM, MATLAB R2009a
+%
+% [KEYWORDS]
+% MATLAB, SBPOP, dataexploration, datacleaning
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle optional input argument
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin==3,
+    filename = '';
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Copy data
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+datanew = data;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Remove all non dose and non PK records
+% Dose defined by TYPE=0, PK by TYPE=1
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+datanew(datanew.TYPE>1,:) = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Remove 0 dose records
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+datanew(datanew.EVID==1 & datanew.AMT==0,:) = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add a YTYPE column (not needed for single output but might add support of
+% multiple error models based on subgroupings of data)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+datanew.YTYPE = datanew.TYPE;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create RATE column
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+datanew.RATE = datanew.AMT./datanew.TINF;
+datanew.RATE(isnan(datanew.RATE)) = 0;
+datanew.RATE(isinf(abs(datanew.RATE))) = 0;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check CENS column
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Output some info for the user
+if sum(abs(datanew.CENS)) ~= 0,
+    disp('IMPORTANT: left and/or right censoring present in the dataset.');
+    disp('           Please make sure the DV values are correctly set to LLOQ or ULOQ values when censored.');
+    disp('           ALSO NOTE THAT FOR NONMEM THE "CENS" COLUMN WILL NOT BE CONSIDERED!');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define initial structure of popPK dataset
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+varNamesData = get(datanew,'VarNames');
+varNames = {'ID' 'STYSID1A' 'STUDY' 'TIME' 'TIMEPOS' 'TIME_UNIT' 'TYPE' 'SUBTYPE' 'NAME' 'DV' 'UNIT' 'MDV' 'EVID' 'CENS' 'AMT'  'ADM' 'RATE' 'DOSE' 'TRT' 'YTYPE'};
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add covariates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+varNames = [varNames covNames(:)' catNames(:)'];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create popPK dataset in defined structure
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+datapopPK = dataset();
+for k=1:length(varNames),
+    datapopPK.(varNames{k}) = datanew.(varNames{k});
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Export dataset to CSV if desired
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(filename),
+    % Create output folder if not yet existing
+    [p,f,e] = fileparts(filename);
+    warning off
+    mkdir(p);
+    warning on
+
+    SBPOPexportCSVdataset(datapopPK,[strrep(filename,'.csv','') '.csv']);
+
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Load dataset as text,
+    % exchange spaces to ":::" and save as text
+    % Then NONMEM can handle chars in columns ... for UNIT, TIME_UNIT, NAME
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    content = fileread([strrep(filename,'.csv','') '.csv']);
+    content = strrep(content,' ',':::');
+    fid = fopen([strrep(filename,'.csv','') '.csv'],'w');
+    fprintf(fid,'%s',content);
+    fclose(fid);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get header
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dataheader = SBPOPgetMonolixDataHeader(datapopPK,covNames,catNames);
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/05_ModelBuilding/SBPOPbuildPopPKModelSpace.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/05_ModelBuilding/SBPOPbuildPopPKModelSpace.m
new file mode 100644
index 0000000000000000000000000000000000000000..1a236fae30e58fd30ecc46eb4452d8f07b0572cd
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/05_ModelBuilding/SBPOPbuildPopPKModelSpace.m
@@ -0,0 +1,262 @@
+function [MODEL_INFO,RESULTS] = SBPOPbuildPopPKModelSpace(nameSpace, modeltest, analysisDatasetFile, dataheaderNLME, optionsNLME, optionsModelSpace)
+% [DESCRIPTION]
+% This functions allows to assess a user defined popPK model subspace.
+% Models within this subspace will be created / run / results will be
+% imported / fitness assessments will be generated / table to compare
+% different models will also be generated.
+% 
+% Since this function is quite comprehensive, it is impossible to handle
+% ALL possible PK model structures. The goal is to handle the most common
+% ones. Applying the Pareto principle.
+%
+% Currently covered are:
+%  1,2,3 compartmental IV, Bolus, 1st order absorption models
+%  IV, Bolus and absorption can happen in the same dataset
+%  Linear and linear+saturable clearance
+%  Lagtime on 1st order absorption
+%
+% Assumptions:
+% - Covariates always log transformed and centered by the median
+% - All parameters (except Fabs1) log normally distributed random effects
+% - Fabs1 also log-normally distributed random effect - but can be changed in SBPOPbuildPopPKModelSpace to logitnormally
+%
+% [SYNTAX]
+% [MODEL_INFO] = SBPOPbuildPopPKModelSpace(nameSpace, modeltest, analysisDatasetFile, dataheaderNLME)
+% [MODEL_INFO] = SBPOPbuildPopPKModelSpace(nameSpace, modeltest, analysisDatasetFile, dataheaderNLME, optionsNLME)
+% [MODEL_INFO] = SBPOPbuildPopPKModelSpace(nameSpace, modeltest, analysisDatasetFile, dataheaderNLME, optionsNLME, optionsModelSpace)
+%
+% [INPUT]
+% nameSpace:                                Unique identifier for giving the output folders and files a name
+% modeltest:                                Matlab structure with model space information
+%
+%    DEFINITIONS REQUIRED FOR:
+%       modeltest.numberCompartments        = [1 2 3];                          Define number of compartments to test
+%       modeltest.errorModels               = {'const','comb1','prop','exp'};   Define residual error models to test
+%       modeltest.errorParam0:                Vector allowing to pass initial guesses for error model parameters. Same order as error models. 
+%                                             'const': a, 'prop': b, 'comb1': a,b
+%
+%       modeltest.saturableClearance        = [0 1];                            Test both linear and linear+saturable clearance
+%       modeltest.lagTime                   = [0 1];                            Test both no lag time and lagtime
+%       modeltest.FACTOR_UNITS              = 1;                                Conversion factor for dose and concentration units
+%       modeltest.POPvalues0                = [ 0.5   0.2   2    10    10    10   10   0.5    5    0.2    0.5];
+%                                             This can also be a cell-array with multiple vectors for initial guesses
+%       modeltest.POPestimate               = [  0     1    1     1     1     1   1     1     1     0       0];
+%                                             This can also be a cell-array with multiple vectors for estimation definitions
+%       modeltest.IIVestimate               = [  0     1    1     1     1     1   1     1     1     0       0];
+%                                             This can also be a cell-array with multiple vectors for estimation definitions
+%  			                                    0: IIV not estimated (IIVvalues0 not used) 
+%           			                        1: IIV estimated (IIVvalues0 as starting guesses)
+%                       		                2: IIV not estimated but fixed on IIVvalues0 value
+%
+%    DEFINITIONS OPTIONAL FOR:
+%       modeltest.IIVvalues0                = [  1     1    1     1     1     1   1     1     1     1       1];
+%                                             This should always be only a vector - no need for testing different initial guesses here
+%                                             It is optional. By default all IIVs start on 1
+%       modeltest.covarianceModels          = Can be a cell-array - all definitions will be combined with all others
+%
+%       modeltest.covariateModels           = Can be a cell-array - all definitions will be combined with all others
+%       modeltest.covariateModelValues      = Can be a cell-array - will not be combined with all others but will be matched with covariateModels
+%                                             If not defined all covariate coefficient estimations start from 0
+%       modeltest.COVestimate               = Can be a cell-array - will not be combined with all others but will be matched with covariateModels
+%                                             If not defined all covariate coefficient are estimated
+%
+% analysisDatasetFile:                      Relative path including filename to the popPK dataset from where this function is called 
+%
+% dataheaderNLME:                           Data set header definition for Monolix and NONMEM
+%
+% optionsNLME: Options for algorithm settings
+%       optionsNLME.parameterEstimationTool: Define to use NONMEM or MONOLIX. 'NONMEM' or 'MONOLIX' (default) as entries. 
+%
+%       optionsNLME.N_PROCESSORS_PAR:       Number of parallel model runs (default: 1)
+%       optionsNLME.N_PROCESSORS_SINGLE:    Number of processors to parallelize single run (if NONMEM and MONOLIX allow for it) (default: 1)
+%
+%       optionsNLME.algorithm.SEED:         Seed setting. Defualt: 123456
+%       optionsNLME.algorithm.K1:           First iterations. Default: 500
+%       optionsNLME.algorithm.K2:           Final iterations. Default: 200
+%       optionsNLME.algorithm.K1_AUTO:      Automatic first iteration number (0: off, 1: on). Default: 0
+%       optionsNLME.algorithm.K2_AUTO:      Automatic final iteration number (0: off, 1: on). Default: 0
+%       optionsNLME.algorithm.NRCHAINS:     Number of parallel chains. Default: 1
+%
+%    NONMEM specific
+%       optionsNLME.algorithm.METHOD:                 'FO','FOCE', or 'FOCEI'
+%       optionsNLME.algorithm.ITS:                    Allow to run an ITS method as first method befor all other methods (METHOD)
+%                                                     ITS = 0 or 1 (default: 0) - ITS=1 only accepted if not FO!
+%       optionsNLME.algorithm.ITS_ITERATIONS:         Number of iterations for ITS (default: 10)
+%       optionsNLME.algorithm.IMPORTANCESAMPLING:     Allow determination of the OFV - only accepted after SAEM
+%                                                     Default: 0, If 1 then do the importance sampling
+%       optionsNLME.algorithm.IMP_ITERATIONS:         Number of iterations for importance sampling (default: 5)
+%
+%    Monolix specific
+%       optionsNLME.algorithm.LLsetting:                'linearization' (default) or 'importantsampling'
+%       optionsNLME.algorithm.FIMsetting:               'linearization' (default) or 'stochasticApproximation'
+%       optionsNLME.algorithm.INDIVparametersetting:    'conditionalMode' (default) ... others not considered for now. 
+%
+% optionsModelSpace:            Structure with additional optional information
+%       optionsModelSpace.buildModelsOnly:      =0 (default): build models and run them. =1: build models only, but to not run them
+%       optionsModelSpace.Ntests:               Number of tests to perform (default=1)
+%       optionsModelSpace.createGOFplots:       Only used if Ntests>1. =0: don't, =1: do (default: 0)
+%       options.std_noise_setting:              Standard deviation to use to add noise to the initial parameter guesses (default=0.5 (50%CV))
+%                                               Normal:         Parameter_guess + std_noise_setting*Parameter_guess*randomNumbers(0-1)
+%                                               Lognormal:      Parameter_guess * exp(std_noise_setting*randomNumbers(0-1))
+%                                               Logitnormal:    Similar and between 0-1
+%
+% [OUTPUT]
+% - All PK models are created in the ['../Models/' nameSpace 'model'] folder 
+% - A modelInfo.txt file is written into the ['../Models/' nameSpace 'model'] folder, detailing what the different models contain
+% - Fit analysis plots are produced and stored in the ['../Output/FitAnalysis/' nameSpace 'model/Plots'] folder
+% - Text results for parameters are produced in the ['../Output/FitAnalysis/' nameSpace 'model/Info'] folder 
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 2nd March, 2013
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define parameternames in ODE and ANALYTIC models 
+% NONLINEAR parameters need to be at the end!!!!
+% Its the required order ... checks for ODE models will be done.
+% MONOLIX works with an analytic template. For NONMEM no analytic template
+% can be used, since numerics horribly bad. Individual ADVANs will be
+% generated automaticall instead.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+TemplateModels = [];
+TemplateModels.ParameterNames.ODE       = {'CL', 'Vc', 'Q1', 'Vp1', 'Q2', 'Vp2', 'Fiv', 'Fabs1', 'ka', 'Tlag_input1', 'VMAX', 'KM'};
+TemplateModels.IIVdistribution.ODE      = { 'L',  'L',  'L',   'L',  'L',   'L',   'L',     'L',  'L',           'L',    'L',  'L'};
+TemplateModels.ParameterNames.ANALYTIC  = {'CL', 'Vc', 'Q1', 'Vp1', 'Q2', 'Vp2', 'Fiv', 'Fabs1', 'ka', 'Tlag_input1'};
+TemplateModels.IIVdistribution.ANALYTIC = { 'L',  'L',  'L',   'L',  'L',   'L',   'L',     'L',  'L',           'L'};
+TemplateModels.Model.MONOLIX.ANALYTIC   = 'template_popPK_model_ANALYTIC_MLXTRAN.txt';
+TemplateModels.Model.ODE                = 'template_popPK_model.txt';
+TemplateModels.Model.DOSING             = 'template_popPK_dosing.dos';
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle some optional things
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try buildModelsOnly         = optionsModelSpace.buildModelsOnly;        catch, buildModelsOnly          = 0;           end
+try Ntests                  = optionsModelSpace.Ntests;                 catch, Ntests                   = 1;           end
+try std_noise_setting       = optionsModelSpace.std_noise_setting;      catch, std_noise_setting        = 0.5;         end
+try createGOFplots          = optionsModelSpace.createGOFplots;         catch, createGOFplots           = 0;           end
+try parameterEstimationTool = optionsNLME.parameterEstimationTool;      catch, parameterEstimationTool  = 'MONOLIX';   end
+try N_PROCESSORS_PAR        = optionsNLME.N_PROCESSORS_PAR;             catch, N_PROCESSORS_PAR         = 1;           end
+try N_PROCESSORS_SINGLE     = optionsNLME.N_PROCESSORS_SINGLE;          catch, N_PROCESSORS_SINGLE      = 1;           end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check NLME tool to be used
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp(lower(parameterEstimationTool),'monolix'),
+    FLAG_NONMEM = 0;
+elseif strcmp(lower(parameterEstimationTool),'nonmem'),
+    FLAG_NONMEM = 1;
+else
+    error('Unknown NLMETOOL input argument.');
+end
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define output location and project name settings
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modelProjectsFolder             = ['../Models/' nameSpace];
+dataRelPathFromProjectPath      = '../../../Data';
+PROJECT_PREFIX                  = ['FIT' nameSpace '_'];
+FitInfoOutputFolder             = ['../Output/FitAnalysis/' nameSpace];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Perturb Ntests popvalues
+% Allow perturbation only of fixed effects that are also estimated.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if Ntests > 1,
+    % Repeated fits from different initial guesses desired
+    popvalues0  = modeltest.POPvalues0;
+    popestimate = modeltest.POPestimate;
+    iivestimate = modeltest.IIVestimate;
+    % Check if single set of initial guesses given, otherwise error
+    if iscell(popvalues0),
+        if length(popvalues0) > 1,
+            error('The repeated fit setting in "optionsModelSpace" can only be used if "modeltest.POPvalues0" given as a single vector.');
+        else
+            popvalues0 = popvalues0{1};
+        end
+    end
+    if ~isvector(popvalues0),
+        error('The repeated fit setting in "optionsModelSpace" can only be used if "modeltest.POPvalues0" given as a single vector.');
+    end
+    if ~isvector(popestimate),
+        error('The repeated fit setting in "optionsModelSpace" can only be used if "modeltest.POPestimate" given as a single vector, not as a cell-array!');
+    end
+    if ~isvector(iivestimate),
+        error('The repeated fit setting in "optionsModelSpace" can only be used if "modeltest.IIVestimate" given as a single vector, not as a cell-array!');
+    end
+    
+    % Get info about parameters where perturbation allowed 
+    randomize_parameters = popestimate;
+    
+    popvaluesnew = {};
+    % Do sample log-normally distributed parameters 
+    for k=1:Ntests,
+        POPvalues0_sampled                          = popvalues0;
+
+        % Handle log-normal distributions
+        ix_lognormal_sampled                        = find(strcmp(TemplateModels.IIVdistribution.ODE,'L').*randomize_parameters);
+        MU                                          = log(popvalues0(ix_lognormal_sampled));
+        XXX                                         = MU + std_noise_setting.*randn(1,length(ix_lognormal_sampled));
+        POPvalues0_sampled(ix_lognormal_sampled)    = exp(XXX);
+        
+        % Handle logit-normal distributions
+        ix_logitnormal_sampled                      = find(strcmp(TemplateModels.IIVdistribution.ODE,'G').*randomize_parameters);
+        MU                                          = log(popvalues0(ix_logitnormal_sampled)./(1-popvalues0(ix_logitnormal_sampled)));
+        XXX                                         = MU + std_noise_setting.*randn(1,length(ix_logitnormal_sampled));
+        POPvalues0_sampled(ix_logitnormal_sampled)  = exp(XXX)./(1+exp(XXX));
+        
+        % Save sampled starting guesses in cell-array
+        popvaluesnew{k}                             = POPvalues0_sampled;
+    end
+    
+    % Update modeltest structure with sampled starting guesses
+    modeltest.POPvalues0 = popvaluesnew;  
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create the popPK model projects 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[MODEL_INFO,text_MODEL_INFO] = buildPKmodelSpaceSBPOP(FLAG_NONMEM,TemplateModels,modelProjectsFolder, dataRelPathFromProjectPath, PROJECT_PREFIX,...
+                               analysisDatasetFile, dataheaderNLME, modeltest, optionsNLME);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Return if only building models desired
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if buildModelsOnly,
+    return
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run the popPK model projects
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBPOPrunNLMEprojectFolder(modelProjectsFolder,N_PROCESSORS_PAR,N_PROCESSORS_SINGLE);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create model comparison tables in FitInfoOutputFolder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+RESULTS = SBPOPfitanalysisProjectsFolderInfo(modelProjectsFolder,FitInfoOutputFolder);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Save text_MODEL_INFO also in fit analysis Info
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fidInfo=fopen([FitInfoOutputFolder '/modelInfo.txt'],'w');
+fprintf(fidInfo,'%s',text_MODEL_INFO);
+fclose(fidInfo);
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/05_ModelBuilding/auxiliary/buildPKmodelSpaceSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/05_ModelBuilding/auxiliary/buildPKmodelSpaceSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..36892bd5cd72d046aac5361e54bd345481bfb269
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/05_ModelBuilding/auxiliary/buildPKmodelSpaceSBPOP.m
@@ -0,0 +1,281 @@
+function [MODEL_INFO,text_MODEL_INFO] = buildPKmodelSpaceSBPOP(FLAG_NONMEM,TemplateModels,modelProjectsFolder, dataRelPathFromProjectPath, PROJECT_PREFIX, ...
+                analysisDatasetFile, dataheaderNLME, modeltest, options)
+% [DESCRIPTION]
+% buildPKmodelSpaceSBPOP: creates a subspace of popPK model projects for
+% Monlix, based on user settings.
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 1st March, 2013
+
+% Information:
+% ============
+% Copyright (C) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle REQUIRED "modeltest" input arguments 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%       
+try numberCompartments      = modeltest.numberCompartments;      catch, error('Please specify "modeltest.numberCompartments".');    end %#ok<*CTCH>
+try errorModels             = modeltest.errorModels;             catch, error('Please specify "modeltest.errorModels".');           end
+try saturableClearance      = modeltest.saturableClearance;      catch, error('Please specify "modeltest.saturableClearance".');    end
+try lagTime                 = modeltest.lagTime;                 catch, error('Please specify "modeltest.lagTime".');               end
+try FACTOR_UNITS            = modeltest.FACTOR_UNITS;            catch, error('Please specify "modeltest.FACTOR_UNITS".');          end
+try POPvalues0              = modeltest.POPvalues0;              catch, error('Please specify "modeltest.POPvalues0".');            end
+try POPestimate             = modeltest.POPestimate;             catch, error('Please specify "modeltest.POPestimate".');           end
+try IIVestimate             = modeltest.IIVestimate;             catch, error('Please specify "modeltest.IIVestimate".');           end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle OPTIONAL "modeltest" input arguments values
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%       
+try IIVvalues0              = modeltest.IIVvalues0;              catch, IIVvalues0             = 0.5*ones(1,length(TemplateModels.ParameterNames.ODE));   end
+try covarianceModels        = modeltest.covarianceModels;        catch, covarianceModels       = '';   end %#ok<*CTCH>
+try covariateModels         = modeltest.covariateModels;         catch, covariateModels        = '';   end
+try covariateModelValues    = modeltest.covariateModelValues;    catch, covariateModelValues   = {};   end %#ok<*CTCH>
+try COVestimate             = modeltest.COVestimate;             catch, COVestimate            = {};   end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Adjust potential strings to cell-arrays if required as cell-arrays
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%       
+if ischar(covarianceModels), covarianceModels = {covarianceModels}; end
+if ischar(covariateModels),  covariateModels  = {covariateModels};  end
+if ischar(errorModels),      errorModels      = {errorModels};      end
+if ~iscell(IIVestimate),     IIVestimate      = {IIVestimate};      end
+if ~iscell(POPestimate),     POPestimate      = {POPestimate};      end
+if ~iscell(POPvalues0),      POPvalues0       = {POPvalues0};       end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if errorParam0 is defined and check if correctly
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%       
+try errorParam0             = modeltest.errorParam0;             catch, errorParam0 = cell(1,length(errorModels)); end
+if ~iscell(errorParam0),      errorParam0      = {errorParam0};      end
+if length(errorParam0) ~= length(errorModels),
+    error('Incorrect number of errorParam0 entries - need to match errorModels.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Adjust covariateModelValues and COVestimate
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%       
+if length(covariateModels) == 1 && length(covariateModelValues) ~= 1,
+    covariateModelValues ={covariateModelValues};
+end
+if length(covariateModels) == 1 && length(COVestimate) ~= 1,
+    COVestimate ={COVestimate};
+end
+
+if isempty(covariateModelValues),
+    covariateModelValues = cell(length(covariateModels),1);
+end
+if isempty(COVestimate),
+    COVestimate = cell(length(covariateModels),1);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check covariateModelValues and COVestimate
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%       
+if length(covariateModelValues) ~= length(covariateModels),
+    error('modeltest.covariateModelValues needs to have same length as modeltest.covariateModels.');
+end
+if length(COVestimate) ~= length(covariateModels),
+    error('modeltest.covariateModelValues needs to have same length as modeltest.covariateModels.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle Monolix/NONMEM default options
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%       
+optionsNLME                                     = [];
+try optionsNLME.algorithm.SEED                  = options.algorithm.SEED;                   catch, optionsNLME.algorithm.SEED                   = 123456;               end
+try optionsNLME.algorithm.K1                    = options.algorithm.K1;                     catch, optionsNLME.algorithm.K1                     = 500;                  end
+try optionsNLME.algorithm.K2                    = options.algorithm.K2;                     catch, optionsNLME.algorithm.K1                     = 200;                  end
+try optionsNLME.algorithm.K1_AUTO               = options.algorithm.K1_AUTO;                catch, optionsNLME.algorithm.K1_AUTO                = 0;                    end
+try optionsNLME.algorithm.K2_AUTO               = options.algorithm.K2_AUTO;                catch, optionsNLME.algorithm.K2_AUTO                = 0;                    end
+try optionsNLME.algorithm.NRCHAINS              = options.algorithm.NRCHAINS;               catch, optionsNLME.algorithm.NRCHAINS               = 1;                    end
+% NOPNMEM specific
+try optionsNLME.algorithm.IMPORTANCESAMPLING    = options.algorithm.IMPORTANCESAMPLING;     catch, optionsNLME.algorithm.IMPORTANCESAMPLING     = 0;                    end
+try optionsNLME.algorithm.METHOD                = options.algorithm.METHOD;                 catch, optionsNLME.algorithm.METHOD                 = 'SAEM';               end
+try optionsNLME.algorithm.ITS                   = options.algorithm.ITS;                    catch, optionsNLME.algorithm.ITS                    = 0;                    end
+% Monolix specific
+try optionsNLME.algorithm.LLsetting             = options.algorithm.LLsetting;              catch, optionsNLME.algorithm.LLsetting              = 'linearization';      end
+try optionsNLME.algorithm.FIMsetting            = options.algorithm.FIMsetting;             catch, optionsNLME.algorithm.FIMsetting             = 'linearization';      end
+try optionsNLME.algorithm.INDIVparametersetting = options.algorithm.INDIVparametersetting;  catch, optionsNLME.algorithm.INDIVparametersetting  = 'conditionalMode';    end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Load dataset, and check data format
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%       
+% Load dataset
+analysisDataset         = SBPOPloadCSVdataset(analysisDatasetFile);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check unsupported administration routes
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%       
+ADMunique = unique(analysisDataset.ADM);
+if sum(ADMunique>2)~=0,
+    error('Unknown/unsupported ADM entries in dataset. 0: observation, 1: 1st order absorption, 2: IV (bolus or infusion).');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Remove and create the folder in which to create the NLME projets
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+warning off; %#ok<*WNOFF>
+try rmdir(modelProjectsFolder,'s'); catch, end; mkdir(modelProjectsFolder);
+warning on; %#ok<*WNON>
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Open model Info Text file for output (create folder if non existent)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+text_MODEL_INFO = sprintf('==================================================================================================================================================================================================================================\n'); 
+text_MODEL_INFO = sprintf('%s%s     Nr Compartments   Error model             Clearance      Lagtime       Type  POPestimate                       IIVestimate                          Covariance Model / Covariate Model                        Initial guesses\n',text_MODEL_INFO,preFillCharSB('MODEL',length(PROJECT_PREFIX)+1,' '));
+text_MODEL_INFO = sprintf('%s==================================================================================================================================================================================================================================\n',text_MODEL_INFO);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Build the defined model space
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+count               = 0;
+MODEL_INFO          = [];
+
+% Cycle through all covariate definitions
+for kcovariates = 1:length(covariateModels),
+    
+    % Cycle through all covariance definitions
+    for kcovariances = 1:length(covarianceModels),
+        
+        % Cycle through all compartment definitions
+        for kcompartments=1:length(numberCompartments),
+            
+            % Cycle through all error model definitions
+            for kerrormodels=1:length(errorModels),
+                errorParam0_k = errorParam0{kerrormodels};
+                
+                % Cycle through all clearance definitions
+                for kclearance=1:length(saturableClearance),
+                    
+                        % Cycle through all lagtime definitions
+                        for klagtime=1:length(lagTime),
+                            
+                            % Cycle through POPestimate
+                            for kpopestimate=1:length(POPestimate),
+                                
+                                % Cycle through IIVestimate
+                                for kiivestimate=1:length(IIVestimate),
+                                    
+                                    % Cycle through POPvalues0
+                                    for kpopvalues=1:length(POPvalues0),
+                                        
+                                        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+                                        % Create Project
+                                        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+                                        count                   = count+1;
+                                        % Get model name
+                                        modelName               = [PROJECT_PREFIX preFillCharSB(count,3,'0')];
+                                        % Get project path
+                                        projectPath             = [modelProjectsFolder '/' modelName];
+                                        % Get data location and header information for monolix
+                                        [p,f,e]                 = fileparts(analysisDatasetFile);
+                                        data                    = [];
+                                        data.path               = p;
+                                        data.filename           = [f e];
+                                        data.header             = dataheaderNLME;
+                                        % Define options
+                                        optionsProject.POPestimate          = POPestimate{kpopestimate};
+                                        optionsProject.POPvalues0           = POPvalues0{kpopvalues};
+                                        optionsProject.IIVdistribution      = {}; % use default => log-normal!
+                                        optionsProject.IIVestimate          = IIVestimate{kiivestimate};
+                                        optionsProject.IIVvalues0           = IIVvalues0;
+                                        optionsProject.errorModels          = errorModels{kerrormodels};
+                                        optionsProject.covarianceModel      = covarianceModels{kcovariances};
+                                        
+                                        optionsProject.covariateModel       = covariateModels{kcovariates};
+                                        optionsProject.covariateModelValues = covariateModelValues{kcovariates};
+                                        optionsProject.COVestimate          = COVestimate{kcovariates};
+                                        
+                                        optionsProject.algorithm             = optionsNLME.algorithm;
+                                        optionsProject.SILENT                = 1;
+                                        
+                                        optionsProject.errorParam0           = errorParam0_k;
+                                        
+                                        % Create the project after specification
+                                        [FLAGanalyticModel,MODEL_SETTINGS] = createPopPK_NLMEproject_ODE_Analytic_SBPOP(...
+                                            FLAG_NONMEM,modelName,TemplateModels, FACTOR_UNITS,...
+                                            numberCompartments(kcompartments),saturableClearance(kclearance), ...
+                                            lagTime(klagtime),...
+                                            data,projectPath,dataRelPathFromProjectPath,optionsProject);
+                                       
+                                        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+                                        % Print out a list with model information
+                                        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+                                        clearanceText = 'Linear';
+                                        if saturableClearance(kclearance)==1,
+                                            clearanceText = 'Linear+Saturable';
+                                        end
+                                        lagtimeText   = 'No Tlag';
+                                        if lagTime(klagtime)==1,
+                                            lagtimeText   = 'Tlag on ABS1';
+                                        end
+                                        modelTypeText = 'ODE';
+                                        if FLAGanalyticModel,
+                                            modelTypeText = 'Analytic';
+                                        end
+                                        text_MODEL_INFO = sprintf('%s%s          %d             %s      %s   %s   %s  [%s] [%s] %s / %s   [%s]\n', ...
+                                            text_MODEL_INFO, ...
+                                            modelName, ...
+                                            numberCompartments(kcompartments),...
+                                            preFillCharSB(errorModels{kerrormodels},8,' '), ...
+                                            preFillCharSB(clearanceText,length('Linear+Saturable'),' '), ...
+                                            preFillCharSB(lagtimeText,length('Tlag on ABS1'),' '), ...
+                                            preFillCharSB(modelTypeText,length('Analytic'),' '), ...
+                                            num2str(POPestimate{kpopestimate}), ...
+                                            num2str(IIVestimate{kiivestimate}), ...
+                                            preFillCharSB(MODEL_SETTINGS.covarianceModel,40,' '), ...
+                                            MODEL_SETTINGS.covariateModel, ...
+                                            num2str(POPvalues0{kpopvalues}));
+                                        
+                                        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+                                        % Safe some model info
+                                        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+                                        MODEL_INFO(count).model                           = modelName;
+                                        MODEL_INFO(count).FACTOR_UNITS                    = FACTOR_UNITS;
+                                        MODEL_INFO(count).numberCompartments              = numberCompartments(kcompartments);
+                                        MODEL_INFO(count).saturableClearance              = saturableClearance(kclearance);
+                                        MODEL_INFO(count).lagTime                         = lagTime(klagtime);
+                                        MODEL_INFO(count).clearanceText                   = clearanceText;
+                                        MODEL_INFO(count).lagtimeText                     = lagtimeText;
+                                        MODEL_INFO(count).modelTypeText                   = modelTypeText;
+                                        
+                                        MODEL_INFO(count).POPestimate                     = MODEL_SETTINGS.POPestimate;
+                                        MODEL_INFO(count).POPvalues0                      = MODEL_SETTINGS.POPvalues0;
+                                        MODEL_INFO(count).IIVdistribution                 = MODEL_SETTINGS.IIVdistribution;
+                                        MODEL_INFO(count).IIVestimate                     = MODEL_SETTINGS.IIVestimate;
+                                        MODEL_INFO(count).errorModels                     = MODEL_SETTINGS.errorModels;
+                                        MODEL_INFO(count).covarianceModels                = MODEL_SETTINGS.covarianceModel;
+                                        MODEL_INFO(count).covariateModels                 = MODEL_SETTINGS.covariateModel;
+                                        
+                                        MODEL_INFO(count).FLAGanalyticModel               = FLAGanalyticModel;
+                                        MODEL_INFO(count).TemplateModels                  = TemplateModels;
+                                    end % popvalues0
+                                end % iivestimate
+                            end % popestimate
+                        end % lagtime
+                end % clearance
+            end % error models
+        end % compartments
+    end % covariances
+end % covariates
+% Close the Info file
+fidInfo=fopen([modelProjectsFolder '/modelInfo.txt'],'w');
+fprintf(fidInfo,'%s',text_MODEL_INFO);
+fclose(fidInfo);
+disp(fileread([modelProjectsFolder '/modelInfo.txt']));
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/05_ModelBuilding/auxiliary/createPopPK_MONOLIXprojectSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/05_ModelBuilding/auxiliary/createPopPK_MONOLIXprojectSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..7349ffbc50988430608d7364cef694770d9328dc
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/05_ModelBuilding/auxiliary/createPopPK_MONOLIXprojectSBPOP.m
@@ -0,0 +1,743 @@
+function createPopPK_MONOLIXprojectSBPOP(modelNameFIT,modelName,modelFile,parameterNames,FACTOR_UNITS,data,projectPath,options)
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define Default Properties (Never changing)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+projectName            = 'project';
+resultsFolder          = 'RESULTS';
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try
+    dataRelPathFromProject = data.dataRelPathFromProject;
+    dataFileName           = data.dataFileName;
+    dataHeaderIdent        = data.dataHeaderIdent;
+    
+    % Removal of TIMEPOS in dataHeaderIdent
+    % TIMEPOS only needed for NONMEM ...
+    dataHeaderIdent         = strrep(dataHeaderIdent,',TIMEPOS,',',IGNORE,');    
+catch
+    error('data input argument not defined correctly.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle optional arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try POPestimate                     = options.POPestimate;              catch, POPestimate = [];                             end
+try POPvalues0                      = options.POPvalues0;               catch, POPvalues0 = [];                              end
+try IIVdistribution                 = options.IIVdistribution;          catch, IIVdistribution = {};                         end
+try IIVestimate                     = options.IIVestimate;              catch, IIVestimate = [];                             end
+try IIVvalues0                      = options.IIVvalues0;               catch, IIVvalues0 = [];                              end
+try errorModels                     = options.errorModels;              catch, errorModels = '';                             end
+try errorParam0                     = options.errorParam0;              catch, errorParam0 = [];                             end
+try covarianceModel                 = options.covarianceModel;          catch, covarianceModel = 'diagonal';                 end
+try covariateModel                  = options.covariateModel;           catch, covariateModel = '';                          end
+try covariateModelValues            = options.covariateModelValues;     catch, covariateModelValues = {};                    end
+try COVestimate                     = options.COVestimate;              catch, COVestimate = {};                             end
+try SEED                            = options.algorithm.SEED;           catch, SEED = 123456;                                end
+try K1                              = options.algorithm.K1;             catch, K1 = 500;                                     end
+try K2                              = options.algorithm.K2;             catch, K2 = 200;                                     end
+try K1_AUTO                         = options.algorithm.K1_AUTO;        catch, K1_AUTO = 0;                                  end
+try K2_AUTO                         = options.algorithm.K2_AUTO;        catch, K2_AUTO = 0;                                  end
+try NRCHAINS                        = options.algorithm.NRCHAINS;       catch, NRCHAINS = 1;                                 end
+try SILENT                          = options.SILENT;                   catch, SILENT = 0;                                   end
+try INDIVparametersetting           = options.algorithm.INDIVparametersetting;    catch, INDIVparametersetting = 'conditionalMode';    end
+try LLsetting                       = options.algorithm.LLsetting;      catch, LLsetting = 'linearization';                  end
+try FIMsetting                      = options.algorithm.FIMsetting;     catch, FIMsetting = 'linearization';                 end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Convert covariate model into different syntax
+% '{CL,BMI0}, {Fsubcut,WT0}, {Vc,SEX,BMI0}'
+% to
+% {{'CL','BMI0'}, {'Fsubcut','WT0'}, {'Vc','SEX','BMI0'}}
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(covariateModel),
+    terms = explodePCSB(covariateModel,',','{','}');
+    y = {};
+    for k=1:length(terms),
+        x = strtrim(terms{k});
+        x = strrep(x,'{','{''');
+        x = strrep(x,'}','''}');
+        x = strrep(x,',',''',''');
+        y{k} = eval(x);
+    end
+    covariateModel = y;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check covariateModelValues
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(covariateModel) && ~isempty(covariateModelValues),
+    error('If you define covariateModelValues, you also need to define the covariateModel.');
+end
+
+if isempty(covariateModelValues),
+    % Determine default covariateModelValues
+    covariateModelValues = {};
+    for k=1:length(covariateModel),
+        covariateModelValues{k} = zeros(1,length(covariateModel{k})-1);
+    end
+else
+    % Check correct length of covariateModelValues elements
+    if length(covariateModel) ~= length(covariateModelValues),
+        error('Number of elements in covariateModel and covariateModelValues needs to match.');
+    end
+    for k=1:length(covariateModel),
+        if length(covariateModel{k})-1 ~= length(covariateModelValues{k}),
+            error('Length of single elements in covariateModel and covariateModelValues needs to match (covariateModelValues elements being one shorter).');
+        end            
+    end    
+end
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check COVestimate
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(covariateModel) && ~isempty(COVestimate),
+    error('If you define COVestimate, you also need to define the covariateModel.');
+end
+
+if isempty(COVestimate),
+    % Determine default COVestimate - all are estimates
+    COVestimate = {};
+    for k=1:length(covariateModel),
+        COVestimate{k} = ones(1,length(covariateModel{k})-1);
+    end
+else
+    % Check correct length of COVestimate elements
+    if length(covariateModel) ~= length(COVestimate),
+        error('Number of elements in covariateModel and COVestimate needs to match.');
+    end
+    for k=1:length(covariateModel),
+        if length(covariateModel{k})-1 ~= length(COVestimate{k}),
+            error('Length of single elements in covariateModel and COVestimate needs to match (COVestimate elements being one shorter).');
+        end            
+    end    
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create and change into project path
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+oldpath = pwd;
+% Create project path
+try
+    warning off;
+    mkdir(projectPath);
+    warning on;
+    if ~SILENT, fprintf('\tProject folder created.\n'); end
+catch
+    if ~SILENT, fprintf('\tProject folder existed already.\n'); end
+end
+cd(projectPath)
+% Create results folder
+try
+    warning off;
+    mkdir(resultsFolder);
+    warning on;
+    if ~SILENT, fprintf('\tResults folder created.\n'); end
+catch
+    if ~SILENT, fprintf('\tResults folder existed already.\n'); disp(' '); end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if datafile exists and csv file and load some information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dataFile = [dataRelPathFromProject '/' dataFileName];
+try
+    dataheader = SBPOPloadCSVdataset(dataFile,1);
+catch
+    cd(oldpath);
+    error('Please check if the data file "%s" exists.',dataFile)
+end
+% Check if length of header identical to dataHeaderIdent
+if length(explodePCSB(dataHeaderIdent,',')) ~= length(dataheader),
+    cd(oldpath);
+    error('Please check: The data header identifiers do not have the same length as the number of columns in the dataset.')
+end
+% Determine continuous and categorical covariates
+IDs = explodePCSB(dataHeaderIdent,',');
+covIDs = strmatchSB('COV',upper(IDs));
+covNames = dataheader(covIDs);
+catIDs = strmatchSB('CAT',upper(IDs));
+catNames = dataheader(catIDs);
+% No regression parameters to be expected!
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Loading dataset and determining medians for covariates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Load dataset
+dataCSV = SBPOPloadCSVdataset(fullfile(dataRelPathFromProject,dataFileName));
+dataheader = get(dataCSV,'VarNames');
+% Determine index of COV columns and their names
+terms = explodePCSB(dataHeaderIdent);
+ixCOVs = strmatchSB('COV',terms,'exact');
+if ~isempty(ixCOVs),
+    dataheaderCOVs = dataheader(ixCOVs);
+    % Determine index of ID column and ID name
+    terms = explodePCSB(dataHeaderIdent);
+    ixID = strmatchSB('ID',terms,'exact');
+    dataheaderID = dataheader(ixID);
+    % Determine median values across ID column
+    allID = eval(sprintf('unique(dataCSV.%s);',dataheaderID{1}));
+    allCOVs = NaN(length(allID),length(ixCOVs));
+    for k=1:length(allID),
+        datak = eval(sprintf('dataCSV(dataCSV.%s==allID(k),ixCOVs);',dataheaderID{1}));
+        allCOVs(k,:) = double(datak(1,:));
+    end
+    covariateMedianValues = median(allCOVs);
+    covariateMedianNames = dataheaderCOVs;
+    if ~SILENT, 
+        disp(' ')
+        disp('==================================================================');
+        disp('Analysis of dataset for covariates - determine the median values  ')
+        disp(' Results:');
+        for k=1:length(covariateMedianValues),
+            disp(sprintf('   median(%s) = %g',covariateMedianNames{k},covariateMedianValues(k)));
+        end
+        disp('These values will be used to center the continuous covariates')
+        disp('==================================================================');
+        disp(' ')
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check POPestimate thing
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(POPestimate),
+    POPestimate = ones(1,length(parameterNames));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check POPvalues0 thing
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(POPvalues0),
+    POPvalues0 = ones(1,length(parameterNames));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check IIV distribution things
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(IIVdistribution),
+    IIVdistribution = {};
+    for k=1:length(parameterNames),
+        IIVdistribution{k} = 'L';
+    end
+end
+
+% Check contents
+test = IIVdistribution;
+for k=1:length(IIVdistribution),
+    if ~ismember(test{k},{'L','N','G'}),
+        cd(oldpath);
+        error('Please make sure that only "N", "L", or "G" appear in the "IIVdistribution" variable.');
+    end
+end
+
+% Check length
+if length(IIVdistribution) ~= length(parameterNames),
+    cd(oldpath);
+    error('Please make sure that an equal number of IIVdistribution is defined as estimated parameters in the model.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check IIV estimation things
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(IIVestimate),
+    IIVestimate = ones(1,length(parameterNames));
+end
+% Check length
+if length(IIVestimate) ~= length(parameterNames),
+    cd(oldpath);
+    error('Please make sure that an equal number of IIVestimate is defined as estimated parameters in the model.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check IIVvalues0 thing
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(IIVvalues0),
+    IIVvalues0 = ones(1,length(parameterNames));
+end
+if length(parameterNames) ~= length(IIVvalues0),
+    cd(oldpath);
+    error('Please make sure IIVvalues0 is of same length as number of parameters to be estimated.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check residual error things
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(errorModels),
+    errorModels = 'comb1';
+end
+test = errorModels;
+test = strtrim(strrep(strrep(strrep(strrep(strrep(strrep(strrep(test,'const',''),'prop',''),'comb1',''),'exp',''),'band(0,100)',''),'logit',''),',',''));
+if ~isempty(test),
+    cd(oldpath);
+    error('Please make sure that only "const", "prop", "comb1", or "exp" appear in the "errorModels" variable.');
+end
+% Check length
+errors = explodePCSB(errorModels,',');
+if length(errors) ~= 1,
+    cd(oldpath);
+    error('Please make sure that only one residual error model is defined.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle empty errorParam0
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(errorParam0),
+    terms = explodePCSB(errorModels);
+    for k=1:length(terms),
+        if strcmp(lower(terms{k}),'const'),
+            errorParam0(end+1) = 1;
+        elseif strcmp(lower(terms{k}),'prop'),
+            errorParam0(end+1) = 0.3;
+        elseif strcmp(lower(terms{k}),'comb1'),
+            errorParam0(end+1) = 1;
+            errorParam0(end+1) = 0.3;          
+        elseif strcmp(lower(terms{k}),'exp'),
+            errorParam0(end+1) = 1;
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check errorParam0
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+terms = explodePCSB(errorModels);
+nrneededelements = 0;
+for k=1:length(terms),
+    if strcmpi(terms{k},'const'),
+        nrneededelements = nrneededelements+1;
+    elseif strcmpi(terms{k},'prop'),
+        nrneededelements = nrneededelements+1;
+    elseif strcmpi(terms{k},'comb1'),
+        nrneededelements = nrneededelements+2;
+    elseif strcmpi(terms{k},'exp'),
+        nrneededelements = nrneededelements+1;
+    end
+end
+if length(errorParam0) ~= nrneededelements,
+    error('Incorrect number of elements in options.errorParam0.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check covariance model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(covarianceModel),
+    covarianceModel = 'diagonal';
+elseif ~strcmp(covarianceModel,'diagonal'),
+    % Need to check that none of the parameters for which no IIV is estimated is used in the covarianceModel
+    param_est_noIIV = parameterNames(find(~IIVestimate));
+    for k=1:length(param_est_noIIV),
+        if ~isempty(regexp(covarianceModel,['\<' param_est_noIIV{k} '\>'])),
+            cd(oldpath);
+            error('Please make sure none of the parameters for which no IIV is estimated is used in the covarianceModel settings.');
+        end
+    end
+    % Check that all parameters in the covariance model actually are model parameters
+    param = {parameterNames};
+    test  = covarianceModel;
+    for k=1:length(param),
+        test = regexprep(test,['\<' param{k} '\>'],'');
+    end
+    test = strrep(test,'{','');
+    test = strrep(test,'}','');
+    test = strrep(test,',','');
+    if ~isempty(test),
+        cd(oldpath);
+        error('Please make sure that covarianceModel only contains parameter names in the model.');
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check LL setting
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(LLsetting),
+    LLsetting = 'both';
+end
+if isempty(strmatchSB(LLsetting,{'linearization','importantSampling','both'})),
+    cd(oldpath);
+    error('Please make sure LLsetting has one of the following values: "linearization", "importantSampling", "both"=""');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check covariate model things
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% First check that all first elements are estimated parameters of the model
+for k=1:length(covariateModel),
+    param = covariateModel{k}{1};
+    if isempty(strmatchSB(param,parameterNames,'exact')),
+        cd(oldpath);
+        error('Please make sure that all parameters for which covariates are defined are defined in the model.');
+    end
+end
+% Second check that all defined covariates actually are covariates
+covcatNames = [covNames catNames];
+for k=1:length(covariateModel),
+    for k2=2:length(covariateModel{k}),
+        cov = covariateModel{k}{k2};
+        if isempty(strmatchSB(cov,covcatNames,'exact')),
+            cd(oldpath);
+            error('Please make sure that all covariates, defined in covariateModel, are defined in the dataset.');
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OPEN File
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen([projectName '.mlxtran'],'w');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INFO
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; MLXTRAN PROJECT, created using the SBPOP toolbox\r\n');
+fprintf(fid,'; Date: %s\r\n',date);
+fprintf(fid,'; By:   %s\r\n',usernameSBPOP());
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Placeholder for project information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; ==PROJECT HEADER START===================================================\r\n');
+fprintf(fid,'PROJECT_HEADER_PLACEHOLDER\r\n');
+fprintf(fid,'; ==PROJECT HEADER END=====================================================\r\n');
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DESCRIPTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; =============================================\r\n');
+fprintf(fid,'DESCRIPTION:\r\n');
+fprintf(fid,'; =============================================\r\n');
+fprintf(fid,'\t%s\r\n',modelNameFIT);
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DATA
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; =============================================\r\n');
+fprintf(fid,'DATA:\r\n');
+fprintf(fid,'; =============================================\r\n');
+fprintf(fid,'\tpath = "%%MLXPROJECT%%/%s/",\r\n',dataRelPathFromProject);
+fprintf(fid,'\tfile  ="%s",\r\n',dataFileName);
+fprintf(fid,'\theaders = {%s},\r\n',dataHeaderIdent);
+fprintf(fid,'\tcolumnDelimiter = ","\r\n');
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% VARIABLES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; =============================================\r\n');
+fprintf(fid,'VARIABLES:\r\n');
+fprintf(fid,'; =============================================\r\n');
+% Assume all covariates defined in dataset are used ...
+% Continuous are always log transformed and centered by median
+% Categorical are always kept as they are
+text = '';
+% Write out continuous first
+for k=1:length(covNames),
+    text = sprintf('%s\t%s,\r\n',text,covNames{k});
+    covname = covNames{k};
+    % Scale covariate by median value from dataset
+    ixmedian = strmatchSB(covname,covariateMedianNames,'exact');
+    covname_weighted = sprintf('%s/%g',covname,covariateMedianValues(ixmedian));
+    text = sprintf('%s\tt_%s = log(%s) [use=cov],\r\n',text,covname,covname_weighted);
+end
+% Write out categorical
+for k=1:length(catNames),
+    text = sprintf('%s\t%s [use=cov, type=cat],\r\n',text,catNames{k});
+end
+% Remove last comma and write text to file
+fprintf(fid,text(1:end-3));
+fprintf(fid,'\r\n');
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INDIVIDUAL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; =============================================\r\n');
+fprintf(fid,'INDIVIDUAL:\r\n');
+fprintf(fid,'; =============================================\r\n');
+% Write out parameters to estimate. Assume iiv=yes on all of them by default. 
+% If no IIV desired then rather fix omega to 0.01.
+text = '';
+for k=1:length(parameterNames),
+    if IIVdistribution{k} == 'L', dtext = 'logNormal'; end
+    if IIVdistribution{k} == 'N', dtext = 'Normal'; end
+    if IIVdistribution{k} == 'G', dtext = 'logitNormal'; end
+    % check if IIV (not if both random effect and population value not estimated)
+    if IIVestimate(k) == 0,
+        iiv='no';
+    else
+        iiv='yes';
+    end
+    % check for covariates to use
+    param = parameterNames{k};
+    covs = {};
+    for k2=1:length(covariateModel),
+        if strcmp(param,covariateModel{k2}{1}),
+            covs = covariateModel{k2}(2:end);
+        end
+    end
+    % Attach "t_" to continuous covariate names, keep categorical covariate names same
+    for k2=1:length(covs),
+        if ~isempty(strmatchSB(covs{k2},covNames,'exact')),
+            covs{k2} = ['t_' covs{k2}];
+        end
+    end
+    % Write it out
+    if isempty(covs),
+        text = sprintf('%s\t%s = {distribution=%s, iiv=%s},\r\n',text,param,dtext,iiv);
+    else
+        % Create cov text
+        covText = '';
+        for k2=1:length(covs),
+            covText = sprintf('%s%s,',covText,covs{k2});
+        end
+        covText = covText(1:end-1);
+        text = sprintf('%s\t%s = {distribution=%s, covariate={%s}, iiv=%s},\r\n',text,param,dtext,covText,iiv);
+    end        
+end
+% Remove last comma and write text to file
+fprintf(fid,text(1:end-3));
+fprintf(fid,'\r\n');
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CORRELATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~strcmp(covarianceModel,'diagonal'),
+    fprintf(fid,'; =============================================\r\n');
+    fprintf(fid,'CORRELATION:\r\n');
+    fprintf(fid,'; =============================================\r\n');
+    fprintf(fid,'\tcorrelationIIV = {%s}\r\n',covarianceModel);
+    fprintf(fid,'\r\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% STRUCTURAL_MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% copy model to project folder
+copyfile(modelFile,'.');
+% add FACTOR_UNITS
+contents = fileread(modelName);
+contents = strrep(contents,'FACTOR_UNITS = 1',sprintf('FACTOR_UNITS = %g',FACTOR_UNITS));
+fid2 = fopen(modelName,'w');
+fprintf(fid2,'%s',contents);
+fclose(fid2);
+fprintf(fid,'; =============================================\r\n');
+fprintf(fid,'STRUCTURAL_MODEL:\r\n');
+fprintf(fid,'; =============================================\r\n');
+fprintf(fid,'\tfile = "%s",\r\n',modelName);
+fprintf(fid,'\tpath = "%%MLXPROJECT%%/",\r\n');
+fprintf(fid,'\toutput = {Cc}');
+fprintf(fid,'\r\n');
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OBSERVATIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; =============================================\r\n');
+fprintf(fid,'OBSERVATIONS:\r\n');
+fprintf(fid,'; =============================================\r\n');
+% Only consider "continuous" observations with SBPOP conversion 
+errors = explodePCSB(errorModels,',');
+text = '';
+for k=1:length(errors),
+    if strcmp(errors{k},'const'), errorModel = 'constant'; end
+    if strcmp(errors{k},'prop'), errorModel = 'proportional'; end
+    if strcmp(errors{k},'comb1'), errorModel = 'combined1'; end
+    if strcmp(errors{k},'exp'), errorModel = 'exponential'; end
+    if strcmp(errors{k},'logit'), errorModel = 'logit'; end
+    if strcmp(errors{k},'band(0,100)'), errorModel = 'band(0,100)'; end
+    text = sprintf('%s\ty%d = {type=continuous, prediction=Cc, error=%s},\r\n',text,k,errorModel);
+end
+% Remove last comma and write text to file
+fprintf(fid,text(1:end-3));
+fprintf(fid,'\r\n');
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% TASKS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; =============================================\r\n');
+fprintf(fid,'TASKS:\r\n');
+fprintf(fid,'; =============================================\r\n');
+fprintf(fid,'\t; settings\r\n');
+fprintf(fid,'\tglobalSettings={\r\n');
+fprintf(fid,'\t\twithVariance=no,\r\n'); % Always estimate standard deviations of IIVs
+fprintf(fid,'\t\tsettingsGraphics="%%MLXPROJECT%%/project_graphics.xmlx",\r\n');
+fprintf(fid,'\t\tsettingsAlgorithms="%%MLXPROJECT%%/project_algorithms.xmlx",\r\n');
+fprintf(fid,'\t\tresultFolder="%%MLXPROJECT%%/%s"},\r\n',resultsFolder);
+fprintf(fid,'\t; workflow\r\n');
+fprintf(fid,'\testimatePopulationParameters(\r\n');
+fprintf(fid,'\t\tinitialValues={\r\n');
+% write out population parameter initial values
+for k=1:length(POPestimate),
+    method = '';
+    if POPestimate(k) == 0,
+        method = '[method=FIXED]';
+    end
+    fprintf(fid,'\t\t\tpop_{%s} = %g %s,\r\n',parameterNames{k},POPvalues0(k),method);
+end
+
+% write out covariate coefficient initial guesses
+for k1=1:length(covariateModel),
+    for k2=2:length(covariateModel{k1}),
+        covarvalue = covariateModelValues{k1}(k2-1);
+        if COVestimate{k1}(k2-1),
+            method = '';
+        else
+            method = '[method=FIXED]';
+        end
+        ix = strmatchSB(covariateModel{k1}{k2},covNames,'exact');
+        if isempty(ix),
+            fprintf(fid,'\t\t\tbeta_{%s,%s} = %g %s,\r\n',covariateModel{k1}{1},covariateModel{k1}{k2},covarvalue,method);
+        else
+            fprintf(fid,'\t\t\tbeta_{%s,t_%s} = %g %s,\r\n',covariateModel{k1}{1},covariateModel{k1}{k2},covarvalue,method);
+        end
+    end
+end
+
+% write out residual error model
+errors = explodePCSB(errorModels,',');
+count = 1;
+for k=1:length(errors),
+    if strcmp(errors{k},'const'), 
+        fprintf(fid,'\t\t\ta_y%d = %g,\r\n',k,errorParam0(count));
+        count = count + 1;
+    end
+    if strcmp(errors{k},'prop'), 
+        fprintf(fid,'\t\t\tb_y%d = %g,\r\n',k,errorParam0(count));
+        count = count + 1;
+    end
+    if strcmp(errors{k},'comb1'), 
+        fprintf(fid,'\t\t\ta_y%d = %g,\r\n',k,errorParam0(count));
+        count = count + 1;
+        fprintf(fid,'\t\t\tb_y%d = %g,\r\n',k,errorParam0(count));
+        count = count + 1;
+    end
+    if strcmp(errors{k},'exp'), 
+        fprintf(fid,'\t\t\ta_y%d = %g,\r\n',k,errorParam0(count));
+        count = count + 1;
+    end
+end
+
+% write out population parameter initial values
+text = '';
+for k=1:length(parameterNames),
+    if IIVestimate(k)==1,
+        value0 = IIVvalues0(k);
+        text = sprintf('%s\t\t\tomega_{%s} = %g,\r\n',text,parameterNames{k},value0);
+    elseif IIVestimate(k)==2,
+        value0 = IIVvalues0(k);
+        text = sprintf('%s\t\t\tomega_{%s} = %g [method=FIXED],\r\n',text,parameterNames{k},value0);
+    end
+end
+fprintf(fid,text(1:end-3));
+fprintf(fid,'\r\n');
+
+fprintf(fid,'\t\t} ),\r\n');
+if strcmp(FIMsetting,'linearization'),
+    fprintf(fid,'\testimateFisherInformationMatrix( method={linearization} ),\r\n');
+else
+    fprintf(fid,'\testimateFisherInformationMatrix( method={stochasticApproximation} ),\r\n');
+end
+fprintf(fid,'\testimateIndividualParameters( method={%s} ),\r\n',INDIVparametersetting);
+if strcmp(LLsetting,'linearization'),
+    fprintf(fid,'\testimateLogLikelihood(method={linearization}),\r\n');
+elseif strcmp(LLsetting,'importantSampling'),
+    fprintf(fid,'\testimateLogLikelihood(method={importantSampling}),\r\n');
+elseif strcmp(LLsetting,'both'),
+    fprintf(fid,'\testimateLogLikelihood(method={importantSampling,linearization}),\r\n');
+end
+fprintf(fid,'\tdisplayGraphics()');
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CLOSE File
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fclose(fid);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create Project Header with Metadata
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+PROJECT_INFO_TEXT = '';
+
+% Data location
+DATA_info = sprintf('; DATA                = ''%s''\r\n',strrep(fullfile(dataRelPathFromProject,dataFileName),'\','/'));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,DATA_info);
+
+% covNames
+x = sprintf('%s,',covNames{:});
+COVNAMES_info = sprintf('; COVNAMES            = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,COVNAMES_info);
+
+% catNames
+x = sprintf('%s,',catNames{:});
+CATNAMES_info = sprintf('; CATNAMES            = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,CATNAMES_info);
+
+% PARAMNAMES
+x = sprintf('%s,',parameterNames{:});
+PARAMNAMES_info = sprintf('; PARAMNAMES          = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,PARAMNAMES_info);
+
+% Outputs
+OUTPUTS_info = sprintf('; OUTPUTS             = ''Cc''\r\n');
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,OUTPUTS_info);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Replace PROJECT_HEADER_PLACEHOLDER
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+content = fileread('project.mlxtran');
+content = strrep(content,'PROJECT_HEADER_PLACEHOLDER',strtrim(PROJECT_INFO_TEXT));
+fid = fopen('project.mlxtran','w');
+fprintf(fid,'%s',content);
+fclose(fid);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Do generate the default graphics settings so that 
+% predictions.txt file is generated and included NPDE and meanPWRES
+% Trick is to load project file and to add things and then to save the file
+% again.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+copyfile(which('template_project_graphics.xmlx'),'project_graphics.xmlx')
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Generate project_algorithms.xmlx file
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% only writing out K1, K2, Number of Chains, Seed, and auto settings for K1,K2,Number of chains
+fid = fopen('project_algorithms.xmlx','w');
+fprintf(fid,'<monolix>\n');
+fprintf(fid,'	<algorithms seed="%d">\n',SEED);
+fprintf(fid,'		<populationParameters>\n');
+fprintf(fid,'			<vna value="%d,%d"/>\n',K1,K2);
+fprintf(fid,'			<iop_Kauto value="%d,%d"/>\n',K1_AUTO,K2_AUTO);
+fprintf(fid,'			<nmc value="%d"/>\n',NRCHAINS);
+fprintf(fid,'		</populationParameters>\n');
+fprintf(fid,'	</algorithms>\n');
+fprintf(fid,'</monolix>\n');
+fclose(fid);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Change out of project path
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+cd(oldpath);
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/05_ModelBuilding/auxiliary/createPopPK_NLMEproject_ODE_Analytic_SBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/05_ModelBuilding/auxiliary/createPopPK_NLMEproject_ODE_Analytic_SBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..901eb71fa30a68bdd17e530ba603417293ea756b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/05_ModelBuilding/auxiliary/createPopPK_NLMEproject_ODE_Analytic_SBPOP.m
@@ -0,0 +1,232 @@
+ function [FLAGanalyticModel,MODEL_SETTINGS] = createPopPK_NLMEproject_ODE_Analytic_SBPOP( ...
+                                FLAG_NONMEM,modelNameFIT,TemplateModels, ... 
+                                FACTOR_UNITS, numberCompartments,saturableClearance, ...
+                                lagTime,data,projectPath,dataRelPathFromProjectPath,optionsProject)
+                           
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define Data Information for Monolix Project Creation
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define data information
+data_NLME                            = [];
+data_NLME.dataRelPathFromProject     = dataRelPathFromProjectPath;
+data_NLME.dataFileName               = data.filename;
+data_NLME.dataHeaderIdent            = data.header;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define Options Information for Monolix Project Creation
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define the options_MLX structure and handle default cases
+options_NLME                         = optionsProject;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle compartment number settings wrt to impact on 
+% estimated fixed and random effects and initial guesses
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if numberCompartments == 1,
+    % Do not estimate Q1,Vp1,Q2,Vp2 and set the Q12 values to 1e-10 etc.
+    % 'CL', 'Vc', 'Q1', 'Vp1', 'Q2', 'Vp2', 'Fiv', 'Fabs1', 'ka', 'TLAGabs1', 'VMAX', 'KM'
+    options_NLME.POPestimate(3:6)    = 0;
+    options_NLME.POPvalues0([3 5])   = 1e-10;    % Setting Q1/2 to 1e-10
+    options_NLME.POPvalues0([4 6])   = 1;        % Setting Vp1/2 to 1
+    options_NLME.IIVestimate(3:6)    = 0;
+elseif numberCompartments == 2,
+    % Do not estimate Q2,Vp2 and set the Q2 value to 1e-10 and Vp2 to 1
+    % 'CL', 'Vc', 'Q1', 'Vp1', 'Q2', 'Vp2', 'Fiv', 'Fabs1', 'ka', 'TLAGabs1', 'VMAX', 'KM'
+    options_NLME.POPestimate(5:6)    = 0;
+    options_NLME.POPvalues0(5)       = 1e-10;    % Setting Q2 to 1e-10
+    options_NLME.POPvalues0(6)       = 1;        % Setting Vp2 to 1
+    options_NLME.IIVestimate(5:6)    = 0;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle clearance settings wrt to impact on 
+% estimated fixed and random effects and initial guesses
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if saturableClearance==0,
+    % Linear clearance only
+    % Do not estimate VMAX and KM and set VMAX to 1e-10 and KM to 1
+    % 'CL', 'Vc', 'Q1', 'Vp1', 'Q2', 'Vp2', 'Fiv', 'Fabs1', 'ka', 'TLAGabs1', 'VMAX', 'KM'
+    options_NLME.POPestimate(11:12)  = 0;
+    options_NLME.POPvalues0(11)      = 1e-10;    % Setting VMAX to 1e-10
+    options_NLME.POPvalues0(12)      = 1;        % Setting KM to 1
+    options_NLME.IIVestimate(11:12)  = 0;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle lagtime settings wrt to impact on 
+% estimated fixed and random effects and initial guesses
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if lagTime==0,
+    % No lagTime
+    % Do not estimate TLAGabs1 and set it to 1e-10
+    % 'CL', 'Vc', 'Q1', 'Vp1', 'Q2', 'Vp2', 'Fiv', 'Fabs1', 'ka', 'TLAGabs1', 'VMAX', 'KM'
+    options_NLME.POPestimate(10)     = 0;
+    options_NLME.POPvalues0(10)      = 1e-10;    % Setting Tlag_input2 to 1e-10
+    options_NLME.IIVestimate(10)     = 0;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle covariance settings 
+% Need to remove model parameter combinations that are not 
+% available in the current model.
+% For example a covariance on Vp2,CL makes no sense if not a 3 
+% compartment model and thus no random effect estimated for some of the
+% parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+RANDOMEFFECTS_NOT_available_ODEmodelParamNames  = TemplateModels.ParameterNames.ODE(find(~options_NLME.IIVestimate));
+% No remove all elements in options_NLME.covarianceModel that do include
+% names in the RANDOMEFFECTS_NOT_available_ODEmodelParamNames list
+terms = explodePCSB(options_NLME.covarianceModel,',','{','}');
+remove_terms_ix = [];
+for k=1:length(terms),
+    for k2=1:length(RANDOMEFFECTS_NOT_available_ODEmodelParamNames),
+        ix = regexp(terms{k},['\<' RANDOMEFFECTS_NOT_available_ODEmodelParamNames{k2} '\>']);
+        if ~isempty(ix),
+            remove_terms_ix = [remove_terms_ix k];
+        end
+    end
+end
+terms(unique(remove_terms_ix)) = [];
+x = sprintf('%s,',terms{:});
+options_NLME.covarianceModel = x(1:end-1);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle covariate settings 
+% Need to remove model parameter combinations that are not 
+% available in the current model.
+% For example a covariate on Vp2 makes no sense if not a 3 compartment
+% model - here we assume that covariates are only tested on parameters for
+% which fixed effects are estimated.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+FIXEDEFFECTS_NOT_available_ODEmodelParamNames   = TemplateModels.ParameterNames.ODE(find(~options_NLME.POPestimate));
+% No remove all elements in options_NLME.covarianceModel that do include
+% names in the FIXEDEFFECTS_NOT_available_ODEmodelParamNames list
+terms = explodePCSB(options_NLME.covariateModel,',','{','}');
+remove_terms_ix = [];
+for k=1:length(terms),
+    for k2=1:length(FIXEDEFFECTS_NOT_available_ODEmodelParamNames),
+        ix = regexp(terms{k},['\<' FIXEDEFFECTS_NOT_available_ODEmodelParamNames{k2} '\>']);
+        if ~isempty(ix),
+            remove_terms_ix = [remove_terms_ix k];
+        end
+    end
+end
+terms(unique(remove_terms_ix)) = [];
+x = sprintf('%s,',terms{:});
+options_NLME.covariateModel = x(1:end-1);
+% Also remove the same terms for COVestimate and covariateModelValues
+% Also remove the same terms for COVestimate and covariateModelValues
+if ~isempty(options_NLME.covariateModelValues),
+    options_NLME.covariateModelValues(remove_terms_ix) = [];
+end
+if ~isempty(options_NLME.COVestimate),
+    options_NLME.COVestimate(remove_terms_ix) = [];
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Decide if ODE or analytic model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if saturableClearance,
+    FLAGanalyticModel = 0;
+else
+    FLAGanalyticModel = 1;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Construct Monolix/NONMEM project
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if FLAGanalyticModel,
+    % Need to adjust the options
+    % Need to remove the ODE model parameters
+    % Find indices of analytic model parameters in the ODE parameters
+    ix_analytic = [];
+    for k=1:length(TemplateModels.ParameterNames.ANALYTIC),
+        ix_analytic = [ix_analytic strmatchSB(TemplateModels.ParameterNames.ANALYTIC{k},TemplateModels.ParameterNames.ODE,'exact')];
+    end
+    ix_remove_ODE_param = setdiff([1:length(TemplateModels.ParameterNames.ODE)],ix_analytic);
+    % Do remove
+    options_NLME_ANALYTIC = options_NLME;
+    options_NLME_ANALYTIC.POPestimate(ix_remove_ODE_param) = [];
+    options_NLME_ANALYTIC.POPvalues0(ix_remove_ODE_param) = [];
+    options_NLME_ANALYTIC.IIVestimate(ix_remove_ODE_param) = [];
+    if ~isempty(options_NLME_ANALYTIC.IIVvalues0),
+        options_NLME_ANALYTIC.IIVvalues0(ix_remove_ODE_param) = [];
+    end
+    options_NLME_ANALYTIC.IIVdistribution = TemplateModels.IIVdistribution.ANALYTIC;
+    
+    if ~FLAG_NONMEM,
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        % Handle Monolix
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        % Get model info - analytic model
+        modelName       = TemplateModels.Model.MONOLIX.ANALYTIC;
+        modelFile       = which(modelName);
+        parameterNames  = TemplateModels.ParameterNames.ANALYTIC;
+        
+        % Create analytic Monolix project
+        createPopPK_MONOLIXprojectSBPOP(modelNameFIT,modelName,modelFile,parameterNames,FACTOR_UNITS,data_NLME,projectPath,options_NLME_ANALYTIC);
+    else
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        % Handle NONMEM
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        modelName       = TemplateModels.Model.ODE;
+        modelFile       = which(modelName);
+        parameterNames  = TemplateModels.ParameterNames.ANALYTIC;
+        
+        % Need to use different ADVANs depending on the compartment number
+        % (for stability reasons, since Q=1e-10 is not good for NONMEM)
+        if numberCompartments==1,
+            modelADVAN = 'ADVAN2 TRANS2';
+            paramNamesODE   = {'CL','Vc','ka'};
+            paramNamesADVAN = {'CL','V','KA'};
+        elseif numberCompartments==2,
+            modelADVAN = 'ADVAN4 TRANS4';
+            paramNamesODE   = {'CL','Vc','Q1','Vp1','ka'};
+            paramNamesADVAN = {'CL','V2','Q', 'V3', 'KA'};
+        elseif numberCompartments==3,
+            modelADVAN = 'ADVAN12 TRANS4';
+            paramNamesODE   = {'CL','Vc','Q1','Vp1','Q2','Vp2','ka'};
+            paramNamesADVAN = {'CL','V2','Q3','V3', 'Q4','V4', 'KA'};
+        end
+        createPopPK_NONMEMprojectSBPOP(parameterNames,FACTOR_UNITS,data_NLME,projectPath,options_NLME_ANALYTIC,modelADVAN,paramNamesODE,paramNamesADVAN);
+    end
+else
+    
+    % All parameters are passed, but they might require a reordering!
+    parameterNames  = TemplateModels.ParameterNames.ODE;
+    options_NLME.IIVdistribution = TemplateModels.IIVdistribution.ODE;
+
+    % Get model info
+    modelName       = TemplateModels.Model.ODE;
+    modelFile       = which(modelName);
+    dosingName      = TemplateModels.Model.DOSING;
+    dosFile         = which(dosingName);
+	
+    % Load model and dosing
+    model           = SBmodel(modelFile);
+    dosing          = SBPOPdosing(dosFile);
+    
+    % Update model name with modelNameFIT
+    ms              = struct(model);
+    ms.name         = modelNameFIT;
+    model           = SBmodel(ms);
+    
+    % Update model with FACTOR_UNITS
+    model           = SBparameters(model,'FACTOR_UNITS',FACTOR_UNITS);
+    
+    if ~FLAG_NONMEM,
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        % Handle Monolix
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        SBPOPcreateMONOLIXproject(model,dosing,data_NLME,projectPath,options_NLME,parameterNames)
+    else
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        % Handle NONMEM
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        SBPOPcreateNONMEMproject(model,dosing,data_NLME,projectPath,options_NLME,parameterNames)        
+    end
+end
+
+% Return the full options for both ODE and ANALYTIC
+MODEL_SETTINGS = options_NLME;
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/05_ModelBuilding/auxiliary/createPopPK_NONMEMprojectSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/05_ModelBuilding/auxiliary/createPopPK_NONMEMprojectSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..a3494889e38c54efaadf1ca6109e0ec1d5d7aa49
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/05_ModelBuilding/auxiliary/createPopPK_NONMEMprojectSBPOP.m
@@ -0,0 +1,1472 @@
+function createPopPK_NONMEMprojectSBPOP(parameterNames,FACTOR_UNITS,data,projectPath,options,modelADVAN,paramNamesODE,paramNamesADVAN)
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define Default Properties (Never changing)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+projectName            = 'project';
+resultsFolder          = 'RESULTS';
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try
+    dataRelPathFromProject = data.dataRelPathFromProject;
+    dataFileName           = data.dataFileName;
+    dataHeaderIdent        = data.dataHeaderIdent;
+    
+    % Need to change the data header
+    % TIME => TIME2 (Since it can contain negative times)
+    % TIMEPOS => TIME (The normal NONMEM time ... since it is only positive)
+    dataHeaderIdent         = regexprep(dataHeaderIdent,'\<TIME\>','TIME2');    
+    dataHeaderIdent         = regexprep(dataHeaderIdent,'\<TIMEPOS\>','TIME');    
+    dataHeaderIdent         = regexprep(dataHeaderIdent,'\<Y\>','DV');    
+catch
+    error('data input argument not defined correctly.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle optional arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try POPestimate                     = options.POPestimate;                      catch, POPestimate = [];                             end
+try POPvalues0                      = options.POPvalues0;                       catch, POPvalues0 = [];                              end
+try IIVdistribution                 = options.IIVdistribution;                  catch, IIVdistribution = {};                         end
+try IIVestimate                     = options.IIVestimate;                      catch, IIVestimate = [];                             end
+try IIVvalues0                      = options.IIVvalues0;                       catch, IIVvalues0 = [];                              end
+try errorModels                     = options.errorModels;                      catch, errorModels = '';                             end
+try errorParam0                     = options.errorParam0;                      catch, errorParam0 = [];                             end
+try covarianceModel                 = options.covarianceModel;                  catch, covarianceModel = 'diagonal';                 end
+try covariateModel                  = options.covariateModel;                   catch, covariateModel = '';                          end
+try covariateModelValues            = options.covariateModelValues;             catch, covariateModelValues = {};                    end
+try COVestimate                     = options.COVestimate;                      catch, COVestimate = {};                             end
+
+try METHOD                          = options.algorithm.METHOD;                 catch, METHOD = 'SAEM';                              end
+try MAXEVAL                         = options.algorithm.MAXEVAL;                catch, MAXEVAL = 9999;                               end
+try SIGDIGITS                       = options.algorithm.SIGDIGITS;              catch, SIGDIGITS = 3;                                end
+try PRINT                           = options.algorithm.PRINT;                  catch, PRINT = 1;                                    end
+try SEED                            = options.algorithm.SEED;                   catch, SEED = 123456;                                end
+try K1                              = options.algorithm.K1;                     catch, K1 = 500;                                     end
+try K2                              = options.algorithm.K2;                     catch, K2 = 200;                                     end
+try NRCHAINS                        = options.algorithm.NRCHAINS;               catch, NRCHAINS = 1;                                 end
+try IMPORTANCESAMPLING              = options.algorithm.IMPORTANCESAMPLING;     catch, IMPORTANCESAMPLING = 0;                       end
+try ITS                             = options.algorithm.ITS;                    catch, ITS = 0;                                      end
+try ITS_ITERATIONS                  = options.algorithm.ITS_ITERATIONS;         catch, ITS_ITERATIONS = 10;                          end
+try IMP_ITERATIONS                  = options.algorithm.IMP_ITERATIONS;         catch, IMP_ITERATIONS = 5;                           end
+
+try SILENT                          = options.SILENT;                           catch, SILENT = 0;                                   end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle methods - some SBPOP limitations
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp(METHOD,'FO') && ITS==1,
+   error('The FO method should not be used with ITS=1.');
+end
+
+if ~strcmp(METHOD,'SAEM') && IMPORTANCESAMPLING==1,
+    error('The importance sampling (IMPORTANCESAMPLING=1) should only be used with the SAEM method.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Info text
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~SILENT,
+    disp(' ')
+    disp('==================================================================');
+    [xdummyx,projectFolderName] = fileparts(projectPath);
+    disp(sprintf('== Start of creation of %s/project.nmctl file',projectFolderName));
+    disp('==================================================================');
+    disp(' ')
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create project and results folder
+% Change into project path
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+oldpath = pwd;
+try, rmdir(projectPath,'s'); catch, end
+mkdir(projectPath); cd(projectPath)
+mkdir(resultsFolder);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Load data and get info about data
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dataModeling = SBPOPloadCSVdataset([data.dataRelPathFromProject '/' data.dataFileName]);
+% Determine maximum number of data records per ID
+maxDATARECORDS_ID = -Inf;
+allID = unique(dataModeling.ID);
+for k=1:length(allID),
+    datak = dataModeling(dataModeling.ID==allID(k),:);
+    maxDATARECORDS_ID = max(maxDATARECORDS_ID,length(datak));
+end
+maxDATARECORDS = length(dataModeling);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Process data to get the dataheader and the median values for the covariates
+% and the categorical covariate names and their unique values.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[covariateMedianNames,covariateMedianValues,covariateCATNames,covariateCATValues,dataheader,dataCSV] = processDataAndGetMedianValuesSBPOP(oldpath,dataRelPathFromProject,dataFileName,dataHeaderIdent,SILENT);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check data regarding the CMT/ADM/YTYPE thing
+%       - If only CMT is present then 
+%           - YTYPE is inferred based on CMT for observation records (in $ERROR)
+%             But this means that CMT needs to follow the OUTPUTn numbering!
+%           - CMT will be used as defined for selecting the dosing compartments
+%       - If CMT and YTYPE and/or ADM is present then error - do not allow
+%       - If ADM and YTYPE is present but not CMT
+%           - Use YTYPE as above
+%           - Use ADM as CMT column but rearrange states to fit the
+%             input/state numbers
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dataHeaderIdentAll = explodePCSB(dataHeaderIdent);
+
+% Need to rename ADM to CMT in dataHeaderIdentAll, dataHeaderIdent, dataheader
+dataHeaderIdent = regexprep(dataHeaderIdent,'\<ADM\>','CMT');
+dataheader{strmatchSB('ADM',dataheader,'exact')} = 'CMT';
+dataHeaderIdentAll{strmatchSB('ADM',dataHeaderIdentAll,'exact')} = 'CMT';
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check and update default input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check POPestimate thing
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(POPestimate),
+    POPestimate = ones(1,length(parameterNames));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check POPvalues0 thing
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(POPvalues0),
+    POPvalues0 = ones(1,length(parameterNames));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check IIV distribution things
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(IIVdistribution),
+    IIVdistribution = {};
+    for k=1:length(parameterNames),
+        IIVdistribution{k} = 'L';
+    end
+end
+
+% Check contents
+test = IIVdistribution;
+for k=1:length(IIVdistribution),
+    if ~ismember(test{k},{'L','N','G'}),
+        cd(oldpath);
+        error('Please make sure that only "N", "L", or "G" appear in the "IIVdistribution" variable.');
+    end
+end
+
+% Check length
+if length(IIVdistribution) ~= length(parameterNames),
+    cd(oldpath);
+    error('Please make sure that an equal number of IIVdistribution is defined as estimated parameters in the model.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check IIV estimation things
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(IIVestimate),
+    IIVestimate = ones(1,length(parameterNames));
+end
+% Check length
+if length(IIVestimate) ~= length(parameterNames),
+    cd(oldpath);
+    error('Please make sure that an equal number of IIVestimate is defined as estimated parameters in the model.');
+end
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check IIVvalues0 thing
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(IIVvalues0),
+    IIVvalues0 = ones(1,length(parameterNames));
+end
+if length(parameterNames) ~= length(IIVvalues0),
+    cd(oldpath);
+    error('Please make sure IIVvalues0 is of same length as number of parameters to be estimated.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Convert covariate model into different syntax
+% '{CL,BMI0}, {Fsubcut,WT0}, {Vc,SEX,BMI0}'
+% to
+% {{'CL','BMI0'}, {'Fsubcut','WT0'}, {'Vc','SEX','BMI0'}}
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(covariateModel),
+    terms = explodePCSB(covariateModel,',','{','}');
+    y = {};
+    for k=1:length(terms),
+        x = strtrim(terms{k});
+        x = strrep(x,'{','{''');
+        x = strrep(x,'}','''}');
+        x = strrep(x,',',''',''');
+        y{k} = eval(x);
+    end
+    covariateModel = y;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check covariateModelValues
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(covariateModel) && ~isempty(covariateModelValues),
+    error('If you define covariateModelValues, you also need to define the covariateModel.');
+end
+
+if isempty(covariateModelValues),
+    % Determine default covariateModelValues
+    covariateModelValues = {};
+    for k=1:length(covariateModel),
+        covariateModelValues{k} = zeros(1,length(covariateModel{k})-1);
+    end
+else
+    % Check correct length of covariateModelValues elements
+    if length(covariateModel) ~= length(covariateModelValues),
+        error('Number of elements in covariateModel and covariateModelValues needs to match.');
+    end
+    for k=1:length(covariateModel),
+        if length(covariateModel{k})-1 ~= length(covariateModelValues{k}),
+            error('Length of single elements in covariateModel and covariateModelValues needs to match (covariateModelValues elements being one shorter).');
+        end            
+    end    
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check COVestimate
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(covariateModel) && ~isempty(COVestimate),
+    error('If you define COVestimate, you also need to define the covariateModel.');
+end
+
+if isempty(COVestimate),
+    % Determine default COVestimate - all are estimates
+    COVestimate = {};
+    for k=1:length(covariateModel),
+        COVestimate{k} = ones(1,length(covariateModel{k})-1);
+    end
+else
+    % Check correct length of COVestimate elements
+    if length(covariateModel) ~= length(COVestimate),
+        error('Number of elements in covariateModel and COVestimate needs to match.');
+    end
+    for k=1:length(covariateModel),
+        if length(covariateModel{k})-1 ~= length(COVestimate{k}),
+            error('Length of single elements in covariateModel and COVestimate needs to match (COVestimate elements being one shorter).');
+        end            
+    end    
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Reorder estimation parameters to allow for block-diagonal covariance
+% matrix
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp(covarianceModel,'diagonal') || isempty(covarianceModel),
+    % Keep parameters in the given order
+    POPestimate_trans       = POPestimate;
+    POPvalues0_trans        = POPvalues0;
+    IIVestimate_trans       = IIVestimate;
+    IIVvalues0_trans        = IIVvalues0;
+    parameterNames_trans    = parameterNames;
+    IIVdistribution_trans   = IIVdistribution;    
+else
+    % Need to rearrange
+    % Determine the order of parameters as they appear in the
+    % covarianceModel definition
+    x = strrep(covarianceModel,'{','');
+    x = strrep(x,'}','');
+    terms = explodePCSB(x);
+    % Check which parameters are missing
+    paramnames_order = terms;
+    for k=1:length(parameterNames),
+        if ~ismember(parameterNames{k},paramnames_order),
+            paramnames_order{end+1} = parameterNames{k};
+        end
+    end
+    % Determine the transformation indices
+    index_trans = [];
+    for k=1:length(paramnames_order),
+        index_trans(k) = strmatchSB(paramnames_order{k},parameterNames,'exact');
+    end
+    % Ok, we got the new order of the parameters, now we need to change the
+    % order in a couple of things
+    % POPestimate
+    % POPvalues0
+    % IIVdistribution
+    % IIVestimate
+    % IIVvalues0
+    % parameterNames
+    POPestimate_trans       = POPestimate(index_trans);
+    POPvalues0_trans        = POPvalues0(index_trans);
+    IIVestimate_trans       = IIVestimate(index_trans);
+    IIVvalues0_trans        = IIVvalues0(index_trans);
+    parameterNames_trans    = parameterNames(index_trans);
+    IIVdistribution_trans   = IIVdistribution(index_trans);
+end
+% Update the variables to the transformed ones
+POPestimate             = POPestimate_trans;
+POPvalues0              = POPvalues0_trans;
+IIVestimate             = IIVestimate_trans;
+IIVvalues0              = IIVvalues0_trans;
+parameterNames          = parameterNames_trans;
+IIVdistribution         = IIVdistribution_trans;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Do additional checks and write out information
+% Definition of param_est and IIVestimation + reordering needed to be ready
+% before running these checks.
+% Additionally, the names of the covariates are determined and the
+% errorModels default setting is handled here.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%
+% Determine continuous and categorical covariates
+%%%%%%%%%%%%%%%%%%%%%%%
+dataHeaderIDs   = explodePCSB(dataHeaderIdent,',');
+covIDs          = strmatchSB('COV',upper(dataHeaderIDs));
+covNames        = dataheader(covIDs);
+catIDs          = strmatchSB('CAT',upper(dataHeaderIDs));
+catNames        = dataheader(catIDs);
+
+%%%%%%%%%%%%%%%%%%%%%%%
+% Check all headers
+%%%%%%%%%%%%%%%%%%%%%%%
+if ~SILENT,
+    disp(' ');
+    disp('Please check that the following matches between data header and identifiers do make sense:');
+    for k=1:length(dataheader),
+        fprintf('\t%s%s: %s\n',dataheader{k},char(32*ones(1,8-length(dataheader{k}))),dataHeaderIDs{k})
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%
+% Check residual error things
+%%%%%%%%%%%%%%%%%%%%%%%
+test = errorModels;
+test = strtrim(strrep(strrep(strrep(strrep(strrep(strrep(strrep(test,'const',''),'prop',''),'comb1',''),'exp',''),'band(0,100)',''),'logit',''),',',''));
+if ~isempty(test),
+    cd(oldpath);
+    error('Please make sure that only "const", "prop", "comb1", or "exp" appear in the "errorModels" variable.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle empty errorParam0
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(errorParam0),
+    terms = explodePCSB(errorModels);
+    for k=1:length(terms),
+        if strcmp(lower(terms{k}),'const'),
+            errorParam0(end+1) = 1;
+        elseif strcmp(lower(terms{k}),'prop'),
+            errorParam0(end+1) = 0.3;
+        elseif strcmp(lower(terms{k}),'comb1'),
+            errorParam0(end+1) = 1;
+            errorParam0(end+1) = 0.3;          
+        elseif strcmp(lower(terms{k}),'exp'),
+            errorParam0(end+1) = 1;
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check errorParam0
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+terms = explodePCSB(errorModels);
+nrneededelements = 0;
+for k=1:length(terms),
+    if strcmpi(terms{k},'const'),
+        nrneededelements = nrneededelements+1;
+    elseif strcmpi(terms{k},'prop'),
+        nrneededelements = nrneededelements+1;
+    elseif strcmpi(terms{k},'comb1'),
+        nrneededelements = nrneededelements+2;
+    elseif strcmpi(terms{k},'exp'),
+        nrneededelements = nrneededelements+1;
+    end
+end
+if length(errorParam0) ~= nrneededelements,
+    error('Incorrect number of elements in options.errorParam0.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%
+% Check covariance model
+%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(covarianceModel),
+    covarianceModel = 'diagonal';
+end
+
+if ~strcmp(covarianceModel,'diagonal'),
+    % Need to check that none of the parameters for which no IIV is estimated is used in the covarianceModel
+    param_est_noIIV = parameterNames(IIVestimate~=1);
+    for k=1:length(param_est_noIIV),
+        if ~isempty(regexp(covarianceModel,['\<' param_est_noIIV{k} '\>'])),
+            cd(oldpath);
+            error('Please make sure none of the parameters for which NO IIV is estimated (IIVestimate 0 and 2) is used in the covarianceModel settings.');
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%
+% Check covariate model things
+%%%%%%%%%%%%%%%%%%%%%%%
+% First check that all first elements are estimated parameters of the model
+for k=1:length(covariateModel),
+    param = covariateModel{k}{1};
+    if isempty(strmatchSB(param,parameterNames,'exact')),
+        cd(oldpath);
+        error('Please make sure that all parameters for which covariates are defined are defined by <estimate> in the model.');
+    end
+end
+% Second check that all defined covariates actually are covariates
+covcatNames = [covNames catNames];
+for k=1:length(covariateModel),
+    for k2=2:length(covariateModel{k}),
+        cov = covariateModel{k}{k2};
+        if isempty(strmatchSB(cov,covcatNames,'exact')),
+            error('Please make sure that all covariates, defined in covariateModel, are defined in the dataset.');
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OPEN File
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen([projectName '.nmctl'],'w');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INFO
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; NONMEM PROJECT, created using the SBPOP toolbox\r\n');
+fprintf(fid,'; Date: %s\r\n',date);
+fprintf(fid,'; By:   %s\r\n',usernameSBPOP());
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Placeholder for project information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; ==PROJECT HEADER START===================================================\r\n');
+fprintf(fid,'PROJECT_HEADER_PLACEHOLDER\r\n');
+fprintf(fid,'; ==PROJECT HEADER END=====================================================\r\n');
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define $SIZES
+% Set all LIM1,2,6 to TOTDREC=maxDATARECORDS!
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'$SIZES LIM1=%d\r\n',maxDATARECORDS);
+fprintf(fid,'$SIZES LIM2=%d\r\n',maxDATARECORDS);
+fprintf(fid,'$SIZES LIM6=%d\r\n',maxDATARECORDS);
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $PROBLEM
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[xdummyx,problemName]     = fileparts(projectPath);
+fprintf(fid,'$PROBLEM %s\r\n',problemName);
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $DATA
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'$DATA %s\r\n',strrep(fullfile(dataRelPathFromProject,dataFileName),'\','/'));
+fprintf(fid,'    IGNORE=@\r\n');
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $INPUT
+% Assumption: names for INPUT are used as in the dataset for CAT,COV,X
+% for all others as in dataHeaderIdent.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dataHeaderIdentAll = explodePCSB(dataHeaderIdent);
+
+text = '$INPUT';
+for k=1:length(dataheader),
+    col     = dataheader{k};
+    coltype = dataHeaderIdentAll{k};
+    
+    % Check if CAT, COV or X
+    if ismember(coltype,{'CAT','COV','X'}),
+        % Use name as in dataset header
+        text = sprintf('%s %s',text,col);
+    elseif strcmp(coltype,'IGNORE'),
+        % If column set to IGNORE then use SKIP in the $INPUT definition
+        text = sprintf('%s SKIP',text);
+    else
+        % Use name as in dataset ident
+        text = sprintf('%s %s',text,coltype);
+    end
+end
+fprintf(fid,'%s\r\n',wrapRowTextSBPOP(text,80,7));
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $SUBROUTINE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'$SUBROUTINE %s\r\n\r\n',modelADVAN);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $PK - Start
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'$PK\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $PK - PK parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; Parameters\r\n');
+
+% FACTOR_UNITS
+fprintf(fid,'    FACTOR_UNITS = %g\r\n',FACTOR_UNITS);
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $PK - Start by THETAs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+MU_param_text = {};
+for k=1:length(parameterNames)
+    MU_param_text{k} = sprintf('    MU_%d%s = THETA(%d)%sX#X#X    ; %s\r\n',k,char(32*ones(1,2-length(num2str(k)))),k,char(32*ones(1,2-length(num2str(k)))),parameterNames{k});
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $PK - Introduce covariates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+beta_parameters     = {};
+beta_parameters_cov_project_info     = {};
+beta_parameters_cat_project_info     = {};
+THETA_INDEX_BETA    = [];
+cov_type_continuous = [];
+covparam            = {};
+covcov              = {};
+
+COV_transformation_info = {};
+CAT_reference_info = {};
+CAT_categories_info = {};
+
+COVCATestimate_info = [];
+
+%%%%%%%%%%%%%%%%%%%%
+% Handle the CONTINUOUS covariate definitions and their introduction into
+% the MU referencing.
+%%%%%%%%%%%%%%%%%%%%
+parameter_add_cov   = {};
+cov_add_cov         = {};
+cov_add_median      = [];
+covTrans_text       = {};
+count = 1;
+for kcov=1:length(covariateModel),
+    covParam = covariateModel{kcov}{1};
+    covCOVs  = covariateModel{kcov}(2:end);
+    for k2=1:length(covCOVs),
+        if ismember(covCOVs{k2},covariateMedianNames),
+            beta_parameters{end+1}      = sprintf('beta_%s(%s)',covParam,covCOVs{k2});
+            theta_index                 = length(parameterNames)+count;
+            THETA_INDEX_BETA(end+1)     = theta_index;
+            cov_type_continuous(end+1)  = 1;
+            count                       = count+1;
+            parameter_add_cov{end+1}    = covParam;
+            cov_add_cov{end+1}          = covCOVs{k2};
+            cov_median                  = covariateMedianValues(strmatchSB(covCOVs{k2},covariateMedianNames,'exact'));
+            cov_add_median(end+1)       = cov_median;
+            
+            COVCATestimate_info(end+1)  = COVestimate{kcov}(k2);
+            
+            % find index of parameter to add covariate to
+            ix                          = strmatchSB(covParam,parameterNames,'exact');
+            % Get transformation
+            TRANS                       = IIVdistribution{ix};
+            if TRANS=='N',
+                covTrans_text{end+1} = sprintf('+ THETA(%d)*log(%s/%g) ',theta_index,covCOVs{k2},cov_median);
+                COV_transformation_info{end+1} = sprintf('log(cov/%g)',cov_median);
+            elseif TRANS=='L',
+                covTrans_text{end+1} = sprintf('+ THETA(%d)*log(%s/%g) ',theta_index,covCOVs{k2},cov_median);
+                COV_transformation_info{end+1} = sprintf('log(cov/%g)',cov_median);
+            elseif TRANS=='G',
+                covTrans_text{end+1} = sprintf('+ THETA(%d)*log(%s/%g) ',theta_index,covCOVs{k2},cov_median);
+                COV_transformation_info{end+1} = sprintf('log(cov/%g)',cov_median);
+            end
+        end
+    end
+end
+% Aggregate covariate text for each parameter
+cov_add_text_param = cell(1,length(parameterNames));
+cov_add_text_param(1:end) = {''};
+for k=1:length(parameter_add_cov),
+    ix = strmatchSB(parameter_add_cov{k},parameterNames,'exact');
+    cov_add_text_param{ix} = [cov_add_text_param{ix} covTrans_text{k}];
+end
+% Add continuous covariates into MU_param_text
+for k=1:length(MU_param_text),
+    MU_param_text{k} = strrep(MU_param_text{k},'X#X#X',[strtrim(cov_add_text_param{k}) 'X#X#X']);
+end
+% Save for later
+covparam            = parameter_add_cov;
+covcov              = cov_add_cov;
+
+beta_parameters_cov_project_info     = beta_parameters;
+
+
+%%%%%%%%%%%%%%%%%%%%
+% Handle the categorical covariates
+% 
+% Example:
+% SEX_1 = 0 (can be omitted)
+% SEX_2 = 0
+% SEX_3 = 0
+% IF SEX==1 THEN SEX_1 = 1 (can be omitted)
+% IF SEX==2 THEN SEX_2 = 1
+% IF SEX==3 THEN SEX_3 = 1
+%     
+% MU_3  = THETA(3) + beta_SEX_2_WT*SEX_2 + beta_SEX_3_WT*SEX_3
+% 
+% Assume reference is always the first one with the smallest number
+%%%%%%%%%%%%%%%%%%%%
+
+text_defining_cat_auxiliaries = '';
+cov_text = cell(1,length(parameterNames));
+cov_text(1:end) = {''};
+covs_handled_text_defining_cat_auxiliaries = {};
+for kcov=1:length(covariateModel),
+    covParam = covariateModel{kcov}{1};
+    covCOVs  = covariateModel{kcov}(2:end);
+    for k2=1:length(covCOVs),
+        if ismember(covCOVs{k2},covariateCATNames),
+            cov                         = covCOVs{k2};
+            cov_values                  = covariateCATValues{strmatchSB(covCOVs{k2},covariateCATNames,'exact')};
+            reference_value             = cov_values(1);
+            other_values                = cov_values(2:end);
+            
+            CAT_reference_info{end+1}   = reference_value;
+            CAT_categories_info{end+1}  = cov_values;
+                        
+            % Define the auxiliary text to be added before the MU thingy
+            if ~ismember(cov,covs_handled_text_defining_cat_auxiliaries),
+                for kaux=1:length(other_values),
+                    text_defining_cat_auxiliaries = sprintf('%s    %s_%d = 0 ; reference: %d\r\n',text_defining_cat_auxiliaries,cov,other_values(kaux),reference_value);
+                end
+                for kaux=1:length(other_values),
+                    text_defining_cat_auxiliaries = sprintf('%s    IF(%s.EQ.%d) %s_%d = 1\r\n',text_defining_cat_auxiliaries,cov,other_values(kaux),cov,other_values(kaux));
+                end
+                % Set cov as handled
+                covs_handled_text_defining_cat_auxiliaries{end+1} = cov;
+            end
+            
+            % Define the rest
+            for kaux=1:length(other_values),
+                COVCATestimate_info(end+1)  = COVestimate{kcov}(k2);
+                
+                covparam{end+1} = covParam;
+                covcov{end+1} = cov;
+                beta_parameters{end+1}      = sprintf('beta_%s(%s_%d)',covParam,cov,other_values(kaux));
+
+                % Check if beta_parameters_cat_project_info already
+                % contains element
+                element_add_check = sprintf('beta_%s(%s)',covParam,cov);
+                if isempty(strmatchSB(element_add_check,beta_parameters_cat_project_info,'exact')),
+                    % not present => add it
+                    beta_parameters_cat_project_info{end+1} = element_add_check;
+                end
+                
+                if isempty(THETA_INDEX_BETA),
+                    nextindex = length(parameterNames)+1;
+                else
+                    nextindex                   = max(THETA_INDEX_BETA)+1;
+                end
+                THETA_INDEX_BETA(end+1)     = nextindex;
+                cov_type_continuous(end+1)  = 0;
+                ixParam                     = strmatchSB(covParam,parameterNames,'exact');
+                cov_text{ixParam}           = sprintf('%s + THETA(%d)*%s_%d',cov_text{ixParam},nextindex,cov,other_values(kaux));
+            end
+        end
+    end
+end
+
+% Add continuous covariates into MU_param_text
+for k=1:length(MU_param_text),
+    MU_param_text{k} = strrep(MU_param_text{k},'X#X#X',cov_text{k});
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $PK - Write out the auxiliaries if needed
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(text_defining_cat_auxiliaries),
+    fprintf(fid,'; Auxiliary definitions for handling categorical covariates\r\n');
+    fprintf(fid,'%s\r\n',text_defining_cat_auxiliaries);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $PK - MU Referencing
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; MU Referencing\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle MU_param_text to wrap lines
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+MAXLENGTHLINE = 80;
+for k=1:length(MU_param_text),
+    if length(MU_param_text{k}) > MAXLENGTHLINE,
+        xxx = MU_param_text{k};
+        % Get first additive element
+        ix = strfind(xxx,' + ');
+        ix = ix(1);
+        text_start = xxx(1:ix(1));
+        text_wrap = xxx(ix(1)+3:end);
+        pieces_wrap = {};
+        while length(text_wrap)>MAXLENGTHLINE,
+            ix = strfind(text_wrap,' + ');
+            ixx = ix(find(ix>MAXLENGTHLINE)-1);
+            if ~isempty(ixx),
+                ix = ixx(1);
+            else
+                ix = ix(end);
+            end
+            pieces_wrap{end+1} = text_wrap(1:ix);
+            text_wrap = text_wrap(ix+3:end);
+        end        
+        pieces_wrap{end+1} = text_wrap;
+        for k2=1:length(pieces_wrap),
+            if k2==1,
+                pieces_wrap{k2} = sprintf('    MU%dWRAP_%d = %s',k,k2,strtrim(pieces_wrap{k2}));
+            else
+                pieces_wrap{k2} = sprintf('    MU%dWRAP_%d = MU%dWRAP_%d + %s',k,k2,k,k2-1,strtrim(pieces_wrap{k2}));
+            end
+        end
+        pieces_wrap{end+1} = sprintf('%s + MU%dWRAP_%d',text_start,k,k2);
+        
+        % Put together
+        xxx = '';
+        for k2=1:length(pieces_wrap),
+            xxx = sprintf('%s%s\r\n',xxx,pieces_wrap{k2});
+        end
+        
+        MU_param_text{k} = xxx;
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $PK - Write out the MU parameter definitions with covariates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(MU_param_text),
+    fprintf(fid,'%s',MU_param_text{k});
+end
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $PK - Parameter transformations
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; MU+ETA\r\n');
+for k=1:length(parameterNames),
+    fprintf(fid,'    T_%s%s = MU_%d + ETA(%d)\r\n',parameterNames{k},char(32*ones(1,cellmaxlengthSBPOP(parameterNames)-length(parameterNames{k})+1)),k,k);
+end
+fprintf(fid,'\r\n');
+
+fprintf(fid,'; Parameter transformations\r\n');
+for k=1:length(parameterNames),
+    if IIVdistribution{k} == 'N',
+        fprintf(fid,'    %s%s = T_%s\r\n',parameterNames{k},char(32*ones(1,cellmaxlengthSBPOP(parameterNames)-length(parameterNames{k})+1)),parameterNames{k});
+    elseif  IIVdistribution{k} == 'L',
+        fprintf(fid,'    %s%s = EXP(T_%s)\r\n',parameterNames{k},char(32*ones(1,cellmaxlengthSBPOP(parameterNames)-length(parameterNames{k})+1)),parameterNames{k});
+    elseif  IIVdistribution{k} == 'G',
+        fprintf(fid,'    %s%s = EXP(T_%s)/(1+EXP(T_%s))\r\n',parameterNames{k},char(32*ones(1,cellmaxlengthSBPOP(parameterNames)-length(parameterNames{k})+1)),parameterNames{k},parameterNames{k});
+    else
+        error('Unknown distribution.');
+    end
+end
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $PK - Renaming to match the used ADVAN/TRANS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; Renaming to match %s\r\n',modelADVAN);
+for k=1:length(paramNamesODE),
+    fprintf(fid,'    %s = %s\r\n',paramNamesADVAN{k},paramNamesODE{k});
+end
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $PK - Compartment assignment, etc.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; Dosing compartments info\r\n');
+fprintf(fid,'    F1 = FACTOR_UNITS*Fabs1 ; Ad\r\n');
+fprintf(fid,'    F2 = FACTOR_UNITS*Fiv   ; Ac\r\n');
+fprintf(fid,'\r\n');
+fprintf(fid,'    ALAG1 = Tlag_input1\r\n');
+fprintf(fid,'\r\n');
+fprintf(fid,'    S2 = %s\r\n',paramNamesADVAN{strmatchSB('Vc',paramNamesODE,'exact')});
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $ERROR
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'$ERROR\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $ERROR - error models
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define next index for THETA parameters
+if isempty(THETA_INDEX_BETA),
+    THETA_INDEX_NEXT = length(parameterNames)+1;
+else
+    THETA_INDEX_NEXT = max(THETA_INDEX_BETA)+1;
+end
+THETA_ERROR_MODELS_IX = [];
+THETA_ERROR_MODELS_NAME = {};
+THETA_ERROR_MODELS_VALUE = [];
+error_model = explodePCSB(errorModels);
+
+output_parameters_project_info = {};
+
+fprintf(fid,'; just to avoid a NONMEM warning\r\n');
+fprintf(fid,'    IPRED = 0.1\r\n');
+fprintf(fid,'    IRES  = 0\r\n');
+fprintf(fid,'    IWRES = 0\r\n');
+fprintf(fid,'    W     = 0\r\n');
+fprintf(fid,'    Y     = 0.1\r\n\r\n');
+
+fprintf(fid,'; Error model\r\n');
+fprintf(fid,'    IF(YTYPE.EQ.1) THEN\r\n');
+fprintf(fid,'        IPRED  = F\r\n');
+fprintf(fid,'        IRES   = DV - IPRED\r\n');
+
+count = 1;
+if strcmp(lower(error_model{1}),'const'),
+    fprintf(fid,'        W      = THETA(%d)\r\n',THETA_INDEX_NEXT);
+    THETA_ERROR_MODELS_IX(end+1) = THETA_INDEX_NEXT;
+    THETA_ERROR_MODELS_NAME{end+1} = sprintf('Additive error');
+    THETA_ERROR_MODELS_VALUE(end+1) = errorParam0(count);
+    count = count + 1;
+    THETA_INDEX_NEXT = THETA_INDEX_NEXT+1;
+    output_parameters_project_info{end+1} = sprintf('error_ADD1');
+elseif strcmp(lower(error_model{1}),'prop'),
+    fprintf(fid,'        W      = THETA(%d)*IPRED\r\n',THETA_INDEX_NEXT);
+    THETA_ERROR_MODELS_IX(end+1) = THETA_INDEX_NEXT;
+    THETA_ERROR_MODELS_NAME{end+1} = sprintf('Proportional error');
+    THETA_ERROR_MODELS_VALUE(end+1) = errorParam0(count);
+    count = count + 1;
+    THETA_INDEX_NEXT = THETA_INDEX_NEXT+1;
+    output_parameters_project_info{end+1} = sprintf('error_PROP1');
+elseif strcmp(lower(error_model{1}),'comb1'),
+    fprintf(fid,'        W      = SQRT(THETA(%d)**2 + (THETA(%d)*IPRED)**2)\r\n',THETA_INDEX_NEXT,THETA_INDEX_NEXT+1);
+    THETA_ERROR_MODELS_IX(end+1) = THETA_INDEX_NEXT;
+    THETA_ERROR_MODELS_IX(end+1) = THETA_INDEX_NEXT+1;
+    THETA_ERROR_MODELS_NAME{end+1} = sprintf('Additive error');
+    THETA_ERROR_MODELS_NAME{end+1} = sprintf('Proportional error');
+    THETA_ERROR_MODELS_VALUE(end+1) = errorParam0(count);
+    count = count + 1;
+    THETA_ERROR_MODELS_VALUE(end+1) = errorParam0(count);
+    count = count + 1;
+    THETA_INDEX_NEXT = THETA_INDEX_NEXT+2;
+    output_parameters_project_info{end+1} = sprintf('error_ADD1');
+    output_parameters_project_info{end+1} = sprintf('error_PROP1');
+else
+    error('Unknown error model definition.');
+end
+
+fprintf(fid,'        IWRES  = IRES/W\r\n');
+fprintf(fid,'        Y      = IPRED + W*ERR(1)\r\n');
+fprintf(fid,'    ENDIF\r\n');
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Assign variables to report in tables
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% ETAs:
+fprintf(fid,'; Assign variables to report in tables\r\n');
+for k=1:length(parameterNames),
+    fprintf(fid,'    ETA_%s%s = ETA(%d)\r\n',parameterNames{k},char(32*ones(1,cellmaxlengthSBPOP(parameterNames)-length(parameterNames{k})+1)),k);
+end
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $THETA for model parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'$THETA\r\n');
+
+fprintf(fid,'; Model parameters\r\n');
+
+THETA_GUESS0_STRING = {};
+PARAM_TRANSNAME_STRING = {};
+PARAM_INVTRANSNAME_STRING = {};
+initialGuess_noTrans = [];
+for k=1:length(parameterNames),
+    initialGuess = POPvalues0(k);
+    initialGuess_noTrans(k) = POPvalues0(k);
+    if IIVdistribution{k} == 'N',
+        initialGuess = initialGuess;
+        if POPestimate(k),
+            if initialGuess == 0,
+                initialGuess = 0.01;
+            end
+        end
+        PARAM_TRANSNAME_STRING{k} = '(psi)';
+        PARAM_INVTRANSNAME_STRING{k} = '(phi)';
+    elseif IIVdistribution{k} == 'L';
+        initialGuess = log(initialGuess);
+        if POPestimate(k),
+            if initialGuess == 0,
+                initialGuess = 0.01;
+            end
+        end
+        PARAM_TRANSNAME_STRING{k} = 'log(psi)';
+        PARAM_INVTRANSNAME_STRING{k} = 'exp(phi)';
+    elseif IIVdistribution{k} == 'G',
+        initialGuess = log(initialGuess/(1-initialGuess));
+        if POPestimate(k),
+            if initialGuess == 0,
+                initialGuess = 0.01;
+            end
+        end
+        PARAM_TRANSNAME_STRING{k} = 'log(psi./(1-psi))';
+        PARAM_INVTRANSNAME_STRING{k} = 'exp(phi)./(1+exp(phi))';
+    else
+        error('Unknown parameter transformation.');
+    end
+    THETA_GUESS0_STRING{k} = sprintf('%1.3g',initialGuess);
+    % Check if parameter fixed or not
+    if POPestimate(k) == 0,
+        THETA_GUESS0_STRING{k} = [THETA_GUESS0_STRING{k} '  FIX'];
+    end
+end    
+
+for k=1:length(parameterNames),
+    texttext = strrep(PARAM_TRANSNAME_STRING{k},'psi',parameterNames{k});
+    fprintf(fid,'    %s%s ; %d %s (%1.3g)\r\n',THETA_GUESS0_STRING{k},char(32*ones(1,cellmaxlengthSBPOP(THETA_GUESS0_STRING)-length(THETA_GUESS0_STRING{k})+1)),k,texttext,initialGuess_noTrans(k));
+end
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $THETA for continuous covariate parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+THETA_INDEX_BETA_cov = THETA_INDEX_BETA(cov_type_continuous==1);
+beta_parameters_cov  = beta_parameters(cov_type_continuous==1);
+
+if ~isempty(COVestimate) && ~isempty(THETA_INDEX_BETA_cov),
+    fprintf(fid,'; Continuous covariate model parameters\r\n');
+    count = 1;
+    for kparam=1:length(COVestimate),
+        for kcov=1:length(COVestimate{kparam}),
+            estimate = COVestimate{kparam}(kcov);
+            value    = covariateModelValues{kparam}(kcov);
+            cov      = covariateModel{kparam}{kcov+1};
+            if ismember(cov,covNames),
+                % Only handle if covariate member iof continuous covariates
+                index    = THETA_INDEX_BETA_cov(count);
+                param    = beta_parameters_cov{count};
+                count    = count+1;
+                if estimate,
+                    if value==0,
+                        value = 0.01;
+                    end
+                    fprintf(fid,'    %g ; %d %s\r\n',value,index,param);
+                else
+                    fprintf(fid,'    %g FIX ; %d %s\r\n',value,index,param);
+                end
+            end
+        end
+    end
+    fprintf(fid,'\r\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $THETA for categorical covariate parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+THETA_INDEX_BETA_cat = THETA_INDEX_BETA(cov_type_continuous==0);
+beta_parameters_cat  = beta_parameters(cov_type_continuous==0);
+covcov_cat           = covcov(cov_type_continuous==0);
+covparam_cat         = covparam(cov_type_continuous==0);
+
+if ~isempty(COVestimate) &&  ~isempty(THETA_INDEX_BETA_cat),
+    fprintf(fid,'; Categorical covariate model parameters\r\n');
+    for k=1:length(THETA_INDEX_BETA_cat),
+        % Get parameter name
+        param = covparam_cat{k};
+        % Get covariate name
+        cov = covcov_cat{k};
+        
+        % Find index of parameter in covariateModel
+        covModelAllParam = {};
+        for k2=1:length(covariateModel),
+            covModelAllParam{end+1} = covariateModel{k2}{1};
+        end
+        ixparam = strmatchSB(param,covModelAllParam,'exact');
+        
+        % Find index of cov in covariateModel{ixparam}
+        ixcov = strmatchSB(cov,covariateModel{ixparam},'exact');
+        
+        % Is this covariate estimated?
+        estimate = COVestimate{ixparam}(ixcov-1);
+        
+        % Which is the value
+        value = covariateModelValues{ixparam}(ixcov-1);
+        
+        % Write out
+        if estimate,
+            if value == 0,
+                value = 0.01;
+            end
+            fprintf(fid,'    %g ; %d %s\r\n',value,THETA_INDEX_BETA_cat(k),beta_parameters_cat{k});
+        else
+            fprintf(fid,'    %g FIX ; %d %s\r\n',value,THETA_INDEX_BETA_cat(k),beta_parameters_cat{k});
+        end
+    end
+    fprintf(fid,'\r\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $THETA for error model parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; Error model parameters\r\n');
+for k=1:length(THETA_ERROR_MODELS_IX),
+    fprintf(fid,'    %g%s ; %d %s\r\n',THETA_ERROR_MODELS_VALUE(k),char(32*ones(1,cellmaxlengthSBPOP(THETA_GUESS0_STRING)-length('1')+1)),THETA_ERROR_MODELS_IX(k),THETA_ERROR_MODELS_NAME{k});
+end
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $OMEGA
+% Using standard deviations and correlations
+%
+% $OMEGA STANDARD CORRELATION BLOCK(2)
+% 0.8
+% -0.394 0.762
+%
+% or:
+% $OMEGA
+% 0.8 STANDARD
+% 0.5 STANDARD
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+	
+if strcmp(lower(covarianceModel),'diagonal') || isempty(covarianceModel),
+    fprintf(fid,'$OMEGA\r\n');
+    OMEGA_GUESS0_STRING = {};
+    for k=1:length(parameterNames),
+        if IIVestimate(k) == 0,
+            % Set IIV value to 0 and FIX
+            OMEGA_GUESS0_STRING{k} = sprintf('0 STANDARD FIX');
+        elseif IIVestimate(k) == 1,
+            value = IIVvalues0(k);
+            if value == 0,
+                value = 0.1;
+            end
+            % Set IIV value
+%             OMEGA_GUESS0_STRING{k} = sprintf('%1.2g',(value)^2); % Convert IIV values from STD to VAR
+            OMEGA_GUESS0_STRING{k} = sprintf('%1.2g STANDARD',value); % USE STD
+        elseif IIVestimate(k) == 2,
+            % Set IIV value and FIX
+%             OMEGA_GUESS0_STRING{k} = sprintf('%1.2g  FIX',(IIVvalues0(k))^2); % Convert IIV values from STD to VAR
+            OMEGA_GUESS0_STRING{k} = sprintf('%1.2g STANDARD FIX',IIVvalues0(k)); % Convert IIV values from STD to VAR
+        end
+    end
+    for k=1:length(parameterNames),
+        fprintf(fid,'    %s%s ; %d %s\r\n',OMEGA_GUESS0_STRING{k},char(32*ones(1,cellmaxlengthSBPOP(OMEGA_GUESS0_STRING)-length(OMEGA_GUESS0_STRING{k})+1)),k,parameterNames{k});
+    end
+else
+    % Handle the covariances ... block by block
+    terms = explodePCSB(covarianceModel,',','{','}');
+    for k=1:length(terms),
+        block = terms{k};
+        block = strrep(block,'{','');
+        block = strrep(block,'}','');
+        block = explodePCSB(block);
+        ix_parameters = [];
+        for k2=1:length(block),
+            ix_parameters(end+1) = strmatchSB(block{k2},parameterNames);
+        end
+        % Need to reorder each block to match the order of the parameters
+        % in param_est.name. It already has been made sure that they are
+        % sequential.
+        ix_parameters_ordered = sort(ix_parameters,'ascend');
+        % Construct the block text
+        blockText = sprintf('$OMEGA STANDARD CORRELATION BLOCK(%d)\r\n',length(block));
+        blockMatrix = 0.1*ones(length(ix_parameters_ordered));
+        for k=1:length(ix_parameters_ordered),
+            value = IIVvalues0(ix_parameters_ordered(k));
+            if value == 0,
+                value = 0.1;
+            end
+            blockMatrix(k,k) = value; % No need to convert, since in STD
+        end
+        for krow=1:length(block),
+            for kcol=1:krow,
+                blockText = sprintf('%s    %1.2g',blockText,blockMatrix(krow,kcol));
+            end
+            blockText = sprintf('%s    ; %d %s',blockText,ix_parameters_ordered(krow),parameterNames{ix_parameters_ordered(krow)});
+            blockText = sprintf('%s\r\n',blockText);
+        end
+        fprintf(fid,'%s\r\n',blockText);
+    end
+    
+    % Finally find the parameters that have not been handled yet by the
+    % block things ...
+    x = strrep(covarianceModel,'{','');
+    x = strrep(x,'}','');
+    terms = explodePCSB(x);
+    missingParam = setdiff(parameterNames,terms);
+    % These are not in the right order ...
+    ix_parameters = [];
+    for k2=1:length(missingParam),
+        ix_parameters(end+1) = strmatchSB(missingParam{k2},parameterNames,'exact');
+    end
+    % Need to reorder according to their appearance in the model
+    % It already has been made sure that they are sequential.
+    ix_parameters_ordered = sort(ix_parameters,'ascend');
+    
+    if ~isempty(missingParam),
+        fprintf(fid,'$OMEGA\r\n');
+    end
+    OMEGA_GUESS0_STRING = {};
+    for k=1:length(missingParam),
+        if IIVestimate(ix_parameters_ordered(k)) == 0,
+            % Set IIV value to 0 and FIX
+            OMEGA_GUESS0_STRING{k} = sprintf('0 STANDARD FIX');
+        elseif IIVestimate(ix_parameters_ordered(k)) == 1,
+            value = IIVvalues0(ix_parameters_ordered(k));
+            if value == 0,
+                value = 0.1;
+            end
+            % Set IIV value
+            OMEGA_GUESS0_STRING{k} = sprintf('%1.2g STANDARD',value); % Need to convert from STD to VAR
+        elseif IIVestimate(ix_parameters_ordered(k)) == 2,
+            % Set IIV value and FIX
+            OMEGA_GUESS0_STRING{k} = sprintf('%1.2g STANDARD FIX',IIVvalues0(ix_parameters_ordered(k))); % Need to convert from STD to VAR
+        end
+    end    
+    for k=1:length(missingParam),
+        fprintf(fid,'    %s%s ; %d %s\r\n',OMEGA_GUESS0_STRING{k},char(32*ones(1,cellmaxlengthSBPOP(OMEGA_GUESS0_STRING)-length(OMEGA_GUESS0_STRING{k})+1)),ix_parameters_ordered(k),parameterNames{ix_parameters_ordered(k)});
+    end
+end
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $SIGMA
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'$SIGMA 1 FIX\r\n');
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $ESTIMATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if ITS done as first method
+if ITS,
+    % ITS
+    if strcmp(upper(METHOD),'FO') || strcmp(upper(METHOD),'FOCE'),
+        text = sprintf('$ESTIMATION METHOD=ITS NOINTERACTION NOABORT NITER=%d SIGDIGITS=%d PRINT=%d\r\n',ITS_ITERATIONS,SIGDIGITS,PRINT);
+    else
+        text = sprintf('$ESTIMATION METHOD=ITS INTERACTION NOABORT NITER=%d SIGDIGITS=%d PRINT=%d\r\n',ITS_ITERATIONS,SIGDIGITS,PRINT);
+    end
+    fprintf(fid,'%s\r\n',wrapRowTextSBPOP(text,80,12));
+end    
+
+% Then the "Main" Method
+if strcmp(upper(METHOD),'FO'),
+    % FO
+    text = sprintf('$ESTIMATION METHOD=ZERO NOINTERACTION NOABORT MAXEVAL=%d CTYPE=4 POSTHOC SIGDIGITS=%d PRINT=%d\r\n',MAXEVAL,SIGDIGITS,PRINT);
+    fprintf(fid,'%s\r\n',wrapRowTextSBPOP(text,80,12));
+elseif strcmp(upper(METHOD),'FOCE'),
+    % FOCE
+    text = sprintf('$ESTIMATION METHOD=CONDITIONAL NOINTERACTION NOABORT MAXEVAL=%d CTYPE=4 POSTHOC SIGDIGITS=%d PRINT=%d\r\n',MAXEVAL,SIGDIGITS,PRINT);
+    fprintf(fid,'%s\r\n',wrapRowTextSBPOP(text,80,12));
+elseif strcmp(upper(METHOD),'FOCEI'),
+    % FOCEI
+    text = sprintf('$ESTIMATION METHOD=CONDITIONAL INTERACTION NOABORT MAXEVAL=%d CTYPE=4 POSTHOC SIGDIGITS=%d PRINT=%d\r\n',MAXEVAL,SIGDIGITS,PRINT);
+    fprintf(fid,'%s\r\n',wrapRowTextSBPOP(text,80,12));
+elseif strcmp(upper(METHOD),'SAEM'),
+    % SAEM
+    text = sprintf('$ESTIMATION METHOD=SAEM INTERACTION NOABORT NBURN=%d NITER=%d ISAMPLE=%d CONSTRAIN=1 CTYPE=0 SEED=%d POSTHOC SIGDIGITS=%d PRINT=%d\r\n',K1,K2,NRCHAINS,SEED,SIGDIGITS,PRINT);
+    fprintf(fid,'%s\r\n',wrapRowTextSBPOP(text,80,12));
+else
+    error('Unknown estimation method.');
+end
+
+% Then check if importance sampling to be done for objective function evaluation
+if IMPORTANCESAMPLING,
+    text = sprintf('$ESTIMATION METHOD=IMP NOABORT EONLY=1 ISAMPLE=1000 NITER=%d MAPITER=0 SIGDIGITS=%d PRINT=%d',IMP_ITERATIONS,SIGDIGITS,PRINT);
+    fprintf(fid,'%s\r\n',wrapRowTextSBPOP(text,80,12));
+end
+
+fprintf(fid,'\r\n');
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $COVARIANCE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'$COVARIANCE UNCONDITIONAL MATRIX=S\r\n');
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define FORMAT for all TABLEs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+FORMAT = 's1PG15.6';
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $TABLE similar to predictions.txt in MONOLIX 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp(METHOD,'FO'),
+    text = sprintf('$TABLE ID TIME TIME2 YTYPE MDV EVID DV IPRED IRES IWRES NPDE NPRED=XPRED  NRES=XRES  NWRES=XWRES  NOPRINT ONEHEADER NOAPPEND FILE=project.pred FORMAT=%s',FORMAT);
+elseif strcmp(METHOD,'FOCE'), 
+    text = sprintf('$TABLE ID TIME TIME2 YTYPE MDV EVID DV IPRED IRES IWRES NPDE NPRED=XPRED  CRES=XRES  CWRES=XWRES  NOPRINT ONEHEADER NOAPPEND FILE=project.pred FORMAT=%s',FORMAT);
+elseif strcmp(METHOD,'FOCEI'),
+    text = sprintf('$TABLE ID TIME TIME2 YTYPE MDV EVID DV IPRED IRES IWRES NPDE CPREDI=XPRED CRESI=XRES CWRESI=XWRES NOPRINT ONEHEADER NOAPPEND FILE=project.pred FORMAT=%s',FORMAT);
+elseif strcmp(METHOD,'SAEM'),
+    text = sprintf('$TABLE ID TIME TIME2 YTYPE MDV EVID DV IPRED IRES IWRES NPDE EPRED=XPRED  ERES=XRES  EWRES=XWRES  NOPRINT ONEHEADER NOAPPEND FILE=project.pred FORMAT=%s ESAMPLE=1000 SEED=%d',FORMAT,SEED);
+else
+    error('Unknown method');
+end
+text = wrapRowTextSBPOP(text,80,7);
+% Print out table command
+fprintf(fid,'%s\r\n',text);
+fprintf(fid,'\r\n');
+  
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $TABLE similar to indiv_eta.txt in MONOLIX - include all covariates
+% in the dataset
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+text = 'ID';
+for k=1:length(parameterNames),
+    text = sprintf('%s ETA_%s',text,parameterNames{k});
+end
+% Add covariates
+for k=1:length(covNames),
+    text = sprintf('%s %s',text,covNames{k});
+end
+for k=1:length(catNames),
+    text = sprintf('%s %s',text,catNames{k});
+end
+% Create the full table command
+text = sprintf('$TABLE %s NOPRINT ONEHEADER FIRSTONLY NOAPPEND FILE=project.eta FORMAT=%s',text,FORMAT);
+text = wrapRowTextSBPOP(text,80,7);
+% Print out table command
+fprintf(fid,'%s\r\n',text);
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $TABLE similar to indiv_parameters.txt in MONOLIX - include all covariates
+% in the dataset - also include the regression parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+text = 'ID';
+for k=1:length(parameterNames),
+    text = sprintf('%s %s',text,parameterNames{k});
+end
+% Add covariates
+for k=1:length(covNames),
+    text = sprintf('%s %s',text,covNames{k});
+end
+for k=1:length(catNames),
+    text = sprintf('%s %s',text,catNames{k});
+end
+% Create the full table command
+text = sprintf('$TABLE %s NOPRINT ONEHEADER FIRSTONLY NOAPPEND FILE=project.indiv FORMAT=%s',text,FORMAT);
+text = wrapRowTextSBPOP(text,80,7);
+% Print out table command
+fprintf(fid,'%s\r\n',text);
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Close file and change out of project path
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fclose(fid);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Construct PROJECT_HEADER_PLACEHOLDER information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+PROJECT_INFO_TEXT = '';
+
+% Method
+METHOD_ALL = METHOD;
+if ITS,
+    METHOD_ALL = ['ITS,' METHOD_ALL];
+end
+if IMPORTANCESAMPLING,
+    METHOD_ALL = [METHOD_ALL ',IMP'];
+end
+METHOD_info = sprintf('; METHOD              = ''%s''\r\n',METHOD_ALL);
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,METHOD_info);
+
+% Data location
+DATA_info = sprintf('; DATA                = ''%s''\r\n',strrep(fullfile(dataRelPathFromProject,dataFileName),'\','/'));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,DATA_info);
+
+% covNames
+x = sprintf('%s,',covNames{:});
+COVNAMES_info = sprintf('; COVNAMES            = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,COVNAMES_info);
+
+% catNames
+x = sprintf('%s,',catNames{:});
+CATNAMES_info = sprintf('; CATNAMES            = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,CATNAMES_info);
+
+% Outputs
+OUTPUTS_info = sprintf('; OUTPUTS             = ''Cc''\r\n');
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,OUTPUTS_info);
+
+% Error models
+ERRORMODELS_info = sprintf('; ERRORMODELS         = ''%s''\r\n',errorModels);
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,ERRORMODELS_info);
+
+% ERRORNAMES
+x = sprintf('%s,',output_parameters_project_info{:});
+ERRORNAMES_info = sprintf('; ERRORNAMES          = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,ERRORNAMES_info);
+
+% PARAMNAMES
+x = sprintf('%s,',parameterNames{:});
+PARAMNAMES_info = sprintf('; PARAMNAMES          = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,PARAMNAMES_info);
+
+% PARAMTRANS
+x = sprintf('%s,',PARAM_TRANSNAME_STRING{:});
+PARAMTRANS_info = sprintf('; PARAMTRANS          = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,PARAMTRANS_info);
+
+% PARAMINVTRANS
+x = sprintf('%s,',PARAM_INVTRANSNAME_STRING{:});
+PARAMINVTRANS_info = sprintf('; PARAMINVTRANS       = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,PARAMINVTRANS_info);
+
+% COVARIATENAMES
+COVARIATENAMES = [covariateMedianNames,covariateCATNames];
+x = sprintf('%s,',COVARIATENAMES{:});
+COVARIATENAMES_info = sprintf('; COVARIATENAMES      = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,COVARIATENAMES_info);
+
+% BETACOVNAMES
+x = sprintf('%s,',beta_parameters_cov_project_info{:});
+BETACOVNAMES_info = sprintf('; BETACOVNAMES        = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,BETACOVNAMES_info);
+
+% TRANSCOV
+x = sprintf('%s,',COV_transformation_info{:});
+TRANSCOV_info = sprintf('; TRANSCOV            = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,TRANSCOV_info);
+
+% BETACATNAMES
+x = sprintf('%s,',beta_parameters_cat_project_info{:});
+BETACATNAMES_info = sprintf('; BETACATNAMES        = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,BETACATNAMES_info);
+
+% BETACATREFERENCE
+x = ''; for k=1:length(CAT_reference_info), x=sprintf('%s%g,',x,CAT_reference_info{k}); end
+BETACATREFERENCE_info = sprintf('; BETACATREFERENCE    = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,BETACATREFERENCE_info);
+
+% BETACATCATEGORIES
+x = ''; 
+for k=1:length(CAT_categories_info), 
+    x = [x '['];
+    x2 = '';
+    x2 = sprintf('%d ',CAT_categories_info{k});
+    x = [x x2(1:end-1) '],'];
+end
+BETACATCATEGORIES_info = sprintf('; BETACATCATEGORIES   = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,BETACATCATEGORIES_info);
+
+% ALL THETANAMES
+x = [parameterNames beta_parameters output_parameters_project_info];
+y = sprintf('%s,',x{:});
+THETANAMES_info = sprintf('; THETANAMES          = ''%s''\r\n',y(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,THETANAMES_info);
+
+% THETAESTIMATE
+% Add theta for parameters
+PARAM_info = sprintf('%d,',POPestimate);
+% Add theta for covariates
+COVCAT_info = sprintf('%d,',COVCATestimate_info);
+if isempty(COVCATestimate_info),
+    COVCAT_info = [];
+end
+% Add theta for error models
+x = ones(1,length(output_parameters_project_info));
+ERROR_info = sprintf('%d,',x);
+% Combine
+ESTIMATE_info = strtrim([PARAM_info COVCAT_info ERROR_info]);
+% Create text
+THETAESTIMATE_info = sprintf('; THETAESTIMATE       = ''%s''\r\n',ESTIMATE_info(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,THETAESTIMATE_info);
+
+% ALL ETANAMES (should be same as PARAMNAMES)
+x = sprintf('omega(%s),',parameterNames{:});
+ETANAMES_info = sprintf('; ETANAMES            = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,ETANAMES_info);
+
+% ETAESTIMATE
+ETAESTIMATE = sprintf('%d,',IIVestimate); 
+ETAESTIMATE_info = sprintf('; ETAESTIMATE         = ''%s''\r\n',ETAESTIMATE(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,ETAESTIMATE_info);
+
+% ALL CORRNAMES 
+cov = explodePCSB(covarianceModel,',','{','}');
+text = '';
+for k=1:length(cov),
+    covk = strrep(strrep(cov{k},'{',''),'}','');
+    covk = explodePCSB(covk);
+    for k1=1:length(covk),
+        for k2=1:k1,
+            if k1~=k2,
+                text = sprintf('%scorr(%s,%s),',text,covk{k1},covk{k2});
+            end
+        end
+    end
+end
+CORR_info = sprintf('; CORRELATIONNAMES    = ''%s''\r\n',text(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,CORR_info);
+
+% CORRESTIMATE
+if ~isempty(text),
+    CORRestimate = ones(1,length(explodePCSB(text(1:end-1))));
+    x = sprintf('%d,',CORRestimate); 
+    CORRESTIMATE_info = sprintf('; CORRESTIMATE        = ''%s''\r\n',x(1:end-1));
+else
+    CORRestimate = 0;
+    CORRESTIMATE_info = sprintf('; CORRESTIMATE        = ''''\r\n');
+end
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,CORRESTIMATE_info);
+
+% Get and store number of observations in the data
+% Remove MDV=1 records
+x = dataCSV(dataCSV.MDV==0,:);
+% Remove CMT>nrOUTPUTS or YTYPE>nrOUTPUT
+nrOUTPUTS = 1;
+x(x.YTYPE > nrOUTPUTS,:) = [];
+
+% Write out number of observations
+nOBS = length(x);
+NROBS_info = sprintf('; NROBSERVATIONS      = ''%d''\r\n',nOBS);
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,NROBS_info);
+
+% Determine the number of estimated parameters (THETA and ETA)
+NRPARAMETERS_ESTIMATED = sum(eval(['[' ESTIMATE_info(1:end-1) ']']))+sum(eval(['[' ETAESTIMATE(1:end-1) ']'])==1)+sum(CORRestimate);
+NRPARAMETERS_ESTIMATED_info = sprintf('; NRPARAM_ESTIMATED   = ''%d''\r\n',NRPARAMETERS_ESTIMATED);
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,NRPARAMETERS_ESTIMATED_info);
+
+% Info about residual names depending on the selected method
+RESIDUAL_NAMES_USED = sprintf('; RESIDUAL_NAMES_USED = ''XPRED,XRES,XWRES''\r\n');
+if strcmp(METHOD,'FO'),
+    RESIDUAL_NAMES_ORIG = sprintf('; RESIDUAL_NAMES_ORIG = ''NPRED,NRES,NWRES''\r\n');
+elseif strcmp(METHOD,'FOCE'), 
+    RESIDUAL_NAMES_ORIG = sprintf('; RESIDUAL_NAMES_ORIG = ''NPRED,CRES,CWRES''\r\n');
+elseif strcmp(METHOD,'FOCEI'),
+    RESIDUAL_NAMES_ORIG = sprintf('; RESIDUAL_NAMES_ORIG = ''CPREDI,CRESI,CWRESI''\r\n');
+elseif strcmp(METHOD,'SAEM'),
+    RESIDUAL_NAMES_ORIG = sprintf('; RESIDUAL_NAMES_ORIG = ''EPRED,ERES,EWRES''\r\n');
+end
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,RESIDUAL_NAMES_USED);
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,RESIDUAL_NAMES_ORIG);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Replace PROJECT_HEADER_PLACEHOLDER
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+content = fileread('project.nmctl');
+content = strrep(content,'PROJECT_HEADER_PLACEHOLDER',strtrim(PROJECT_INFO_TEXT));
+fid = fopen('project.nmctl','w');
+fprintf(fid,'%s',content);
+fclose(fid);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Go back to old path
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+cd(oldpath);
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/05_ModelBuilding/templateModels/template_popPK_dosing.dos b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/05_ModelBuilding/templateModels/template_popPK_dosing.dos
new file mode 100644
index 0000000000000000000000000000000000000000..78b5cafe294521ae955fb7bf5500ce57f04a3af6
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/05_ModelBuilding/templateModels/template_popPK_dosing.dos
@@ -0,0 +1,25 @@
+********** DOSING NAME
+template_dosing
+
+********** DOSING NOTES
+This is a template dosing scheme for popPK analysis.
+
+Assumption is that INPUT2 goes into central compartment as either bolus or 
+infusion - depending on the TINF information in the dataset
+
+And that INPUT1 is first order absorption, going into the central 
+compartment. Since the absorption compartment is included in the model,
+INPUT2 is realized as BOLUS.
+
+********** INPUT1
+type:   BOLUS
+time:   0            % time for first application or all applications (scalar or vector)
+D:      0            % dose (scalar or vector)
+Tlag:   1            % <estimate> lag time for input application
+
+********** INPUT2
+type:   INFUSION
+time:   0            % time for first application or all applications (scalar or vector)
+D:      0            % dose (scalar or vector)
+Tinf:   1            % Infusion rate (required)
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/05_ModelBuilding/templateModels/template_popPK_model.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/05_ModelBuilding/templateModels/template_popPK_model.txt
new file mode 100644
index 0000000000000000000000000000000000000000..d2d14297b1abb7d6d2a544c352cb73c9c9964704
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/05_ModelBuilding/templateModels/template_popPK_model.txt
@@ -0,0 +1,85 @@
+********** MODEL NAME
+template_basemodel
+
+********** MODEL NOTES
+This model by itself is not simulatable. It requires merging with the dosing
+scheme to allow for simulation (Dose_input2 needs to be defined).
+
+This model is NOT used for the fitting part. It is here because this is what
+is converted to MLXTRAN to serve as the nonlinear basemodel.
+
+This is a template for a popPK basemodel.
+
+Features
+========
+- Central compartment Ac
+- 2 peripheral compartments Ap1 and Ap2
+- Linear clearance from central compartment
+- Saturable (Michaelis-Menten) clearance from central compartment
+- Linear distribution between central and peripheral compartments
+- Allowing for 2 differnt inputs
+	    - INPUT1: first order absorption into central compartment
+	    - INPUT2: bolus/infusion into central compartment
+
+Limitation
+==========
+    
+Units:
+======
+- No assumption is made regarding the time units
+- Units of INPUT dose and OUTPUT concentration need to match or be 
+  adjusted by FACTOR_UNITS 
+
+********** MODEL STATES
+
+% Dosing compartment for first order absorption
+d/dt(Ad)    = -ka*Ad + FACTOR_UNITS*Fabs1*INPUT1
+
+% Central compartment
+d/dt(Ac)    = +ka*Ad - CL/Vc*Ac - (VMAX*Ac/Vc)/(KM+Ac/Vc) - Q1/Vc*Ac + Q1/Vp1*Ap1 - Q2/Vc*Ac + Q2/Vp2*Ap2 + FACTOR_UNITS*Fiv*INPUT2    
+
+% First peripheral compartment
+d/dt(Ap1)   =                                             + Q1/Vc*Ac - Q1/Vp1*Ap1 
+
+% Second peripheral compartment
+d/dt(Ap2)   =                                                                     + Q2/Vc*Ac - Q2/Vp2*Ap2
+
+********** MODEL PARAMETERS
+
+% Linear components
+FACTOR_UNITS = 1
+
+CL           = 0     % <estimate>   
+Vc           = 1     % <estimate>             
+Q1           = 0     % <estimate>   
+Vp1          = 1     % <estimate>   
+Q2           = 0     % <estimate>   
+Vp2          = 1     % <estimate>   
+
+Fiv          = 1     % <estimate>   
+Fabs1        = 1     % <estimate>   
+ka           = 1     % <estimate>   
+
+% Saturable elimination
+VMAX         = 0     % <estimate>   
+KM           = 1     % <estimate>   
+
+********** MODEL VARIABLES
+
+% Determine concentration in dataset units
+Cc          = Ac/Vc 
+
+% Set output variable for Monolix
+OUTPUT1     = Cc
+
+********** MODEL REACTIONS
+
+
+********** MODEL FUNCTIONS
+
+
+********** MODEL EVENTS
+
+
+********** MODEL MATLAB FUNCTIONS
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/05_ModelBuilding/templateModels/template_popPK_model_ANALYTIC_MLXTRAN.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/05_ModelBuilding/templateModels/template_popPK_model_ANALYTIC_MLXTRAN.txt
new file mode 100644
index 0000000000000000000000000000000000000000..df6d6b25c000e55bbcbb8376526e02a7e5833d4b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/05_ModelBuilding/templateModels/template_popPK_model_ANALYTIC_MLXTRAN.txt
@@ -0,0 +1,59 @@
+; =============================================
+DESCRIPTION: template_basemodel
+; =============================================
+	This is a template for a popPK basemodel. ANALYTIC version.
+	
+	Features
+	========
+	- Central compartment Ac
+	- 2 peripheral compartments Ap1 and Ap2
+	- Linear clearance from central compartment
+	- Linear distribution between central and peripheral compartments
+	- Allowing for 2 differnt inputs
+	    - INPUT1: first order absorption into central compartment
+	    - INPUT2: bolus/infusion into central compartment
+	
+	Limitation
+	==========
+	    
+	Units:
+	======
+	- No assumption is made regarding the t units
+	- Units of INPUT dose and OUTPUT concentration need to match or be 
+	  adjusted by FACTOR_UNITS
+
+; =============================================
+INPUT:
+; =============================================
+	parameter = {CL, Vc, Q1, Vp1, Q2, Vp2, Fiv, Fabs1, ka, Tlag_input1}
+
+; =============================================
+PK:
+; =============================================
+	FACTOR_UNITS = 1
+	compartment(cmt=1, amount=Ac)
+	compartment(cmt=2, amount=Ap1)
+	compartment(cmt=3, amount=Ap2)
+	oral(adm=1, cmt=1, ka, p=FACTOR_UNITS*Fabs1, Tlag=Tlag_input1)
+	iv(adm=2, cmt=1, p=FACTOR_UNITS*Fiv)
+
+	; Transfer between compartments
+    
+	; Ac<->Ap1
+	transfer(from=1, to=2, kt=Q1/Vc)
+    	transfer(from=2, to=1, kt=Q1/Vp1)
+	
+	; Ac<->Ap2
+	transfer(from=1, to=3, kt=Q2/Vc)
+    	transfer(from=3, to=1, kt=Q2/Vp2)
+
+	; Clearance
+	elimination(cmt=1, k=CL/Vc)
+    
+	; Calculate concentration
+	Cc = Ac/Vc
+
+; =============================================
+OUTPUT:
+; =============================================
+	output = {Cc}
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/08_ModelComparison/SBPOPcomparePopPKmodels.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/08_ModelComparison/SBPOPcomparePopPKmodels.m
new file mode 100644
index 0000000000000000000000000000000000000000..5006fc1d9e4908fefe5e47846bec55db50d373d3
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/08_ModelComparison/SBPOPcomparePopPKmodels.m
@@ -0,0 +1,150 @@
+function [] = SBPOPcomparePopPKmodels(projectFolders,FACTOR_UNITS,dosing,obsTimes,options,covNames,catNames,data)
+% [DESCRIPTION]
+% This function allows to compare different popPK models created with the
+% PKPD toolbox in SBPOP. Useful for model selection when GOF
+% plots and other assessments suggest models are behaving very similar.
+%
+% Covariates can be taken into account. For that the relevant information
+% need to be provided. Sampling is done from the covariates in the modeling
+% dataset. The user has to make sure that a reasonable number of
+% simulations (options.Nsim) is done.
+%
+% [SYNTAX]
+% [] = SBPOPcomparePopPKmodels(projectFolders,FACTOR_UNITS,dosing,obsTimes)
+% [] = SBPOPcomparePopPKmodels(projectFolders,FACTOR_UNITS,dosing,obsTimes,options)
+% [] = SBPOPcomparePopPKmodels(projectFolders,FACTOR_UNITS,dosing,obsTimes,options,covNames,catNames,data)
+%
+% [INPUT]
+% projectFolders:   Cell-array with the names of the Monolix project
+%                   folders for which to compare the models. The elements
+%                   need to include the full/relative path to the models
+% FACTOR_UNITS:     The FACTOR_UNITS value used for popPK model fitting.
+% dosing:           Dosing scheme to simulate the model for
+% obsTimes:         Observation times to compare the models at
+% covNames:         Cell-array with continous covariate names to take into
+%                   account (only done if the modelfit uses these)
+% catNames:         Cell-array with categorical covariate names to take into
+%                   account (only done if the modelfit uses these)
+% data:             MATLAB dataset which was used for model fitting. Standard
+%                   SBPOP dataset is assumed. The columns with the
+%                   specified covariate names have to exist
+%                   Alternatively, the path to the datafile can be
+%                   specified
+% options:          Matlab structure with optional information
+%       options.filename            Filename (with path) for export of
+%                                   resulting figure. If undefined or empty
+%                                   then not exported (default: '')
+%
+%       options.N_PROCESSORS:       Number of processors for parallel computation (default: 1)
+%
+%                                   If N_PROCESSORS>1 then parallel nodes are requested via the matlabpool
+%                                   command. N_PROCESSORS models will then be run in parallel.
+%
+%       options.Nsim                Number of samples from IIV
+%                                   distributions (default: 100)
+%       options.quantiles           Vector with quantiles to compute for
+%                                   comparison (does only make sense if
+%                                   Nsim reasonably large) (default: [0.05 0.95])
+%       options.logY                =1: log Y axis, =0: linear Y axis
+%       options.minY                Lower limit for Y-axis, e.g. LLOQ for PK
+%       options.plotData            =0 no (by default); =1 yes
+%       options.optionsIntegrator   options for the integration.
+%                                   By default: abstol=1e-6, reltol=1e-6
+%
+% [OUTPUT]
+% The figure with the comparison is stored in the filename file or if not
+% defined, then just shown
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 4th April, 2013
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle optional input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try options         = options;                  catch, options      = [];   end
+try filename        = options.filename;         catch, filename     = '';   end
+try covNames        = covNames;                 catch, covNames     = {};   end
+try catNames        = catNames;                 catch, catNames     = {};   end
+try data            = data;                     catch, data         = [];   end
+try Nsim            = options.Nsim;             catch, Nsim         = 100;  end
+try N_PROCESSORS    = options.N_PROCESSORS;     catch, N_PROCESSORS = 1;    end
+try logY            = options.logY;             catch, logY         = 1;    end
+try minY            = options.minY;             catch, minY         = [];   end
+try plotData        = options.plotData;         catch, plotData     = 0;    end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle data
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ischar(data),
+    % If not provided as dataset, then load it
+    data = SBPOPloadCSVdataset(data);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle interface to SBPOPcompareModels
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+model                           = SBmodel('template_popPK_model.txt');
+output                          = 'OUTPUT1';
+optionsComparison               = [];
+optionsComparison.Nsim          = Nsim;
+optionsComparison.N_PROCESSORS  = N_PROCESSORS;
+optionsComparison.logY          = logY;
+optionsComparison.minY          = minY;
+optionsComparison.plotData      = plotData;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Update model with needed parameter settings
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+model                           = SBparameters(model,'FACTOR_UNITS',FACTOR_UNITS);
+% Ensure VMAX and other param are 0 and only changed by the fit
+model                           = SBparameters(model,{'CL','Q1','Q2','VMAX','ka'},[0 0 0 0 0]);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if dosing contains Tlag on INPUT1
+% If not then set to to very small
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ds                              = struct(dosing);
+if isempty(ds.inputs(1).Tlag),
+    ds.inputs(1).Tlag           = 1e-10;
+end
+dosing                          = SBPOPdosing(ds);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run compare models
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBPOPcompareModels(projectFolders,model,output,dosing,obsTimes,optionsComparison,covNames,catNames,data)
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Export figure
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(filename),
+    [p,f,e] = fileparts(filename);
+    warning off
+    mkdir(p);
+    warning on
+    startNewPrintFigureSBPOP(filename);
+    printFigureSBPOP(gcf,filename);
+    convert2pdfSBPOP(filename);
+    close all
+end
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/10_VPC/SBPOPcreatePopPKstratifiedVPC.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/10_VPC/SBPOPcreatePopPKstratifiedVPC.m
new file mode 100644
index 0000000000000000000000000000000000000000..2ba0ce620086d8064cbd7106248624abeeee67d7
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/10_VPC/SBPOPcreatePopPKstratifiedVPC.m
@@ -0,0 +1,154 @@
+function [] = SBPOPcreatePopPKstratifiedVPC(projectFolder,FACTOR_UNITS,data,covNames,catNames,options)
+% [DESCRIPTION]
+% This function creates a stratified VPC for a given model on a given
+% dataset. Assumption is that the model has been built using the popPKPD
+% toolbox within SBPOP.
+% Stratification is done automatically using the TRT column. Also, the PK
+% is identified by "OUTPUT1" variable in the model and by TYPE==1.
+% The structural model is selected automatically.
+%
+% The doses and dosing schedule and the covariates are obtained from the
+% dataset.  
+%
+% Assumption: ADM=1: IV, ADM=2: 1st order absorption
+%
+% [SYNTAX]
+% [] = SBPOPcreatePopPKstratifiedVPC(projectFolder,FACTOR_UNITS,data,covNames,catNames)
+% [] = SBPOPcreatePopPKstratifiedVPC(projectFolder,FACTOR_UNITS,data,covNames,catNames,options)
+% [INPUT]
+% projectFolder:    Cell-array with the name of the Monolix project folder.
+%                   Needs to include the full path to the folder.
+% FACTOR_UNITS:     The FACTOR_UNITS value used for popPK model fitting.
+% data:             Dataset for the VPC - covariates will be sampled from
+%                   this dataset
+% covNames:         Cell-array with names of continuous covariates. Only 
+%                   the ones used in the model will be considered 
+% catNames:         Cell-array with names of categorical covariates. Only 
+%                   the ones used in the model will be considered 
+%
+% options:          Matlab structure with optional information
+%       options.filename            Filename, including path, for
+%                                   generated output PS (windows) or PDF
+%                                   (unix) file (default: VPC.ps/pdf in
+%                                   current folder)
+%       options.N_PROCESSORS:       Number of processors for parallel computation (default: 1)
+%
+%                                   If N_PROCESSORS>1 then parallel nodes are requested via the matlabpool
+%                                   command. N_PROCESSORS models will then be run in parallel.
+%
+%       options.NTRIALS             Number of TRIALS to simulate to
+%                                   determine simulation quantiles and
+%                                   confidence intervals. (default: 100).  
+%       options.quantiles           Vector with quantiles to compute for
+%                                   comparison (does only make sense if
+%                                   Nsim reasonably large) (default: [0.05 0.95])
+%       options.logY                =1: log Y axis, =0: linear Y axis
+%       options.optionsIntegrator   options for the integration.
+%                                   By default: abstol=1e-6, reltol=1e-6
+%       options.plotIndivLines      =1: Connect individual data points with
+%                                   lines (default: 0)
+%       options.showDataQuantiles   =1: Show lines for the observation
+%                                   quantiles (default: 0)
+%       options.numbins             Number of bins for the calculation of
+%                                   the observation quantiles
+%       options.quantileLogX        =0: use numbins bins for quantile
+%                                   calculation, spaced uniformly over
+%                                   LINEAR x-axis 
+%                                   =1: use numbins bins for quantile
+%                                   calculation, spaced uniformly over
+%                                   LOG x-axis (negative times will be
+%                                   ignored)
+%       options.nTimePoints         Number time points to simulate - spaced
+%                                   equidistantly (default: 100)
+%       options.groupName           Grpup name for stratification (default:
+%                                   'TRT')
+%
+% [OUTPUT]
+% Figures, exported to PS (Windows) or PDF (Unix) in a file that can be
+% user selected or by default VPC.ps/pdf in the current folder.
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 8th April, 2013
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+% This function, basically, is just a wrapper, hiding some of the settings
+% that have default values if using the popPKPD toolbox in SBPOP for a
+% popPK analysis
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get data header
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+header = get(data,'VarNames');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle missing TINF column
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(strmatchSB('TINF',header,'exact')),
+    if ~isempty(strmatchSB('RATE',header,'exact')),
+        data.TINF = data.AMT./data.RATE;
+        data.TINF(isnan(data.TINF)) = 0;
+        data.TINF(isinf(abs(data.TINF))) = 0;
+    else
+        error('Please ensure that either a RATE or a TINF column present in the VPC data.');
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Load template model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+model                       = SBmodel('template_popPK_model.txt');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Parameterize model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+model                       = SBparameters(model,'FACTOR_UNITS',FACTOR_UNITS);
+% Ensure VMAX and other param are 0 and only changed by the fit
+model                       = SBparameters(model,{'CL','Q1','Q2','VMAX','ka'},[0 0 0 0 0]);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define additional things known for popPK model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dosing                      = SBPOPdosing('template_popPK_dosing.dos');
+output                      = 'OUTPUT1';
+outputTYPE                  = 1;
+regressionVariables         = {};
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define default stratification
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try groupName = options.groupName; catch, groupName = 'TRT'; end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Set default number of processors for parallel computation
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try options.N_PROCESSORS; catch, options.N_PROCESSORS = 1; end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run it
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBPOPcreateStratifiedVPC(projectFolder,model,dosing,output,outputTYPE,covNames,catNames,data,groupName,regressionVariables,options)
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Done!
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/12_Other/SBPOPscmPopPK.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/12_Other/SBPOPscmPopPK.m
new file mode 100644
index 0000000000000000000000000000000000000000..f36040a1ba958044d8037483b3c564efbc0abcfb
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tasks/popPKtoolbox/12_Other/SBPOPscmPopPK.m
@@ -0,0 +1,1293 @@
+function [] = SBPOPscmPopPK(nameSpace, modeltest, modelingDatasetFile, dataheaderNLME, optionsNLME, optionsSCM)
+% SBPOPscmPopPK: Stepwise covariate search, using forward inclusion / backward
+% elimination. Decision can be made based on objective function value or confidence interval
+% of estimated covariate coefficients. This function takes input arguments
+% that are used by the PopPK modeling workflow and thus allows to run
+% analytic versions of linear PK models.
+%
+% Two modes/types of search:
+%   - type='OBJ': Behaves like the traditional PsN SCM, considering the
+%                 objective function value.
+%   - type='P':   Considers the probabilities that estimated covariate
+%                 coefficients are different from 0. In each forward step
+%                 the covariate coefficient is retained that is most
+%                 statistically significant.
+%
+% In case NONMEM/SAEM is used it will be checked that IMPORTANCESAMPLING
+% option is set to 1, in order to determine the true objective function
+% that is suitable for statistical testing.
+%
+% Although the algorithm is in principle applicable to categorical
+% covariates with more than 2 categories, it does not really make sense and
+% might introduce to many parameters that are not significant. A better
+% approach is to get the modeler to think a little more and reduce the
+% number of categories to 2. Covariates with multiple categories can be
+% assessed after the SCM has been done by adding them one at a time.
+%
+% This function here will only allow for categorical covariates with 2
+% categories - not more.
+%
+% USAGE:
+% ======
+% SBPOPscmPopPK(nameSpace, modeltest, modelingDatasetFile, dataheaderNLME, optionsNLME, optionsSCM)
+%
+% Input arguments modeltest, modelingDatasetFile, dataheaderNLME, optionsNLME are identical to the ones
+% used and documented in SBPOPbuilPopPKModelSpace and are not repeated here.
+% However, instead of a model space, only a single model is allowed to be
+% defined. This is checked and an error is returned if multiple models are
+% defined.
+%
+% If covariateModel is defined in modeltest, then these covariates are
+% included by default and are not subject to the SCM algorithm.
+%
+% nameSpace:    Defines the folder where to store the SCM models and the summary output
+%               in the same way as for SBPOPbuilPopPKModelSpace
+%
+% optionsSCM: structure with optional settings for the covariate search.
+%   optionsSCM.type:            Define if decisions based on objective function value or based on
+%                               probability that covariate coefficients are different from 0.
+%                               'OBJ' or 'P' (default: 'OBJ'). For categorical covariates with multiple
+%                               levels the delta OFV is adjusted and for 'P' the lowest p-value is used.
+%   optionsSCM.p_forward:       p-value for forward inclusion step (default: 0.05)
+%                               Either for OFV or for probability that 0 included in CI for covariate coefficient.
+%   optionsSCM.p_backward:      p-value for forward inclusion step (default: 0.001)
+%                               Either for OFV or for probability that 0 included in CI for covariate coefficient.
+%   optionsSCM.covariateTests:  cell-array with parameter/covariate combinations to test
+%                               First element in each sub-array is the parameter name,
+%                               following are the covariates to test.
+%                               Example:
+%                                          {
+%                                             {'EMAX','WT0','SEX','HT0','ETHN'}
+%                                             {'EC50','WT0','SEX','HT0','ETHN'}
+%                                             {'fS'  ,'WT0','SEX','HT0','ETHN'}
+%                                           }
+%                               If not specified or empty, then all covariates will be
+%                               tested on all parameters.
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+%
+% This program is Free Open Source Software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Get modeltest elements
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try numberCompartments = modeltest.numberCompartments;      catch, error('modeltest.numberCompartments undefined'); end
+try errorModels = modeltest.errorModels;                    catch, error('modeltest.errorModels undefined'); end
+try saturableClearance = modeltest.saturableClearance;      catch, error('modeltest.saturableClearance undefined'); end
+try lagTime = modeltest.lagTime;                            catch, error('modeltest.lagTime undefined'); end
+try FACTOR_UNITS = modeltest.FACTOR_UNITS;                  catch, error('modeltest.FACTOR_UNITS undefined'); end
+try POPvalues0 = modeltest.POPvalues0;                      catch, error('modeltest.POPvalues0 undefined'); end
+try POPestimate = modeltest.POPestimate;                    catch, error('modeltest.POPestimate undefined'); end
+try IIVestimate = modeltest.IIVestimate;                    catch, error('modeltest.IIVestimate undefined'); end
+try IIVvalues0 = modeltest.IIVvalues0;                      catch, IIVvalues0 = []; end
+try covarianceModel = modeltest.covarianceModels;           catch, covarianceModel = ''; end
+try IIVdistribution = modeltest.IIVdistribution;            catch, IIVdistribution = {}; end
+try errorParam0 = modeltest.errorParam0;                    catch, errorParam0 = []; end
+
+try SILENT = optionsNLME.SILENT;                            catch, SILENT = 1; end
+try algorithm = optionsNLME.algorithm;                      catch, algorithm = []; end
+
+% Get fixed covariate model
+try covariateModel = modeltest.covariateModels;             catch, covariateModel = ''; end
+try covariateModelValues = modeltest.covariateModelValues;  catch, covariateModelValues = {}; end
+try COVestimate = modeltest.COVestimate;                    catch, COVestimate = {}; end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if model space is single model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+multiple = 0;
+if length(numberCompartments) > 1, multiple = 1; end
+if iscell(errorModels), if length(errorModels) > 1, multiple = 1; else errorModels = errorModels{1}; end; end
+if length(saturableClearance) > 1, multiple = 1; end
+if length(lagTime) > 1, multiple = 1; end
+if iscell(POPvalues0), if length(POPvalues0)>1, multiple = 1; else POPvalues0 = POPvalues0{1}; end; end
+if iscell(POPestimate), if length(POPestimate)>1, multiple = 1; else POPestimate = POPestimate{1}; end; end
+if iscell(IIVestimate), if length(IIVestimate)>1, multiple = 1; else IIVestimate = IIVestimate{1}; end; end
+if iscell(IIVvalues0), if length(IIVvalues0)>1, multiple = 1; else IIVvalues0 = IIVvalues0{1}; end; end
+if iscell(covarianceModel), if length(covarianceModel)>1, multiple = 1; else covarianceModel = covarianceModel{1}; end; end
+if iscell(covariateModel), if length(covariateModel)>1, multiple = 1; else covariateModel = covariateModel{1}; end; end
+
+if multiple,
+    error('Modelspace is larger than a single model.');
+end
+
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Interface popPK version (concerns mostly model generation)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+TOOL = optionsNLME.parameterEstimationTool;
+% Check TOOL definition
+if strcmpi(TOOL,'nonmem'),
+    FLAG_NONMEM = 1;
+elseif strcmpi(TOOL,'monolix'),
+    FLAG_NONMEM = 0;
+else
+    error('Please select as first input argument either ''NONMEM'' or ''MONOLIX''');
+end
+
+[xdummyx,f,e] = fileparts(modelingDatasetFile);
+data = [];
+data.filename = [f e];
+data.header = dataheaderNLME;
+data.dataRelPathFromProject = '../../Data';
+
+% Define parameternames in ODE and ANALYTIC models
+% NONLINEAR parameters need to be at the end!!!!
+% Its the required order ... checks for ODE models will be done.
+% MONOLIX works with an analytic template. For NONMEM no analytic template
+% can be used, since numerics horribly bad. Individual ADVANs will be
+% generated automaticall instead.
+TemplateModels = [];
+TemplateModels.ParameterNames.ODE       = {'CL', 'Vc', 'Q1', 'Vp1', 'Q2', 'Vp2', 'Fiv', 'Fabs1', 'ka', 'Tlag_input1', 'VMAX', 'KM'};
+TemplateModels.IIVdistribution.ODE      = { 'L',  'L',  'L',   'L',  'L',   'L',   'L',     'L',  'L',           'L',    'L',  'L'};
+TemplateModels.ParameterNames.ANALYTIC  = {'CL', 'Vc', 'Q1', 'Vp1', 'Q2', 'Vp2', 'Fiv', 'Fabs1', 'ka', 'Tlag_input1'};
+TemplateModels.IIVdistribution.ANALYTIC = { 'L',  'L',  'L',   'L',  'L',   'L',   'L',     'L',  'L',           'L'};
+TemplateModels.Model.MONOLIX.ANALYTIC   = 'template_popPK_model_ANALYTIC_MLXTRAN.txt';
+TemplateModels.Model.ODE                = 'template_popPK_model.txt';
+TemplateModels.Model.DOSING             = 'template_popPK_dosing.dos';
+
+% If IIVvalues0 is empty then initialize it
+if isempty(IIVvalues0),
+    IIVvalues0 = ones(1,length(TemplateModels.ParameterNames.ODE));
+end
+
+if iscell(errorParam0),
+    errorParam0 = errorParam0{1};
+end
+
+
+% Copy the options
+options = [];
+options.POPestimate = POPestimate;
+options.POPvalues0 = POPvalues0;
+options.IIVdistribution = IIVdistribution;
+options.IIVestimate = IIVestimate;
+options.IIVvalues0 = IIVvalues0;
+options.errorModels = errorModels;
+options.errorParam0 = errorParam0;
+options.covarianceModel = covarianceModel;
+options.SILENT = SILENT;
+options.algorithm = algorithm;
+% Keep below for BASE model
+options.covariateModel = covariateModel;
+options.covariateModelValues = covariateModelValues;
+options.COVestimate = COVestimate;
+
+
+% [FLAGanalyticModel,MODEL_SETTINGS] = createPopPK_NLMEproject_ODE_Analytic_SBPOP( ...
+%                                 FLAG_NONMEM,modelNameFIT,TemplateModels, ...
+%                                 FACTOR_UNITS, numberCompartments,saturableClearance, ...
+%                                 lagTime,dataCreate,projectPath,dataRelPathFromProjectPath,options)
+%
+% Still to define: modelNameFIT, projectModelPath
+
+outputPath      = ['../Output/FitAnalysis/' nameSpace];
+mkdir(outputPath);
+
+projectPath     = ['../Models/' nameSpace];
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle optionsSCM
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try p_forward       = optionsSCM.p_forward;            catch, p_forward         = 0.05;         end
+try p_backward      = optionsSCM.p_backward;           catch, p_backward        = 0.001;        end
+try covariateTests  = optionsSCM.covariateTests;       catch, covariateTests    = {};           end
+try type            = optionsSCM.type;                 catch, type              = 'OBJ';        end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle number processors ... already defined in optionsNLME ...
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try N_PROCESSORS_PAR        = optionsNLME.N_PROCESSORS_PAR;             catch, N_PROCESSORS_PAR          = 1;            end
+try N_PROCESSORS_SINGLE     = optionsNLME.N_PROCESSORS_SINGLE;          catch, N_PROCESSORS_SINGLE       = 1;            end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Create the projectFolder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try rmdir(projectPath,'s'); catch, end
+mkdir(projectPath);
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Load dataset to assess number of categorical elements
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+oldpath = pwd();
+cd(projectPath);
+dataContents = SBPOPloadCSVdataset([data.dataRelPathFromProject '/' data.filename]);
+cd(oldpath);
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Create the BASE model (MODEL_00) and load header
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+BASEmodelFolder = [projectPath '/MODEL_BASE'];
+% Assume standard popPK workflow structure
+dataRelPathFromProjectPath = '../../../Data';
+modelNameFIT = 'MODEL_BASE';
+[FLAGanalyticModel,MODEL_SETTINGS] = createPopPK_NLMEproject_ODE_Analytic_SBPOP( ...
+    FLAG_NONMEM,modelNameFIT,TemplateModels, ...
+    FACTOR_UNITS, numberCompartments,saturableClearance, ...
+    lagTime,data,BASEmodelFolder,dataRelPathFromProjectPath,options);
+if strcmpi(TOOL,'nonmem')
+    % Check if IMP set to 1
+    if strcmpi(options.algorithm.METHOD,'saem') && options.algorithm.IMPORTANCESAMPLING == 0,
+        error('When using NONMEM/SAEM, please set the options.algorithm.IMPORTANCESAMPLING=1.');
+    end
+    projectInfo = parseProjectHeaderNONMEMSBPOP(BASEmodelFolder);
+elseif strcmpi(TOOL,'monolix'),
+    projectInfo = parseProjectHeaderMONOLIXSBPOP(BASEmodelFolder);
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Get param cov and cat
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+parNames    = projectInfo.PARAMNAMES;
+covNames    = projectInfo.COVNAMES;
+catNames    = projectInfo.CATNAMES;
+covcatNames = [covNames catNames];
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Change parNames based on MODEL_SETTINGS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% Get estimated parameters
+ix = find((MODEL_SETTINGS.IIVestimate+MODEL_SETTINGS.POPestimate)~=0);
+parNames = parNames(ix);
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% If list of covariates empty then generate it
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(covariateTests)
+    covariateTests = cell(length(parNames),1);
+    for k1=1:length(parNames),
+        cTk{1} = parNames{k1};
+        for k2=1:length(covcatNames),
+            cTk{k2+1} = covcatNames{k2};
+        end
+        covariateTests{k1} = cTk(:)';
+    end
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Get covariate list for parameters and covariate names
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+covSearch = [];
+covSearch.paramNamesTest  = {};
+covSearch.covcatNamesTest = {};
+% Get param and covcat names from covariateTests
+for k1=1:length(covariateTests),
+    for k2=2:length(covariateTests{k1}),
+        covSearch.paramNamesTest{end+1}  = covariateTests{k1}{1};
+        covSearch.covcatNamesTest{end+1} = covariateTests{k1}{k2};
+    end
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Check covariate list for parameters and covariate names
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(covSearch.paramNamesTest),
+    ix = strmatchSB(covSearch.paramNamesTest{k},parNames,'exact');
+    if isempty(ix),
+        error('Parameter %s is not estimated in the model.',covSearch.paramNamesTest{k});
+    end
+end
+
+for k=1:length(covSearch.covcatNamesTest),
+    ix = strmatchSB(covSearch.covcatNamesTest{k},covcatNames,'exact');
+    if isempty(ix),
+        error('Covariate %s is not present in the dataset.',covSearch.covcatNamesTest{k});
+    end
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine structural covariate information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+covStructural = [];
+covStructural.paramNames  = {};
+covStructural.covcatNames = {};
+covStructural.value       = [];
+covStructural.estimate    = [];
+terms = strrep(strrep(explodePCSB(covariateModel,',','{','}'),'{',''),'}','');
+for k=1:length(terms),
+    x = explodePCSB(terms{k});
+    for k2=2:length(x),
+        covStructural.paramNames{end+1} = x{1};
+        covStructural.covcatNames{end+1} = x{k2};
+        if isempty(covariateModelValues),
+            covStructural.value(end+1) = 0.1;
+        else
+            covStructural.value(end+1) = covariateModelValues{k}(k2-1);
+        end
+        if isempty(COVestimate),
+            covStructural.estimate(end+1) = 1;
+        else
+            covStructural.estimate(end+1) = COVestimate{k}(k2-1);
+        end
+    end
+    
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Remove structural covariates from covSearch
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ix_remove = [];
+for k=1:length(covStructural.paramNames),
+    par = covStructural.paramNames{k};
+    cov = covStructural.covcatNames{k};
+    ix1 = strmatchSB(par,covSearch.paramNamesTest,'exact');
+    ix2 = strmatchSB(cov,covSearch.covcatNamesTest,'exact');
+    if ~isempty(intersect(ix1,ix2)),
+        ix_remove(end+1) = intersect(ix1,ix2);
+    end
+end
+if ~isempty(ix_remove),
+    covSearch.paramNamesTest(ix_remove) = [];
+    covSearch.covcatNamesTest(ix_remove) = [];
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine delta Objective functions required for covariates
+% DF: 1 for continuous, N-1 for categorical
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(covSearch.covcatNamesTest),
+    % Check if categorical
+    if ~isempty(strmatchSB(covSearch.covcatNamesTest{k},covNames,'exact')),
+        % Continuous covariate
+        N_DF = 1;
+    else
+        % Categorical covariate
+        N_categories = length(unique(dataContents.(covSearch.covcatNamesTest{k})));
+        if N_categories > 2,
+            error('Categorical covariate "%s" has more than 2 categories - this is not allowed.',covSearch.covcatNamesTest{k});
+            N_DF = length(unique(dataContents.(covSearch.covcatNamesTest{k}))) - 1;
+        end
+    end
+    covSearch.delta_forward(k)   = chi2inv(1-p_forward,N_DF);
+    covSearch.delta_backward(k)  = chi2inv(1-p_backward,N_DF);
+end
+
+% For later
+covSearchBackUp = covSearch;
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Open report file
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+mkdir(outputPath);
+fid = fopen([outputPath '/SCMlogfile.txt'],'w');
+
+fprintf(fid,'****************************************************************************\n');
+fprintf(fid,'* Covariate search using forward inclusion and backward elimination method *\n');
+fprintf(fid,'****************************************************************************\n');;
+fprintf(fid,'p-value forward:      %g\n',p_forward);
+fprintf(fid,'p-value backward:     %g\n',p_backward);
+fprintf(fid,'\n');
+if strcmpi(type,'P'),
+    fprintf(fid,'Decisions based on probability of CI of covariate coefficient including 0.\n');
+elseif strcmpi(type,'OBJ'),
+    fprintf(fid,'Decisions based on delta objective function.\n');
+else
+    error('Incorrect definition of "type"');
+end
+fprintf(fid,'\n');
+
+fprintf(fid,'************************************\n');
+fprintf(fid,'* RUNNING BASE MODEL (MODEL_BASE)  *\n');
+fprintf(fid,'************************************\n');
+fprintf(fid,'\n');
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Run the BASE model (MODEL_BASE)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+BASEmodelFolder = [projectPath '/MODEL_BASE'];
+if strcmpi(TOOL,'nonmem')
+    SBPOPrunNONMEMproject(BASEmodelFolder,N_PROCESSORS_SINGLE);
+    RESULTS = parseNONMEMresultsSBPOP(BASEmodelFolder,1);
+elseif strcmpi(TOOL,'monolix'),
+    SBPOPrunMONOLIXproject(BASEmodelFolder,N_PROCESSORS_SINGLE);
+    RESULTS = parseMONOLIXresultsSBPOP(BASEmodelFolder);
+end
+close all; drawnow();
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Get OFV and optimal parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+BASE_OFV            = RESULTS.objectivefunction.OBJ;
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Update options with optimal BASE model parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(parNames),
+    ix_options = strmatchSB(parNames{k},TemplateModels.ParameterNames.ODE,'exact');
+    ix_result  = strmatchSB(parNames{k},RESULTS.rawParameterInfo.fixedEffects.names,'exact');
+    options.POPvalues0(ix_options)  = RESULTS.rawParameterInfo.fixedEffects.values(ix_result);
+    options.IIVvalues0(ix_options)  = RESULTS.rawParameterInfo.randomEffects.values(ix_result);
+end
+options.errorParam0 = RESULTS.rawParameterInfo.errorParameter.values;
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Forward inclusion
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'************************************\n');
+fprintf(fid,'* FORWARD INCLUSION                *\n');
+fprintf(fid,'************************************\n');
+fprintf(fid,'\n');
+
+OLD_OFV                 = BASE_OFV;
+covariatesForward       = {};
+
+%%%
+covariateModelValuesForward = {};
+COVestimateForward          = {};
+%%%
+
+countModel              = 1;
+Nmaxmodels              = (length(covSearch.covcatNamesTest)^2-length(covSearch.covcatNamesTest))/2+length(covSearch.covcatNamesTest);
+continueForwardSearch   = 1;
+levelCount              = 1;
+levelModel              = '';
+ForwardModelName        = BASEmodelFolder;
+ModelNameAll            = {};
+
+while continueForwardSearch,
+    fprintf(fid,'* Level %d: ',levelCount);
+    
+    % Run through remaining parameter/covariate combinations
+    % Generate all models first and then run all at once
+    covariatesTestForward = {};
+    %%%
+    covariateModelValuesTESTForward = {};
+    COVestimateTESTForward          = {};
+    %%%
+    covariateModelAll     = {};
+    for k1=1:length(covSearch.paramNamesTest),
+        
+        % Reset covariate setting to previous level
+        covariatesTest = covariatesForward;
+        %%%
+        covariateModelValues = covariateModelValuesForward;
+        COVestimate = COVestimateForward;
+        %%%
+        
+        % Get new parameter/covariate combination to test
+        param = covSearch.paramNamesTest{k1};
+        cov   = covSearch.covcatNamesTest{k1};
+        delta = covSearch.delta_forward(k1);
+        
+        %%%
+        value = 0.1; % Setting default value to 0.1 (NONMEM does not allow 0)
+        
+        % Build covariate test structure and covariateModelValues and COVestimate
+        ix = [];
+        for k2=1:length(covariatesTest),
+            if strcmp(covariatesTest{k2}{1},param),
+                ix = k2;
+            end
+        end
+        if isempty(ix),
+            covariatesTest{end+1}{1} = param;
+            covariatesTest{end}{2} = cov;
+            covariateModelValues{end+1} = value;
+            COVestimate{end+1} = 1;
+        else
+            covariatesTest{ix}{end+1} = cov;
+            covariateModelValues{ix}(end+1) = value;
+            COVestimate{ix}(end+1) = 1;
+        end
+        covariatesTest = covariatesTest(:);
+        %%%
+        
+        % Save for later
+        covariatesTestForward{k1} = covariatesTest;
+        %%%
+        covariateModelValuesTESTForward{k1} = covariateModelValues;
+        COVestimateTESTForward{k1}          = COVestimate;
+        %%%
+        
+        
+        % Convert to required format for the search things
+        covariateModel                      = '';
+        for k3=1:size(covariatesTest,1),
+            if ~isempty(covariatesTest{k3}),
+                text                        = sprintf('%s,',covariatesTest{k3}{:});
+                covariateModel              = [covariateModel '{' text(1:end-1) '},'];
+            end
+        end
+        covariateModel                      = covariateModel(1:end-1);
+        covariateModelAll{k1}               = covariateModel;
+        
+        
+        % Add structural covariates to covariate model
+        for k3=1:length(covStructural.paramNames),
+            param    = covStructural.paramNames{k3};
+            cov      = covStructural.covcatNames{k3};
+            value    = covStructural.value(k3);
+            estimate = covStructural.estimate(k3);
+            % Find where to add
+            ix = [];
+            for k4=1:size(covariatesTest,1),
+                if strcmp(param,covariatesTest{k4}{1}),
+                    ix = k4;
+                    break;
+                end
+            end
+            if ~isempty(ix),
+                % add info
+                covariatesTest{ix}{end+1} = cov;
+                covariateModelValues{ix}(end+1) = value;
+                COVestimate{ix}(end+1) = estimate;
+            else
+                % new param
+                covariatesTest{end+1}{1} = param;
+                covariatesTest{end}{2} = cov;
+                covariateModelValues{end+1}(1) = value;
+                COVestimate{end+1}(1) = estimate;
+            end
+            covariatesTest = covariatesTest(:);
+        end
+        
+        % Convert to required format for the search things
+        covariateModel                      = '';
+        for k3=1:size(covariatesTest,1),
+            if ~isempty(covariatesTest{k3}),
+                text                        = sprintf('%s,',covariatesTest{k3}{:});
+                covariateModel              = [covariateModel '{' text(1:end-1) '},'];
+            end
+        end
+        covariateModel                      = covariateModel(1:end-1);
+        
+        % Set covariateModel
+        options.covariateModel              = covariateModel;
+        options.covariateModelValues        = covariateModelValues;
+        options.COVestimate                 = COVestimate;
+        
+        % Create model
+        ModelName                           = sprintf('MODEL_%s',preFillCharSB(countModel,length(num2str(Nmaxmodels)),'0'));
+        FolderName                          = [projectPath sprintf('/FW_LEVEL_%d',levelCount)];
+        ModelFolder                         = [FolderName '/' ModelName];
+        ModelNameAll{k1}                    = ModelFolder;
+        
+        % Assume standard popPK workflow structure
+        dataRelPathFromProjectPath = '../../../../Data';
+        modelNameFIT = ModelName;
+        [FLAGanalyticModel,MODEL_SETTINGS] = createPopPK_NLMEproject_ODE_Analytic_SBPOP( ...
+            FLAG_NONMEM,modelNameFIT,TemplateModels, ...
+            FACTOR_UNITS, numberCompartments,saturableClearance, ...
+            lagTime,data,ModelFolder,dataRelPathFromProjectPath,options);
+        
+        countModel                          = countModel + 1;
+    end
+    
+    % Write out level base cov model
+    fprintf(fid,'"%s"\n',levelModel);
+    fprintf(fid,'\n');
+    
+    % Run the level models - do not create GoF plots!
+    SBPOPrunNLMEprojectFolder(FolderName,N_PROCESSORS_PAR,N_PROCESSORS_SINGLE,1);
+    
+    % Read the results
+    LEVEL_RESULTS = SBPOPfitanalysisProjectsFolderInfo(FolderName,FolderName);
+    
+    % Determine significance in different ways, defined by "type"
+    LEVEL_SIGNIFICANCE = [];
+    % Get OBJ
+    LEVEL_OBJ = [LEVEL_RESULTS.OBJ];
+    
+    % Handle P or OBJ type
+    if strcmpi(type,'OBJ'),
+        % BASED ON OBJECTIVE FUNCTION VALUE
+        % Print out info and determine significance
+        for k1=1:length(covSearch.paramNamesTest),
+            fprintf(fid,'%s (%s on %s): DeltaOFV=%g Goal>=%g ... ',LEVEL_RESULTS(k1).model,covSearch.covcatNamesTest{k1},covSearch.paramNamesTest{k1},OLD_OFV-LEVEL_OBJ(k1),covSearch.delta_forward(k1));
+            if OLD_OFV-LEVEL_OBJ(k1) >= covSearch.delta_forward(k1),
+                LEVEL_SIGNIFICANCE(k1) = 1;
+                fprintf(fid,'significant');
+            else
+                LEVEL_SIGNIFICANCE(k1) = 0;
+                fprintf(fid,'not significant');
+            end
+            fprintf(fid,'\n');
+        end
+        fprintf(fid,'\n');
+        
+        % Determine which covariate leads to the largest drop in OBJ
+        [xdummyx,ixBEST] = max(OLD_OFV-LEVEL_OBJ);
+        
+    else
+        % BASED ON ESTIMATED COVARIATE COEFFICIENTS
+        LEVEL_PVALUES = Inf(1,length(covSearch.paramNamesTest));
+        % Get covariate estimate informations for the current fit
+        for k1=1:length(covSearch.paramNamesTest),
+            param = covSearch.paramNamesTest{k1};
+            cov   = covSearch.covcatNamesTest{k1};
+            for k2=1:length(LEVEL_RESULTS(k1).rawParameterInfo.covariate.names),
+                xxx = strrep(LEVEL_RESULTS(k1).rawParameterInfo.covariate.names{k2},'(','_');
+                xxx = strrep(xxx,')','_');
+                test1 = strfind(xxx,['_' param '_']);
+                test2 = strfind(xxx,['_' cov]);
+                if ~isempty(test1) && ~isempty(test2),
+                    % Yes, this was a tested covariate
+                    % Calculate the p-value
+                    mu = LEVEL_RESULTS(k1).rawParameterInfo.covariate.values(k2);
+                    sigma = LEVEL_RESULTS(k1).rawParameterInfo.covariate.stderr(k2);
+                    p = min(normcdf(0,abs(mu),abs(sigma))*2);
+                    LEVEL_PVALUES(k1) = min(p,LEVEL_PVALUES(k1)); % Minimum handles multiple levels categorical covs
+                end
+            end
+        end
+        for k1=1:length(LEVEL_PVALUES),
+            fprintf(fid,'%s (%s on %s): P=%g Goal<=%g ... ',LEVEL_RESULTS(k1).model,covSearch.covcatNamesTest{k1},covSearch.paramNamesTest{k1},LEVEL_PVALUES(k1),p_forward);
+            if LEVEL_PVALUES(k1)<=p_forward,
+                LEVEL_SIGNIFICANCE(k1) = 1;
+                fprintf(fid,'significant');
+            else
+                LEVEL_SIGNIFICANCE(k1) = 0;
+                fprintf(fid,'not significant');
+            end
+            fprintf(fid,'\n');
+        end
+        fprintf(fid,'\n');
+        
+        % Determine which covariate leads to the lowest p-value
+        [xdummyx,ixBEST] = min(LEVEL_PVALUES);
+    end
+    
+    % If none significant then stop forward inclusion here
+    if sum(LEVEL_SIGNIFICANCE) == 0,
+        continueForwardSearch = 0;
+    else
+        % Message
+        fprintf(fid,'\n');
+        fprintf(fid,'Retained covariate for next level: %s on %s\n',covSearch.covcatNamesTest{ixBEST},covSearch.paramNamesTest{ixBEST});
+        fprintf(fid,'\n');
+        % Setup for new level
+        OLD_OFV = LEVEL_OBJ(ixBEST);
+        % Update options with optimal model parameters from last run
+        for kkk=1:length(parNames),
+            ix_options = strmatchSB(parNames{kkk},TemplateModels.ParameterNames.ODE,'exact');
+            ix_result  = strmatchSB(parNames{kkk},LEVEL_RESULTS(ixBEST).rawParameterInfo.fixedEffects.names,'exact');
+            options.POPvalues0(ix_options)  = LEVEL_RESULTS(ixBEST).rawParameterInfo.fixedEffects.values(ix_result);
+            options.IIVvalues0(ix_options)  = LEVEL_RESULTS(ixBEST).rawParameterInfo.randomEffects.values(ix_result);
+        end
+        options.errorParam0 = LEVEL_RESULTS(ixBEST).rawParameterInfo.errorParameter.values;
+        % Determine parameter and covariate retained
+        parBEST = covSearch.paramNamesTest{ixBEST};
+        covBEST = covSearch.covcatNamesTest{ixBEST};
+        % Remove covariate from search
+        covSearch.covcatNamesTest(ixBEST) = [];
+        covSearch.delta_forward(ixBEST)  = [];
+        covSearch.delta_backward(ixBEST)  = [];
+        covSearch.paramNamesTest(ixBEST)  = [];
+        % Set new base covariates
+        covariatesForward = covariatesTestForward{ixBEST};
+        
+        %%%
+        covariateModelValuesForward = covariateModelValuesTESTForward{ixBEST};
+        COVestimateForward = COVestimateTESTForward{ixBEST};
+        
+        % Update estimated covariate coefficient for next level - with all new
+        % estimates!
+        covInfo = LEVEL_RESULTS(ixBEST).rawParameterInfo.covariate;
+        
+        for k1x = 1:length(covariatesForward),
+            paramUpdate = covariatesForward{k1x}{1};
+            for k2x = 2:length(covariatesForward{k1x}),
+                covUpdate = covariatesForward{k1x}{k2x};
+                % Find parameter and covariate
+                matchIX = [];
+                for kkkx=1:length(covInfo.names),
+                    ixParam = strfind(covInfo.names{kkkx},paramUpdate);
+                    ixCov = strfind(covInfo.names{kkkx},covUpdate);
+                    if ~isempty(ixParam) && ~isempty(ixCov),
+                        matchIX(end+1) = kkkx;
+                    end
+                end
+                if length(matchIX) ~= 1,
+                    error('Problem with getting covariate coefficient value.');
+                end
+                % Get the estimated value
+                value = covInfo.values(matchIX);
+                % Add value to covariateModelValuesForward
+                ix = [];
+                for k2=1:length(covariatesForward),
+                    if strcmp(covariatesForward{k2}{1},paramUpdate),
+                        ix = k2;
+                    end
+                end
+                covariateModelValuesForward{ix}(strmatchSB(covUpdate,covariatesForward{ix},'exact')-1) = value;
+            end
+        end
+        %%%
+        
+        levelModel = covariateModelAll{ixBEST};
+        ForwardModelName = ModelNameAll{ixBEST};
+        levelCount = levelCount+1;
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get forward results
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+FORWARD_OFV = OLD_OFV;
+forwardModel = levelModel;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Report forward model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+fprintf(fid,'************************************\n');
+fprintf(fid,'* FORWARD MODEL RESULTS            *\n');
+fprintf(fid,'************************************\n');
+fprintf(fid,'\n');
+
+fprintf(fid,'Forward model:             %s\n',ForwardModelName);
+fprintf(fid,'Covariates:                %s\n',forwardModel);
+fprintf(fid,'Objective function value:  %g\n',FORWARD_OFV);
+fprintf(fid,'\n');
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Backward elimination
+% Handle P and OBJ differently
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'************************************\n');
+fprintf(fid,'* BACKWARD ELIMINATION             *\n');
+fprintf(fid,'************************************\n');
+fprintf(fid,'\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create covSearch structure for backward search
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+covSearchBackward = covSearchBackUp;
+ix_keep = [];
+for k1=1:size(covariatesForward),
+    param = covariatesForward{k1}{1};
+    for k2=2:length(covariatesForward{k1}),
+        cov = covariatesForward{k1}{k2};
+        ix_keep(end+1) = intersect(strmatchSB(param,covSearchBackward.paramNamesTest,'exact'),strmatchSB(cov,covSearchBackward.covcatNamesTest,'exact'));
+    end
+end
+covSearchBackward.covcatNamesTest = covSearchBackward.covcatNamesTest(ix_keep);
+covSearchBackward.paramNamesTest = covSearchBackward.paramNamesTest(ix_keep);
+covSearchBackward.delta_forward = covSearchBackward.delta_forward(ix_keep);
+covSearchBackward.delta_backward = covSearchBackward.delta_backward(ix_keep);
+
+%%%
+% Add parameter values
+for k1=1:length(covSearchBackward.paramNamesTest),
+    paramName = covSearchBackward.paramNamesTest{k1};
+    covName   = covSearchBackward.covcatNamesTest{k1};
+    for k2=1:size(covariatesForward),
+        if strcmp(paramName,covariatesForward{k2}{1}),
+            ix = k2;
+            break;
+        end
+    end
+    ix2 = strmatchSB(covName,covariatesForward{ix}(2:end),'exact');
+    value = covariateModelValuesForward{ix}(ix2);
+    covSearchBackward.value(k1) = value;
+end
+%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Do the search
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+covariateModelAll  = {};
+levelCount         = 1;
+countModel         = 1;
+BackwardModelName  = ForwardModelName;
+ModelNameAll       = {};
+
+% Check if backward search needed
+if ~isempty(covariatesForward),
+    continueBackwardSearch = 1;
+else
+    continueBackwardSearch = 0;
+end
+
+if strcmpi(type,'OBJ'),
+    % OBJ:  Start with FORWARD_OFV and remove one by one ... until deltaOFV>... for
+    
+    while continueBackwardSearch,
+        fprintf(fid,'* Level %d: ',levelCount);
+        
+        % Run through remaining parameter/covariate combinations
+        % Generate all models first and then run all at once
+        
+        for k1=1:length(covSearchBackward.paramNamesTest),
+            
+            % Reset covariate setting to previous level
+            covariatesTest = covSearchBackward;
+            
+            % Remove parameter to test
+            %%%
+            param = covariatesTest.paramNamesTest;
+            cov   = covariatesTest.covcatNamesTest;
+            value = covariatesTest.value;
+            param(k1) = [];
+            cov(k1)   = [];
+            value(k1) = [];
+            %%%
+            % Build covariate test structure
+            x = unique(param);
+            covTestStructure = {};
+            
+            %%%
+            covariateModelValues = cell(1,length(x));
+            COVestimate = cell(1,length(x));
+            %%%
+            for k2=1:length(x),
+                covTestStructure{k2}{1} = x{k2};
+            end
+            covTestStructure = covTestStructure(:);
+            for k2=1:length(param),
+                ix = strmatchSB(param{k2},x,'exact');
+                covTestStructure{ix}{end+1} = cov{k2};
+                %%%
+                covariateModelValues{ix}(end+1) = value(k2);
+                COVestimate{ix}(end+1) = 1;
+                %%%
+            end
+            
+            % Convert to required format
+            covariateModel                      = '';
+            for k3=1:size(covTestStructure,1),
+                if ~isempty(covTestStructure{k3}),
+                    text                        = sprintf('%s,',covTestStructure{k3}{:});
+                    covariateModel              = [covariateModel '{' text(1:end-1) '},'];
+                end
+            end
+            covariateModel                      = covariateModel(1:end-1);
+            covariateModelAll{k1}               = covariateModel;
+            
+            % Add structural covariates to covariate model
+            for k3=1:length(covStructural.paramNames),
+                param    = covStructural.paramNames{k3};
+                cov      = covStructural.covcatNames{k3};
+                value    = covStructural.value(k3);
+                estimate = covStructural.estimate(k3);
+                % Find where to add
+                ix = [];
+                for k4=1:size(covTestStructure,1),
+                    if strcmp(param,covTestStructure{k4}{1}),
+                        ix = k4;
+                        break;
+                    end
+                end
+                if ~isempty(ix),
+                    % add info
+                    covTestStructure{ix}{end+1} = cov;
+                    covariateModelValues{ix}(end+1) = value;
+                    COVestimate{ix}(end+1) = estimate;
+                else
+                    % new param
+                    covTestStructure{end+1}{1} = param;
+                    covTestStructure{end}{2} = cov;
+                    covariateModelValues{end+1}(1) = value;
+                    COVestimate{end+1}(1) = estimate;
+                end
+                covTestStructure = covTestStructure(:);
+            end
+            
+            % Convert to required format for the search things
+            covariateModel                      = '';
+            for k3=1:size(covTestStructure,1),
+                if ~isempty(covTestStructure{k3}),
+                    text                        = sprintf('%s,',covTestStructure{k3}{:});
+                    covariateModel              = [covariateModel '{' text(1:end-1) '},'];
+                end
+            end
+            covariateModel                      = covariateModel(1:end-1);
+            
+            % Set covariateModel
+            options.covariateModel              = covariateModel;
+            options.covariateModelValues        = covariateModelValues;
+            options.COVestimate                 = COVestimate;
+            
+            % Create model
+            ModelName                           = sprintf('MODEL_%s',preFillCharSB(countModel,length(num2str(Nmaxmodels)),'0'));
+            FolderName                          = [projectPath sprintf('/BW_LEVEL_%d',levelCount)];
+            ModelFolder                         = [FolderName '/' ModelName];
+            ModelNameAll{k1}                    = ModelFolder;
+            
+            % Assume standard popPK workflow structure
+            dataRelPathFromProjectPath = '../../../../Data';
+            modelNameFIT = ModelName;
+            [FLAGanalyticModel,MODEL_SETTINGS] = createPopPK_NLMEproject_ODE_Analytic_SBPOP( ...
+                FLAG_NONMEM,modelNameFIT,TemplateModels, ...
+                FACTOR_UNITS, numberCompartments,saturableClearance, ...
+                lagTime,data,ModelFolder,dataRelPathFromProjectPath,options);
+            
+            countModel                          = countModel + 1;
+        end
+        
+        % Write out level base cov model
+        fprintf(fid,'"%s"\n',levelModel);
+        fprintf(fid,'\n');
+        
+        % Run the level models - do not create GoF plots
+        SBPOPrunNLMEprojectFolder(FolderName,N_PROCESSORS_PAR,N_PROCESSORS_SINGLE,1);
+        
+        % Read the results
+        LEVEL_RESULTS = SBPOPfitanalysisProjectsFolderInfo(FolderName,FolderName);
+        
+        % Determine significance in different ways, defined by "type"
+        LEVEL_SIGNIFICANCE = [];
+        % Get OBJ
+        LEVEL_OBJ = [LEVEL_RESULTS.OBJ];
+        
+        % Print out info and determine significance
+        for k1=1:length(covSearchBackward.paramNamesTest),
+            fprintf(fid,'%s (%s on %s): DeltaOFV=%g Goal>=%g ... ',LEVEL_RESULTS(k1).model,covSearchBackward.covcatNamesTest{k1},covSearchBackward.paramNamesTest{k1},-OLD_OFV+LEVEL_OBJ(k1),covSearchBackward.delta_backward(k1));
+            if -OLD_OFV+LEVEL_OBJ(k1) >= covSearchBackward.delta_backward(k1),
+                LEVEL_SIGNIFICANCE(k1) = 1;
+                fprintf(fid,'significant');
+            else
+                LEVEL_SIGNIFICANCE(k1) = 0;
+                fprintf(fid,'not significant');
+            end
+            fprintf(fid,'\n');
+        end
+        fprintf(fid,'\n');
+        
+        % Determine which covariate leads to the largest increase in OBJ
+        [xdummyx,ixBEST] = min(-OLD_OFV+LEVEL_OBJ);
+        
+        % If all significant then stop backward elimination here
+        if sum(LEVEL_SIGNIFICANCE~=1) == 0,
+            continueBackwardSearch = 0;
+        else
+            % Message
+            fprintf(fid,'\n');
+            fprintf(fid,'Removed covariate for next level: %s on %s\n',covSearchBackward.covcatNamesTest{ixBEST},covSearchBackward.paramNamesTest{ixBEST});
+            fprintf(fid,'\n');
+            % Setup for new level
+            OLD_OFV = LEVEL_OBJ(ixBEST);
+            % Update options with optimal model parameters from last run
+            for kkk=1:length(parNames),
+                ix_options = strmatchSB(parNames{kkk},TemplateModels.ParameterNames.ODE,'exact');
+                ix_result  = strmatchSB(parNames{kkk},LEVEL_RESULTS(ixBEST).rawParameterInfo.fixedEffects.names,'exact');
+                options.POPvalues0(ix_options)  = LEVEL_RESULTS(ixBEST).rawParameterInfo.fixedEffects.values(ix_result);
+                options.IIVvalues0(ix_options)  = LEVEL_RESULTS(ixBEST).rawParameterInfo.randomEffects.values(ix_result);
+            end
+            options.errorParam0 = LEVEL_RESULTS(ixBEST).rawParameterInfo.errorParameter.values;
+            % Remove covariate from search
+            covSearchBackward.covcatNamesTest(ixBEST) = [];
+            covSearchBackward.delta_forward(ixBEST)  = [];
+            covSearchBackward.delta_backward(ixBEST)  = [];
+            covSearchBackward.paramNamesTest(ixBEST)  = [];
+            covSearchBackward.value(ixBEST)  = [];
+            levelModel = covariateModelAll{ixBEST};
+            levelCount = levelCount+1;
+            BackwardModelName = ModelNameAll{ixBEST};
+            
+            
+            
+            
+            %%%
+            % Update values in covSearchBackward to estimated ones in best model
+            covInfo = LEVEL_RESULTS(ixBEST).rawParameterInfo.covariate;
+            
+            for k1x = 1:length(covSearchBackward.paramNamesTest),
+                paramUpdate = covSearchBackward.paramNamesTest{k1x};
+                covUpdate   = covSearchBackward.covcatNamesTest{k1x};
+                
+                % Find parameter and covariate
+                matchIX = [];
+                for kkkx=1:length(covInfo.names),
+                    ixParam = strfind(covInfo.names{kkkx},paramUpdate);
+                    ixCov = strfind(covInfo.names{kkkx},covUpdate);
+                    if ~isempty(ixParam) && ~isempty(ixCov),
+                        matchIX(end+1) = kkkx;
+                    end
+                end
+                if length(matchIX) ~= 1,
+                    error('Problem with getting covariate coefficient value.');
+                end
+                % Get the estimated value
+                value = covInfo.values(matchIX);
+                % Add value to covSearchBackward
+                covSearchBackward.value(k1x) = value;
+            end
+            %%%
+            
+        end
+        
+        if  isempty(covSearchBackward.paramNamesTest),
+            continueBackwardSearch = 0;
+        end
+        
+    end
+else
+    % P:    Remove largest of the p-values>p_backward then rerun until all p-values<=p_backward
+    
+    while continueBackwardSearch,
+        if  isempty(covSearchBackward.paramNamesTest),
+            continueBackwardSearch = 0;
+            break
+        end
+        
+        
+        % Get all P values for the last model
+        if strcmpi(TOOL,'nonmem')
+            RESULTS = parseNONMEMresultsSBPOP(BackwardModelName,1);
+        elseif strcmpi(TOOL,'monolix'),
+            RESULTS = parseMONOLIXresultsSBPOP(BackwardModelName);
+        end
+        P_VALUES = Inf(1,length(covSearchBackward.paramNamesTest));
+        for k1=1:length(covSearchBackward.paramNamesTest),
+            param = covSearchBackward.paramNamesTest{k1};
+            cov   = covSearchBackward.covcatNamesTest{k1};
+            for k2=1:length(RESULTS.rawParameterInfo.covariate.names),
+                xxx = strrep(RESULTS.rawParameterInfo.covariate.names{k2},'(','_');
+                xxx = strrep(xxx,')','_');
+                test1 = strfind(xxx,['_' param '_']);
+                test2 = strfind(xxx,['_' cov]);
+                if ~isempty(test1) && ~isempty(test2),
+                    % Yes, this was a tested covariate
+                    % Calculate the p-value
+                    mu = RESULTS.rawParameterInfo.covariate.values(k2);
+                    sigma = RESULTS.rawParameterInfo.covariate.stderr(k2);
+                    p = min(normcdf(0,abs(mu),abs(sigma))*2);
+                    P_VALUES(k1) = min(p,P_VALUES(k1)); % Minimum handles multiple levels categorical covs
+                end
+            end
+        end
+        
+        % Check if all P values <= p_backward
+        if sum(P_VALUES > p_backward) ~= 0,
+            continueBackwardSearch = 1;
+            
+            % Message
+            fprintf(fid,'* Level %d: "%s"\n',levelCount,levelModel);
+            fprintf(fid,'\n');
+            
+            for k1=1:length(covSearchBackward.paramNamesTest),
+                fprintf(fid,'%s on %s: P=%g Goal<=%g ... ',covSearchBackward.covcatNamesTest{k1},covSearchBackward.paramNamesTest{k1},P_VALUES(k1),p_backward);
+                if P_VALUES(k1)<=p_backward,
+                    fprintf(fid,'significant');
+                else
+                    fprintf(fid,'not significant');
+                end
+                fprintf(fid,'\n');
+            end
+            
+            % Remove the largest P_value
+            [xdummyx,ix_remove] = max(P_VALUES);
+            
+            % Message
+            fprintf(fid,'\n');
+            fprintf(fid,'Removed covariate for next level: %s on %s\n',covSearchBackward.covcatNamesTest{ix_remove},covSearchBackward.paramNamesTest{ix_remove});
+            fprintf(fid,'\n');
+            
+            % Remove covariate
+            covSearchBackward.paramNamesTest(ix_remove) = [];
+            covSearchBackward.covcatNamesTest(ix_remove) = [];
+            covSearchBackward.delta_forward(ix_remove) = [];
+            covSearchBackward.delta_backward(ix_remove) = [];
+            %%%
+            covSearchBackward.value(ix_remove) = [];
+            %%%
+            
+            % Build covariate test structure
+            x = unique(covSearchBackward.paramNamesTest);
+            covTestStructure = {};
+            %%%
+            covariateModelValues = cell(1,length(x));
+            COVestimate = cell(1,length(x));
+            %%%
+            for k2=1:length(x),
+                covTestStructure{k2}{1} = x{k2};
+            end
+            covTestStructure = covTestStructure(:);
+            for k2=1:length(covSearchBackward.paramNamesTest),
+                ix = strmatchSB(covSearchBackward.paramNamesTest{k2},x,'exact');
+                covTestStructure{ix}{end+1} = covSearchBackward.covcatNamesTest{k2};
+                %%%
+                covariateModelValues{ix}(end+1) = covSearchBackward.value(k2);
+                COVestimate{ix}(end+1) = 1;
+                %%%
+            end
+            
+            
+            
+            
+            
+            % Convert to required format
+            covariateModel                      = '';
+            for k3=1:size(covTestStructure,1),
+                if ~isempty(covTestStructure{k3}),
+                    text                        = sprintf('%s,',covTestStructure{k3}{:});
+                    covariateModel              = [covariateModel '{' text(1:end-1) '},'];
+                end
+            end
+            covariateModel                      = covariateModel(1:end-1);
+            
+            % Add structural covariates to covariate model
+            for k3=1:length(covStructural.paramNames),
+                param    = covStructural.paramNames{k3};
+                cov      = covStructural.covcatNames{k3};
+                value    = covStructural.value(k3);
+                estimate = covStructural.estimate(k3);
+                % Find where to add
+                ix = [];
+                for k4=1:size(covTestStructure,1),
+                    if strcmp(param,covTestStructure{k4}{1}),
+                        ix = k4;
+                        break;
+                    end
+                end
+                if ~isempty(ix),
+                    % add info
+                    covTestStructure{ix}{end+1} = cov;
+                    covariateModelValues{ix}(end+1) = value;
+                    COVestimate{ix}(end+1) = estimate;
+                else
+                    % new param
+                    covTestStructure{end+1}{1} = param;
+                    covTestStructure{end}{2} = cov;
+                    covariateModelValues{end+1}(1) = value;
+                    COVestimate{end+1}(1) = estimate;
+                end
+                covTestStructure = covTestStructure(:);
+            end
+            
+            % Convert to required format for the search things
+            covariateModel                      = '';
+            for k3=1:size(covTestStructure,1),
+                if ~isempty(covTestStructure{k3}),
+                    text                        = sprintf('%s,',covTestStructure{k3}{:});
+                    covariateModel              = [covariateModel '{' text(1:end-1) '},'];
+                end
+            end
+            covariateModel                      = covariateModel(1:end-1);
+            
+            % Set covariateModel
+            options.covariateModel              = covariateModel;
+            options.covariateModelValues        = covariateModelValues;
+            options.COVestimate                 = COVestimate;
+            
+            
+            % Create model
+            ModelName                           = sprintf('MODEL_%s',preFillCharSB(countModel,length(num2str(Nmaxmodels)),'0'));
+            FolderName                          = [projectPath sprintf('/BW_LEVEL_%d',levelCount)];
+            ModelFolder                         = [FolderName '/' ModelName];
+            
+            % Assume standard popPK workflow structure
+            dataRelPathFromProjectPath = '../../../../Data';
+            modelNameFIT = ModelName;
+            [FLAGanalyticModel,MODEL_SETTINGS] = createPopPK_NLMEproject_ODE_Analytic_SBPOP( ...
+                FLAG_NONMEM,modelNameFIT,TemplateModels, ...
+                FACTOR_UNITS, numberCompartments,saturableClearance, ...
+                lagTime,data,ModelFolder,dataRelPathFromProjectPath,options);
+            
+            countModel                          = countModel + 1;
+            
+            % Run the model - do not create GoF plots
+            SBPOPrunNLMEprojectFolder(FolderName,N_PROCESSORS_PAR,N_PROCESSORS_SINGLE,1);
+            
+            % Read information
+            LEVEL_RESULTS = SBPOPfitanalysisProjectsFolderInfo(FolderName,FolderName);
+            OLD_OFV = LEVEL_RESULTS.OBJ;
+            
+            % Define things for next level
+            for kkk=1:length(parNames),
+                ix_options = strmatchSB(parNames{kkk},TemplateModels.ParameterNames.ODE,'exact');
+                ix_result  = strmatchSB(parNames{kkk},LEVEL_RESULTS.rawParameterInfo.fixedEffects.names,'exact');
+                options.POPvalues0(ix_options)  = LEVEL_RESULTS.rawParameterInfo.fixedEffects.values(ix_result);
+                options.IIVvalues0(ix_options)  = LEVEL_RESULTS.rawParameterInfo.randomEffects.values(ix_result);
+            end
+            options.errorParam0 = LEVEL_RESULTS.rawParameterInfo.errorParameter.values;
+            
+            levelModel = covariateModel;
+            levelCount = levelCount+1;
+            BackwardModelName = ModelFolder;
+            
+            
+            %%%
+            % Update values in covSearchBackward to estimated ones in best model
+            covInfo = LEVEL_RESULTS.rawParameterInfo.covariate;
+            
+            for k1x = 1:length(covSearchBackward.paramNamesTest),
+                paramUpdate = covSearchBackward.paramNamesTest{k1x};
+                covUpdate   = covSearchBackward.covcatNamesTest{k1x};
+                
+                % Find parameter and covariate
+                matchIX = [];
+                for kkkx=1:length(covInfo.names),
+                    ixParam = strfind(covInfo.names{kkkx},paramUpdate);
+                    ixCov = strfind(covInfo.names{kkkx},covUpdate);
+                    if ~isempty(ixParam) && ~isempty(ixCov),
+                        matchIX(end+1) = kkkx;
+                    end
+                end
+                if length(matchIX) ~= 1,
+                    error('Problem with getting covariate coefficient value.');
+                end
+                % Get the estimated value
+                value = covInfo.values(matchIX);
+                % Add value to covSearchBackward
+                covSearchBackward.value(k1x) = value;
+            end
+            %%%
+            
+        else
+            continueBackwardSearch = 0;
+            
+            % Message
+            fprintf(fid,'* Level %d: "%s"\n',levelCount,levelModel);
+            fprintf(fid,'\n');
+            
+            for k1=1:length(covSearchBackward.paramNamesTest),
+                fprintf(fid,'%s on %s: P=%g Goal<=%g ... ',covSearchBackward.covcatNamesTest{k1},covSearchBackward.paramNamesTest{k1},P_VALUES(k1),p_backward);
+                if P_VALUES(k1)<=p_backward,
+                    fprintf(fid,'significant');
+                else
+                    fprintf(fid,'not significant');
+                end
+                fprintf(fid,'\n');
+            end
+            fprintf(fid,'\n');
+            
+        end
+        
+    end
+    
+    
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get backward results
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+BACKWARD_OFV = OLD_OFV;
+backwardModel = levelModel;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Report backward model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+fprintf(fid,'************************************\n');
+fprintf(fid,'* BACKWARD MODEL RESULTS           *\n');
+fprintf(fid,'************************************\n');
+fprintf(fid,'\n');
+
+fprintf(fid,'Backward model:            %s\n',BackwardModelName);
+fprintf(fid,'Covariates:                %s\n',backwardModel);
+fprintf(fid,'Objective function value:  %g\n',BACKWARD_OFV);
+fprintf(fid,'\n');
+
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%
+% Close report file
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fclose(fid);
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/dataset/SBPOPdataset2wide.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/dataset/SBPOPdataset2wide.m
new file mode 100644
index 0000000000000000000000000000000000000000..64849b88bc277ed77131fdbc1bf96ed2946e1072
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/dataset/SBPOPdataset2wide.m
@@ -0,0 +1,91 @@
+function [datawide] = SBPOPdataset2wide(data,groupID,groupTIME,paramnames,paramvalues)
+% [DESCRIPTION]
+% This function expands a dataset from a row based format to a column based 
+% format. Records in the row based format are stored in rows, while a parameter
+% column defines the type/name of the recorded parameter. In the column  based 
+% format there is a column for each measured parameter with the column name as
+% the parameters name. 
+% The name of the columns with the parameternames and values need to be provided.
+% All other columns are kept. An ID and a TIME column needs to be present, since
+% all parameters for a single ID at a single TIME point are converted into one row
+% of the wide dataset.
+%
+% [SYNTAX]
+% datawide = SBPOPdataset2wide(data,groupID,groupTIME,paramnames,paramvalues)
+%
+% [INPUT]
+% data:         dataset in row format
+% groupID:      string: name of the column to use as individual grouping (e.g. ID)
+% groupTIME:    string: name of the column to use as time grouping (e.g. TIME or NOMINAL_TIME)
+% paramnames:   string: name of the column in which the parameter names are recorded
+% paramvalues:  string: name of the column in which the parameter values are recorded
+%
+% [OUTPUT]
+% datawide:     dataset in wide format (one column per parameter)
+%
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 13.12.2010
+%
+% [PLATFORM]
+% Windows XP Engine, MATLAB R2009a, MODESIM MATLAB
+%
+% [KEYWORDS]
+% dataset, row, column
+% 
+% [TOOLBOXES USED]
+% Statistics toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+% Bring into column based (wide) format
+datawide = dataset();
+PARAM = unique(data.(paramnames));
+
+allID = unique(data.(groupID));
+for k=1:length(allID),
+    datak = data(data.(groupID)==allID(k),:);
+    allTIME = unique(datak.(groupTIME));
+    for k2=1:length(allTIME),
+        datakk2 = datak(datak.(groupTIME)==allTIME(k2),:);
+        % Create row
+        row = datakk2(1,:);
+        for k3=1:length(PARAM),
+            ix = strmatchSB(PARAM{k3},datakk2.(paramnames),'exact');
+            if isempty(ix),
+                row.(PARAM{k3}) = NaN;
+            else
+                row.(PARAM{k3}) = mean(datakk2.(paramvalues)(ix));
+            end
+        end
+        datawide = [datawide; row];
+    end
+end
+datawide.(paramnames) = [];
+datawide.(paramvalues) = [];
+
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/dataset/SBPOPexportCSVdataset.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/dataset/SBPOPexportCSVdataset.m
new file mode 100644
index 0000000000000000000000000000000000000000..433aa28a83beab3e4e860e30f7ac153299151e7a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/dataset/SBPOPexportCSVdataset.m
@@ -0,0 +1,162 @@
+function [] = SBPOPexportCSVdataset(data,filename,varargin)
+% [DESCRIPTION]
+% This function exporst a MATLAB dataset as standard CSV datafile. 
+% Nothing magic, just avoiding a lengthy "export" command.
+%
+% [SYNTAX]
+% [] = SBPOPexportCSVdataset(data,filename)
+% [] = SBPOPexportCSVdataset(data,filename,options)
+%
+% [INPUT]
+% data:         a MATLAB dataset
+% filename:     Filename, possibly including relative or absolute path.
+%               Extension is arbitrary.
+% options:      MATLAB structure with additional options
+%
+%               options.headerCharNONMEM: A character should be given,
+%                   which is added as starting character into the first line.
+%                   This is needed for NONMEM to be able to exclude the
+%                   header from being read. ($DATA filename.csv
+%                   IGNORE="CHAR"). Default: '' 
+%
+%               options.maxlengthNumbers: allows to define the maximum
+%                   length of numbers in the datafile (NONMEM6 has a max of
+%                   12). Default: Do not change anything ([]).
+%
+% [OUTPUT]
+% NONE
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 14th April 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MATLAB R2009a, MATLAB
+%
+% [KEYWORDS]
+% MATLAB, SBPOP, CSV, import, dataset
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+ 
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input argument
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~ischar(filename),
+    error('Please provide a filename as second input argument.');
+end
+if ~strcmp(class(data),'dataset'),
+    error('The first input argument needs to be a dataset.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create folder if needed
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[p,f] = fileparts(filename);
+if ~isempty(p),
+    mkdir(p);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Default values
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+headerCharNONMEM = '';
+maxlengthNumbers = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle varargins
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 2,
+elseif nargin == 3,
+    options = varargin{1};
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle options
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try headerCharNONMEM = options.headerCharNONMEM; catch, end
+try maxlengthNumbers = options.maxlengthNumbers; catch, end
+
+if ~ischar(headerCharNONMEM),
+    error('The "headerCharNONMEM" option needs to be a sinlge character.');
+end
+if length(headerCharNONMEM) > 1,
+    error('The "headerCharNONMEM" option needs to be a sinlge character.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Export dataset
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+export(data,'File',filename,'Delimiter',',');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if char to be added
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(headerCharNONMEM),
+    content = fileread(filename);
+    content = [headerCharNONMEM content];
+    % Add one single 10 at the end
+    content = [strtrim(content) char(10)];
+    fid = fopen(filename,'w');
+    fprintf(fid,content);
+    fclose(fid);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle the maximum length of numbers
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(maxlengthNumbers),
+    % Do the conversion
+    fid = fopen(filename);
+    header = fgetl(fid);
+    newcontent = '';
+    while(~feof(fid)),
+        line = fgetl(fid);
+        terms = explodePCSB(line);
+        for k=1:length(terms),
+            if length(terms{k}) > maxlengthNumbers,
+                terms{k} = terms{k}(1:maxlengthNumbers);
+            end
+        end
+        newline = sprintf('%s,',terms{:});
+        newline = newline(1:end-1);
+        newcontent = [newcontent char(10) newline];
+    end
+    newheader = header;
+    newcontent = [newheader newcontent char(10)];
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Write out converted dataset
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    fid = fopen(filename,'w');
+    fprintf(fid,'%s',newcontent);
+    fclose(fid);
+end
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/dataset/SBPOPloadCSVdataset.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/dataset/SBPOPloadCSVdataset.m
new file mode 100644
index 0000000000000000000000000000000000000000..9e008945e608b92d9ccb540193a92efa50208d70
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/dataset/SBPOPloadCSVdataset.m
@@ -0,0 +1,156 @@
+function [varargout] = SBPOPloadCSVdataset(filename, varargin)
+% [DESCRIPTION]
+% This function loads a standard CSV datafile with header as a dataset into
+% MATLAB. Nothing magic, just avoiding a lengthy "dataset" command, and 
+% replacing non a-z,A-z,_,0-9 by underscores, so the dataset functionality
+% in MATLAB can work with it nicely.
+% If the function has two output arguments, then the function tries to
+% separate the data into observation and dosing datasets. For this the
+% columns MDV and EVID need to be present.
+%
+% Since MATLAB 2012a, the dataset command is unable to correctly read CSV
+% files if empty entries somewhere in the last column. This should be a bug
+% in MATLAB. Anyway, if in the first attempt the dataset loading results in
+% an error, empty fields in the last column are going to be filled with
+% NaNs and a reload is attempted.
+%
+% [SYNTAX]
+% [data] = SBPOPloadCSVdataset(filename)
+% [header] = SBPOPloadCSVdataset(filename,FLAG_HEADER_ONLY)
+%
+% [INPUT]
+% filename: Filename, possibly including relative or absolute path.
+%           Extension is arbitrary.
+% FLAG_HEADER_ONLY: =0: loads dataset normally, =1: return cell-array with header names
+%
+% [OUTPUT]
+% data:      a MATLAB dataset containing the contents of the CSV datafile
+% obs_data:  a MATLAB dataset containing the observations (MDV==0) of the
+%            CSV datafile (if MDV defined)
+% dose_data: a MATLAB dataset containing the dosing records (EVID==1) of the
+%            CSV datafile (if EVID defined)
+% header:    cell-array with header names
+%
+% [ASSUMPTIONS]
+% It is assumed that the dataset file is comma separated and correct. Any
+% apriori modifications of the file have to be done outside this function.
+% The header is expected in the first row.
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 14th April 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MATLAB R2009a, MATLAB
+%
+% [KEYWORDS]
+% MATLAB, SBPOP, CSV, import, dataset
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+ 
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input argument
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~ischar(filename),
+    error('Please provide a filename as input argument.');
+end
+if exist(filename) ~= 2,
+    error(['The file ''' filename ''' does not exist.']);
+end
+
+FLAG_HEADER_ONLY = 0;
+if nargin==2,
+    FLAG_HEADER_ONLY = varargin{1};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Load header
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen(filename);
+header = fgetl(fid);
+fclose(fid);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Process header
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% split into single terms (CSV)
+header = explodePCSB(header);
+% replace all unwanted chars by underscore
+header = regexprep(header,'\W','_');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Return only header if desired
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if FLAG_HEADER_ONLY,
+    varargout{1} = header;
+    return
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Load dataset from CSV file
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try
+    % Normal behavior
+    data = dataset('File',filename,'delimiter',',');
+catch x
+    if strcmp(x.message,'Index exceeds matrix dimensions.'),
+        % Warn the user and try the MATLAB R2012 tweak - Mathworks is really
+        % stupid - if they can not even support well CSV import!!!
+        warning(sprintf('SBPOPloadCSVfile: First attempt at loading dataset failed. Trying now with R2012 tweak of last column.\n Previous error message was:\n\t"%s"',x.message));
+        % R2012 MATLAB tweak
+        contents = fileread(filename);
+        contents = strrep(contents,[',' char(10)],[',NaN' char(10)]);
+        tempCSVfile_tweaked = tempname;
+        fid = fopen(tempCSVfile_tweaked,'w');
+        fprintf(fid,'%s',contents);
+        fclose(fid);
+        data = dataset('File',tempCSVfile_tweaked,'delimiter',',');
+    else
+        rethrow(x);
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Replace the header by the cleaned header
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+data = set(data,'VarNames',header);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle output arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargout == 1,
+    varargout{1} = data;
+else
+    error('Incorrect number of output arguments.');
+end
+
+
+
+
+
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/dataset/SBPOPloadNONCSVdataset.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/dataset/SBPOPloadNONCSVdataset.m
new file mode 100644
index 0000000000000000000000000000000000000000..83234f97f70b2178ef3b80f41d48a152e3ea19a9
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/dataset/SBPOPloadNONCSVdataset.m
@@ -0,0 +1,127 @@
+function [data] = SBPOPloadNONCSVdataset(filename,varargin)
+% [DESCRIPTION]
+% This function loads a NON CSV datafile with header as a dataset into
+% MATLAB. Nothing magic, just avoiding a lengthy "dataset" command, and 
+% replacing non a-z,A-z,_,0-9 by underscores, so the dataset functionality
+% in MATLAB can work with it nicely.
+% Difference to loading CSV datasets is that in this function more general
+% type of files is handled. They can be tab separated, space separated,
+% etc. 
+% Typical files that can be loaded in this way are: NONMEM output tables,
+% Monolix output tables, etc. 
+% NONMEM typically has on crap line as first line and the header starting
+% in the second line. For this the number of lines to drop can be passed to
+% this function.
+%
+% [SYNTAX]
+% [data] = SBPOPloadNONCSVdataset(filename)
+% [data] = SBPOPloadNONCSVdataset(filename,droplines)
+%
+% [INPUT]
+% filename: Filename, possibly including relative or absolute path.
+%           Extension is arbitrary.
+% droplines: number of lines before the start of the header (default: 0)
+%
+% [OUTPUT]
+% data: a MATLAB dataset
+%
+% [ASSUMPTIONS]
+% It is assumed that the dataset is rectangular and either space, tab, or
+% comma separated. A separation by semicolon, colon, etc. will not work.
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 15th April 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MATLAB R2009a, MATLAB
+%
+% [KEYWORDS]
+% MATLAB, SBPOP, CSV, import, dataset
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+% Updated by Irina Baltcheva, Sept. 27th, 2013
+% If inter-occasions variability was used (for ex: with SS and II column
+% for steady state PK modeling), we remove the #x (where x is the occasion
+% number) next to the id number in predictions.txt.
+
+% Information:
+% ============
+% Copyright ? 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle varargins
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 1,
+    droplines = 0;
+elseif nargin == 2,
+    droplines = varargin{1};
+else
+    error('Incorrect number of input arguments.');
+end 
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input argument
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~ischar(filename),
+    error('Please provide a filename as input argument.');
+end
+if exist(filename) ~= 2,
+    error(['The file ''' filename ''' does not exist.']);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Load header & content
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen(filename);
+k = 0;
+while k<droplines,
+    fgetl(fid);
+    k=k+1;
+end
+header = fgetl(fid);
+content = [];
+while ~feof(fid),
+    aline = fgetl(fid); % get one line at the time
+    [token, remain] = strtok(aline); % separate the id from the remaining columns
+    [the_id, crap] = strtok(token, '#'); % separate the id from the #1, etc.
+    new_line = [the_id remain]; % reconstitute the line without the crap
+    content = [content char(10) new_line];
+end
+fclose(fid);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Process header
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+header2 = regexprep(strtrim(header),'[\s]+',',');
+% split into single terms (CSV)
+header2 = explodePCSB(header2);
+% replace all unwanted chars by underscore
+header2 = regexprep(header2,'\W','_');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create dataset
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+values = eval(['[' content ']']);
+data = dataset({values,header2{:}});
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/dataset/SBPOPsas7bdat2csv.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/dataset/SBPOPsas7bdat2csv.m
new file mode 100644
index 0000000000000000000000000000000000000000..a664f56789bdac3d5522e36e8d6042f156f0bfd3
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/dataset/SBPOPsas7bdat2csv.m
@@ -0,0 +1,89 @@
+function [] = SBPOPsas7bdat2csv( filenameSAS7BDAT,pathCSVfile,version )
+% [DESCRIPTION]
+% This function converts a sas7bdat file into a CSV file. It only works if
+% SAS is installed on the system and available by the command line command
+% "sas".
+% Version control via clearcase is assumed. 
+%
+% [SYNTAX]
+% [] = SBPOPsas7bdat2csv( filenameSAS7BDAT, pathCSVfile )
+% [] = SBPOPsas7bdat2csv( filenameSAS7BDAT, pathCSVfile, version )
+%
+% [INPUT]
+% filenameSAS7BDAT:     String with path and filename of sas7bdat file
+% pathCSVfile:          Path to where to store the CSV file. Same filename
+%                       is used as for the sas7bdat file, but with .csv at the end
+% version:              Numeric version  of file under clearcase (default: NaN=use latest version)
+%
+% [OUTPUT]
+% exitflag:             SAS ran successfully if exitflag==0
+% 
+% CSV file is written in the specified folder.
+%
+% [ASSUMPTIONS]
+% SAS is installed on the system and available by the command line command
+% "sas".
+% Clearcase version control is assumed for access to a specific version.
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 14.02.2013
+%
+% [PLATFORM]
+% Windows, MATLAB R2012a, Linux
+
+if nargin==2,
+    version = NaN;
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Copy the original sas file to temp folder
+% (allows for handling clearcase version numbers)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isnan(version),
+    filenameversion = filenameSAS7BDAT;
+else
+    filenameversion = sprintf('%s@@/main/%d',filenameSAS7BDAT,version);
+end
+copyfile(filenameversion,fullfile(tempdirSB,'tempsasfile.sas7bdat'),'f');
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create SAS command in temp folder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen([tempdirSB 'export2csv.sas'],'w');
+fprintf(fid,'libname output "%s" ;\n',tempdirSB);
+fprintf(fid,'options fmterr=no;\n');
+fprintf(fid,'\n');
+fprintf(fid,'proc export data=output.tempsasfile\n');
+fprintf(fid,'           outfile   = "%stempsasfile.csv" replace ;\n',tempdirSB);
+fprintf(fid,' 	        delimiter = ''%s'' ;\n',char(127));
+fprintf(fid,'run;\n');
+fclose(fid);
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run SAS command
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[~,~,~,PATH_SAS] = getNLMEtoolInfoSBPOP();
+if isempty(PATH_SAS),
+    error('Path to SAS not defined in SETUP_PATHS_TOOLS.m');
+end
+
+exitflag = system(sprintf('%s %sexport2csv.sas',PATH_SAS,tempdirSB));
+if exitflag~=0,
+    error('SAS is required for conversion from sas7bdat to CSV. It might not be available on your system.');
+end
+    
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Load file, remove commata and replace "char(127)" sign
+% Also, empty fields in the last column only will be filled with "NA"
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[x,CSVfilename] = fileparts(filenameSAS7BDAT);
+contents = fileread([tempdirSB 'tempsasfile.csv']);
+contents = strrep(contents,',','');
+contents = strrep(contents,char(127),',');
+fid = fopen(fullfile(pathCSVfile,[CSVfilename '.csv']),'w');
+fprintf(fid,'%s',contents);
+fclose(fid);
+    
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/dataset/auxiliary/createStratifiedDatasetSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/dataset/auxiliary/createStratifiedDatasetSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..fd8b99705bcb1d7350d1cbf3f1347a9e1a75deae
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/dataset/auxiliary/createStratifiedDatasetSBPOP.m
@@ -0,0 +1,118 @@
+function [dataStratified,THRESHOLD] = createStratifiedDatasetSBPOP(data,IDname,stratificationName,stratificationRange)
+% [DESCRIPTION]
+% This function returns a subset of the data.
+% "stratificationName" needs to be a column name for a column which
+% entries are constant for each subject (covariate columns).
+% "stratificationRange" indicates if the lower range or the upper range of
+% the covariate values is to be kept.
+%
+% Both continuous and categorical covariates can be used for
+% stratification. In the continuous case, the median is used. The lower
+% part includes the median. In the categorical case the mean is used as
+% threshold. The stratification threshold is determined based on the
+% overall dataset.
+%
+% [SYNTAX]
+% [datastratified,THRESHOLD] = createStratifiedDatasetSBPOP(data,IDname,stratificationName,stratificationRange)
+%
+% [INPUT]
+% data:                 dataset to be stratified
+% IDname:               column name defining unique subject identifier - for example "ID"
+% stratificationName:   column name of a covariate to use for
+%                       stratification - if empty then full dataset is
+%                       returned
+% stratificationRange:  "" or "lower" or "upper". In the case of
+%                       "" the full dataset is returned. In the
+%                       case of "lower" all subjects with covariate above
+%                       the median (continuous) or mean (categorical) are
+%                       removed from the dataset. And
+%                       similar for "upper"
+%
+% [OUTPUT]
+% The stratified dataset. Also the THRESHOLD value that was used is returned
+% (NaN if not stratified)
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 20th April 2014
+%
+% [PLATFORM]
+% Windows, Unix, MATLAB
+%
+% [TOOLBOXES USED]
+% Statistics Toolbox
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+%
+% This program is Free Open Source Software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%% Check inputs
+if ~isempty(stratificationRange) && ~strcmp(lower(stratificationRange),'lower') && ~strcmp(lower(stratificationRange),'upper'),
+    error('Wrong definition of input argument "stratificationRange".');
+end
+
+varnames = get(data,'VarNames');
+
+if ~isempty(stratificationName),
+    ix = strmatchSB(stratificationName,varnames,'exact');
+    if isempty(ix),
+        error('Selected stratification variable does not exist in the dataset.');
+    end
+end
+
+ix = strmatchSB(IDname,varnames,'exact');
+if isempty(ix),
+    error('Selected IDname does not exist in the dataset.');
+end
+
+%% Handle stratification
+if ~isempty(stratificationName) && ~isempty(stratificationRange),
+    stratificationRange = strrep(stratificationRange,'_','');
+    % Get values for stratificationName 
+    VALUES = [];
+    allID = unique(data.(IDname));
+    for k=1:length(allID),
+        datak = data(data.(IDname)==allID(k),:);
+        VALUES = [VALUES datak.(stratificationName)(1)];
+    end
+    % Determine threshold ... median for continuous, mean for categorical. 
+    % Categorical is decided if number of unique values == 2
+    if length(unique(VALUES))==2,
+        THRESHOLD = mean(unique(VALUES));
+    else
+        THRESHOLD = median(VALUES);
+    end    
+    % Keep only specified range
+    if strcmp(lower(stratificationRange),'lower'),
+        % Keep values <=THRESHOLD
+        dataUse = data(data.(stratificationName)<=THRESHOLD,:);
+    else
+        % Keep values >THRESHOLD
+        dataUse = data(data.(stratificationName)>THRESHOLD,:);
+    end
+else
+    THRESHOLD = NaN;
+    % Keep all data
+    dataUse = data;
+end
+
+dataStratified = dataUse;
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/dataset/auxiliary/resampleDatasetSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/dataset/auxiliary/resampleDatasetSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..3e8c1f946377457cbd8efbaba86a8da8dc265a0b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/dataset/auxiliary/resampleDatasetSBPOP.m
@@ -0,0 +1,147 @@
+function [datasampled] = resampleDatasetSBPOP(data,IDname,groupName)
+% [DESCRIPTION]
+% This function resamples a dataset. The structure and the number of 
+% subjects is preserved. Useful for bootstrapping. Original subjects can
+% appear several times in the resampled dataset.
+%
+% [SYNTAX]
+% [datasampled] = resampleDatasetMedianSBPOP(data,IDname)
+% [datasampled] = resampleDatasetMedianSBPOP(data,IDname,groupName)
+%
+% [INPUT]
+% data:                 dataset to be resampled
+% IDname:               column name defining unique subject identifier - for example "ID"
+% groupName:            column name defining structure to keep in the
+%                       resampled dataset (e.g. "TRT"). Then resampling is
+%                       done independently for each of these groups.
+%                       The values in the groupName column need to be
+%                       constant for each subject (IDname). Continuous
+%                       covariates should not be chosen - categorical
+%                       covariates are better suited. Combinations of
+%                       several covariates for grouping could be done by
+%                       defining a new categorical covariate that reflects
+%                       the modelers wishes.
+%
+% [OUTPUT]
+% The resampled dataset. 
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 20th April 2014
+%
+% [PLATFORM]
+% Windows, Unix, MATLAB
+%
+% [TOOLBOXES USED]
+% Statistics Toolbox
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+%
+% This program is Free Open Source Software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%% Handle variable input arguments
+if nargin == 2,
+    groupName = '';
+end    
+
+%% Check input arguments
+varnames = get(data,'VarNames');
+
+ix = strmatchSB(IDname,varnames,'exact');
+if isempty(ix),
+    error('Selected IDname does not exist in the dataset.');
+end
+
+if ~isempty(groupName),
+    ix = strmatchSB(groupName,varnames,'exact');
+    if isempty(ix),
+        error('Selected groupName does not exist in the dataset.');
+    end
+end
+
+%% Determine number of groups in groupName and warn if too large
+if ~isempty(groupName),
+    groupCount = length(unique(data.(groupName)));
+    IDcount    = length(unique(data.(IDname)));
+    if groupCount > IDcount/4,
+        warning('Number of groupName elements larger than 25% of subjects.');
+    end
+end
+
+%% Resample if groupName not defined
+if isempty(groupName),
+    datasampled                 = dataset();
+    countID                     = 1;
+    
+    % Get all IDs
+    allID                       = unique(data.(IDname));
+    
+    % Get number of subjects
+    Nsubjects                   = length(allID);
+    
+    % Sample from the IDs
+    newID                       = allID(ceil(Nsubjects*rand(Nsubjects,1)));
+    
+    for k2=1:length(newID),
+        datak2 = data(data.(IDname)==newID(k2),:);
+        % Update ID so it becomes unique
+        datak2.(IDname)         = countID*ones(length(datak2),1);
+        countID                 = countID+1;
+        % Add to new dataset
+        datasampled             = [datasampled; datak2];
+    end
+end
+
+%% Resample if groupName is defined
+if ~isempty(groupName),
+    datasampled                 = dataset();
+    countID                     = 1;
+    allGROUP                    = unique(data.(groupName));
+    
+    for k=1:length(allGROUP),
+        datak                   = data(data.(groupName)==allGROUP(k),:);
+        
+        % Get all IDs
+        allID                   = unique(datak.(IDname));
+        
+        % Get number of subjects
+        Nsubjects               = length(allID);
+        
+        % Sample from the IDs
+        newID                   = allID(ceil(Nsubjects*rand(Nsubjects,1)));
+        
+        % add new subjects to dataset
+        datasampledGROUP        = dataset();
+        
+        for k2=1:length(newID),
+            datak2 = datak(datak.(IDname)==newID(k2),:);
+            % Update ID so it becomes unique
+            datak2.(IDname)     = countID*ones(length(datak2),1);
+            countID             = countID+1;
+            % Add to new dataset
+            datasampledGROUP    = [datasampledGROUP; datak2];
+        end
+        
+        % Add to new dataset
+        datasampled             = [datasampled; datasampledGROUP];
+    end
+end
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/model/basicmodelparsingSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/model/basicmodelparsingSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..2add056694de9ecd5d9d965c072c25184ea3f829
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/model/basicmodelparsingSBPOP.m
@@ -0,0 +1,378 @@
+function [modelinfo] = basicmodelparsingSBPOP(model)
+% basicmodelparsingSBPOP: Basic parsing of the model as preparation for 
+% export of population modeling formats (e.g. MONOLIX/NONMEM). The
+% function returns the following structure:
+%
+% modelinfo.model:             the model
+% modelinfo.inputs.name:       input name
+% modelinfo.inputs.factors:    cell-array with input factors
+% modelinfo.inputs.terms:      cell-array with complete input string (for
+%                              simpler removing)
+% modelinfo.inputs.stateindex: vector with stateindices to which the same
+%                              input is applied
+% modelinfo.inputs.parindex:   index of the INPUT* parameter definition in
+%                              the SBmodel (used to remove it when
+%                              parameters are written to (e.g.) an MLXTRAN
+%                              file).   
+% modelinfo.outputs.name:      output name
+% modelinfo.outputs.formula:   output formula
+% modelinfo.outputs.notes:     output notes
+% modelinfo.outputs.varindex:  index of output in model variables
+% modelinfo.param_est.name:    name of parameter to estimate 
+% modelinfo.param_est.notes:   estimated parameter notes
+% modelinfo.param_est.value0:  initial guess for parameter
+% modelinfo.param_est.parindex: index of parameter in parameters
+% modelinfo.param_reg.name:    name of regression parameter
+% modelinfo.param_reg.notes:   regression parameter notes
+% modelinfo.param_reg.parindex: index of reg param in parameters
+% modelinfo.param_reg.varindex: index of reg param in variables
+% modelinfo.param_pk.name:     name of parameter to define in PK section
+%                              (this is MLXTRAN specific but might be
+%                              useful for other applications to).
+% modelinfo.param_pk.value:    value of parameter
+% modelinfo.param_pk.parindex: index or parameter in model
+% modelinfo.param_pk.notes:    notes of the parameters
+%
+% Only very basic error handling is done. More intensive error checking is
+% done later, dependent on the tool that is going to be used for
+% pop-modelling (different features might be allowed).
+%
+% USAGE:
+% ======
+% [modelinfo] = basicmodelparsingSBPOP(model) 
+%
+% model: SBmodel
+%
+% Output Arguments:
+% =================
+% modelinfo: see structure definition above
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBmodel(model),
+    error('First input argument is not an SBmodel.');
+end
+ms = struct(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK MODEL: INPUTS ONLY ON STATES?
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~inputsonlyonstatesSBPOP(model),
+    error('The model contains ''INPUT*'' identifiers on other elements than ODEs.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INITIALIZE OUTPUT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+inputsStruct = struct('name',{},'stateindex',{},'parindex',{},'factors',{},'terms',{});
+outputsStruct = struct('name',{},'formula',{},'notes',{});
+param_estStruct = struct('name',{},'notes',{},'value0',{},'parindex',{});
+param_regStruct = struct('name',{},'notes',{},'parindex',{},'varindex',{});
+param_pkStruct = struct('name',{},'notes',{},'value',{},'parindex',{});
+modelinfo = struct('model',model,'inputs',inputsStruct,'outputs',outputsStruct,'param_est',param_estStruct,'param_reg',param_regStruct,'param_pk',param_pkStruct);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE PARAMETERS TO BE ESTIMATED
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(ms.parameters),
+    if ~isempty(strfind(ms.parameters(k).notes,'<estimate>')),
+        modelinfo.param_est(end+1).name = ms.parameters(k).name;
+        modelinfo.param_est(end).value0 = ms.parameters(k).value;
+        modelinfo.param_est(end).notes = ms.parameters(k).notes;
+        modelinfo.param_est(end).parindex = k;
+    end
+end
+% if no parameters to be estimated => error!
+if isempty(modelinfo.param_est),
+    error('No parameters in model selected for estimation.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE REGRESSION PARAMETERS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Regression parameters can be defined as parameters or as variables in the
+% SBmodel. The latter allows to implement lookup-tables in the model (if
+% the use of experiment descriptions is not considered).
+for k=1:length(ms.parameters),
+    if ~isempty(strfind(ms.parameters(k).notes,'<regression>')),
+        modelinfo.param_reg(end+1).name = ms.parameters(k).name;
+        modelinfo.param_reg(end).notes = strrep(ms.parameters(k).notes,'<regression>','');
+        modelinfo.param_reg(end).parindex = k;
+        modelinfo.param_reg(end).varindex = [];
+    end
+end        
+for k=1:length(ms.variables),
+    if ~isempty(strfind(ms.variables(k).notes,'<regression>')),
+        modelinfo.param_reg(end+1).name = ms.variables(k).name;
+        modelinfo.param_reg(end).notes = strrep(ms.variables(k).notes,'<regression>','');
+        modelinfo.param_reg(end).parindex = [];
+        modelinfo.param_reg(end).varindex = k;
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET MODEL INPUT INFORMATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[statenames,ODEs] = SBstates(model);
+% get model input names (unique)
+inputnames = {};
+inputodeindex = [];
+for k=1:length(ODEs),
+    y = regexp(ODEs{k},'(INPUT\w*)','tokens');
+    for k2=1:length(y),
+        x = y{k2};
+        inputnames{end+1} = x{1};
+        inputodeindex(end+1) = k;
+    end
+end    
+% add the current into to the structure and do basic error checking (same
+% input is not allowed to appear twice in same ODE)
+for k=1:length(inputnames),
+    inputindex = strmatchSB(inputnames{k},{modelinfo.inputs.name},'exact');
+    if isempty(inputindex),
+        modelinfo.inputs(end+1).name = inputnames{k};
+        modelinfo.inputs(end).stateindex = inputodeindex(k);
+    else
+        modelinfo.inputs(inputindex).stateindex = [modelinfo.inputs(inputindex).stateindex inputodeindex(k)];
+    end
+end
+for k=1:length(modelinfo.inputs),
+    if length(modelinfo.inputs(k).stateindex) ~= length(unique(modelinfo.inputs(k).stateindex)),
+        error('Input ''%s'' appears more than once in the same ODE.',modelinfo.inputs(k).name);
+    end
+end
+% determine the input factors
+for k=1:length(modelinfo.inputs),
+    stateindex = modelinfo.inputs(k).stateindex;
+    for k2=1:length(stateindex),
+        [factor, term] = getInputFactorFromODE(ODEs{stateindex(k2)},modelinfo.inputs(k).name);
+        modelinfo.inputs(k).factors{end+1} = factor;
+        modelinfo.inputs(k).terms{end+1} = term;
+    end
+end
+% determine the indices of the SBmodel parameters that define the nominal
+% input parameters
+for k=1:length(modelinfo.inputs),
+    index = strmatchSB(modelinfo.inputs(k).name,{ms.parameters.name},'exact');
+    if isempty(index),
+        error('Input ''%s'' is used in the model but undefined as a parameter.',modelinfo.inputs(k).name);
+    end
+    modelinfo.inputs(k).parindex = index;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET MODEL OUTPUT INFORMATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Outputs are defined be OUTPUT1 = ..., OUTPUT2 = ...
+% The ordering is done by the number after OUTPUT.
+searchOutput = 1;
+indexOutput = 1;
+allvarnames = {ms.variables.name};
+while (searchOutput == 1),
+    searchOutputName = sprintf('OUTPUT%d',indexOutput);
+    index = strmatchSB(searchOutputName,allvarnames,'exact');
+    if ~isempty(index),
+        modelinfo.outputs(end+1).name = searchOutputName;
+        modelinfo.outputs(end).formula = ms.variables(index).formula;
+        modelinfo.outputs(end).notes = ms.variables(index).notes;
+        modelinfo.outputs(end).varindex = index;
+        % search for next output
+        indexOutput = indexOutput + 1;
+    else
+        % No output with given index found => stop the search
+        searchOutput = 0;
+    end
+end
+% Error if no outputs are detected
+if isempty(modelinfo.outputs),
+    error('No outputs have been defined in the model using the "OUTPUT*" identifier.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE PARAMETERS etc. FOR INPUT FACTORS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Parameters used in the prefactors of inputs are either estimated, 
+% defined as regression variables, or defined in the PK section of an 
+% MLXTRAN file (and not in the ODE section). For that we need to determine 
+% the parameters that are to be put
+% into the PK section. This is MLXTRAN specific but the information
+% collected might come handy also for other export formats(?).
+% The information is stored in the following part of the structure:
+%
+% modelinfo.param_pk.name:     name of parameter to define in PK section
+%                              (this is MLXTRAN specific but might be
+%                              useful for other applications to).
+% modelinfo.param_pk.value:    value of parameter
+% modelinfo.param_pk.parindex: index or parameter in model
+% modelinfo.param_pk.notes:    notes of the parameters
+% 
+% All input pre-factors are only allowed to contain parameters No states,
+% no other parameters, no variables. => error if
+% 1) get all pre-factors
+allfactors = {};
+for k=1:length(modelinfo.inputs),
+    temp = modelinfo.inputs(k).factors;
+    allfactors = {allfactors{:} temp{:}};
+end
+% 2) get all parameters ... remove the ones to be estimated
+pn = SBparameters(model);               % all 
+pnest = {modelinfo.param_est.name};     % to be estimated
+pnreg = {};
+for k=1:length(modelinfo.param_reg),
+    if ~isempty(modelinfo.param_reg(k).parindex),
+        pnreg{end+1} = modelinfo.param_reg(k).name;
+    end
+end
+pnnotest = setdiff(pn,{pnest{:} pnreg{:}});           % not to be estimated
+% 3) Check if parameter that are not estimated appear in the factors and
+% add them to the param_pk field of the modelinfo structure
+for k=1:length(allfactors),
+    test = ['#' allfactors{k} '#'];
+    for k2=1:length(pnnotest),
+        index = regexp(test,['\W' pnnotest{k2} '\W'], 'once' );
+        if ~isempty(index),
+            % the parameter is not estimated an appears in the input factor
+            % check if it is already added to the param_pk field and if not
+            % => add it 
+            if isempty(strmatchSB(pnnotest{k2},{modelinfo.param_pk.name},'exact')),
+                parindex = strmatchSB(pnnotest{k2},pn,'exact');
+                modelinfo.param_pk(end+1).name = ms.parameters(parindex).name;
+                modelinfo.param_pk(end).value = ms.parameters(parindex).value;
+                modelinfo.param_pk(end).parindex = parindex;
+                modelinfo.param_pk(end).notes = ms.parameters(parindex).notes;
+            end
+        end
+    end
+end
+% 4) Check state, variable, reaction appearance in factors (if yes => error)
+sn = SBstates(model);
+vn = SBvariables(model);
+rn = SBreactions(model);
+allother = {sn{:} vn{:} rn{:}};
+for k=1:length(allfactors),
+    test = ['#' allfactors{k} '#'];
+    for k2=1:length(allother),
+        index = regexp(test,['\W' allother{k2} '\W'], 'once' );
+        if ~isempty(index),
+            disp('===============================================================================================');
+            disp(sprintf('The model component ''%s'' appears in an input pre-factor ''%s''.\nPlease note that no states, variables, or reactions are allowed to\nappear in these pre-factors. Only parameters!',allother{k2},allfactors{k}));
+            disp(' ');
+            disp('You might need to rearrange manually some equations from the ODE section in MLXTRAN to the PK section.');
+            disp('===============================================================================================');
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ITS DONE ... RETURN
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+return
+
+
+        
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXTRACT INPUT TERMS and check for validity
+% Only prefixes/prefactors to inputs allowed - otherwise error
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [factor,term] = getInputFactorFromODE(ODE,name)
+% find the start-index for the input name
+si = strfind(ODE,name);
+% get ODE text before input
+ODEpre = strtrim(ODE(1:si-1));
+ODEpost = strtrim(ODE(si+length(name):end));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DO SOME CHECKS FIRST: 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% 1) the INPUT* identifier needs to be the last element in the input term.
+% => ODEpost needs to start by "+" or "-" and contain as many opening
+% parentheses than closing ones. Because otherwise INPUT* would be in at
+% least one parenthesis. => Not allowed. 
+if ~isempty(ODEpost),
+    if ODEpost(1) ~= '+' && ODEpost(1) ~= '-',
+        error('The ''%s'' identifier must be the last element in the input term.',name);
+    end
+end
+npo = length(strfind(ODEpost,'(')); 
+npc = length(strfind(ODEpost,')'));
+if npo ~= npc,
+    error('The ''%s'' identifier is not allowed to be inside a parenthesis.',name);
+end
+% 2) The last character in the ODEpre string needs to be a '+' or a '*'. So
+% that in the latter case the part in front of the INPUT* identifier can be
+% understood as a factor. 
+if ~isempty(ODEpre),
+    if ODEpre(end) ~= '+' && ODEpre(end) ~= '*',
+        error('The ''%s'' term requires the following syntax: ''...+%s'' or ''...+(expression)*%s''.',name,name,name);
+    end
+end
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET THE FACTORS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% 3) If ODEpre is empty or ODEpre(end) = '+' then the factor is simply: 1
+if isempty(ODEpre),
+    factor = '1';
+    term = name;
+    return
+elseif ODEpre(end) == '+',
+    factor = '1';
+    term = ['+' name];
+    return
+end
+% 4) Parse the multiplicative input factor: We search for a '+' or '-'
+% outside of parentheses from right to left in ODEpre. If '-' then error.
+% If no + found then it is assumed that INPUT statement first in ODE.
+po = 0;
+plusFound = 0;
+for k=length(ODEpre):-1:1,
+    if ODEpre(k) == '(',
+        % count opening parenthesis
+        po = po+1;
+    end
+    if ODEpre(k) == ')',
+        % count closing parenthesis
+        po = po-1;
+    end
+    if ODEpre(k) == '+' && po == 0,
+        % start of factor found
+        plusFound = 1;
+        break;
+    end
+    if ODEpre(k) == '-' && po == 0,
+        % start of factor found but '-' not allowed
+        error('An input term for ''%s'' is substracted from an ODE (addition only allowed).',name); 
+        break;
+    end
+end
+% 5) extract the factor and return (ITS DONE :))
+if plusFound,
+    factor = ODEpre(k+1:end-1);
+else
+    factor = ODEpre(k:end-1);
+end    
+term = [ODEpre(k:end-1) '*' name];
+return
+
+
+
+
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/model/inputsonlyonstatesSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/model/inputsonlyonstatesSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..aaea309cdd0c0d2e173ada28f9efd08fe788076f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/model/inputsonlyonstatesSBPOP.m
@@ -0,0 +1,64 @@
+function [output] = inputsonlyonstatesSBPOP(model)
+% inputsonlyonstatesSBPOP: Function checks if dosing inputs defined by
+% "INPUTS*" are only added to ODEs.
+%
+% USAGE:
+% ======
+% [output] = inputsonlyonstatesSBPOP(model) 
+%
+% model: SBmodel
+%
+% Output Arguments:
+% =================
+% output: =0: inputs not only on states (ODEs)
+%         =1: inputs only on states (ODEs) (or if no INPUT* definition
+%         exists in the model
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBmodel(model),
+    error('First input argument is not an SBmodel.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INITIALIZE OUTPUT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output = 1;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK RHSs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[statenames,ODEs] = SBstates(model);
+[varnames,varformulas] = SBvariables(model);
+[reacnames,reacformulas] = SBreactions(model);
+
+% 1) Check if "INPUT" defined in varformulas or reacformulas => error
+for k=1:length(varformulas),
+    if ~isempty(strfind(varformulas{k},'INPUT')),
+        output = 0; 
+    end
+end    
+for k=1:length(reacformulas),
+    if ~isempty(strfind(reacformulas{k},'INPUT')),
+        output = 0;
+    end
+end    
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/model/mergemoddosstructsSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/model/mergemoddosstructsSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..35268afc5794091879fbd2e63882c7688157ffcf
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/model/mergemoddosstructsSBPOP.m
@@ -0,0 +1,203 @@
+function [moddosinfo] = mergemoddosstructsSBPOP(modelinfo,dosing)
+% mergemoddosstructsSBPOP: Merge a modelinfo struct (returned by
+% basicmodelparsingSBPOP) with an SBPOPdosing object into a structure that
+% contains necessary information for both MONOLIX and NONMEM conversion and simulation
+% of the dosing scheme. 
+%
+% moddosinfo.model:             the model
+% moddosinfo.inputs.name:       input name
+% moddosinfo.inputs.factors:    cell-array with input factors
+% moddosinfo.inputs.terms:      cell-array with complete input string (for
+%                               simpler removing)
+% moddosinfo.inputs.stateindex: vector with stateindices to which the same
+%                               input is applied
+% moddosinfo.inputs.parindex:   index of the INPUT* parameter definition in
+%                               the SBmodel (used to remove it when
+%                               parameters are written to (e.g.) an MLXTRAN
+%                               file).   
+% moddosinfo.inputs.type:       type of the input
+% moddosinfo.inputs.time:       time point of the input (unused for
+%                               MLXTRAN conversion but for simulation)
+% moddosinfo.inputs.Tlag:       []: no lag, numeric: lag present with
+%                               given value. (=0: lag present with 0 as
+%                               initial value ... in case of
+%                               optimization)
+% moddosinfo.inputs.D:          dose information (unused for MLXTRAN
+%                               conversion but for simulation)
+% moddosinfo.inputs.parameters: additional parameters (input-type
+%                               dependent (Tinf, Tk0, ka) ... already
+%                               changed parameter names for after merging!
+% moddosinfo.inputs.notes:      input notes (unsused, except for
+%                               documentation)
+% moddosinfo.outputs.name:      output name
+% moddosinfo.outputs.formula:   output formula
+% moddosinfo.outputs.notes:     output notes
+% moddosinfo.outputs.varindex:  index of output in model variables
+% moddosinfo.param_est.name:    name of parameter to estimate (defined by
+%                               the identifier "<estimate>" in the
+%                               SBmodel)
+% moddosinfo.param_est.notes:   estimated parameter notes
+% moddosinfo.param_est.value0:  initial guess for parameter
+% moddosinfo.param_est.parindex: index of parameter in parameters
+% moddosinfo.param_reg.name:    name of regression parameter (defined by
+%                               the identifier "<regression>" in the
+%                               SBmodel) 
+% moddosinfo.param_reg.notes:   regression parameter notes
+% moddosinfo.param_reg.parindex: index of reg param in parameters
+% moddosinfo.param_reg.varindex: index of reg param in variables
+% moddosinfo.param_pk.name:     name of parameter to define in PK section
+%                               (this is MLXTRAN specific but might be
+%                               useful for other applications to).
+% moddosinfo.param_pk.value:    value of parameter
+% moddosinfo.param_pk.parindex: index or parameter in model
+% moddosinfo.param_pk.notes:    notes of the parameters
+%
+% Only very basic error handling is done. More intensive error checking is
+% done later, dependent on the tool that is going to be used for
+% pop-modelling (different features might be allowed).
+%
+% USAGE:
+% ======
+% [moddosinfo] = mergemoddosstructsSBPOP(modelinfo,dosing)
+%
+% modelinfo: modelinfo struct (returned by basicmodelparsingSBPOP)
+% dosing: SBPOPdosing object
+%
+% Output Arguments:
+% =================
+% moddosinfo: see structure definition above
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check inputs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBPOPdosing(dosing),
+    error('Second input argument is not an SBPOPdosing object.');
+end
+ds = struct(dosing);
+moddosinfo  = modelinfo; % assign output with modelinfo, then add input info
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% RUN THROUGH ALL MODEL INPUTS AND ADD INPUT RELATED INFORMATION TO moddosinfo
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(moddosinfo.inputs),
+    % find model input in dosing scheme (by comparing names)
+    index = strmatchSB(moddosinfo.inputs(k).name, {ds.inputs.name},'exact');
+    % if input name not found => error
+    % We keep this error for the moment. Technically it is not necessary
+    % ... but forces the modeler to be more consistent. If too restrictive
+    % then we can take the error away and just remove this input from the
+    % moddosinfo structure.
+    if isempty(index),
+        error('Input ''%s'' defined in the model but undefined in the SBPOPdosing scheme.',moddosinfo.inputs(k).name);
+    end
+    % add the dosing input definition from the SBPOPdosing object to the
+    % moddosinfo structure
+    moddosinfo.inputs(k).type = ds.inputs(index).type;
+    moddosinfo.inputs(k).time = ds.inputs(index).time;
+    moddosinfo.inputs(k).Tlag = ds.inputs(index).Tlag;
+    moddosinfo.inputs(k).D = ds.inputs(index).D;
+    moddosinfo.inputs(k).parameters = ds.inputs(index).parameters;
+    moddosinfo.inputs(k).TlagNotes = ds.inputs(index).TlagNotes;
+    moddosinfo.inputs(k).TlagName = ['Tlag' '_' lower(ds.inputs(index).name)];
+    moddosinfo.inputs(k).notes = ds.inputs(index).notes;
+    % update parameter name
+    if ~isempty(moddosinfo.inputs(k).parameters),
+        moddosinfo.inputs(k).parameters.name = [moddosinfo.inputs(k).parameters.name '_' lower(ds.inputs(index).name)];
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% RUN THROUGH ALL dosing parameters (ka, Tinf, Rate, Tk0) and check
+% if they are to be estimated or obtained from regression => add to
+% respective field in moddosinfo. 
+% If not estimate and not regression, then add to PK parameters, since to
+% be defined in the $PK section in MLXTRAN ... and also in NONMEM.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(moddosinfo.inputs),
+    nameinput = lower(moddosinfo.inputs(k).name);
+    if ~isempty(moddosinfo.inputs(k).parameters),
+        nameparam = [moddosinfo.inputs(k).parameters.name]; 
+        notesparam = moddosinfo.inputs(k).parameters.notes;
+        valueparam = moddosinfo.inputs(k).parameters.value;
+        % Check if to be estimated
+        if ~isempty(strfind(notesparam,'<estimate>')),
+            % Add to param_est
+            notesparam = strrep(notesparam,'<estimate>','');
+            moddosinfo.param_est(end+1).name = nameparam;
+            moddosinfo.param_est(end).notes = notesparam;
+            moddosinfo.param_est(end).value0 = valueparam;
+            moddosinfo.param_est(end).parindex = [];  % keep it empty, because yet unknown
+        elseif ~isempty(strfind(notesparam,'<regression>'))
+            % Add to param_reg
+            notesparam = strrep(notesparam,'<regression>','');
+            moddosinfo.param_reg(end+1).name = nameparam;
+            moddosinfo.param_reg(end).notes = notesparam;
+            moddosinfo.param_reg(end).parindex = [];  % keep it empty, because yet unknown            
+            moddosinfo.param_reg(end).varindex = [];  % keep it empty, because always empty
+        else
+            % Add to param_pk
+            moddosinfo.param_pk(end+1).name = nameparam;
+            moddosinfo.param_pk(end).notes = notesparam;
+            moddosinfo.param_pk(end).value = valueparam;             
+            moddosinfo.param_pk(end).parindex = [];  % keep it empty, because yet unknown 
+        end            
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% RUN THROUGH ALL Tlag parameters and check
+% if they are to be estimated or obtained from regression => add to
+% respective field in moddosinfo.
+% If not estimate and not regression, then add to PK parameters, since to
+% be defined in the $PK section in MLXTRAN ... and also in NONMEM.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(moddosinfo.inputs),
+    nameinput = lower(moddosinfo.inputs(k).name);
+    if ~isempty(moddosinfo.inputs(k).Tlag),
+        nameparam = moddosinfo.inputs(k).TlagName; 
+        notesparam = moddosinfo.inputs(k).TlagNotes;
+        valueparam = moddosinfo.inputs(k).Tlag;
+        % Check if to be estimated
+        if ~isempty(strfind(notesparam,'<estimate>')),
+            % Add to param_est
+            notesparam = strrep(notesparam,'<estimate>','');
+            moddosinfo.param_est(end+1).name = nameparam;
+            moddosinfo.param_est(end).notes = notesparam;
+            moddosinfo.param_est(end).value0 = valueparam;
+            moddosinfo.param_est(end).parindex = [];  % keep it empty, because yet unknown
+        elseif ~isempty(strfind(notesparam,'<regression>'))
+            % Add to param_reg
+            notesparam = strrep(notesparam,'<regression>','');
+            moddosinfo.param_reg(end+1).name = nameparam;
+            moddosinfo.param_reg(end).notes = notesparam;
+            moddosinfo.param_reg(end).parindex = [];  % keep it empty, because yet unknown            
+            moddosinfo.param_reg(end).varindex = [];  % keep it empty, because always empty
+        else
+            % Add to param_pk
+            moddosinfo.param_pk(end+1).name = nameparam;
+            moddosinfo.param_pk(end).notes = notesparam;
+            moddosinfo.param_pk(end).value = valueparam;             
+            moddosinfo.param_pk(end).parindex = [];  % keep it empty, because yet unknown 
+        end            
+    end
+end
+
+
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/SBPOPcreateMLXTRANfile.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/SBPOPcreateMLXTRANfile.m
new file mode 100644
index 0000000000000000000000000000000000000000..d518f8b9edc9fe98d292d7e07513f5b93995cf0f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/SBPOPcreateMLXTRANfile.m
@@ -0,0 +1,694 @@
+function [filename, moddosinfo] = SBPOPcreateMLXTRANfile(model,dosing,varargin)
+% SBPOPcreateMLXTRANfile: creates an MLXTRAN structural model file based on 
+% the SBmodel and the dosing information.
+% 
+% Regression parameters are taken directly from the model and IT IS IMPORTANT
+% that the regression parameters appear in the model in the same order as they
+% appear in the data file, used for fitting.
+%
+% USAGE:
+% ======
+% SBPOPcreateMLXTRANfile(model,dosing)
+% SBPOPcreateMLXTRANfile(model,dosing,filename)
+% SBPOPcreateMLXTRANfile(model,dosing,filename,SILENT)
+%
+% model: SBmodel (annotated with additional information, see above)
+% dosing: SBPOPdosing object (or empty [] if no input defined in model)
+% filename: Name of the created MLXTRAN file (or '' if undefined)
+% SILENT:   No output to command window during run if 1, otherwise 0 (default: 0)
+% 
+% DEFAULT VALUES:
+% ===============
+% filename: constructed from the model name "modelname_MLXTRAN".
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check minimum version of Monolix
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% try
+%     x = verLessThan('monolix','4.2.0');
+% catch
+%     x = NaN;
+% end
+% if  x==1,
+%     error('SBPOP requires Monolix version >= 4.2.0');
+% elseif isnan(x),
+%     warning('Please check your version of Monolix - it should be at least 4.2.0.');
+% end
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SOME CHECKS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBmodel(model),
+    error('First input argument is not an SBmodel.');
+end
+if isempty(dosing),
+    dosing = SBPOPdosing();
+end
+if ~isSBPOPdosing(dosing),
+    error('Second input argument is not an SBPOPdosing object.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% REPLACE "time" by "t" in the model (MLXTRAN uses t as time variable)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% first check that "t" is not a state, variable, parameter or reaction name
+sn = SBstates(model);
+pn = SBparameters(model);
+vn = SBvariables(model);
+rn = SBreactions(model);
+allelements = {sn{:} pn{:} vn{:} rn{:}};
+if ~isempty(strmatchSB('t',allelements,'exact')),
+    error('''t'' defined in the model, but MLXTRAN uses it as the time variable.');
+end
+model = replaceelementSB(model,'time','t');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET STRUCTURES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ms = struct(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+filename = [regexprep(ms.name,'\W','') '_MLXTRAN.txt'];
+if nargin >= 3,
+    if ~isempty(varargin{1}),
+        filename = varargin{1};
+        filename = strrep(filename,'.txt','');
+        filename = regexprep(filename,'\W','');
+        filename = [filename '_MLXTRAN.txt'];
+    end
+end
+
+SILENT = 0;
+if nargin == 4,
+    SILENT = varargin{2};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Start conversion protocol with important information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~SILENT,
+    fprintf('======================================================================\n');
+    fprintf('======================================================================\n');
+    fprintf('Conversion of model to MLXTRAN syntax.\n');
+    fprintf('Please read carefully the information below - it is important to\n');
+    fprintf('ensure correct use of the MLXTRAN model\n');
+    fprintf('==========================================================\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% BASIC MODEL PARSING AND MERGE WITH DOSING INFO
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modelinfo = basicmodelparsingSBPOP(model);
+moddosinfo = mergemoddosstructsSBPOP(modelinfo,dosing);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OPEN FILE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen(filename,'w');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INFO
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; MLXTRAN model, created using the SBPOP toolbox\r\n');
+fprintf(fid,'; Date: %s\r\n',date);
+fprintf(fid,'; By:   %s\r\n',usernameSBPOP());
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DESCRIPTION (name and notes)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% First line: model name 
+fprintf(fid,'; =============================================\r\n');
+fprintf(fid,'DESCRIPTION: %s\r\n',ms.name);
+fprintf(fid,'; =============================================\r\n');
+% Second (etc.) lines: model notes
+notes = ms.notes;
+% replace "\n" by "\r\n"
+notes = strrep(notes,sprintf('\r'),sprintf('\n'));
+notes = strrep(notes,sprintf('\n'),sprintf('\r\n'));
+% add "\t" in front of each line
+notes = strrep(notes,sprintf('\r\n'),sprintf('\r\n\t'));
+% write out notes
+fprintf(fid,'\t%s\r\n',notes);
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INPUT (parameters etc.)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; =============================================\r\n');
+fprintf(fid,'INPUT:\r\n');
+fprintf(fid,'; =============================================\r\n');
+% Parameters to be estimated are the parameters in the model, marked to be
+% estimated and additional parameters from the dosing scheme also marked for estimation.
+% These parameters are defined in the moddosinfo.param_est structure.
+% Add the parameter names for the parameters to be estimated
+fprintf(fid,'\tparameter = {');
+for k=1:length(moddosinfo.param_est)-1,
+    fprintf(fid,'%s, ',moddosinfo.param_est(k).name);
+end
+fprintf(fid,'%s}',moddosinfo.param_est(end).name);
+fprintf(fid,'\r\n');
+% Regression parameters (if defined)
+if ~isempty(moddosinfo.param_reg),
+    fprintf(fid,'\tregressor = {');
+    for k=1:length(moddosinfo.param_reg)-1,
+        fprintf(fid,'%s, ',moddosinfo.param_reg(k).name);
+    end
+    fprintf(fid,'%s}',moddosinfo.param_reg(end).name);
+    fprintf(fid,'\r\n');
+    % Warn the user:
+    if ~SILENT,
+        fprintf('\tRegression parameters present in model:\n');
+        fprintf('\t\tMake sure these parameters appear in the same order in\n');
+        fprintf('\t\tthe dataset as in the model!\n');
+        fprintf('\t=========================================================\n');
+    end
+end
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PK (input application information)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+warningInfusion = 0;
+if ~isempty(moddosinfo.inputs),
+    % write section identifier
+    fprintf(fid,'; =============================================\r\n');
+    fprintf(fid,'PK:\r\n');
+    fprintf(fid,'; =============================================\r\n');    
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % 1) Define the param_pk parameters that are not estimated, not 
+    %    obtained as regression parameters
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % These parameters are dosing type dependent parameters and model
+    % parameters that appear in the pre-factor of the input definitions
+    % Need to define all but Tinf and Rate parameter (defined in dataset)
+    warningMultipledosings = 0;
+    for k=1:length(moddosinfo.param_pk),
+        if isempty(strfind(moddosinfo.param_pk(k).name,'Rate_')) && isempty(strfind(moddosinfo.param_pk(k).name,'Tinf_')),
+            if length(moddosinfo.param_pk(k).value) > 1 && ~warningMultipledosings,
+                if ~SILENT,
+                    fprintf('\tMultiple dosings present:\n');
+                    fprintf('\t\tIt is assumed that each ka and Tk0 value that might be\n');
+                    fprintf('\t\tdefined in the SBPOPdosing is equal for all events!\n');
+                    fprintf('\t==========================================================\n');
+                end
+                warningMultipledosings = 1;
+            end
+            if ~isempty(moddosinfo.param_pk(k).notes),
+                fprintf(fid,'\t%s = %g',moddosinfo.param_pk(k).name,moddosinfo.param_pk(k).value(1));
+                fprintf(fid,'\t; %s\r\n',moddosinfo.param_pk(k).notes);
+            else
+                fprintf(fid,'\t%s = %g\r\n',moddosinfo.param_pk(k).name,moddosinfo.param_pk(k).value(1));
+            end
+        end
+    end    
+
+    % Collect information about input fraction definitions etc
+    Xinfo = [];
+    Xinfo.stateindex = [];
+    Xinfo.INPUT_NUMBER = [];
+    Xinfo.factors = {};
+    
+    for k=1:length(moddosinfo.inputs),
+        stateindex = [moddosinfo.inputs(k).stateindex];
+        factors = moddosinfo.inputs(k).factors;
+        % Get input number for comparison with "INPUT" dataset column
+        INPUT_NUMBER = str2double(strrep(moddosinfo.inputs(k).name,'INPUT',''));
+        % Check if partial application into different compartments =>
+        % we do not allow that!
+        if length(stateindex) ~= 1,
+            error('Partial application of a dose into different compartments not supported yet by the MLXTRAN conversion.');
+        end
+        
+        Xinfo.stateindex(end+1) = stateindex(1);
+        Xinfo.INPUT_NUMBER(end+1) = INPUT_NUMBER;
+        Xinfo.factors{end+1} = factors{1};
+    end
+    % Write out one "compartment" statement for each compartment in which doses are administered.
+    % use "amount", since everything else is taken care of by the equations in the model.
+    compstateindices = unique(Xinfo.stateindex);
+    admInfo_compIx = [];
+    admInfo_stateIndex = [];
+    for k=1:length(compstateindices),
+        fprintf(fid,'\tcompartment(cmt=%d, amount=%s)\r\n',k,ms.states(compstateindices(k)).name);
+        admInfo_compIx(end+1) = k;
+        admInfo_stateIndex(end+1) = compstateindices(k);
+    end
+    % Write out dosing type and additional information
+    for k=1:length(moddosinfo.inputs),
+        STATE_NUMBER = moddosinfo.inputs(k).stateindex;
+        % adm: number of input
+        INPUT_NUMBER = eval(strrep(moddosinfo.inputs(k).name,'INPUT',''));
+        % cmt number
+        CMT_NUMBER = admInfo_compIx(admInfo_stateIndex==STATE_NUMBER);
+        % Fraction
+        FRACTION = moddosinfo.inputs(k).factors{1};
+        % Tlag
+        TLAGNAME = '';
+        if ~isempty(moddosinfo.inputs(k).Tlag),
+            TLAGNAME = moddosinfo.inputs(k).TlagName;
+        end
+        
+        % Handle infusion
+        if strcmp(moddosinfo.inputs(k).type,'INFUSION'),
+            fprintf(fid,'\tiv(adm=%d, cmt=%d, p=%s',INPUT_NUMBER,CMT_NUMBER,FRACTION);
+            if isempty(TLAGNAME),
+                fprintf(fid,')\r\n');
+            else
+                fprintf(fid,', Tlag=%s)\r\n',TLAGNAME);
+            end
+            if ~warningInfusion,
+                % Warn the user:
+                if ~SILENT,
+                    fprintf('\tInfusion administration present in model:\n');
+                    fprintf('\t\tMake sure you have a TINF or RATE column in your dataset!\n');
+                    fprintf('\t==========================================================\n');
+                end
+                warningInfusion = 1;
+            end
+        end
+        
+        % Handle 1st order absorption
+        if strcmp(moddosinfo.inputs(k).type,'ABSORPTION1'),
+            KA_PARAMETER = moddosinfo.inputs(k).parameters.name;
+            fprintf(fid,'\tabsorption(adm=%d, cmt=%d, ka=%s, p=%s',INPUT_NUMBER,CMT_NUMBER,KA_PARAMETER,FRACTION);
+            if isempty(TLAGNAME),
+                fprintf(fid,')\r\n');
+            else
+                fprintf(fid,', Tlag=%s)\r\n',TLAGNAME);
+            end
+        end
+        
+        % Handle 0 order absorption
+        if strcmp(moddosinfo.inputs(k).type,'ABSORPTION0'),
+            TK0_PARAMETER = moddosinfo.inputs(k).parameters.name;
+            fprintf(fid,'\tabsorption(adm=%d, cmt=%d, Tk0=%s, p=%s',INPUT_NUMBER,CMT_NUMBER,TK0_PARAMETER,FRACTION);
+            if isempty(TLAGNAME),
+                fprintf(fid,')\r\n');
+            else
+                fprintf(fid,', Tlag=%s)\r\n',TLAGNAME);
+            end
+        end
+        
+        % Handle bolus
+        if strcmp(moddosinfo.inputs(k).type,'BOLUS'),
+            fprintf(fid,'\tiv(adm=%d, cmt=%d, p=%s',INPUT_NUMBER,CMT_NUMBER,FRACTION);
+            if isempty(TLAGNAME),
+                fprintf(fid,')\r\n');
+            else
+                fprintf(fid,', Tlag=%s)\r\n',TLAGNAME);
+            end
+        end
+        
+    end
+    fprintf(fid,'\r\n');
+end
+% Warn the user:
+try
+    if length(unique(Xinfo.INPUT_NUMBER)) > 1,
+        if ~SILENT,
+            fprintf('\tYou have multiple inputs into your model:\n');
+            fprintf('\t\tMake sure you have an "ADM" column in your dataset!\n');
+            fprintf('\t\tFor each dosing record the entry in this column should\n');
+            fprintf('\t\tcorrespond to the number of the input of this dose.\n');
+            fprintf('\t==========================================================\n');
+        end
+    end
+catch
+    % No input available ...
+end
+        
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EQUATION (define the ODEs, help variables, initial conditions, initial time)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% write section identifier
+fprintf(fid,'; =============================================\r\n');
+fprintf(fid,'EQUATION:\r\n');
+fprintf(fid,'; =============================================\r\n');
+
+fprintf(fid,'\r\n\t; Always use stiff solver');
+fprintf(fid,'\r\n\t; -----------------------\r\n');
+fprintf(fid,'\todeType = stiff\r\n\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% define the parameters that are not going to be estimated
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% write out all parameter definitions but NEGLECT the following ones:
+%   - parameters to be estimated
+%   - parameters defined as regression parameters
+%   - parameters defined in the PK section (used in input factor terms)
+%   - parameters defining the nominal (0) inputs: INPUT* *=1,2,3,4,...
+%   - consider ONLY model parameters. All dosing specific parameters need
+%     to be handled in the $PK section.
+% All model parameters:
+[pn, pv] = SBparameters(moddosinfo.model);
+% Remove INPUT*
+removeindex = strmatchSB('INPUT',pn);
+keepindex = setdiff([1:length(pn)],removeindex);
+pn = pn(keepindex);
+pv = pv(keepindex);
+% Remove the estimated parameters
+removeindex = [];
+pn_est = {moddosinfo.param_est.name};
+for k=1:length(pn_est),
+    removeindex = [removeindex strmatchSB(pn_est{k},pn,'exact')];
+end
+keepindex = setdiff([1:length(pn)],removeindex);
+pn = pn(keepindex);
+pv = pv(keepindex);
+% Remove the regression parameters
+removeindex = [];
+pn_reg = {moddosinfo.param_reg.name};
+for k=1:length(pn_reg),
+    removeindex = [removeindex strmatchSB(pn_reg{k},pn,'exact')];
+end
+keepindex = setdiff([1:length(pn)],removeindex);
+pn = pn(keepindex);
+pv = pv(keepindex);
+% Remove the PK parameters
+removeindex = [];
+pn_pk = {moddosinfo.param_pk.name};
+for k=1:length(pn_pk),
+    removeindex = [removeindex strmatchSB(pn_pk{k},pn,'exact')];
+end
+keepindex = setdiff([1:length(pn)],removeindex);
+pn = pn(keepindex);
+pv = pv(keepindex);
+% Get the parameter notes from the model
+pnotes = {};
+ms = struct(moddosinfo.model);
+for k=1:length(pn),
+    index = strmatchSB(pn{k},{ms.parameters.name},'exact');
+    pnotes{end+1} = ms.parameters(index).notes;
+end
+% Write out the parameters
+if ~isempty(pn),
+    fprintf(fid,'\t; Model parameters\r\n');
+    fprintf(fid,'\t; ----------------\r\n');
+    for k=1:length(pn),
+        if ~isempty(pnotes{k}),
+            fprintf(fid,'\t%s = %g',pn{k},pv(k));
+            fprintf(fid,'\t; %s\r\n',pnotes{k});
+        else
+            fprintf(fid,'\t%s = %g\r\n',pn{k},pv(k));
+        end
+    end
+    fprintf(fid,'\r\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% define the auxiliary variables (model variables)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% write out variables but neglect the following ones:
+%   - output definitions
+%   - regression parameters as variables
+allvarindices = [1:length(ms.variables)];
+% remove output variables
+outputvarindices = [moddosinfo.outputs.varindex];
+varindices = setdiff(allvarindices,outputvarindices);
+% remove regression parameters implemented as variables in the SBmodel
+if ~isempty(moddosinfo.param_reg),
+    regparvarindices = [moddosinfo.param_reg.varindex];
+    varindices = setdiff(varindices,regparvarindices);
+end
+% Write out the variables
+if ~isempty(varindices),
+    fprintf(fid,'\t; Model variables\r\n');
+    fprintf(fid,'\t; ---------------\r\n');    
+    for k=1:length(varindices),
+        % check if variable contains a piecewise construct
+        if isempty(strfind(ms.variables(varindices(k)).formula,'piecewiseSB')),
+            % no piecewise contruct present in formula
+            if ~isempty(ms.variables(varindices(k)).notes),
+                fprintf(fid,'\t%s = %s',ms.variables(varindices(k)).name,ms.variables(varindices(k)).formula);
+                fprintf(fid,'; %s\r\n',ms.variables(varindices(k)).notes);
+            else
+                fprintf(fid,'\t%s = %s\r\n',ms.variables(varindices(k)).name,ms.variables(varindices(k)).formula);
+            end
+        else
+            % piecewise contruct present in formula
+            piecewiseText = handlepiecewise4mlxtran(ms.variables(varindices(k)).name,ms.variables(varindices(k)).formula);
+            if ~isempty(ms.variables(varindices(k)).notes),
+                fprintf(fid,'\t%s',piecewiseText);
+                fprintf(fid,'; %s\r\n',ms.variables(varindices(k)).notes);
+            else
+                fprintf(fid,'\t%s\r\n',piecewiseText);
+            end
+        end
+    end
+    fprintf(fid,'\r\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Do not define initial time (undefined, means that integrator starts at first event in dataset for each individual)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% initial conditions (only define them if they are non-zero)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% We need to add "_0" to the state names in the assignments
+ictext = '';
+for k=1:length(ms.states),
+    % In IC string if regression variables are used these need "_0" at the end.
+    % If IC defined by a variable that itself is defined by a regression variable then there will be an error --- not caught yet!
+    ICstring = getICstring(ms,k,{moddosinfo.param_reg.name}); % We need to add "_0" to the state names in the assignments
+    ictext = sprintf('%s%s_0 = %s\r\n\t',ictext,ms.states(k).name,ICstring);
+end
+if ~isempty(ictext),
+    fprintf(fid,'\t; Initial conditions\r\n\t;------------------\r\n\t%s',ictext);
+    fprintf(fid,'\r\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% define the reactions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(ms.reactions),
+    fprintf(fid,'\t; Model reactions\r\n');
+    fprintf(fid,'\t; ---------------\r\n');    
+    for k=1:length(ms.reactions),
+        % check if reaction contains a piecewise construct
+        if isempty(strfind(ms.reactions(k).formula,'piecewiseSB')),
+            % no piecewise contruct present in formula
+            if ~isempty(ms.reactions(k).notes),
+                fprintf(fid,'\t%s = %s',ms.reactions(k).name,ms.reactions(k).formula);
+                fprintf(fid,'\t; %s\r\n',ms.reactions(k).notes);
+            else
+                fprintf(fid,'\t%s = %s\r\n',ms.reactions(k).name,ms.reactions(k).formula);
+            end
+        else
+            % piecewise contruct present in formula
+            piecewiseText = handlepiecewise4mlxtran(ms.reactions(k).name,ms.reactions(k).formula);
+            if ~isempty(ms.reactions(k).notes),
+                fprintf(fid,'\t%s',piecewiseText);
+                fprintf(fid,'\t; %s\r\n',ms.reactions(k).notes);
+            else
+                fprintf(fid,'\t%s\r\n',piecewiseText);
+            end
+        end            
+    end
+    fprintf(fid,'\r\n');    
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% define the differential equations (remove the input terms)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'\t; Differential equations\r\n');
+fprintf(fid,'\t; ----------------------\r\n');
+for k=1:length(ms.states),
+    ODE = ms.states(k).ODE;
+    % remove input terms (do this already general for several inputs)
+    for k2 = 1:length(moddosinfo.inputs),
+        % check if current input exists in current (k-th) ODE:
+        index = find(moddosinfo.inputs(k2).stateindex == k);
+        if ~isempty(index),
+            % the input term to replace is:
+            termreplace = moddosinfo.inputs(k2).terms{index};
+            ODE = strrep(ODE,termreplace,'');
+        end
+    end
+    % write out the ODE
+    fprintf(fid,'\tddt_%s = %s\r\n',ms.states(k).name,ODE);
+end
+% final line break
+fprintf(fid,'\r\n');
+ 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OUTPUT (all the outputs and expressions, defined in the model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% write section identifier
+fprintf(fid,'; =============================================\r\n');
+fprintf(fid,'OUTPUT:\r\n');
+fprintf(fid,'; =============================================\r\n');
+fprintf(fid,'\toutput = {');
+for k=1:length(moddosinfo.outputs)-1,
+    fprintf(fid,'%s, ',moddosinfo.outputs(k).formula);
+end
+fprintf(fid,'%s}',moddosinfo.outputs(end).formula);
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CLOSE FILE AND RETURN
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fclose(fid);
+return
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get IC string
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [ICstring] = getICstring(ms,k,regressionvariables)
+IC = ms.states(k).initialCondition;
+% If numeric, then convert to string and return
+if isnumeric(IC),
+    ICstring = num2str(ms.states(k).initialCondition,20);
+    return
+end
+% If not numeric then need to add "_0" to all state names in the equation
+states = {ms.states.name};
+for k2=1:length(states),
+    findstates{k2} = ['\<' states{k2} '\>'];
+    replstates{k2} = [states{k2} '_0'];
+end
+ICstring = regexprep(IC,findstates,replstates);
+% And add "_0" to all regression parameters in the equation
+findregression = {};
+replregression = {};
+for k2=1:length(regressionvariables),
+    findregression{k2} = ['\<' regressionvariables{k2} '\>'];
+    replregression{k2} = [regressionvariables{k2} '_0'];
+end
+ICstring = regexprep(ICstring,findregression,replregression);
+return
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE PIECEWISE EXPRESSIONS => if elseif else end
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [changedformula] = handlepiecewise4mlxtran(name,formula)
+formula = strtrim(formula);
+% 1) Check that only a single piecewise expression 
+index = strfind(formula,'piecewiseSB');
+if length(index) > 1,
+    error('More than one piecewise expression in formula ''%s''. Only one is allowed.',formula);
+end
+% 2) Get the piecewise expression
+pwformula = strtrim(formula(index:end));
+offset = length('piecewiseSB(')+1;
+po = 1;
+while po~=0,
+    if pwformula(offset) == '(',
+        po = po+1;
+    end
+    if pwformula(offset) == ')',
+        po = po-1;
+    end
+    offset = offset+1;
+end
+pwformula = pwformula(1:offset-1);
+% 3) Check length pwformula against formula. If not same => error, since
+% then additional terms are present in the formula.
+if length(formula) ~= length(pwformula),
+    error('Formula ''%s'' contains more than a simple piecewise expression.',formula);
+end
+% 4) Get elements of pw expression
+elements = explodePCSB(pwformula(13:end-1));
+% 5) parse and convert the trigger expressions
+for k=2:2:length(elements),
+    elements{k} = convertlogicalrelationalexpressions(elements{k});
+end
+% 6) check if an else is present
+n = length(elements);
+if n/2 == floor(n/2),
+    elsepresent = 0;
+else
+    elsepresent = 1;
+end
+% 6) construct the if elseif else text
+if elsepresent,
+    elseelement = elements{end};
+    elements = elements(1:end-1);
+end
+% if 
+text = sprintf('if (%s)\r\n\t%s = %s\r\n',elements{2},name,elements{1});
+% elseif
+if length(elements) > 2,
+    for k=4:2:length(elements),
+        text = sprintf('%selseif (%s)\r\n\t%s = %s\r\n',text,elements{k},name,elements{k-1});        
+    end
+end
+% else
+if elsepresent,
+    text = sprintf('%selse\r\n\t%s = %s\r\n',text,name,elseelement);
+end
+% end
+text = sprintf('%send',text);
+% done
+changedformula = text;
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PARSE AND CONVERT LOGICAL AND RELATIONAL OPERATORS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% the syntax of MLXTRAN only allows two elements for each and, or, ...
+% and(gt(time,5),lt(time,10)) => (time.gt.5).and.(time.lt.10)
+function [exp] = convertlogicalrelationalexpressions(exp)
+operatorsfind = {'and','or','andSB','orSB','lt','gt','le','ge','eq','ne'};
+operatorsuse  = {' & ',' | ',' & ',' | ',' < ',' > ',' <= ',' >= ',' == ',' != '};
+exp = ['#' exp '#'];
+for k=1:length(operatorsfind),
+    index = regexp(exp,['\W' operatorsfind{k} '\W']);
+    if ~isempty(index),
+        % get pre text
+        exppre = exp(1:index);
+        % get post text and arguments
+        temp = exp(index+1+length(operatorsfind{k})+1:end);
+        po = 1;
+        offset = 1;
+        while po~= 0,
+            if temp(offset) == '(',
+                po = po+1;
+            end
+            if temp(offset) == ')',
+                po = po-1;
+            end
+            offset = offset + 1;
+        end
+        args = explodePCSB(temp(1:offset-2));
+        if length(args) > 2,
+            error('Only two arguments allowed in an ''andSB'' or ''orSB'' when converting piecewiseSB to MLXTRAN.');
+        end
+        exppost = temp(offset:end);
+        % get args
+        exp = [exppre '(' args{1} ')' operatorsuse{k} '(' args{2} ')'   exppost];
+    end
+end
+exp = exp(2:end-1);
+return
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/SBPOPcreateMONOLIXproject.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/SBPOPcreateMONOLIXproject.m
new file mode 100644
index 0000000000000000000000000000000000000000..cd254765c522699e491e51b56b157be28bae4e05
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/SBPOPcreateMONOLIXproject.m
@@ -0,0 +1,1111 @@
+function SBPOPcreateMONOLIXproject(model,dosing,data,projectPath,varargin)
+% SBPOPcreateMONOLIXproject: creates a Monolix/MLXTRAN project from an SBmodel and
+% an SBPOPdosing scheme. Some additional information is needed, which is also passed.
+%
+% This function allows also robustness analysis:
+% If in option Ntest is defined different from 1 then not a single but
+% Ntest models are generated with randomly chosen initial guesses for the
+% fixed effects. These models are then stored in folders in the
+% "projectPath" folder. 
+%
+% ASSUMPTIONS:
+% ============
+% - Always log transformed continuous covariates (centered by the median)
+% - Always untransformed categorical covariates
+% - FIM: always by computed by linearization
+% - Individual parameters are always determined by conditional modes, 
+% - Use Monolix default graphics settings
+% - Correlation IIV parameters always 0 at initial guess
+%
+% WHAT COULD BE ADDED:
+% ====================
+% - Categorical data (easy to do - separate simulation from monolix file generation)
+%       PROB(Y<=1) = k1*Cc
+%       PROB(Y<=2) = k1*Cc+k2+Cc
+%       PROB(Y<=3) = k1*Cc+k2*Cc+k3*Cc
+%       OUTPUT2    = Y
+% - Mixture models (latent covariates)
+% - IOV
+% - Additional algorithm settings
+% - Covariates on random effects
+%
+% USAGE:
+% ======
+% SBPOPcreateMONOLIXproject(model,dosing,data,projectPath)
+% SBPOPcreateMONOLIXproject(model,dosing,data,projectPath,options)
+% SBPOPcreateMONOLIXproject(model,dosing,data,projectPath,options,parameterOrder)
+%
+% parameterOrder: Used to reorder parameters (used by the popPK workflow, do not use otherwise)
+%
+% model:        SBmodel (annotated with additional information for MLXTRAN conversion)
+%
+% dosing:       SBPOPdosing object (or empty [] if no input defined in model)
+%
+% data:         Structure with following fields:
+%       data.dataRelPathFromProject:    path to data file
+%       data.dataFileName:              data file filename
+%       data.dataHeaderIdent:           String with datafile header Monolix identifiers (example: 'ID,TIME,Y,MDV,EVID,AMT,TINF,ADM,YTYPE,COV,COV,CAT')
+%
+% projectPath:  String with the path/foldername to which the project files are to be written (example: 'FIT_01' or 'Models/FITS/FIT_01')
+%
+% options:      Structure with following fields (all optional with default settings):
+%       options.POPestimate:            Vector with 0 and 1 entries. 1 if pop parameter is estimated, 0 if not. Default or []: => all are estimated
+%       options.POPvalues0:             Vector with pop parameter initial values. Default or []: => values stored in model and dosing scheme
+%
+%       options.IIVdistribution:        Cell-array with information about parameter distribution. L (lognormal), N (normal), G (logit)
+%                                       Example: {'L' 'L' 'L' 'L' 'N' 'L' 'L' 'L'}. Default or {}: => use lognormal for all
+%       options.IIVestimate:            Vector with 0 and 1 entries. 1 if random effect is estimated, 0 if not. Default or []: => all are estimated
+%                                       0: IIV not estimated (IIVvalues0 not used) 
+%                                       1: IIV estimated (IIVvalues0 as starting guesses)
+%                                       2: IIV not estimated but fixed on IIVvalues0 value
+%       options.IIVvalues0:             Vector with random effect parameter
+%                                       initial values. Default or []: => all set to 0.5
+%                                       If IIV not estimated then defined initial guess not used but replaced by 0
+%
+%       options.errorModels:            String with definition of residual error models, comma separated for each output.
+%                                       Possible values: const,prop,comb1. Example: 'comb1,prop', Default or '': => const for all outputs
+%
+%       options.errorParam0:            Vector allowing to pass initial guesses for error model parameters. Same order as error models. 
+%                                       'const': a, 'prop': b, 'comb1': a,b
+%
+%       options.covarianceModel:        Definition of covariance model. String with cell-array text inside, grouping the parameters to consider having 
+%                                       correlated random effects. Example: '{CL,Vc},{Q,Vp,KM}'. Default: 'diagonal'
+%
+%       options.covariateModel:         Definition of covariate model. Cell-array. Each element is a sub-cell-array. First element in sub-cell-array is the 
+%                                       parameter to which to add the covariate, all following elements define the covariates as named in the dataset.
+%                                       Example: '{CL,BMI0}, {Fsubcut,WT0}, {Vc,SEX,BMI0}'. Default: '' => no covariates
+%                                       By default (and so far not changeable, the continuous covariates are all weighted by their median, determined from the dataset)
+%       options.covariateModelValues:   Definition of covariate coefficients for the selected covariate model. 
+%                                       Syntax is similar to options.covariateModel. It is a cell-array containing vectors instead of cell-arrays.
+%                                       Each vector contains values for the covariate coefficients, matching the covariateModel definition order.
+%                                       Example: if options.covariateModel = '{CL,BMI0,AGE0}, {Fsubcut,WT0}, {Vc,SEX,BMI0}'
+%                                       Then: options.covariateModelValues = {[0.5,0], [0.75], [0,0]}
+%                                       Defines the initial guesses for the covariate coefficients for BMI0 on CL to be 0.5, WT0 on Fsubcut to be 0.75, and the other ones are 0.
+%                                       If not defined, all covariate coefficients start from 0 in the estimation.
+%       options.COVestimate:            Same structure as options.covariateModelValues but with entries 0 or 1. 0 means not estimated, 1 means estimated.
+%                                       By default all are estimated.
+%                                       In the example above options.COVestimate = {[0,1], [1], [1,0]}   will estimate AE0 on CL, WT0 on Fsubcut, SEX on Vc.
+%                                       The other coefficients will be kept fixed.
+%       options.COVcentering.covs:      Cell-array with covariates that should be centered around a custom value. 
+%       options.COVcentering.values:    Vector with centering values. 
+%
+%       options.Ntests:                 Doing robustness analysis - number of models to generate with different initial guesses (randomly generated based on POPvalues0)
+%                                       Default: 1 (no robustness analysis, using initial guesses as provided)
+%       options.std_noise_setting:      Standard deviation to use to add noise to the initial parameter guesses (default=0.5 (50%CV))
+%                                       Normal:         Parameter_guess + std_noise_setting*Parameter_guess*randomNumbers(0-1)
+%                                       Lognormal:      Parameter_guess * exp(std_noise_setting*randomNumbers(0-1))
+%                                       Logitnormal:    Similar and between 0-1
+%
+%       options.algorithm.SEED:         Seed setting. Defualt: 123456
+%       options.algorithm.K1:           First iterations. Default: 500
+%       options.algorithm.K2:           Final iterations. Default: 200
+%       options.algorithm.K1_AUTO:      Automatic first iteration number (0: off, 1: on). Default: 0
+%       options.algorithm.K2_AUTO:      Automatic final iteration number (0: off, 1: on). Default: 0
+%       options.algorithm.NRCHAINS:     Number of parallel chains. Default: 1
+%       options.algorithm.LLsetting:    'linearization' (default) or 'importantsampling'
+%       options.algorithm.FIMsetting:   'linearization' (default) or 'stochasticApproximation'
+%       options.algorithm.INDIVparametersetting: 'conditionalMode' (default) ... others not considered for now. 
+%
+%       options.SILENT:                 =0: do some output in the command window, =1: do no output in command window (default: 0)
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check minimum version of Monolix
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% try
+%     x = verLessThan('monolix','4.2.0');
+% catch
+%     x = NaN;
+% end
+% if  x==1,
+%     error('SBPOP requires Monolix version >= 4.2.0');
+% elseif isnan(x),
+%     warning('Please check your version of Monolix - it should be at least 4.2.0.');
+% end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define Default Properties (Never changing)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+projectName            = 'project';
+resultsFolder          = 'RESULTS';
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBmodel(model),
+    error('First input argument is not an SBmodel.');
+end
+if ~isSBPOPdosing(dosing) && ~isempty(dosing),
+    error('Second input argument is not an SBPOPdosing scheme.');
+end
+try
+    dataRelPathFromProject = data.dataRelPathFromProject;
+    dataFileName           = data.dataFileName;
+    dataHeaderIdent        = data.dataHeaderIdent;
+    
+    % Removal of TIMEPOS in dataHeaderIdent
+    % TIMEPOS only needed for NONMEM ...
+    dataHeaderIdent         = regexprep(dataHeaderIdent,'\<TIMEPOS\>','IGNORE');
+catch
+    error('data input argument not defined correctly.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+options = [];
+parameterOrder = {};
+if nargin==5,
+    options = varargin{1};
+    parameterOrder = {};
+elseif nargin==6,
+    options = varargin{1};
+    parameterOrder = varargin{2};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle optional arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try POPestimate                     = options.POPestimate;              catch, POPestimate = [];                             end
+try POPvalues0                      = options.POPvalues0;               catch, POPvalues0 = [];                              end
+try IIVdistribution                 = options.IIVdistribution;          catch, IIVdistribution = {};                         end
+try IIVestimate                     = options.IIVestimate;              catch, IIVestimate = [];                             end
+try IIVvalues0                      = options.IIVvalues0;               catch, IIVvalues0 = [];                              end
+try errorModels                     = options.errorModels;              catch, errorModels = '';                             end
+try errorParam0                     = options.errorParam0;              catch, errorParam0 = [];                             end
+try covarianceModel                 = options.covarianceModel;          catch, covarianceModel = 'diagonal';                 end
+try covariateModel                  = options.covariateModel;           catch, covariateModel = '';                          end
+try covariateModelValues            = options.covariateModelValues;     catch, covariateModelValues = {};                    end
+try COVestimate                     = options.COVestimate;              catch, COVestimate = {};                             end
+
+try COVcentering_covs               = options.COVcentering.covs;        catch, COVcentering_covs = {};                       end
+try COVcentering_values             = options.COVcentering.values;      catch, COVcentering_values = [];                     end
+
+try SEED                            = options.algorithm.SEED;           catch, SEED = 123456;                                end
+try K1                              = options.algorithm.K1;             catch, K1 = 500;                                     end
+try K2                              = options.algorithm.K2;             catch, K2 = 200;                                     end
+try K1_AUTO                         = options.algorithm.K1_AUTO;        catch, K1_AUTO = 0;                                  end
+try K2_AUTO                         = options.algorithm.K2_AUTO;        catch, K2_AUTO = 0;                                  end
+try NRCHAINS                        = options.algorithm.NRCHAINS;       catch, NRCHAINS = 1;                                 end
+try SILENT                          = options.SILENT;                   catch, SILENT = 0;                                   end
+try INDIVparametersetting           = options.algorithm.INDIVparametersetting;    catch, INDIVparametersetting = 'conditionalMode';    end
+try LLsetting                       = options.algorithm.LLsetting;      catch, LLsetting = 'linearization';                  end
+try FIMsetting                      = options.algorithm.FIMsetting;     catch, FIMsetting = 'linearization';                 end
+try keepProjectFolder               = options.keepProjectFolder;                catch, keepProjectFolder = 0;                        end   
+
+try Ntests                          = options.Ntests;                           catch, Ntests = 1;                                    end
+try std_noise_setting               = options.std_noise_setting;                catch, options.std_noise_setting = 0.5;               end
+std_noise_setting                   = options.std_noise_setting;
+
+
+if ~iscell(COVcentering_covs),
+    COVcentering_covs = {COVcentering_covs};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle first the case with robustness analysis
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if Ntests>1,
+    % Robustness analysis desired
+    % Check if POPvalues0 and POPestimate defined
+    if isempty(POPestimate) || isempty(POPvalues0),
+        error('When doing robustness analysis, please define options.POPvalues0 and options.POPestimate!');
+    end
+    
+    % Define IIVdistribution if still empty (default: all 'L')
+    if isempty(IIVdistribution),
+        for k=1:length(POPvalues0),
+            IIVdistribution{k} = 'L';
+        end
+    end
+    
+    % Sample Ntests new POPvalues0 for the ones that are estimated using
+    % std_noise_setting as standard deviation
+    
+    % Allocating variable
+    POPvalues0_sampled                          = POPvalues0(ones(1,Ntests),:);
+    
+    % Sampling normally distributed (IIV) parameters - which are also estimated on a population level
+    ix_normal_sampled                           = find(strcmp(IIVdistribution,'N').*POPestimate);
+    POPvalues0_sampled(:,ix_normal_sampled)     = POPvalues0(ones(1,Ntests),ix_normal_sampled) + std_noise_setting*POPvalues0(ones(1,Ntests),ix_normal_sampled).*randn(Ntests,length(ix_normal_sampled));
+
+    % Sampling log normally distributed (IIV) parameters - which are also estimated on a population level
+    ix_lognormal_sampled                        = find(strcmp(IIVdistribution,'L').*POPestimate);
+    MU                                          = log(POPvalues0(ones(1,Ntests),ix_lognormal_sampled));
+    XXX                                         = MU + std_noise_setting.*randn(Ntests,length(ix_lognormal_sampled));
+    POPvalues0_sampled(:,ix_lognormal_sampled)  = exp(XXX);
+    
+    % Sampling logit normally distributed parameters - which are also estimated on a population level
+    ix_logitnormal_sampled                          = find(strcmp(IIVdistribution,'G').*POPestimate);
+    MU                                              = log(POPvalues0(ones(1,Ntests),ix_logitnormal_sampled)./(1-POPvalues0(ones(1,Ntests),ix_logitnormal_sampled)));
+    XXX                                             = MU + std_noise_setting.*randn(Ntests,length(ix_logitnormal_sampled));
+    POPvalues0_sampled(:,ix_logitnormal_sampled)    = exp(XXX)./(1+exp(XXX));
+    
+    % Clean folder
+    try rmdir(projectPath,'s'); catch, end
+    
+    % Create Ntests different models in the projectPath/MODEL_01/02, ... folders
+    for k=1:Ntests,
+        % Setup new project creation stuff
+        modelK                          = model;
+        dosingK                         = dosing;
+        dataK                           = data;
+        dataK.dataRelPathFromProject    = ['../' data.dataRelPathFromProject];
+        projectPathK                    = [projectPath sprintf('/MODEL_%s',preFillCharSB(k,length(num2str(Ntests)),'0'))];
+        optionsK                        = options;
+        optionsK                        = rmfield(optionsK,'Ntests');
+        optionsK                        = rmfield(optionsK,'std_noise_setting');
+        optionsK.POPvalues0             = POPvalues0_sampled(k,:);
+        SBPOPcreateMONOLIXproject(modelK,dosingK,dataK,projectPathK,optionsK)
+    end
+    
+    % Ready, return
+    return
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Convert covariate model into different syntax
+% '{CL,BMI0}, {Fsubcut,WT0}, {Vc,SEX,BMI0}'
+% to
+% {{'CL','BMI0'}, {'Fsubcut','WT0'}, {'Vc','SEX','BMI0'}}
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(covariateModel),
+    terms = explodePCSB(covariateModel,',','{','}');
+    y = {};
+    for k=1:length(terms),
+        x = strtrim(terms{k});
+        x = strrep(x,'{','{''');
+        x = strrep(x,'}','''}');
+        x = strrep(x,',',''',''');
+        y{k} = eval(x);
+    end
+    covariateModel = y;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check covariateModelValues
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(covariateModel) && ~isempty(covariateModelValues),
+    error('If you define covariateModelValues, you also need to define the covariateModel.');
+end
+
+if isempty(covariateModelValues),
+    % Determine default covariateModelValues
+    covariateModelValues = {};
+    for k=1:length(covariateModel),
+        covariateModelValues{k} = zeros(1,length(covariateModel{k})-1);
+    end
+else
+    % Check correct length of covariateModelValues elements
+    if length(covariateModel) ~= length(covariateModelValues),
+        error('Number of elements in covariateModel and covariateModelValues needs to match.');
+    end
+    for k=1:length(covariateModel),
+        if length(covariateModel{k})-1 ~= length(covariateModelValues{k}),
+            error('Length of single elements in covariateModel and covariateModelValues needs to match (covariateModelValues elements being one shorter).');
+        end            
+    end    
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check COVestimate
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(covariateModel) && ~isempty(COVestimate),
+    error('If you define COVestimate, you also need to define the covariateModel.');
+end
+
+if isempty(COVestimate),
+    % Determine default COVestimate - all are estimates
+    COVestimate = {};
+    for k=1:length(covariateModel),
+        COVestimate{k} = ones(1,length(covariateModel{k})-1);
+    end
+else
+    % Check correct length of COVestimate elements
+    if length(covariateModel) ~= length(COVestimate),
+        error('Number of elements in covariateModel and COVestimate needs to match.');
+    end
+    for k=1:length(covariateModel),
+        if length(covariateModel{k})-1 ~= length(COVestimate{k}),
+            error('Length of single elements in covariateModel and COVestimate needs to match (COVestimate elements being one shorter).');
+        end            
+    end    
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create project and results folder
+% Change into project path
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+oldpath = pwd;
+if ~keepProjectFolder,
+    try, rmdir(projectPath,'s'); catch, end
+end
+mkdir(projectPath); cd(projectPath)
+mkdir(resultsFolder);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Loading dataset and determining medians for covariates
+% Also handle in case custom centering values are defined.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Load dataset
+dataCSV = SBPOPloadCSVdataset(fullfile(dataRelPathFromProject,dataFileName));
+dataheader = get(dataCSV,'VarNames');
+% Determine index of COV columns and their names
+terms = explodePCSB(dataHeaderIdent);
+ixCOVs = strmatchSB('COV',terms,'exact');
+if ~isempty(ixCOVs),
+    dataheaderCOVs = dataheader(ixCOVs);
+    % Determine index of ID column and ID name
+    terms = explodePCSB(dataHeaderIdent);
+    ixID = strmatchSB('ID',terms,'exact');
+    dataheaderID = dataheader(ixID);
+    % Determine median values across ID column
+    allID = eval(sprintf('unique(dataCSV.%s);',dataheaderID{1}));
+    allCOVs = NaN(length(allID),length(ixCOVs));
+    for k=1:length(allID),
+        datak = eval(sprintf('dataCSV(dataCSV.%s==allID(k),ixCOVs);',dataheaderID{1}));
+        allCOVs(k,:) = double(datak(1,:));
+    end
+    covariateMedianValues = median(allCOVs);
+    covariateMedianNames = dataheaderCOVs;
+
+    % Handle custom centering values
+    for k=1:length(COVcentering_covs),
+        ix = strmatchSB(COVcentering_covs{k},covariateMedianNames,'exact');
+        covariateMedianValues(ix) = COVcentering_values(k);
+    end
+    
+    if ~SILENT, 
+        disp(' ')
+        disp('==================================================================');
+        disp('Analysis of dataset for covariates - determine the centering values  ')
+        disp('These are the median values, if not defined differently by the user.')
+        disp(' Results:');
+        for k=1:length(covariateMedianValues),
+            disp(sprintf('   median(%s) = %g',covariateMedianNames{k},covariateMedianValues(k)));
+        end
+        disp('These values will be used to center the continuous covariates')
+        disp('==================================================================');
+        disp(' ')
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get model structure
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ms = struct(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create MLXTRAN model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[modelFileName, modelInfo] = SBPOPcreateMLXTRANfile(model,dosing,'',SILENT);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% If needed, reorder parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(parameterOrder),
+    % First load the MLXTRAN file and change the order of the parameters
+    ptext = sprintf('%s, ',parameterOrder{:});
+    ptext = ptext(1:end-2);
+    parameter_def_new = sprintf('parameter = {%s}\r',ptext);
+    % Read file to be changed
+    content = fileread(modelFileName);
+    % Change
+    content = regexprep(content,'(parameter = {[^\n]+)',parameter_def_new);
+    % Save file again
+    fid = fopen(modelFileName,'w');
+    fprintf(fid,'%s',content);
+    fclose(fid);
+    % Reorder parameters in modelInfo.param_est
+    ix_reorder = [];
+    for k=1:length(parameterOrder),
+        ix_reorder(k) = strmatchSB(parameterOrder{k},{modelInfo.param_est.name},'exact');
+    end
+    modelInfo.param_est = modelInfo.param_est(ix_reorder);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Info text
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~SILENT,
+    disp(' ')
+    disp('==================================================================');
+    disp('==================================================================');
+    disp('== Start of creation of Monolix project.mlxtran file');
+    disp('==================================================================');
+    disp('==================================================================');
+    disp(' ')
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Write out parameter names and values for information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~SILENT,
+    disp('Parameters selected to be estimated and their values in the model (this order):');
+    disp('===============================================================================');
+    for k=1:length(modelInfo.param_est),
+        fprintf('\t%d)\t%s%s: %g\n',k,modelInfo.param_est(k).name,char(32*ones(1,15-length(modelInfo.param_est(k).name))),modelInfo.param_est(k).value0(1));
+    end
+    disp('==================================================================');
+    disp(' ');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if datafile exists and csv file and load some information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dataFile = [dataRelPathFromProject '/' dataFileName];
+try
+    dataheader = SBPOPloadCSVdataset(dataFile,1);
+catch
+    cd(oldpath);
+    error('Please check if the data file "%s" exists.',dataFile)
+end
+% Check if length of header identical to dataHeaderIdent
+if length(explodePCSB(dataHeaderIdent,',')) ~= length(dataheader),
+    cd(oldpath);
+    error('Please check: The data header identifiers do not have the same length as the number of columns in the dataset.')
+end
+% Determine continuous and categorical covariates
+IDs = explodePCSB(dataHeaderIdent,',');
+covIDs = strmatchSB('COV',upper(IDs));
+covNames = dataheader(covIDs);
+catIDs = strmatchSB('CAT',upper(IDs));
+catNames = dataheader(catIDs);
+% Check that regression parameters correctly defined
+nrREGSmodel = length(modelInfo.param_reg);
+nrREGSdata  = length(strmatchSB('X',upper(IDs)));
+if nrREGSmodel ~= nrREGSdata,
+    cd(oldpath);
+    error('Different numbers of regression parameters in model and in dataset.');
+end
+% Print table with regression parameters model and data
+REGAnamesData  = dataheader(strmatchSB('X',upper(IDs)));
+
+if ~SILENT,
+    disp(' ');
+    disp('Please check that the following matches regression parameters in data and model do make sense:');
+    for k=1:length(REGAnamesData),
+        fprintf('\t%s%s: %s\n',REGAnamesData{k},char(32*ones(1,8-length(REGAnamesData{k}))),modelInfo.param_reg(k).name)
+    end
+end
+% Print table with header names and identifiers
+IDs = explodePCSB(dataHeaderIdent,',');
+
+if ~SILENT,
+    disp(' ');
+    disp('Please check that the following matches between data header and identifiers do make sense:');
+    for k=1:length(dataheader),
+        fprintf('\t%s%s: %s\n',dataheader{k},char(32*ones(1,8-length(dataheader{k}))),IDs{k})
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check POPestimate thing
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(POPestimate),
+    POPestimate = ones(1,length(modelInfo.param_est));
+end
+if length(modelInfo.param_est) ~= length(POPestimate),
+    cd(oldpath);
+    error('Please make sure POPestimate is of same length as number of parameters to be estimated.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check POPvalues0 thing
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(POPvalues0),
+    POPvalues0 = [];
+    for k=1:length(modelInfo.param_est),
+        POPvalues0(k) = modelInfo.param_est(k).value0(1);
+    end
+end
+if length(modelInfo.param_est) ~= length(POPvalues0),
+    cd(oldpath);
+    error('Please make sure POPvalues0 is of same length as number of parameters to be estimated.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check IIV distribution things
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(IIVdistribution),
+    IIVdistribution = {};
+    for k=1:length(modelInfo.param_est),
+        IIVdistribution{k} = 'L';
+    end
+end
+
+% Check contents
+test = IIVdistribution;
+for k=1:length(IIVdistribution),
+    if ~ismember(test{k},{'L','N','G'}),
+        cd(oldpath);
+        error('Please make sure that only "N", "L", or "G" appear in the "IIVdistribution" variable.');
+    end
+end
+
+% Check length
+if length(IIVdistribution) ~= length(modelInfo.param_est),
+    cd(oldpath);
+    error('Please make sure that an equal number of IIVdistribution is defined as estimated parameters in the model.');
+end
+
+% Print table parameter names and IIV distributions
+if ~SILENT,
+    disp(' ');
+    disp('Please check that the following matches between parameters and used IIV distributions are correct:');
+    for k=1:length(modelInfo.param_est),
+        if IIVdistribution{k} == 'L', dtext = 'logNormal'; end
+        if IIVdistribution{k} == 'N', dtext = 'Normal'; end
+        if IIVdistribution{k} == 'G', dtext = 'logitNormal'; end
+        fprintf('\t%s%s: %s\n',modelInfo.param_est(k).name,char(32*ones(1,15-length(modelInfo.param_est(k).name))),dtext)
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check IIV estimation things
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(IIVestimate),
+    IIVestimate = ones(1,length(modelInfo.param_est));
+end
+% Check length
+if length(IIVestimate) ~= length(modelInfo.param_est),
+    cd(oldpath);
+    error('Please make sure that an equal number of IIVestimate is defined as estimated parameters in the model.');
+end
+% Print table parameter names and IIV esimations
+if ~SILENT,
+    disp(' ');
+    disp('Please check that the following matches between parameters and used estimated IIVs are correct:');
+    for k=1:length(modelInfo.param_est),
+        if IIVestimate(k) == 0,
+            fprintf('\t%s%s: IIV NOT ESTIMATED (kept on 0)\n',modelInfo.param_est(k).name,char(32*ones(1,15-length(modelInfo.param_est(k).name))));
+        elseif IIVestimate(k) == 1,
+            fprintf('\t%s%s: IIV ESTIMATED\n',modelInfo.param_est(k).name,char(32*ones(1,15-length(modelInfo.param_est(k).name))));
+        elseif IIVestimate(k) == 2,
+            fprintf('\t%s%s: IIV NOT ESTIMATED (kept on initial value)\n',modelInfo.param_est(k).name,char(32*ones(1,15-length(modelInfo.param_est(k).name))));
+        end
+    end
+    disp(' ');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check IIVvalues0 thing
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(IIVvalues0),
+    IIVvalues0 = 0.5*ones(1,length(modelInfo.param_est));
+end
+if length(modelInfo.param_est) ~= length(IIVvalues0),
+    cd(oldpath);
+    error('Please make sure IIVvalues0 is of same length as number of parameters to be estimated.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check residual error things
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(errorModels),
+    errorModels = '';
+    for k=1:length(modelInfo.outputs),
+        errorModels = sprintf('%sconst,',errorModels);
+    end
+    errorModels = errorModels(1:end-1);
+end
+test = errorModels;
+test = strtrim(strrep(strrep(strrep(strrep(strrep(test,'exp',''),'const',''),'prop',''),'comb1',''),',',''));
+if ~isempty(test),
+    cd(oldpath);
+    error('Please make sure that only "const", "prop", "comb1", or "exp" appear in the "errorModels" variable.');
+end
+% Check length
+errors = explodePCSB(errorModels,',');
+if length(errors) ~= length(modelInfo.outputs),
+    cd(oldpath);
+    error('Please make sure that an equal number of errorModels is defined as outputs in the model.');
+end
+% Print table parameter names and IIV distributions
+if ~SILENT,
+    disp(' ');
+    disp('Please check that the following matches between outputs and used residual error models are correct:');
+    for k=1:length(modelInfo.outputs),
+        fprintf('\t%s%s: %s\n',modelInfo.outputs(k).formula,char(32*ones(1,15-length(modelInfo.outputs(k).formula))),errors{k})
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle empty errorParam0
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(errorParam0),
+    terms = explodePCSB(errorModels);
+    for k=1:length(terms),
+        if strcmp(lower(terms{k}),'const'),
+            errorParam0(end+1) = 1;
+        elseif strcmp(lower(terms{k}),'prop'),
+            errorParam0(end+1) = 0.3;
+        elseif strcmp(lower(terms{k}),'comb1'),
+            errorParam0(end+1) = 1;
+            errorParam0(end+1) = 0.3;          
+        elseif strcmp(lower(terms{k}),'exp'),
+            errorParam0(end+1) = 1;
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check errorParam0
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+terms = explodePCSB(errorModels);
+nrneededelements = 0;
+for k=1:length(terms),
+    if strcmpi(terms{k},'const'),
+        nrneededelements = nrneededelements+1;
+    elseif strcmpi(terms{k},'prop'),
+        nrneededelements = nrneededelements+1;
+    elseif strcmpi(terms{k},'comb1'),
+        nrneededelements = nrneededelements+2;
+    elseif strcmpi(terms{k},'exp'),
+        nrneededelements = nrneededelements+1;
+    end
+end
+if length(errorParam0) ~= nrneededelements,
+    error('Incorrect number of elements in options.errorParam0.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check covariance model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(covarianceModel),
+    covarianceModel = 'diagonal';
+elseif ~strcmp(covarianceModel,'diagonal'),
+    % Need to check that none of the parameters for which no IIV is estimated is used in the covarianceModel
+    param_est_noIIV = {modelInfo.param_est(find(~IIVestimate)).name};
+    for k=1:length(param_est_noIIV),
+        if ~isempty(regexp(covarianceModel,['\<' param_est_noIIV{k} '\>'])),
+            cd(oldpath);
+            error('Please make sure none of the parameters for which no IIV is estimated is used in the covarianceModel settings.');
+        end
+    end
+    % Check that all parameters in the covariance model actually are model parameters
+    param = {modelInfo.param_est.name};
+    test  = covarianceModel;
+    for k=1:length(param),
+        test = regexprep(test,['\<' param{k} '\>'],'');
+    end
+    test = strrep(test,'{','');
+    test = strrep(test,'}','');
+    test = strrep(test,',','');
+    test = strtrim(test);
+    if ~isempty(test),
+        cd(oldpath);
+        error('Please make sure that covarianceModel only contains parameter names that are set to <estimate> in the model.');
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check LL setting
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(LLsetting),
+    LLsetting = 'both';
+end
+if isempty(strmatchSB(LLsetting,{'linearization','importantSampling','both'})),
+    cd(oldpath);
+    error('Please make sure LLsetting has one of the following values: "linearization", "importantSampling", "both"=""');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check FIM setting
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(FIMsetting),
+    FIMsetting = 'linearization';
+end
+if isempty(strmatchSB(FIMsetting,{'linearization','stochasticApproximation'})),
+    cd(oldpath);
+    error('Please make sure FIMsetting has one of the following values: "linearization" or "stochasticApproximation"');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check covariate model things
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% First check that all first elements are estimated parameters of the model
+param_est = {modelInfo.param_est.name};
+for k=1:length(covariateModel),
+    param = covariateModel{k}{1};
+    if isempty(strmatchSB(param,param_est,'exact')),
+        cd(oldpath);
+        error('Please make sure that all parameters for which covariates are defined are defined by <estimate> in the model.');
+    end
+end
+% Second check that all defined covariates actually are covariates
+covcatNames = [covNames catNames];
+for k=1:length(covariateModel),
+    for k2=2:length(covariateModel{k}),
+        cov = covariateModel{k}{k2};
+        if isempty(strmatchSB(cov,covcatNames,'exact')),
+            cd(oldpath);
+            error('Please make sure that all covariates, defined in covariateModel, are defined in the dataset.');
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OPEN File
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen([projectName '.mlxtran'],'w');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INFO
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; MLXTRAN PROJECT, created using the SBPOP toolbox\r\n');
+fprintf(fid,'; Date: %s\r\n',date);
+fprintf(fid,'; By:   %s\r\n',usernameSBPOP());
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Placeholder for project information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; ==PROJECT HEADER START===================================================\r\n');
+fprintf(fid,'PROJECT_HEADER_PLACEHOLDER\r\n');
+fprintf(fid,'; ==PROJECT HEADER END=====================================================\r\n');
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DESCRIPTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; =============================================\r\n');
+fprintf(fid,'DESCRIPTION:\r\n');
+fprintf(fid,'; =============================================\r\n');
+fprintf(fid,'\t%s\r\n',ms.name);
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DATA
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; =============================================\r\n');
+fprintf(fid,'DATA:\r\n');
+fprintf(fid,'; =============================================\r\n');
+fprintf(fid,'\tpath = "%%MLXPROJECT%%/%s/",\r\n',dataRelPathFromProject);
+fprintf(fid,'\tfile  ="%s",\r\n',dataFileName);
+fprintf(fid,'\theaders = {%s},\r\n',dataHeaderIdent);
+fprintf(fid,'\tcolumnDelimiter = ","\r\n');
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% VARIABLES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; =============================================\r\n');
+fprintf(fid,'VARIABLES:\r\n');
+fprintf(fid,'; =============================================\r\n');
+% Assume all covariates defined in dataset are used ...
+% Continuous are always log transformed and centered by median
+% Categorical are always kept as they are
+text = '';
+% Write out continuous first
+for k=1:length(covNames),
+    text = sprintf('%s\t%s,\r\n',text,covNames{k});
+    covname = covNames{k};
+    % Scale covariate by median value from dataset
+    ixmedian = strmatchSB(covname,covariateMedianNames,'exact');
+    covname_weighted = sprintf('%s/%g',covname,covariateMedianValues(ixmedian));
+    text = sprintf('%s\tt_%s = log(%s) [use=cov],\r\n',text,covname,covname_weighted);
+end
+% Write out categorical
+for k=1:length(catNames),
+    text = sprintf('%s\t%s [use=cov, type=cat],\r\n',text,catNames{k});
+end
+% Remove last comma and write text to file
+fprintf(fid,text(1:end-3));
+fprintf(fid,'\r\n');
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INDIVIDUAL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; =============================================\r\n');
+fprintf(fid,'INDIVIDUAL:\r\n');
+fprintf(fid,'; =============================================\r\n');
+% Write out parameters to estimate. Assume iiv=yes on all of them by default. 
+% If no IIV desired then rather fix omega to 0.01.
+text = '';
+for k=1:length(modelInfo.param_est),
+    if IIVdistribution{k} == 'L', dtext = 'logNormal'; end
+    if IIVdistribution{k} == 'N', dtext = 'Normal'; end
+    if IIVdistribution{k} == 'G', dtext = 'logitNormal'; end
+    % check if IIV 
+    if IIVestimate(k) == 0,
+        iiv='no';
+    else
+        iiv='yes';
+    end
+    % check for covariates to use
+    param = modelInfo.param_est(k).name;
+    covs = {};
+    for k2=1:length(covariateModel),
+        if strcmp(param,covariateModel{k2}{1}),
+            covs = covariateModel{k2}(2:end);
+        end
+    end
+    % Attach "t_" to continuous covariate names, keep categorical covariate names same
+    for k2=1:length(covs),
+        if ~isempty(strmatchSB(covs{k2},covNames,'exact')),
+            covs{k2} = ['t_' covs{k2}];
+        end
+    end
+    % Write it out
+    if isempty(covs),
+        text = sprintf('%s\t%s = {distribution=%s, iiv=%s},\r\n',text,param,dtext,iiv);
+    else
+        % Create cov text
+        covText = '';
+        for k2=1:length(covs),
+            covText = sprintf('%s%s,',covText,covs{k2});
+        end
+        covText = covText(1:end-1);
+        text = sprintf('%s\t%s = {distribution=%s, covariate={%s}, iiv=%s},\r\n',text,param,dtext,covText,iiv);
+    end        
+end
+% Remove last comma and write text to file
+fprintf(fid,text(1:end-3));
+fprintf(fid,'\r\n');
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CORRELATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~strcmp(covarianceModel,'diagonal'),
+    fprintf(fid,'; =============================================\r\n');
+    fprintf(fid,'CORRELATION:\r\n');
+    fprintf(fid,'; =============================================\r\n');
+    fprintf(fid,'\tcorrelationIIV = {%s}\r\n',covarianceModel);
+    fprintf(fid,'\r\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% STRUCTURAL_MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; =============================================\r\n');
+fprintf(fid,'STRUCTURAL_MODEL:\r\n');
+fprintf(fid,'; =============================================\r\n');
+fprintf(fid,'\tfile = "mlxt:%s",\r\n',strrep(modelFileName,'.txt',''));
+fprintf(fid,'\tpath = "%%MLXPROJECT%%",\r\n');
+fprintf(fid,'\toutput = {');
+for k=1:length(modelInfo.outputs)-1,
+    fprintf(fid,'%s, ',modelInfo.outputs(k).formula);
+end
+fprintf(fid,'%s}',modelInfo.outputs(end).formula);
+fprintf(fid,'\r\n');
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OBSERVATIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; =============================================\r\n');
+fprintf(fid,'OBSERVATIONS:\r\n');
+fprintf(fid,'; =============================================\r\n');
+% Only consider "continuous" observations with SBPOP conversion 
+errors = explodePCSB(errorModels,',');
+text = '';
+for k=1:length(modelInfo.outputs),
+    if strcmp(errors{k},'const'), errorModel = 'constant'; end
+    if strcmp(errors{k},'prop'), errorModel = 'proportional'; end
+    if strcmp(errors{k},'comb1'), errorModel = 'combined1'; end
+    if strcmp(errors{k},'exp'), errorModel = 'exponential'; end
+    text = sprintf('%s\ty%d = {type=continuous, prediction=%s, error=%s},\r\n',text,k,modelInfo.outputs(k).formula,errorModel);
+end
+% Remove last comma and write text to file
+fprintf(fid,text(1:end-3));
+fprintf(fid,'\r\n');
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% TASKS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; =============================================\r\n');
+fprintf(fid,'TASKS:\r\n');
+fprintf(fid,'; =============================================\r\n');
+fprintf(fid,'\t; settings\r\n');
+fprintf(fid,'\tglobalSettings={\r\n');
+fprintf(fid,'\t\twithVariance=no,\r\n'); % Always estimate standard deviations of IIVs
+% Use default graphics settings
+fprintf(fid,'\t\tsettingsGraphics="%%MLXPROJECT%%/project_graphics.xmlx",\r\n');
+fprintf(fid,'\t\tsettingsAlgorithms="%%MLXPROJECT%%/project_algorithms.xmlx",\r\n');
+fprintf(fid,'\t\tresultFolder="%%MLXPROJECT%%/%s"},\r\n',resultsFolder);
+fprintf(fid,'\t; workflow\r\n');
+fprintf(fid,'\testimatePopulationParameters(\r\n');
+fprintf(fid,'\t\tinitialValues={\r\n');
+% write out population parameter initial values
+for k=1:length(modelInfo.param_est),
+    method = '';
+    if POPestimate(k) == 0,
+        method = '[method=FIXED]';
+    end
+    fprintf(fid,'\t\t\tpop_{%s} = %g %s,\r\n',modelInfo.param_est(k).name,POPvalues0(k),method);
+end
+
+% write out covariate coefficient initial guesses
+for k1=1:length(covariateModel),
+    for k2=2:length(covariateModel{k1}),
+        covarvalue = covariateModelValues{k1}(k2-1);
+        if COVestimate{k1}(k2-1),
+            method = '';
+        else
+            method = '[method=FIXED]';
+        end
+        ix = strmatchSB(covariateModel{k1}{k2},covNames,'exact');
+        if isempty(ix),
+            fprintf(fid,'\t\t\tbeta_{%s,%s} = %g %s,\r\n',covariateModel{k1}{1},covariateModel{k1}{k2},covarvalue,method);
+        else
+            fprintf(fid,'\t\t\tbeta_{%s,t_%s} = %g %s,\r\n',covariateModel{k1}{1},covariateModel{k1}{k2},covarvalue,method);
+        end
+    end
+end
+
+% write out residual error model
+errors = explodePCSB(errorModels,',');
+count = 1;
+for k=1:length(errors),
+    if strcmp(errors{k},'const'), 
+        fprintf(fid,'\t\t\ta_y%d = %g,\r\n',k,errorParam0(count));
+        count = count + 1;
+    end
+    if strcmp(errors{k},'prop'), 
+        fprintf(fid,'\t\t\tb_y%d = %g,\r\n',k,errorParam0(count));
+        count = count + 1;
+    end
+    if strcmp(errors{k},'comb1'), 
+        fprintf(fid,'\t\t\ta_y%d = %g,\r\n',k,errorParam0(count));
+        count = count + 1;
+        fprintf(fid,'\t\t\tb_y%d = %g,\r\n',k,errorParam0(count));
+        count = count + 1;
+    end
+    if strcmp(errors{k},'exp'), 
+        fprintf(fid,'\t\t\ta_y%d = %g,\r\n',k,errorParam0(count));
+        count = count + 1;
+    end
+end
+% write out population parameter initial values
+text = '';
+for k=1:length(modelInfo.param_est),
+    if IIVestimate(k)==1,
+        value0 = IIVvalues0(k);
+        text = sprintf('%s\t\t\tomega_{%s} = %g,\r\n',text,modelInfo.param_est(k).name,value0);
+    elseif IIVestimate(k)==2,
+        value0 = IIVvalues0(k);
+        text = sprintf('%s\t\t\tomega_{%s} = %g [method=FIXED],\r\n',text,modelInfo.param_est(k).name,value0);
+    end
+end
+fprintf(fid,text(1:end-3));
+fprintf(fid,'\r\n');
+
+fprintf(fid,'\t\t} ),\r\n');
+if strcmp(FIMsetting,'linearization'),
+    fprintf(fid,'\testimateFisherInformationMatrix( method={linearization} ),\r\n');
+else
+    fprintf(fid,'\testimateFisherInformationMatrix( method={stochasticApproximation} ),\r\n');
+end    
+fprintf(fid,'\testimateIndividualParameters( method={%s} ),\r\n',INDIVparametersetting);
+if strcmp(LLsetting,'linearization'),
+    fprintf(fid,'\testimateLogLikelihood(method={linearization}),\r\n');
+elseif strcmp(LLsetting,'importantSampling'),
+    fprintf(fid,'\testimateLogLikelihood(method={importantSampling}),\r\n');
+elseif strcmp(LLsetting,'both'),
+    fprintf(fid,'\testimateLogLikelihood(method={importantSampling,linearization}),\r\n');
+end
+fprintf(fid,'\tdisplayGraphics()');
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CLOSE File
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fclose(fid);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create Project Header with Metadata
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+PROJECT_INFO_TEXT = '';
+
+% Data location
+DATA_info = sprintf('; DATA                = ''%s''\r\n',strrep(fullfile(dataRelPathFromProject,dataFileName),'\','/'));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,DATA_info);
+
+% covNames
+x = sprintf('%s,',covNames{:});
+COVNAMES_info = sprintf('; COVNAMES            = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,COVNAMES_info);
+
+% catNames
+x = sprintf('%s,',catNames{:});
+CATNAMES_info = sprintf('; CATNAMES            = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,CATNAMES_info);
+
+% PARAMNAMES
+x = sprintf('%s,',modelInfo.param_est.name);
+PARAMNAMES_info = sprintf('; PARAMNAMES          = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,PARAMNAMES_info);
+
+% Outputs
+x = cell(1,length(modelInfo.outputs));
+for k=1:length(modelInfo.outputs),
+    on = eval(strrep(modelInfo.outputs(k).name,'OUTPUT',''));
+    x{on} = modelInfo.outputs(k).formula;
+end
+y = '';
+for k=1:length(x),
+    y = sprintf('%s%s,',y,x{k});
+end
+y = y(1:end-1);
+OUTPUTS_info = sprintf('; OUTPUTS             = ''%s''\r\n',y);
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,OUTPUTS_info);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Replace PROJECT_HEADER_PLACEHOLDER
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+content = fileread('project.mlxtran');
+content = strrep(content,'PROJECT_HEADER_PLACEHOLDER',strtrim(PROJECT_INFO_TEXT));
+fid = fopen('project.mlxtran','w');
+fprintf(fid,'%s',content);
+fclose(fid);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Do generate the default graphics settings so that 
+% predictions.txt file is generated and included NPDE and meanPWRES
+% Trick is to load project file and to add things and then to save the file
+% again.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+copyfile(which('template_project_graphics.xmlx'),'project_graphics.xmlx')
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Generate project_algorithms.xmlx file
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% only writing out K1, K2, Number of Chains, Seed, and auto settings for K1,K2,Number of chains
+fid = fopen('project_algorithms.xmlx','w');
+fprintf(fid,'<monolix>\n');
+fprintf(fid,'	<algorithms seed="%d">\n',SEED);
+fprintf(fid,'		<populationParameters>\n');
+fprintf(fid,'			<vna value="%d,%d"/>\n',K1,K2);
+fprintf(fid,'			<iop_Kauto value="%d,%d"/>\n',K1_AUTO,K2_AUTO);
+fprintf(fid,'			<nmc value="%d"/>\n',NRCHAINS);
+fprintf(fid,'		</populationParameters>\n');
+fprintf(fid,'	</algorithms>\n');
+fprintf(fid,'</monolix>\n');
+fclose(fid);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Change out of project path
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+cd(oldpath);
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/SBPOPgetMonolixDataHeader.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/SBPOPgetMonolixDataHeader.m
new file mode 100644
index 0000000000000000000000000000000000000000..bd53518e3b20ad62310e305b11f4b049e1cf9239
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/SBPOPgetMonolixDataHeader.m
@@ -0,0 +1,163 @@
+function [header] = SBPOPgetMonolixDataHeader(data,covNames,catNames,regressionNames,silent)
+% [DESCRIPTION]
+% This function takes a dataset in the standard clinical data format and
+% determines the Monolix header information for the column names.
+% 
+% The data need to be provided, following the standard dataspec, defined in
+% the help to the function SBPOPcheckDataFormat, so please look there for
+% more information.   
+%
+% [SYNTAX]
+% [header] = SBPOPgetMonolixDataHeader(data,covNames,catNames)
+% [header] = SBPOPgetMonolixDataHeader(data,covNames,catNames,regressionNames)
+% [header] = SBPOPgetMonolixDataHeader(data,covNames,catNames,regressionNames,silent)
+%
+% [INPUT]
+% data:             MATLAB PKPD dataset in standard data spec format  
+% covNames:         Cell-array with names of continuous covariates
+% catNames:         Cell-array with names of categorical covariates
+% regressionNames:  Cell-array with names of regression variables
+% silent:           =0: no output to screen, =1: output to screen
+%
+% [OUTPUT]
+% header:      String with comma separated header info
+%
+% [ASSUMPTIONS]
+% Important assumption: standard dataset format
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 10th May 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MODESIM, MATLAB R2009a
+%
+% [KEYWORDS]
+% MATLAB, SBPOP, datacleaning, covariate, imputation, impute
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+if nargin<4,
+    regressionNames = {};
+end
+
+if nargin<5,
+    silent = 0;
+else
+    silent = 1;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check cov and catnames
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+datanames = get(data,'VarNames');
+for k=1:length(covNames),
+    if isempty(strmatchSB(covNames{k},datanames,'exact')), error('The dataset does not contain the covariate ''%s''.',covNames{k}); end    
+end
+for k=1:length(catNames),
+    if isempty(strmatchSB(catNames{k},datanames,'exact')), error('The dataset does not contain the covariate ''%s''.',catNames{k}); end    
+end
+for k=1:length(regressionNames),
+    if isempty(strmatchSB(regressionNames{k},datanames,'exact')), error('The dataset does not contain the regression variable ''%s''.',regressionNames{k}); end    
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define matches
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+colName = {'STYSID1A' 'SS' 'II' 'ADDL' 'STUDY'   'SUBJECT'    'ID' 'TIME' 'TIMEPOS' 'TAD'    'TIME_UNIT' 'TYPE'   'SUBTYPE'  'DV' 'NAME'   'UNIT'   'MDV' 'EVID' 'CENS' 'AMT'   'ADM' 'RATE' 'TINF' 'DOSE'    'TRT'  'YTYPE'};
+colType = {'IGNORE'   'SS' 'II' 'ADDL' 'CAT'     'IGNORE'     'ID' 'TIME' 'TIMEPOS' 'IGNORE' 'IGNORE'    'IGNORE' 'IGNORE'   'Y'  'IGNORE' 'IGNORE' 'MDV' 'EVID' 'CENS' 'AMT'  'ADM'  'RATE' 'TINF' 'IGNORE'  'CAT'   'YTYPE'};
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Fill header with 'IGNORE' first
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+headerContent = cell(1,length(datanames));
+for k=1:length(headerContent),
+    headerContent{k} = 'IGNORE';
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Generate header
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Apply matches
+for k=1:length(colName),
+    ix = strmatchSB(colName{k},datanames,'exact');
+    if ~isempty(ix),
+        headerContent{ix} = colType{k};
+    end
+end
+% Add continuous covariate information
+for k=1:length(covNames),
+    ix = strmatchSB(covNames{k},datanames,'exact');
+    if ~isempty(ix),
+        headerContent{ix} = 'COV';
+    end
+end
+% Add categorical covariate information
+for k=1:length(catNames),
+    ix = strmatchSB(catNames{k},datanames,'exact');
+    if ~isempty(ix),
+        headerContent{ix} = 'CAT';
+    end
+end
+% Add regression variable information
+for k=1:length(regressionNames),
+    ix = strmatchSB(regressionNames{k},datanames,'exact');
+    if ~isempty(ix),
+        headerContent{ix} = 'X';
+    end
+end
+
+% Run through all CAT definitions and check if single element value - then
+% warn the user and remove the cat cov by setting to IGNORE, otherwise
+% Monolix error.
+ixCAT = strmatchSB('CAT',headerContent);
+% Add categorical covariate information
+for k=1:length(ixCAT),
+    catName = datanames{ixCAT(k)};
+    if length(unique(data.(catName))) == 1,
+        headerContent{ixCAT(k)} = 'IGNORE';
+        fprintf('\nOnly single cagtegory for candidate categorical covariate "%s" => IGNORE.\n',catName);    
+    end
+end
+   
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create header output string
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+header = sprintf('%s,',headerContent{:});
+header = header(1:end-1);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Print Info
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~silent,
+    fprintf('\tMatching of dataset column names with Monolix column types:\n')
+    fprintf('\t===========================================================\n')
+    for k=1:length(datanames),
+        fprintf('\t%s:\t%s\n',datanames{k},headerContent{k});
+    end
+    fprintf('\n');
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/SBPOPrunMONOLIXproject.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/SBPOPrunMONOLIXproject.m
new file mode 100644
index 0000000000000000000000000000000000000000..b145e302f14ca9c65590acdffdb99a8e0d980bb5
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/SBPOPrunMONOLIXproject.m
@@ -0,0 +1,130 @@
+function SBPOPrunMONOLIXproject(projectPath,N_PROCESSORS,NO_GOF_PLOTS)
+% SBPOPrunMONOLIXproject: runs a specified Monolix project
+%
+% Essentially this function is just a simple wrapper.
+%
+% It requires the path to the standalone version of MONOLIX!
+%
+% USAGE:
+% ======
+% SBPOPrunMONOLIXproject(projectPath)
+% SBPOPrunMONOLIXproject(projectPath,N_PROCESSORS)
+% SBPOPrunMONOLIXproject(projectPath,N_PROCESSORS,NO_GOF_PLOTS)
+%
+% projectPath:              path to the .mlxtran Monolix project file
+% NPROCESSORS:              Number of processors if use of parallel (default: 1)
+%                           This argumentis not used yet!
+% NO_GOF_PLOTS:             =0: Create GoF plots for all runs (default), =1: No Gof plots
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 1,
+    NPROCESSORS = 1;
+    NO_GOF_PLOTS = 0;
+elseif nargin == 2,
+    NO_GOF_PLOTS = 0;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Change in to project path 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+oldpath = pwd;
+cd(projectPath);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Load information about the MONOLIX PATH
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[PATH_MONOLIX,PATH_NONMEM,PATH_NONMEM_PAR] = getNLMEtoolInfoSBPOP();
+if isempty(PATH_MONOLIX),
+    error('Path to MONOLIX standalone version not defined in SETUP_PATHS_TOOLS.m');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run the MONOLIX project
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isunix,
+    system([PATH_MONOLIX ' -p ./project.mlxtran -nowin -f run']);
+else
+    fullProjectPath = pwd();
+    PATH_MONOLIX_BAT = fileparts(PATH_MONOLIX);
+    cd(PATH_MONOLIX_BAT);
+    systemcall = sprintf('Monolix.bat -p "%s/project.mlxtran" -nowin -f run',fullProjectPath);
+    system(systemcall);
+    cd(fullProjectPath);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Convert the results.ps to results.pdf
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try
+    convert2pdfSBPOP('RESULTS/results.ps')
+catch
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Generate information for GOF plots
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+try
+    PROJECTINFO     = parseProjectHeaderMONOLIXSBPOP('.');
+    
+    % outputNumber: Defined by metadata "OUTPUTS"
+    outputNumberALL = [1:length(PROJECTINFO.OUTPUTS)];
+    outputNamesALL  = PROJECTINFO.OUTPUTS;
+    
+    % data:
+    data            = SBPOPloadCSVdataset(PROJECTINFO.DATA{1});
+    
+    % covNames:
+    covNames        = PROJECTINFO.COVNAMES;
+    
+    % catNames:
+    catNames        = PROJECTINFO.CATNAMES;
+catch
+    warning('Problem with obtaining information for GOF plots.');
+    disp(lasterr);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Do GOF plots
+% For each output one folder in RESULTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~NO_GOF_PLOTS,
+    try
+        for k=1:length(outputNumberALL),
+            outputNumber            = outputNumberALL(k);
+            options                 = [];
+            options.basefilename    = sprintf(['./RESULTS/GOF_OUTPUT_%d_%s/GOF_%d_%s_'],outputNumber,outputNamesALL{k},outputNumber,outputNamesALL{k});
+            SBPOPfitanalysisGeneralPlots(outputNumber,data,'.',covNames,catNames,options)
+        end
+    catch
+        warning('Problem with GOF plots.');
+        disp(lasterr);        
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Change back to previous path
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+cd(oldpath)
+
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/SBPOPrunMONOLIXprojectFolder.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/SBPOPrunMONOLIXprojectFolder.m
new file mode 100644
index 0000000000000000000000000000000000000000..9fbaa47e65769390913692ab5d594062edde602c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/SBPOPrunMONOLIXprojectFolder.m
@@ -0,0 +1,120 @@
+function [] = SBPOPrunMONOLIXprojectFolder(modelProjectsFolder,N_PROCESSORS_PAR,N_PROCESSORS_SINGLE,NO_GOF_PLOTS)
+% [DESCRIPTION]
+% This functions runs all the Monolix projects in the specified folder.
+% Parallel computation is supported in two different ways. Parallel execution 
+% of models at the same time (par for loop) and also allowing each single model
+% run to be parallelized (if the MONOLIX installation allows for it).
+%
+% [SYNTAX]
+% [] = SBPOPrunMONOLIXprojectFolder(modelProjectsFolder)
+% [] = SBPOPrunMONOLIXprojectFolder(modelProjectsFolder,N_PROCESSORS)
+% [] = SBPOPrunMONOLIXprojectFolder(modelProjectsFolder,N_PROCESSORS,N_PROCESSORS_SINGLE)
+% [] = SBPOPrunMONOLIXprojectFolder(modelProjectsFolder,N_PROCESSORS,N_PROCESSORS_SINGLE,NO_GOF_PLOTS)
+%
+% [INPUT]
+% modelProjectsFolder:      Path to a folder with Monolix project folders
+%                           to be run. Folder names are arbitrary, but a
+%                           project.mlxtran file needs to be present in
+%                           each folder.
+% N_PROCESSORS_PAR:         Number of processors for parallel model evaluation (default: 1)
+% N_PROCESSORS_SINGLE:      Number of processors for parallelization of single model run (default: 1)
+% NO_GOF_PLOTS:             =0: Create GoF plots for all runs (default), =1: No Gof plots
+%
+% If N_PROCESSORS_PAR>1 then parallel nodes are requested via the matlabpool
+% command and N_PROCESSORS_PAR models will be run in parallel.
+%
+% [OUTPUT]
+% No output! The function just runs the Monolix projects. All results are
+% written by Monolix to the relevant output folders ("RESULTS").
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 2nd March, 2013
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 1,
+    N_PROCESSORS_PAR    = 1;
+    N_PROCESSORS_SINGLE = 1;
+    NO_GOF_PLOTS = 0;
+elseif nargin == 2,
+    N_PROCESSORS_SINGLE = 1;
+    NO_GOF_PLOTS = 0;
+elseif nargin == 3,
+    NO_GOF_PLOTS = 0;
+end
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get the projects to run in the folder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+projects = dir([modelProjectsFolder '/*']);
+% Remove . and ..
+ix_dot = strmatchSB('.',{projects.name});
+projects(ix_dot) = [];
+% Remove files
+projects(find(~[projects.isdir])) = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Request processors
+% Request min(N_PROCESSORS,length(projects))
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+N_PROCESSORS_NEEDED = min(N_PROCESSORS_PAR,length(projects));
+
+killMATLABpool = 0;
+if N_PROCESSORS_NEEDED>1,
+    try
+        if matlabpool('size') == 0,
+            eval(sprintf('matlabpool %d',N_PROCESSORS_NEEDED));
+            killMATLABpool = 1;
+        end
+    catch
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run the models
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+warning off
+oldpath = pwd();
+parfor k=1:length(projects),
+    fprintf('Running project %d of %d ...\n',k,length(projects));
+    pathfolder = [modelProjectsFolder '/' projects(k).name];
+    if isMONOLIXfitSBPOP(pathfolder),
+        SBPOPrunMONOLIXproject(pathfolder,N_PROCESSORS_SINGLE,NO_GOF_PLOTS);
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Release processors
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try
+    if matlabpool('size')>1 && killMATLABpool==1,
+        matlabpool close
+    end
+catch
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Done!
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf('\nEstimations READY!\n\n');
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/SBPOPsampleMONOLIXparam.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/SBPOPsampleMONOLIXparam.m
new file mode 100644
index 0000000000000000000000000000000000000000..4018540577b31a9937e08813d240b64a04dede86
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/SBPOPsampleMONOLIXparam.m
@@ -0,0 +1,768 @@
+function [output] = SBPOPsampleMONOLIXparam( path_to_monolix_project_folder, FLAG_SAMPLE, Nsamples, varargin )
+% [NAME]
+% SBPOPsampleMONOLIXparam
+%
+% [DESCRIPTION]
+% This function samples parameters from both uncertainty and variability distributions from a Monolix fit.
+% The result is a structure with sampled population parameters and sampled individual parameters. The desired
+% number of parameter sets can be specified.
+%
+% This function is very useful for trial simulation purposes.
+%
+% Handles automatically different parameter distributions (logNormal, Normal, logitNormal)
+%
+% VERY IMPORTANT:
+% If using Monolix versions before 4.2, you should NOT center the covariates automatically by the median or mean, etc. This is so,
+% because Monolix before 4.2 does NOT store this centering value. For versions before 4.2 you need to center manually, by choosing the
+% covariate transformation method "other" and then e.g. type: log(cov/78) if cov is weight and you want to center it at 78kg and use a
+% log transformation.
+% For versions from 4.2 upwards, no problem, centering values are stored and automatic centering can be used.
+%
+% [SYNTAX]
+% output = SBPOPsampleMONOLIXparam( path_to_monolix_project_folder, FLAG_SAMPLE, Nsamples )
+% output = SBPOPsampleMONOLIXparam( path_to_monolix_project_folder, FLAG_SAMPLE, Nsamples, covNames, covValues, catNames, catValues )
+%
+% [INPUT]
+% path_to_monolix_project_folder: path to the Monolix project folder. It is assumed that the results of the estimation
+%                                 (pop_parameters.txt, results.mat) are stored in a "RESULTS" folder within this
+%                                 project folder.
+% FLAG_SAMPLE:                    0=use point estimates of population parameters (do not consider uncertainty) and sample Nsample 
+%                                   individual patients based on these. Covariates considered if defined by user and used in model.
+%                                   Please note: population parameters do not take covariates into account!
+%                                 1=sample single set of population parameters from uncertainty distribution and sample Nsample 
+%                                   individual patient parameters based on these. Covariates considered if defined by user and used in model.
+%                                   Please note: population parameters do not take covariates into account!
+%                                 2=sample Nsample sets of population parameters from uncertainty distribution 
+%                                   Do not sample from variability distribution and do not take into account covariates (even if user specified).
+%                                 3=use point estimates of population parameters (do not consider uncertainty)
+%                                   Return Nsamples sets of population parameters with covariates taken into account.
+%                                 4=sample single set of population parameters from uncertainty distribution 
+%                                   Return Nsamples sets of population parameters with covariates taken into account.
+%                                 5=sample Nsamples sets of population parameters from uncertainty distribution 
+%                                   And take provided covariates into account.
+% 
+% Nsamples:                       Number of individual parameter sets to sample
+%
+% covNames:                       Cell-array with names of continuous covariates to consider in the parameter sampling (only used for FLAG_SAMPLE=0 or 1)
+%                                 Default: {}
+% covValues:                      Matrix with Nsamples rows and as many columns as continuous covariate names in covNames (only used for FLAG_SAMPLE=0 or 1)
+% catNames:                       Cell-array with names of categorical covariates to consider in the parameter sampling (only used for FLAG_SAMPLE=0 or 1)
+%                                 Default: {}
+% catValues:                      Matrix with Nsamples rows and as many columns as categorical covariate names in covNames (only used for FLAG_SAMPLE=0 or 1)
+%
+% [OUTPUT]
+% Structure with the following fields:
+% output.parameterNames:                Cell-array with parameter names
+% output.FLAG_SAMPLE:                   Sampling flag used (see above for definition)
+% output.Nsamples:                      Number of sampled parameter sets (type of parameter sets sampled depends on FLAG_SAMPLE)
+% output.parameterValuesPopulation:     Vector or Matrix with (sampled) population parameters
+% output.parameterValuesIndividual:     Matrix with samples individual parameter sets (one set per row, one parameter per column)
+%
+% [ASSUMPTIONS]
+% 
+% [AUTHOR]
+% Henning Schmidt 
+%
+% [DATE]
+% 08.06.2012
+%
+% [PLATFORM]
+% MATLAB R2009a
+%
+% [KEYWORDS]
+% MONOLIX, results, sampling, parameters, individual
+% 
+% [TOOLBOXES USED]
+% NONE
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% % Check minimum version of Monolix
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% try
+%     x = verLessThan('monolix','4.2.0');
+% catch
+%     x = NaN;
+% end
+% if  x==1,
+%     error('SBPOP requires Monolix version >= 4.2.0');
+% elseif isnan(x),
+%     warning('Please check your version of Monolix - it should be at least 4.2.0.');
+% end
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Parse Monolix results
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+x = parseMONOLIXresultsSBPOP(path_to_monolix_project_folder);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Need to handle variable input arguments for CONTINUOUS covariates 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin>=5,
+    covNames = varargin{1};
+    covValues = varargin{2};
+    
+    if ~isempty(covNames),
+        % Check correct size (Nsamples)
+        if size(covValues,1) ~= Nsamples,
+            error('Provided values for continuous covariates need to have length of "Nsamples".');
+        end
+    else
+        covNames = {};
+        covValues = [];
+    end
+else
+    % No covariates provided! 
+    covNames = {};
+    covValues = [];
+end
+if ~iscell(covNames),
+    covNames = {covNames};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Need to handle variable input arguments for CATEGORICAL covariates 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin==7,
+    catNames = varargin{3};
+    catValues = varargin{4};
+    
+    if ~isempty(catNames),
+        % Check correct size (Nsamples)
+        if size(catValues,1) ~= Nsamples,
+            error('Provided values for categorical covariates need to have length of "Nsamples".');
+        end
+    else
+        catNames = {};
+        catValues = [];
+    end
+else
+    % No covariates provided! 
+    catNames = {};
+    catValues = [];
+end
+if ~iscell(catNames),
+    catNames = {catNames};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run the sampling function once to get covariate information
+% Parameter values will not be considered here and handled later
+% Check if covariates in model and warn if yes but user has not provided covariate information
+%
+% Do run this part only if FLAG_SAMPLE not equal to 2
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if FLAG_SAMPLE~=2,
+    y = sampleMONOLIXpopulationParametersSBPOP(x,0,1);
+    covInfo = y.covariates.continuous;
+    catInfo = y.covariates.categorical;
+    % Check if covariates are in the model but not provided
+    if ~isempty(covInfo(1).parameter) && isempty(covNames),
+        disp('Model contains continuous covariates but no covariates are provided by the user.');
+        disp(' ');
+    end
+    if ~isempty(catInfo(1).parameter) && isempty(catNames),
+        disp('Model contains categorical covariates but no covariates are provided by the user.');
+        disp(' ');
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Prepare CONTINUOUS covariate information (if needed)
+    %
+    % phi = mu + eta + t_cov * beta
+    %
+    % phi:      matrix of transformed individual parameters. one row per individual. (Nsamples x Nparameters)
+    % mu:       matrix of transformed population parameter values (same row repeated Nsamples times). (Nsamples x Nparameters)
+    % t_cov:    matrix of transformed covariates (Nsamples x Ncovariates)
+    %           We will assume that each covariate with the same name has the same transformation. And this will be checked.
+    % beta:     matrix with covariate coefficients beta_ij (Ncovariates x Nparameters)
+    %
+    % Only covariates will be considered that actually are passed by the user.
+    % If other covariates are present in the model then a warning will be made.
+    %
+    % No covariate parameter values are considered here. Just error checking, data transformation, ...
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    if ~isempty(covNames),
+        % Cycle through covariate information and build data and do some error checks
+        % Handle centervalue by replacing "cov" by "cov/centervalue". But only if centervalue not NaN and not 0.
+        allModelCovNames = {};
+        allModelCovFormulas = {};
+        for k1=1:length(covInfo),
+            paramName = covInfo(k1).parameter;
+            for k2=1:length(covInfo(k1).covariates),
+                covname     = covInfo(k1).covariates{k2};
+                betavalue   = covInfo(k1).values(k2);
+                formula     = covInfo(k1).transformation{k2}.formula;
+                centervalue = covInfo(k1).transformation{k2}.centervalue;
+                % Handle the centering
+                % If center value defined then use it, if NOT defined, then
+                % just assume it is 0
+                if centervalue~=0 && ~isnan(centervalue),
+                    % Center value in Monolix is already transformed, so
+                    % that substraction of it from the transformed
+                    % covariate leads to 0 if cov at the center thing
+                    formula = [formula sprintf('-%g',centervalue)];
+                end
+                % Check if covname already in allModelCovNames
+                ix = strmatchSB(covname,allModelCovNames,'exact');
+                if isempty(ix),
+                    % add covariate and formula to lists
+                    allModelCovNames{end+1} = covname;
+                    allModelCovFormulas{end+1} = formula;
+                else
+                    % check that formula is the same, otherwise error
+                    if ~strcmp(formula,allModelCovFormulas{ix}),
+                        error('Different covariate transformations for same continuous covariate.');
+                    end
+                end
+            end
+        end
+        
+        % Check model covariates against provided covariates
+        % Remove covariates provided by the user that are not used in the model - warn the user
+        % Warn the user also about covariates that are in the model but not provided by the user
+        [covsUser_notinmodel,ix_notinmodel] = setdiff(covNames,allModelCovNames);
+        [covsModel_notuser,ix_notuser] = setdiff(allModelCovNames,covNames);
+        
+        % Remove user defined covariates that are not used in the model
+        covNames(ix_notinmodel) = [];
+        covValues(:,ix_notinmodel) = [];
+        
+        % Warn the user about what has been found
+        if ~isempty(ix_notinmodel),
+            disp('The following continuous covariates have been defined by the user but they are not present in the model. They will be not considered.');
+            covsUser_notinmodel
+        end
+        if ~isempty(ix_notuser),
+            disp('The following continuous covariates are defined in the model but have not been provided by the user. They will be not considered.');
+            covsModel_notuser
+        end
+        
+        % Generate the transformed covariates
+        t_cov = covValues;
+        for k=1:length(covNames),
+            ix = strmatchSB(covNames{k},allModelCovNames,'exact');
+            formula = allModelCovFormulas{ix};
+            t_cov(:,k) = eval(strrep(formula,'cov','covValues(:,k)'));
+        end
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Prepare CATEGORICAL covariate information (if needed)
+    %
+    % phi = mu + eta + t_cov * beta + beta_cat
+    %
+    % phi:      matrix of transformed individual parameters. one row per individual. (Nsamples x Nparameters)
+    % mu:       matrix of transformed population parameter values (same row repeated Nsamples times). (Nsamples x Nparameters)
+    % t_cov:    matrix of transformed covariates (Nsamples x Ncovariates)
+    %           We will assume that each covariate with the same name has the same transformation. And this will be checked.
+    % beta:     matrix with covariate coefficients beta_ij (Ncovariates x Nparameters)
+    % beta_cat: matrix with categorical covariate coefficients (Nsamples x Nparameters)
+    %           Does not need to be prepared much but some error checking needs to be done
+    %
+    % Only covariates will be considered that actually are passed by the user.
+    % If other covariates are present in the model then a warning will be made.
+    %
+    % No covariate parameter values are considered here. Just error checking, data transformation, ...
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    if ~isempty(catNames),
+        % Cycle through covariate information and get all categorical covariate names used
+        allModelCatNames = {};
+        for k1=1:length(catInfo),
+            paramName = catInfo(k1).parameter;
+            for k2=1:length(catInfo(k1).covariates),
+                catname     = catInfo(k1).covariates{k2};
+                % Check if catname already in allModelCatNames
+                ix = strmatchSB(catname,allModelCatNames,'exact');
+                if isempty(ix),
+                    % add covariate and formula to lists
+                    allModelCatNames{end+1} = catname;
+                end
+            end
+        end
+        
+        % Check model covariates against provided covariates
+        % Remove covariates provided by the user that are not used in the model - warn the user
+        % Warn the user also about covariates that are in the model but not provided by the user
+        [catsUser_notinmodel,ix_notinmodel] = setdiff(catNames,allModelCatNames);
+        [catsModel_notuser,ix_notuser] = setdiff(allModelCatNames,catNames);
+        
+        % Remove user defined covariates that are not used in the model
+        catNames(ix_notinmodel) = [];
+        catValues(:,ix_notinmodel) = [];
+        
+        % Warn the user about what has been found
+        if ~isempty(ix_notinmodel),
+            disp('The following categorical covariates have been defined by the user but they are not present in the model. They will be not considered.');
+            catsUser_notinmodel
+        end
+        if ~isempty(ix_notuser),
+            disp('The following categorical covariates are defined in the model but have not been provided by the user. They will be not considered.');
+            catsModel_notuser
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle case of FLAG_SAMPLE=0 and 1
+% Sampling individual parameters with (1) or without (0) uncertainty 
+% Taking covariates into account if provided.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if FLAG_SAMPLE == 0 || FLAG_SAMPLE ==1,
+    % Need to sample until reasonable values (no imaginary parts in parameters)
+    while 1,
+        % Parse and sample monolix results
+        y = sampleMONOLIXpopulationParametersSBPOP(x,FLAG_SAMPLE);
+        
+        % Get covariance matrix
+        cov = y.randomEffects.covariancematrix;
+        [eigV,eigD] = eig(cov);
+        if min(diag(eigD)) > -1e-3,
+            % It is not positive semidefinite, but the smallest eigenvalue
+            % is so close to zero that we are going to put it on zero
+            eigD(eigD<0) = 0;
+            cov = eigV*eigD*inv(eigV);
+            disp('Random effect covariance matrix not positive semidefinite. Smallest eigenvalue is closer to 0 than -1e-3 => making it positive semidefinite.');
+        end
+        
+        % Sample individual random effects (etas)
+        ETA = mvnrnd(zeros(1,size(cov,1)),cov,Nsamples);
+        
+        % Transform population estimates to normal distribution (mu) (allowing for transformations: lognormal, logitnormal, normal)
+        mu = [];
+        for k=1:length(y.randomEffects.inv_transformation),
+            mu(k) = eval(strrep(y.randomEffects.inv_transformation{k},'psi',sprintf('%g',y.fixedEffects.values(k))));
+        end
+        
+        % Determine normally distributed phi - without covariate contributions: phi = mu + eta  (+ beta*t_cov + beta_cat)
+        phi = mu(ones(1,Nsamples),:) + ETA;
+        
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        % Determine and add effect of continuous covariates to phi: phi = mu + eta + t_cov*beta  (+ beta_cat)
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        if ~isempty(covNames),
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Determine the beta matrix
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Get parameter names of estimates
+            paramNames = y.fixedEffects.names;
+            % Initialize the beta matrix
+            beta = zeros(length(covNames),length(paramNames));
+            % Fill the beta matrix
+            for k1=1:length(covInfo),
+                paramName = covInfo(k1).parameter;
+                ix_j = strmatchSB(paramName,paramNames,'exact');
+                for k2=1:length(covInfo(k1).covariates),
+                    covname     = covInfo(k1).covariates{k2};
+                    beta_ij     = covInfo(k1).values(k2);
+                    ix_i        = strmatchSB(covname,covNames,'exact');
+                    % Fill beta_ij value into beta matrix
+                    beta(ix_i,ix_j) = beta_ij;
+                end
+            end
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Add t_cov*beta to phi
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            phi = phi + t_cov*beta;
+        end
+        
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        % Determine and add effect of categorical covariates to phi: phi = mu + eta + beta*t_cov + beta_cat
+        % One beta_cat matrix for each parameter/covariate combination!
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        if ~isempty(catNames),
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Determine the beta_cat matrix
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Get parameter names of estimates
+            paramNames = y.fixedEffects.names;
+            % Initialize the beta_cat matrix (Nsamples x Nparameters)
+            beta_cat = {};
+            % Determine the beta_cat matrices
+            for k1=1:length(catInfo),
+                paramName = catInfo(k1).parameter;
+                ix_j = strmatchSB(paramName,paramNames,'exact');
+                for k2=1:length(catInfo(k1).covariates),
+                    % Initialize parameter/covariate dependent beta_cat matrix
+                    beta_cat_cov = zeros(Nsamples,length(paramNames));
+                    % Get categorical cov name and index
+                    catname     = catInfo(k1).covariates{k2};
+                    ix_i        = strmatchSB(catname,catNames,'exact');
+                    if ~isempty(ix_i),
+                        % Fill the beta_cat_cov matrix
+                        categories_user = catValues(:,ix_i);
+                        categories_model = catInfo(k1).information(k2).categories;
+                        categories_values = catInfo(k1).information(k2).values;
+                        % Initialize values
+                        values = NaN(size(categories_user));
+                        for kkk=1:length(categories_model),
+                            ix = categories_user==categories_model(kkk);
+                            values(ix) = categories_values(kkk);
+                        end
+                        % Check if values contains NaN, then error and inform the user
+                        if ~isempty(find(isnan(values), 1)),
+                            error('Categorical covariate "%s" contains user provided category that has not been used for model building.',catname);
+                        end
+                        % Assign values
+                        beta_cat_cov(:,ix_j) = values;
+                    end
+                    beta_cat{end+1} = beta_cat_cov;
+                end
+            end
+            
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Add beta_cat to phi
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            for k1=1:length(beta_cat),
+                phi = phi + beta_cat{k1};
+            end
+        end
+        
+        % Back transform individual parameters (each column one parameter)
+        psi = [];
+        for k=1:size(phi,2),
+            transform_string = strrep(y.randomEffects.transformation{k},'phi',sprintf('phi(:,%d)',k));
+            psi(:,k) = eval(transform_string);
+            % Handle the case when phi=Inf and logit transformation => manually set to 1
+            if strcmp(y.randomEffects.transformation{k},'exp(phi)./(1+exp(phi))'),
+                psi(isnan(psi)) = 1;
+            end
+        end
+        
+        % Check if some issues with the sampled parameters (should not lead to complex values)
+        if isempty(find(imag(psi) ~=0)),
+            break;
+        else
+            % Rerun sampling since problem with population parameter sampling
+        end
+    end
+    % Define output variable
+    output                              = [];
+    output.parameterNames               = y.fixedEffects.names;
+    output.FLAG_SAMPLE                  = FLAG_SAMPLE;
+    output.Nsamples                     = Nsamples;
+    output.parameterValuesPopulation    = y.fixedEffects.values;
+    output.parameterValuesIndividual    = psi;
+
+elseif FLAG_SAMPLE == 2,
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Handle special case of FLAG_SAMPLE=2 (sampling population parameters only)
+    % Not taking covariates into account
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    FLAG_SAMPLE_POPULATIONPARAM = 1;
+    
+    % Run sampling function once just to get the number of parameters to sample
+    y = sampleMONOLIXpopulationParametersSBPOP(x,0,1);
+
+    % Initialize the matrix with the parameter values (number of parameters needed for that)
+    popvalues = zeros(Nsamples,length(y.fixedEffects.names));
+    
+    % Get Nsamples sets of population parameters from uncertainty distribution
+    for k=1:Nsamples,
+        y = sampleMONOLIXpopulationParametersSBPOP(x,FLAG_SAMPLE_POPULATIONPARAM,1);
+        popvalues(k,:) = y.fixedEffects.values;
+    end
+    
+    % Define output variable
+    output                              = [];
+    output.parameterNames               = y.fixedEffects.names;
+    output.FLAG_SAMPLE                  = FLAG_SAMPLE;
+    output.Nsamples                     = Nsamples;
+    output.parameterValuesPopulation    = popvalues;
+    output.parameterValuesIndividual    = [];
+    
+elseif FLAG_SAMPLE == 3 || FLAG_SAMPLE == 4,
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Handle special case of FLAG_SAMPLE=3 || 4
+    % - Sampling population parameters once only from uncertainty distributions (if FLAG_SAMPLE=4)
+    % - Including covariate effect on sampled population parameters
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    
+    if FLAG_SAMPLE==3,
+        FLAG_SAMPLE_POPULATIONPARAM = 0;
+    else
+        FLAG_SAMPLE_POPULATIONPARAM = 1;
+    end
+    
+    % Need to sample until reasonable values (no imaginary parts in parameters)
+    while 1,
+        % Parse and sample monolix results to get base population parameters without covariate effects
+        y = sampleMONOLIXpopulationParametersSBPOP(x,FLAG_SAMPLE_POPULATIONPARAM);
+        
+        % Transform population parameters to normal distribution (mu) (allowing for transformations: lognormal, logitnormal, normal)
+        mu = [];
+        for k=1:length(y.randomEffects.inv_transformation),
+            mu(k) = eval(strrep(y.randomEffects.inv_transformation{k},'psi',sprintf('%g',y.fixedEffects.values(k))));
+        end
+        
+        % Determine normally distributed phi - without eta and covariate contribution: phi = mu (+ eta)  (+ beta*t_cov + beta_cat)
+        phi = mu(ones(1,Nsamples),:);
+        
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        % Determine and add effect of continuous covariates to phi: phi = mu (+ eta) + t_cov*beta  (+ beta_cat)
+        % Without eta contribution
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        if ~isempty(covNames),
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Determine the beta matrix
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Get parameter names of estimates
+            paramNames = y.fixedEffects.names;
+            % Initialize the beta matrix
+            beta = zeros(length(covNames),length(paramNames));
+            % Fill the beta matrix
+            for k1=1:length(covInfo),
+                paramName = covInfo(k1).parameter;
+                ix_j = strmatchSB(paramName,paramNames,'exact');
+                for k2=1:length(covInfo(k1).covariates),
+                    covname     = covInfo(k1).covariates{k2};
+                    beta_ij     = covInfo(k1).values(k2);
+                    ix_i        = strmatchSB(covname,covNames,'exact');
+                    % Fill beta_ij value into beta matrix
+                    beta(ix_i,ix_j) = beta_ij;
+                end
+            end
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Add t_cov*beta to phi
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            phi = phi + t_cov*beta;
+        end
+        
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        % Determine and add effect of categorical covariates to phi: phi = mu + eta + beta*t_cov + beta_cat
+        % One beta_cat matrix for each parameter/covariate combination!
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        if ~isempty(catNames),
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Determine the beta_cat matrix
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Get parameter names of estimates
+            paramNames = y.fixedEffects.names;
+            % Initialize the beta_cat matrix (Nsamples x Nparameters)
+            beta_cat = {};
+            % Determine the beta_cat matrices
+            for k1=1:length(catInfo),
+                paramName = catInfo(k1).parameter;
+                ix_j = strmatchSB(paramName,paramNames,'exact');
+                for k2=1:length(catInfo(k1).covariates),
+                    % Initialize parameter/covariate dependent beta_cat matrix
+                    beta_cat_cov = zeros(Nsamples,length(paramNames));
+                    % Get categorical cov name and index
+                    catname     = catInfo(k1).covariates{k2};
+                    ix_i        = strmatchSB(catname,catNames,'exact');
+                    if ~isempty(ix_i),
+                        % Fill the beta_cat_cov matrix
+                        categories_user = catValues(:,ix_i);
+                        categories_model = catInfo(k1).information(k2).categories;
+                        categories_values = catInfo(k1).information(k2).values;
+                        % Initialize values
+                        values = NaN(size(categories_user));
+                        for kkk=1:length(categories_model),
+                            ix = categories_user==categories_model(kkk);
+                            values(ix) = categories_values(kkk);
+                        end
+                        % Check if values contains NaN, then error and inform the user
+                        if ~isempty(find(isnan(values), 1)),
+                            error('Categorical covariate "%s" contains user provided category that has not been used for model building.',catname);
+                        end
+                        % Assign values
+                        beta_cat_cov(:,ix_j) = values;
+                    end
+                    beta_cat{end+1} = beta_cat_cov;
+                end
+            end
+            
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Add beta_cat to phi
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            for k1=1:length(beta_cat),
+                phi = phi + beta_cat{k1};
+            end
+        end
+        
+        % Back transform individual parameters (each column one parameter)
+        psi = [];
+        for k=1:size(phi,2),
+            transform_string = strrep(y.randomEffects.transformation{k},'phi',sprintf('phi(:,%d)',k));
+            psi(:,k) = eval(transform_string);
+            % Handle the case when phi=Inf and logit transformation => manually set to 1
+            if strcmp(y.randomEffects.transformation{k},'exp(phi)./(1+exp(phi))'),
+                psi(isnan(psi)) = 1;
+            end
+        end
+        
+        % Check if some issues with the sampled parameters (should not lead to complex values)
+        if isempty(find(imag(psi) ~=0)),
+            break;
+        else
+            % Rerun sampling since problem with population parameter sampling
+        end
+    end
+    % Define output variable
+    output                              = [];
+    output.parameterNames               = y.fixedEffects.names;
+    output.FLAG_SAMPLE                  = FLAG_SAMPLE;
+    output.Nsamples                     = Nsamples;
+    output.parameterValuesPopulation    = psi;    
+    output.parameterValuesIndividual    = [];
+    
+elseif FLAG_SAMPLE == 5,
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Handle special case of FLAG_SAMPLE=5
+    % - Sampling Nsamples population parameters from uncertainty distribution
+    % - Including covariate effect on sampled population parameters
+    %   Need to provide Nsamples number of covariate values
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    
+    FLAG_SAMPLE_POPULATIONPARAM = 1;
+    
+    % Run sampling function once just to get the number of parameters to sample
+    y = sampleMONOLIXpopulationParametersSBPOP(x,0,1);
+
+    % Initialize the matrix with the parameter values (number of parameters needed for that)
+    mu = zeros(Nsamples,length(y.fixedEffects.names));
+
+    % Need to sample until reasonable values (no imaginary parts in parameters)
+    while 1,
+
+        % Get Nsamples sets of population parameters from uncertainty distribution
+        for k0=1:Nsamples,
+            % Sample
+            y = sampleMONOLIXpopulationParametersSBPOP(x,FLAG_SAMPLE_POPULATIONPARAM,1);
+            mu(k0,:) = y.fixedEffects.values;
+        end
+
+        % Transform
+        for k=1:length(y.randomEffects.inv_transformation),
+            mu(:,k) = eval(strrep(y.randomEffects.inv_transformation{k},'psi',sprintf('mu(:,%d)',k)));
+        end
+        
+        % Determine normally distributed phi - without eta and covariate contribution: phi = mu (+ eta)  (+ beta*t_cov + beta_cat)
+        phi = mu;
+        
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        % Determine and add effect of continuous covariates to phi: phi = mu (+ eta) + t_cov*beta  (+ beta_cat)
+        % Without eta contribution
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        if ~isempty(covNames),
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Determine the beta matrix
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Get parameter names of estimates
+            paramNames = y.fixedEffects.names;
+            % Initialize the beta matrix
+            beta = zeros(length(covNames),length(paramNames));
+            % Fill the beta matrix
+            for k1=1:length(covInfo),
+                paramName = covInfo(k1).parameter;
+                ix_j = strmatchSB(paramName,paramNames,'exact');
+                for k2=1:length(covInfo(k1).covariates),
+                    covname     = covInfo(k1).covariates{k2};
+                    beta_ij     = covInfo(k1).values(k2);
+                    ix_i        = strmatchSB(covname,covNames,'exact');
+                    % Fill beta_ij value into beta matrix
+                    beta(ix_i,ix_j) = beta_ij;
+                end
+            end
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Add t_cov*beta to phi
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            phi = phi + t_cov*beta;
+        end
+        
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        % Determine and add effect of categorical covariates to phi: phi = mu + eta + beta*t_cov + beta_cat
+        % One beta_cat matrix for each parameter/covariate combination!
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        if ~isempty(catNames),
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Determine the beta_cat matrix
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Get parameter names of estimates
+            paramNames = y.fixedEffects.names;
+            % Initialize the beta_cat matrix (Nsamples x Nparameters)
+            beta_cat = {};
+            % Determine the beta_cat matrices
+            for k1=1:length(catInfo),
+                paramName = catInfo(k1).parameter;
+                ix_j = strmatchSB(paramName,paramNames,'exact');
+                for k2=1:length(catInfo(k1).covariates),
+                    % Initialize parameter/covariate dependent beta_cat matrix
+                    beta_cat_cov = zeros(Nsamples,length(paramNames));
+                    % Get categorical cov name and index
+                    catname     = catInfo(k1).covariates{k2};
+                    ix_i        = strmatchSB(catname,catNames,'exact');
+                    if ~isempty(ix_i),
+                        % Fill the beta_cat_cov matrix
+                        categories_user = catValues(:,ix_i);
+                        categories_model = catInfo(k1).information(k2).categories;
+                        categories_values = catInfo(k1).information(k2).values;
+                        % Initialize values
+                        values = NaN(size(categories_user));
+                        for kkk=1:length(categories_model),
+                            ix = categories_user==categories_model(kkk);
+                            values(ix) = categories_values(kkk);
+                        end
+                        % Check if values contains NaN, then error and inform the user
+                        if ~isempty(find(isnan(values), 1)),
+                            error('Categorical covariate "%s" contains user provided category that has not been used for model building.',catname);
+                        end
+                        % Assign values
+                        beta_cat_cov(:,ix_j) = values;
+                    end
+                    beta_cat{end+1} = beta_cat_cov;
+                end
+            end
+            
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Add beta_cat to phi
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            for k1=1:length(beta_cat),
+                phi = phi + beta_cat{k1};
+            end
+        end
+        
+        % Back transform individual parameters (each column one parameter)
+        psi = [];
+        for k=1:size(phi,2),
+            transform_string = strrep(y.randomEffects.transformation{k},'phi',sprintf('phi(:,%d)',k));
+            psi(:,k) = eval(transform_string);
+            % Handle the case when phi=Inf and logit transformation => manually set to 1
+            if strcmp(y.randomEffects.transformation{k},'exp(phi)./(1+exp(phi))'),
+                psi(isnan(psi)) = 1;
+            end
+        end
+        
+        % Check if some issues with the sampled parameters (should not lead to complex values)
+        if isempty(find(imag(psi) ~=0)),
+            break;
+        else
+            % Rerun sampling since problem with population parameter sampling
+        end
+    end
+    % Define output variable
+    output                              = [];
+    output.parameterNames               = y.fixedEffects.names;
+    output.FLAG_SAMPLE                  = FLAG_SAMPLE;
+    output.Nsamples                     = Nsamples;
+    output.parameterValuesPopulation    = psi;    
+    output.parameterValuesIndividual    = [];
+    
+end
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/auxiliary/isMONOLIXfitSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/auxiliary/isMONOLIXfitSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..d582a428919e25ca605d42e8a4ae9a0efdceb0f0
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/auxiliary/isMONOLIXfitSBPOP.m
@@ -0,0 +1,14 @@
+function [ output ] = isMONOLIXfitSBPOP( projectPath )
+% isMONOLIXfitSBPOP: Checks if provided path contains a MONOLIX project
+% output = 0: no MONOLIX project
+% output = 1: MONOLIX project
+% Decision rule: project.mlxtran is present in the projectPath
+
+testfile = fullfile(projectPath,'project.mlxtran');
+if ~exist(testfile),
+    output = 0;
+else
+    output = 1;
+end
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/auxiliary/other/fitanalysisETAvsCOVmonolixSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/auxiliary/other/fitanalysisETAvsCOVmonolixSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..f1aad89932596dfe54d9c41ef7ddf564c960892a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/auxiliary/other/fitanalysisETAvsCOVmonolixSBPOP.m
@@ -0,0 +1,246 @@
+function [] = fitanalysisETAvsCOVmonolixSBPOP(data,projectPath,covNames,catNames,options)    
+% fitanalysisETAvsCOVmonolixSBPOP: Called by SBPOPfitanalysisETAvsCOV - same calling syntax.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle varargins
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try corrcoeffThreshold = options.corrcoeffThreshold; catch, corrcoeffThreshold = 0.3; end
+try filename = options.filename; catch, filename = ''; end
+try withlabels = options.labels; catch, withlabels = 0; end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check cov and catnames
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+datanames = get(data,'VarNames');
+for k=1:length(covNames),
+    if isempty(strmatchSB(covNames{k},datanames,'exact')), error('The dataset does not contain the covariate ''%s''.',covNames{k}); end    
+end
+for k=1:length(catNames),
+    if isempty(strmatchSB(catNames{k},datanames,'exact')), error('The dataset does not contain the covariate ''%s''.',catNames{k}); end    
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Construct RESULTS path
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+resultsPath = [projectPath '/RESULTS'];
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check the projectPath
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~exist(resultsPath),
+    error(sprintf('The provided project path "%s" does not point to a valid SBPOP/Monolix project.\nPlease make sure a "RESULTS" folder is in the provided path.',projectPath));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check that indiv_eta.txt is present in the RESULTS folder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+indiv_eta_file = [resultsPath '/indiv_eta.txt'];
+if ~exist(indiv_eta_file)
+    error('The "indiv_eta.txt" file does not exist in the RESULTS folder.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Load eta file
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+indiv_eta   = SBPOPloadNONCSVdataset([resultsPath '/indiv_eta.txt']);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Remove duplicate lines from indiv_eta dataset
+% (in case there was inter-occasion variability)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% indiv_eta.flag = zeros(size(indiv_eta,1),1);
+% for i=1:size(indiv_eta,1)-1
+%     if(double(indiv_eta(i,:)) == double(indiv_eta(i+1,:)))
+%         indiv_eta.flag(i+1) = 1;
+%     end
+% end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine random effect estimates for shrinkage determination
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+x = parseMONOLIXresultsSBPOP(projectPath);
+y = sampleMONOLIXpopulationParametersSBPOP(x,0,1);
+OMEGA       = y.randomEffects.values;
+OMEGAnames  = y.randomEffects.names;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get eta modes
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dataeta = dataset();
+dataeta.ID = indiv_eta.ID;
+for k=1:length(OMEGAnames),
+    dataeta.(OMEGAnames{k}) = indiv_eta.(['eta_' OMEGAnames{k} '_mode']);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Remove the non estimated omegas/etas
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ix =  find(sum(abs(double(dataeta(:,2:end)))) ~= 0);
+dataeta_est                 = dataeta(:,[1 ix+1]);
+OMEGAnames_est              = OMEGAnames(ix);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get the continuous covariates - transformed or not from indiv_eta
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+datacovs = dataset();
+datacovs.ID = indiv_eta.ID;
+varnames = get(indiv_eta,'VarNames');
+for k=1:length(covNames),
+    ix = strmatchSB(covNames{k},varnames,'exact');
+    covname = covNames{k};
+    if isempty(ix),
+        ix = strmatchSB(['t_' covNames{k}],varnames,'exact');
+        covname = ['t_' covNames{k}];
+    end
+    if isempty(ix),
+        error('Trouble finding the right covariate - check!');
+    end
+    datacovs.(covname) = indiv_eta.(covname);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get the categorical covariates for same IDs as in the dataeta_est
+% This only works correclty if no transformation has been done in Monolix
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+allIDeta = unique(dataeta_est.ID);
+datacats = dataset();
+dataeta_cats = dataset(); % eta dataset in case when there is iov and each occasion has a repeated entry in dataeta_est
+for k=1:length(allIDeta),
+    datak = data(data.ID==allIDeta(k),:);
+    datacatsk = dataset();
+    datacatsk.ID = allIDeta(k);
+    datak_etas = dataeta_est(dataeta_est.ID == allIDeta(k),:);
+    for k2=1:length(catNames),
+        datacatsk.(catNames{k2}) = datak.(catNames{k2})(1);
+    end
+    datacats = [datacats; datacatsk];
+    dataeta_cats = [dataeta_cats; datak_etas(1,:)]; % this avoids duplicate lines when iov
+end
+dataeta_cats.ID = []; % we don't need the id column
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Interface to old code ;-)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+etas = dataeta_est(:,2:end);
+covs = datacovs(:,2:end);
+cats = datacats(:,2:end);
+nretas = size(etas,1);
+nrcovs = size(covs,1);
+nrcats = size(cats,1);
+etaNames = get(etas,'VarNames');
+covNames = get(covs,'VarNames');
+catNames = get(cats,'VarNames');
+ids = datacovs.ID;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine subplot organization
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+Neta = length(etaNames);
+nrow = ceil(sqrt(Neta));
+ncol = ceil(Neta/nrow);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% If filename then remove old file
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(filename),
+    startNewPrintFigureSBPOP(filename);
+    % also create path if not yet created
+    [p,f,e] = fileparts(filename);
+    warning off
+    mkdir(p);
+    warning on
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% First handle continuous covariates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Cycle through covariates and produce on figure per covariate
+% The etas in subplots
+for k=1:size(covs,2),
+    cov = double(covs(:,k));
+    % New figure
+    h = figure;
+    set(h,'Name',['Covariate: ' covNames{k}])
+    for k2=1:size(etas,2),
+        name = etaNames{k2};
+        eta = double(etas(:,k2));
+        subplot(nrow,ncol,k2);
+        [cc,pp] = corrcoef([cov,eta]);
+        cc = cc(1,2);
+        pp = pp(1,2);
+        if abs(cc) > corrcoeffThreshold,            
+            plot(cov,eta,'.r','MarkerSize',20); hold on
+            if(withlabels)
+                labels1 = cellstr( num2str(ids, '%d') );
+                text(cov, eta, labels1, 'VerticalAlignment','bottom', 'HorizontalAlignment','right', 'FontSize', 8)
+            end
+        else
+            plot(cov,eta,'.b','MarkerSize',20); hold on
+            if(withlabels)
+                labels1 = cellstr( num2str(ids, '%d') );
+                text(cov, eta, labels1, 'VerticalAlignment','bottom', 'HorizontalAlignment','right', 'FontSize', 8)
+            end
+        end
+
+        % Remove the potential NaN things
+        covreg          = cov;
+        ixNaN           = find(isnan(covreg));
+        covreg(ixNaN)   = [];
+        etareg          = eta;
+        etareg(ixNaN)   = [];
+        % Add linear regression result
+        X = [ones(size(covreg)) covreg];
+        
+        try
+            b = regress(etareg,X); % Removes NaN data
+            x = get(gca,'XLim');        
+            plot(x, b(1)+b(2)*x,'k--','LineWidth',2)
+            % Title etc.
+            title(['Corr. coeff.: ' sprintf('%1.2g (p=%1.2g)',cc,pp)],'Interpreter','None');
+        catch
+        end
+        
+        xlabel(covNames{k},'Interpreter','None')
+        ylabel(['eta_' etaNames{k2}],'Interpreter','None')
+    end
+    set(h,'Color',[1 1 1]);
+    if ~isempty(filename),
+        printFigureSBPOP(gcf,filename);
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Second handle categorical covariates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
+% Cycle through covariates and produce on figure per covariate
+% The etas in subplots
+for k=1:size(cats,2),
+    cat = double(cats(:,k));
+    catunique = unique(cat);
+    % New figure
+    h = figure;
+    set(h,'Name',['Covariate: ' catNames{k}]);
+    for k2=1:size(etas,2),
+        name = etaNames{k2};
+        eta = double(dataeta_cats(:,k2));
+        subplot(nrow,ncol,k2);
+        SBPOPboxplot([5 95],0,eta,cat,'orientation','horizontal');
+        plotZeroLim = get(gca,'YLim');
+        hold on;
+        plot([0 0],plotZeroLim,'--k')
+        xlabel(['eta_' etaNames{k2}],'Interpreter','None')
+        ylabel(catNames{k},'Interpreter','None')
+    end
+    set(h,'Color',[1 1 1]);    
+    if ~isempty(filename),
+        printFigureSBPOP(gcf,filename);
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PS2PDF
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(filename),
+    convert2pdfSBPOP(filename);
+    close all;
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/auxiliary/other/parseMONOLIXetasSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/auxiliary/other/parseMONOLIXetasSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..867364ab77ead935a39e22cfbe326c612269f18a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/auxiliary/other/parseMONOLIXetasSBPOP.m
@@ -0,0 +1,44 @@
+function [ dataeta, OMEGA, OMEGAnames ] = parseMONOLIXetasSBPOP( projectPath )
+% parseMONOLIXetasSBPOP: Parses a MONOLIX project and returns the ETAs.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Construct RESULTS path
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+resultsPath = [projectPath '/RESULTS'];
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check the projectPath
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~exist(resultsPath),
+    error(sprintf('The provided project path "%s" does not point to a valid SBPOP/Monolix project.\nPlease make sure a "RESULTS" folder is in the provided path.',projectPath));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check that indiv_eta.txt is present in the RESULTS folder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+indiv_eta_file = [resultsPath '/indiv_eta.txt'];
+if ~exist(indiv_eta_file)
+    error('The "indiv_eta.txt" file does not exist in the RESULTS folder.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine random effect estimates for shrinkage determination
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+x = parseMONOLIXresultsSBPOP(projectPath);
+y = sampleMONOLIXpopulationParametersSBPOP(x,0,1);
+OMEGA       = y.randomEffects.values;
+OMEGAnames  = y.randomEffects.names;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Load eta file
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+indiv_eta   = SBPOPloadNONCSVdataset([resultsPath '/indiv_eta.txt']);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get eta modes
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dataeta = dataset();
+for k=1:length(OMEGAnames),
+    dataeta.(OMEGAnames{k}) = indiv_eta.(['eta_' OMEGAnames{k} '_mode']);
+end
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/auxiliary/other/parseMONOLIXindivparamSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/auxiliary/other/parseMONOLIXindivparamSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..91b0babeec878a848613f18271c6b457f4dcf111
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/auxiliary/other/parseMONOLIXindivparamSBPOP.m
@@ -0,0 +1,9 @@
+function [ indiv_param ] = parseMONOLIXindivparamSBPOP( projectPath,numberParameters )
+% parseMONOLIXindivparamSBPOP: Returns the individual parameters from a
+% MONOLIX fit. numberParameters needs to be provided to know how many they
+% are, since this can change depending on the settings.
+
+indiv_param             = SBPOPloadNONCSVdataset([projectPath '/RESULTS/indiv_parameters.txt']);
+indiv_param             = indiv_param(:,1:numberParameters+1);
+% Remove the _mode thing
+indiv_param = set(indiv_param,'VarNames',strrep(get(indiv_param,'VarNames'),'_mode',''));
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/auxiliary/other/parseMONOLIXpredictionsSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/auxiliary/other/parseMONOLIXpredictionsSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..144e42d3453c82715d47cf4748722c0a8c6c933c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/auxiliary/other/parseMONOLIXpredictionsSBPOP.m
@@ -0,0 +1,41 @@
+function [ predictions ] = parseMONOLIXpredictionsSBPOP( projectPath,outputNumber )
+% parseMONOLIXpredictionsSBPOP: Parses a NONMEM project and returns the 
+% predictions for a given output number.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Construct RESULTS path
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+resultsPath = [projectPath '/RESULTS'];
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check the projectPath
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~exist(resultsPath),
+    error(sprintf('The provided project path "%s" does not point to a valid SBPOP/Monolix project.\nPlease make sure a "RESULTS" folder is in the provided path.',projectPath));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check that predictions.txt or predictions<outputNumber>.txt is present in the RESULTS folder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+predictions_file = [resultsPath '/predictions' num2str(outputNumber) '.txt'];
+if ~exist(predictions_file)
+    if outputNumber == 1,
+        % Check if predictions.txt is present
+        if ~exist([resultsPath '/predictions.txt']),
+            error('The "%s" or "predictions.txt" file for output "%d" does not exist in the RESULTS folder.',predictions_file,outputNumber);
+        else
+            % It does exist - rename predictions_file
+            predictions_file = [resultsPath '/predictions.txt'];
+        end
+    else
+        error('The "%s" file for output "%d" does not exist in the RESULTS folder.',predictions_file,outputNumber);
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Load predictions file
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+predictions = SBPOPloadNONCSVdataset(predictions_file);
+
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/auxiliary/parseMONOLIXresultsSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/auxiliary/parseMONOLIXresultsSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..e13cec5b23367579fdb54ad28161281df099e691
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/auxiliary/parseMONOLIXresultsSBPOP.m
@@ -0,0 +1,550 @@
+function [ output ] = parseMONOLIXresultsSBPOP( path_to_monolix_project_folder )
+% [DESCRIPTION]
+% This function parses the output of Monolix and returns all information in a structure
+%
+% [SYNTAX]
+% output = parseMONOLIXresultsSBPOP( path_to_monolix_project_folder )
+%
+% [INPUT]
+% path_to_monolix_project_folder: path to the Monolix project folder. It is assumed that the results of the estimation
+%                                 (pop_parameters.txt, results.mat) are stored in a "RESULTS" folder within this
+%                                 project folder.
+%
+% [OUTPUT]
+% Structure with the following fields:
+%
+% output.path                         : path from which the results are read (project folder+RESULTS)
+% output.parameters                   : a structure with all parameter information
+% output.parameters.names             : cell-array with the parameter names
+% output.parameters.values            : vector with estimated values
+% output.parameters.stderrors         : vector with standard errors of estimation
+% output.parameters.correlationmatrix : full correlation matrix for estimates
+% output.parameters.FLAGestimated     : vector with flags 1 if estimated, 0 if not estimated
+% output.parameters.covariancematrix  : full covariance matrix for parameter estimates, determined
+%                                       from correlationmatrix and standard errors
+% output.objectivefunction            : structure with the values for the log-likelihood, AIC and BIC for
+%                                       both linearization and importance sampling. NaN if not determined
+% output.residualerrormodels          : cell-array with the aliases of the residual error models in the order 
+%                                       of the outputs, as defined in the MLXTRAN models
+% output.trans_randeffects            : a cell-array with the transformation of the random effects 
+% output.inv_trans_randeffects        : a cell-array with the inverse transformation of the random effects
+%
+% output.MONOLIXresultStruct          : full MONOLIX structure from the results.mat file for futher processing
+%
+% [ASSUMPTIONS]
+% String assumptions about the structure and syntax of the pop_parameters.txt file were made.
+% Need to reassess when new functions of Monolix arrive.
+%
+% [AUTHOR]
+% Marco Garieri & Henning Schmidt
+%
+% [DATE]
+% 17.08.2011
+%
+% [PLATFORM]
+% MATLAB R2009a
+%
+% [KEYWORDS]
+% MONOLIX, results, parsing
+% 
+% [TOOLBOXES USED]
+% NONE
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if folder exists and that RESULTS folder exists within
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if exist(path_to_monolix_project_folder) ~= 7,
+    error('The specified Monolix project folder "%s" does not exist.',path_to_monolix_project_folder);
+end
+path_to_monolix_project_folder = [path_to_monolix_project_folder '/RESULTS'];
+if exist(path_to_monolix_project_folder) ~= 7,
+    error('The "RESULTS" folder within the project folder "%s" does not exist.',path_to_monolix_project_folder);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check availability of required files in specified folder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if exist(fullfile(path_to_monolix_project_folder, 'pop_parameters.txt')) ~= 2, 
+    error('Please check if the "%s" folder contains the ''pop_parameters.txt'' file.',path_to_monolix_project_folder);
+end
+if exist(fullfile(path_to_monolix_project_folder, 'results.mat')) ~= 2, 
+    error('Please check if the "%s" folder contains the ''results.mat'' file.',path_to_monolix_project_folder);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Load pop_parameters.txt (results.mat file is loaded later)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+content = fileread(fullfile(path_to_monolix_project_folder, 'pop_parameters.txt'));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Parse parameters, standard errors and correlations
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% If there is an estimation by groups, I change the name in GROUPS
+% It helps to parse the file
+content = strrep(content,'Estimation of the population parameters by groups', 'GROUPS');
+
+% Define output structure
+output.type = 'MONOLIX';
+output.path = path_to_monolix_project_folder;
+output.parameters.names = {};
+output.parameters.values = [];
+output.parameters.stderrors = [];
+output.parameters.correlationmatrix = [];
+output.parameters.FLAGestimated = [];
+output.objectivefunction.OBJ = [];
+output.objectivefunction.AIC = [];
+output.objectivefunction.BIC = [];
+output.residualerrormodels = {};
+output.trans_randeffects = {};
+output.inv_trans_randeffects = {};
+output.MONOLIXresultStruct = [];
+
+% Remove 13s
+dc = double(content); dc(dc==13) = []; content = char(dc);
+% Remove curly brackets in case the is more than one Error Model
+dc = double(content); dc(dc==123) = []; dc(dc==125)=[]; content=char(dc);
+
+% Get start of population parameter estimates
+% There might be more than one instance ... take last
+searchstring = 'Estimation of the population parameters';
+ix = strfind(content,searchstring);
+content = content(ix(end):end);
+
+% Get start of correlation matrices of estimates and of parameters 
+searchstring = 'correlation matrix of the estimates';
+ix = strfind(content,searchstring);
+if ~isempty(ix)
+    contentparam   = content(1:ix(end)-1);
+    contentcorrest = content(ix(end):end);
+else
+    % There is no correalation matrix
+    searchstring1 = 'The F.I.M was not correctly estimated';
+    ix1 = strfind(content,searchstring1);
+    if ~isempty(ix1)
+        contentparam = content(1:ix1(end)-1);
+        contentcorrest = content(ix1(1):end);
+    else
+        % We did not try to have and estimation of the FIM
+        searchstring2 = 'GROUPS';
+        ix2 = strfind(content,searchstring2);
+        if ~isempty(ix2)
+            contentparam = content(1:ix2(1)-1);
+        else
+            contentparam = content;
+        end
+        contentcorrest = [];
+        contentLL = [];
+    end
+end
+
+% Remove first lines until line break
+dc = double(contentparam); ix = find(dc==10); contentparam = strtrim(contentparam(ix(1)+1:end));
+if ~isempty(contentcorrest)
+    dc = double(contentcorrest); ix = find(dc==10); contentcorrest = strtrim(contentcorrest(ix(1)+1:end));
+end
+
+% Separate parameters and IIV correlation matrix (if it is present)
+% We do not need this matrix, so we can remove it
+searchstring = 'correlation matrix (IIV)';
+ix = strfind(contentparam,searchstring);
+if ~isempty(ix),
+    contentparam = contentparam(1:ix(1)-1);
+end
+
+% Separate everything below the last Eigenvalues statement and we already
+% divide the LL part
+if ~isempty(contentcorrest),
+    searchstring = 'Eigenvalues';
+    ix = strfind(contentcorrest, searchstring);
+    % Case where there are the correlation matrices
+    if ~isempty(ix)
+        contentLL = contentcorrest(ix(end):end);
+        contentcorrest = contentcorrest(1:ix(end)-1);
+        searchstring1 = 'Log-likelihood Estimation';
+        ix1 = strfind(contentLL,searchstring1);
+        % Case where there is also the LL 
+        if ~isempty(ix1)
+            contentLL = contentLL(ix1(1):end);
+        % Case where there is no LL
+        else
+            contentLL = [];
+        end
+    % Case where there are no correlation matrices;
+    else
+        searchstring1 = 'Log-likelihood Estimation';
+        ix1 = strfind(contentcorrest,searchstring1);
+        % Case where there is LL
+        if ~isempty(ix1)
+            contentLL = contentcorrest(ix1(1):end);
+            contentcorrest = [];
+        % No correlation matrices and no LL, only GROUPS
+        else
+            contentcorrest = [];
+            contentLL = [];
+        end
+    end
+end
+
+% Parse population parameters: names, values, standard errors
+% Remove first line (e.g.: parameter     s.e. (lin)   r.s.e.(%) )
+dc = double(contentparam); ix = find(dc==10); contentparam = strtrim(contentparam(ix(1)+1:end));
+% Remove "_____" if present
+contentparam = strtrim(regexprep(contentparam,'\n[_]+',''));
+% Remove ":"
+contentparam = strrep(contentparam,':',' ');
+% Several spaces to one space but keep single linebreaks
+contentparam = regexprep(contentparam,'[\n]*','$$$');
+contentparam = regexprep(contentparam,'[\s]+',' ');
+contentparam = regexprep(contentparam,'\$\$\$','\n');
+% Set the non-estimated standard errors to Inf to distinguish them from problems with estimation of standard errors
+% Handled later in this code where they are set to zero and the problematic SEs are kept on NaN.
+contentparam = strrep(contentparam,' - ',' Inf ');
+% Loop through the rows and load the information
+paramnames = {};
+paramvalues = [];
+paramstderrors = [];
+terms = explodePCSB(contentparam,char(10));
+for k=1:length(terms),
+    % explode by spaces
+    terms2 = explodePCSB(terms{k},' ');
+    % get name
+    paramnames{end+1} = terms2{1};
+    % get values
+    paramvalues(end+1) = str2double(terms2{2});
+    % get standard errors if exist
+    if length(terms2)>2
+        paramstderrors(end+1) = str2double(terms2{3});
+    else
+        paramstderrors(end+1) = Inf;
+    end
+end
+
+% Handle stupidly changing names in Monolix (between versions)
+% Replace () and , to _ ... now only in correlations
+paramnames = strrep(paramnames,'(','_');
+paramnames = strrep(paramnames,',','_');
+paramnames = strrep(paramnames,')','');
+
+% Assign results to output structure
+output.parameters.names = paramnames;
+output.parameters.values = paramvalues;
+output.parameters.stderrors = paramstderrors;
+
+% Parse correlation matrices only if they exist!!!
+% Split into parts based on searchstring
+if ~isempty(contentcorrest)
+    searchstring = 'Eigenvalues';
+    ix = [1 strfind(contentcorrest,searchstring) length(contentcorrest)];
+    corrparts = {};
+    for k=1:length(ix)-1,
+        corrparts{k} = strtrim(contentcorrest(ix(k):ix(k+1)-1));
+        % Remove first lines if k~=1
+        % (e.g.: Eigenvalues (min, max, max/min): 0.48  1.5  3.2)
+        if k>1,
+            dc = double(corrparts{k}); 
+            ix2 = find(dc==10); 
+            corrparts{k} = strtrim(corrparts{k}(ix2(1):end));
+        end
+    end
+
+    % Parse correlation matrices from text into matrix
+    % Need to store the names also
+    corrnames = {};
+    corrmatrices = {};
+    for k=1:length(corrparts),
+        textmatrix = corrparts{k};
+        % get size
+        N = length(find(double(textmatrix)==10))+1;
+        % Initialize matrix
+        matrix = zeros(N);
+        % Run through matrix rows and get values
+        terms = explodePCSB(textmatrix,char(10));
+        for k2=1:length(terms),
+            % Exchange multiple spaces for single space
+            row = regexprep(terms{k2},'[\s]*',' ');
+            % Explode by space
+            terms2 = explodePCSB(row,' ');
+            % Get name 
+            corrnames{end+1} = terms2{1};
+            % Get values
+            for k3=2:length(terms2),
+                matrix(k2,k3-1) = str2double(terms2{k3});
+                matrix(k3-1,k2) = str2double(terms2{k3});
+            end
+        end
+        corrmatrices{k} = matrix;
+    end
+
+    % Build full correlation matrix (blockdiagonal)
+    % based on ordering in the correlation matrices (reordering done later)
+    corrmatrix = blkdiag(corrmatrices{:});
+
+    % Finally, we need to reorder either the parameters or permutate the correlation matrix to 
+    % bring it into the same order of parameter names
+    % Also we need to handle the fact that non-estimated random effects are not included in the 
+    % correlation matrix, so we need to add them as uncorrelated
+
+    % Step 1: Identify parameters for which no correlations exist and add them into the correlation matrix at the end
+    param2add2corrmatrix = setdiff(output.parameters.names,corrnames);
+    % Add them to names
+    corrnames = [corrnames param2add2corrmatrix];
+    % Add them to block correlation matrix (add identity mnatrix at the end with size of added parameter names)
+    corrmatrix = blkdiag(corrmatrix,eye(length(param2add2corrmatrix)));
+
+    % Step 2: Reorder the parameter names so that estimated values do match the estimated correlations
+    % Determine the permutation order
+    ix = [];
+    for k=1:length(output.parameters.names),
+        ixk = strmatchSB(output.parameters.names{k},corrnames,'exact');
+        if length(ixk) > 1,
+            error('Problem with parameter ''%s'': it seems to be defined more than once in the estimation result.',output.parameters.names{k});
+            % Might happen is someone uses a,b,c,d as parameter value in the model, since names also used for the residual error model parameters
+        end
+        ix(k) = ixk;
+    end
+    % Do the permutation:
+    corrnames = corrnames(ix);
+    corrmatrix = corrmatrix(ix,ix);
+else
+    corrmatrix = [];
+end
+% Assign results to output structure
+output.parameters.correlationmatrix = corrmatrix;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add additional information to the output structure and change some values
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add flag: FLAGestimated: 0=estimated, 1=not estimated (fixed)
+% Defined by NaN values in the standard errors
+output.parameters.FLAGestimated = ~isinf(output.parameters.stderrors);
+% Set not estimated standard errors from Inf to 0 (not estimated defined now by flag)
+output.parameters.stderrors(isinf(output.parameters.stderrors)) = 0;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine the covariance matrix for the parameters (inverse FIM) only if
+% the FIM was estimated
+% Store it in the output structure
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%% MARCO: It is correct how is done here, otherwise it is possible to
+%%%%        compute in the following way:                       
+%%%%            D = diag(se);
+%%%%            covariancematrix = D*corr*D;
+%%%%        (But it is less efficient, because of the double matrix
+%%%%         multiplication, and it matters when we have huge corr matrices)
+
+corr = output.parameters.correlationmatrix;
+if ~isempty(corr)
+    se = output.parameters.stderrors;
+    sigma = se'*se;
+    covariancematrix = corr.*sigma;
+    output.parameters.covariancematrix = covariancematrix;
+else
+    output.parameters.covariancematrix = [];
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Load results.mat for all the information that we need.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+r = load(fullfile(path_to_monolix_project_folder, 'results.mat'));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Read the loglikelihood information if available
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(contentLL)
+    % by linearization
+    searchstring = 'Log-likelihood Estimation by linearization';
+    ixlin = strfind(contentLL,searchstring);
+    if length(ixlin) > 1,
+        error('More than 1 loglikelihood calculations by linearization present in the pop_parameters.txt file. Please check.');
+    end
+    LLlin = NaN;
+    AIClin = NaN;
+    BIClin = NaN;
+    if length(ixlin) == 1,
+        LLlin = (-2)*r.logl_lin;
+        AIClin = r.AIC_lin;
+        BIClin = r.BIC_lin;
+    end
+    % by importance sampling
+    searchstring = 'Log-likelihood Estimation by Imp';
+    ixis = strfind(lower(contentLL),lower(searchstring));
+    if length(ixis) > 1,
+        error('More than 1 loglikelihood calculations by importance sampling present in the pop_parameters.txt file. Please check.');
+    end
+    LLis = NaN;
+    AICis = NaN;
+    BICis = NaN;
+    if length(ixis) == 1,
+        LLis = (-2)*r.logl_is;
+        AICis = r.AIC_is;
+        BICis = r.BIC_is;
+    end
+else
+    LLlin = NaN; AIClin = NaN; BIClin = NaN;
+    LLis = NaN; AICis = NaN; BICis = NaN;
+end
+% We store the information in the structure
+output.objectivefunction.OBJ = NaN;
+output.objectivefunction.AIC = NaN;
+output.objectivefunction.BIC = NaN;
+if ~isnan(LLlin),
+    output.objectivefunction.OBJ = LLlin;
+    output.objectivefunction.AIC = AIClin;
+    output.objectivefunction.BIC = BIClin;
+end    
+if ~isnan(LLis),
+    output.objectivefunction.OBJ = LLis;
+    output.objectivefunction.AIC = AICis;
+    output.objectivefunction.BIC = BICis;
+end    
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Read the results.mat file to obtain information about error model
+% IMPORTANT: with multiple outputs there can be multiple different error models
+% We store them as a cell array of their aliases
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output.residualerrormodels = r.g_str.g_alias;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add information about the transformation of the random effects 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output.trans_randeffects = r.transphi.formula;
+output.inv_trans_randeffects = r.transphi.formula_inv;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add information about the covariates (still needs information about the transformation of the covariates)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output.covariates.names = regexprep(r.cov_names,'\<t_','');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add project and results structure information from MONOLIX to output structure
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output.MONOLIXresultStruct = r;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine additional information
+% Fixed effect parameter values, standard errors, rel std errors
+% Random effect parameter values, standard errors, rel std errors
+% Correlation parameter values, standard errors, rel std errors
+% Covariate parameter values, standard errors, rel std errors
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+paramnames  = output.parameters.names;
+paramvalues = output.parameters.values;
+paramstderr = output.parameters.stderrors;
+FLAGestimated = output.parameters.FLAGestimated;
+
+% Determine indices of omegas
+ix_omega = strmatchSB('omega_',paramnames);
+% Determine indices of correlations
+ix_corr  = strmatchSB('corr_',paramnames);
+% Determine indices of covariates
+ix_cov   = strmatchSB('beta_',paramnames);
+
+% Get random effect names, values, standard errors
+omega_names  = paramnames(ix_omega);
+omega_values = paramvalues(ix_omega);
+omega_stderr = paramstderr(ix_omega);
+omega_rse    = abs(100*(omega_stderr./omega_values));
+omega_rse(omega_stderr==0) = 0;
+omega_estimated = FLAGestimated(ix_omega);
+
+% Get correlation coefficient names, values, standard errors
+corr_names  = paramnames(ix_corr);
+corr_values = paramvalues(ix_corr);
+corr_stderr = paramstderr(ix_corr);
+corr_rse    = abs(100*(corr_stderr./corr_values));
+corr_rse(corr_stderr==0) = 0;
+corr_estimated = FLAGestimated(ix_corr);
+
+% Get covariate coefficient names, values, standard errors
+cov_names  = paramnames(ix_cov);
+cov_values = paramvalues(ix_cov);
+cov_stderr = paramstderr(ix_cov);
+cov_rse    = abs(100*(cov_stderr./cov_values));
+cov_rse(cov_stderr==0) = 0;
+cov_estimated = FLAGestimated(ix_cov);
+
+% Remove handled elements from all results to take care of rest
+paramnames([ix_omega(:);ix_corr(:);ix_cov(:)]) = [];
+paramvalues([ix_omega(:);ix_corr(:);ix_cov(:)]) = [];
+paramstderr([ix_omega(:);ix_corr(:);ix_cov(:)]) = [];
+FLAGestimated([ix_omega(:);ix_corr(:);ix_cov(:)]) = [];
+
+% Get fixed effect results
+ix_fixed = 1:length(omega_names);
+fixed_names  = paramnames(ix_fixed);
+fixed_values = paramvalues(ix_fixed);
+fixed_stderr = paramstderr(ix_fixed);
+fixed_rse    = abs(100*(fixed_stderr./fixed_values));
+fixed_rse(fixed_stderr==0) = 0;
+fixed_estimated = FLAGestimated(ix_fixed);
+
+% Add to output
+output.rawParameterInfo.fixedEffects.names      = fixed_names;
+output.rawParameterInfo.fixedEffects.values     = fixed_values;
+output.rawParameterInfo.fixedEffects.stderr     = fixed_stderr;
+output.rawParameterInfo.fixedEffects.rse        = fixed_rse;
+output.rawParameterInfo.fixedEffects.estimated  = fixed_estimated;
+
+output.rawParameterInfo.randomEffects.names     = omega_names;
+output.rawParameterInfo.randomEffects.values    = omega_values;
+output.rawParameterInfo.randomEffects.stderr    = omega_stderr;
+output.rawParameterInfo.randomEffects.rse       = omega_rse;
+output.rawParameterInfo.randomEffects.estimated = omega_estimated;
+
+output.rawParameterInfo.correlation.names       = corr_names;
+output.rawParameterInfo.correlation.values      = corr_values;
+output.rawParameterInfo.correlation.stderr      = corr_stderr;
+output.rawParameterInfo.correlation.rse         = corr_rse;
+output.rawParameterInfo.correlation.estimated   = corr_estimated;
+
+output.rawParameterInfo.covariate.names         = cov_names;
+output.rawParameterInfo.covariate.values        = cov_values;
+output.rawParameterInfo.covariate.stderr        = cov_stderr;
+output.rawParameterInfo.covariate.rse           = cov_rse;
+output.rawParameterInfo.covariate.estimated     = cov_estimated;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Finally parse the error model parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+names                                           = output.parameters.names;
+residual_error_names                            = paramnames(length(omega_names)+1:end);
+residual_error_values                           = [];
+residual_error_stderr                           = [];
+residual_error_rse                              = [];
+residual_error_estimated                        = [];
+for k=1:length(residual_error_names),
+    ix = strmatchSB(residual_error_names{k},names,'exact');
+    residual_error_values(end+1)                = output.parameters.values(ix);
+    residual_error_stderr(end+1)                = output.parameters.stderrors(ix);
+    residual_error_estimated(end+1)             = output.parameters.FLAGestimated(ix);
+end
+residual_error_rse                              = 100*residual_error_stderr./residual_error_values;
+
+output.rawParameterInfo.errorParameter.names     = residual_error_names;
+output.rawParameterInfo.errorParameter.values    = residual_error_values;
+output.rawParameterInfo.errorParameter.stderr    = residual_error_stderr;
+output.rawParameterInfo.errorParameter.rse       = residual_error_rse;
+output.rawParameterInfo.errorParameter.estimated = residual_error_estimated;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Fix some things
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output.rawParameterInfo.fixedEffects.names = strrep(output.rawParameterInfo.fixedEffects.names,'_pop','');
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/auxiliary/parseProjectHeaderMONOLIXSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/auxiliary/parseProjectHeaderMONOLIXSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..54b89e663e6c8268652e5f47cefcd9a88619b0f2
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/auxiliary/parseProjectHeaderMONOLIXSBPOP.m
@@ -0,0 +1,54 @@
+function [projectinfo] = parseProjectHeaderMONOLIXSBPOP(projectPath)
+% parseProjectHeaderMONOLIXSBPOP: Parses the project header information from
+% the MONOLIX project and returns it.
+%
+% USAGE:
+% ======
+% projectinfo = parseProjectHeaderMONOLIXSBPOP(projectPath)
+%
+% projectPath:   path to the project.mlxtran MONOLIX project file
+
+% Information:
+% ============
+% Copyright (C) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Check if project.nmctl in project folder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if exist([projectPath '/project.mlxtran']),
+    project = fileread([projectPath '/project.mlxtran']);
+else
+    error('project.mlxtran file could not be found.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get the header
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ixstart = strfind(project,'; ==PROJECT HEADER START===================================================');
+ixend = strfind(project,  '; ==PROJECT HEADER END=====================================================');
+if isempty(ixstart) || isempty(ixend),
+    error('Project header could not be found in project.nmctl file.');
+end
+headertext = strtrim(project(ixstart+75:ixend-1));
+headerterms = explodePCSB(headertext,char(10));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Construct output
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+projectinfo = [];
+for k=1:length(headerterms),
+    eval(['projectinfo.' strrep(strtrim(headerterms{k}(2:end)),'=','=explodePCSB(') ');']);
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/auxiliary/sampleMONOLIXpopulationParametersSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/auxiliary/sampleMONOLIXpopulationParametersSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..68a18f5169d70c7ddc0670d3d32c1622fc975696
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/auxiliary/sampleMONOLIXpopulationParametersSBPOP.m
@@ -0,0 +1,626 @@
+function [ output ] = sampleMONOLIXpopulationParametersSBPOP( input, varargin )
+% [DESCRIPTION]
+% This function uses the output of the parseMONOLIXresultsSBPOP function.
+% It samples once the distributions to obtain population parameters.
+% Then it splits these up into fixed effects, random effects, residual 
+% error models, covariates, IOV.
+%
+% Not everything is handled, but if things are found that can not be handled, 
+% then an error message is shown.
+%
+% Covariate information is parsed. 
+%   Continuous covariates:  no limitation
+%   Categorical covariates: parsed but at the moment identification problems when grouping is 
+%                           used with groups of more than one category (then the names of these 
+%                           categories are unclear). No issue in this function and handled in the
+%                           SBPOPsampleMONOLIXparam function by warning the user.
+%
+% [SYNTAX]
+% output = sampleMONOLIXpopulationParametersSBPOP( input )
+% output = sampleMONOLIXpopulationParametersSBPOP( input, FLAG_SAMPLE )
+% output = sampleMONOLIXpopulationParametersSBPOP( input, FLAG_SAMPLE, FLAG_SILENT )
+%
+% [INPUT]
+% input        : output structure from the parseMONOLIXresultsSBPOP function
+% FLAG_SAMPLE  : 1=sample population parameters from uncertainty distribution (default case)
+%                0=use estimated population parameters and do not consider uncertainty
+% FLAG_SILENT  : 1=do not output any warnings and messages, only errors 
+%                0=do output any warnings and messages, only errors (default)
+%
+% [OUTPUT]
+% Structure with the following fields:
+%
+% output.path                               : the path provided by the user from which Monolix results have been read
+%
+% output.fixedEffects.names                 : cell-array with names of fixed effect parameters
+% output.fixedEffects.values                : vector with sampled values of fixed effect parameters
+%
+% output.randomEffects.names                : cell-array with names of random effect parameters (same as fixed effect param names)
+% output.randomEffects.values               : vector with sampled values of random effect parameters
+% output.randomEffects.covariancematrix     : covariance matrix of random effects
+% output.randomEffects.transformation       : formula of the transformation
+% output.randomEffects.inv_transformation   : inverse of the formula
+% output.randomEffects.correlationmatrix    : correlation matrix of random effects
+% 
+% output.residualErrorModel.alias           : for each output/residual error model one substructure in the order of the outpt numbering. "alias" is a string with the name of the error model
+% output.residualErrorModel.abcr            : vector with 4 elements for the a,b,c,rho parameters. If undefined then NaN
+% output.residualErrorModel.formula         : formula of the transformation
+% 
+% output.covariates.continuous.parameter               : one substructure per parameter. "parameter" is a string with the parameter name
+% output.covariates.continuous.covariates              : cell-array with the covariates on this parameter
+% output.covariates.continuous.information             : cell-array with covariate transformation in formation (categorical:reference group, continuous:transformation formula and centering value)
+% output.covariates.continuous.information.categories  : vector with numerical categories (only numerical ones are accepted)
+% output.covariates.continuous.information.values      : vector with estimated covariate coefficients for each category (same order). Reference group has 0 value
+%                           
+%
+% [ASSUMPTIONS]
+% 
+% [AUTHOR]
+% Marco Garieri & Henning Schmidt 
+%
+% [DATE]
+% 18.08.2011
+%
+% [PLATFORM]
+% MATLAB R2009a
+%
+% [KEYWORDS]
+% MONOLIX, results, parsing
+% 
+% [TOOLBOXES USED]
+% NONE
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+FLAG_SAMPLE = 1;
+FLAG_SILENT = 0;
+if nargin == 2,
+    FLAG_SAMPLE = varargin{1};
+elseif nargin == 3,
+    FLAG_SAMPLE = varargin{1};
+    FLAG_SILENT = varargin{2};
+end    
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define output structure
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output = [];
+output.type                                 = 'MONOLIX';
+output.path                                 = '';
+
+output.fixedEffects.names                   = {};
+output.fixedEffects.values                  = [];   % Vector
+
+output.randomEffects.names                  = {};
+output.randomEffects.values                 = [];   % Vector
+output.randomEffects.covariancematrix       = [];   % Matrix 
+output.randomEffects.transformation          = {};   % cell-array defining the transformation (normal, lognormal, etc.)
+output.randomEffects.inv_transformation      = {};   % cell-array defining the inverse transformation
+
+output.residualErrorModel.alias             = '';   % One substructure per output alias=string
+output.residualErrorModel.abcr              = [];   % Vector with 4 elements (a,b,c,d - parameters in error model)
+output.residualErrorModel.formula           = '';   % Formula of the transformation
+output.residualErrorModel.inv_formula       = '';   % Inverse of the formula if there is a transformation
+output.residualErrorModel.FlagTransf        = 0;    % Flag if there is a transformation or not (t) 0 if there is not, 1 if there is.
+
+output.covariates.continuous.parameter                 = [];   % One substructure per parameter
+output.covariates.continuous.covariates                = {};   % cell array with all covariates
+output.covariates.continuous.values                    = [];   % vector with corresponding values
+output.covariates.continuous.transformation            = {};   % cell-array with covariate transformation: formula and centering value
+
+output.covariates.categorical.parameter                = [];   % One substructure per parameter
+output.covariates.categorical.covariates               = {};   % cell array with all covariates
+output.covariates.categorical.information              = {};   % cell-array with covariate transformation: 
+                                     
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Write the path of the folder with all the results
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output.path = input.path;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Sample ALL parameters from the distribution N-times
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+names      = input.parameters.names;
+values     = input.parameters.values;
+covariance = input.parameters.covariancematrix;
+% Flag to stay (if 1 then stop sampling ... also set to 1 if sampling not feasible (not desired or not possible since no FIM/covariance matrix determined).
+stopSamplingFlag = 0;
+while stopSamplingFlag == 0,
+    if FLAG_SAMPLE,
+        if ~isempty(covariance),
+            samples = mvnrnd(values,covariance);
+        else
+            if ~FLAG_SILENT,
+                disp('The FIM was not estimated => No sampling of population parameters from uncertainty distributions.');
+            end
+            samples = values;
+            % In this case we cannot sample another time
+            stopSamplingFlag = 1;
+        end
+    else
+        samples = values;
+        if ~FLAG_SILENT,
+            disp('No sampling of population parameters from uncertainty distributions.');
+        end
+        stopSamplingFlag = 1;
+    end
+
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Determine the random effects and covariance matrix
+    % (names determined by "omega_" or "omega2_" as prefix and their correlations "corr(" as prefix)
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    ixo = strmatchSB('omega_',names);
+    if ~isempty(ixo),
+        % if they are the standard errors we just stored the values
+        output.randomEffects.names = strrep(names(ixo),'omega_','');
+        output.randomEffects.values = samples(ixo);
+    else
+        ixo = strmatchSB('omega2_',names);
+        output.randomEffects.names = strrep(names(ixo),'omega2_','');
+        % convert variance to standard deviation
+        output.randomEffects.values = sqrt(samples(ixo));
+    end
+    correlationmatrix = eye(length(output.randomEffects.names));
+    % Determine the correlations between random effects and update the correlation matrix
+    ixc = strmatchSB('corr_',names);
+    recorrelationnames = strrep(strrep(names(ixc),'corr_',''),')','');
+    recorrelationvalues = samples(ixc);
+    % Run through the correlations and update the correlation matrix
+    if ~isempty(recorrelationnames)
+        for k=1:length(recorrelationnames),
+            % Find the two correlated things
+            terms = explodePCSB(recorrelationnames{k},'_');
+            ix1 = strmatchSB(terms{1},output.randomEffects.names,'exact');
+            ix2 = strmatchSB(terms{2},output.randomEffects.names,'exact');
+            % Update matrix
+            correlationmatrix(ix1,ix2) = recorrelationvalues(k);
+            correlationmatrix(ix2,ix1) = recorrelationvalues(k);
+        end
+    end
+    var = output.randomEffects.values'*output.randomEffects.values;
+    output.randomEffects.covariancematrix = correlationmatrix.*var;
+    output.randomEffects.correlationmatrix = correlationmatrix;
+  
+    % Check if sampled covariance matrix is positive semi-definite
+    % by checking that all eigenvalues are >=0
+    % Only check if stopSamplingFlag==0
+    eigen = eig(output.randomEffects.covariancematrix);
+    xx = find(eigen<0, 1);
+    if isempty(xx),
+        % positive semi-definite => OK, take it and exit loop
+        stopSamplingFlag = 1;
+    else
+        if stopSamplingFlag ==1,
+            % Only warn when no sampling possible
+            if ~FLAG_SILENT,
+                disp('The covariance matrix of the random effects is not positive semi-definite.');
+            end
+        end
+    end
+end
+% Remove omega_... and corr(... from samples and names
+ix = [ixo' ixc'];
+samples(ix) = [];
+names(ix) = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Second determine the fixed effects
+% In the input structure it has been made sure that all names that appear as fixed effects also appear in random effects
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% Remove "_pop" from names at the end ... some monolix versions add that
+% some others do not add it
+names = regexprep(names,'_pop\>','');
+
+output.fixedEffects.names = output.randomEffects.names;
+% Get the values
+ixfe = [];
+for k=1:length(output.fixedEffects.names),
+    ix = strmatchSB(output.fixedEffects.names{k},names,'exact');
+    output.fixedEffects.values(k) = samples(ix);
+    ixfe = [ixfe ix];
+end
+% Remove fixed effects from samples and names
+samples(ixfe) = [];
+names(ixfe) = [];
+
+% Add the distribution of the random effects to the output
+output.randomEffects.transformation = input.trans_randeffects;
+output.randomEffects.inv_transformation = input.inv_trans_randeffects;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Third get residual error information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+Noutput = length(input.residualerrormodels);
+removeIX = [];
+if Noutput == 1,
+    output.residualErrorModel.alias = input.residualerrormodels{1};
+    output.residualErrorModel.abcr = NaN(1,4);
+    ix = strmatchSB('a',names,'exact'); if ~isempty(ix), output.residualErrorModel.abcr(1) = samples(ix); removeIX = [removeIX ix]; end
+    ix = strmatchSB('b',names,'exact'); if ~isempty(ix), output.residualErrorModel.abcr(2) = samples(ix); removeIX = [removeIX ix]; end
+    ix = strmatchSB('c',names,'exact'); if ~isempty(ix), output.residualErrorModel.abcr(3) = samples(ix); removeIX = [removeIX ix]; end
+    ix = strmatchSB('rho',names,'exact'); if ~isempty(ix), output.residualErrorModel.abcr(4) = samples(ix); removeIX = [removeIX ix]; end
+else
+    for k=1:Noutput,
+        output.residualErrorModel(k).alias = input.residualerrormodels{k};
+        output.residualErrorModel(k).abcr = NaN(1,4);
+        ix = strmatchSB(['a_' num2str(k)],names,'exact'); if ~isempty(ix), output.residualErrorModel(k).abcr(1) = samples(ix); removeIX = [removeIX ix]; end
+        ix = strmatchSB(['b_' num2str(k)],names,'exact'); if ~isempty(ix), output.residualErrorModel(k).abcr(2) = samples(ix); removeIX = [removeIX ix]; end
+        ix = strmatchSB(['c_' num2str(k)],names,'exact'); if ~isempty(ix), output.residualErrorModel(k).abcr(3) = samples(ix); removeIX = [removeIX ix]; end
+        ix = strmatchSB(['rho_' num2str(k)],names,'exact'); if ~isempty(ix), output.residualErrorModel(k).abcr(4) = samples(ix); removeIX = [removeIX ix]; end
+    end
+end
+% Remove the handled elements
+samples(removeIX) = [];
+names(removeIX) = [];
+
+% Save the formula of the function of the residual error.
+for k = 1:Noutput
+    ix = strmatchSB(output.residualErrorModel(k).alias,'const','exact'); if ~isempty(ix), output.residualErrorModel(k).formula = 'abcr(1).*ones(size(f))'; output.residualErrorModel(k).FlagTransf = 0; end
+    ix = strmatchSB(output.residualErrorModel(k).alias,'prop','exact'); if ~isempty(ix), output.residualErrorModel(k).formula = 'abcr(2).*f'; output.residualErrorModel(k).FlagTransf = 0; end
+    ix = strmatchSB(output.residualErrorModel(k).alias,'comb1','exact'); if ~isempty(ix), output.residualErrorModel(k).formula = 'abcr(1) + abcr(2).*f'; output.residualErrorModel(k).FlagTransf = 0; end
+    ix = strmatchSB(output.residualErrorModel(k).alias,'comb2','exact'); if ~isempty(ix), output.residualErrorModel(k).formula = 'sqrt(abcr(1).^2+abcr(2).^2.*(f.^2))'; output.residualErrorModel(k).FlagTransf = 0; end
+    ix = strmatchSB(output.residualErrorModel(k).alias,'propc','exact'); if ~isempty(ix), output.residualErrorModel(k).formula = 'abcr(2).*f.^abcr(3)'; output.residualErrorModel(k).FlagTransf = 0; end
+    ix = strmatchSB(output.residualErrorModel(k).alias,'comb1c','exact'); if ~isempty(ix), output.residualErrorModel(k).formula = 'abcr(1)+abcr(2).*(f.^abcr(3))'; output.residualErrorModel(k).FlagTransf = 0; end
+    ix = strmatchSB(output.residualErrorModel(k).alias,'comb2c','exact'); if ~isempty(ix), output.residualErrorModel(k).formula = 'sqrt(abcr(1).^2+abcr(2).^2.*((f.^2).^abcr(3)))'; output.residualErrorModel(k).FlagTransf = 0; end
+    
+    ix = strmatchSB(output.residualErrorModel(k).alias,'none','exact'); if ~isempty(ix), output.residualErrorModel(k).formula = 'x'; output.residualErrorModel(k).inv_formula = 'x'; output.residualErrorModel(k).FlagTransf = 1; end
+    ix = strmatchSB(output.residualErrorModel(k).alias,'exp','exact'); if ~isempty(ix), output.residualErrorModel(k).formula = 'log(abs(x)+eps)'; output.residualErrorModel(k).inv_formula = 'exp(x)'; output.residualErrorModel(k).FlagTransf = 1; end
+    ix = strmatchSB(output.residualErrorModel(k).alias,'logit','exact'); if ~isempty(ix), output.residualErrorModel(k).formula = 'log( (x+eps)./(1-f+eps))'; output.residualErrorModel(k).inv_formula = '1./(exp(-x)+1)'; output.residualErrorModel(k).FlagTransf = 1; end
+    ix = strmatchSB(output.residualErrorModel(k).alias,'band','exact'); if ~isempty(ix), output.residualErrorModel(k).formula = 'log( (x-const(1)+eps)./(const(2)-x+eps) )'; output.residualErrorModel(k).inv_formula = 'const(1)+(const(2)-const(1))./(exp(-x)+1)'; output.residualErrorModel(k).FlagTransf = 1; end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Fourth get covariate information
+% On one hand just the parameter estimates which are defined by "beta(..." which is easy.
+% On the other hand we need to obtain information about the transformation of the covariates (lets see where we can find this)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ix              = strmatchSB('beta_',names);
+covariates      = strrep(names(ix),'beta_','');
+covariatevalues = samples(ix);
+% Remove the handled elements
+samples(ix)     = [];
+names(ix)       = [];
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle issue in Monolix 4.3.2 and 4.3.3
+% Unfortunately the Monolix developers come up with different ideas version to version again ...
+% ... and typically it does not really make sense ... anyway!
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(covariates),
+    % Handle issues in Monolix 4.3.2 and 4.3.3 ... if no "(" present
+    if isempty(strfind(covariates{k},'(')),
+        ix = strfind(covariates{k},'_');
+        if length(ix) > 1,
+            % 4.3.2: numbers in cat covs are separated by "_"
+            covariates{k}(ix(end-1)) = '(';
+        else
+            % 4.3.3: numbers in cat covs are not separated by "_"
+            covariates{k}(ix(end)) = '(';
+        end
+        covariates{k}(end+1) = ')';
+    end
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Collect information about covariates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+cont_cov_structure = [];
+cat_cov_structure = [];
+if ~isempty(covariates),
+
+    % Separate parameter names and covariates by commata
+    covariates = strrep(covariates,')','');
+    covariates = strrep(covariates,'(',',');
+    
+    % Initialize some data collection structure for covariates
+    cov_structure.names = {};
+    cov_structure.flags = [];
+    cov_structure.functions = {};
+    
+    % Store covariate names
+    cov_structure.names = input.covariates.names;
+
+    % Get Monolix result info 
+    ccc = input.MONOLIXresultStruct;
+
+    % We create the vector of flags - not sure what Marco did here and why but it seems that the flags at the 
+    % end are 0 for categorical and 1 for continuous covariates
+    flags = ccc.ch.options;
+    ix = find(flags==abs(flags)); 
+    flags(ix) = 1;
+    flags(~ismember(1:length(flags),ix)) = 0;
+    cov_structure.flags = flags;
+    
+    % Determine info for categorical and continuous covariates
+    % Reference group for categorical covariates and trasformation formula and centering value for continuous covariates
+    for k = 1:length(flags)
+        if flags(k)==0
+            % Categorical case
+            i = find(ccc.ch.cat.ind==k);
+            cov_structure.functions{k}.values          = ccc.ch.cat.gnames{i}(:)';
+            cov_structure.functions{k}.reference_value = ccc.ch.cat.gnames{i}(ccc.ch.cat.ref(i));
+            cov_structure.functions{k}.groups_ix_value = ccc.ch.cat.groups{i};
+            % Remove elements for empty groups
+            remove_ix = [];
+            for kkk=1:length(cov_structure.functions{k}.groups_ix_value),
+                if isempty(cov_structure.functions{k}.groups_ix_value{kkk}),
+                    remove_ix(end+1) = kkk;
+                end
+            end
+            cov_structure.functions{k}.groups_ix_value(remove_ix) = [];
+            try
+                % Sometimes there are empty field ... sometimes there are empty field in the fields and thus the fields are not empty
+                cov_structure.functions{k}.values(remove_ix) = [];
+            catch
+            end
+        else
+            % Continuos case
+            cov_structure.functions{k}.formula = ccc.ch.functions{k};
+            cov_structure.functions{k}.centervalue = str2double(ccc.ch.const{k});
+        end
+    end
+    
+    % Separate continuous and categorical covariates
+    cont_cov_structure = cov_structure;
+    cat_cov_structure  = cov_structure;
+    ix_contcov = find(cov_structure.flags==1);
+    ix_catcov  = find(cov_structure.flags==0);
+    cont_cov_structure.names(ix_catcov) = [];
+    cont_cov_structure.flags(ix_catcov) = [];
+    cont_cov_structure.functions(ix_catcov) = [];
+    cat_cov_structure.names(ix_contcov) = [];
+    cat_cov_structure.flags(ix_contcov) = [];
+    cat_cov_structure.functions(ix_contcov) = [];
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle CONTINUOUS covariates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+continuous_covnames = {};
+if ~isempty(cont_cov_structure),
+    % Initialize names arrays
+    parameternames = {};
+    covariatenames = {};
+
+    % Split parameter names and covariate names (cov names include still cat and cov covariates and t_ and groups for cat covs)
+    for k=1:length(covariates),
+        terms = explodePCSB(covariates{k},',');
+        parameternames{end+1} = terms{1};
+        covariatenames{end+1} = terms{2};
+    end
+    
+    % Remove the "t_" flag that indicates a transformed covariate
+    covariatenames = regexprep(covariatenames,'\<t_','');
+
+    % Determine and remove the categorical covariates and corresponding parameter names
+    catnames = setdiff(covariatenames,cont_cov_structure.names);
+    ix_remove = [];
+    for k=1:length(catnames),
+        ix = strmatchSB(catnames{k},covariatenames,'exact');
+        ix_remove = [ix_remove ix(:)'];
+    end
+    covariatenames(ix_remove) = [];
+    parameternames(ix_remove) = [];
+    covariatevalues_continuous = covariatevalues;
+    covariatevalues_continuous(ix_remove) = [];
+
+    % Parse covariate information into output structure
+    parameters = unique(parameternames);
+    for k=1:length(parameters),
+        ix = strmatchSB(parameters{k},parameternames,'exact');
+        output.covariates.continuous(k).parameter = parameters{k};
+        output.covariates.continuous(k).covariates = covariatenames(ix);
+        output.covariates.continuous(k).values = covariatevalues_continuous(ix);
+        fun = {};
+        for i = 1:length(output.covariates.continuous(k).covariates)
+            in = strmatchSB(output.covariates.continuous(k).covariates(i),cont_cov_structure.names,'exact');
+            fun(end+1) = cont_cov_structure.functions(in);
+        end
+        output.covariates.continuous(k).transformation = fun;
+    end
+    
+    % Remember for later
+    continuous_covnames = covariatenames;
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle CATEGORICAL covariates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(cat_cov_structure),
+    %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Handling further MONOLIX crap changes from version to version ...
+    % This time ... from 4.3.2 to 4.3.3
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    for k=1:length(cat_cov_structure.names),
+        name = cat_cov_structure.names{k};
+        fcts = cat_cov_structure.functions{k};
+        for k2=1:length(fcts.values),
+            old = [name fcts.values{k2}];
+            new = [name '_' fcts.values{k2}];
+            covariates = strrep(covariates,old,new);
+        end
+    end
+    
+    % Initialize names arrays
+    parameternames = {};
+    covariatenames = {};
+
+    % Split parameter names and covariate names (cov names include still cat and cov covariates and t_ and groups for cat covs)
+    for k=1:length(covariates),
+        terms = explodePCSB(covariates{k},',');
+        parameternames{end+1} = terms{1};
+        covariatenames{end+1} = terms{2};
+    end
+    
+    % Remove the "t_" flag that indicates a transformed covariate
+    covariatenames = regexprep(covariatenames,'\<t_','');
+
+    % Determine and remove the continuous covariates and corresponding parameter names
+    catnames = setdiff(unique(covariatenames),unique(continuous_covnames));
+    covnames = setdiff(unique(covariatenames),catnames);
+    ix_remove = [];
+    for k=1:length(covnames),
+        ix = strmatchSB(covnames{k},covariatenames,'exact');
+        ix_remove = [ix_remove ix(:)'];
+    end
+    covariatenames(ix_remove) = [];
+    parameternames(ix_remove) = [];
+    covariatevalues_categorical = covariatevalues;
+    covariatevalues_categorical(ix_remove) = [];
+
+    % Determine information about categorical covariate
+    parameters = unique(parameternames);
+    for k=1:length(parameters),
+        ix = strmatchSB(parameters{k},parameternames,'exact');
+        parameter = parameters{k};
+        covariates_raw_names = covariatenames(ix);
+        covariates_raw_values = covariatevalues_categorical(ix);
+        % Record parameter name
+        output.covariates.categorical(k).parameter          = parameter;
+        % Record covariate names (the true names, not the raw names)
+        covused_ix = [];
+        for k2=1:length(covariates_raw_names),
+            covused = covariates_raw_names{k2};
+            for k3=1:length(cat_cov_structure.names),
+                ix = strmatchSB([cat_cov_structure.names{k3} '_'],covused);
+                if ~isempty(ix),
+                    % Check if index already recorded
+                    if ~ismember(k3,covused_ix),
+                        covused_ix(end+1) = k3; % index in cat_cov_structure
+                    end
+                end
+            end
+        end
+        % Record name of covariate
+        output.covariates.categorical(k).covariates = cat_cov_structure.names(covused_ix);
+        % Get information about categories and parameter values for each covariate
+        for k2=1:length(covused_ix),
+            % Get names of the involved categories
+            output.covariates.categorical(k).information(k2).categories = cat_cov_structure.functions{covused_ix(k2)}.values;
+            % Get parameter estimates for the covariate coefficients in the order of the categories
+            covname = cat_cov_structure.names{covused_ix(k2)};
+            refcategory = cat_cov_structure.functions{covused_ix(k2)}.reference_value{1};
+            
+            values = [];
+            for k3=1:length(output.covariates.categorical(k).information(k2).categories),
+                checkFlag = 0;
+                if strcmp(output.covariates.categorical(k).information(k2).categories{k3},refcategory),
+                    values(k3) = 0;
+                    checkFlag  = 1;
+                end
+                ix = strmatchSB([covname '_' output.covariates.categorical(k).information(k2).categories{k3}],covariates_raw_names,'exact');
+                if ~isempty(ix),
+                    values(k3) = covariates_raw_values(ix);
+                    checkFlag  = 1;
+                end
+                if checkFlag == 0,
+                    error('Problem in category / covariate matching');
+                end
+            end
+            output.covariates.categorical(k).information(k2).values = values;
+        end
+    end
+end
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Process categorical covariates and keep only the ones that can be handled
+% => Remove if grouping is done with more than one element per group
+% => Warn the user about it
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(cat_cov_structure),
+    remove_cat_covs_names = {};
+    for k=1:length(cat_cov_structure.names),
+        test = cat_cov_structure.functions{k}.groups_ix_value;
+        if ~isempty(test),
+            for k2=1:length(test),
+                if length(test{k2}) > 1,
+                    % This covariate seems to have groups with more than one category => not possible to handle at the moment
+                    % => remove from consideration as covariate but warn the user!
+                    remove_cat_covs_names{end+1} = cat_cov_structure.names{k};
+                    if ~FLAG_SILENT,
+                        disp(sprintf('Categorical covariate "%s" in the model but it used grouping of more than one category\n\t=> not handled by the parameter sampling function. Handle by grouping in dataset if needed.',cat_cov_structure.names{k}));
+                        disp(' ');
+                    end
+                    break
+                end
+            end
+        end
+    end
+    % Remove identified covariates
+    yy = output.covariates.categorical;
+    for k=1:length(yy),
+        ix_remove = [];
+        for k2=1:length(yy(k).covariates),
+            covname = yy(k).covariates{k2};
+            if ismember(covname, remove_cat_covs_names),
+                % cov needs to be removed
+                ix_remove(end+1) = k2;
+            end
+        end
+        % Remove
+        yy(k).covariates(ix_remove) = [];
+        yy(k).information(ix_remove) = [];
+    end
+    output.covariates.categorical = yy;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Process categorical covariates again
+% Convert all categories to numerical values and error if not numeric
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+yy = output.covariates.categorical;
+for k1=1:length(yy),
+    for k2=1:length(yy(k1).information),
+        categories_string = yy(k1).information(k2).categories;
+        categories_value = [];
+        for k3=1:length(categories_string),
+            % Convert category string to a value and check if it is really a value - do not allow non-numeric values.
+            value = NaN;
+            try
+                value = eval(categories_string{k3});
+            catch
+                value = NaN;
+            end
+            if isnan(value),
+                error('Category for covariate "%s" is not numeric ("%s"). Function can only handle numeric categories.',yy(1).covariates{k2}, categories_string{k3})
+            end
+            % Record the value
+            categories_value(end+1) = value;
+        end
+        % Record the values instead of the strings
+        yy(k1).information(k2).categories = categories_value;
+    end
+end
+output.covariates.categorical = yy;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if everything was handled
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(names),
+    if ~FLAG_SILENT,
+        disp('Warning: The Monolix output contained information that are currently not handled.');
+        disp('This could be IOV or other things. Please have a look at the following unhandled names:');
+        for k=1:length(names),
+            fprintf('\t%s\n',names{k})
+        end
+    end
+end
+
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/templates/template_project_graphics.xmlx b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/templates/template_project_graphics.xmlx
new file mode 100644
index 0000000000000000000000000000000000000000..c6bc74f358d13e8605f4d55a6efc6885f5167940
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/monolix/templates/template_project_graphics.xmlx
@@ -0,0 +1,75 @@
+<monolix>
+	<graphics>
+		<version value="420"/>
+		<graphicList>
+			<graphic name="residuals" out="1">
+				<K value="10"/>
+				<Kmax value="30"/>
+				<Kmin value="5"/>
+				<alpha value="0.0005"/>
+				<beta value="0.4"/>
+				<beta_reg value="0.75"/>
+				<continous value="1"/>
+				<gamma value="0"/>
+				<iop_blqres value="2"/>
+				<iop_censcalc value="1"/>
+				<iop_colorcens value="1"/>
+				<iop_colorobs value="1"/>
+				<iop_displaybins value="0"/>
+				<iop_displaycens value="1"/>
+				<iop_displayciout value="0"/>
+				<iop_displayciprct value="0"/>
+				<iop_displayemdens value="1"/>
+				<iop_displayemprct value="0"/>
+				<iop_displayhisto value="0"/>
+				<iop_displayobs value="1"/>
+				<iop_displayoutprct value="0"/>
+				<iop_displayspline value="0"/>
+				<iop_displaythdens value="1"/>
+				<iop_displaythprct value="0"/>
+				<iop_gfind value="1"/>
+				<iop_gfobs value="1"/>
+				<iop_gs value="1"/>
+				<iop_legend value="0"/>
+				<level value="90"/>
+				<lmin value="10"/>
+				<nmax value="200"/>
+				<obin value="3"/>
+				<prctile value="3" vector="10,50,90"/>
+				<selectK value="1"/>
+				<select_graphics value="4" vector="1,1,1,0"/>
+				<select_residual value="6" vector="0,1,0,1,1,0"/>
+			</graphic>
+			<graphic name="cvSAEM" out="0">
+				<nbParam value="100"/>
+				<firstIndividual value="1"/>
+			</graphic>
+		</graphicList>
+		<graphicsToPrint>
+			<projectSummary value="0"/>
+			<spaghetti value="0"/>
+			<individualFits value="0"/>
+			<predVsObs value="0"/>
+			<residuals value="0"/>
+			<covariates value="0"/>
+			<VPC value="0"/>
+			<NPC value="0"/>
+			<BLQ value="0"/>
+			<categorizedData value="0"/>
+			<vpcPredDist value="0"/>
+			<distPsi value="0"/>
+			<boxplot value="0"/>
+			<jointDist value="0"/>
+			<kaplanMeier value="0"/>
+			<transProba value="0"/>
+			<bayesian value="0"/>
+			<individualContribution value="0"/>
+			<cvSAEM value="1"/>
+			<obsTimes value="1"/>
+			<intTimes value="0"/>
+			<fullTimes value="0"/>
+			<indContTable value="0"/>
+			<covTable value="0"/>
+		</graphicsToPrint>
+	</graphics>
+</monolix>
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nlme/SBPOPcreateNLMEproject.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nlme/SBPOPcreateNLMEproject.m
new file mode 100644
index 0000000000000000000000000000000000000000..2237b256b5966695248794281cc8ad501b421dd3
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nlme/SBPOPcreateNLMEproject.m
@@ -0,0 +1,161 @@
+function SBPOPcreateNLMEproject(TOOL,model,dosing,data,projectPath,varargin)
+% SBPOPcreateNLMEproject: creates a NONMEM or MONOLIX roject from an
+% SBmodel and an SBPOPdosing scheme. Some additional information is needed,
+% which is also passed. 
+%
+% Basically a wrapper function for SBPOPcreateNONMEMproject and
+% SBPOPcreateMONOLIXproject. The only additional argument is the definition
+% of the TOOL to be used ('MONOLIX' or 'NONMEM').
+%
+% The user needs to ensure that the algorithm options are chosen adequately
+% for the selected parameter estimation tool. If NONMEM is chosen, the
+% Monolix specific settings are ignored. If MONOLIX is chosen, the NONMEM
+% specific settings are ignored.
+%
+% This function allows also robustness analysis:
+% If in option Ntest is defined different from 1 then not a single but
+% Ntest models are generated with randomly chosen initial guesses for the
+% fixed effects. These models are then stored in folders in the
+% "projectPath" folder. 
+%
+% USAGE:
+% ======
+% SBPOPcreateNLMEproject(TOOL,model,dosing,data,projectPath)
+% SBPOPcreateNLMEproject(TOOL,model,dosing,data,projectPath,options)
+%
+% TOOL:         'NONMEM' or 'MONOLIX'
+%
+% model:        SBmodel (annotated with additional information for MLXTRAN conversion)
+%
+% dosing:       SBPOPdosing object (or empty [] if no input defined in model)
+%
+% data:         Structure with following fields:
+%       data.dataRelPathFromProject:    path to data file
+%       data.dataFileName:              data file filename
+%       data.dataHeaderIdent:           String with datafile header identifiers (example: 'ID,TIME,Y,MDV,EVID,AMT,TINF,ADM,YTYPE,COV,COV,CAT')
+%
+% projectPath:  String with the path/foldername to which the project files are to be written (example: 'FIT_01' or 'Models/FITS/FIT_01')
+%
+% options:      Structure with following fields (all optional with default settings):
+%       options.POPestimate:            Vector with 0 and 1 entries. 1 if pop parameter is estimated, 0 if not. Default or []: => all are estimated
+%       options.POPvalues0:             Vector with pop parameter initial values. Default or []: => values stored in model and dosing scheme
+%
+%       options.IIVdistribution:        Cell-array with information about parameter distribution. L (lognormal), N (normal), G (logit)
+%                                       Example: {'L' 'L' 'L' 'L' 'N' 'L' 'L' 'L'}. Default or {}: => use lognormal for all
+%       options.IIVestimate:            Vector with 0 and 1 entries. 1 if random effect is estimated, 0 if not. Default or []: => all are estimated
+%                                       0: IIV not estimated (IIVvalues0 not used)
+%                                       1: IIV estimated (IIVvalues0 as starting guesses)
+%                                       2: IIV not estimated but fixed on IIVvalues0 value
+%       options.IIVvalues0:             Vector with random effect parameter initial values. Default or []: => all set to 0.5
+%                                       If IIV not estimated then defined initial guess not used but replaced by 0
+%                                       THESE ARE STANDARD DEVIATIONS!!!
+%
+%       options.errorModels:            String with definition of residual error models, comma separated for each output.
+%                                       Possible values: const,prop,comb1. Example: 'comb1,prop', Default or '': => const for all outputs
+%
+%       options.errorParam0:            Vector allowing to pass initial guesses for error model parameters. Same order as error models. 
+%                                       'const': a, 'prop': b, 'comb1': a,b
+%
+%       options.covarianceModel:        Definition of covariance model. String with cell-array text inside, grouping the parameters to consider having
+%                                       correlated random effects. Example: '{CL,Vc},{Q,Vp,KM}'. Default: 'diagonal'
+%
+%       options.covariateModel:         Definition of covariate model. Cell-array. Each element is a sub-cell-array. First element in sub-cell-array is the
+%                                       parameter to which to add the covariate, all following elements define the covariates as named in the dataset.
+%                                       Example: '{CL,BMI0}, {Fsubcut,WT0}, {Vc,SEX,BMI0}'. Default: '' => no covariates
+%                                       By default (and so far not changeable, the continuous covariates are all weighted by their median, determined from the dataset)
+%       options.covariateModelValues:   Definition of covariate coefficients for the selected covariate model.
+%                                       Syntax is similar to options.covariateModel. It is a cell-array containing vectors instead of cell-arrays.
+%                                       Each vector contains values for the covariate coefficients, matching the covariateModel definition order.
+%                                       Example: if options.covariateModel = '{CL,BMI0,AGE0}, {Fsubcut,WT0}, {Vc,SEX,BMI0}'
+%                                       Then: options.covariateModelValues = {[0.5,0], [0.75], [0,0]}
+%                                       Defines the initial guesses for the covariate coefficients for BMI0 on CL to be 0.5, WT0 on Fsubcut to be 0.75, and the other ones are 0.
+%                                       If not defined, all covariate coefficients start from 0.1 in the estimation.
+%                                       Categorical covariate coefficients for more than 2 categories can not be defined in this way.
+%                                       For the reference value it is always 0 and for the other values always the same specified here
+%                                       (since only a single can be defined).
+%       options.COVestimate:            Same structure as options.covariateModelValues but with entries 0 or 1. 0 means not estimated, 1 means estimated.
+%                                       By default all are estimated.
+%                                       In the example above options.COVestimate = {[0,1], [1], [1,0]}   will estimate AE0 on CL, WT0 on Fsubcut, SEX on Vc.
+%                                       The other coefficients will be kept fixed.
+%
+%       options.SILENT:                 =0: do some output in the command window, =1: do no output in command window (default: 0)
+%
+%       options.Ntests:                 Doing robustness analysis - number of models to generate with different initial guesses (randomly generated based on POPvalues0)
+%                                       Default: 1 (no robustness analysis, using initial guesses as provided)
+%       options.std_noise_setting:      Standard deviation to use to add noise to the initial parameter guesses (default=0.2 (20%CV))
+%                                       Normal:         Parameter_guess + std_noise_setting*Parameter_guess*randomNumbers(0-1)
+%                                       Lognormal:      Parameter_guess * exp(std_noise_setting*randomNumbers(0-1))
+%                                       Logitnormal:    Similar and between 0-1
+%
+% ALGORITHM SETTINGS:
+% ===================
+%
+% GENERAL ones:
+%       options.algorithm.SEED:         Seed setting. Defualt: 123456
+%       options.algorithm.K1:           First iterations. Default: 500
+%       options.algorithm.K2:           Final iterations. Default: 200
+%       options.algorithm.NRCHAINS:     Number of parallel chains. Default: 1
+%
+% MONOLIX specific ones:
+%       options.algorithm.LLsetting:    'linearization' (default) or 'importantsampling'
+%       options.algorithm.FIMsetting:   'linearization' (default) or 'stochasticApproximation'
+%
+% NONMEM specific ones:
+%       options.algorithm.METHOD:       'FO','FOCE','FOCEI','SAEM' (default: SAEM)
+%       options.algorithm.MAXEVAL:      Default: 9999
+%       options.algorithm.SIGDIGITS:    Default: 3
+%       options.algorithm.PRINT:        Default: 1
+%
+%       options.algorithm.ITS:                  Allow to run an ITS method as first method befor all other methods (METHOD)
+%                                               ITS = 0 or 1 (default: 1 if not FO) - ITS=1 only accepted if not FO!
+%       options.algorithm.ITS_ITERATIONS:       Number of iterations for ITS (default: 10)
+%
+%       options.algorithm.IMPORTANCESAMPLING:   Allow determination of the OFV - only accepted after SAEM
+%                                               Default: 1, If 1 then do the importance sampling
+%       options.algorithm.IMP_ITERATIONS:       Number of iterations for importance sampling (default: 5)
+% 
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+%
+% This program is Free Open Source Software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 5,
+    options = [];
+elseif nargin == 6,
+    options = varargin{1};
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check TOOL definition
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~strcmp(lower(TOOL),'nonmem') && ~strcmp(lower(TOOL),'monolix'),
+    error('Please select as first input argument either ''NONMEM'' or ''MONOLIX''');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create the model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp(lower(TOOL),'nonmem')
+    SBPOPcreateNONMEMproject(model,dosing,data,projectPath,options);
+elseif strcmp(lower(TOOL),'monolix'),
+    SBPOPcreateMONOLIXproject(model,dosing,data,projectPath,options);
+end    
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nlme/SBPOPrunNLMEprojectFolder.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nlme/SBPOPrunNLMEprojectFolder.m
new file mode 100644
index 0000000000000000000000000000000000000000..5198ba3f8cb9b38bca001331f5e320096bf41b14
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nlme/SBPOPrunNLMEprojectFolder.m
@@ -0,0 +1,121 @@
+function [] = SBPOPrunNLMEprojectFolder(modelProjectsFolder,N_PROCESSORS_PAR,N_PROCESSORS_SINGLE,NO_GOF_PLOTS)
+% [DESCRIPTION]
+% This functions runs all the NONMEM and MONOLIX projects in the specified folder.
+% Parallel computation is supported in two different ways. Parallel execution 
+% of models at the same time (par for loop) and also allowing each single model
+% run to be parallelized (if the NONMEM and MONOLIX installation allows for it).
+%
+% [SYNTAX]
+% [] = SBPOPrunNLMEprojectFolder(modelProjectsFolder)
+% [] = SBPOPrunNLMEprojectFolder(modelProjectsFolder,N_PROCESSORS_PAR)
+% [] = SBPOPrunNLMEprojectFolder(modelProjectsFolder,N_PROCESSORS,N_PROCESSORS_SINGLE)
+% [] = SBPOPrunNLMEprojectFolder(modelProjectsFolder,N_PROCESSORS,N_PROCESSORS_SINGLE,NO_GOF_PLOTS)
+%
+% [INPUT]
+% modelProjectsFolder:      Path to a folder with NONMEM project folders
+%                           to be run. Folder names are arbitrary, but a
+%                           project.nmctl file needs to be present in
+%                           each folder.
+% N_PROCESSORS_PAR:         Number of processors for parallel model evaluation (default: 1)
+% N_PROCESSORS_SINGLE:      Number of processors for parallelization of single model run (default: 1)
+% NO_GOF_PLOTS:             =0: Create GoF plots for all runs (default), =1: No Gof plots
+%
+% If N_PROCESSORS_PAR>1 then parallel nodes are requested via the matlabpool
+% command and N_PROCESSORS_PAR models will be run in parallel.
+%
+% [OUTPUT]
+% No output! The function just runs the NONMEM and MONOLIX projects. All results are
+% written to the relevant output folders ("RESULTS").
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 12 August, 2014
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 1,
+    N_PROCESSORS_PAR    = 1;
+    N_PROCESSORS_SINGLE = 1;
+    NO_GOF_PLOTS = 0;
+elseif nargin == 2,
+    N_PROCESSORS_SINGLE = 1;
+    NO_GOF_PLOTS = 0;
+elseif nargin == 3,
+    NO_GOF_PLOTS = 0;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get the projects to run in the folder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+projects = dir([modelProjectsFolder '/*']);
+% Remove . and ..
+ix_dot = strmatchSB('.',{projects.name});
+projects(ix_dot) = [];
+% Remove files
+projects(find(~[projects.isdir])) = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Request processors
+% Request min(N_PROCESSORS,length(projects))
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+N_PROCESSORS_NEEDED = min(N_PROCESSORS_PAR,length(projects));
+
+killMATLABpool = 0;
+if N_PROCESSORS_NEEDED>1,
+    try
+        if matlabpool('size') == 0,
+            eval(sprintf('matlabpool %d',N_PROCESSORS_NEEDED));
+            killMATLABpool = 1;
+        end
+    catch
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run the models
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+oldpath = pwd();
+parfor k=1:length(projects),
+    fprintf('Running project %d of %d ...\n',k,length(projects));
+    pathfolder = [modelProjectsFolder '/' projects(k).name];
+    if isNONMEMfitSBPOP(pathfolder),
+        SBPOPrunNONMEMproject(pathfolder,N_PROCESSORS_SINGLE,NO_GOF_PLOTS);
+    elseif isMONOLIXfitSBPOP(pathfolder),
+        SBPOPrunMONOLIXproject(pathfolder,N_PROCESSORS_SINGLE,NO_GOF_PLOTS);
+    end
+end
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Release processors
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try
+    if matlabpool('size')>1 && killMATLABpool==1,
+        matlabpool close
+    end
+catch
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Done!
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf('\nEstimations READY!\n\n');
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nlme/SBPOPsampleNLMEfitParam.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nlme/SBPOPsampleNLMEfitParam.m
new file mode 100644
index 0000000000000000000000000000000000000000..bf03c99f73c25384ebfb6e958e74bcb4742e11d4
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nlme/SBPOPsampleNLMEfitParam.m
@@ -0,0 +1,119 @@
+function [output] = SBPOPsampleNLMEfitParam( projectPath, FLAG_SAMPLE, Nsamples, covNames, covValues, catNames, catValues )
+% [NAME]
+% SBPOPsampleNLMEfitParam
+%
+% [DESCRIPTION]
+% This function samples parameters from both uncertainty and variability distributions from a NLME
+% fit which has been done using Monolix or NONMEM. 
+% 
+% The result is a structure with sampled population parameters and sampled individual parameters. 
+% The desired number of parameter sets can be specified.
+%
+% This function is very useful for trial simulation purposes.
+%
+% Handles automatically different parameter distributions (logNormal, Normal, logitNormal)
+%
+% VERY IMPORTANT:
+% If using Monolix versions before 4.2, you should NOT center the covariates automatically by the median or mean, etc. This is so,
+% because Monolix before 4.2 does NOT store this centering value. For versions before 4.2 you need to center manually, by choosing the
+% covariate transformation method "other" and then e.g. type: log(cov/78) if cov is weight and you want to center it at 78kg and use a
+% log transformation.
+% For versions from 4.2 upwards, no problem, centering values are stored and automatic centering can be used.
+%
+% [SYNTAX]
+% output = SBPOPsampleNLMEfitParam( projectPath, FLAG_SAMPLE, Nsamples )
+% output = SBPOPsampleNLMEfitParam( projectPath, FLAG_SAMPLE, Nsamples, covNames, covValues, catNames, catValues )
+%
+% [INPUT]
+% projectPath: path to the NLME project folder. NONMEM and MONOLIX projects
+%              need to have been generated with SBPOP.
+% FLAG_SAMPLE:                    0=use point estimates of population parameters (do not consider uncertainty) and sample Nsample 
+%                                   individual patients based on these. Covariates considered if defined by user and used in model.
+%                                   Please note: population parameters do not take covariates into account!
+%                                 1=sample single set of population parameters from uncertainty distribution and sample Nsample 
+%                                   individual patient parameters based on these. Covariates considered if defined by user and used in model.
+%                                   Please note: population parameters do not take covariates into account!
+%                                 2=sample Nsample sets of population parameters from uncertainty distribution 
+%                                   Do not sample from variability distribution and do not take into account covariates (even if user specified).
+%                                 3=use point estimates of population parameters (do not consider uncertainty)
+%                                   Return Nsamples sets of population parameters with covariates taken into account.
+%                                 4=sample single set of population parameters from uncertainty distribution 
+%                                   Return Nsamples sets of population parameters with covariates taken into account.
+%                                 5=sample Nsamples sets of population parameters from uncertainty distribution 
+%                                   And take provided covariates into account.
+% 
+% Nsamples:                       Number of individual parameter sets to sample
+%
+% covNames:                       Cell-array with names of continuous covariates to consider in the parameter sampling (only used for FLAG_SAMPLE=0 or 1)
+%                                 Default: {}
+% covValues:                      Matrix with Nsamples rows and as many columns as continuous covariate names in covNames (only used for FLAG_SAMPLE=0 or 1)
+% catNames:                       Cell-array with names of categorical covariates to consider in the parameter sampling (only used for FLAG_SAMPLE=0 or 1)
+%                                 Default: {}
+% catValues:                      Matrix with Nsamples rows and as many columns as categorical covariate names in covNames (only used for FLAG_SAMPLE=0 or 1)
+%
+% [OUTPUT]
+% Structure with the following fields:
+% output.parameterNames:                Cell-array with parameter names
+% output.FLAG_SAMPLE:                   Sampling flag used (see above for definition)
+% output.Nsamples:                      Number of sampled parameter sets (type of parameter sets sampled depends on FLAG_SAMPLE)
+% output.parameterValuesPopulation:     Vector or Matrix with (sampled) population parameters
+% output.parameterValuesIndividual:     Matrix with samples individual parameter sets (one set per row, one parameter per column)
+%
+% [ASSUMPTIONS]
+% 
+% [AUTHOR]
+% Henning Schmidt 
+%
+% [DATE]
+% 04.05.2014
+%
+% [PLATFORM]
+% MATLAB R2013a
+%
+% [KEYWORDS]
+% MONOLIX, NONMEM, results, sampling, parameters, individual
+% 
+% [TOOLBOXES USED]
+% NONE
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 3,
+    covNames = {};
+    covValues = []; 
+    catNames = {}; 
+    catValues = [];
+elseif nargin ==5,
+    catNames = {}; 
+    catValues = [];
+elseif nargin ==7,
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle NONMEM or MONOLIX
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isNONMEMfitSBPOP(projectPath),
+    output = SBPOPsampleNONMEMparam(projectPath, FLAG_SAMPLE, Nsamples, covNames, covValues, catNames, catValues);
+else
+    output = SBPOPsampleMONOLIXparam(projectPath, FLAG_SAMPLE, Nsamples, covNames, covValues, catNames, catValues);
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nlme/getCovariateInformationSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nlme/getCovariateInformationSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..d7baf5e833289d4e82a50b8c7a37ee3e7a7fde6b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nlme/getCovariateInformationSBPOP.m
@@ -0,0 +1,86 @@
+function [covNames,catNames,referenceCAT] = getCovariateInformationSBPOP( projectPath )
+% [NAME]
+% getCovariateNamesSBPOP
+%
+% [DESCRIPTION]
+% Returns the names of the categorical and continuous covariates that are
+% used in a NONMEM or MONOLIX model that is defined by the "projectPath"
+% input argument. Additionally, it returns the values that are used as
+% reference categories for the categorical covariates (identified by a
+% covariate coefficient of "0").
+% 
+% [SYNTAX]
+% [covNames,catNames] = getCovariateNamesSBPOP( projectPath )
+%
+% [INPUT]
+% projectPath: path to the NLME project folder. NONMEM and MONOLIX projects
+%              need to have been generated with SBPOP.
+%
+% [OUTPUT]
+% covNames:     Cell-array with names of continuous covariates used in the model
+% catNames:     Cell-array with names of categorical covariates used in the model
+% referenceCAT: Vector with reference values for the categorical covariates in catNames
+%
+% [AUTHOR]
+% Henning Schmidt 
+%
+% [DATE]
+% 25.08.2014
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+if isempty(projectPath),
+    covNames = {};
+    catNames = {};
+    referenceCAT = [];
+    return
+end
+
+% Handle NONMEM or MONOLIX
+if isNONMEMfitSBPOP(projectPath),
+    x = parseNONMEMresultsSBPOP(projectPath);
+    y = sampleNONMEMpopulationParametersSBPOP(x,0,1);
+elseif isMONOLIXfitSBPOP(projectPath),
+    x = parseMONOLIXresultsSBPOP(projectPath);
+    y = sampleMONOLIXpopulationParametersSBPOP(x,0,1);
+else
+    error('Wrong project path? Not an NLME project!');
+end
+
+% Get covariate names in cell arrays
+covNames = unique([y.covariates.continuous.covariates]);
+catNames = unique([y.covariates.categorical.covariates]);
+
+% Get reference values for categorical covariates
+referenceCAT = NaN(1,length(catNames));
+
+for k=1:length(catNames),
+    for k2=1:length(y.covariates.categorical),
+        z = y.covariates.categorical(k2);
+        % Check if covariate present
+        ix = strmatchSB(catNames{k},z.covariates,'exact');
+        if ~isempty(ix),
+            values = z.information(ix).values;
+            ix0 = find(values==0);
+            reference = z.information(ix).categories(ix0(1));
+            referenceCAT(k) = reference;
+        end
+    end
+end
+    
+    
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/SBPOPcreateNONMEMproject.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/SBPOPcreateNONMEMproject.m
new file mode 100644
index 0000000000000000000000000000000000000000..de291b1558cba5bb364fb6d810bbc6c474150e91
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/SBPOPcreateNONMEMproject.m
@@ -0,0 +1,1609 @@
+function SBPOPcreateNONMEMproject(model,dosing,data,projectPath,varargin)
+% SBPOPcreateNONMEMproject: creates a NONMEM project from an SBmodel and
+% an SBPOPdosing scheme. Some additional information is needed, which is
+% also passed.
+%
+% This function allows also robustness analysis:
+% If in option Ntest is defined different from 1 then not a single but
+% Ntest models are generated with randomly chosen initial guesses for the
+% fixed effects. These models are then stored in folders in the
+% "projectPath" folder. 
+%
+% ASSUMPTIONS:
+% ============
+% - MU Referencing always used. Covariates transformed using the same
+%   transformation as the random effects. Centering by the median for the
+%   covariates.
+% - Always untransformed categorical covariates. Several categories per
+%   covariate possible but all need to be numeric and integers.
+% - IIV correlation parameters always zero at the initial guess.
+% - Selection of PRED,RES,WRES outputs dependent on the method that is used
+%   for estimation (in the tables renamed to: XPRED, XRES, XWRES):
+%       - PREDI RESI WRESI if FO
+%       - CPREDI, CRESI, CWRESI if FOCE
+%       - EPRED, ERES, EWRES if SAEM
+% - Default values for add and prop errors: 1 and 0.3
+% - Dataset can contain CMT or (ADM+YTYPE) columns. The output on the
+%   screen of this function will guide the user as to the needed values in
+%   these columns.
+%       - If only CMT is present then 
+%           - YTYPE is inferred based on CMT for observation records (in $ERROR)
+%           - CMT will be used as defined for selecting the dosing compartments
+%       - If CMT and YTYPE and/or ADM is present then error - do not allow
+%       - If ADM and YTYPE is present but not CMT
+%           - Use YTYPE as above
+%           - Use ADM as CMT column but rearrange states to fit the
+%             input/state numbers
+%
+% USAGE:
+% ======
+% SBPOPcreateNONMEMproject(model,dosing,data,projectPath)
+% SBPOPcreateNONMEMproject(model,dosing,data,projectPath,options)
+% SBPOPcreateNONMEMproject(model,dosing,data,projectPath,options,parameterOrder)
+%
+% parameterOrder: Used to reorder parameters (used by the popPK workflow, do not use otherwise)
+%
+% model:        SBmodel (annotated with additional information for MLXTRAN conversion)
+%
+% dosing:       SBPOPdosing object (or empty [] if no input defined in model)
+%
+% data:         Structure with following fields:
+%       data.dataRelPathFromProject:    path to data file
+%       data.dataFileName:              data file filename
+%       data.dataHeaderIdent:           String with datafile header identifiers (example: 'ID,TIME,Y,MDV,EVID,AMT,TINF,ADM,YTYPE,COV,COV,CAT')
+%
+% projectPath:  String with the path/foldername to which the project files are to be written (example: 'FIT_01' or 'Models/FITS/FIT_01')
+%
+% options:      Structure with following fields (all optional with default settings):
+%       options.POPestimate:            Vector with 0 and 1 entries. 1 if pop parameter is estimated, 0 if not. Default or []: => all are estimated
+%       options.POPvalues0:             Vector with pop parameter initial values. Default or []: => values stored in model and dosing scheme
+%
+%       options.IIVdistribution:        Cell-array with information about parameter distribution. L (lognormal), N (normal), G (logit)
+%                                       Example: {'L' 'L' 'L' 'L' 'N' 'L' 'L' 'L'}. Default or {}: => use lognormal for all
+%       options.IIVestimate:            Vector with 0 and 1 entries. 1 if random effect is estimated, 0 if not. Default or []: => all are estimated
+%                                       0: IIV not estimated (IIVvalues0 not used)
+%                                       1: IIV estimated (IIVvalues0 as starting guesses)
+%                                       2: IIV not estimated but fixed on IIVvalues0 value
+%       options.IIVvalues0:             Vector with random effect parameter initial values. Default or []: => all set to 0.5
+%                                       If IIV not estimated then defined initial guess not used but replaced by 0
+%                                       THESE ARE STANDARD DEVIATIONS!!!
+%
+%       options.errorModels:            String with definition of residual error models, comma separated for each output.
+%                                       Possible values: const,prop,comb1. Example: 'comb1,prop', Default or '': => const for all outputs
+%
+%       options.errorParam0:            Vector allowing to pass initial guesses for error model parameters. Same order as error models. 
+%                                       'const': a, 'prop': b, 'comb1': a,b
+%
+%       options.covarianceModel:        Definition of covariance model. String with cell-array text inside, grouping the parameters to consider having
+%                                       correlated random effects. Example: '{CL,Vc},{Q,Vp,KM}'. Default: 'diagonal'
+%
+%       options.covariateModel:         Definition of covariate model. Cell-array. Each element is a sub-cell-array. First element in sub-cell-array is the
+%                                       parameter to which to add the covariate, all following elements define the covariates as named in the dataset.
+%                                       Example: '{CL,BMI0}, {Fsubcut,WT0}, {Vc,SEX,BMI0}'. Default: '' => no covariates
+%                                       By default (and so far not changeable, the continuous covariates are all weighted by their median, determined from the dataset)
+%       options.covariateModelValues:   Definition of covariate coefficients for the selected covariate model.
+%                                       Syntax is similar to options.covariateModel. It is a cell-array containing vectors instead of cell-arrays.
+%                                       Each vector contains values for the covariate coefficients, matching the covariateModel definition order.
+%                                       Example: if options.covariateModel = '{CL,BMI0,AGE0}, {Fsubcut,WT0}, {Vc,SEX,BMI0}'
+%                                       Then: options.covariateModelValues = {[0.5,0], [0.75], [0,0]}
+%                                       Defines the initial guesses for the covariate coefficients for BMI0 on CL to be 0.5, WT0 on Fsubcut to be 0.75, and the other ones are 0.
+%                                       If not defined, all covariate coefficients start from 0.1 in the estimation.
+%                                       Categorical covariate coefficients for more than 2 categories can not be defined in this way.
+%                                       For the reference value it is always 0 and for the other values always the same specified here
+%                                       (since only a single can be defined).
+%       options.COVestimate:            Same structure as options.covariateModelValues but with entries 0 or 1. 0 means not estimated, 1 means estimated.
+%                                       By default all are estimated.
+%                                       In the example above options.COVestimate = {[0,1], [1], [1,0]}   will estimate AE0 on CL, WT0 on Fsubcut, SEX on Vc.
+%                                       The other coefficients will be kept fixed.
+%       options.COVcentering.covs:      Cell-array with covariates that should be centered around a custom value. 
+%       options.COVcentering.values:    Vector with centering values. 
+%
+%       options.SILENT:                 =0: do some output in the command window, =1: do no output in command window (default: 0)
+%
+%
+%       options.Ntests:                 Doing robustness analysis - number of models to generate with different initial guesses (randomly generated based on POPvalues0)
+%                                       Default: 1 (no robustness analysis, using initial guesses as provided)
+%       options.std_noise_setting:      Standard deviation to use to add noise to the initial parameter guesses (default=0.5 (50%CV))
+%                                       Normal:         Parameter_guess + std_noise_setting*Parameter_guess*randomNumbers(0-1)
+%                                       Lognormal:      Parameter_guess * exp(std_noise_setting*randomNumbers(0-1))
+%                                       Logitnormal:    Similar and between 0-1
+%
+% ALGORITHM SETTINGS:
+% ===================
+%
+%       options.algorithm.METHOD:       'FO','FOCE','FOCEI','SAEM' (default: SAEM)
+%       options.algorithm.MAXEVAL:      Default: 9999
+%       options.algorithm.SIGDIGITS:    Default: 3
+%       options.algorithm.PRINT:        Default: 1
+%
+%       options.algorithm.ITS:                  Allow to run an ITS method as first method befor all other methods (METHOD)
+%                                               ITS = 0 or 1 (default: 0 if not FO) - ITS=1 only accepted if not FO!
+%       options.algorithm.ITS_ITERATIONS:       Number of iterations for ITS (default: 10)
+%
+%       options.algorithm.IMPORTANCESAMPLING:   Allow determination of the OFV - only accepted after SAEM
+%                                               Default: 0, If 1 then do the importance sampling
+%       options.algorithm.IMP_ITERATIONS:       Number of iterations for importance sampling (default: 5)
+% 
+%       options.algorithm.SEED:         Seed setting. Defualt: 123456
+%       options.algorithm.K1:           First iterations. Default: 500
+%       options.algorithm.K2:           Final iterations. Default: 200
+%       options.algorithm.NRCHAINS:     Number of parallel chains. Default: 1
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+%
+% This program is Free Open Source Software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define Default Properties (Never changing)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+projectName            = 'project';
+resultsFolder          = 'RESULTS';
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBmodel(model),
+    error('First input argument is not an SBmodel.');
+end
+if ~isSBPOPdosing(dosing) && ~isempty(dosing),
+    error('Second input argument is not an SBPOPdosing scheme.');
+end
+try
+    dataRelPathFromProject = data.dataRelPathFromProject;
+    dataFileName           = data.dataFileName;
+    dataHeaderIdent        = data.dataHeaderIdent;
+    
+    % Need to change the data header
+    % TIME => TIME2 (Since it can contain negative times)
+    % TIMEPOS => TIME (The normal NONMEM time ... since it is only positive)
+    dataHeaderIdent         = regexprep(dataHeaderIdent,'\<TIME\>','TIME2');    
+    dataHeaderIdent         = regexprep(dataHeaderIdent,'\<TIMEPOS\>','TIME');    
+    dataHeaderIdent         = regexprep(dataHeaderIdent,'\<Y\>','DV');    
+catch
+    error('data input argument not defined correctly.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+options = [];
+parameterOrder = {};
+if nargin==5,
+    options = varargin{1};
+    parameterOrder = {};
+elseif nargin==6,
+    options = varargin{1};
+    parameterOrder = varargin{2};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle optional arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try POPestimate                     = options.POPestimate;                      catch, POPestimate = [];                             end
+try POPvalues0                      = options.POPvalues0;                       catch, POPvalues0 = [];                              end
+try IIVdistribution                 = options.IIVdistribution;                  catch, IIVdistribution = {};                         end
+try IIVestimate                     = options.IIVestimate;                      catch, IIVestimate = [];                             end
+try IIVvalues0                      = options.IIVvalues0;                       catch, IIVvalues0 = [];                              end
+try errorModels                     = options.errorModels;                      catch, errorModels = '';                             end
+try errorParam0                     = options.errorParam0;                      catch, errorParam0 = [];                             end
+try covarianceModel                 = options.covarianceModel;                  catch, covarianceModel = 'diagonal';                 end
+try covariateModel                  = options.covariateModel;                   catch, covariateModel = '';                          end
+try covariateModelValues            = options.covariateModelValues;             catch, covariateModelValues = {};                    end
+try COVestimate                     = options.COVestimate;                      catch, COVestimate = {};                             end
+
+try COVcentering_covs               = options.COVcentering.covs;                catch, COVcentering_covs = {};                       end
+try COVcentering_values             = options.COVcentering.values;              catch, COVcentering_values = [];                     end
+
+try METHOD                          = options.algorithm.METHOD;                 catch, METHOD = 'SAEM';                              end
+try MAXEVAL                         = options.algorithm.MAXEVAL;                catch, MAXEVAL = 9999;                               end
+try SIGDIGITS                       = options.algorithm.SIGDIGITS;              catch, SIGDIGITS = 3;                                end
+try PRINT                           = options.algorithm.PRINT;                  catch, PRINT = 1;                                    end
+try SEED                            = options.algorithm.SEED;                   catch, SEED = 123456;                                end
+try K1                              = options.algorithm.K1;                     catch, K1 = 500;                                     end
+try K2                              = options.algorithm.K2;                     catch, K2 = 200;                                     end
+try NRCHAINS                        = options.algorithm.NRCHAINS;               catch, NRCHAINS = 1;                                 end
+try IMPORTANCESAMPLING              = options.algorithm.IMPORTANCESAMPLING;     catch, IMPORTANCESAMPLING = 0;                       end
+try ITS                             = options.algorithm.ITS;                    catch, ITS = 0;                                      end
+try ITS_ITERATIONS                  = options.algorithm.ITS_ITERATIONS;         catch, ITS_ITERATIONS = 10;                          end
+try IMP_ITERATIONS                  = options.algorithm.IMP_ITERATIONS;         catch, IMP_ITERATIONS = 5;                           end
+
+try SILENT                          = options.SILENT;                           catch, SILENT = 0;                                   end
+try keepProjectFolder               = options.keepProjectFolder;                catch, keepProjectFolder = 0;                        end   
+
+try Ntests                          = options.Ntests;                           catch, Ntests = 1;                                    end
+try std_noise_setting               = options.std_noise_setting;                catch, options.std_noise_setting = 0.5;               end
+std_noise_setting                   = options.std_noise_setting;
+
+
+if ~iscell(COVcentering_covs),
+    COVcentering_covs = {COVcentering_covs};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle first the case with robustness analysis
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if Ntests>1,
+    % Robustness analysis desired
+    % Check if POPvalues0 and POPestimate defined
+    if isempty(POPestimate) || isempty(POPvalues0),
+        error('When doing robustness analysis, please define options.POPvalues0 and options.POPestimate!');
+    end
+    
+    % Define IIVdistribution if still empty (default: all 'L')
+    if isempty(IIVdistribution),
+        for k=1:length(POPvalues0),
+            IIVdistribution{k} = 'L';
+        end
+    end
+    
+    % Sample Ntests new POPvalues0 for the ones that are estimated using
+    % std_noise_setting as standard deviation
+    
+    % Allocating variable
+    POPvalues0_sampled                          = POPvalues0(ones(1,Ntests),:);
+    
+    % Sampling normally distributed (IIV) parameters - which are also estimated on a population level
+    ix_normal_sampled                           = find(strcmp(IIVdistribution,'N').*POPestimate);
+    POPvalues0_sampled(:,ix_normal_sampled)     = POPvalues0(ones(1,Ntests),ix_normal_sampled) + std_noise_setting*POPvalues0(ones(1,Ntests),ix_normal_sampled).*randn(Ntests,length(ix_normal_sampled));
+
+    % Sampling log normally distributed (IIV) parameters - which are also estimated on a population level
+    ix_lognormal_sampled                        = find(strcmp(IIVdistribution,'L').*POPestimate);
+    MU                                          = log(POPvalues0(ones(1,Ntests),ix_lognormal_sampled));
+    XXX                                         = MU + std_noise_setting.*randn(Ntests,length(ix_lognormal_sampled));
+    POPvalues0_sampled(:,ix_lognormal_sampled)  = exp(XXX);
+    
+    % Sampling logit normally distributed parameters - which are also estimated on a population level
+    ix_logitnormal_sampled                          = find(strcmp(IIVdistribution,'G').*POPestimate);
+    MU                                              = log(POPvalues0(ones(1,Ntests),ix_logitnormal_sampled)./(1-POPvalues0(ones(1,Ntests),ix_logitnormal_sampled)));
+    XXX                                             = MU + std_noise_setting.*randn(Ntests,length(ix_logitnormal_sampled));
+    POPvalues0_sampled(:,ix_logitnormal_sampled)    = exp(XXX)./(1+exp(XXX));
+      
+    % Clean folder
+    try rmdir(projectPath,'s'); catch, end
+    
+    % Create Ntests different models in the projectPath/MODEL_01/02, ... folders
+    for k=1:Ntests,
+        % Setup new project creation stuff
+        modelK                          = model;
+        dosingK                         = dosing;
+        dataK                           = data;
+        dataK.dataRelPathFromProject    = ['../' data.dataRelPathFromProject];
+        projectPathK                    = [projectPath sprintf('/MODEL_%s',preFillCharSB(k,length(num2str(Ntests)),'0'))];
+        optionsK                        = options;
+        optionsK                        = rmfield(optionsK,'Ntests');
+        optionsK                        = rmfield(optionsK,'std_noise_setting');
+        optionsK.POPvalues0             = POPvalues0_sampled(k,:);
+        SBPOPcreateNONMEMproject(modelK,dosingK,dataK,projectPathK,optionsK)
+    end
+    
+    % Ready, return
+    return
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle methods - some SBPOP limitations
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp(METHOD,'FO') && ITS==1,
+    ITS = 0;
+end
+
+if ~strcmp(METHOD,'SAEM') && IMPORTANCESAMPLING==1,
+    warning('The importance sampling (IMPORTANCESAMPLING=1) is disabled for all but the SAEM method.');
+    IMPORTANCESAMPLING = 0;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Info text
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~SILENT,
+    disp(' ')
+    disp('==================================================================');
+    [xdummyx,projectFolderName] = fileparts(projectPath);
+    disp(sprintf('== Start of creation of %s/project.nmctl file',projectFolderName));
+    disp('==================================================================');
+    disp(' ')
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create project and results folder
+% Change into project path
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+oldpath = pwd;
+if ~keepProjectFolder,
+    try, rmdir(projectPath,'s'); catch, end
+end
+mkdir(projectPath); cd(projectPath)
+mkdir(resultsFolder);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Load data and get info about data
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dataModeling = SBPOPloadCSVdataset([data.dataRelPathFromProject '/' data.dataFileName]);
+% Determine maximum number of data records per ID
+maxDATARECORDS_ID = -Inf;
+allID = unique(dataModeling.ID);
+for k=1:length(allID),
+    datak = dataModeling(dataModeling.ID==allID(k),:);
+    maxDATARECORDS_ID = max(maxDATARECORDS_ID,length(datak));
+end
+maxDATARECORDS = length(dataModeling);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Process data to get the dataheader and the median values for the covariates
+% and the categorical covariate names and their unique values.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[covariateMedianNames,covariateMedianValues,covariateCATNames,covariateCATValues,dataheader,dataCSV] = processDataAndGetMedianValuesSBPOP(oldpath,dataRelPathFromProject,dataFileName,dataHeaderIdent,SILENT,COVcentering_covs,COVcentering_values);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check data regarding the CMT/ADM/YTYPE thing
+%       - If only CMT is present then 
+%           - YTYPE is inferred based on CMT for observation records (in $ERROR)
+%             But this means that CMT needs to follow the OUTPUTn numbering!
+%           - CMT will be used as defined for selecting the dosing compartments
+%       - If CMT and YTYPE and/or ADM is present then error - do not allow
+%       - If ADM and YTYPE is present but not CMT
+%           - Use YTYPE as above
+%           - Use ADM as CMT column but rearrange states to fit the
+%             input/state numbers
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dataHeaderIdentAll = explodePCSB(dataHeaderIdent);
+
+ix_CMT   = strmatchSB('CMT',dataHeaderIdentAll,'exact');
+ix_ADM   = strmatchSB('ADM',dataHeaderIdentAll,'exact');
+ix_YTYPE = strmatchSB('YTYPE',dataHeaderIdentAll,'exact');
+if ~isempty(ix_CMT) && (~isempty(ix_ADM) || ~isempty(ix_YTYPE)),
+    error(sprintf('CMT and ADM and/or YTYPE present in the dataset.\n\tIf CMT than neither ADM nor YTYPE allowed.\n\tAnd if YTYPE and ADM then no CMT allowed.'));
+end
+if (~isempty(ix_ADM) && isempty(ix_YTYPE)) || (isempty(ix_ADM) && ~isempty(ix_YTYPE)),
+    error('ADM or YTYPE missing from the dataset. Please specify both!');
+end
+if ~isempty(ix_CMT),
+    FLAG_CMT = 1;       % Defines that the CMT column is present
+else
+    FLAG_CMT = 0;       % Defines that the CMT column is not present and that ADM and YTYPE are present instead
+    % Need to rename ADM to CMT in dataHeaderIdentAll, dataHeaderIdent, dataheader
+    dataHeaderIdent = regexprep(dataHeaderIdent,'\<ADM\>','CMT');
+    dataheader{strmatchSB('ADM',dataheader,'exact')} = 'CMT';
+    dataHeaderIdentAll{strmatchSB('ADM',dataHeaderIdentAll,'exact')} = 'CMT';
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check and update model syntax to be fit(ter) for NONMEM
+% Also check dosing object ...
+%
+% Also, based on the FLAG_CMT (if 0) flag do a re-ordering of the states to
+% match the ADM values to the state order. Check if this is possible - if
+% more than one INPUT on the same state then this is not possible and the
+% CMT version should be used! Print an error if this happens!
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+model = checkAndChangeModelSyntax4NONMEMconversionSBPOP(model,dosing,FLAG_CMT);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get model information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modelInfo           = mergemoddosstructsSBPOP(basicmodelparsingSBPOP(model),dosing);
+ms                  = struct(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% If needed, reorder parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(parameterOrder),
+    ix_reorder = [];
+    for k=1:length(parameterOrder),
+        ix_reorder(k) = strmatchSB(parameterOrder{k},{modelInfo.param_est.name},'exact');
+    end
+    modelInfo.param_est = modelInfo.param_est(ix_reorder);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Copy param_est information for reordering for covariance
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+param_est           = modelInfo.param_est;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check and update default input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[ POPestimate,POPvalues0,IIVestimate,IIVvalues0,IIVdistribution,...
+    covariateModel,covariateModelValues, COVestimate ] = ...
+    checkHandleDefaultInputArguments4NONMEMconversionSBPOP( oldpath,param_est,...
+    POPestimate,POPvalues0,IIVestimate,IIVvalues0,IIVdistribution,...
+    covariateModel,covariateModelValues,COVestimate );
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Reorder estimation parameters to allow for block-diagonal covariance
+% matrix
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[param_est,POPestimate,POPvalues0,IIVestimate,IIVvalues0,IIVdistribution] = reorderParameters4NONMEMcovSBPOP(covarianceModel,param_est,POPestimate,POPvalues0,IIVestimate,IIVvalues0,IIVdistribution);
+
+if ~SILENT,
+    writeOutConversionNONMEMinformationSBPOP( param_est, IIVdistribution, IIVestimate )
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Do additional checks and write out information
+% Definition of param_est and IIVestimation + reordering needed to be ready
+% before running these checks.
+% Additionally, the names of the covariates are determined and the
+% errorModels default setting is handled here.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[covNames,catNames,errorModels,errorParam0] = additionalChecks4NONMEMconversionSBPOP( oldpath,param_est, dataHeaderIdent,dataheader,modelInfo,IIVestimate,errorModels,errorParam0,covarianceModel,covariateModel,SILENT);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OPEN File
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen([projectName '.nmctl'],'w');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INFO
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; NONMEM PROJECT, created using the SBPOP toolbox\r\n');
+fprintf(fid,'; Date: %s\r\n',date);
+fprintf(fid,'; By:   %s\r\n',usernameSBPOP());
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Placeholder for project information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; ==PROJECT HEADER START===================================================\r\n');
+fprintf(fid,'PROJECT_HEADER_PLACEHOLDER\r\n');
+fprintf(fid,'; ==PROJECT HEADER END=====================================================\r\n');
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define $SIZES
+% Set all LIM1,2,6 to TOTDREC=maxDATARECORDS!
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'$SIZES LIM1=%d\r\n',maxDATARECORDS);
+fprintf(fid,'$SIZES LIM2=%d\r\n',maxDATARECORDS);
+fprintf(fid,'$SIZES LIM6=%d\r\n',maxDATARECORDS);
+fprintf(fid,'$SIZES LTH=XXX\r\n');
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $PROBLEM
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[xdummyx,problemName]     = fileparts(projectPath);
+fprintf(fid,'$PROBLEM %s\r\n',problemName);
+% Convert model notes to commented nonmem string
+if ~isempty(strtrim(ms.notes)),
+    fprintf(fid,'\r\n; %s\r\n',strrep(ms.notes,sprintf('\n'),sprintf('\n; ')));
+end
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $DATA
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'$DATA %s\r\n',strrep(fullfile(dataRelPathFromProject,dataFileName),'\','/'));
+fprintf(fid,'    IGNORE=@\r\n');
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $INPUT
+% Assumption: names for INPUT are used as in the dataset for CAT,COV,X
+% for all others as in dataHeaderIdent.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dataHeaderIdentAll = explodePCSB(dataHeaderIdent);
+
+text = '$INPUT';
+for k=1:length(dataheader),
+    col     = dataheader{k};
+    coltype = dataHeaderIdentAll{k};
+    
+    % Check if CAT, COV or X
+    if ismember(coltype,{'CAT','COV','X'}),
+        % Use name as in dataset header
+        text = sprintf('%s %s',text,col);
+    elseif strcmp(coltype,'IGNORE'),
+        % If column set to IGNORE then use SKIP in the $INPUT definition
+        text = sprintf('%s SKIP',text);
+    else
+        % Use name as in dataset ident
+        text = sprintf('%s %s',text,coltype);
+    end
+end
+fprintf(fid,'%s\r\n',wrapRowTextSBPOP(text,80,7));
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $SUBROUTINE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'$SUBROUTINE ADVAN13 TOL=6\r\n\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'$MODEL\r\n');
+
+textAll = {};
+maxLength = 0;
+for k=1:length(ms.states),
+    textAll{k} = sprintf('    COMP = (%s)',ms.states(k).name);
+    maxLength = max(maxLength,length(textAll{k}));
+end
+text = '';
+for k=1:length(ms.states),
+    notes = ms.states(k).notes;
+    if isempty(notes),
+        notes = ['Compartment ' num2str(k)];
+    end
+    text = sprintf('%s%s%s; %s\r\n',text,textAll{k},char(32*ones(1,4+maxLength-length(textAll{k}))),notes);
+end
+fprintf(fid,'%s\r\n',text);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $PK - Start
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'$PK\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $PK - PK parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; Parameters\r\n');
+% 1) Define the param_pk parameters that are not estimated, not
+%    obtained as regression parameters
+% These parameters are dosing type dependent parameters and model
+% parameters that appear in the pre-factor of the input definitions
+% Need to define all but Tinf and Rate parameter (defined in dataset)
+for k=1:length(modelInfo.param_pk),
+    if isempty(strfind(modelInfo.param_pk(k).name,'Rate_')) && isempty(strfind(modelInfo.param_pk(k).name,'Tinf_')),
+        if ~isempty(modelInfo.param_pk(k).notes),
+            fprintf(fid,'    %s = %g',modelInfo.param_pk(k).name,modelInfo.param_pk(k).value(1));
+            fprintf(fid,'\t; %s\r\n',modelInfo.param_pk(k).notes);
+        else
+            fprintf(fid,'    %s = %g\r\n',modelInfo.param_pk(k).name,modelInfo.param_pk(k).value(1));
+        end
+    end
+end
+fprintf(fid,'\r\n');
+
+% Write out all other parameters also
+model_element_prefix = '';
+time_variable_replacement = 'TIME2';
+[StatesText, ParametersText, VariablesText, ODEsText] = getmodelPartTextInfo4NONMEMconversion(model,model_element_prefix,param_est,modelInfo,time_variable_replacement);
+if ~isempty(ParametersText),
+    fprintf(fid,'; Parameters\r\n');
+    fprintf(fid,'%s',ParametersText);
+    fprintf(fid,'\r\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $PK - Start by THETAs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+MU_param_text = {};
+for k=1:length(param_est)
+    MU_param_text{k} = sprintf('    MU_%d%s = THETA(%d)%sX#X#X    ; %s\r\n',k,char(32*ones(1,2-length(num2str(k)))),k,char(32*ones(1,2-length(num2str(k)))),param_est(k).name);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $PK - Introduce covariates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+[MU_param_text,THETA_INDEX_BETA,beta_parameters,text_defining_cat_auxiliaries,cov_type_continuous,covparam,covcov,beta_parameters_cov_project_info,beta_parameters_cat_project_info,COV_transformation_info,CAT_reference_info,CAT_categories_info,COVCATestimate_info] = handleCovariateDefinitionsSBPOP(MU_param_text,covariateModel,param_est,covariateMedianValues,covariateMedianNames,covariateCATNames,covariateCATValues,IIVdistribution,COVestimate);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $PK - Write out the auxiliaries if needed
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(text_defining_cat_auxiliaries),
+    fprintf(fid,'; Auxiliary definitions for handling categorical covariates\r\n');
+    fprintf(fid,'%s\r\n',text_defining_cat_auxiliaries);
+end
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $PK - MU Referencing
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; MU Referencing\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle MU_param_text to wrap lines
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+MAXLENGTHLINE = 80;
+for k=1:length(MU_param_text),
+    if length(MU_param_text{k}) > MAXLENGTHLINE,
+        xxx = MU_param_text{k};
+        % Get first additive element
+        ix = strfind(xxx,' + ');
+        ix = ix(1);
+        text_start = xxx(1:ix(1));
+        text_wrap = xxx(ix(1)+3:end);
+        pieces_wrap = {};
+        while length(text_wrap)>MAXLENGTHLINE,
+            ix = strfind(text_wrap,' + ');
+            ixx = ix(find(ix>MAXLENGTHLINE)-1);
+            if ~isempty(ixx),
+                ix = ixx(1);
+            else
+                ix = ix(end);
+            end
+            pieces_wrap{end+1} = text_wrap(1:ix);
+            text_wrap = text_wrap(ix+3:end);
+        end        
+        pieces_wrap{end+1} = text_wrap;
+        for k2=1:length(pieces_wrap),
+            if k2==1,
+                pieces_wrap{k2} = sprintf('    MU%dWRAP_%d = %s',k,k2,strtrim(pieces_wrap{k2}));
+            else
+                pieces_wrap{k2} = sprintf('    MU%dWRAP_%d = MU%dWRAP_%d + %s',k,k2,k,k2-1,strtrim(pieces_wrap{k2}));
+            end
+        end
+        pieces_wrap{end+1} = sprintf('%s + MU%dWRAP_%d',text_start,k,k2);
+        
+        % Put together
+        xxx = '';
+        for k2=1:length(pieces_wrap),
+            xxx = sprintf('%s%s\r\n',xxx,pieces_wrap{k2});
+        end
+        
+        MU_param_text{k} = xxx;
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $PK - Write out the MU parameter definitions with covariates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(MU_param_text),
+    fprintf(fid,'%s',MU_param_text{k});
+end
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $PK - Parameter transformations
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; MU+ETA\r\n');
+for k=1:length(param_est),
+    fprintf(fid,'    T_%s%s = MU_%d + ETA(%d)\r\n',param_est(k).name,char(32*ones(1,cellmaxlengthSBPOP({param_est.name})-length(param_est(k).name)+1)),k,k);
+end
+fprintf(fid,'\r\n');
+
+fprintf(fid,'; Parameter transformations\r\n');
+for k=1:length(param_est),
+    if IIVdistribution{k} == 'N',
+        fprintf(fid,'    %s%s = T_%s\r\n',param_est(k).name,char(32*ones(1,cellmaxlengthSBPOP({param_est.name})-length(param_est(k).name)+1)),param_est(k).name);
+    elseif  IIVdistribution{k} == 'L',
+        fprintf(fid,'    %s%s = EXP(T_%s)\r\n',param_est(k).name,char(32*ones(1,cellmaxlengthSBPOP({param_est.name})-length(param_est(k).name)+1)),param_est(k).name);
+    elseif  IIVdistribution{k} == 'G',
+        fprintf(fid,'    %s%s = EXP(T_%s)/(1+EXP(T_%s))\r\n',param_est(k).name,char(32*ones(1,cellmaxlengthSBPOP({param_est.name})-length(param_est(k).name)+1)),param_est(k).name,param_est(k).name);
+    else
+        error('Unknown distribution.');
+    end
+end
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $PK - Compartment assignment, etc.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; Dosing compartments info\r\n');
+warningInfusion = 0;
+% Collect information about input fraction definitions etc
+Xinfo = [];
+Xinfo.stateindex = [];
+Xinfo.INPUT_NUMBER = [];
+Xinfo.factors = {};
+
+for k=1:length(modelInfo.inputs),
+    stateindex = [modelInfo.inputs(k).stateindex];
+    factors = modelInfo.inputs(k).factors;
+    % Get input number for comparison with "INPUT" dataset column
+    INPUT_NUMBER = str2double(strrep(modelInfo.inputs(k).name,'INPUT',''));
+    % Check if partial application into different compartments =>
+    % we do not allow that!
+    if length(stateindex) ~= 1,
+        error('Partial application of a dose into different compartments not supported yet by the MLXTRAN conversion.');
+    end
+    
+    Xinfo.stateindex(end+1) = stateindex(1);
+    Xinfo.INPUT_NUMBER(end+1) = INPUT_NUMBER;
+    Xinfo.factors{end+1} = factors{1};
+end
+
+% Here for NONMEM that is relatively straight forward ... only need to
+% define the Fn parameters for each compartment based on the dosing
+% information from the models input
+for k=1:length(Xinfo.stateindex),
+    fprintf(fid,'    F%d = %s%s; %s\r\n',Xinfo.stateindex(k),Xinfo.factors{k},char(32*ones(1,cellmaxlengthSBPOP(Xinfo.factors)-length(Xinfo.factors{k})+1)),ms.states(Xinfo.stateindex(k)).name );
+end
+fprintf(fid,'\r\n');
+
+% Infusion with bioavailability terms ... or conversion to other unit terms
+% is not allowed in NONMEM conversion. The bioavailability part is not
+% applied to the RATE ... really really really stupid.
+for k=1:length(Xinfo.stateindex),
+    % Get dosing data with input number
+    datak = dataModeling(dataModeling.YTYPE==0 & dataModeling.ADM==Xinfo.INPUT_NUMBER(k),:);
+    % Check if RATE>0 for these doses (at least one rate)
+    if max(datak.RATE)>0,
+        % Check if bioavailability term present
+        factor = Xinfo.factors{k};
+        if ~strcmp(factor,'1'),
+            error(sprintf('NONMEM does not apply bioavailability factors (or unit conversions) to RATE.\nPlease consider changing the unit of your input to not need a pre-factor - or use MONOLIX!'));
+        end
+    end
+end
+fprintf(fid,'\r\n');
+
+% Also define the lag times if present
+for k=1:length(modelInfo.inputs),
+    % Get state/compartment number for input
+    STATE_NUMBER = modelInfo.inputs(k).stateindex;
+    % Write out the ALAGn statement if Tlag defined
+    if ~isempty(modelInfo.inputs(k).Tlag),
+        fprintf(fid,'    ALAG%d = %s\r\n',STATE_NUMBER,modelInfo.inputs(k).TlagName);
+    end
+end
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check for infusion presence
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ismember('INFUSION',{modelInfo.inputs.type}),
+    % Warn the user:
+    if ~SILENT,
+        disp(' ');
+        fprintf('==========================================================\n');
+        fprintf('Infusion administration present in model:\n');
+        fprintf('Make sure you have a RATE column in your dataset!\n');
+        fprintf('==========================================================\n');
+        disp(' ');
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Tell the user how to map INPUTn and OUTPUTn with the CMT column or 
+% with the optional ADM and YTYPE columns.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+if ~SILENT,
+    if FLAG_CMT,
+        disp('===============================================================================');
+        disp('IMPORTANT:');
+        disp('The dataset contains the "CMT" column. In order to correctly map dosing inputs');
+        disp('and observations with the CMT column, please make sure you used the following');
+        disp('entries in the CMT column:');
+        disp(' ');
+        disp('Mapping of the INPUTn in the model and the CMT column in the dataset:');
+        for k=1:length(modelInfo.inputs),
+            % Get state/compartment number for input
+            STATE_NUMBER = modelInfo.inputs(k).stateindex;
+            INPUT_NUMBER = eval(strrep(modelInfo.inputs(k).name,'INPUT',''));
+            fprintf('INPUT%d => CMT column value: %d\n',INPUT_NUMBER,STATE_NUMBER);
+        end
+        disp(' ');
+        disp('Mapping of the OUTPUTn in the model and the CMT column in the dataset:');
+        for k=1:length(modelInfo.outputs),
+            OUTPUT_NUMBER = eval(strrep(modelInfo.outputs(k).name,'OUTPUT',''));        
+            fprintf('OUTPUT%d => CMT column value: %d\n',OUTPUT_NUMBER,OUTPUT_NUMBER);
+        end
+        disp('===============================================================================');
+    else
+        disp('===============================================================================');
+        disp('IMPORTANT:');
+        disp('The dataset contains the "ADM" and "YTYPE" columns. In order to correctly map');
+        disp('dosing inputs and observations with the these columns, please make sure you');
+        disp('used the following entries in the "ADM" and "YTYPE" columns:');
+        disp(' ');
+        disp('Mapping of the INPUTn in the model and the ADM column in the dataset:');
+        for k=1:length(modelInfo.inputs),
+            % Get state/compartment number for input
+            STATE_NUMBER = modelInfo.inputs(k).stateindex;
+            INPUT_NUMBER = eval(strrep(modelInfo.inputs(k).name,'INPUT',''));
+            fprintf('INPUT%d => ADM column value: %d\n',INPUT_NUMBER,STATE_NUMBER);
+        end
+        disp(' ');
+        disp('Mapping of the OUTPUTn in the model and the YTYPE column in the dataset:');
+        for k=1:length(modelInfo.outputs),
+            OUTPUT_NUMBER = eval(strrep(modelInfo.outputs(k).name,'OUTPUT',''));        
+            fprintf('OUTPUT%d => YTYPE column value: %d\n',OUTPUT_NUMBER,OUTPUT_NUMBER);
+        end
+        disp('===============================================================================');        
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $PK - Initial conditions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; Initial conditions\r\n');
+for k=1:length(ms.states),
+    ic = ms.states(k).initialCondition;
+    if isnumeric(ic),
+        fprintf(fid,'    A_0(%d) = %g\r\n',k,ic);
+    else
+        fprintf(fid,'    A_0(%d) = %s\r\n',k,ic);
+    end        
+end
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $PK - Define TIMEOFFSET
+% For NONMEM this is the difference between TIME and TIME2
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; Define TIMEOFFSET\r\n');
+fprintf(fid,'    TIMEOFFSET = TIME-TIME2\r\n');
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $DES - Start
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'$DES\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get model information 
+% Use "DES_" as prefix and (T-TIMEOFFSET) as time variable T
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+model_element_prefix = 'DES_';
+time_variable_replacement = '(T-TIMEOFFSET)';
+[StatesText, ParametersText, VariablesText, ODEsText] = getmodelPartTextInfo4NONMEMconversion(model,model_element_prefix,param_est,modelInfo,time_variable_replacement);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $DES Write out the components
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; States\r\n');
+fprintf(fid,'%s',StatesText);
+fprintf(fid,'\r\n');
+
+if ~isempty(ParametersText),
+    fprintf(fid,'; Parameters\r\n');
+    fprintf(fid,'%s',ParametersText);
+    fprintf(fid,'\r\n');
+end
+
+if ~isempty(VariablesText),
+    fprintf(fid,'; Variables\r\n');
+    fprintf(fid,'%s',VariablesText);
+    fprintf(fid,'\r\n');
+end
+
+fprintf(fid,'; ODEs\r\n');
+fprintf(fid,'%s',ODEsText);
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $ERROR
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'$ERROR\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get model information 
+% Use empty prefix and (TIME2) as time variable T
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+model_element_prefix = '';
+time_variable_replacement = 'TIME2';
+[StatesText, ParametersText, VariablesText, ODEsText] = getmodelPartTextInfo4NONMEMconversion(model,model_element_prefix,param_est,modelInfo,time_variable_replacement);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $ERROR Write out the components
+% Dont write out parameters here - do that in $PK
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; States\r\n');
+fprintf(fid,'%s',StatesText);
+fprintf(fid,'\r\n');
+
+if ~isempty(VariablesText),
+    fprintf(fid,'; Variables\r\n');
+    fprintf(fid,'%s',VariablesText);
+    fprintf(fid,'\r\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $ERROR - error models
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define next index for THETA parameters
+if isempty(THETA_INDEX_BETA),
+    THETA_INDEX_NEXT = length(param_est)+1;
+else
+    THETA_INDEX_NEXT = max(THETA_INDEX_BETA)+1;
+end
+THETA_ERROR_MODELS_IX = [];
+THETA_ERROR_MODELS_NAME = {};
+THETA_ERROR_MODELS_VALUE = [];
+error_model = explodePCSB(errorModels);
+
+if FLAG_CMT,
+    fprintf(fid,'; Use CMT as YTYPE information\r\n');
+    fprintf(fid,'    IF(EVID.EQ.1) THEN\r\n');
+    fprintf(fid,'        YTYPE = 0\r\n');
+    fprintf(fid,'    ELSE\r\n');
+    fprintf(fid,'       YTYPE = CMT\r\n');
+    fprintf(fid,'    ENDIF\r\n');
+    fprintf(fid,'\r\n');
+end
+
+fprintf(fid,'; just to avoid a NONMEM warning\r\n');
+fprintf(fid,'    IPRED = 0.1\r\n');
+fprintf(fid,'    IRES  = 0\r\n');
+fprintf(fid,'    IWRES = 0\r\n');
+fprintf(fid,'    W     = 0\r\n');
+fprintf(fid,'    Y     = 0.1\r\n\r\n');
+
+output_parameters_project_info = {};
+count = 1;
+for k=1:length(ms.outputs),
+    fprintf(fid,'; Error model %s / %s\r\n',ms.outputs(k).name,ms.outputs(k).formula);
+    outputNumber = eval(strrep(ms.outputs(k).name,'OUTPUT',''));
+    fprintf(fid,'    IF(YTYPE.EQ.%d) THEN\r\n',outputNumber);
+    fprintf(fid,'        IPRED  = %s\r\n',ms.outputs(k).formula);
+    fprintf(fid,'        IRES   = DV - IPRED\r\n');
+    
+    if strcmpi(error_model{k},'const'),
+        fprintf(fid,'        W      = THETA(%d)\r\n',THETA_INDEX_NEXT); 
+        THETA_ERROR_MODELS_IX(end+1) = THETA_INDEX_NEXT;
+        THETA_ERROR_MODELS_NAME{end+1} = sprintf('Additive error %s',ms.outputs(k).name);
+        THETA_ERROR_MODELS_VALUE(end+1) = errorParam0(count);
+        count = count + 1;
+        THETA_INDEX_NEXT = THETA_INDEX_NEXT+1;
+        output_parameters_project_info{end+1} = sprintf('error_ADD%d',outputNumber);
+    elseif strcmpi(error_model{k},'prop'),
+        fprintf(fid,'        W      = THETA(%d)*IPRED\r\n',THETA_INDEX_NEXT); 
+        THETA_ERROR_MODELS_IX(end+1) = THETA_INDEX_NEXT;
+        THETA_ERROR_MODELS_NAME{end+1} = sprintf('Proportional error %s',ms.outputs(k).name);
+        THETA_ERROR_MODELS_VALUE(end+1) = errorParam0(count);
+        count = count + 1;
+        THETA_INDEX_NEXT = THETA_INDEX_NEXT+1;
+        output_parameters_project_info{end+1} = sprintf('error_PROP%d',outputNumber);
+    elseif strcmpi(error_model{k},'comb1'),
+        fprintf(fid,'        W      = SQRT(THETA(%d)**2 + (THETA(%d)*IPRED)**2)\r\n',THETA_INDEX_NEXT,THETA_INDEX_NEXT+1); 
+        THETA_ERROR_MODELS_IX(end+1) = THETA_INDEX_NEXT;
+        THETA_ERROR_MODELS_IX(end+1) = THETA_INDEX_NEXT+1;
+        THETA_ERROR_MODELS_NAME{end+1} = sprintf('Additive error %s',ms.outputs(k).name);
+        THETA_ERROR_MODELS_NAME{end+1} = sprintf('Proportional error %s',ms.outputs(k).name);
+        THETA_ERROR_MODELS_VALUE(end+1) = errorParam0(count);
+        count = count + 1;
+        THETA_ERROR_MODELS_VALUE(end+1) = errorParam0(count);
+        count = count + 1;
+        THETA_INDEX_NEXT = THETA_INDEX_NEXT+2;
+        output_parameters_project_info{end+1} = sprintf('error_ADD%d',outputNumber);
+        output_parameters_project_info{end+1} = sprintf('error_PROP%d',outputNumber);
+    else
+        error('Unknown error model definition.');
+    end
+    fprintf(fid,'        IWRES  = IRES/W\r\n');
+	fprintf(fid,'        Y      = IPRED + W*ERR(%d)\r\n',k);
+    fprintf(fid,'    ENDIF\r\n');
+    fprintf(fid,'\r\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Assign variables to report in tables
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% ETAs:
+fprintf(fid,'; Assign variables to report in tables\r\n');
+for k=1:length(param_est),
+    fprintf(fid,'    ETA_%s%s = ETA(%d)\r\n',param_est(k).name,char(32*ones(1,cellmaxlengthSBPOP({param_est(k).name})-length(param_est(k).name)+1)),k);
+end
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $THETA for model parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'$THETA\r\n');
+
+fprintf(fid,'; Model parameters\r\n');
+
+THETA_GUESS0_STRING = {};
+PARAM_TRANSNAME_STRING = {};
+PARAM_INVTRANSNAME_STRING = {};
+initialGuess_noTrans = [];
+for k=1:length(param_est),
+    initialGuess = POPvalues0(k);
+    initialGuess_noTrans(k) = POPvalues0(k);
+    if IIVdistribution{k} == 'N',
+        initialGuess = initialGuess;
+        if POPestimate(k),
+            if initialGuess == 0,
+                initialGuess = 0.01;
+            end
+        end
+        PARAM_TRANSNAME_STRING{k} = '(psi)';
+        PARAM_INVTRANSNAME_STRING{k} = '(phi)';
+    elseif IIVdistribution{k} == 'L';
+        initialGuess = log(initialGuess);
+        if POPestimate(k),
+            if initialGuess == 0,
+                initialGuess = 0.01;
+            end
+        end
+        PARAM_TRANSNAME_STRING{k} = 'log(psi)';
+        PARAM_INVTRANSNAME_STRING{k} = 'exp(phi)';
+    elseif IIVdistribution{k} == 'G',
+        initialGuess = log(initialGuess/(1-initialGuess));
+        if POPestimate(k),
+            if initialGuess == 0,
+                initialGuess = 0.01;
+            end
+        end
+        PARAM_TRANSNAME_STRING{k} = 'log(psi./(1-psi))';
+        PARAM_INVTRANSNAME_STRING{k} = 'exp(phi)./(1+exp(phi))';
+    else
+        error('Unknown parameter transformation.');
+    end
+    THETA_GUESS0_STRING{k} = sprintf('%1.3g',initialGuess);
+    % Check if parameter fixed or not
+    if POPestimate(k) == 0,
+        THETA_GUESS0_STRING{k} = [THETA_GUESS0_STRING{k} '  FIX'];
+    end
+end    
+
+for k=1:length(param_est),
+    texttext = strrep(PARAM_TRANSNAME_STRING{k},'psi',param_est(k).name);
+    fprintf(fid,'    %s%s ; %d %s (%1.3g)\r\n',THETA_GUESS0_STRING{k},char(32*ones(1,cellmaxlengthSBPOP(THETA_GUESS0_STRING)-length(THETA_GUESS0_STRING{k})+1)),k,texttext,initialGuess_noTrans(k));
+end
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $THETA for continuous covariate parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+THETA_INDEX_BETA_cov = THETA_INDEX_BETA(cov_type_continuous==1);
+beta_parameters_cov  = beta_parameters(cov_type_continuous==1);
+
+if ~isempty(COVestimate) && ~isempty(THETA_INDEX_BETA_cov),
+    fprintf(fid,'; Continuous covariate model parameters\r\n');
+    count = 1;
+    for kparam=1:length(COVestimate),
+        for kcov=1:length(COVestimate{kparam}),
+            estimate = COVestimate{kparam}(kcov);
+            value    = covariateModelValues{kparam}(kcov);
+            cov      = covariateModel{kparam}{kcov+1};
+            if ismember(cov,covNames),
+                % Only handle if covariate member iof continuous covariates
+                index    = THETA_INDEX_BETA_cov(count);
+                param    = beta_parameters_cov{count};
+                count    = count+1;
+                if estimate,
+                    if value==0,
+                        value = 0.01;
+                    end
+                    fprintf(fid,'    %g ; %d %s\r\n',value,index,param);
+                else
+                    fprintf(fid,'    %g FIX ; %d %s\r\n',value,index,param);
+                end
+            end
+        end
+    end
+    fprintf(fid,'\r\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $THETA for categorical covariate parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+THETA_INDEX_BETA_cat = THETA_INDEX_BETA(cov_type_continuous==0);
+beta_parameters_cat  = beta_parameters(cov_type_continuous==0);
+covcov_cat           = covcov(cov_type_continuous==0);
+covparam_cat         = covparam(cov_type_continuous==0);
+
+if ~isempty(COVestimate) &&  ~isempty(THETA_INDEX_BETA_cat),
+    fprintf(fid,'; Categorical covariate model parameters\r\n');
+    for k=1:length(THETA_INDEX_BETA_cat),
+        % Get parameter name
+        param = covparam_cat{k};
+        % Get covariate name
+        cov = covcov_cat{k};
+        
+        % Find index of parameter in covariateModel
+        covModelAllParam = {};
+        for k2=1:length(covariateModel),
+            covModelAllParam{end+1} = covariateModel{k2}{1};
+        end
+        ixparam = strmatchSB(param,covModelAllParam,'exact');
+        
+        % Find index of cov in covariateModel{ixparam}
+        ixcov = strmatchSB(cov,covariateModel{ixparam},'exact');
+        
+        % Is this covariate estimated?
+        estimate = COVestimate{ixparam}(ixcov-1);
+        
+        % Which is the value
+        value = covariateModelValues{ixparam}(ixcov-1);
+        
+        % Write out
+        if estimate,
+            if value == 0,
+                value = 0.01;
+            end
+            fprintf(fid,'    %g ; %d %s\r\n',value,THETA_INDEX_BETA_cat(k),beta_parameters_cat{k});
+        else
+            fprintf(fid,'    %g FIX ; %d %s\r\n',value,THETA_INDEX_BETA_cat(k),beta_parameters_cat{k});
+        end
+    end
+    fprintf(fid,'\r\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $THETA for error model parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'; Error model parameters\r\n');
+for k=1:length(THETA_ERROR_MODELS_IX),
+    fprintf(fid,'    %g%s ; %d %s\r\n',THETA_ERROR_MODELS_VALUE(k),char(32*ones(1,cellmaxlengthSBPOP(THETA_GUESS0_STRING)-length('1')+1)),THETA_ERROR_MODELS_IX(k),THETA_ERROR_MODELS_NAME{k});
+end
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $OMEGA
+% Using standard deviations and correlations
+%
+% $OMEGA STANDARD CORRELATION BLOCK(2)
+% 0.8
+% -0.394 0.762
+%
+% or:
+% $OMEGA
+% 0.8 STANDARD
+% 0.5 STANDARD
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+	
+if strcmp(lower(covarianceModel),'diagonal') || isempty(covarianceModel),
+    fprintf(fid,'$OMEGA\r\n');
+    OMEGA_GUESS0_STRING = {};
+    for k=1:length(param_est),
+        if IIVestimate(k) == 0,
+            % Set IIV value to 0 and FIX
+            OMEGA_GUESS0_STRING{k} = sprintf('0 STANDARD FIX');
+        elseif IIVestimate(k) == 1,
+            value = IIVvalues0(k);
+            if value == 0,
+                value = 0.1;
+            end
+            % Set IIV value
+%             OMEGA_GUESS0_STRING{k} = sprintf('%1.2g',(value)^2); % Convert IIV values from STD to VAR
+            OMEGA_GUESS0_STRING{k} = sprintf('%1.2g STANDARD',value); % USE STD
+        elseif IIVestimate(k) == 2,
+            % Set IIV value and FIX
+%             OMEGA_GUESS0_STRING{k} = sprintf('%1.2g  FIX',(IIVvalues0(k))^2); % Convert IIV values from STD to VAR
+            OMEGA_GUESS0_STRING{k} = sprintf('%1.2g STANDARD FIX',IIVvalues0(k)); % Convert IIV values from STD to VAR
+        end
+    end
+    for k=1:length(param_est),
+        fprintf(fid,'    %s%s ; %d %s\r\n',OMEGA_GUESS0_STRING{k},char(32*ones(1,cellmaxlengthSBPOP(OMEGA_GUESS0_STRING)-length(OMEGA_GUESS0_STRING{k})+1)),k,param_est(k).name);
+    end
+else
+    % Handle the covariances ... block by block
+    terms = explodePCSB(covarianceModel,',','{','}');
+    for k=1:length(terms),
+        block = terms{k};
+        block = strrep(block,'{','');
+        block = strrep(block,'}','');
+        block = explodePCSB(block);
+        ix_parameters = [];
+        for k2=1:length(block),
+            ix_parameters(end+1) = strmatchSB(block{k2},{param_est.name},'exact');
+        end
+        % Need to reorder each block to match the order of the parameters
+        % in param_est.name. It already has been made sure that they are
+        % sequential.
+        ix_parameters_ordered = sort(ix_parameters,'ascend');
+        % Construct the block text
+        blockText = sprintf('$OMEGA STANDARD CORRELATION BLOCK(%d)\r\n',length(block));
+        blockMatrix = 0.1*ones(length(ix_parameters_ordered));
+        for k=1:length(ix_parameters_ordered),
+            value = IIVvalues0(ix_parameters_ordered(k));
+            if value == 0,
+                value = 0.1;
+            end
+            blockMatrix(k,k) = value; % No need to convert, since in STD
+        end
+        for krow=1:length(block),
+            for kcol=1:krow,
+                if kcol ~= krow,
+                    blockText = sprintf('%s    %1.2g',blockText,blockMatrix(krow,kcol));
+                else
+                    if IIVestimate(ix_parameters_ordered(krow)) == 2,
+                        blockText = sprintf('%s    %1.2g FIX',blockText,blockMatrix(krow,kcol));
+                    else
+                        blockText = sprintf('%s    %1.2g',blockText,blockMatrix(krow,kcol));
+                    end
+                end
+            end
+            blockText = sprintf('%s    ; %d %s',blockText,ix_parameters_ordered(krow),param_est(ix_parameters_ordered(krow)).name);
+            blockText = sprintf('%s\r\n',blockText);
+        end
+        fprintf(fid,'%s\r\n',blockText);
+    end
+    
+    % Finally find the parameters that have not been handled yet by the
+    % block things ...
+    x = strrep(covarianceModel,'{','');
+    x = strrep(x,'}','');
+    terms = explodePCSB(x);
+    missingParam = setdiff({param_est.name},terms);
+    % These are not in the right order ...
+    ix_parameters = [];
+    for k2=1:length(missingParam),
+        ix_parameters(end+1) = strmatchSB(missingParam{k2},{param_est.name},'exact');
+    end
+    % Need to reorder according to their appearance in the model
+    % It already has been made sure that they are sequential.
+    ix_parameters_ordered = sort(ix_parameters,'ascend');
+    
+    if ~isempty(missingParam),
+        fprintf(fid,'$OMEGA\r\n');
+    end
+    OMEGA_GUESS0_STRING = {};
+    for k=1:length(missingParam),
+        if IIVestimate(ix_parameters_ordered(k)) == 0,
+            % Set IIV value to 0 and FIX
+            OMEGA_GUESS0_STRING{k} = sprintf('0 STANDARD FIX');
+        elseif IIVestimate(ix_parameters_ordered(k)) == 1,
+            value = IIVvalues0(ix_parameters_ordered(k));
+            if value == 0,
+                value = 0.1;
+            end
+            % Set IIV value
+            OMEGA_GUESS0_STRING{k} = sprintf('%1.2g STANDARD',value); % Need to convert from STD to VAR
+        elseif IIVestimate(ix_parameters_ordered(k)) == 2,
+            % Set IIV value and FIX
+            OMEGA_GUESS0_STRING{k} = sprintf('%1.2g STANDARD FIX',IIVvalues0(ix_parameters_ordered(k))); % Need to convert from STD to VAR
+        end
+    end    
+    for k=1:length(missingParam),
+        fprintf(fid,'    %s%s ; %d %s\r\n',OMEGA_GUESS0_STRING{k},char(32*ones(1,cellmaxlengthSBPOP(OMEGA_GUESS0_STRING)-length(OMEGA_GUESS0_STRING{k})+1)),ix_parameters_ordered(k),param_est(ix_parameters_ordered(k)).name);
+    end
+end
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $SIGMA
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'$SIGMA\r\n');
+for k=1:length(ms.outputs),
+    fprintf(fid,'    1 FIX\r\n');
+end   
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $ESTIMATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if ITS done as first method
+if ITS,
+    % ITS
+    if strcmp(upper(METHOD),'FO') || strcmp(upper(METHOD),'FOCE'),
+        text = sprintf('$ESTIMATION METHOD=ITS NOINTERACTION NOABORT NITER=%d SIGDIGITS=%d PRINT=%d\r\n',ITS_ITERATIONS,SIGDIGITS,PRINT);
+    else
+        text = sprintf('$ESTIMATION METHOD=ITS INTERACTION NOABORT NITER=%d SIGDIGITS=%d PRINT=%d\r\n',ITS_ITERATIONS,SIGDIGITS,PRINT);
+    end
+    fprintf(fid,'%s\r\n',wrapRowTextSBPOP(text,80,12));
+end    
+
+% Then the "Main" Method
+if strcmp(upper(METHOD),'FO'),
+    % FO
+    text = sprintf('$ESTIMATION METHOD=ZERO NOINTERACTION NOABORT MAXEVAL=%d CTYPE=4 POSTHOC SIGDIGITS=%d PRINT=%d\r\n',MAXEVAL,SIGDIGITS,PRINT);
+    fprintf(fid,'%s\r\n',wrapRowTextSBPOP(text,80,12));
+elseif strcmp(upper(METHOD),'FOCE'),
+    % FOCE
+    text = sprintf('$ESTIMATION METHOD=CONDITIONAL NOINTERACTION NOABORT MAXEVAL=%d CTYPE=4 POSTHOC SIGDIGITS=%d PRINT=%d\r\n',MAXEVAL,SIGDIGITS,PRINT);
+    fprintf(fid,'%s\r\n',wrapRowTextSBPOP(text,80,12));
+elseif strcmp(upper(METHOD),'FOCEI'),
+    % FOCEI
+    text = sprintf('$ESTIMATION METHOD=CONDITIONAL INTERACTION NOABORT MAXEVAL=%d CTYPE=4 POSTHOC SIGDIGITS=%d PRINT=%d\r\n',MAXEVAL,SIGDIGITS,PRINT);
+    fprintf(fid,'%s\r\n',wrapRowTextSBPOP(text,80,12));
+elseif strcmp(upper(METHOD),'SAEM'),
+    % SAEM
+    text = sprintf('$ESTIMATION METHOD=SAEM INTERACTION NOABORT NBURN=%d NITER=%d ISAMPLE=%d CONSTRAIN=1 CTYPE=0 SEED=%d POSTHOC SIGDIGITS=%d PRINT=%d\r\n',K1,K2,NRCHAINS,SEED,SIGDIGITS,PRINT);
+    fprintf(fid,'%s\r\n',wrapRowTextSBPOP(text,80,12));
+else
+    error('Unknown estimation method.');
+end
+
+% Then check if importance sampling to be done for objective function evaluation
+if IMPORTANCESAMPLING,
+    text = sprintf('$ESTIMATION METHOD=IMP NOABORT EONLY=1 ISAMPLE=1000 NITER=%d MAPITER=0 SIGDIGITS=%d PRINT=%d',IMP_ITERATIONS,SIGDIGITS,PRINT);
+    fprintf(fid,'%s\r\n',wrapRowTextSBPOP(text,80,12));
+end
+
+fprintf(fid,'\r\n');
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $COVARIANCE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'$COVARIANCE UNCONDITIONAL MATRIX=S\r\n');
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define FORMAT for all TABLEs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+FORMAT = 's1PG15.6';
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $TABLE similar to predictions.txt in MONOLIX 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp(METHOD,'FO'),
+    text = sprintf('$TABLE ID TIME TIME2 YTYPE MDV EVID DV IPRED IRES IWRES NPDE NPRED=XPRED  NRES=XRES  NWRES=XWRES  NOPRINT ONEHEADER NOAPPEND FILE=project.pred FORMAT=%s',FORMAT);
+elseif strcmp(METHOD,'FOCE'), 
+    text = sprintf('$TABLE ID TIME TIME2 YTYPE MDV EVID DV IPRED IRES IWRES NPDE NPRED=XPRED  CRES=XRES  CWRES=XWRES  NOPRINT ONEHEADER NOAPPEND FILE=project.pred FORMAT=%s',FORMAT);
+elseif strcmp(METHOD,'FOCEI'),
+    text = sprintf('$TABLE ID TIME TIME2 YTYPE MDV EVID DV IPRED IRES IWRES NPDE CPREDI=XPRED CRESI=XRES CWRESI=XWRES NOPRINT ONEHEADER NOAPPEND FILE=project.pred FORMAT=%s',FORMAT);
+elseif strcmp(METHOD,'SAEM'),
+    text = sprintf('$TABLE ID TIME TIME2 YTYPE MDV EVID DV IPRED IRES IWRES NPDE EPRED=XPRED  ERES=XRES  EWRES=XWRES  NOPRINT ONEHEADER NOAPPEND FILE=project.pred FORMAT=%s ESAMPLE=1000 SEED=%d',FORMAT,SEED);
+else
+    error('Unknown method');
+end
+text = wrapRowTextSBPOP(text,80,7);
+% Print out table command
+fprintf(fid,'%s\r\n',text);
+fprintf(fid,'\r\n');
+  
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $TABLE similar to indiv_eta.txt in MONOLIX - include all covariates
+% in the dataset
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+text = 'ID';
+for k=1:length(param_est),
+    text = sprintf('%s ETA_%s',text,param_est(k).name);
+end
+% Add covariates
+for k=1:length(covNames),
+    text = sprintf('%s %s',text,covNames{k});
+end
+for k=1:length(catNames),
+    text = sprintf('%s %s',text,catNames{k});
+end
+% Create the full table command
+text = sprintf('$TABLE %s NOPRINT ONEHEADER FIRSTONLY NOAPPEND FILE=project.eta FORMAT=%s',text,FORMAT);
+text = wrapRowTextSBPOP(text,80,7);
+% Print out table command
+fprintf(fid,'%s\r\n',text);
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% $TABLE similar to indiv_parameters.txt in MONOLIX - include all covariates
+% in the dataset - also include the regression parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+text = 'ID';
+for k=1:length(param_est),
+    text = sprintf('%s %s',text,param_est(k).name);
+end
+% Add regression parameters
+for k=1:length(modelInfo.param_reg),
+    text = sprintf('%s %s',text,modelInfo.param_reg(k).name);
+end
+% Add covariates
+for k=1:length(covNames),
+    text = sprintf('%s %s',text,covNames{k});
+end
+for k=1:length(catNames),
+    text = sprintf('%s %s',text,catNames{k});
+end
+% Create the full table command
+text = sprintf('$TABLE %s NOPRINT ONEHEADER FIRSTONLY NOAPPEND FILE=project.indiv FORMAT=%s',text,FORMAT);
+text = wrapRowTextSBPOP(text,80,7);
+% Print out table command
+fprintf(fid,'%s\r\n',text);
+fprintf(fid,'\r\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Close file and change out of project path
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fclose(fid);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Construct PROJECT_HEADER_PLACEHOLDER information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+PROJECT_INFO_TEXT = '';
+
+% Method
+METHOD_ALL = METHOD;
+if ITS,
+    METHOD_ALL = ['ITS,' METHOD_ALL];
+end
+if IMPORTANCESAMPLING,
+    METHOD_ALL = [METHOD_ALL ',IMP'];
+end
+METHOD_info = sprintf('; METHOD              = ''%s''\r\n',METHOD_ALL);
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,METHOD_info);
+
+% Data location
+DATA_info = sprintf('; DATA                = ''%s''\r\n',strrep(fullfile(dataRelPathFromProject,dataFileName),'\','/'));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,DATA_info);
+
+% covNames
+x = sprintf('%s,',covNames{:});
+COVNAMES_info = sprintf('; COVNAMES            = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,COVNAMES_info);
+
+% catNames
+x = sprintf('%s,',catNames{:});
+CATNAMES_info = sprintf('; CATNAMES            = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,CATNAMES_info);
+
+% Outputs
+x = cell(1,length(modelInfo.outputs));
+for k=1:length(modelInfo.outputs),
+    on = eval(strrep(modelInfo.outputs(k).name,'OUTPUT',''));
+    x{on} = modelInfo.outputs(k).formula;
+end
+y = '';
+for k=1:length(x),
+    y = sprintf('%s%s,',y,x{k});
+end
+y = y(1:end-1);
+OUTPUTS_info = sprintf('; OUTPUTS             = ''%s''\r\n',y);
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,OUTPUTS_info);
+
+% Error models
+ERRORMODELS_info = sprintf('; ERRORMODELS         = ''%s''\r\n',errorModels);
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,ERRORMODELS_info);
+
+% ERRORNAMES
+x = sprintf('%s,',output_parameters_project_info{:});
+ERRORNAMES_info = sprintf('; ERRORNAMES          = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,ERRORNAMES_info);
+
+% PARAMNAMES
+x = sprintf('%s,',param_est.name);
+PARAMNAMES_info = sprintf('; PARAMNAMES          = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,PARAMNAMES_info);
+
+% PARAMTRANS
+x = sprintf('%s,',PARAM_TRANSNAME_STRING{:});
+PARAMTRANS_info = sprintf('; PARAMTRANS          = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,PARAMTRANS_info);
+
+% PARAMINVTRANS
+x = sprintf('%s,',PARAM_INVTRANSNAME_STRING{:});
+PARAMINVTRANS_info = sprintf('; PARAMINVTRANS       = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,PARAMINVTRANS_info);
+
+% COVARIATENAMES
+COVARIATENAMES = [covariateMedianNames,covariateCATNames];
+x = sprintf('%s,',COVARIATENAMES{:});
+COVARIATENAMES_info = sprintf('; COVARIATENAMES      = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,COVARIATENAMES_info);
+
+% BETACOVNAMES
+x = sprintf('%s,',beta_parameters_cov_project_info{:});
+BETACOVNAMES_info = sprintf('; BETACOVNAMES        = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,BETACOVNAMES_info);
+
+% TRANSCOV
+x = sprintf('%s,',COV_transformation_info{:});
+TRANSCOV_info = sprintf('; TRANSCOV            = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,TRANSCOV_info);
+
+% BETACATNAMES
+x = sprintf('%s,',beta_parameters_cat_project_info{:});
+BETACATNAMES_info = sprintf('; BETACATNAMES        = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,BETACATNAMES_info);
+
+% BETACATREFERENCE
+x = ''; for k=1:length(CAT_reference_info), x=sprintf('%s%g,',x,CAT_reference_info{k}); end
+BETACATREFERENCE_info = sprintf('; BETACATREFERENCE    = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,BETACATREFERENCE_info);
+
+% BETACATCATEGORIES
+x = ''; 
+for k=1:length(CAT_categories_info), 
+    x = [x '['];
+    x2 = '';
+    x2 = sprintf('%d ',CAT_categories_info{k});
+    x = [x x2(1:end-1) '],'];
+end
+BETACATCATEGORIES_info = sprintf('; BETACATCATEGORIES   = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,BETACATCATEGORIES_info);
+
+% ALL THETANAMES
+x = [{param_est.name} beta_parameters output_parameters_project_info];
+y = sprintf('%s,',x{:});
+THETANAMES_info = sprintf('; THETANAMES          = ''%s''\r\n',y(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,THETANAMES_info);
+
+% THETAESTIMATE
+% Add theta for parameters
+PARAM_info = sprintf('%d,',POPestimate);
+% Add theta for covariates
+COVCAT_info = sprintf('%d,',COVCATestimate_info);
+if isempty(COVCATestimate_info),
+    COVCAT_info = [];
+end
+% Add theta for error models
+x = ones(1,length(output_parameters_project_info));
+ERROR_info = sprintf('%d,',x);
+% Combine
+ESTIMATE_info = strtrim([PARAM_info COVCAT_info ERROR_info]);
+% Create text
+THETAESTIMATE_info = sprintf('; THETAESTIMATE       = ''%s''\r\n',ESTIMATE_info(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,THETAESTIMATE_info);
+
+% ALL ETANAMES (should be same as PARAMNAMES)
+x = sprintf('omega(%s),',param_est.name);
+ETANAMES_info = sprintf('; ETANAMES            = ''%s''\r\n',x(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,ETANAMES_info);
+
+% ETAESTIMATE
+ETAESTIMATE = sprintf('%d,',IIVestimate); 
+ETAESTIMATE_info = sprintf('; ETAESTIMATE         = ''%s''\r\n',ETAESTIMATE(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,ETAESTIMATE_info);
+
+% ALL CORRNAMES 
+cov = explodePCSB(covarianceModel,',','{','}');
+text = '';
+for k=1:length(cov),
+    covk = strrep(strrep(cov{k},'{',''),'}','');
+    covk = explodePCSB(covk);
+    for k1=1:length(covk),
+        for k2=1:k1,
+            if k1~=k2,
+                text = sprintf('%scorr(%s,%s),',text,covk{k1},covk{k2});
+            end
+        end
+    end
+end
+CORR_info = sprintf('; CORRELATIONNAMES    = ''%s''\r\n',text(1:end-1));
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,CORR_info);
+
+% CORRESTIMATE
+if ~isempty(text),
+    CORRestimate = ones(1,length(explodePCSB(text(1:end-1))));
+    x = sprintf('%d,',CORRestimate); 
+    CORRESTIMATE_info = sprintf('; CORRESTIMATE        = ''%s''\r\n',x(1:end-1));
+else
+    CORRestimate = 0;
+    CORRESTIMATE_info = sprintf('; CORRESTIMATE        = ''''\r\n');
+end
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,CORRESTIMATE_info);
+
+% Get and store number of observations in the data
+% Remove MDV=1 records
+x = dataCSV(dataCSV.MDV==0,:);
+% Remove CMT>nrOUTPUTS or YTYPE>nrOUTPUT
+nrOUTPUTS = length(length(modelInfo.outputs));
+if FLAG_CMT,
+    x(x.CMT > nrOUTPUTS,:) = [];
+else
+    x(x.YTYPE > nrOUTPUTS,:) = [];
+end
+% Write out number of observations
+nOBS = length(x);
+NROBS_info = sprintf('; NROBSERVATIONS      = ''%d''\r\n',nOBS);
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,NROBS_info);
+
+% Determine the number of estimated parameters (THETA and ETA)
+NRPARAMETERS_ESTIMATED = sum(eval(['[' ESTIMATE_info(1:end-1) ']']))+sum(eval(['[' ETAESTIMATE(1:end-1) ']'])==1)+sum(CORRestimate);
+NRPARAMETERS_ESTIMATED_info = sprintf('; NRPARAM_ESTIMATED   = ''%d''\r\n',NRPARAMETERS_ESTIMATED);
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,NRPARAMETERS_ESTIMATED_info);
+
+% Info about residual names depending on the selected method
+RESIDUAL_NAMES_USED = sprintf('; RESIDUAL_NAMES_USED = ''XPRED,XRES,XWRES''\r\n');
+if strcmp(METHOD,'FO'),
+    RESIDUAL_NAMES_ORIG = sprintf('; RESIDUAL_NAMES_ORIG = ''NPRED,NRES,NWRES''\r\n');
+elseif strcmp(METHOD,'FOCE'), 
+    RESIDUAL_NAMES_ORIG = sprintf('; RESIDUAL_NAMES_ORIG = ''NPRED,CRES,CWRES''\r\n');
+elseif strcmp(METHOD,'FOCEI'),
+    RESIDUAL_NAMES_ORIG = sprintf('; RESIDUAL_NAMES_ORIG = ''CPREDI,CRESI,CWRESI''\r\n');
+elseif strcmp(METHOD,'SAEM'),
+    RESIDUAL_NAMES_ORIG = sprintf('; RESIDUAL_NAMES_ORIG = ''EPRED,ERES,EWRES''\r\n');
+end
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,RESIDUAL_NAMES_USED);
+PROJECT_INFO_TEXT = sprintf('%s%s',PROJECT_INFO_TEXT,RESIDUAL_NAMES_ORIG);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Replace PROJECT_HEADER_PLACEHOLDER and 
+% "$SIZES LTH=XXX"
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+content = fileread('project.nmctl');
+content = strrep(content,'PROJECT_HEADER_PLACEHOLDER',strtrim(PROJECT_INFO_TEXT));
+x = [{param_est.name} beta_parameters output_parameters_project_info]; % get theta names
+content = strrep(content,'$SIZES LTH=XXX',sprintf('$SIZES LTH=%d',length(x)));
+fid = fopen('project.nmctl','w');
+fprintf(fid,'%s',content);
+fclose(fid);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Go back to old path
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+cd(oldpath);
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/SBPOPgetNONMEMdataHeader.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/SBPOPgetNONMEMdataHeader.m
new file mode 100644
index 0000000000000000000000000000000000000000..1fc4acbc8aaf5f88d56144895ce7fb9d3c683437
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/SBPOPgetNONMEMdataHeader.m
@@ -0,0 +1,172 @@
+function [header] = SBPOPgetNONMEMdataHeader(data,covNames,catNames,regressionNames,silent)
+% [DESCRIPTION]
+% This function takes a dataset in the standard clinical data format and
+% determines the NONMEM header information for the column names.
+% 
+% The data need to be provided, following the standard dataspec, defined in
+% the help to the function SBPOPcheckDataFormat, so please look there for
+% more information.   
+%
+% [SYNTAX]
+% [header] = SBPOPgetNONMEMdataHeader(data,covNames,catNames)
+% [header] = SBPOPgetNONMEMdataHeader(data,covNames,catNames,regressionNames)
+% [header] = SBPOPgetNONMEMdataHeader(data,covNames,catNames,regressionNames,silent)
+%
+% [INPUT]
+% data:             MATLAB PKPD dataset in standard data spec format  
+% covNames:         Cell-array with names of continuous covariates
+% catNames:         Cell-array with names of categorical covariates
+% regressionNames:  Cell-array with names of regression variables
+% silent:           =0: no output to screen, =1: output to screen
+%
+% [OUTPUT]
+% header:      String with comma separated header info
+%
+% [ASSUMPTIONS]
+% Important assumption: standard dataset format
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 10th May 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MODESIM, MATLAB R2009a
+%
+% [KEYWORDS]
+% MATLAB, SBPOP, datacleaning, covariate, imputation, impute
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+if nargin<4,
+    regressionNames = {};
+end
+
+if nargin<5,
+    silent = 0;
+else
+    silent = 1;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check cov and catnames
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+datanames = get(data,'VarNames');
+for k=1:length(covNames),
+    if isempty(strmatchSB(covNames{k},datanames,'exact')), error('The dataset does not contain the covariate ''%s''.',covNames{k}); end    
+end
+for k=1:length(catNames),
+    if isempty(strmatchSB(catNames{k},datanames,'exact')), error('The dataset does not contain the covariate ''%s''.',catNames{k}); end    
+end
+for k=1:length(regressionNames),
+    if isempty(strmatchSB(regressionNames{k},datanames,'exact')), error('The dataset does not contain the regression variable ''%s''.',regressionNames{k}); end    
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define matches
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+colName = {'STYSID1A' 'SS' 'II' 'ADDL' 'STUDY'   'SUBJECT'    'ID' 'TIME'  'TIMEPOS'  'TAD'    'TIMEUNIT' 'TYPE'   'SUBTYPE'  'DV' 'NAME'   'UNIT'   'MDV' 'EVID' 'CENS'   'AMT'  'ADM' 'RATE' 'DOSE'    'TRT'  'YTYPE'  'CMT'};
+colType = {'IGNORE'   'SS' 'II' 'ADDL' 'CAT'     'IGNORE'     'ID' 'TIME'  'TIMEPOS'  'IGNORE' 'IGNORE'   'IGNORE' 'IGNORE'   'DV' 'IGNORE' 'IGNORE' 'MDV' 'EVID' 'IGNORE' 'AMT'  'ADM' 'RATE' 'IGNORE'  'CAT'  'YTYPE'  'CMT'};
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Fill header with 'IGNORE' first
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+headerContent = cell(1,length(datanames));
+for k=1:length(headerContent),
+    headerContent{k} = 'IGNORE';
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Generate header
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Apply matches
+for k=1:length(colName),
+    ix = strmatchSB(colName{k},datanames,'exact');
+    if ~isempty(ix),
+        headerContent{ix} = colType{k};
+    end
+end
+% Add continuous covariate information
+for k=1:length(covNames),
+    ix = strmatchSB(covNames{k},datanames,'exact');
+    if ~isempty(ix),
+        headerContent{ix} = 'COV';
+    end
+end
+% Add categorical covariate information
+for k=1:length(catNames),
+    ix = strmatchSB(catNames{k},datanames,'exact');
+    if ~isempty(ix),
+        headerContent{ix} = 'CAT';
+    end
+end
+% Add regression variable information
+for k=1:length(regressionNames),
+    ix = strmatchSB(regressionNames{k},datanames,'exact');
+    if ~isempty(ix),
+        headerContent{ix} = 'X';
+    end
+end
+
+% Run through all CAT definitions and check if single element value - then
+% warn the user and remove the cat cov by setting to IGNORE, otherwise
+% Monolix error but we also remove that for NONMEM!
+ixCAT = strmatchSB('CAT',headerContent);
+% Add categorical covariate information
+for k=1:length(ixCAT),
+    catName = datanames{ixCAT(k)};
+    if length(unique(data.(catName))) == 1,
+        headerContent{ixCAT(k)} = 'IGNORE';
+        fprintf('\nOnly single cagtegory for candidate categorical covariate "%s" => IGNORE.\n',catName);    
+    end
+end
+   
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create header output string
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+header = sprintf('%s,',headerContent{:});
+header = header(1:end-1);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Print Info
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~silent,
+    fprintf('\tMatching of dataset column names with NONMEM "column types":\n')
+    fprintf('\t============================================================\n')
+    for k=1:length(datanames),
+        fprintf('\t%s:\t%s\n',datanames{k},headerContent{k});
+    end
+    fprintf('\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if RATE is present
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ix = strmatchSB('RATE',header,'exact');
+if isempty(ix),
+    warning('Please make sure a ''RATE'' column is present in your NONMEM dataset.');
+end
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/SBPOPplotConvergenceNONMEM.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/SBPOPplotConvergenceNONMEM.m
new file mode 100644
index 0000000000000000000000000000000000000000..6ce9eb3f3329bd5508608ea8953e8e8a147ed9c7
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/SBPOPplotConvergenceNONMEM.m
@@ -0,0 +1,344 @@
+function SBPOPplotConvergenceNONMEM(projectPath)
+% SBPOPplotConvergenceNONMEM: plots the convergence plots for NONMEM
+% Assumes that NONMEM >=7.2 has been used.
+% Function can be used when run is still executed or afterwards when
+% cleanup is done and result files have been moved to the RESULTS folder.
+% If several estimation methods where concatenated, then for each method a
+% plot wil be done.
+%
+% The function also saves the convergence plots in the projectPath/RESULTS
+% folder. If several methods present, then for each a figure will be saved.
+% Figures will only be printed if project.ext file in the RESULTS folder! 
+%
+% USAGE:
+% ======
+% SBPOPplotConvergenceNONMEM(projectPath)
+%
+% projectPath:   path to the .nmctl NONMEM project file
+
+% Information:
+% ============
+% Copyright (C) 2012 Novartis Pharma AG
+%
+% This program is Free Open Source Software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Load the project information to get parameter names etc.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+projectinfo = parseProjectHeaderNONMEMSBPOP(projectPath);
+
+THETANAMES = strrep(strrep(strrep(projectinfo.THETANAMES,'(','_'),')','_'),',','_');
+ETANAMES = strrep(strrep(strrep(projectinfo.ETANAMES,'(','_'),')','_'),',','_');
+BETACATNAMES = strrep(strrep(strrep(projectinfo.BETACATNAMES,'(','_'),')','_'),',','_');
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if METHOD more than one ...
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for nrTable=1:length(projectinfo.METHOD),
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Check if project.ext in project or in RESULTS folder
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    PRINT = 0;
+    if exist([projectPath '/project.ext']),
+        x = getTableNnonmemOutputSBPOP([projectPath '/project.ext'],nrTable);
+    elseif exist([projectPath '/RESULTS/project.ext']),
+        x = getTableNnonmemOutputSBPOP([projectPath '/RESULTS/project.ext'],nrTable);
+        PRINT = 1;
+    else
+        error('project.ext file could not be found.');
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Remove the negative ITERATIONs at the end
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    x(x.ITERATION<-100000000,:) = [];
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Remove all 0 elements
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    x(:,find(sum(abs(double(x))) == 0)) = [];
+
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Remove all elements which are not changing
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    x(:,find(var(double(x)) < 100*eps)) = [];
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Split data into ITERATION, THETA, OBJ, OMEGA
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    header          = get(x,'VarNames');
+    % Get ITERATIONs
+    xITERATION      = x(:,strmatch('ITERATION',header));
+    % Get THETAs
+    xTHETA          = x(:,strmatchSB('THETA',header));
+    % Get OMEGAs
+    xOMEGA          = x(:,strmatchSB('OMEGA',header));
+    % Get OBJs
+    xOBJ            = x(:,end);
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Calculate standard deviation and correlation from OMEGAs
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    xSTDCORR = dataset();
+    h = strrep(strrep(get(xOMEGA,'VarNames'),'OMEGA',''),'_',',');
+    h2 = get(xOMEGA,'VarNames');
+    % Convert first the variances
+    for k=1:length(h),
+        rc = explodePCSB(h{k}(2:end-1));
+        r = eval(rc{1});
+        c = eval(rc{2});
+        if r==c,
+            xSTDCORR.(sprintf('%s',ETANAMES{r})) = sqrt(double(xOMEGA(:,k)));
+        end
+    end
+    % Then do the correlations
+    for k=1:length(h),
+        rc = explodePCSB(h{k}(2:end-1));
+        r = eval(rc{1});
+        c = eval(rc{2});
+        if r~=c,
+            covariance = xOMEGA(:,k);
+            variance1  = xOMEGA.(sprintf('OMEGA_%d_%d_',r,r));
+            variance2  = xOMEGA.(sprintf('OMEGA_%d_%d_',c,c));
+            correlation = double(xOMEGA(:,k))./sqrt(variance1.*variance2);
+            xSTDCORR.(sprintf('corr_%s_%s',ETANAMES{c},ETANAMES{r})) = correlation;
+        end
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Split xSTDCORR into diagonal and off-diagonal
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    h = get(xSTDCORR,'VarNames');
+    ixSTD = strmatchSB('omega',h);
+    ixCORR = strmatchSB('corr',h);
+    xSTANDARD = xSTDCORR(:,ixSTD);
+    xCORR = xSTDCORR(:,ixCORR);
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Rename THETAs
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    header = get(xTHETA,'VarNames');
+    theta_name_indices = [];
+    for k=1:length(header),
+        theta_name_indices(end+1) = eval(strrep(header{k},'THETA',''));
+    end
+    xTHETA = set(xTHETA,'VarNames',THETANAMES(theta_name_indices));
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Split of beta and betacat from theta
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    header = get(xTHETA,'VarNames');
+    ixbeta = strmatchSB('beta_',header);
+    xBETA = xTHETA(:,ixbeta);
+    xTHETA(:,ixbeta) = [];
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Split of beta cont and cat
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    xBETA_cat = {};
+    xBETA_cov = xBETA;
+    header = get(xBETA,'VarNames');
+    ixcovremove = [];
+    for k=1:length(BETACATNAMES),
+        if ~isempty(BETACATNAMES{k}),
+            ix = strmatch(BETACATNAMES{k},header);
+            xBETA_cat{end+1} = xBETA(:,ix);
+            ixcovremove = [ixcovremove; ix(:)];
+        end
+    end
+    xBETA_cov(:,ixcovremove) = [];
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Split of ERROR from theta
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    header = get(xTHETA,'VarNames');
+    ixerror = strmatchSB('error_',header);
+    xERROR = xTHETA(:,ixerror);
+    xTHETA(:,ixerror) = [];
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Determine needed subplots
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    nTHETA      = size(xTHETA,2);
+    nBETAcov    = size(xBETA_cov,2);
+    nBETAcat    = length(BETACATNAMES);
+    if isempty(BETACATNAMES{1}),
+        nBETAcat = 0;
+    end
+    nSTD        = size(xSTANDARD,2);
+    nCORR       = double(~isempty(xCORR));
+    nERROR      = size(xERROR,2);
+    nOBJ        = 1;
+    nTotal      = nTHETA+nBETAcov+nBETAcat+nSTD+nCORR+nERROR+nOBJ;
+    nrows       = ceil(sqrt(nTotal));
+    ncols       = ceil(nTotal/nrows);
+    
+    % If method is IMP then only OFV is determined, so set nrows and ncols to 1
+    if strcmp(projectinfo.METHOD{nrTable},'IMP'),
+        nrows = 1;
+        ncols = 1;
+        nCORR = 0;
+        nTHETA = 0;
+        nBETAcov = 0;
+        nBETAcat = 0;
+        nTotal = 1;
+    end
+    
+    figure(nrTable); clf
+    colors      = getcolorsSBPOP();
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Plot THETAs
+    % And first backtransform them
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    h = get(xTHETA,'VarNames');
+    for k=1:size(xTHETA,2),
+        phi = double(xTHETA(:,k));
+        param = h{k};
+        ixparam = strmatchSB(param,projectinfo.PARAMNAMES,'exact');
+        % get inverse transformation
+        invtrans = projectinfo.PARAMINVTRANS{ixparam};
+        % do inverse trans
+        value = eval(invtrans);
+        % plot
+        subplot(nrows,ncols,k);
+        plot(double(xITERATION),value,'-','Color',colors(1,:),'LineWidth',2);
+        grid on;
+        title([h{k} ' (' projectinfo.METHOD{nrTable} ')'],'Interpreter','None','FontWeight','bold')
+        hold on;
+        set(gca,'YLim',get(gca,'YLim'))
+        set(gca,'XLim',[min(xITERATION.ITERATION) max(xITERATION.ITERATION)])
+%         set(gca,'XTick',[]);
+        YLim = get(gca,'YLim');
+        set(gca,'YTick',linspace(YLim(1),YLim(2),5));
+        plot([0 0],get(gca,'YLim'),'k-')
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Plot BETAcovs
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    h = get(xBETA_cov,'VarNames');
+    for k=1:size(xBETA_cov,2),
+        subplot(nrows,ncols,k+nTHETA);
+        plot(double(xITERATION),xBETA_cov(:,k),'-','Color',colors(2,:),'LineWidth',2);
+        grid on;
+        title([h{k} ' (' projectinfo.METHOD{nrTable} ')'],'Interpreter','None','FontWeight','bold')
+        hold on;
+        set(gca,'YLim',get(gca,'YLim'))
+        set(gca,'XLim',[min(xITERATION.ITERATION) max(xITERATION.ITERATION)])
+%         set(gca,'XTick',[]);
+        YLim = get(gca,'YLim');
+        set(gca,'YTick',linspace(YLim(1),YLim(2),5));
+        plot([0 0],get(gca,'YLim'),'k-')
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Plot BETAcats
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    for k=1:length(xBETA_cat),
+        if ~isempty(xBETA_cat{k}),
+            subplot(nrows,ncols,k+nTHETA+nBETAcov);
+            plot(double(xITERATION),double(xBETA_cat{k}),'-','LineWidth',2);
+            grid on;
+            title([BETACATNAMES{k} ' (' projectinfo.METHOD{nrTable} ')'],'Interpreter','None','FontWeight','bold')
+            hold on;
+            set(gca,'YLim',get(gca,'YLim'))
+            set(gca,'XLim',[min(xITERATION.ITERATION) max(xITERATION.ITERATION)])
+%             set(gca,'XTick',[]);
+            YLim = get(gca,'YLim');
+            set(gca,'YTick',linspace(YLim(1),YLim(2),5));
+            plot([0 0],get(gca,'YLim'),'k-')
+        end
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Plot OMEGAs (STDs)
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    h = get(xSTANDARD,'VarNames');
+    for k=1:size(xSTANDARD,2),
+        subplot(nrows,ncols,k+nTHETA+nBETAcov+nBETAcat);
+        plot(double(xITERATION),xSTANDARD(:,k),'-','Color',colors(4,:),'LineWidth',2);
+        grid on;
+        title([h{k} ' (' projectinfo.METHOD{nrTable} ')'],'Interpreter','None','FontWeight','bold')
+        hold on;
+        set(gca,'YLim',get(gca,'YLim'))
+        set(gca,'XLim',[min(xITERATION.ITERATION) max(xITERATION.ITERATION)])
+%         set(gca,'XTick',[]);
+        YLim = get(gca,'YLim');
+        set(gca,'YTick',linspace(YLim(1),YLim(2),5));
+        plot([0 0],get(gca,'YLim'),'k-')
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Plot CORRs
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    if ~isempty(xCORR)
+        subplot(nrows,ncols,nCORR+nTHETA+nBETAcov+nBETAcat+nSTD);
+        plot(double(xITERATION),double(xCORR),'-','LineWidth',2);
+        grid on;
+        title('IIV Correlations','Interpreter','None','FontWeight','bold')
+        hold on;
+        set(gca,'YLim',get(gca,'YLim'))
+        plot([0 0],get(gca,'YLim'),'k-')
+        set(gca,'XLim',[min(xITERATION.ITERATION) max(xITERATION.ITERATION)])
+%         set(gca,'XTick',[]);
+        YLim = get(gca,'YLim');
+        set(gca,'YTick',linspace(YLim(1),YLim(2),5));
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Plot ERRORs
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    h = get(xERROR,'VarNames');
+    for k=1:size(xERROR,2),
+        subplot(nrows,ncols,k+nCORR+nTHETA+nBETAcov+nBETAcat+nSTD);
+        plot(double(xITERATION),xERROR(:,k),'-','Color',colors(5,:),'LineWidth',2);
+        grid on;
+        title([h{k} ' (' projectinfo.METHOD{nrTable} ')'],'Interpreter','None','FontWeight','bold')
+        hold on;
+        set(gca,'YLim',get(gca,'YLim'))
+        set(gca,'XLim',[min(xITERATION.ITERATION) max(xITERATION.ITERATION)])
+%         set(gca,'XTick',[]);
+        YLim = get(gca,'YLim');
+        set(gca,'YTick',linspace(YLim(1),YLim(2),5));
+        plot([0 0],get(gca,'YLim'),'k-')
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Plot OBJ
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    h = get(xOBJ,'VarNames');
+    subplot(nrows,ncols,nTotal);
+    plot(double(xITERATION),double(xOBJ),'r-','LineWidth',2);
+    grid on;
+    title([h{1} ' (' projectinfo.METHOD{nrTable} ')'],'Interpreter','None','FontWeight','bold')
+    set(gca,'XTickLabel',[]);
+    hold on;
+    set(gca,'YLim',get(gca,'YLim'))
+    plot([0 0],get(gca,'YLim'),'k-')
+    set(gca,'XLim',[min(xITERATION.ITERATION) max(xITERATION.ITERATION)])
+%     set(gca,'XTick',[]);
+    YLim = get(gca,'YLim');
+    set(gca,'YTick',linspace(YLim(1),YLim(2),5));
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Print figure
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    if PRINT,
+        filename = sprintf('%s/RESULTS/CONVERGENCE_PLOT__%d_%s',projectPath,nrTable,projectinfo.METHOD{nrTable});
+        printFigureSBPOP(gcf,filename,'png');
+    end
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/SBPOPreportNONMEMresults.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/SBPOPreportNONMEMresults.m
new file mode 100644
index 0000000000000000000000000000000000000000..29dcece8728975eaf80ee030fe958261e6aa8589
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/SBPOPreportNONMEMresults.m
@@ -0,0 +1,405 @@
+function SBPOPreportNONMEMresults(projectPath)
+% SBPOPreportNONMEMresults: parses the results of a NONMEM run and reports
+% them in a similar manner as in the MONOLIX pop_parameters.txt file.
+%
+% The function saves a text file version in the projectPath/RESULTS
+% folder. Additionally, the result is shown in the command window.
+%
+% USAGE:
+% ======
+% SBPOPreportNONMEMresults(projectPath)
+%
+% projectPath:   path to the .nmctl NONMEM project file
+
+% Information:
+% ============
+% Copyright (C) 2012 Novartis Pharma AG
+%
+% This program is Free Open Source Software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% parse the results
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+x = parseNONMEMresultsSBPOP(projectPath);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Start output text
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+OUTPUT = '';
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Print the header
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+OUTPUT  = sprintf('%s========================================================================================================\n',OUTPUT);
+OUTPUT  = sprintf('%s    Summary results\n',OUTPUT);
+[xdummyx,project] = fileparts(x.path);
+OUTPUT  = sprintf('%s    Project: %s\n',OUTPUT,project);
+OUTPUT  = sprintf('%s========================================================================================================\n',OUTPUT);
+OUTPUT  = sprintf('%s\n',OUTPUT);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Print termination information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(x.termination_info),
+    OUTPUT = sprintf('%s--------------------------------------------------------------------------------------------------------\n',OUTPUT);
+    method = sprintf('%s,',x.PROJECTINFO.METHOD{:});
+    OUTPUT = sprintf('%sTermination information (Method(s): %s)\n',OUTPUT,method(1:end-1));
+    OUTPUT = sprintf('%s--------------------------------------------------------------------------------------------------------\n',OUTPUT);
+    for k=1:length(x.termination_info),
+        OUTPUT = sprintf('%s%s\n',OUTPUT,x.termination_info{k});
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if major problems with the fit
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isnan(x.objectivefunction.OBJ),
+    OUTPUT = sprintf('%sMajor problems with the project results. Please check!\n',OUTPUT);
+    % Save the text
+    filename = sprintf('%s/RESULTS/project_results.txt',projectPath);
+    fid = fopen(filename,'w');
+    fprintf(fid,'%s',OUTPUT);   
+    fclose(fid);
+    % Print out in command window
+    disp(OUTPUT)    
+    return
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Print the fixed effects (still transformed)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+OUTPUT = sprintf('%s--------------------------------------------------------------------------------------------------------\n',OUTPUT);
+OUTPUT  = sprintf('%sName                           Value          stderr         RSE (%%)          95%%CI\n',OUTPUT);
+OUTPUT = sprintf('%s--------------------------------------------------------------------------------------------------------\n',OUTPUT);
+fe = x.rawParameterInfo.fixedEffects;
+names = {};
+values = {};
+stderrs = {};
+RSEs = {};
+for k=1:length(fe.names)
+    % Names
+    if strcmp(fe.trans{k},'(phi)'),
+        names{k} = fe.names{k};
+    elseif strcmp(fe.trans{k},'exp(phi)'),
+        names{k} = ['log(' fe.names{k} ')'];
+    elseif strcmp(fe.trans{k},'exp(phi)./(1+exp(phi))'),
+        names{k} = ['logit(' fe.names{k} ')'];
+    else
+        error('Unknown transformation');
+    end
+    % Values
+    if fe.estimated(k)==1,
+        values{k} = sprintf('%1.4g',fe.values(k));
+        stderrs{k} = sprintf('%1.4g',fe.stderr(k));
+        RSEs{k} = sprintf('%1.4g',fe.rse(k));
+    else
+        values{k} = sprintf('%1.4g (FIX)',fe.values(k));
+        stderrs{k} = '-';
+        RSEs{k} = '-';
+    end
+end
+for k=1:length(names),
+    text = sprintf('%s%s%s%s\n',postFillCharSB(names{k},20,' '),...
+        preFillCharSB(values{k},16,' '), ...
+        preFillCharSB(stderrs{k},16,' '), ...
+        preFillCharSB(RSEs{k},16,' '));
+    OUTPUT = sprintf('%s%s',OUTPUT,text);
+end
+OUTPUT  = sprintf('%s\n',OUTPUT);
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Print the fixed effects (back transformed)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fe = x.rawParameterInfo.fixedEffects;
+names = {};
+values = {};
+stderrs = {};
+RSEs = {};
+for k=1:length(fe.names)
+    % Names
+    names{k} = fe.names{k};
+    % Value
+    phi = fe.values(k);
+    value = eval(fe.trans{k});
+    % sample standard error
+    if fe.stderr(k)==0,
+        stderr = 0;
+    else
+        phi = fe.values(k)+fe.stderr(k)*randn(1,100000);
+        stderr = std(eval(fe.trans{k}));
+    end
+    
+    % Values
+    if fe.estimated(k)==1,
+        values{k} = sprintf('%1.4g',value);
+        rse = sprintf('%1.4g*',100*stderr/value);
+        stderr = sprintf('%1.4g*',stderr);
+    else
+        values{k} = sprintf('%1.4g (FIX)',value);
+        stderr = '-';
+        rse = '-';
+    end        
+    
+    % Stderrs
+    stderrs{k} = stderr;
+    % RSEs
+    RSEs{k} = rse;
+end
+for k=1:length(names),
+    text = sprintf('%s%s%s%s\n',postFillCharSB(names{k},20,' '),...
+        preFillCharSB(values{k},16,' '), ...
+        preFillCharSB(stderrs{k},16,' '), ...
+        preFillCharSB(RSEs{k},16,' '));
+    OUTPUT = sprintf('%s%s',OUTPUT,text);
+end
+OUTPUT  = sprintf('%s                                    (*approximation by sampling)\n',OUTPUT);
+OUTPUT  = sprintf('%s\n',OUTPUT);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Print the covariates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fe = x.rawParameterInfo.covariate;
+names = {};
+values = {};
+stderrs = {};
+RSEs = {};
+CI = {};
+for k=1:length(fe.names)
+    names{k} = fe.names{k};
+    if fe.estimated(k) 
+        values{k} = sprintf('%1.4g',fe.values(k));
+        stderrs{k} = sprintf('%1.4g',fe.stderr(k));
+        RSEs{k} = sprintf('%1.4g',fe.rse(k));
+        CI{k} = sprintf('[%1.2f %1.2f]',fe.values(k)-1.96*fe.stderr(k),fe.values(k)+1.96*fe.stderr(k));
+    else
+        % Not estimated
+        values{k} = sprintf('%1.4g (FIX)',fe.values(k));
+        stderrs{k} = '-';
+        RSEs{k} = '-';
+        CI{k} = '-';
+    end
+end
+for k=1:length(names),
+    text = sprintf('%s%s%s%s%s\n',postFillCharSB(names{k},20,' '),...
+        preFillCharSB(values{k},16,' '), ...
+        preFillCharSB(stderrs{k},16,' '), ...
+        preFillCharSB(RSEs{k},16,' '), ...
+        preFillCharSB(CI{k},30,' '));
+    OUTPUT = sprintf('%s%s',OUTPUT,text);
+end
+if length(fe.names) > 0,
+    OUTPUT  = sprintf('%s\n',OUTPUT);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Print the random effects
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fe = x.rawParameterInfo.randomEffects;
+names = {};
+values = {};
+stderrs = {};
+RSEs = {};
+for k=1:length(fe.names)
+    names{k} = fe.names{k};
+    if fe.estimated(k) == 1,
+        % Really estimated
+        values{k} = sprintf('%1.4g',fe.values(k));
+        stderrs{k} = sprintf('%1.4g',fe.stderr(k));
+        RSEs{k} = sprintf('%1.4g',fe.rse(k));
+    else
+        values{k} = sprintf('%1.4g (FIX)',fe.values(k));
+        stderrs{k} = '-';
+        RSEs{k} = '-';
+    end
+end
+for k=1:length(names),
+    text = sprintf('%s%s%s%s\n',postFillCharSB(names{k},20,' '),...
+        preFillCharSB(values{k},16,' '), ...
+        preFillCharSB(stderrs{k},16,' '), ...
+        preFillCharSB(RSEs{k},16,' '));
+    OUTPUT = sprintf('%s%s',OUTPUT,text);
+end
+if length(fe.names) > 0,
+    OUTPUT  = sprintf('%s\n',OUTPUT);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Print the correlations
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(x.rawParameterInfo.correlation.names),
+    fe = x.rawParameterInfo.correlation;
+    names = {};
+    values = {};
+    stderrs = {};
+    RSEs = {};
+    CI = {};
+    for k=1:length(fe.names)
+        names{k} = fe.names{k};
+        % Always estimated
+        values{k} = sprintf('%1.4g',fe.values(k));
+        stderrs{k} = sprintf('%1.4g',fe.stderr(k));
+        RSEs{k} = sprintf('%1.4g',fe.rse(k));
+        CI{k} = sprintf('[%1.2f %1.2f]',fe.values(k)-1.96*fe.stderr(k),fe.values(k)+1.96*fe.stderr(k));
+    end
+    for k=1:length(names),
+        text = sprintf('%s%s%s%s%s\n',postFillCharSB(names{k},20,' '),...
+            preFillCharSB(values{k},16,' '), ...
+            preFillCharSB(stderrs{k},16,' '), ...
+            preFillCharSB(RSEs{k},16,' '), ...
+            preFillCharSB(CI{k},30,' '));
+        OUTPUT = sprintf('%s%s',OUTPUT,text);
+    end
+    OUTPUT  = sprintf('%s\n',OUTPUT);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Print the errors
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fe = x.rawParameterInfo.errorParameter;
+names = {};
+values = {};
+stderrs = {};
+RSEs = {};
+for k=1:length(fe.names)
+    names{k} = fe.names{k};
+    if fe.estimated(k) == 1,
+        values{k} = sprintf('%1.4g',fe.values(k));
+        stderrs{k} = sprintf('%1.4g',fe.stderr(k));
+        RSEs{k} = sprintf('%1.4g',fe.rse(k));
+    else
+        values{k} = sprintf('%1.4g (FIX)',fe.values(k));
+        stderrs{k} = '-';
+        RSEs{k} = '-';
+    end
+end
+for k=1:length(names),
+    text = sprintf('%s%s%s%s\n',postFillCharSB(names{k},20,' '),...
+        preFillCharSB(values{k},16,' '), ...
+        preFillCharSB(stderrs{k},16,' '), ...
+        preFillCharSB(RSEs{k},16,' '));
+    OUTPUT = sprintf('%s%s',OUTPUT,text);
+end
+OUTPUT  = sprintf('%s\n',OUTPUT);
+
+
+if ~isempty(x.parameters.correlationmatrix),
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Correlation fE and beta
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    OUTPUT = sprintf('%s--------------------------------------------------------------------------------------------------------\n',OUTPUT);
+    OUTPUT = sprintf('%sCorrelation of fixed effects and covariate coefficients\n',OUTPUT);
+    OUTPUT = sprintf('%s--------------------------------------------------------------------------------------------------------\n',OUTPUT);
+    names = [x.rawParameterInfo.fixedEffects.names x.rawParameterInfo.covariate.names];
+    ix_all = [];
+    for k=1:length(names),
+        ix_all(k) = strmatchSB(names{k},x.parameters.names,'exact');
+    end
+    cor = x.parameters.correlationmatrix(ix_all,ix_all);
+    for row=1:length(cor),
+        rowtext = postFillCharSB(names{row},18,' ');
+        for col=1:row,
+            rowtext = sprintf('%s%s',rowtext,preFillCharSB(sprintf('%1.2g',0.01*round(100*cor(row,col))),7,' '));
+        end
+        OUTPUT = sprintf('%s%s\n',OUTPUT,rowtext);
+    end
+    OUTPUT  = sprintf('%s\n',OUTPUT);
+    eigM    = eig(cor);
+    eigMmin = min(eigM);
+    eigMmax = max(eigM);
+    OUTPUT  = sprintf('%sEigenvalues (min, max, max/min): %1.2f  %1.2f  %1.2f\n',OUTPUT,eigMmin,eigMmax,eigMmax/eigMmin);
+    OUTPUT  = sprintf('%s\n',OUTPUT);
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Correlation of omegas and error parameters
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    OUTPUT = sprintf('%s--------------------------------------------------------------------------------------------------------\n',OUTPUT);
+    OUTPUT = sprintf('%sCorrelation of random effects (variances) and error parameters\n',OUTPUT);
+    OUTPUT = sprintf('%s--------------------------------------------------------------------------------------------------------\n',OUTPUT);
+    names = [strrep(x.rawParameterInfo.randomEffects.names,'omega','omega2') x.rawParameterInfo.errorParameter.names];
+    ix_all = [];
+    for k=1:length(names),
+        ix_all(k) = strmatchSB(names{k},x.parameters.names,'exact');
+    end
+    cor = x.parameters.correlationmatrix(ix_all,ix_all);
+    for row=1:length(cor),
+        rowtext = postFillCharSB(names{row},18,' ');
+        for col=1:row,
+            rowtext = sprintf('%s%s',rowtext,preFillCharSB(sprintf('%1.2g',0.01*round(100*cor(row,col))),7,' '));
+        end
+        OUTPUT = sprintf('%s%s\n',OUTPUT,rowtext);
+    end
+    OUTPUT  = sprintf('%s\n',OUTPUT);
+    eigM    = eig(cor);
+    eigMmin = min(eigM);
+    eigMmax = max(eigM);
+    OUTPUT  = sprintf('%sEigenvalues (min, max, max/min): %1.2f  %1.2f  %1.2f\n',OUTPUT,eigMmin,eigMmax,eigMmax/eigMmin);
+    OUTPUT  = sprintf('%s\n',OUTPUT);
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Correlation of correlations
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    names = [strrep(x.rawParameterInfo.correlation.names,'corr(','omega2(')];
+    if length(names) > 1,
+        OUTPUT = sprintf('%s--------------------------------------------------------------------------------------------------------\n',OUTPUT);
+        OUTPUT = sprintf('%sCorrelation of random effect covariances\n',OUTPUT);
+        OUTPUT = sprintf('%s--------------------------------------------------------------------------------------------------------\n',OUTPUT);
+        ix_all = [];
+        for k=1:length(names),
+            ix_all(k) = strmatchSB(names{k},x.parameters.names);
+        end
+        cor = x.parameters.correlationmatrix(ix_all,ix_all);
+        for row=1:length(cor),
+            rowtext = postFillCharSB(names{row},18,' ');
+            for col=1:row,
+                rowtext = sprintf('%s%s',rowtext,preFillCharSB(sprintf('%1.2g',0.01*round(100*cor(row,col))),7,' '));
+            end
+            OUTPUT = sprintf('%s%s\n',OUTPUT,rowtext);
+        end
+        OUTPUT  = sprintf('%s\n',OUTPUT);
+        eigM    = eig(cor);
+        eigMmin = min(eigM);
+        eigMmax = max(eigM);
+        OUTPUT  = sprintf('%sEigenvalues (min, max, max/min): %1.2f  %1.2f  %1.2f\n',OUTPUT,eigMmin,eigMmax,eigMmax/eigMmin);
+        OUTPUT  = sprintf('%s\n',OUTPUT);
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Print the OFV / AIC / BIC
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+OUTPUT = sprintf('%s--------------------------------------------------------------------------------------------------------\n',OUTPUT);
+METHOD = x.PROJECTINFO.METHOD{end};
+OUTPUT = sprintf('%sObjective function (%s)\n',OUTPUT,METHOD);
+if strcmp(METHOD,'SAEM'),
+    OUTPUT = sprintf('%sThe SAEM objective function should not be used for statistical testing.\n',OUTPUT);
+    OUTPUT = sprintf('%sPlease consider the use of the IMPORTANCESAMPLING option!\n',OUTPUT);
+end
+OUTPUT = sprintf('%s--------------------------------------------------------------------------------------------------------\n',OUTPUT);
+OUTPUT = sprintf('%sOFV:    %g\n',OUTPUT,x.objectivefunction.OBJ);
+OUTPUT = sprintf('%sAIC:    %g\n',OUTPUT,x.objectivefunction.AIC);
+OUTPUT = sprintf('%sBIC:    %g\n',OUTPUT,x.objectivefunction.BIC);
+OUTPUT  = sprintf('%s\n',OUTPUT);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Save the text
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+filename = sprintf('%s/RESULTS/project_results.txt',projectPath);
+fid = fopen(filename,'w');
+fprintf(fid,'%s',OUTPUT);
+fclose(fid);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Print out in command window
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+disp(OUTPUT)
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/SBPOPrunNONMEMproject.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/SBPOPrunNONMEMproject.m
new file mode 100644
index 0000000000000000000000000000000000000000..8cae02e756af82ee5fce144b12de63a59bb03ece
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/SBPOPrunNONMEMproject.m
@@ -0,0 +1,157 @@
+function SBPOPrunNONMEMproject(projectPath,NPROCESSORS,NO_GOF_PLOTS)
+% SBPOPrunNONMEMproject: runs a specified NONMEM project
+%
+% Essentially this function is just a simple wrapper.
+%
+% USAGE:
+% ======
+% SBPOPrunNONMEMproject(projectPath)
+% SBPOPrunNONMEMproject(projectPath,NPROCESSORS)
+% SBPOPrunNONMEMproject(projectPath,NPROCESSORS,NO_GOF_PLOTS)
+%
+% projectPath:   path to the .nmctl NONMEM project file
+% NPROCESSORS:   Number of processors if use of parallel (default: 1)
+% NO_GOF_PLOTS:             =0: Create GoF plots for all runs (default), =1: No Gof plots
+%
+% Control NONMEM run from commandline:
+% ====================================
+% CTRL-J: Console iteration printing on/off 
+% CTRL-K: Exit analysis at any time, which completes its output, and goes
+%         on to next mode or estimation method
+% CTRL-E: Exit program gracefully at any time
+% CTRL-T: Monitor the progress of each individual during an estimation by
+%         toggling ctrl-T. Wait 15 seconds or more to observe a subject’s
+%         ID, and individual objective function value. It is also good to
+%         test that the problem did not hang if a console output had not
+%         been observed for a long while
+
+% Information:
+% ============
+% Copyright (C) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Change in to project path 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+oldpath = pwd;
+cd(projectPath);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 1,
+    NPROCESSORS = 1;
+    NO_GOF_PLOTS = 0;
+elseif nargin == 2,
+    NO_GOF_PLOTS = 0;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Load information about the MONOLIX PATH
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[PATH_MONOLIX,PATH_NONMEM,PATH_NONMEM_PAR] = getNLMEtoolInfoSBPOP();
+if isempty(PATH_NONMEM) && NPROCESSORS==1,
+    error('Path to NONMEM executable not defined in SETUP_PATHS_TOOLS.m');
+end
+if isempty(PATH_NONMEM_PAR) && NPROCESSORS>1,
+    error('Path to NONMEM parallel executable not defined in SETUP_PATHS_TOOLS.m');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run NONMEM
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if NPROCESSORS == 1,
+    eval(sprintf('!%s project.nmctl project.nmlog',PATH_NONMEM));
+else
+    eval(sprintf('!%s %d project.nmctl project.nmlog',PATH_NONMEM_PAR,NPROCESSORS));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Change back to old path
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+cd(oldpath);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Cleanup
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try
+    cleanNONMEMprojectFolderSBPOP(projectPath);
+catch
+    cd(oldpath);
+    error('NONMEM run created a problem. Please check.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Postprocess ...
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try
+    SBPOPplotConvergenceNONMEM(projectPath)
+	close all
+catch
+    disp('Problem with plotting');
+    disp(lasterr);    
+end
+try
+    SBPOPreportNONMEMresults(projectPath)
+catch
+    disp('Problem with reporting');
+    disp(lasterr);    
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Generate information for GOF plots
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+try
+    PROJECTINFO     = parseProjectHeaderNONMEMSBPOP(projectPath);
+    
+    % outputNumber: Defined by metadata "OUTPUTS"
+    outputNumberALL = [1:length(PROJECTINFO.OUTPUTS)];
+    outputNamesALL  = PROJECTINFO.OUTPUTS;
+    
+    % data:
+    oldpath         = pwd();
+    cd(projectPath)
+    data            = SBPOPloadCSVdataset(PROJECTINFO.DATA{1});
+    cd(oldpath)
+    
+    % covNames:
+    covNames        = PROJECTINFO.COVNAMES;
+    
+    % catNames:
+    catNames        = PROJECTINFO.CATNAMES;
+catch
+    warning('Problem with obtaining information for GOF plots.');
+    disp(lasterr);    
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Do GOF plots
+% For each output one folder in RESULTS
+% If not switched off
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~NO_GOF_PLOTS,
+    try
+        for k=1:length(outputNumberALL),
+            outputNumber            = outputNumberALL(k);
+            options                 = [];
+            options.basefilename    = sprintf([projectPath '/RESULTS/GOF_OUTPUT_%d_%s/GOF_%d_%s_'],outputNumber,outputNamesALL{k},outputNumber,outputNamesALL{k});
+            SBPOPfitanalysisGeneralPlots(outputNumber,data,projectPath,covNames,catNames,options)
+        end
+    catch
+        warning('Problem with GOF plots.');
+        disp(lasterr);
+    end
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/SBPOPrunNONMEMprojectFolder.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/SBPOPrunNONMEMprojectFolder.m
new file mode 100644
index 0000000000000000000000000000000000000000..ef89ab8c15c22142b942f2ff1003b3e084d929b2
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/SBPOPrunNONMEMprojectFolder.m
@@ -0,0 +1,120 @@
+function [] = SBPOPrunNONMEMprojectFolder(modelProjectsFolder,N_PROCESSORS_PAR,N_PROCESSORS_SINGLE,NO_GOF_PLOTS)
+% [DESCRIPTION]
+% This functions runs all the NONMEM projects in the specified folder.
+% Parallel computation is supported in two different ways. Parallel execution 
+% of models at the same time (par for loop) and also allowing each single model
+% run to be parallelized (if the NONMEM installation allows for it).
+%
+% [SYNTAX]
+% [] = SBPOPrunNONMEMprojectFolder(modelProjectsFolder)
+% [] = SBPOPrunNONMEMprojectFolder(modelProjectsFolder,N_PROCESSORS_PAR)
+% [] = SBPOPrunNONMEMprojectFolder(modelProjectsFolder,N_PROCESSORS,N_PROCESSORS_SINGLE)
+% [] = SBPOPrunNONMEMprojectFolder(modelProjectsFolder,N_PROCESSORS,N_PROCESSORS_SINGLE,NO_GOF_PLOTS)
+%
+% [INPUT]
+% modelProjectsFolder:      Path to a folder with NONMEM project folders
+%                           to be run. Folder names are arbitrary, but a
+%                           project.nmctl file needs to be present in
+%                           each folder.
+% N_PROCESSORS_PAR:         Number of processors for parallel model evaluation (default: 1)
+% N_PROCESSORS_SINGLE:      Number of processors for parallelization of single model run (default: 1)
+% NO_GOF_PLOTS:             =0: Create GoF plots for all runs (default), =1: No Gof plots
+%
+% If N_PROCESSORS_PAR>1 then parallel nodes are requested via the matlabpool
+% command and N_PROCESSORS_PAR models will be run in parallel.
+%
+% [OUTPUT]
+% No output! The function just runs the NONMEM projects. All results are
+% written to the relevant output folders ("RESULTS").
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 14nd March, 2014
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 1,
+    N_PROCESSORS_PAR    = 1;
+    N_PROCESSORS_SINGLE = 1;
+    NO_GOF_PLOTS = 0;
+elseif nargin == 2,
+    N_PROCESSORS_SINGLE = 1;
+    NO_GOF_PLOTS = 0;
+elseif nargin == 3,
+    NO_GOF_PLOTS = 0;
+end
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get the projects to run in the folder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+projects = dir([modelProjectsFolder '/*']);
+% Remove . and ..
+ix_dot = strmatchSB('.',{projects.name});
+projects(ix_dot) = [];
+% Remove files
+projects(find(~[projects.isdir])) = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Request processors
+% Request min(N_PROCESSORS,length(projects))
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+N_PROCESSORS_NEEDED = min(N_PROCESSORS_PAR,length(projects));
+
+killMATLABpool = 0;
+if N_PROCESSORS_NEEDED>1,
+    try
+        if matlabpool('size') == 0,
+            eval(sprintf('matlabpool %d',N_PROCESSORS_NEEDED));
+            killMATLABpool = 1;
+        end
+    catch
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run the models
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+warning off
+oldpath = pwd();
+parfor k=1:length(projects),
+    fprintf('Running project %d of %d ...\n',k,length(projects));
+    pathfolder = [modelProjectsFolder '/' projects(k).name];
+    if isNONMEMfitSBPOP(pathfolder),
+        SBPOPrunNONMEMproject(pathfolder,N_PROCESSORS_SINGLE,NO_GOF_PLOTS);
+    end
+end
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Release processors
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try
+    if matlabpool('size')>1 && killMATLABpool==1,
+        matlabpool close
+    end
+catch
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Done!
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf('\nEstimations READY!\n\n');
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/SBPOPsampleNONMEMparam.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/SBPOPsampleNONMEMparam.m
new file mode 100644
index 0000000000000000000000000000000000000000..bc3c7e22efddcd09a8fdb5575d8edda888bb55c8
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/SBPOPsampleNONMEMparam.m
@@ -0,0 +1,733 @@
+function [output] = SBPOPsampleNONMEMparam( projectPath, FLAG_SAMPLE, Nsamples, varargin )
+% [NAME]
+% SBPOPsampleNONMEMparam
+%
+% [DESCRIPTION]
+% This function samples parameters from both uncertainty and variability distributions from a NONMEM fit.
+% The result is a structure with sampled population parameters and sampled individual parameters. The desired
+% number of parameter sets can be specified.
+%
+% This function is very useful for trial simulation purposes.
+%
+% Handles automatically different parameter distributions (logNormal, Normal, logitNormal)
+%
+% [SYNTAX]
+% output = SBPOPsampleNONMEMparam( projectPath, FLAG_SAMPLE, Nsamples )
+% output = SBPOPsampleNONMEMparam( projectPath, FLAG_SAMPLE, Nsamples, covNames, covValues, catNames, catValues )
+%
+% [INPUT]
+% projectPath: path to the NONMEM project folder (created by SBPOP)
+% FLAG_SAMPLE:                    0=use point estimates of population parameters (do not consider uncertainty) and sample Nsample 
+%                                   individual patients based on these. Covariates considered if defined by user and used in model.
+%                                   Please note: population parameters do not take covariates into account!
+%                                 1=sample single set of population parameters from uncertainty distribution and sample Nsample 
+%                                   individual patient parameters based on these. Covariates considered if defined by user and used in model.
+%                                   Please note: population parameters do not take covariates into account!
+%                                 2=sample Nsample sets of population parameters from uncertainty distribution 
+%                                   Do not sample from variability distribution and do not take into account covariates (even if user specified).
+%                                 3=use point estimates of population parameters (do not consider uncertainty)
+%                                   Return Nsamples sets of population parameters with covariates taken into account.
+%                                 4=sample single set of population parameters from uncertainty distribution 
+%                                   Return Nsamples sets of population parameters with covariates taken into account.
+%                                 5=sample Nsamples sets of population parameters from uncertainty distribution 
+%                                   And take provided covariates into account.
+% 
+% Nsamples:                       Number of individual parameter sets to sample
+%
+% covNames:                       Cell-array with names of continuous covariates to consider in the parameter sampling (only used for FLAG_SAMPLE=0 or 1)
+%                                 Default: {}
+% covValues:                      Matrix with Nsamples rows and as many columns as continuous covariate names in covNames (only used for FLAG_SAMPLE=0 or 1)
+% catNames:                       Cell-array with names of categorical covariates to consider in the parameter sampling (only used for FLAG_SAMPLE=0 or 1)
+%                                 Default: {}
+% catValues:                      Matrix with Nsamples rows and as many columns as categorical covariate names in covNames (only used for FLAG_SAMPLE=0 or 1)
+%
+% [OUTPUT]
+% Structure with the following fields:
+% output.parameterNames:                Cell-array with parameter names
+% output.FLAG_SAMPLE:                   Sampling flag used (see above for definition)
+% output.Nsamples:                      Number of sampled parameter sets (type of parameter sets sampled depends on FLAG_SAMPLE)
+% output.parameterValuesPopulation:     Vector or Matrix with (sampled) population parameters
+% output.parameterValuesIndividual:     Matrix with samples individual parameter sets (one set per row, one parameter per column)
+%
+% [ASSUMPTIONS]
+% 
+% [AUTHOR]
+% Henning Schmidt 
+%
+% [DATE]
+% 08.06.2012
+%
+% [PLATFORM]
+% MATLAB R2009a
+%
+% [KEYWORDS]
+% MONOLIX, results, sampling, parameters, individual
+% 
+% [TOOLBOXES USED]
+% NONE
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Parse NONMEM results
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+x = parseNONMEMresultsSBPOP(projectPath);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Need to handle variable input arguments for CONTINUOUS covariates 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin>=5,
+    covNames = varargin{1};
+    covValues = varargin{2};
+    
+    if ~isempty(covNames),
+        % Check correct size (Nsamples)
+        if size(covValues,1) ~= Nsamples,
+            error('Provided values for continuous covariates need to have length of "Nsamples".');
+        end
+    else
+        covNames = {};
+        covValues = [];
+    end
+else
+    % No covariates provided! 
+    covNames = {};
+    covValues = [];
+end
+if ~iscell(covNames),
+    covNames = {covNames};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Need to handle variable input arguments for CATEGORICAL covariates 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin==7,
+    catNames = varargin{3};
+    catValues = varargin{4};
+    
+    if ~isempty(catNames),
+        % Check correct size (Nsamples)
+        if size(catValues,1) ~= Nsamples,
+            error('Provided values for categorical covariates need to have length of "Nsamples".');
+        end
+    else
+        catNames = {};
+        catValues = [];
+    end
+else
+    % No covariates provided! 
+    catNames = {};
+    catValues = [];
+end
+if ~iscell(catNames),
+    catNames = {catNames};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run the sampling function once to get covariate information
+% Parameter values will not be considered here and handled later
+% Check if covariates in model and warn if yes but user has not provided covariate information
+%
+% Do run this part only if FLAG_SAMPLE not equal to 2
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if FLAG_SAMPLE~=2,
+    y = sampleNONMEMpopulationParametersSBPOP(x,0,1);
+    covInfo = y.covariates.continuous;
+    catInfo = y.covariates.categorical;
+    % Check if covariates are in the model but not provided
+    if ~isempty(covInfo(1).parameter) && isempty(covNames),
+        disp('Model contains continuous covariates but no covariates are provided by the user.');
+        disp(' ');
+    end
+    if ~isempty(catInfo(1).parameter) && isempty(catNames),
+        disp('Model contains categorical covariates but no covariates are provided by the user.');
+        disp(' ');
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Prepare CONTINUOUS covariate information (if needed)
+    %
+    % phi = mu + eta + t_cov * beta
+    %
+    % phi:      matrix of transformed individual parameters. one row per individual. (Nsamples x Nparameters)
+    % mu:       matrix of transformed population parameter values (same row repeated Nsamples times). (Nsamples x Nparameters)
+    % t_cov:    matrix of transformed covariates (Nsamples x Ncovariates)
+    %           We will assume that each covariate with the same name has the same transformation. And this will be checked.
+    % beta:     matrix with covariate coefficients beta_ij (Ncovariates x Nparameters)
+    %
+    % Only covariates will be considered that actually are passed by the user.
+    % If other covariates are present in the model then a warning will be made.
+    %
+    % No covariate parameter values are considered here. Just error checking, data transformation, ...
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    if ~isempty(covNames),
+        % Cycle through covariate information and build data and do some error checks
+        allModelCovNames = {};
+        allModelCovFormulas = {};
+        for k1=1:length(covInfo),
+            paramName = covInfo(k1).parameter;
+            for k2=1:length(covInfo(k1).covariates),
+                covname     = covInfo(k1).covariates{k2};
+                betavalue   = covInfo(k1).values(k2);
+                formula     = covInfo(k1).transformation{k2}.formula;
+                % Check if covname already in allModelCovNames
+                ix = strmatchSB(covname,allModelCovNames,'exact');
+                if isempty(ix),
+                    % add covariate and formula to lists
+                    allModelCovNames{end+1} = covname;
+                    allModelCovFormulas{end+1} = formula;
+                else
+                    % check that formula is the same, otherwise error
+                    if ~strcmp(formula,allModelCovFormulas{ix}),
+                        error('Different covariate transformations for same continuous covariate.');
+                    end
+                end
+            end
+        end
+        
+        % Check model covariates against provided covariates
+        % Remove covariates provided by the user that are not used in the model - warn the user
+        % Warn the user also about covariates that are in the model but not provided by the user
+        [covsUser_notinmodel,ix_notinmodel] = setdiff(covNames,allModelCovNames);
+        [covsModel_notuser,ix_notuser] = setdiff(allModelCovNames,covNames);
+        
+        % Remove user defined covariates that are not used in the model
+        covNames(ix_notinmodel) = [];
+        covValues(:,ix_notinmodel) = [];
+        
+        % Warn the user about what has been found
+        if ~isempty(ix_notinmodel),
+            disp('The following continuous covariates have been defined by the user but they are not present in the model. They will be not considered.');
+            covsUser_notinmodel
+        end
+        if ~isempty(ix_notuser),
+            disp('The following continuous covariates are defined in the model but have not been provided by the user. They will be not considered.');
+            covsModel_notuser
+        end
+        
+        % Generate the transformed covariates
+        t_cov = covValues;
+        for k=1:length(covNames),
+            ix = strmatchSB(covNames{k},allModelCovNames,'exact');
+            formula = allModelCovFormulas{ix};
+            t_cov(:,k) = eval(strrep(formula,'cov','covValues(:,k)'));
+        end
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Prepare CATEGORICAL covariate information (if needed)
+    %
+    % phi = mu + eta + t_cov * beta + beta_cat
+    %
+    % phi:      matrix of transformed individual parameters. one row per individual. (Nsamples x Nparameters)
+    % mu:       matrix of transformed population parameter values (same row repeated Nsamples times). (Nsamples x Nparameters)
+    % t_cov:    matrix of transformed covariates (Nsamples x Ncovariates)
+    %           We will assume that each covariate with the same name has the same transformation. And this will be checked.
+    % beta:     matrix with covariate coefficients beta_ij (Ncovariates x Nparameters)
+    % beta_cat: matrix with categorical covariate coefficients (Nsamples x Nparameters)
+    %           Does not need to be prepared much but some error checking needs to be done
+    %
+    % Only covariates will be considered that actually are passed by the user.
+    % If other covariates are present in the model then a warning will be made.
+    %
+    % No covariate parameter values are considered here. Just error checking, data transformation, ...
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    if ~isempty(catNames),
+        % Cycle through covariate information and get all categorical covariate names used
+        allModelCatNames = {};
+        for k1=1:length(catInfo),
+            paramName = catInfo(k1).parameter;
+            for k2=1:length(catInfo(k1).covariates),
+                catname     = catInfo(k1).covariates{k2};
+                % Check if catname already in allModelCatNames
+                ix = strmatchSB(catname,allModelCatNames,'exact');
+                if isempty(ix),
+                    % add covariate and formula to lists
+                    allModelCatNames{end+1} = catname;
+                end
+            end
+        end
+        
+        % Check model covariates against provided covariates
+        % Remove covariates provided by the user that are not used in the model - warn the user
+        % Warn the user also about covariates that are in the model but not provided by the user
+        [catsUser_notinmodel,ix_notinmodel] = setdiff(catNames,allModelCatNames);
+        [catsModel_notuser,ix_notuser] = setdiff(allModelCatNames,catNames);
+        
+        % Remove user defined covariates that are not used in the model
+        catNames(ix_notinmodel) = [];
+        catValues(:,ix_notinmodel) = [];
+        
+        % Warn the user about what has been found
+        if ~isempty(ix_notinmodel),
+            disp('The following categorical covariates have been defined by the user but they are not present in the model. They will be not considered.');
+            catsUser_notinmodel
+        end
+        if ~isempty(ix_notuser),
+            disp('The following categorical covariates are defined in the model but have not been provided by the user. They will be not considered.');
+            catsModel_notuser
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle case of FLAG_SAMPLE=0 and 1
+% Sampling individual parameters with (1) or without (0) uncertainty 
+% Taking covariates into account if provided.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if FLAG_SAMPLE == 0 || FLAG_SAMPLE ==1,
+    % Need to sample until reasonable values (no imaginary parts in parameters)
+    while 1,
+        % Parse and sample NONMEM results
+        y = sampleNONMEMpopulationParametersSBPOP(x,FLAG_SAMPLE);
+        
+        % Get covariance matrix
+        cov = y.randomEffects.covariancematrix;
+        [eigV,eigD] = eig(cov);
+        if min(diag(eigD)) > -1e-3,
+            % It is not positive semidefinite, but the smallest eigenvalue
+            % is so close to zero that we are going to put it on zero
+            eigD(eigD<0) = 0;
+            cov = eigV*eigD*inv(eigV);
+            disp('Random effect covariance matrix not positive semidefinite. Smallest eigenvalue is closer to 0 than -1e-3 => making it positive semidefinite.');
+        end
+        
+        % Sample individual random effects (etas)
+        ETA = mvnrnd(zeros(1,size(cov,1)),cov,Nsamples);
+        
+        % Transform population estimates to normal distribution (mu) (allowing for transformations: lognormal, logitnormal, normal)
+        mu = [];
+        for k=1:length(y.randomEffects.inv_transformation),
+            mu(k) = eval(strrep(y.randomEffects.inv_transformation{k},'psi',sprintf('%g',y.fixedEffects.values(k))));
+        end
+        
+        % Determine normally distributed phi - without covariate contributions: phi = mu + eta  (+ beta*t_cov + beta_cat)
+        phi = mu(ones(1,Nsamples),:) + ETA;
+        
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        % Determine and add effect of continuous covariates to phi: phi = mu + eta + t_cov*beta  (+ beta_cat)
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        if ~isempty(covNames),
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Determine the beta matrix
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Get parameter names of estimates
+            paramNames = y.fixedEffects.names;
+            % Initialize the beta matrix
+            beta = zeros(length(covNames),length(paramNames));
+            % Fill the beta matrix
+            for k1=1:length(covInfo),
+                paramName = covInfo(k1).parameter;
+                ix_j = strmatchSB(paramName,paramNames,'exact');
+                for k2=1:length(covInfo(k1).covariates),
+                    covname     = covInfo(k1).covariates{k2};
+                    beta_ij     = covInfo(k1).values(k2);
+                    ix_i        = strmatchSB(covname,covNames,'exact');
+                    % Fill beta_ij value into beta matrix
+                    beta(ix_i,ix_j) = beta_ij;
+                end
+            end
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Add t_cov*beta to phi
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            phi = phi + t_cov*beta;
+        end
+        
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        % Determine and add effect of categorical covariates to phi: phi = mu + eta + beta*t_cov + beta_cat
+        % One beta_cat matrix for each parameter/covariate combination!
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        if ~isempty(catNames),
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Determine the beta_cat matrix
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Get parameter names of estimates
+            paramNames = y.fixedEffects.names;
+            % Initialize the beta_cat matrix (Nsamples x Nparameters)
+            beta_cat = {};
+            % Determine the beta_cat matrices
+            for k1=1:length(catInfo),
+                paramName = catInfo(k1).parameter;
+                ix_j = strmatchSB(paramName,paramNames,'exact');
+                for k2=1:length(catInfo(k1).covariates),
+                    % Initialize parameter/covariate dependent beta_cat matrix
+                    beta_cat_cov = zeros(Nsamples,length(paramNames));
+                    % Get categorical cov name and index
+                    catname     = catInfo(k1).covariates{k2};
+                    ix_i        = strmatchSB(catname,catNames,'exact');
+                    if ~isempty(ix_i),
+                        % Fill the beta_cat_cov matrix
+                        categories_user = catValues(:,ix_i);
+                        categories_model = catInfo(k1).information(k2).categories;
+                        categories_values = catInfo(k1).information(k2).values;
+                        % Initialize values
+                        values = NaN(size(categories_user));
+                        for kkk=1:length(categories_model),
+                            ix = categories_user==categories_model(kkk);
+                            values(ix) = categories_values(kkk);
+                        end
+                        % Check if values contains NaN, then error and inform the user
+                        if ~isempty(find(isnan(values), 1)),
+                            error('Categorical covariate "%s" contains user provided category that has not been used for model building.',catname);
+                        end
+                        % Assign values
+                        beta_cat_cov(:,ix_j) = values;
+                    end
+                    beta_cat{end+1} = beta_cat_cov;
+                end
+            end
+            
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Add beta_cat to phi
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            for k1=1:length(beta_cat),
+                phi = phi + beta_cat{k1};
+            end
+        end
+        
+        % Back transform individual parameters (each column one parameter)
+        psi = [];
+        for k=1:size(phi,2),
+            transform_string = strrep(y.randomEffects.transformation{k},'phi',sprintf('phi(:,%d)',k));
+            psi(:,k) = eval(transform_string);
+            % Handle the case when phi=Inf and logit transformation => manually set to 1
+            if strcmp(y.randomEffects.transformation{k},'exp(phi)./(1+exp(phi))'),
+                psi(isnan(psi)) = 1;
+            end
+        end
+        
+        % Check if some issues with the sampled parameters (should not lead to complex values)
+        if isempty(find(imag(psi) ~=0)),
+            break;
+        else
+            % Rerun sampling since problem with population parameter sampling
+        end
+    end
+    % Define output variable
+    output                              = [];
+    output.parameterNames               = y.fixedEffects.names;
+    output.FLAG_SAMPLE                  = FLAG_SAMPLE;
+    output.Nsamples                     = Nsamples;
+    output.parameterValuesPopulation    = y.fixedEffects.values;
+    output.parameterValuesIndividual    = psi;
+
+elseif FLAG_SAMPLE == 2,
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Handle special case of FLAG_SAMPLE=2 (sampling population parameters only)
+    % Not taking covariates into account
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    FLAG_SAMPLE_POPULATIONPARAM = 1;
+    
+    % Run sampling function once just to get the number of parameters to sample
+    y = sampleNONMEMpopulationParametersSBPOP(x,0,1);
+
+    % Initialize the matrix with the parameter values (number of parameters needed for that)
+    popvalues = zeros(Nsamples,length(y.fixedEffects.names));
+    
+    % Get Nsamples sets of population parameters from uncertainty distribution
+    for k=1:Nsamples,
+        y = sampleNONMEMpopulationParametersSBPOP(x,FLAG_SAMPLE_POPULATIONPARAM,1);
+        popvalues(k,:) = y.fixedEffects.values;
+    end
+    
+    % Define output variable
+    output                              = [];
+    output.parameterNames               = y.fixedEffects.names;
+    output.FLAG_SAMPLE                  = FLAG_SAMPLE;
+    output.Nsamples                     = Nsamples;
+    output.parameterValuesPopulation    = popvalues;
+    output.parameterValuesIndividual    = [];
+    
+elseif FLAG_SAMPLE == 3 || FLAG_SAMPLE == 4,
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Handle special case of FLAG_SAMPLE=3 || 4
+    % - Sampling population parameters once only from uncertainty distributions (if FLAG_SAMPLE=4)
+    % - Including covariate effect on sampled population parameters
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    
+    if FLAG_SAMPLE==3,
+        FLAG_SAMPLE_POPULATIONPARAM = 0;
+    else
+        FLAG_SAMPLE_POPULATIONPARAM = 1;
+    end
+    
+    % Need to sample until reasonable values (no imaginary parts in parameters)
+    while 1,
+        % Parse and sample NONMEM results to get base population parameters without covariate effects
+        y = sampleNONMEMpopulationParametersSBPOP(x,FLAG_SAMPLE_POPULATIONPARAM);
+        
+        % Transform population parameters to normal distribution (mu) (allowing for transformations: lognormal, logitnormal, normal)
+        mu = [];
+        for k=1:length(y.randomEffects.inv_transformation),
+            mu(k) = eval(strrep(y.randomEffects.inv_transformation{k},'psi',sprintf('%g',y.fixedEffects.values(k))));
+        end
+        
+        % Determine normally distributed phi - without eta and covariate contribution: phi = mu (+ eta)  (+ beta*t_cov + beta_cat)
+        phi = mu(ones(1,Nsamples),:);
+        
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        % Determine and add effect of continuous covariates to phi: phi = mu (+ eta) + t_cov*beta  (+ beta_cat)
+        % Without eta contribution
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        if ~isempty(covNames),
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Determine the beta matrix
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Get parameter names of estimates
+            paramNames = y.fixedEffects.names;
+            % Initialize the beta matrix
+            beta = zeros(length(covNames),length(paramNames));
+            % Fill the beta matrix
+            for k1=1:length(covInfo),
+                paramName = covInfo(k1).parameter;
+                ix_j = strmatchSB(paramName,paramNames,'exact');
+                for k2=1:length(covInfo(k1).covariates),
+                    covname     = covInfo(k1).covariates{k2};
+                    beta_ij     = covInfo(k1).values(k2);
+                    ix_i        = strmatchSB(covname,covNames,'exact');
+                    % Fill beta_ij value into beta matrix
+                    beta(ix_i,ix_j) = beta_ij;
+                end
+            end
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Add t_cov*beta to phi
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            phi = phi + t_cov*beta;
+        end
+        
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        % Determine and add effect of categorical covariates to phi: phi = mu + eta + beta*t_cov + beta_cat
+        % One beta_cat matrix for each parameter/covariate combination!
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        if ~isempty(catNames),
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Determine the beta_cat matrix
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Get parameter names of estimates
+            paramNames = y.fixedEffects.names;
+            % Initialize the beta_cat matrix (Nsamples x Nparameters)
+            beta_cat = {};
+            % Determine the beta_cat matrices
+            for k1=1:length(catInfo),
+                paramName = catInfo(k1).parameter;
+                ix_j = strmatchSB(paramName,paramNames,'exact');
+                for k2=1:length(catInfo(k1).covariates),
+                    % Initialize parameter/covariate dependent beta_cat matrix
+                    beta_cat_cov = zeros(Nsamples,length(paramNames));
+                    % Get categorical cov name and index
+                    catname     = catInfo(k1).covariates{k2};
+                    ix_i        = strmatchSB(catname,catNames,'exact');
+                    if ~isempty(ix_i),
+                        % Fill the beta_cat_cov matrix
+                        categories_user = catValues(:,ix_i);
+                        categories_model = catInfo(k1).information(k2).categories;
+                        categories_values = catInfo(k1).information(k2).values;
+                        % Initialize values
+                        values = NaN(size(categories_user));
+                        for kkk=1:length(categories_model),
+                            ix = categories_user==categories_model(kkk);
+                            values(ix) = categories_values(kkk);
+                        end
+                        % Check if values contains NaN, then error and inform the user
+                        if ~isempty(find(isnan(values), 1)),
+                            error('Categorical covariate "%s" contains user provided category that has not been used for model building.',catname);
+                        end
+                        % Assign values
+                        beta_cat_cov(:,ix_j) = values;
+                    end
+                    beta_cat{end+1} = beta_cat_cov;
+                end
+            end
+            
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Add beta_cat to phi
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            for k1=1:length(beta_cat),
+                phi = phi + beta_cat{k1};
+            end
+        end
+        
+        % Back transform individual parameters (each column one parameter)
+        psi = [];
+        for k=1:size(phi,2),
+            transform_string = strrep(y.randomEffects.transformation{k},'phi',sprintf('phi(:,%d)',k));
+            psi(:,k) = eval(transform_string);
+            % Handle the case when phi=Inf and logit transformation => manually set to 1
+            if strcmp(y.randomEffects.transformation{k},'exp(phi)./(1+exp(phi))'),
+                psi(isnan(psi)) = 1;
+            end
+        end
+        
+        % Check if some issues with the sampled parameters (should not lead to complex values)
+        if isempty(find(imag(psi) ~=0)),
+            break;
+        else
+            % Rerun sampling since problem with population parameter sampling
+        end
+    end
+    % Define output variable
+    output                              = [];
+    output.parameterNames               = y.fixedEffects.names;
+    output.FLAG_SAMPLE                  = FLAG_SAMPLE;
+    output.Nsamples                     = Nsamples;
+    output.parameterValuesPopulation    = psi;    
+    output.parameterValuesIndividual    = [];
+    
+elseif FLAG_SAMPLE == 5,
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Handle special case of FLAG_SAMPLE=5
+    % - Sampling Nsamples population parameters from uncertainty distribution
+    % - Including covariate effect on sampled population parameters
+    %   Need to provide Nsamples number of covariate values
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    
+    FLAG_SAMPLE_POPULATIONPARAM = 1;
+    
+    % Run sampling function once just to get the number of parameters to sample
+    y = sampleNONMEMpopulationParametersSBPOP(x,0,1);
+
+    % Initialize the matrix with the parameter values (number of parameters needed for that)
+    mu = zeros(Nsamples,length(y.fixedEffects.names));
+
+    % Need to sample until reasonable values (no imaginary parts in parameters)
+    while 1,
+
+        % Get Nsamples sets of population parameters from uncertainty distribution
+        for k0=1:Nsamples,
+            % Sample
+            y = sampleNONMEMpopulationParametersSBPOP(x,FLAG_SAMPLE_POPULATIONPARAM,1);
+            mu(k0,:) = y.fixedEffects.values;
+        end
+
+        % Transform
+        for k=1:length(y.randomEffects.inv_transformation),
+            mu(:,k) = eval(strrep(y.randomEffects.inv_transformation{k},'psi',sprintf('mu(:,%d)',k)));
+        end
+        
+        % Determine normally distributed phi - without eta and covariate contribution: phi = mu (+ eta)  (+ beta*t_cov + beta_cat)
+        phi = mu;
+        
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        % Determine and add effect of continuous covariates to phi: phi = mu (+ eta) + t_cov*beta  (+ beta_cat)
+        % Without eta contribution
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        if ~isempty(covNames),
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Determine the beta matrix
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Get parameter names of estimates
+            paramNames = y.fixedEffects.names;
+            % Initialize the beta matrix
+            beta = zeros(length(covNames),length(paramNames));
+            % Fill the beta matrix
+            for k1=1:length(covInfo),
+                paramName = covInfo(k1).parameter;
+                ix_j = strmatchSB(paramName,paramNames,'exact');
+                for k2=1:length(covInfo(k1).covariates),
+                    covname     = covInfo(k1).covariates{k2};
+                    beta_ij     = covInfo(k1).values(k2);
+                    ix_i        = strmatchSB(covname,covNames,'exact');
+                    % Fill beta_ij value into beta matrix
+                    beta(ix_i,ix_j) = beta_ij;
+                end
+            end
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Add t_cov*beta to phi
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            phi = phi + t_cov*beta;
+        end
+        
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        % Determine and add effect of categorical covariates to phi: phi = mu + eta + beta*t_cov + beta_cat
+        % One beta_cat matrix for each parameter/covariate combination!
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        if ~isempty(catNames),
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Determine the beta_cat matrix
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Get parameter names of estimates
+            paramNames = y.fixedEffects.names;
+            % Initialize the beta_cat matrix (Nsamples x Nparameters)
+            beta_cat = {};
+            % Determine the beta_cat matrices
+            for k1=1:length(catInfo),
+                paramName = catInfo(k1).parameter;
+                ix_j = strmatchSB(paramName,paramNames,'exact');
+                for k2=1:length(catInfo(k1).covariates),
+                    % Initialize parameter/covariate dependent beta_cat matrix
+                    beta_cat_cov = zeros(Nsamples,length(paramNames));
+                    % Get categorical cov name and index
+                    catname     = catInfo(k1).covariates{k2};
+                    ix_i        = strmatchSB(catname,catNames,'exact');
+                    if ~isempty(ix_i),
+                        % Fill the beta_cat_cov matrix
+                        categories_user = catValues(:,ix_i);
+                        categories_model = catInfo(k1).information(k2).categories;
+                        categories_values = catInfo(k1).information(k2).values;
+                        % Initialize values
+                        values = NaN(size(categories_user));
+                        for kkk=1:length(categories_model),
+                            ix = categories_user==categories_model(kkk);
+                            values(ix) = categories_values(kkk);
+                        end
+                        % Check if values contains NaN, then error and inform the user
+                        if ~isempty(find(isnan(values), 1)),
+                            error('Categorical covariate "%s" contains user provided category that has not been used for model building.',catname);
+                        end
+                        % Assign values
+                        beta_cat_cov(:,ix_j) = values;
+                    end
+                    beta_cat{end+1} = beta_cat_cov;
+                end
+            end
+            
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            % Add beta_cat to phi
+            %%%%%%%%%%%%%%%%%%%%%%%%%%%
+            for k1=1:length(beta_cat),
+                phi = phi + beta_cat{k1};
+            end
+        end
+        
+        % Back transform individual parameters (each column one parameter)
+        psi = [];
+        for k=1:size(phi,2),
+            transform_string = strrep(y.randomEffects.transformation{k},'phi',sprintf('phi(:,%d)',k));
+            psi(:,k) = eval(transform_string);
+            % Handle the case when phi=Inf and logit transformation => manually set to 1
+            if strcmp(y.randomEffects.transformation{k},'exp(phi)./(1+exp(phi))'),
+                psi(isnan(psi)) = 1;
+            end
+        end
+        
+        % Check if some issues with the sampled parameters (should not lead to complex values)
+        if isempty(find(imag(psi) ~=0)),
+            break;
+        else
+            % Rerun sampling since problem with population parameter sampling
+        end
+    end
+    % Define output variable
+    output                              = [];
+    output.parameterNames               = y.fixedEffects.names;
+    output.FLAG_SAMPLE                  = FLAG_SAMPLE;
+    output.Nsamples                     = Nsamples;
+    output.parameterValuesPopulation    = psi;    
+    output.parameterValuesIndividual    = [];
+    
+end
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/cleanNONMEMprojectFolderSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/cleanNONMEMprojectFolderSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..0ff33407a78dd253ee1c7795ac723732aca8afaf
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/cleanNONMEMprojectFolderSBPOP.m
@@ -0,0 +1,77 @@
+function cleanNONMEMprojectFolderSBPOP(projectPath)
+% cleanNONMEMprojectFolderSBPOP: moves all files into the RESULTS folder
+%    removes all additional folders. Does not move the project.nmctl file
+%
+% USAGE:
+% ======
+% cleanNONMEMprojectFolderSBPOP(projectPath)
+%
+% projectPath:   path to the .nmctl NONMEM project file
+
+% Information:
+% ============
+% Copyright (C) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Change in to project path and load Monolix project
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+oldpath = pwd;
+cd(projectPath);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Delete all folder except RESULTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+warning off
+x = dir();
+for k=1:length(x),
+    if x(k).isdir,
+        if ~strcmp(x(k).name,'.') && ~strcmp(x(k).name,'..') && ~strcmp(x(k).name,'RESULTS'),
+            rmdir(x(k).name,'s');
+        end
+    end
+end
+warning on
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Delete some other files
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+warning off
+try, delete('temporaryfile.xml'); catch, end
+try, delete('INTER'); catch, end
+warning on
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Delete nonmem queue files
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try, delete('nm*.e*'); catch, end
+try, delete('nm*.o*'); catch, end
+try, delete('nm*.pe*'); catch, end
+try, delete('nm*.po*'); catch, end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Copy all other files into RESULTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+x = dir('project.*');
+for k=1:length(x),
+    if ~strcmp(x(k).name,'project.nmctl'),
+        movefile(x(k).name,'RESULTS')
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Change back to old path
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+cd(oldpath);
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/getTableNnonmemOutputSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/getTableNnonmemOutputSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..a73b7a92e1d94cf63c92192b77672479a369b3a0
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/getTableNnonmemOutputSBPOP.m
@@ -0,0 +1,34 @@
+function [ data ] = getTableNnonmemOutputSBPOP(filename,nrTable)
+% getTableNnonmemOutputSBPOP: basically doing a SBPOPloadNONCSVdataset for
+% NONMEM outputs where more than one table might be present, due to
+% concatenated estimation methods
+
+% Load file
+content = fileread(filename);
+
+% Get start index of table
+ix = strfind(content,sprintf('TABLE NO.     %d',nrTable));
+if isempty(ix),
+    error('Table %d could not be found.',nrTable);
+end
+
+% Get text until end
+table = content(ix:end);
+
+% find next table
+ix = strfind(table,sprintf('TABLE NO.'));
+if length(ix)>1,
+    table = table(1:ix(2)-1);
+end
+
+% save as temporary
+[xdummyx,tempfile] = fileparts(tempnameSB);
+fid = fopen(tempfile,'w');
+fprintf(fid,'%s',table);
+fclose(fid);
+
+% Load as dataset
+data = SBPOPloadNONCSVdataset(tempfile,1);
+
+% Delete tempfile
+delete(tempfile)
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/isNONMEMfitSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/isNONMEMfitSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..82ac8da3e2dc987a7ed9904f55b6eef4b2255879
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/isNONMEMfitSBPOP.m
@@ -0,0 +1,14 @@
+function [ output ] = isNONMEMfitSBPOP( projectPath )
+% isNONMEMfitSBPOP: Checks if provided path contains a NONMEM project
+% output = 0: no NONMEM project
+% output = 1: NONMEM project
+% Decision rule: project.nmctl is present in the projectPath
+
+testfile = fullfile(projectPath,'project.nmctl');
+if ~exist(testfile),
+    output = 0;
+else
+    output = 1;
+end
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/additionalChecks4NONMEMconversionSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/additionalChecks4NONMEMconversionSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..3142f7a534d7225e2ffaf2f0f34debd224b1cf42
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/additionalChecks4NONMEMconversionSBPOP.m
@@ -0,0 +1,166 @@
+function [ covNames,catNames,errorModels,errorParam0 ] = additionalChecks4NONMEMconversionSBPOP( oldpath,param_est, dataHeaderIdent,dataheader,modelInfo,IIVestimate,errorModels,errorParam0,covarianceModel,covariateModel,SILENT)
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine continuous and categorical covariates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dataHeaderIDs   = explodePCSB(dataHeaderIdent,',');
+covIDs          = strmatchSB('COV',upper(dataHeaderIDs));
+covNames        = dataheader(covIDs);
+catIDs          = strmatchSB('CAT',upper(dataHeaderIDs));
+catNames        = dataheader(catIDs);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check that regression parameters correctly defined
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+nrREGSmodel     = length(modelInfo.param_reg);
+nrREGSdata      = length(strmatchSB('X',upper(dataHeaderIDs)));
+if nrREGSmodel ~= nrREGSdata,
+    cd(oldpath);
+    error('Different numbers of regression parameters in model and in dataset.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Print table with regression parameters model and data
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+REGSnamesData   = dataheader(strmatchSB('X',upper(dataHeaderIDs)));
+if ~SILENT,
+    if ~isempty(REGSnamesData),
+        disp(' ');
+        disp('Please check that the following matches regression parameters in data and model do make sense:');
+        disp('    DATA    : MODEL');
+        disp('--------------------------');
+        for k=1:length(REGSnamesData),
+            fprintf('\t%s%s: %s\n',REGSnamesData{k},char(32*ones(1,8-length(REGSnamesData{k}))),modelInfo.param_reg(k).name)
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check all headers
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~SILENT,
+    disp(' ');
+    disp('Please check that the following matches between data header and identifiers do make sense:');
+    for k=1:length(dataheader),
+        fprintf('\t%s%s: %s\n',dataheader{k},char(32*ones(1,8-length(dataheader{k}))),dataHeaderIDs{k})
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check residual error things
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(errorModels),
+    errorModels = '';
+    for k=1:length(modelInfo.outputs),
+        errorModels = sprintf('%sconst,',errorModels);
+    end
+    errorModels = errorModels(1:end-1);
+end
+test = errorModels;
+test = strtrim(strrep(strrep(strrep(strrep(test,'const',''),'prop',''),'comb1',''),',',''));
+if ~isempty(test),
+    cd(oldpath);
+    error('Please make sure that only "const", "prop", or "comb1" appear in the "errorModels" variable.');
+end
+% Check length
+errors = explodePCSB(errorModels,',');
+if length(errors) ~= length(modelInfo.outputs),
+    cd(oldpath);
+    error('Please make sure that an equal number of errorModels is defined as outputs in the model.');
+end
+% Print table parameter names and IIV distributions
+if ~SILENT,
+    disp(' ');
+    disp('Please check that the following matches between outputs and used residual error models are correct:');
+    for k=1:length(modelInfo.outputs),
+        fprintf('\t%s%s: %s\n',modelInfo.outputs(k).formula,char(32*ones(1,15-length(modelInfo.outputs(k).formula))),errors{k})
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle empty errorParam0
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(errorParam0),
+    terms = explodePCSB(errorModels);
+    for k=1:length(terms),
+        if strcmp(lower(terms{k}),'const'),
+            errorParam0(end+1) = 1;
+        elseif strcmp(lower(terms{k}),'prop'),
+            errorParam0(end+1) = 0.3;
+        elseif strcmp(lower(terms{k}),'comb1'),
+            errorParam0(end+1) = 1;
+            errorParam0(end+1) = 0.3;          
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check errorParam0
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+terms = explodePCSB(errorModels);
+nrneededelements = 0;
+for k=1:length(terms),
+    if strcmp(lower(terms{k}),'const'),
+        nrneededelements = nrneededelements+1;
+    elseif strcmp(lower(terms{k}),'prop'),
+        nrneededelements = nrneededelements+1;
+    elseif strcmp(lower(terms{k}),'comb1'),
+        nrneededelements = nrneededelements+2;
+    end
+end
+if length(errorParam0) ~= nrneededelements,
+    error('Incorrect number of elements in options.errorParam0.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check covariance model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(covarianceModel),
+    covarianceModel = 'diagonal';
+elseif ~strcmp(covarianceModel,'diagonal'),
+    % Need to check that none of the parameters for which no IIV is estimated is used in the covarianceModel
+    param_est_noIIV = {param_est(IIVestimate==0).name};
+    for k=1:length(param_est_noIIV),
+        if ~isempty(regexp(covarianceModel,['\<' param_est_noIIV{k} '\>'])),
+            cd(oldpath);
+            error('Please make sure none of the parameters for which NO IIV is estimated (IIVestimate=0) is used in the covarianceModel settings.');
+        end
+    end
+    % Check that all parameters in the covariance model actually are model parameters
+    param = {param_est.name};
+    test  = covarianceModel;
+    for k=1:length(param),
+        test = regexprep(test,['\<' param{k} '\>'],'');
+    end
+    test = strrep(test,'{','');
+    test = strrep(test,'}','');
+    test = strrep(test,',','');
+    test = strtrim(test);
+    if ~isempty(test),
+        cd(oldpath);
+        error('Please make sure that covarianceModel only contains parameter names that are set to <estimate> in the model.');
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check covariate model things
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% First check that all first elements are estimated parameters of the model
+for k=1:length(covariateModel),
+    param = covariateModel{k}{1};
+    if isempty(strmatchSB(param,{param_est.name},'exact')),
+        cd(oldpath);
+        error('Please make sure that all parameters for which covariates are defined are defined by <estimate> in the model.');
+    end
+end
+% Second check that all defined covariates actually are covariates
+covcatNames = [covNames catNames];
+for k=1:length(covariateModel),
+    for k2=2:length(covariateModel{k}),
+        cov = covariateModel{k}{k2};
+        if isempty(strmatchSB(cov,covcatNames,'exact')),
+            error('Please make sure that all covariates, defined in covariateModel, are defined in the dataset.');
+        end
+    end
+end
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/checkAndChangeModelSyntax4NONMEMconversionSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/checkAndChangeModelSyntax4NONMEMconversionSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..fc612ed02f3934ab662d4e42a4f8b5ed78abdba5
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/checkAndChangeModelSyntax4NONMEMconversionSBPOP.m
@@ -0,0 +1,101 @@
+function [ model ] = checkAndChangeModelSyntax4NONMEMconversionSBPOP( model,dosing,FLAG_CMT )
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check reactions - for now we do not allow reactions in the SBmodel
+% for NONMEM conversion
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if length(SBreactions(model)) > 0,
+    error('Model not allowed to contain reactions.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check dosing for other than BOLUS and INFUSION
+% We will only allow BOLUS and INFUSION for NONMEM conversion ... not a
+% limitation but simpler and cleaner
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ds = struct(dosing);
+allTypes = {ds.inputs.type};
+if ismember('ABSORPTION1',allTypes) || ismember('ABSORPTION0',allTypes),
+    error('ABSORPTION0 and ABSORPTION1 dosings not allowed for NONMEM conversion.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if "T" is used in the model 
+% and check other things
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% first check that "T" is not a state, variable, parameter or reaction name
+sn = SBstates(model);
+pn = SBparameters(model);
+vn = SBvariables(model);
+rn = SBreactions(model);
+allelements = {sn{:} pn{:} vn{:} rn{:}};
+if ~isempty(strmatchSB('T',allelements,'exact')),
+    error('''T'' defined in the model, but NONMEM uses it as the time variable.');
+end
+if ~isempty(strmatchSB('F',allelements,'exact')),
+    error('''F'' defined in the model, but NONMEM uses it as reserved word - please change it in the model.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% REPLACE some functions wth fortran equivalents accepted by NONMEM 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+nonmemfct = {'LOG','LOG10','EXP','SQRT','SIN','COS','ABS','TAN','ASIN','ACOS','ATAN','ABS'};
+sbmodelfct = lower({'LOG','LOG10','EXP','SQRT','SIN','COS','ABS','TAN','ASIN','ACOS','ATAN','ABS'});
+for k=1:length(nonmemfct),
+    model = replaceelementSB(model,sbmodelfct{k},nonmemfct{k});
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% REPLACE ^ by **
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modelTextStructure = convertModelToTextSB(model);
+modelText = setPartsToCompleteTextSB(modelTextStructure);
+modelText = strrep(modelText,'^','**');
+[SBstructure,errorMsg] = convertTextToModelSB(modelText);
+model = SBmodel(SBstructure);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle the FLAG_CMT thingy - but only if FLAG_CMT=0
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+if FLAG_CMT==1,
+    return
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if multiple inputs on same state - if yes => error
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ms = struct(model);
+for k=1:length(ms.inputs),
+    if length(ms.inputs(k).stateindex)>1,
+        error(sprintf('An INPUTn definition is used on more than one state. This can not be handled.'))
+    end
+end
+if length(ms.inputs) ~= length(unique([ms.inputs.stateindex])),
+    error(sprintf('Multiple INPUTn definitions on the same state.\n\tThe ADM/YTYPE version can not be used.\n\tPlease use the CMT version.'))
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Now reorder the states according to the INPUTn numbers
+% INPUT1 => state 1
+% INPUT2 => state 2
+% ...
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ms = struct(model);
+input_numbers = [];
+state_numbers = [];
+for k=1:length(ms.inputs),
+    input_numbers(end+1) = eval(strrep(ms.inputs(k).name,'INPUT',''));
+    state_numbers(end+1) = ms.inputs(k).stateindex;
+end
+if length(ms.states)<max(input_numbers),
+    error('Model can not be handled by NONMEM due to INPUT* number larger than state numbers - consider changing INPUT* number.');
+end
+% Reorder states
+ms.states(input_numbers) = ms.states(state_numbers);
+% Need to reassign stateindex in ms.states.input
+for k=1:length(ms.inputs),
+    ms.inputs(k).stateindex = input_numbers(k);
+end
+% Create again a model and return
+model = SBmodel(ms);
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/checkHandleDefaultInputArguments4NONMEMconversionSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/checkHandleDefaultInputArguments4NONMEMconversionSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..60c41fd9b904652e073f490c6b81eebf8a5ce662
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/checkHandleDefaultInputArguments4NONMEMconversionSBPOP.m
@@ -0,0 +1,149 @@
+function [ POPestimate,POPvalues0,IIVestimate,IIVvalues0,IIVdistribution,covariateModel, covariateModelValues, COVestimate ] = checkHandleDefaultInputArguments4NONMEMconversionSBPOP( oldpath,param_est,POPestimate,POPvalues0,IIVestimate,IIVvalues0,IIVdistribution,covariateModel, covariateModelValues, COVestimate )
+% Do some checks on the input arguments and assign default values if
+% needed.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check POPestimate thing
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(POPestimate),
+    POPestimate = ones(1,length(param_est));
+end
+if length(param_est) ~= length(POPestimate),
+    error('Please make sure POPestimate is of same length as number of parameters to be estimated.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check POPvalues0 thing
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(POPvalues0),
+    POPvalues0 = [];
+    for k=1:length(param_est),
+        POPvalues0(k) = param_est(k).value0(1);
+    end
+end
+if length(param_est) ~= length(POPvalues0),
+    cd(oldpath);
+    error('Please make sure POPvalues0 is of same length as number of parameters to be estimated.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check IIV distribution things
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(IIVdistribution),
+    IIVdistribution = {};
+    for k=1:length(param_est),
+        IIVdistribution{k} = 'L';
+    end
+end
+
+% Check contents
+test = IIVdistribution;
+for k=1:length(IIVdistribution),
+    if ~ismember(test{k},{'L','N','G'}),
+        cd(oldpath);
+        error('Please make sure that only "N", "L", or "G" appear in the "IIVdistribution" variable.');
+    end
+end
+
+% Check length
+if length(IIVdistribution) ~= length(param_est),
+    cd(oldpath);
+    error('Please make sure that an equal number of IIVdistribution is defined as estimated parameters in the model.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check IIV estimation things
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(IIVestimate),
+    IIVestimate = ones(1,length(param_est));
+end
+% Check length
+if length(IIVestimate) ~= length(param_est),
+    cd(oldpath);
+    error('Please make sure that an equal number of IIVestimate is defined as estimated parameters in the model.');
+end
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check IIVvalues0 thing
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(IIVvalues0),
+    IIVvalues0 = 0.5*ones(1,length(param_est));
+end
+if length(param_est) ~= length(IIVvalues0),
+    cd(oldpath);
+    error('Please make sure IIVvalues0 is of same length as number of parameters to be estimated.');
+end
+
+% Convert covariate model into different syntax
+% '{CL,BMI0}, {Fsubcut,WT0}, {Vc,SEX,BMI0}'
+% to
+% {{'CL','BMI0'}, {'Fsubcut','WT0'}, {'Vc','SEX','BMI0'}}
+if ~isempty(covariateModel),
+    terms = explodePCSB(covariateModel,',','{','}');
+    y = {};
+    for k=1:length(terms),
+        x = strtrim(terms{k});
+        x = strrep(x,'{','{''');
+        x = strrep(x,'}','''}');
+        x = strrep(x,',',''',''');
+        y{k} = eval(x);
+    end
+    covariateModel = y;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check covariateModelValues
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(covariateModel) && ~isempty(covariateModelValues),
+    error('If you define covariateModelValues, you also need to define the covariateModel.');
+end
+
+if isempty(covariateModelValues),
+    % Determine default covariateModelValues
+    covariateModelValues = {};
+    for k=1:length(covariateModel),
+        covariateModelValues{k} = 0.1*ones(1,length(covariateModel{k})-1);
+    end
+else
+    % Check correct length of covariateModelValues elements
+    if length(covariateModel) ~= length(covariateModelValues),
+        error('Number of elements in covariateModel and covariateModelValues needs to match.');
+    end
+    for k=1:length(covariateModel),
+        if length(covariateModel{k})-1 ~= length(covariateModelValues{k}),
+            error('Length of single elements in covariateModel and covariateModelValues needs to match (covariateModelValues elements being one shorter).');
+        end
+    end
+    % Check if one of the covariateModelValues is 0 (not allowed in NONMEM)
+    for k=1:length(covariateModel),
+        if sum(covariateModelValues{k} == 0) > 0,
+            error('Initial guess for at least one covariate coefficient is 0. Not allowed for NONMEM!');
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check COVestimate
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(covariateModel) && ~isempty(COVestimate),
+    error('If you define COVestimate, you also need to define the covariateModel.');
+end
+
+if isempty(COVestimate),
+    % Determine default COVestimate - all are estimates
+    COVestimate = {};
+    for k=1:length(covariateModel),
+        COVestimate{k} = ones(1,length(covariateModel{k})-1);
+    end
+else
+    % Check correct length of COVestimate elements
+    if length(covariateModel) ~= length(COVestimate),
+        error('Number of elements in covariateModel and COVestimate needs to match.');
+    end
+    for k=1:length(covariateModel),
+        if length(covariateModel{k})-1 ~= length(COVestimate{k}),
+            error('Length of single elements in covariateModel and COVestimate needs to match (COVestimate elements being one shorter).');
+        end
+    end
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/getmodelPartTextInfo4NONMEMconversion.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/getmodelPartTextInfo4NONMEMconversion.m
new file mode 100644
index 0000000000000000000000000000000000000000..5c68654e1bc6723ba4024db655bd77aa784474db
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/getmodelPartTextInfo4NONMEMconversion.m
@@ -0,0 +1,144 @@
+function [StatesText, ParametersText, VariablesText, ODEsText] = getmodelPartTextInfo4NONMEMconversion(model,model_element_prefix,param_est,modelInfo,time_variable_replacement)
+% Add prefix to model elements that need it and return formatted
+% strings for states, parameters, variables and ODEs ... to be used for
+% NONMEM conversion.
+% Also the time variable is handled appropriately
+
+% Start by handling the time variable
+model = replaceelementSB(model,'time',time_variable_replacement);
+ 
+% Determine elements that might need prefix
+sn = SBstates(model);
+rn = SBreactions(model);
+% For variables do not consider OUTPUTx
+vn = SBvariables(model);
+ix = strmatchSB('OUTPUT',vn);
+vn(ix) = [];
+% For parameters we need to NOT consider the ones which are handled already and the
+% ones which are related to the INPUTs
+pn = SBparameters(model);
+pn = setdiff(setdiff(setdiff(pn,{param_est.name}),{modelInfo.param_pk.name}),{modelInfo.param_reg.name});
+ix = strmatchSB('INPUT',pn);
+pn(ix) = [];
+
+% Implement the prefix
+allelements = {sn{:} pn{:} vn{:} rn{:}};
+for k=1:length(allelements),
+    model = replaceelementSB(model,allelements{k},[model_element_prefix allelements{k}]);
+end
+
+% Get new element names
+for k=1:length(sn),
+    sn{k} = [model_element_prefix sn{k}];
+end
+
+for k=1:length(pn),
+    pn{k} = [model_element_prefix pn{k}];
+end
+
+for k=1:length(vn),
+    vn{k} = [model_element_prefix vn{k}];
+end
+
+for k=1:length(rn),
+    rn{k} = [model_element_prefix rn{k}];
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get model structure
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ms = struct(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get States text
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+StatesText = '';
+for k=1:length(ms.states),
+    StatesText = sprintf('%s    %s%s = A(%d)\r\n',StatesText,ms.states(k).name,char(32*ones(1,cellmaxlengthSBPOP({ms.states.name})-length(ms.states(k).name)+1)),k);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get Parameters text
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ParametersText = '';
+for k=1:length(pn),
+    pv = SBparameters(model,pn{k});
+    ParametersText = sprintf('%s    %s%s = %g\r\n',ParametersText,pn{k},char(32*ones(1,cellmaxlengthSBPOP(pn)-length(pn{k})+1)),pv);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get Variables text
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+VariablesText = '';
+% write out variables but neglect the following ones:
+%   - output definitions
+%   - regression parameters as variables
+allvarindices = [1:length(ms.variables)];
+% remove output variables
+outputvarindices = [modelInfo.outputs.varindex];
+varindices = setdiff(allvarindices,outputvarindices);
+% remove regression parameters implemented as variables in the SBmodel
+if ~isempty(modelInfo.param_reg),
+    regparvarindices = [modelInfo.param_reg.varindex];
+    varindices = setdiff(varindices,regparvarindices);
+end
+% Write out the variables
+if ~isempty(varindices),
+    for k=1:length(varindices),
+        % check if variable contains a construct that needs special
+        % handling - at the moment this is only piecewiseSB, min, max
+        formula = ms.variables(varindices(k)).formula;
+        flag_piecewise = ~isempty(strfind(formula,'piecewiseSB'));
+        flag_min       = ~isempty(strfind(formula,'min('));
+        flag_max       = ~isempty(strfind(formula,'max('));
+        if flag_piecewise+flag_min+flag_max > 1,
+            error('Model contains more than one MAX, MIN or PIECEWISESB expression in a variable assignment. Only one is allowed.');
+        end
+        
+        if flag_piecewise+flag_min+flag_max == 0,
+            % Neither piecewiseSB, nor min, nor max expressions present
+            VariablesText = sprintf('%s    %s%s = %s\r\n',VariablesText,ms.variables(varindices(k)).name,char(32*ones(1,cellmaxlengthSBPOP({ms.variables.name})-length(ms.variables(varindices(k)).name)+1)),ms.variables(varindices(k)).formula);
+        elseif flag_piecewise,
+            % piecewise contruct present in formula
+            newText = handleNONMEMpiecewiseSBPOP(ms.variables(varindices(k)).name,ms.variables(varindices(k)).formula);
+            VariablesText = sprintf('%s\r\n    %s\r\n\r\n',VariablesText,newText);
+        elseif flag_min,
+            % min expression present
+            newText = handleNONMEMminmaxSBPOP(ms.variables(varindices(k)).name,ms.variables(varindices(k)).formula,'min');
+            VariablesText = sprintf('%s\r\n    %s\r\n\r\n',VariablesText,newText);
+        elseif flag_max
+            % max expression present
+            newText = handleNONMEMminmaxSBPOP(ms.variables(varindices(k)).name,ms.variables(varindices(k)).formula,'max');
+            VariablesText = sprintf('%s\r\n    %s\r\n\r\n',VariablesText,newText);
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get ODEs text
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ODEsText = '';
+ODEs = {};
+for k=1:length(ms.states),
+    ODE = ms.states(k).ODE;
+    % remove input terms (do this already general for several inputs)
+    for k2 = 1:length(modelInfo.inputs),
+        % check if current input exists in current (k-th) ODE:
+        index = find(modelInfo.inputs(k2).stateindex == k);
+        if ~isempty(index),
+            % the input term to replace is:
+            termreplace = modelInfo.inputs(k2).terms{index};
+            ODE = strrep(ODE,termreplace,'');
+        end
+    end
+    % Remove prefix "+"
+    ODE = strtrim(ODE);
+    if ODE(1)=='+',
+        ODE = ODE(2:end);
+    end
+    ODEs{k} = ODE;
+end
+for k=1:length(ms.states),
+    % write out the ODE
+    ODEsText = sprintf('%s    DADT(%d) = %s%s ; %s\r\n',ODEsText,k,ODEs{k},char(32*ones(1,cellmaxlengthSBPOP(ODEs)-length(ODEs{k})+1)),strrep(ms.states(k).name,model_element_prefix,''));
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/handleCovariateDefinitionsSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/handleCovariateDefinitionsSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..a72a97a0546a1adb2b628e5052cfd46cfac9689a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/handleCovariateDefinitionsSBPOP.m
@@ -0,0 +1,160 @@
+function [ MU_param_text,THETA_INDEX_BETA,beta_parameters,text_defining_cat_auxiliaries,cov_type_continuous,covparam,covcov,beta_parameters_cov_project_info,beta_parameters_cat_project_info,COV_transformation_info,CAT_reference_info,CAT_categories_info,COVCATestimate_info ] = handleContCovariateDefinitionsSBPOP( MU_param_text,covariateModel,param_est,covariateMedianValues,covariateMedianNames,covariateCATNames,covariateCATValues,IIVdistribution,COVestimate )
+%%
+beta_parameters     = {};
+beta_parameters_cov_project_info     = {};
+beta_parameters_cat_project_info     = {};
+THETA_INDEX_BETA    = [];
+cov_type_continuous = [];
+covparam            = {};
+covcov              = {};
+
+COV_transformation_info = {};
+CAT_reference_info = {};
+CAT_categories_info = {};
+
+COVCATestimate_info = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle the CONTINUOUS covariate definitions and their introduction into
+% the MU referencing.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+parameter_add_cov   = {};
+cov_add_cov         = {};
+cov_add_median      = [];
+covTrans_text       = {};
+count = 1;
+for kcov=1:length(covariateModel),
+    covParam = covariateModel{kcov}{1};
+    covCOVs  = covariateModel{kcov}(2:end);
+    for k2=1:length(covCOVs),
+        if ismember(covCOVs{k2},covariateMedianNames),
+            beta_parameters{end+1}      = sprintf('beta_%s(%s)',covParam,covCOVs{k2});
+            theta_index                 = length(param_est)+count;
+            THETA_INDEX_BETA(end+1)     = theta_index;
+            cov_type_continuous(end+1)  = 1;
+            count                       = count+1;
+            parameter_add_cov{end+1}    = covParam;
+            cov_add_cov{end+1}          = covCOVs{k2};
+            cov_median                  = covariateMedianValues(strmatchSB(covCOVs{k2},covariateMedianNames,'exact'));
+            cov_add_median(end+1)       = cov_median;
+            
+            COVCATestimate_info(end+1)  = COVestimate{kcov}(k2);
+            
+            % find index of parameter to add covariate to
+            ix                          = strmatchSB(covParam,{param_est.name},'exact');
+            % Get transformation
+            TRANS                       = IIVdistribution{ix};
+            if TRANS=='N',
+                covTrans_text{end+1} = sprintf('+ THETA(%d)*log(%s/%g) ',theta_index,covCOVs{k2},cov_median);
+                COV_transformation_info{end+1} = sprintf('log(cov/%g)',cov_median);
+            elseif TRANS=='L',
+                covTrans_text{end+1} = sprintf('+ THETA(%d)*log(%s/%g) ',theta_index,covCOVs{k2},cov_median);
+                COV_transformation_info{end+1} = sprintf('log(cov/%g)',cov_median);
+            elseif TRANS=='G',
+                covTrans_text{end+1} = sprintf('+ THETA(%d)*log(%s/%g) ',theta_index,covCOVs{k2},cov_median);
+                COV_transformation_info{end+1} = sprintf('log(cov/%g)',cov_median);
+            end
+        end
+    end
+end
+% Aggregate covariate text for each parameter
+cov_add_text_param = cell(1,length(param_est));
+cov_add_text_param(1:end) = {''};
+for k=1:length(parameter_add_cov),
+    ix = strmatchSB(parameter_add_cov{k},{param_est.name},'exact');
+    cov_add_text_param{ix} = [cov_add_text_param{ix} covTrans_text{k}];
+end
+% Add continuous covariates into MU_param_text
+for k=1:length(MU_param_text),
+    MU_param_text{k} = strrep(MU_param_text{k},'X#X#X',[strtrim(cov_add_text_param{k}) 'X#X#X']);
+end
+% Save for later
+covparam            = parameter_add_cov;
+covcov              = cov_add_cov;
+
+beta_parameters_cov_project_info     = beta_parameters;
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle the categorical covariates
+% 
+% Example:
+% SEX_1 = 0 (can be omitted)
+% SEX_2 = 0
+% SEX_3 = 0
+% IF SEX==1 THEN SEX_1 = 1 (can be omitted)
+% IF SEX==2 THEN SEX_2 = 1
+% IF SEX==3 THEN SEX_3 = 1
+%     
+% MU_3  = THETA(3) + beta_SEX_2_WT*SEX_2 + beta_SEX_3_WT*SEX_3
+% 
+% Assume reference is always the first one with the smallest number
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+text_defining_cat_auxiliaries = '';
+cov_text = cell(1,length(param_est));
+cov_text(1:end) = {''};
+covs_handled_text_defining_cat_auxiliaries = {};
+for kcov=1:length(covariateModel),
+    covParam = covariateModel{kcov}{1};
+    covCOVs  = covariateModel{kcov}(2:end);
+    for k2=1:length(covCOVs),
+        if ismember(covCOVs{k2},covariateCATNames),
+            cov                         = covCOVs{k2};
+            cov_values                  = covariateCATValues{strmatchSB(covCOVs{k2},covariateCATNames,'exact')};
+            reference_value             = cov_values(1);
+            other_values                = cov_values(2:end);
+            
+            CAT_reference_info{end+1}   = reference_value;
+            CAT_categories_info{end+1}  = cov_values;
+                        
+            % Define the auxiliary text to be added before the MU thingy
+            if ~ismember(cov,covs_handled_text_defining_cat_auxiliaries),
+                for kaux=1:length(other_values),
+                    text_defining_cat_auxiliaries = sprintf('%s    %s_%d = 0 ; reference: %d\r\n',text_defining_cat_auxiliaries,cov,other_values(kaux),reference_value);
+                end
+                for kaux=1:length(other_values),
+                    text_defining_cat_auxiliaries = sprintf('%s    IF(%s.EQ.%d) %s_%d = 1\r\n',text_defining_cat_auxiliaries,cov,other_values(kaux),cov,other_values(kaux));
+                end
+                % Set cov as handled
+                covs_handled_text_defining_cat_auxiliaries{end+1} = cov;
+            end
+            
+            % Define the rest
+            for kaux=1:length(other_values),
+                COVCATestimate_info(end+1)  = COVestimate{kcov}(k2);
+                
+                covparam{end+1} = covParam;
+                covcov{end+1} = cov;
+                beta_parameters{end+1}      = sprintf('beta_%s(%s_%d)',covParam,cov,other_values(kaux));
+                
+                % Check if beta_parameters_cat_project_info already
+                % contains element
+                element_add_check = sprintf('beta_%s(%s)',covParam,cov);
+                if isempty(strmatchSB(element_add_check,beta_parameters_cat_project_info,'exact')),
+                    % not present => add it
+                    beta_parameters_cat_project_info{end+1} = element_add_check;
+                end
+                
+                if isempty(THETA_INDEX_BETA),
+                    nextindex = length(param_est)+1;
+                else
+                    nextindex                   = max(THETA_INDEX_BETA)+1;
+                end
+                THETA_INDEX_BETA(end+1)     = nextindex;
+                cov_type_continuous(end+1)  = 0;
+                ixParam                     = strmatchSB(covParam,{param_est.name},'exact');
+                cov_text{ixParam}           = sprintf('%s + THETA(%d)*%s_%d',cov_text{ixParam},nextindex,cov,other_values(kaux));
+            end
+        end
+    end
+end
+
+% Add continuous covariates into MU_param_text
+for k=1:length(MU_param_text),
+    MU_param_text{k} = strrep(MU_param_text{k},'X#X#X',cov_text{k});
+end
+
+% CAT_reference_info = {};
+% CAT_categories_info = {};
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/handleNONMEMminmaxSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/handleNONMEMminmaxSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..900db474b47083fb6ab60720bd3374b4b0663345
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/handleNONMEMminmaxSBPOP.m
@@ -0,0 +1,52 @@
+function [ changedformula ] = handleNONMEMminmaxSBPOP(name,formula,type)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE PIECEWISE EXPRESSIONS => if elseif else end
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+formula = strtrim(formula);
+% 1) Check that only a single piecewise expression 
+index = strfind(formula,[type '(']);
+if length(index) > 1,
+    error('More than one min or max expression in formula ''%s''. Only one is allowed.',formula);
+end
+% 2) Get the expression
+mmformula = strtrim(formula(index:end));
+offset = length([type '('])+1;
+po = 1;
+while po~=0,
+    if mmformula(offset) == '(',
+        po = po+1;
+    end
+    if mmformula(offset) == ')',
+        po = po-1;
+    end
+    offset = offset+1;
+end
+mmformula = mmformula(1:offset-1);
+% 3) Check length mmformula against formula. If not same => error, since
+% then additional terms are present in the formula.
+if length(formula) ~= length(mmformula),
+    error('Formula ''%s'' contains more than a simple min or max expression => please reformulate the SBmodel.',formula);
+end
+% 4) Get elements of expression
+elements = explodePCSB(mmformula(5:end-1));
+% 5) contruct the IF THEN expression
+
+% if 
+if strcmp(type,'max'),
+    text = sprintf('IF((%s).GT.(%s)) THEN\r\n',elements{1},elements{2});
+    text = sprintf('%s        %s = %s\r\n',text,name,elements{1});
+    text = sprintf('%s    ELSE\r\n',text);
+    text = sprintf('%s        %s = %s\r\n',text,name,elements{2});
+    text = sprintf('%s    ENDIF',text);
+else
+    text = sprintf('IF((%s).LT.(%s)) THEN\r\n',elements{1},elements{2});
+    text = sprintf('%s        %s = %s\r\n',text,name,elements{1});
+    text = sprintf('%s    ELSE\r\n',text);
+    text = sprintf('%s        %s = %s\r\n',text,name,elements{2});
+    text = sprintf('%s    ENDIF',text);
+end
+changedformula = text;
+return
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/handleNONMEMpiecewiseSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/handleNONMEMpiecewiseSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..16ba91f7270705c38ca1a19d383e17aad2be0b87
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/handleNONMEMpiecewiseSBPOP.m
@@ -0,0 +1,110 @@
+function [ changedformula ] = handleNONMEMpiecewiseSBPOP(name,formula)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE PIECEWISE EXPRESSIONS => if elseif else end
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+formula = strtrim(formula);
+% 1) Check that only a single piecewise expression 
+index = strfind(formula,'piecewiseSB');
+if length(index) > 1,
+    error('More than one piecewise expression in formula ''%s''. Only one is allowed.',formula);
+end
+% 2) Get the piecewise expression
+pwformula = strtrim(formula(index:end));
+offset = length('piecewiseSB(')+1;
+po = 1;
+while po~=0,
+    if pwformula(offset) == '(',
+        po = po+1;
+    end
+    if pwformula(offset) == ')',
+        po = po-1;
+    end
+    offset = offset+1;
+end
+pwformula = pwformula(1:offset-1);
+% 3) Check length pwformula against formula. If not same => error, since
+% then additional terms are present in the formula.
+if length(formula) ~= length(pwformula),
+    error('Formula ''%s'' contains more than a simple piecewise expression => please reformulate the SBmodel.',formula);
+end
+% 4) Get elements of pw expression
+elements = explodePCSB(pwformula(13:end-1));
+% 5) parse and convert the trigger expressions
+for k=2:2:length(elements),
+    elements{k} = convertlogicalrelationalexpressions(elements{k});
+end
+% 6) check if an else is present
+n = length(elements);
+if n/2 == floor(n/2),
+    elsepresent = 0;
+else
+    elsepresent = 1;
+end
+% 6) construct the if elseif else text
+if elsepresent,
+    elseelement = elements{end};
+    elements = elements(1:end-1);
+end
+% if 
+text = sprintf('IF(%s) THEN\r\n        %s = %s\r\n',elements{2},name,elements{1});
+% elseif
+if length(elements) > 2,
+    for k=4:2:length(elements),
+        text = sprintf('%s    ELSEIF(%s) THEN\r\n        %s = %s\r\n',text,elements{k},name,elements{k-1});        
+    end
+end
+% else
+if elsepresent,
+    text = sprintf('%s    ELSE\r\n        %s = %s\r\n',text,name,elseelement);
+end
+% end
+text = sprintf('%s    ENDIF',text);
+% done
+changedformula = text;
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PARSE AND CONVERT LOGICAL AND RELATIONAL OPERATORS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% the syntax of MLXTRAN only allows two elements for each and, or, ...
+% and(gt(time,5),lt(time,10)) => (time.gt.5).and.(time.lt.10)
+function [exp] = convertlogicalrelationalexpressions(exp)
+operatorsfind = {'and','or','andSB','orSB','lt','gt','le','ge','eq','ne'};
+operatorsuse  = {'.AND.','.OR.','.AND.','.OR.',' < ',' > ',' <= ',' >= ',' == ',' /= '};
+exp = ['#' exp '#'];
+for k=1:length(operatorsfind),
+    index = regexp(exp,['\W' operatorsfind{k} '\W']);
+    if ~isempty(index),
+        % get pre text
+        exppre = exp(1:index);
+        % get post text and arguments
+        temp = exp(index+1+length(operatorsfind{k})+1:end);
+        po = 1;
+        offset = 1;
+        while po~= 0,
+            if temp(offset) == '(',
+                po = po+1;
+            end
+            if temp(offset) == ')',
+                po = po-1;
+            end
+            offset = offset + 1;
+        end
+        args = explodePCSB(temp(1:offset-2));
+        if length(args) > 2,
+            error('Only two arguments allowed in an ''andSB'' or ''orSB'' when converting piecewiseSB to MLXTRAN.');
+        end
+        exppost = temp(offset:end);
+        % get args
+        exp = [exppre '(' args{1} ')' operatorsuse{k} '(' args{2} ')'   exppost];
+    end
+end
+exp = exp(2:end-1);
+return
+
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/processDataAndGetMedianValuesSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/processDataAndGetMedianValuesSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..6e42a81dbfbea98ba0ba15f410ecee1ab61ff5ab
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/processDataAndGetMedianValuesSBPOP.m
@@ -0,0 +1,106 @@
+function [ covariateMedianNames,covariateMedianValues,covariateCATNames,covariateCATValues,dataheader,dataCSV ] = processDataAndGetMedianValuesSBPOP( oldpath,dataRelPathFromProject,dataFileName,dataHeaderIdent,SILENT,COVcentering_covs,COVcentering_values  )
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if datafile exists and csv file and load some information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dataFile = fullfile(dataRelPathFromProject,dataFileName);
+try
+    dataheader = SBPOPloadCSVdataset(dataFile,1);
+catch
+    cd(oldpath);
+    error('Please check if the data file "%s" exists.',dataFile)
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if length of header identical to dataHeaderIdent
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if length(explodePCSB(dataHeaderIdent,',')) ~= length(dataheader),
+    cd(oldpath);
+    error('Please check: The data header identifiers do not have the same length as the number of columns in the dataset.')
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Load dataset and get header information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dataCSV     = SBPOPloadCSVdataset(fullfile(dataRelPathFromProject,dataFileName));
+dataheader  = get(dataCSV,'VarNames');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine medians for covariates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine index of COV columns and their names
+terms                   = explodePCSB(dataHeaderIdent);
+ixCOVs                  = strmatchSB('COV',terms,'exact');
+
+covariateMedianValues = [];
+covariateMedianNames = {};
+if ~isempty(ixCOVs),
+    dataheaderCOVs      = dataheader(ixCOVs);
+    
+    % Determine index of ID column and ID name
+    terms               = explodePCSB(dataHeaderIdent);
+    ixID                = strmatchSB('ID',terms,'exact');
+    dataheaderID        = dataheader(ixID);
+    
+    % Get covariate values for each individual
+    allID               = unique(dataCSV.(dataheaderID{1}));
+    allCOVs             = NaN(length(allID),length(ixCOVs));
+    for k=1:length(allID),
+        datak           = dataCSV(dataCSV.(dataheaderID{1})==allID(k),ixCOVs);
+        allCOVs(k,:)    = double(datak(1,:));
+    end
+    
+    % Determine median
+    covariateMedianValues   = median(allCOVs);
+    covariateMedianNames    = dataheaderCOVs;
+    
+    % Handle custom centering values
+    for k=1:length(COVcentering_covs),
+        ix = strmatchSB(COVcentering_covs{k},covariateMedianNames,'exact');
+        covariateMedianValues(ix) = COVcentering_values(k);
+    end
+    
+    if ~SILENT,
+        disp(' ')
+        disp('Analysis of dataset for covariates - determine the centering values  ')
+        disp('These are the median values, if not defined differently by the user.')
+        disp(' Results:');
+        for k=1:length(covariateMedianValues),
+            disp(sprintf('   median(%s) = %g',covariateMedianNames{k},covariateMedianValues(k)));
+        end
+        disp('These values will be used to center the continuous covariates')
+        disp(' ')
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determines the categorical covariates and the elements they can take
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine index of COV columns and their names
+terms                   = explodePCSB(dataHeaderIdent);
+ixCATs                  = strmatchSB('CAT',terms,'exact');
+
+covariateCATValues = {};
+covariateCATNames = {};
+if ~isempty(ixCATs),
+    dataheaderCATs      = dataheader(ixCATs);
+    
+    % Get unique elements for each cat covariate and names ...
+    for k=1:length(ixCATs),
+        covariateCATNames{k} = dataheaderCATs{k};
+        covariateCATValues{k} = unique(dataCSV.(dataheaderCATs{k}));
+        if sum(isnan(unique(dataCSV.(dataheaderCATs{k})))) > 0,
+            error('The categorical covariate "%s" contains NaN => please impute before running the parameter estimation.',dataheaderCATs{k});
+        end
+    end
+    
+    % Print information about reference values
+    if ~SILENT,
+        disp(' ');
+        disp('The following values for the categorical covariates are used as reference values:');
+        for k=1:length(covariateCATNames),
+            disp(sprintf('\t%s%s: %d',covariateCATNames{k},char(32*ones(1,cellmaxlengthSBPOP(covariateCATNames)-length(covariateCATNames{k})+5)),covariateCATValues{k}(1)));
+        end
+        disp(' ');
+    end
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/reorderParameters4NONMEMcovSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/reorderParameters4NONMEMcovSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..87525a3c667b7b5e0660ed9055deb0f3935e3bc6
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/reorderParameters4NONMEMcovSBPOP.m
@@ -0,0 +1,48 @@
+function [param_est_trans,POPestimate_trans,POPvalues0_trans,IIVestimate_trans,IIVvalues0_trans,IIVdistribution_trans] = reorderParameters4NONMEMcovSBPOP(covarianceModel,param_est,POPestimate,POPvalues0,IIVestimate,IIVvalues0,IIVdistribution)
+% Change the order of parameters in relvant variables based on the
+% covariance model information (we need to allow for block diagonal
+% covariance matrices)
+
+if strcmp(covarianceModel,'diagonal') || isempty(covarianceModel),
+    % Keep parameters in the given order
+    POPestimate_trans       = POPestimate;
+    POPvalues0_trans        = POPvalues0;
+    IIVestimate_trans       = IIVestimate;
+    IIVvalues0_trans        = IIVvalues0;
+    param_est_trans         = param_est;
+    IIVdistribution_trans   = IIVdistribution;    
+else
+    % Need to rearrange
+    % Determine the order of parameters as they appear in the
+    % covarianceModel definition
+    x = strrep(covarianceModel,'{','');
+    x = strrep(x,'}','');
+    terms = explodePCSB(x);
+    % Check which parameters are missing
+    paramnames_order = terms;
+    for k=1:length(param_est),
+        if ~ismember(param_est(k).name,paramnames_order),
+            paramnames_order{end+1} = param_est(k).name;
+        end
+    end
+    % Determine the transformation indices
+    index_trans = [];
+    for k=1:length(paramnames_order),
+        index_trans(k) = strmatchSB(paramnames_order{k},{param_est.name},'exact');
+    end
+    % Ok, we got the new order of the parameters, now we need to change the
+    % order in a couple of things
+    % POPestimate
+    % POPvalues0
+    % IIVdistribution
+    % IIVestimate
+    % IIVvalues0
+    % param_est
+    POPestimate_trans       = POPestimate(index_trans);
+    POPvalues0_trans        = POPvalues0(index_trans);
+    IIVestimate_trans       = IIVestimate(index_trans);
+    IIVvalues0_trans        = IIVvalues0(index_trans);
+    param_est_trans         = param_est(index_trans);
+    IIVdistribution_trans   = IIVdistribution(index_trans);
+end
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/wrapRowTextSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/wrapRowTextSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..3cc639839e8a18786204b1b640edd11114321414
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/wrapRowTextSBPOP.m
@@ -0,0 +1,20 @@
+function [ wraptext ] = wrapRowTextSBPOP( text,ncol, npre )
+% wrapRowTextSBPOP: wraps the text to max ncol characters per row and adds
+% npre spaces at the beginning of all subsequent rows
+
+textwork            = text;
+wraptext            = '';
+while length(textwork)>ncol,
+    ixSpace = find(double(textwork)==32);
+    ixSpaceAbove = find(ixSpace>ncol);
+    if ~isempty(ixSpaceAbove),
+        ixSpaceLimit = ixSpace(ixSpaceAbove(1)-1);
+    else
+        ixSpaceLimit = ixSpace(end);
+    end
+    wraptext = sprintf('%s%s\r\n',wraptext,textwork(1:ixSpaceLimit-1));
+    textwork = [char(32*ones(1,npre)) textwork(ixSpaceLimit+1:end)];
+end
+wraptext = strtrim(sprintf('%s%s\r\n',wraptext,textwork));
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/writeOutConversionNONMEMinformationSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/writeOutConversionNONMEMinformationSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..4aa85257302ca2d1f3fa4b28d482ccd2e57c5b2e
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/modelconversion/writeOutConversionNONMEMinformationSBPOP.m
@@ -0,0 +1,31 @@
+function [ ] = writeOutConversionNONMEMinformationSBPOP( param_est, IIVdistribution, IIVestimate )
+
+% Print table parameter names and IIV distributions
+disp(' ');
+disp('Please check that the following matches between parameters and used IIV distributions are correct:');
+for k=1:length(param_est),
+    if IIVdistribution{k} == 'L', dtext = 'logNormal'; end
+    if IIVdistribution{k} == 'N', dtext = 'Normal'; end
+    if IIVdistribution{k} == 'G', dtext = 'logitNormal'; end
+    fprintf('\t%s%s: %s\n',param_est(k).name,char(32*ones(1,15-length(param_est(k).name))),dtext)
+end
+
+% Print table parameter names and IIV esimations
+disp(' ');
+disp('Please check that the following matches between parameters and used estimated IIVs are correct:');
+for k=1:length(param_est),
+    if IIVestimate(k) == 0,
+        fprintf('\t%s%s: IIV NOT ESTIMATED (kept on 0)\n',param_est(k).name,char(32*ones(1,15-length(param_est(k).name))));
+    elseif IIVestimate(k) == 1,
+        fprintf('\t%s%s: IIV ESTIMATED\n',param_est(k).name,char(32*ones(1,15-length(param_est(k).name))));
+    elseif IIVestimate(k) == 2,
+        fprintf('\t%s%s: IIV NOT ESTIMATED (kept on initial value)\n',param_est(k).name,char(32*ones(1,15-length(param_est(k).name))));
+    end
+end
+disp(' ');
+
+disp('Parameters selected to be estimated and their values in the model (this order):');
+for k=1:length(param_est),
+    fprintf('\t%d)\t%s%s: %g\n',k,param_est(k).name,char(32*ones(1,15-length(param_est(k).name))),param_est(k).value0(1));
+end
+disp(' ');
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/other/fitanalysisETAvsCOVnonmemSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/other/fitanalysisETAvsCOVnonmemSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..0102740698a01a1e6fe559390b99e7bb8ad4095d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/other/fitanalysisETAvsCOVnonmemSBPOP.m
@@ -0,0 +1,207 @@
+function [] = fitanalysisETAvsCOVnonmemSBPOP(data,projectPath,covNames,catNames,options)    
+% fitanalysisETAvsCOVnonmemSBPOP: Called by SBPOPfitanalysisETAvsCOV - same calling syntax.
+% Not using the data information.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle varargins
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try corrcoeffThreshold = options.corrcoeffThreshold; catch, corrcoeffThreshold = 0.3; end
+try filename = options.filename; catch, filename = ''; end
+try withlabels = options.labels; catch, withlabels = 0; end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Load the etas and covariates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+etaCovs = SBPOPloadNONCSVdataset([projectPath '/RESULTS/project.eta'],1); 
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check cov and catnames to be present in the etaCovs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+datanames = get(etaCovs,'VarNames');
+
+ixRemoveCovNames = [];
+for k=1:length(covNames),
+    if isempty(strmatchSB(covNames{k},datanames,'exact')), 
+        warning('The project.eta file does not contain the covariate ''%s''.\nNot considered in analysis.',covNames{k}); 
+        ixRemoveCovNames(end+1) = k;
+    end    
+end
+covNames(ixRemoveCovNames) = [];
+
+ixRemoveCovNames = [];
+for k=1:length(catNames),
+    if isempty(strmatchSB(catNames{k},datanames,'exact')), 
+        warning('The project.eta file does not contain the covariate ''%s''\nNot considered in analysis.',catNames{k}); 
+        ixRemoveCovNames(end+1) = k;
+    end    
+end
+catNames(ixRemoveCovNames) = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get the ETAs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ixETA = strmatchSB('ETA_',get(etaCovs,'VarNames'));
+dataeta = etaCovs(:,[1 ixETA(:)']);
+dataeta = set(dataeta,'VarNames',strrep(get(dataeta,'VarNames'),'ETA_',''));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get covs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ixCOVs = [];
+for k=1:length(covNames),
+    ixCOVs(end+1) = strmatchSB(covNames{k},get(etaCovs,'VarNames'),'exact');
+end
+datacovs = etaCovs(:,[1 ixCOVs(:)']);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get cats
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ixCATs = [];
+for k=1:length(catNames),
+    ixCATs(end+1) = strmatchSB(catNames{k},get(etaCovs,'VarNames'),'exact');
+end
+datacats = etaCovs(:,[1 ixCATs(:)']);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Remove the non estimated omegas/etas
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ix =  find(sum(abs(double(dataeta(:,2:end)))) ~= 0);
+dataeta_est                 = dataeta(:,[1 ix+1]);
+
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% % Get the categorical covariates for same IDs as in the dataeta_est
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% allIDeta = unique(dataeta_est.ID);
+% datacats = dataset();
+% dataeta_cats = dataset(); % eta dataset in case when there is iov and each occasion has a repeated entry in dataeta_est
+% for k=1:length(allIDeta),
+%     datak = data(data.ID==allIDeta(k),:);
+%     datacatsk = dataset();
+%     datacatsk.ID = allIDeta(k);
+%     datak_etas = dataeta_est(dataeta_est.ID == allIDeta(k),:);
+%     for k2=1:length(catNames),
+%         datacatsk.(catNames{k2}) = datak.(catNames{k2})(1);
+%     end
+%     datacats = [datacats; datacatsk];
+%     dataeta_cats = [dataeta_cats; datak_etas(1,:)]; % this avoids duplicate lines when iov
+% end
+% dataeta_cats.ID = []; % we don't need the id column
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Interface to old code ;-)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+etas = dataeta_est(:,2:end);
+covs = datacovs(:,2:end);
+cats = datacats(:,2:end);
+nretas = size(etas,1);
+nrcovs = size(covs,1);
+nrcats = size(cats,1);
+etaNames = get(etas,'VarNames');
+covNames = get(covs,'VarNames');
+catNames = get(cats,'VarNames');
+ids = datacovs.ID;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine subplot organization
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+Neta = length(etaNames);
+nrow = ceil(sqrt(Neta));
+ncol = ceil(Neta/nrow);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% If filename then remove old file
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(filename),
+    startNewPrintFigureSBPOP(filename);
+    % also create path if not yet created
+    [p,f,e] = fileparts(filename);
+    warning off
+    mkdir(p);
+    warning on
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% First handle continuous covariates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Cycle through covariates and produce one figure per covariate
+% The etas in subplots
+for k=1:size(covs,2),
+    cov = double(covs(:,k));
+    % New figure
+    h = figure;
+    set(h,'Name',['Covariate: ' covNames{k}])
+    for k2=1:size(etas,2),
+        name = etaNames{k2};
+        eta = double(etas(:,k2));
+        subplot(nrow,ncol,k2);
+        [cc,pp] = corrcoef([cov,eta]);
+        cc = cc(1,2);
+        pp = pp(1,2);
+        if abs(cc) > corrcoeffThreshold,            
+            plot(cov,eta,'.r','MarkerSize',20); hold on
+            if(withlabels)
+                labels1 = cellstr( num2str(ids, '%d') );
+                text(cov, eta, labels1, 'VerticalAlignment','bottom', 'HorizontalAlignment','right', 'FontSize', 8)
+            end
+        else
+            plot(cov,eta,'.b','MarkerSize',20); hold on
+            if(withlabels)
+                labels1 = cellstr( num2str(ids, '%d') );
+                text(cov, eta, labels1, 'VerticalAlignment','bottom', 'HorizontalAlignment','right', 'FontSize', 8)
+            end
+        end
+        % Add linear regression result
+        X = [ones(size(cov)) cov];
+        warning off
+        b = regress(eta,X); % Removes NaN data
+        warning on
+        x = get(gca,'XLim');        
+        plot(x, b(1)+b(2)*x,'k--','LineWidth',2)
+        % Title etc.
+        title(['Corr. coeff.: ' sprintf('%1.2g (p=%1.2g)',cc,pp)],'Interpreter','None');
+        xlabel(covNames{k},'Interpreter','None')
+        ylabel(['eta_' etaNames{k2}],'Interpreter','None')
+    end
+    set(h,'Color',[1 1 1]);
+    if ~isempty(filename),
+        printFigureSBPOP(gcf,filename);
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Second handle categorical covariates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
+% Cycle through covariates and produce one figure per covariate
+% The etas in subplots
+for k=1:size(cats,2),
+    cat = double(cats(:,k));
+    catunique = unique(cat);
+    % New figure
+    h = figure;
+    set(h,'Name',['Covariate: ' catNames{k}]);
+    for k2=1:size(etas,2),
+        name = etaNames{k2};
+        eta = double(etas(:,k2));
+        x = [eta cat];
+        subplot(nrow,ncol,k2);
+        % Adjust whislers to 5 and 95 percentiles
+        SBPOPboxplot([5 95],0,eta,cat,'orientation','horizontal');
+        plotZeroLim = get(gca,'YLim');
+        hold on;
+        plot([0 0],plotZeroLim,'--k')
+        xlabel(['eta_' etaNames{k2}],'Interpreter','None')
+        ylabel(catNames{k},'Interpreter','None')
+    end
+    set(h,'Color',[1 1 1]);    
+    if ~isempty(filename),
+        printFigureSBPOP(gcf,filename);
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PS2PDF
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(filename),
+    convert2pdfSBPOP(filename);
+    close all;
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/other/parseNONMEMetasSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/other/parseNONMEMetasSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..649acfdbde5117fdb14079228ffe94dff7dbd0c5
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/other/parseNONMEMetasSBPOP.m
@@ -0,0 +1,44 @@
+function [ dataeta, OMEGA, OMEGAnames ] = parseNONMEMetasSBPOP( projectPath )
+% parseNONMEMetasSBPOP: Parses a NONMEM project and returns the ETAs.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Construct RESULTS path
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+resultsPath = [projectPath '/RESULTS'];
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check the projectPath
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~exist(resultsPath),
+    error(sprintf('The provided project path "%s" does not point to a valid SBPOP/NONMEM project.\nPlease make sure a "RESULTS" folder is in the provided path.',projectPath));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check that indiv_eta.txt is present in the RESULTS folder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+indiv_eta_file = [resultsPath '/project.eta'];
+if ~exist(indiv_eta_file)
+    error('The "project.eta" file does not exist in the RESULTS folder.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine random effect estimates for shrinkage determination
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+x = parseNONMEMresultsSBPOP(projectPath);
+y = sampleNONMEMpopulationParametersSBPOP(x,0,1);
+OMEGA       = y.randomEffects.values;
+OMEGAnames  = y.randomEffects.names;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Load eta file
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+indiv_eta   = SBPOPloadNONCSVdataset([resultsPath '/project.eta'],1);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get eta modes
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dataeta = dataset();
+for k=1:length(OMEGAnames),
+    dataeta.(OMEGAnames{k}) = indiv_eta.(['ETA_' OMEGAnames{k}]);
+end
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/other/parseNONMEMindivparamSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/other/parseNONMEMindivparamSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..3407084be1c3c92e4a3fc61efb4ca77c8433a9e7
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/other/parseNONMEMindivparamSBPOP.m
@@ -0,0 +1,20 @@
+function [ indiv_param ] = parseNONMEMindivparamSBPOP( projectPath,numberParameters )
+% parseNONMEMindivparamSBPOP: Returns the individual parameters from a
+% MONOLIX fit. numberParameters needs to be provided to know how many they
+% are, since this can change depending on the settings.
+
+indiv_param             = SBPOPloadNONCSVdataset([projectPath '/RESULTS/project.indiv'],1);
+indiv_param             = indiv_param(:,1:numberParameters+1);
+
+% Check case of parameter names (might be changed by really cute NONMEM
+% program ...)
+X = parseProjectHeaderNONMEMSBPOP(projectPath);
+PN = X.PARAMNAMES;
+VN = get(indiv_param,'VarNames');
+for k=1:length(VN),
+    ix = strmatch(lower(VN{k}),lower(PN),'exact');
+    if ~isempty(ix),
+        VN{k} = PN{ix};
+    end
+end
+indiv_param = set(indiv_param,'VarNames',VN);
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/other/parseNONMEMpredictionsSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/other/parseNONMEMpredictionsSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..c2bb29c73fdcddd93123217de4bbcee734b836b4
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/other/parseNONMEMpredictionsSBPOP.m
@@ -0,0 +1,29 @@
+function [ predictions ] = parseNONMEMpredictionsSBPOP( projectPath,outputNumber )
+% parseNONMEMpredictionsSBPOP: Parses a NONMEM project and returns the 
+% predictions for a given output number.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Construct RESULTS path
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+resultsPath = [projectPath '/RESULTS'];
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check the projectPath
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~exist(resultsPath),
+    error(sprintf('The provided project path "%s" does not point to a valid SBPOP/NONMEM project.\nPlease make sure a "RESULTS" folder is in the provided path.',projectPath));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Load predictions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+predictions = SBPOPloadNONCSVdataset([resultsPath '/project.pred'],1);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Select the right output
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+predictions(predictions.EVID==1,:) = [];
+predictions = predictions(predictions.YTYPE==outputNumber,:);
+
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/parseNONMEMresultsSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/parseNONMEMresultsSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..74c9f235d95b87c96304098bc7696acc375c0a4a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/parseNONMEMresultsSBPOP.m
@@ -0,0 +1,582 @@
+function [ output ] = parseNONMEMresultsSBPOP( path_to_nonmem_project_folder, transformFlag )
+% [DESCRIPTION]
+% This function parses the output of NONMEM and returns all information in
+% a structure. The NONMEM project needs to have been created with SBPOP!
+% If more than one estimation methods have been concatenated, the results
+% of the last one are reported. 
+%
+% The parameters are not backtransformed from the MU referencing. But the
+% required transformations are defined in the output structure. This does
+% only apply to the fixed effect parameters in the THETAs.
+%
+% [SYNTAX]
+% output = parseNONMEMresultsSBPOP( path_to_nonmem_project_folder )
+% output = parseNONMEMresultsSBPOP( path_to_nonmem_project_folder, transformFlag )
+%
+% [INPUT]
+% path_to_nonmem_project_folder: path to the NONMEM project folder.
+% transformFlag: =0 (default): do not back transform the fixed effect
+%                parameters in the output.rawParameterInfo.fixedEffects and
+%                output.parameters.values based on the MU referencing
+%                transformation. 
+%                =1: do back transform ... will also approximate the
+%                standard errors by sampling.
+%                Note: these backtransformed parameters are for analysis
+%                purpose only ... for reporting the original parameters
+%                need to be used - or careful wording.
+% [OUTPUT]
+% Structure with the certain outputs.
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt
+%
+% [DATE]
+% 02.05.2014
+%
+% [PLATFORM]
+% MATLAB R2013a
+%
+% [KEYWORDS]
+% MONOLIX, results, parsing
+% 
+% [TOOLBOXES USED]
+% NONE
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+if nargin == 1,
+    transformFlag = 0;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if folder exists and that RESULTS folder exists within
+% and that the project.nmctl file exists
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if exist(path_to_nonmem_project_folder) ~= 7,
+    error('The specified NONMEM project folder "%s" does not exist.',path_to_nonmem_project_folder);
+end
+if exist([path_to_nonmem_project_folder '/RESULTS']) ~= 7,
+    error('The "RESULTS" folder within the project folder "%s" does not exist.',path_to_nonmem_project_folder);
+end
+if ~exist([path_to_nonmem_project_folder '/project.nmctl']),
+    error('The "project.nmctl" in the NONMEM project folder "%s" does not exist.',path_to_nonmem_project_folder);
+end
+if ~exist(fullfile(path_to_nonmem_project_folder, 'RESULTS', 'project.xml')), 
+    error('Please check if the "%s" folder contains the ''project.xml'' file.',path_to_nonmem_project_folder);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Load project info
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+PROJECTINFO = parseProjectHeaderNONMEMSBPOP(path_to_nonmem_project_folder);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Parse the xml results
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+RESULTS = parseNONMEMxmlFileSBPOP(path_to_nonmem_project_folder);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Initialize the output structure and enter already the simple things
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+output                          = [];
+output.type                     = 'NONMEM';
+output.method                   = PROJECTINFO.METHOD;
+output.termination_info         = RESULTS.termination_info;
+output.path                     = path_to_nonmem_project_folder;
+output.parameters               = [];
+output.objectivefunction        = [];
+output.residualerrormodels      = PROJECTINFO.ERRORMODELS; % mapping inv/trans OK
+output.trans_randeffects        = PROJECTINFO.PARAMINVTRANS;
+output.inv_trans_randeffects    = PROJECTINFO.PARAMTRANS;
+% output.covariates.names         = PROJECTINFO.COVARIATENAMES;
+output.rawParameterInfo         = [];
+output.PROJECTINFO              = PROJECTINFO;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine AIC and BIC
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+OFVvalue = RESULTS.objectivefunction;
+NRPARAMETERS_ESTIMATED = eval(PROJECTINFO.NRPARAM_ESTIMATED{1});
+NROBSERVATIONS = eval(PROJECTINFO.NROBSERVATIONS{1});
+% AIC: OFVvalue+2*numberParametersEstimated
+AIC = OFVvalue + 2*NRPARAMETERS_ESTIMATED;
+% BIC: 
+BIC = OFVvalue + NRPARAMETERS_ESTIMATED*(log(NROBSERVATIONS) + log(2*pi));
+% Add to output structure
+output.objectivefunction.OBJ = OFVvalue;
+output.objectivefunction.AIC = AIC;
+output.objectivefunction.BIC = BIC;
+
+if isnan(OFVvalue),
+    return
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get real THETA names and transformations
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+names_real  = {};
+names = RESULTS.THETA.names;
+theta_ix = 1:length(names);
+% Match with THETANAMES etc. (order is correct)
+names_real  = PROJECTINFO.THETANAMES(theta_ix)';
+% Get transformations for all thetas but do not transform
+trans  = cell(1,length(names_real));
+trans(1:end) = {''};
+for k=1:length(PROJECTINFO.PARAMNAMES),
+    invtrans = PROJECTINFO.PARAMINVTRANS{k};
+    param = PROJECTINFO.PARAMNAMES{k};
+    % find index in theta_names
+    ix = strmatchSB(param,names_real,'exact');
+    trans{ix} = invtrans;
+end
+RESULTS.THETA.names_real = names_real(:)';
+RESULTS.THETA.trans = trans(:)';
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Change names for OMEGA2
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+names_real = {};
+names_real_alternative = {};
+names = RESULTS.OMEGA2.names;
+for k=1:length(names),
+    n = names{k};
+    n = strrep(n,'OMEGA2','');
+    n = strrep(n,'_','');
+    terms = explodePCSB(n);
+    row = eval(terms{1});
+    col = eval(terms{2});
+    if row==col,
+        names_real{end+1} = sprintf('omega2(%s)',PROJECTINFO.PARAMNAMES{row});
+    else
+        names_real{end+1} = sprintf('omega2(%s,%s)',PROJECTINFO.PARAMNAMES{row},PROJECTINFO.PARAMNAMES{col});
+        names_real_alternative{end+1} = sprintf('omega2(%s,%s)',PROJECTINFO.PARAMNAMES{col},PROJECTINFO.PARAMNAMES{row});
+    end
+end
+RESULTS.OMEGA2.names_real = names_real(:)';
+RESULTS.OMEGA2.names_real_alternative = names_real(:)';
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Change names for OMEGAC
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+names_real = {};
+names_real_alternative = {};
+names = RESULTS.OMEGAC.names;
+for k=1:length(names),
+    n = names{k};
+    n = strrep(n,'OMEGAC','');
+    n = strrep(n,'_','');
+    terms = explodePCSB(n);
+    row = eval(terms{1});
+    col = eval(terms{2});
+    if row==col,
+        names_real{end+1} = sprintf('omega(%s)',PROJECTINFO.PARAMNAMES{row});
+    else
+        names_real{end+1} = sprintf('corr(%s,%s)',PROJECTINFO.PARAMNAMES{row},PROJECTINFO.PARAMNAMES{col});
+        names_real_alternative{end+1} = sprintf('corr(%s,%s)',PROJECTINFO.PARAMNAMES{col},PROJECTINFO.PARAMNAMES{row});
+    end
+end
+RESULTS.OMEGAC.names_real = names_real(:)';
+RESULTS.OMEGAC.names_real_alternative = names_real(:)';
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Change names for CORRELATION and COVARIANCE matrices
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+names_real = {};
+names_real_alternative = {};
+names = RESULTS.COV_COR_MATRIX_NAMES;
+names_notcell = {};
+for k=1:length(names),
+    x = names{k}{1};
+    names_notcell{end+1} = x;
+    % check if THETA
+    if ~isempty(strfind(x,'THETA')),
+        names_real{k} = RESULTS.THETA.names_real{eval(strrep(x,'THETA',''))};
+        names_real_alternative{k} = RESULTS.THETA.names_real{eval(strrep(x,'THETA',''))};
+    end
+    % Check if OMEGA
+    if ~isempty(strfind(x,'OMEGA')),
+        x = strrep(x,'OMEGA','');
+        x = strrep(x,'_','');
+        terms = explodePCSB(x);
+        row = eval(terms{1});
+        col = eval(terms{2});
+        if row==col,
+            names_real{k} = sprintf('omega2(%s)',PROJECTINFO.PARAMNAMES{row});
+            names_real_alternative{k} = sprintf('varIIV_%s',PROJECTINFO.PARAMNAMES{row});
+        else
+            names_real{k} = sprintf('omega2(%s,%s)',PROJECTINFO.PARAMNAMES{row},PROJECTINFO.PARAMNAMES{col});
+            names_real_alternative{k} = sprintf('omega2(%s,%s)',PROJECTINFO.PARAMNAMES{col},PROJECTINFO.PARAMNAMES{row});
+        end    
+    end
+    % Check if SIGMA (not needed)
+    if ~isempty(strfind(x,'SIGMA')),
+        names_real{k} = 'SIGMA';
+        names_real_alternative{k} = 'SIGMA';
+    end
+end
+RESULTS.COVARIANCEMATRIX.names = names_notcell(:)';
+RESULTS.COVARIANCEMATRIX.names_real = names_real(:)';
+RESULTS.COVARIANCEMATRIX.names_real_alternative = names_real_alternative(:)';
+RESULTS.COVARIANCEMATRIX.matrix = RESULTS.COVARIANCE_MATRIX;
+RESULTS = rmfield(RESULTS,'COVARIANCE_MATRIX');
+
+RESULTS.CORRELATIONMATRIX.names = names_notcell(:)';
+RESULTS.CORRELATIONMATRIX.names_real = names_real(:)';
+RESULTS.CORRELATIONMATRIX.names_real_alternative = names_real_alternative(:)';
+RESULTS.CORRELATIONMATRIX.matrix = RESULTS.CORRELATION_MATRIX;
+RESULTS = rmfield(RESULTS,'CORRELATION_MATRIX');
+
+RESULTS = rmfield(RESULTS,'COV_COR_MATRIX_NAMES');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% rawParameters field: information only for displaying but not for sampling
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create the rawParameterInfo field - fixedEffects
+% Based on RESULTS.THETA
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fixedEffects            = [];
+fixedEffects.names      = PROJECTINFO.PARAMNAMES;
+fixedEffects.estimated  = [];
+fixedEffects.trans      = PROJECTINFO.PARAMINVTRANS;
+fixedEffects.invtrans   = PROJECTINFO.PARAMTRANS;
+fixedEffects.values     = [];
+fixedEffects.stderr     = [];
+fixedEffects.rse        = [];
+for k=1:length(fixedEffects.names),
+    % Determine if parameter was estimated
+    ix = strmatchSB(fixedEffects.names{k},PROJECTINFO.THETANAMES,'exact');
+    fixedEffects.estimated(k) = eval(PROJECTINFO.THETAESTIMATE{ix});
+    
+    % Always report value ... if estimated or not
+    % Determine index of parameter in results
+    ix = strmatchSB(fixedEffects.names{k},RESULTS.THETA.names_real,'exact');
+    fixedEffects.values(k)  = RESULTS.THETA.values(ix);
+    fixedEffects.stderr(k)  = RESULTS.THETA.standarderror(ix);
+    fixedEffects.rse(k)     = abs(100*fixedEffects.stderr(k)/fixedEffects.values(k));
+    
+    % But if not estimated then set stderr and rse to NaN
+    if fixedEffects.estimated(k)==0,
+        fixedEffects.stderr(k)  = NaN;
+        fixedEffects.rse(k)     = NaN;
+    end
+end
+% Add to output
+output.rawParameterInfo.fixedEffects = fixedEffects;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create the rawParameterInfo field - randomEffects
+% Based on RESULTS.OMEGAC
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+randomEffects = [];
+randomEffects.names = PROJECTINFO.ETANAMES;
+randomEffects.values = [];
+randomEffects.estimated = [];
+randomEffects.stderr = [];
+randomEffects.rse = [];
+for k=1:length(randomEffects.names),
+    % Determine if parameter was estimated
+    ix = strmatchSB(randomEffects.names{k},PROJECTINFO.ETANAMES,'exact');
+    randomEffects.estimated(k) = eval(PROJECTINFO.ETAESTIMATE{ix});
+    
+    ix = strmatchSB(randomEffects.names{k},RESULTS.OMEGAC.names_real,'exact');
+    if randomEffects.estimated(k)==1,
+    % If estimated provide values
+        randomEffects.values(k)  = RESULTS.OMEGAC.values(ix);
+        randomEffects.stderr(k)  = RESULTS.OMEGAC.standarderror(ix);
+        randomEffects.rse(k)     = abs(100*randomEffects.stderr(k)/randomEffects.values(k));
+    elseif randomEffects.estimated(k)==2,
+    % If fixed then provide values but NaN for stderr and rse
+        randomEffects.values(k)  = RESULTS.OMEGAC.values(ix);
+        randomEffects.stderr(k)  = NaN;
+        randomEffects.rse(k)     = NaN;
+    elseif randomEffects.estimated(k)==0,
+    % Not considered => value=0 and set stderr and rse to NaN
+        randomEffects.values(k)  = RESULTS.OMEGAC.values(ix);
+        randomEffects.stderr(k)  = NaN;
+        randomEffects.rse(k)     = NaN;
+    end    
+end
+% Add to output
+output.rawParameterInfo.randomEffects = randomEffects;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create the rawParameterInfo field - correlation
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+correlation = [];
+correlation.names = PROJECTINFO.CORRELATIONNAMES;
+ix_remove = [];
+for k=1:length(correlation.names),
+    if isempty(correlation.names{k}),
+        ix_remove(end+1) = k;
+    end
+end
+correlation.names(ix_remove) = [];
+correlation.values = [];
+correlation.estimated = [];
+correlation.stderr = [];
+correlation.rse = [];
+for k=1:length(correlation.names),
+    if ~isempty(correlation.names{k}),
+        % So far correlations appearing in results always estimated
+        correlation.estimated(k) = 1;
+
+        % Only handle if estimated, otherwise set to NaN
+        if correlation.estimated(k),
+            % Determine index of parameter in results
+            ix1 = strmatchSB(correlation.names{k},RESULTS.OMEGAC.names_real,'exact');
+            ix2 = strmatchSB(correlation.names{k},RESULTS.OMEGAC.names_real_alternative,'exact');
+            ix = unique([ix1 ix2]);
+            if isempty(ix), error('Please check.'); end
+            correlation.values(k)  = RESULTS.OMEGAC.values(ix);
+            correlation.stderr(k)  = RESULTS.OMEGAC.standarderror(ix);
+            correlation.rse(k)     = abs(100*correlation.stderr(k)/correlation.values(k));
+        else
+            correlation.values(k)  = RESULTS.OMEGAC.values(ix);
+            correlation.stderr(k)  = NaN;
+            correlation.rse(k)     = NaN;
+        end
+    end
+end
+% Add to output
+output.rawParameterInfo.correlation = correlation;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create the rawParameterInfo field - covariate
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+covariate = [];
+covariate.names = RESULTS.THETA.names_real(strmatchSB('beta_',RESULTS.THETA.names_real));
+covariate.values = [];
+covariate.stderr = [];
+covariate.estimated = [];
+covariate.rse = [];
+for k=1:length(covariate.names),
+    % Determine if parameter was estimated
+    ix = strmatchSB(covariate.names{k},PROJECTINFO.THETANAMES,'exact');
+    covariate.estimated(k) = eval(PROJECTINFO.THETAESTIMATE{ix});
+    
+    % Only handle if estimated, otherwise set to NaN
+    if covariate.estimated(k),
+        % Determine index of parameter in results
+        ix = strmatchSB(covariate.names{k},RESULTS.THETA.names_real,'exact');
+        covariate.values(k)  = RESULTS.THETA.values(ix);
+        covariate.stderr(k)  = RESULTS.THETA.standarderror(ix);
+        covariate.rse(k)     = abs(100*covariate.stderr(k)/covariate.values(k));
+    else
+        covariate.values(k)  = RESULTS.THETA.values(ix);
+        covariate.stderr(k)  = NaN;
+        covariate.rse(k)     = NaN;
+    end    
+end
+% Add to output
+output.rawParameterInfo.covariate = covariate;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create the rawParameterInfo field - covariate
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+errorParameter = [];
+errorParameter.names = RESULTS.THETA.names_real(strmatchSB('error_',RESULTS.THETA.names_real));
+errorParameter.values = [];
+errorParameter.stderr = [];
+errorParameter.estimated = [];
+errorParameter.rse = [];
+for k=1:length(errorParameter.names),
+    % Determine if parameter was estimated
+    ix = strmatchSB(errorParameter.names{k},PROJECTINFO.THETANAMES,'exact');
+    errorParameter.estimated(k) = eval(PROJECTINFO.THETAESTIMATE{ix});
+    
+    % Only handle if estimated, otherwise set to NaN
+    if errorParameter.estimated(k),
+        % Determine index of parameter in results
+        ix = strmatchSB(errorParameter.names{k},RESULTS.THETA.names_real,'exact');
+        errorParameter.values(k)  = RESULTS.THETA.values(ix);
+        errorParameter.stderr(k)  = RESULTS.THETA.standarderror(ix);
+        errorParameter.rse(k)     = abs(100*errorParameter.stderr(k)/errorParameter.values(k));
+    else
+        errorParameter.values(k)  = RESULTS.THETA.values(ix);
+        errorParameter.stderr(k)  = NaN;
+        errorParameter.rse(k)     = NaN;
+    end    
+end
+% Add to output
+output.rawParameterInfo.errorParameter = errorParameter;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% parameters field: contains information for sampling from uncertainty
+% distribution. all based on omega2 ... since for that the covariance
+% matrix works.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Construct the names field
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+names = [PROJECTINFO.THETANAMES PROJECTINFO.ETANAMES PROJECTINFO.CORRELATIONNAMES];
+names = strrep(names,'omega(','omega2(');
+names = strrep(names,'corr(','omega2(');
+% Remove empty fields (can happen due to PROJECTINFO.CORRELATIONNAMES)
+ix_remove = [];
+for k=1:length(names),
+    if isempty(names{k}),
+        ix_remove(end+1) = k;
+    end
+end
+names(ix_remove) = [];
+parameters = [];
+parameters.names = names;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Construct the FLAGestimated vector based on PROJECTINFO
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+x = [PROJECTINFO.THETAESTIMATE PROJECTINFO.ETAESTIMATE PROJECTINFO.CORRESTIMATE];
+x(ix_remove) = [];
+FLAGestimated = [];
+for k=1:length(x),
+    FLAGestimated(k) = eval(x{k});
+end
+parameters.FLAGestimated = FLAGestimated;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add the transformation information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+transformation = cell(1,length([PROJECTINFO.ETAESTIMATE PROJECTINFO.CORRESTIMATE]));
+transformation(1:end) = {''};
+transformation = [RESULTS.THETA.trans transformation];
+transformation(ix_remove) = [];
+parameters.transformation = transformation;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Construct the values vector
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+nmnames1 = [RESULTS.THETA.names_real(:)' RESULTS.OMEGA2.names_real(:)'];
+nmnames2 = [RESULTS.THETA.names_real(:)' RESULTS.OMEGA2.names_real_alternative(:)'];
+nmvalues = [RESULTS.THETA.values(:)'     RESULTS.OMEGA2.values(:)'];
+values = [];
+for k=1:length(parameters.names),
+    ix1 = strmatchSB(names{k},nmnames1,'exact');
+    ix2 = strmatchSB(names{k},nmnames2,'exact');
+    ix = unique([ix1 ix2]);
+    if isempty(ix),
+        error('Please check!');
+    end
+    values(k) = nmvalues(ix);
+end
+parameters.values = values;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Construct the standard errors vector
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(RESULTS.CORRELATIONMATRIX.matrix),
+    nmnames1 = [RESULTS.THETA.names_real(:)'        RESULTS.OMEGA2.names_real(:)'];
+    nmnames2 = [RESULTS.THETA.names_real(:)'        RESULTS.OMEGA2.names_real_alternative(:)'];
+    nmvalues = [RESULTS.THETA.standarderror(:)'     RESULTS.OMEGA2.standarderror(:)'];
+    stderrors = [];
+    for k=1:length(parameters.names),
+        ix1 = strmatchSB(names{k},nmnames1,'exact');
+        ix2 = strmatchSB(names{k},nmnames2,'exact');
+        ix = unique([ix1 ix2]);
+        if isempty(ix),
+            error('Please check!');
+        end
+        stderrors(k) = nmvalues(ix);
+    end
+else
+    stderrors = NaN(size(values));
+end
+parameters.stderrors = stderrors;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Construct the correlation and covariance matrices
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(RESULTS.CORRELATIONMATRIX.matrix),
+    nmnames1 = RESULTS.COVARIANCEMATRIX.names_real;
+    nmnames2 = RESULTS.COVARIANCEMATRIX.names_real_alternative;
+    ix_permutate = [];
+    for k=1:length(names)
+        ix1 = strmatchSB(parameters.names{k},nmnames1,'exact');
+        ix2 = strmatchSB(parameters.names{k},nmnames2,'exact');
+        ix = unique([ix1 ix2]);
+        if isempty(ix),
+            error('Please check!');
+        end
+        ix_permutate(k) = ix;
+    end
+    correlationmatrix = RESULTS.CORRELATIONMATRIX.matrix(ix_permutate,ix_permutate);
+    covariancematrix = RESULTS.COVARIANCEMATRIX.matrix(ix_permutate,ix_permutate);
+    % Need to set diagonal elements of correlationmatrix to 1
+    for k=1:length(correlationmatrix),
+        correlationmatrix(k,k) = 1;
+    end
+else
+    correlationmatrix = [];
+    covariancematrix = [];
+end
+parameters.correlationmatrix = correlationmatrix;
+parameters.covariancematrix = covariancematrix;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add parameters to output
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output.parameters = parameters;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Finally, check if the parameters should be back
+% transformed ... including approximation of standard errors.
+%
+% Application to output.parameters and output.rawParameterInfo.fixedEffects
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if transformFlag,
+    % Handle output.rawParameterInfo.fixedEffects
+    values = output.rawParameterInfo.fixedEffects.values;
+    stderr = output.rawParameterInfo.fixedEffects.stderr;
+    transf = output.rawParameterInfo.fixedEffects.trans;
+    for k=1:length(values),
+        if ~isempty(transf{k}),
+            phi     = values(k);
+            val     = eval(transf{k});
+            % sample standard error
+            if stderr(k)==0,
+                ste = 0;
+            else
+                phi = values(k)+stderr(k)*randn(1,100000);
+                ste = std(eval(trans{k}));
+            end
+            values(k) = val;
+            stderr(k) = ste;
+            transf{k} = '';
+            output.rawParameterInfo.fixedEffects.invtrans{k} = '';
+        end
+    end
+    output.rawParameterInfo.fixedEffects.values = values;
+    output.rawParameterInfo.fixedEffects.stderr = stderr;
+    output.rawParameterInfo.fixedEffects.trans  = transf;      
+    % Determine new RSEs
+    output.rawParameterInfo.fixedEffects.rse    = 100*stderr./values;
+    disp('NONMEM project: If IIV distributions other than "normal" have been used then the standard errors');
+    disp('                of the fixed effects are approximated by sampling in the back transformation.');
+    disp('                Impacting only: rawParameterInfo output from function parseNONMEMresultsSBPOP.');
+end
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/parseNONMEMxmlFileSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/parseNONMEMxmlFileSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..dba2300eede98bb3c7b7732d3e5e1251816d618f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/parseNONMEMxmlFileSBPOP.m
@@ -0,0 +1,374 @@
+function [ output ] = parseNONMEMxmlFileSBPOP( path_to_nonmem_project_folder )
+% [DESCRIPTION]
+% This function parses the xml file from NONMEM and returns all the
+% information. In case that multiple methods have been run, only the
+% results from the last one are reported.
+%
+% [SYNTAX]
+% output = parseNONMEMxmlFile( path_to_nonmem_project_folder )
+%
+% [INPUT]
+% path_to_nonmem_project_folder: path to the NONMEM project folder.
+%
+% [OUTPUT]
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt
+%
+% [DATE]
+% 02.05.2014
+%
+% [PLATFORM]
+% MATLAB R2013a
+%
+% [KEYWORDS]
+% MONOLIX, results, parsing
+% 
+% [TOOLBOXES USED]
+% NONE
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if folder exists and that RESULTS folder exists within
+% and that the project.nmctl file exists
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if exist(path_to_nonmem_project_folder) ~= 7,
+    error('The specified NONMEM project folder "%s" does not exist.',path_to_nonmem_project_folder);
+end
+if exist([path_to_nonmem_project_folder '/RESULTS']) ~= 7,
+    error('The "RESULTS" folder within the project folder "%s" does not exist.',path_to_nonmem_project_folder);
+end
+if ~exist([path_to_nonmem_project_folder '/project.nmctl']),
+    error('The "project.nmctl" in the NONMEM project folder "%s" does not exist.',path_to_nonmem_project_folder);
+end
+if ~exist(fullfile(path_to_nonmem_project_folder, 'RESULTS', 'project.xml')), 
+    error('Please check if the "%s" folder contains the ''project.xml'' file.',path_to_nonmem_project_folder);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Initialize the output structure and enter already the simple things
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+output                          = [];
+output.projectPath              = path_to_nonmem_project_folder;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Load the project.xml file and 
+% remove the namespace thingy ... NONMEM does not seem to be consistently using it :-(
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+content  = fileread(fullfile(path_to_nonmem_project_folder,'RESULTS','project.xml'));
+content  = strrep(content,'nm:','');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get termination information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ixstart  = strfind(content,'<termination_information>');
+ixend    = strfind(content,'</termination_information>');
+termination_info = {};
+for k=1:length(ixstart),
+    x = content(ixstart(k)+25:ixend(k)-1);
+    x = strrep(x,'<![CDATA[','');
+    x = strtrim(strrep(x,']]>',''));
+    x = explodePCSB(x,char(10));
+    y = '';
+    for k2=1:length(x),
+        y = sprintf('    %s\n',y,strtrim(x{k2}));
+    end
+    y = strrep(y,char([10 10]),char(10));
+    termination_info{k} = sprintf('    %s\n',strtrim(y));
+end
+output.termination_info = termination_info;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Parse objective function
+% In case of concatemated estimation methods only get the last one.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ixstart  = strfind(content,'<final_objective_function>');
+ixend    = strfind(content,'</final_objective_function>');
+if ~isempty(ixstart),
+    OFVvalue = eval(content(ixstart(end)+26:ixend(end)-1));
+else
+    OFVvalue = NaN;
+end
+output.objectivefunction = OFVvalue;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get THETA estimates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ixstart    = strfind(content,'<theta>');
+ixend      = strfind(content,'</theta>');
+if ~isempty(ixstart),
+    theta_text = strtrim(content(ixstart(end)+7:ixend(end)-1));
+    theta_text = strrep(theta_text,'</val>','');
+    theta_text = strrep(theta_text,sprintf('<val name='''),'');
+    theta_text = strrep(theta_text,sprintf('''>'),', ');
+    theta_vec  = eval(['[' theta_text ']']);
+    output.THETA.names = {};
+    output.THETA.values = theta_vec(:,2)';
+    for k=1:length(output.THETA.values),
+        output.THETA.names{k} = sprintf('THETA%d',k);
+    end
+else
+    output.THETA.names = {};
+    output.THETA.values = [];
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get the OMEGA2 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ixstart    = strfind(content,'<omega>');
+ixend      = strfind(content,'</omega>');
+if ~isempty(ixstart),
+    omega_text = strtrim(content(ixstart(end)+7:ixend(end)-1));
+    omega_text = strrep(omega_text,'</row>','#');
+    omega_text = strrep(omega_text,'</col>','');
+    omega_text = strrep(omega_text,'<row rname=','');
+    omega_text = strrep(omega_text,'<col cname=','');
+    omega_text = strrep(omega_text,'''','');
+    omega_text = regexprep(omega_text,'\<[0-9]+>','');
+    terms = explodePCSB(omega_text,'#');
+    terms = terms(1:end-1);
+    OMEGA2 = [];
+    OMEGA2_names  = {};
+    OMEGA2_values  = [];
+    for row=1:length(terms),
+        rowtext = strtrim(terms{row});
+        colterms = explodePCSB(rowtext,char(10));
+        for col=1:length(colterms),
+            OMEGA2(row,col) = eval(colterms{col});
+            OMEGA2(col,row) = eval(colterms{col});
+            OMEGA2_names{end+1} = sprintf('OMEGA2_%d,%d_',row,col);
+            OMEGA2_values(end+1) = eval(colterms{col});
+        end
+    end
+    output.OMEGA2.names = OMEGA2_names;
+    output.OMEGA2.values = OMEGA2_values;
+    output.OMEGA2.matrix = OMEGA2;
+else
+    output.OMEGA2.names = {};
+    output.OMEGA2.values = [];
+    output.OMEGA2.matrix = [];
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get the OMEGAC
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ixstart    = strfind(content,'<omegac>');
+ixend      = strfind(content,'</omegac>');
+if ~isempty(ixstart),
+    omega_text = strtrim(content(ixstart(end)+8:ixend(end)-1));
+    omega_text = strrep(omega_text,'</row>','#');
+    omega_text = strrep(omega_text,'</col>','');
+    omega_text = strrep(omega_text,'<row rname=','');
+    omega_text = strrep(omega_text,'<col cname=','');
+    omega_text = strrep(omega_text,'''','');
+    omega_text = regexprep(omega_text,'\<[0-9]+>','');
+    terms = explodePCSB(omega_text,'#');
+    terms = terms(1:end-1);
+    OMEGA2 = [];
+    OMEGA2_names  = {};
+    OMEGA2_values = [];
+    for row=1:length(terms),
+        rowtext = strtrim(terms{row});
+        colterms = explodePCSB(rowtext,char(10));
+        for col=1:length(colterms),
+            OMEGA2(row,col) = eval(colterms{col});
+            OMEGA2(col,row) = eval(colterms{col});
+            OMEGA2_names{end+1} = sprintf('OMEGAC_%d,%d_',row,col);
+            OMEGA2_values(end+1) = eval(colterms{col});
+        end
+    end
+    output.OMEGAC.names = OMEGA2_names;
+    output.OMEGAC.values = OMEGA2_values;
+    output.OMEGAC.matrix = OMEGA2;
+else
+    output.OMEGAC.names = {};
+    output.OMEGAC.values = [];
+    output.OMEGAC.matrix = [];
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get THETA standard error estimates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ixstart    = strfind(content,'<thetase>');
+ixend      = strfind(content,'</thetase>');
+if ~isempty(ixstart),
+    theta_text = strtrim(content(ixstart(end)+9:ixend(end)-1));
+    theta_text = strrep(theta_text,'</val>','');
+    theta_text = strrep(theta_text,sprintf('<val name='''),'');
+    theta_text = strrep(theta_text,sprintf('''>'),', ');
+    theta_vec  = eval(['[' theta_text ']']);
+    output.THETA.standarderror = theta_vec(:,2)';
+else
+    output.THETA.standarderror = NaN(size(output.THETA.names));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get the OMEGA2 standarderror 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ixstart    = strfind(content,'<omegase>');
+ixend      = strfind(content,'</omegase>');
+if ~isempty(ixstart),
+    omega_text = strtrim(content(ixstart(end)+9:ixend(end)-1));
+    omega_text = strrep(omega_text,'</row>','#');
+    omega_text = strrep(omega_text,'</col>','');
+    omega_text = strrep(omega_text,'<row rname=','');
+    omega_text = strrep(omega_text,'<col cname=','');
+    omega_text = strrep(omega_text,'''','');
+    omega_text = regexprep(omega_text,'\<[0-9]+>','');
+    terms = explodePCSB(omega_text,'#');
+    terms = terms(1:end-1);
+    OMEGA2 = [];
+    OMEGA2_values = [];
+    for row=1:length(terms),
+        rowtext = strtrim(terms{row});
+        colterms = explodePCSB(rowtext,char(10));
+        for col=1:length(colterms),
+            OMEGA2(row,col) = eval(colterms{col});
+            OMEGA2(col,row) = eval(colterms{col});
+            OMEGA2_values(end+1) = eval(colterms{col});
+        end
+    end
+    output.OMEGA2.standarderror = OMEGA2_values;
+    output.OMEGA2.standarderrorMATRIX = OMEGA2;
+else
+    output.OMEGA2.standarderror = NaN(size(output.OMEGA2.names));
+    output.OMEGA2.standarderrorMATRIX = NaN(length(output.OMEGA2.names),length(output.OMEGA2.names));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get the OMEGAC standarderror
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ixstart    = strfind(content,'<omegacse>');
+ixend      = strfind(content,'</omegacse>');
+if ~isempty(ixstart),
+    omega_text = strtrim(content(ixstart(end)+10:ixend(end)-1));
+    omega_text = strrep(omega_text,'</row>','#');
+    omega_text = strrep(omega_text,'</col>','');
+    omega_text = strrep(omega_text,'<row rname=','');
+    omega_text = strrep(omega_text,'<col cname=','');
+    omega_text = strrep(omega_text,'''','');
+    omega_text = regexprep(omega_text,'\<[0-9]+>','');
+    terms = explodePCSB(omega_text,'#');
+    terms = terms(1:end-1);
+    OMEGA2 = [];
+    OMEGA2_values = [];
+    for row=1:length(terms),
+        rowtext = strtrim(terms{row});
+        colterms = explodePCSB(rowtext,char(10));
+        for col=1:length(colterms),
+            OMEGA2(row,col) = eval(colterms{col});
+            OMEGA2(col,row) = eval(colterms{col});
+            OMEGA2_values(end+1) = eval(colterms{col});
+        end
+    end
+    output.OMEGAC.standarderror = OMEGA2_values.*(output.OMEGA2.standarderror~=0);
+    output.OMEGAC.standarderrorMATRIX = OMEGA2.*(output.OMEGA2.standarderrorMATRIX~=0);
+else
+    output.OMEGAC.standarderror = NaN(size(output.OMEGAC.names));
+    output.OMEGAC.standarderrorMATRIX = NaN(length(output.OMEGAC.names),length(output.OMEGAC.names));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get covariance matrix
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ixstart    = strfind(content,'<covariance>');
+ixend      = strfind(content,'</covariance>');
+
+if ~isempty(ixstart) && ~isempty(ixend),
+    cormatrix_text = strtrim(content(ixstart(end)+12:ixend(end)-1));
+    cormatrix_text = strrep(cormatrix_text,'''','');
+    cormatrix_text = strrep(cormatrix_text,'</row>','#');
+    cormatrix_text = strrep(cormatrix_text,'</col>','');
+    cormatrix_text = strrep(cormatrix_text,'<col cname=','');
+    cormatrix_text = strrep(cormatrix_text,'<','');
+    cormatrix_text = strrep(cormatrix_text,'>',' ');
+    cormatrix_text = strrep(cormatrix_text,'(','_');
+    cormatrix_text = strrep(cormatrix_text,')','_');
+    
+    % Get the names of the rows/cols
+    cormatrix_names = regexp(cormatrix_text,'row rname=([A-Z_,0-9]+)','tokens');
+    
+    cormatrix_text = regexprep(cormatrix_text,'row rname=([A-Z_,0-9]+)','');
+    cormatrix_text = regexprep(cormatrix_text,'\<([A-Z_,0-9]+) ','');
+    
+    terms = explodePCSB(cormatrix_text,'#');
+    terms = terms(1:end-1);
+    
+    COV_MATRIX = [];
+    for row=1:length(terms),
+        rowtext = strtrim(terms{row});
+        colterms = explodePCSB(rowtext,char(10));
+        for col=1:length(colterms),
+            value = eval(colterms{col});
+            COV_MATRIX(row,col) = value;
+            COV_MATRIX(col,row) = value;
+        end
+    end
+else
+    COV_MATRIX = [];
+    cormatrix_names = {};
+end
+output.COVARIANCE_MATRIX = COV_MATRIX;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get correlation matrix
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ixstart    = strfind(content,'<correlation>');
+ixend      = strfind(content,'</correlation>');
+
+if ~isempty(ixstart) && ~isempty(ixend),
+    cormatrix_text = strtrim(content(ixstart(end)+13:ixend(end)-1));
+    cormatrix_text = strrep(cormatrix_text,'''','');
+    cormatrix_text = strrep(cormatrix_text,'</row>','#');
+    cormatrix_text = strrep(cormatrix_text,'</col>','');
+    cormatrix_text = strrep(cormatrix_text,'<col cname=','');
+    cormatrix_text = strrep(cormatrix_text,'<','');
+    cormatrix_text = strrep(cormatrix_text,'>',' ');
+    cormatrix_text = strrep(cormatrix_text,'(','_');
+    cormatrix_text = strrep(cormatrix_text,')','_');
+    
+    % Get the names of the rows/cols
+    cormatrix_names = regexp(cormatrix_text,'row rname=([A-Z_,0-9]+)','tokens');
+    
+    cormatrix_text = regexprep(cormatrix_text,'row rname=([A-Z_,0-9]+)','');
+    cormatrix_text = regexprep(cormatrix_text,'\<([A-Z_,0-9]+) ','');
+    
+    terms = explodePCSB(cormatrix_text,'#');
+    terms = terms(1:end-1);
+    
+    CORRELATION_MATRIX = [];
+    for row=1:length(terms),
+        rowtext = strtrim(terms{row});
+        colterms = explodePCSB(rowtext,char(10));
+        for col=1:length(colterms),
+            value = eval(colterms{col});
+            CORRELATION_MATRIX(row,col) = value;
+            CORRELATION_MATRIX(col,row) = value;
+        end
+    end
+else
+    CORRELATION_MATRIX = [];
+    cormatrix_names = {};
+end
+output.CORRELATION_MATRIX = CORRELATION_MATRIX;
+output.COV_COR_MATRIX_NAMES = cormatrix_names;
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/parseProjectHeaderNONMEMSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/parseProjectHeaderNONMEMSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..cd434142cd6ee28a2d55d222fc3fdff7aea28462
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/parseProjectHeaderNONMEMSBPOP.m
@@ -0,0 +1,54 @@
+function [projectinfo] = parseProjectHeaderNONMEMSBPOP(projectPath)
+% parseProjectHeaderNONMEMSBPOP: Parses the project header information from
+% the NONMEM control foile (project.nmctl) and returns it.
+%
+% USAGE:
+% ======
+% projectinfo = parseProjectHeaderNONMEMSBPOP(projectPath)
+%
+% projectPath:   path to the project.nmctl NONMEM project file
+
+% Information:
+% ============
+% Copyright (C) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Check if project.nmctl in project folder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if exist([projectPath '/project.nmctl']),
+    project = fileread([projectPath '/project.nmctl']);
+else
+    error('project.nmctl file could not be found.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get the header
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ixstart = strfind(project,'; ==PROJECT HEADER START===================================================');
+ixend = strfind(project,  '; ==PROJECT HEADER END=====================================================');
+if isempty(ixstart) || isempty(ixend),
+    error('Project header could not be found in project.nmctl file.');
+end
+headertext = strtrim(project(ixstart+75:ixend-1));
+headerterms = explodePCSB(headertext,char(10));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Construct output
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+projectinfo = [];
+for k=1:length(headerterms),
+    eval(['projectinfo.' strrep(strtrim(headerterms{k}(2:end)),'=','=explodePCSB(') ');']);
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/sampleNONMEMpopulationParametersSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/sampleNONMEMpopulationParametersSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..c1bf12bb2dd615a4c8db01ab0a9d55b656e65d7c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/nonmem/auxiliary/sampleNONMEMpopulationParametersSBPOP.m
@@ -0,0 +1,462 @@
+function [ output ] = sampleNONMEMpopulationParametersSBPOP( input, varargin )
+% [DESCRIPTION]
+% This function uses the output of the parseNONMEMresultsSBPOP function.
+% It samples once the distributions to obtain population parameters.
+% Then it splits these up into fixed effects, random effects, residual 
+% error models, covariates. The resulting fixed effect parameters will be
+% in the untransformed domain (not in the MU referencing one).
+%
+% Not everything is handled, but if things are found that can not be handled, 
+% then an error message is shown.
+%
+% [SYNTAX]
+% output = sampleNONMEMpopulationParametersSBPOP( input )
+% output = sampleNONMEMpopulationParametersSBPOP( input, FLAG_SAMPLE )
+% output = sampleNONMEMpopulationParametersSBPOP( input, FLAG_SAMPLE, FLAG_SILENT )
+%
+% [INPUT]
+% input        : output structure from the parseNONMEMresultsSBPOP function
+% FLAG_SAMPLE  : 1=sample population parameters from uncertainty distribution (default case)
+%                0=use estimated population parameters and do not consider uncertainty
+% FLAG_SILENT  : 1=do not output any warnings and messages, only errors 
+%                0=do output any warnings and messages, only errors (default)
+%
+% [OUTPUT]
+% Structure with the following fields:
+%
+% output.path                               : the path provided by the user from which Monolix results have been read
+%
+% output.fixedEffects.names                 : cell-array with names of fixed effect parameters
+% output.fixedEffects.values                : vector with sampled values of fixed effect parameters
+%
+% output.randomEffects.names                : cell-array with names of random effect parameters (same as fixed effect param names)
+% output.randomEffects.values               : vector with sampled values of random effect parameters
+% output.randomEffects.covariancematrix     : covariance matrix of random effects
+% output.randomEffects.transformation       : formula of the transformation
+% output.randomEffects.inv_transformation   : inverse of the formula
+% output.randomEffects.correlationmatrix    : correlation matrix of random effects
+% 
+% output.residualErrorModel.alias           : for each output/residual error model one substructure in the order of the outpt numbering. "alias" is a string with the name of the error model
+% output.residualErrorModel.abcr            : vector with 4 elements for the a,b,c,rho parameters. If undefined then NaN
+% output.residualErrorModel.formula         : formula of the transformation
+% 
+% output.covariates.continuous.parameter               : one substructure per parameter. "parameter" is a string with the parameter name
+% output.covariates.continuous.covariates              : cell-array with the covariates on this parameter
+% output.covariates.continuous.information             : cell-array with covariate transformation in formation (categorical:reference group, continuous:transformation formula and centering value)
+% output.covariates.continuous.information.categories  : vector with numerical categories (only numerical ones are accepted)
+% output.covariates.continuous.information.values      : vector with estimated covariate coefficients for each category (same order). Reference group has 0 value
+%                           
+%
+% [ASSUMPTIONS]
+% 
+% [AUTHOR]
+% Henning Schmidt 
+%
+% [DATE]
+% 03.05.2014
+%
+% [PLATFORM]
+% MATLAB R2013a
+%
+% [KEYWORDS]
+% NONMEM, results, parsing
+% 
+% [TOOLBOXES USED]
+% NONE
+
+% Information:
+% ============
+% Copyright (C) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+FLAG_SAMPLE = 1;
+FLAG_SILENT = 0;
+if nargin == 2,
+    FLAG_SAMPLE = varargin{1};
+elseif nargin == 3,
+    FLAG_SAMPLE = varargin{1};
+    FLAG_SILENT = varargin{2};
+end    
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if information present, otherwise return empty
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isnan(input.objectivefunction.OBJ)
+    output = [];
+    return
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define output structure
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output = [];
+output.type                                 = 'NONMEM';
+output.path                                 = '';
+
+output.fixedEffects.names                   = {};
+output.fixedEffects.values                  = [];   % Vector
+
+output.randomEffects.names                  = {};
+output.randomEffects.values                 = [];   % Vector
+output.randomEffects.covariancematrix       = [];   % Matrix 
+output.randomEffects.transformation          = {};   % cell-array defining the transformation (normal, lognormal, etc.)
+output.randomEffects.inv_transformation      = {};   % cell-array defining the inverse transformation
+
+output.residualErrorModel.alias             = '';   % One substructure per output alias=string
+output.residualErrorModel.abcr              = [];   % Vector with 4 elements (a,b,c,d - parameters in error model)
+output.residualErrorModel.formula           = '';   % Formula of the transformation
+output.residualErrorModel.inv_formula       = '';   % Inverse of the formula if there is a transformation
+output.residualErrorModel.FlagTransf        = 0;    % Flag if there is a transformation or not (t) 0 if there is not, 1 if there is.
+
+output.covariates.continuous.parameter                 = [];   % One substructure per parameter
+output.covariates.continuous.covariates                = {};   % cell array with all covariates
+output.covariates.continuous.values                    = [];   % vector with corresponding values
+output.covariates.continuous.transformation            = {};   % cell-array with covariate transformation: formula and centering value
+
+output.covariates.categorical.parameter                = [];   % One substructure per parameter
+output.covariates.categorical.covariates               = {};   % cell array with all covariates
+output.covariates.categorical.information              = {};   % cell-array with covariate transformation: 
+                                     
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Write the path of the folder with all the results
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output.path = input.path;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Sample ALL parameters from the distribution N-times
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+names      = input.parameters.names;
+values     = input.parameters.values;
+covariance = input.parameters.covariancematrix;
+% Flag to stay (if 1 then stop sampling ... also set to 1 if sampling not feasible (not desired or not possible since no FIM/covariance matrix determined).
+stopSamplingFlag = 0;
+while stopSamplingFlag == 0,
+    if FLAG_SAMPLE,
+        if ~isempty(covariance),
+            samples = mvnrnd(values,covariance);
+        else
+            if ~FLAG_SILENT,
+                disp('The covariance matrix was not determined => No sampling of population parameters from uncertainty distribution.');
+            end
+            samples = values;
+            % In this case we cannot sample another time
+            stopSamplingFlag = 1;
+        end
+    else
+        samples = values;
+        if ~FLAG_SILENT,
+            disp('No sampling of population parameters from uncertainty distributions.');
+        end
+        stopSamplingFlag = 1;
+    end
+
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Determine the random effects 
+    % Names determined by "omega2(" 
+    % Covariances have a commata in them
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    ixo = strmatchSB('omega2(',names);
+    n = names(ixo);
+    ixno = strfind(n,',');
+    no = {};
+    ixouseo = [];
+    for k=1:length(ixno),
+        if isempty(ixno{k}),
+            no{end+1} = n{k};
+            ixouseo(end+1) = ixo(k);
+        end
+    end
+    no = strrep(no,'omega2(','');
+    no = strrep(no,')','');
+    output.randomEffects.names = no;
+    output.randomEffects.values = sqrt(samples(ixouseo));
+
+    % Determine the covariance matrix
+    covariancematrix = diag(samples(ixouseo));
+    ixo = strmatchSB('omega2(',names);
+    n = names(ixo);
+    ixno = strfind(n,',');
+    no = {};
+    ixousec = [];
+    for k=1:length(ixno),
+        if ~isempty(ixno{k}),
+            no{end+1} = n{k};
+            ixousec(end+1) = ixo(k);
+        end
+    end    
+    no = strrep(no,'omega2(','');
+    recovnames = strrep(no,')','');
+    recovvalues = samples(ixousec);
+    % Run through the correlations and update the correlation matrix
+    if ~isempty(recovnames)
+        for k=1:length(recovnames),
+            % Find the two correlated things
+            terms = explodePCSB(recovnames{k});
+            ix1 = strmatchSB(terms{1},output.randomEffects.names,'exact');
+            ix2 = strmatchSB(terms{2},output.randomEffects.names,'exact');
+            % Update matrix
+            covariancematrix(ix1,ix2) = recovvalues(k);
+            covariancematrix(ix2,ix1) = recovvalues(k);
+        end
+    end
+    output.randomEffects.covariancematrix = covariancematrix;
+  
+    % Determine correlation matrix
+    corrmatrix = NaN(size(covariancematrix));
+    for krow=1:length(corrmatrix),
+        for kcol=1:length(corrmatrix),
+            corrmatrix(krow,kcol) = covariancematrix(krow,kcol)/sqrt(covariancematrix(krow,krow)*covariancematrix(kcol,kcol));
+        end
+    end
+    output.randomEffects.correlationmatrix = corrmatrix;
+    
+    % Check if sampled covariance matrix is positive semi-definite
+    % by checking that all eigenvalues are >=0
+    % Only check if stopSamplingFlag==0
+    eigen = eig(output.randomEffects.covariancematrix);
+    xx = find(eigen<0, 1);
+    if isempty(xx),
+        % positive semi-definite => OK, take it and exit loop
+        stopSamplingFlag = 1;
+    else
+        if stopSamplingFlag ==1,
+            % Only warn when no sampling possible
+            if ~FLAG_SILENT,
+                disp('The covariance matrix of the random effects is not positive semi-definite.');
+            end
+        end
+    end
+end
+% Remove omega_... and corr(... from samples and names
+ix = [ixouseo(:)' ixousec(:)'];
+samples(ix) = [];
+names(ix) = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Second determine the fixed effects
+% In the input structure it has been made sure that all names that appear as fixed effects also appear in random effects
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output.fixedEffects.names = output.randomEffects.names;
+% Get the values
+ixfe = [];
+for k=1:length(output.fixedEffects.names),
+    ix = strmatchSB(output.fixedEffects.names{k},names,'exact');
+    output.fixedEffects.values(k) = samples(ix);
+    ixfe = [ixfe ix];
+end
+% Remove fixed effects from samples and names
+samples(ixfe) = [];
+names(ixfe) = [];
+
+% Add the distribution of the random effects to the output
+output.randomEffects.transformation = input.trans_randeffects;
+output.randomEffects.inv_transformation = input.inv_trans_randeffects;
+output.fixedEffects.transformation = input.trans_randeffects;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Third get residual error information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+Noutput = length(input.residualerrormodels);
+removeIX = [];
+for k=1:Noutput,
+    output.residualErrorModel(k).alias = input.residualerrormodels{k};
+    output.residualErrorModel(k).abcr = NaN(1,2);
+    ix = strmatchSB(['error_ADD' num2str(k)],names,'exact'); if ~isempty(ix), output.residualErrorModel(k).abcr(1) = samples(ix); removeIX = [removeIX ix]; end
+    ix = strmatchSB(['error_PROP' num2str(k)],names,'exact'); if ~isempty(ix), output.residualErrorModel(k).abcr(2) = samples(ix); removeIX = [removeIX ix]; end
+end
+% Remove the handled elements
+samples(removeIX) = [];
+names(removeIX) = [];
+
+% Save the formula of the function of the residual error.
+for k = 1:Noutput
+    ix = strmatchSB(output.residualErrorModel(k).alias,'const','exact'); if ~isempty(ix), output.residualErrorModel(k).formula = 'abcr(1).*ones(size(f))'; output.residualErrorModel(k).FlagTransf = 0; end
+    ix = strmatchSB(output.residualErrorModel(k).alias,'prop','exact'); if ~isempty(ix), output.residualErrorModel(k).formula = 'abcr(2).*f'; output.residualErrorModel(k).FlagTransf = 0; end
+    ix = strmatchSB(output.residualErrorModel(k).alias,'comb1','exact'); if ~isempty(ix), output.residualErrorModel(k).formula = 'abcr(1) + abcr(2).*f'; output.residualErrorModel(k).FlagTransf = 0; end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Fourth get covariate information
+% On one hand just the parameter estimates which are defined by "beta(..." which is easy.
+% On the other hand we need to obtain information about the transformation of the covariates (lets see where we can find this)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ix              = strmatchSB('beta_',names);
+covariates      = names(ix);
+covariatevalues = samples(ix);
+% Remove the handled elements
+samples(ix)     = [];
+names(ix)       = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get info of categorical covariates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+categorical_covariates              = [];
+categorical_covariates.parameter    = {};
+categorical_covariates.covariate    = {};
+categorical_covariates.categories   = {};
+categorical_covariates.reference    = {};
+categorical_covariates.value         = {};
+
+for k=1:length(input.PROJECTINFO.BETACATNAMES),
+    if ~isempty(input.PROJECTINFO.BETACATNAMES{k}),
+        bcnk = input.PROJECTINFO.BETACATNAMES{k};
+        bcnk = strrep(bcnk,'beta_','');
+        bcnk = strrep(bcnk,'(',',');
+        bcnk = strrep(bcnk,')','');
+        terms = explodePCSB(bcnk);
+        categories = eval(input.PROJECTINFO.BETACATCATEGORIES{k});
+        reference  = eval(input.PROJECTINFO.BETACATREFERENCE{k});
+        categorical_covariates.parameter{end+1} = terms{1};
+        categorical_covariates.covariate{end+1} = terms{2};
+        categorical_covariates.categories{end+1} = categories;
+        categorical_covariates.reference{end+1} = reference;
+        for k2=1:length(categories),
+            n = strrep(input.PROJECTINFO.BETACATNAMES{k},')',sprintf('_%d)',categories(k2)));
+            if categories(k2) == reference,
+                value = 0;
+            else
+                value = covariatevalues(strmatchSB(n,covariates,'exact'));
+            end
+            categorical_covariates.value{k}(k2) = value;
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get info of continuous covariates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+continuous_covariates = [];
+continuous_covariates.parameter = {};
+continuous_covariates.covariate = {};
+continuous_covariates.formula   = {};
+continuous_covariates.value   = [];
+
+for k=1:length(input.PROJECTINFO.BETACOVNAMES),
+    if ~isempty(input.PROJECTINFO.BETACOVNAMES{k}),
+        bcnk = input.PROJECTINFO.BETACOVNAMES{k};
+        bcnk = strrep(bcnk,'beta_','');
+        bcnk = strrep(bcnk,'(',',');
+        bcnk = strrep(bcnk,')','');
+        terms = explodePCSB(bcnk);
+        continuous_covariates.parameter{end+1}  = terms{1};
+        continuous_covariates.covariate{end+1}  = terms{2};
+        continuous_covariates.formula{end+1}    = input.PROJECTINFO.TRANSCOV{k};
+        continuous_covariates.value(end+1)      = covariatevalues(strmatchSB(input.PROJECTINFO.BETACOVNAMES{k},covariates,'exact'));
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle CONTINUOUS covariates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+continuous = [];
+continuous.parameter = {};
+continuous.covariates = {};
+continuous.values = [];
+continuous.transformation = {};
+empty = 1;
+for k=1:length(continuous_covariates.parameter),
+    if empty,
+        continuous(1).parameter = continuous_covariates.parameter{k};
+        continuous(1).covariates{end+1} = continuous_covariates.covariate{k};
+        continuous(1).values(end+1) = continuous_covariates.value(k);
+        transformation = [];
+        transformation.formula = continuous_covariates.formula{k};
+        transformation.centervalue = 0;
+        continuous(1).transformation{end+1} = transformation;
+        empty = 0;
+    else
+        ix = strmatchSB(continuous_covariates.parameter{k},{continuous.parameter},'exact');
+        if isempty(ix),
+            continuous(end+1).parameter = continuous_covariates.parameter{k};
+            continuous(end).covariates{end+1} = continuous_covariates.covariate{k};
+            continuous(end).values(end+1) = continuous_covariates.value(k);
+            transformation = [];
+            transformation.formula = continuous_covariates.formula{k};
+            transformation.centervalue = 0;
+            continuous(end).transformation{end+1} = transformation;
+        else
+            continuous(ix).covariates{end+1} = continuous_covariates.covariate{k};
+            continuous(ix).values(end+1) = continuous_covariates.value(k);
+            transformation = [];
+            transformation.formula = continuous_covariates.formula{k};
+            transformation.centervalue = 0;
+            continuous(ix).transformation{end+1} = transformation;
+        end
+    end
+end
+output.covariates.continuous = continuous;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle CATEGORICAL covariates
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+categorical = [];
+categorical.parameter = {};
+categorical.covariates = {};
+categorical.information = [];
+empty = 1;
+for k=1:length(categorical_covariates.parameter),
+    if empty,
+        categorical(1).parameter = categorical_covariates.parameter{k};
+        categorical(1).covariates{end+1} = categorical_covariates.covariate{k};
+        categorical(1).information(end+1).categories = categorical_covariates.categories{k};
+        categorical(1).information(end).values = categorical_covariates.value{k};
+        empty = 0;
+    else
+        ix = strmatchSB(categorical_covariates.parameter{k},{categorical.parameter},'exact');
+        if isempty(ix),
+            categorical(end+1).parameter = categorical_covariates.parameter{k};
+            categorical(end).covariates{end+1} = categorical_covariates.covariate{k};
+            categorical(end).information(end+1).categories = categorical_covariates.categories{k};
+            categorical(end).information(end).values = categorical_covariates.value{k};
+        else
+            categorical(ix).covariates{end+1} = categorical_covariates.covariate{k};
+            categorical(ix).information(end+1).categories = categorical_covariates.categories{k};
+            categorical(ix).information(end).values = categorical_covariates.value{k};
+        end
+    end
+end
+output.covariates.categorical = categorical;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if everything was handled
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(names),
+    if ~FLAG_SILENT,
+        disp('Warning: The NONMEM output contained information that are currently not handled.');
+        disp('This could be IOV or other things. Please have a look at the following unhandled names:');
+        for k=1:length(names),
+            fprintf('\t%s\n',names{k})
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Very last thing: transform the parameters into the true domain.
+% For sampling later everything is going to be handled correctly, since 
+% information about covariate transformation and random effect
+% transformation is present ...
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+values  = output.fixedEffects.values;
+trans   = output.fixedEffects.transformation;
+tvalues = [];
+for k=1:length(values),
+    phi = values(k);
+    tvalues(k) = eval(trans{k});
+end
+output.fixedEffects.values = tvalues;
+output.fixedEffects = rmfield(output.fixedEffects,'transformation');
+
+%% DONE!
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/SBPOPboxplot.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/SBPOPboxplot.m
new file mode 100644
index 0000000000000000000000000000000000000000..21a5da11a0298ee1fc14ceda3b58379275c696eb
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/SBPOPboxplot.m
@@ -0,0 +1,157 @@
+function [ h ] = SBPOPboxplot( perc, axisij, varargin )
+% This function is a wrapper for the MATLAB function "boxplot" with identical input arguments
+% (varargin). Additionall, the percentiles argument is to be provided and should contain the values
+% for the percentiles to which the whiskers are to be plotted.
+%
+% The DIFFERENCES are:
+% - The whiskers are plotted to span 95% of the data (2.5 to 97.5 percentiles)
+% - Plotting of outliers is omitted
+% - The following assumptions are made
+%     - If the first argument is a double matrix then do not allow the second 
+%       one to be a group vector.
+%     - If the first argument is a vector, check if the second is a vector and 
+%       if it is, then assume its a group vector
+%
+% [ h ] = SBPOPboxplot( perc, location, varargin )
+%
+% perc:         percentiles to use for whiskers (example: perc = [2.5 97.5])
+% axisij:       =0 if not axisij plot, =1 if axisij plot
+% varargin:     normal boxplot matlab arguments
+
+% Define the percentiles to be used for plotting
+
+
+% Handle first and second input argument and determine the percentiles of the 
+% data to be plotted ... 
+if nargin == 1,
+    plotDataMatrix = varargin{1}; % To be used to determine 95% CI for whiskers
+    % Determine data based percentiles for the 2.5 and 97.5
+    percentiles = prctile(plotDataMatrix,perc);
+else
+    arg1 = varargin{1};
+    arg2 = varargin{2};
+    [n1,m1] = size(arg1);
+    try
+        [n2,m2] = size(arg2);
+    catch
+        n2 = NaN;
+        m2 = NaN;
+    end
+    
+    % Check if arg1 a double matrix
+    if n1>1 && m1>1,
+        % Its a double matrix. Do not allow second to be a double vector
+        if isnumeric(arg2),
+            error('SBPOPboxplot: Group variable not allowed if matrix first input argument.');
+        end
+        plotDataMatrix = arg1;
+        % Determine data based percentiles for the percentile_low and percentile_high
+        percentiles = prctile(plotDataMatrix,perc);
+    elseif n1==1 && m1==1,
+        % Its a scalar double => do not allow
+        error('SBPOPboxplot: Scalar double as first argument is not allowed.');
+    else
+        % arg1 is a vector ... make it column
+        arg1 = arg1(:);
+        
+        if ~isnumeric(arg2),
+            % If second argument not a vector / double then get percentiles from this here
+            percentiles = prctile(arg1,perc)';
+        else
+            % Assume arg2 being group vector and determine percentiles per group
+            allGroup = unique(arg2);
+            percentiles = [];
+            for k=1:length(allGroup),
+                ix = find(arg2==allGroup(k));
+                percentiles = [percentiles prctile(arg1(ix),perc)'];
+            end
+        end
+    end
+end
+
+% Plot the standard boxplot
+h = boxplot(varargin{:},'symbol','');
+
+% Adjust whiskers to the defined percentiles of the data
+
+% CASE 1
+hw = flipud(findobj(gca,'Tag','Whisker'));
+% Replace whiskers with 95% CI values
+for kw = 1:length(hw),
+    % Check if XData or YData
+    XData = get(hw(kw),'XData');
+    if XData(1)~=XData(2),
+        set(hw(kw),'XData',percentiles(:,kw)');
+    else
+        set(hw(kw),'YData',percentiles(:,kw)');
+    end        
+end
+
+% CASE 2 'Upper Whisker'
+hw = flipud(findobj(gca,'Tag','Upper Whisker'));
+% Replace whiskers with 95% CI values
+for kw = 1:length(hw),
+    XData = get(hw(kw),'XData');
+    YData = get(hw(kw),'YData');
+    if XData(1)~=XData(2),
+        XData(2) = max(percentiles(:,kw));
+        set(hw(kw),'XData',XData);
+    else
+        YData(2) = max(percentiles(:,kw));
+        set(hw(kw),'YData',YData);
+    end
+end
+
+% CASE 2 'Upper Adjacent Value'
+hw = flipud(findobj(gca,'Tag','Upper Adjacent Value'));
+% Replace whiskers with 95% CI values
+for kw = 1:length(hw),
+    XData = get(hw(kw),'XData');
+    YData = get(hw(kw),'YData');
+    if XData(1)==XData(2),
+        XData = [1 1]*max(percentiles(:,kw));
+        set(hw(kw),'XData',XData);
+    else
+        YData = [1 1]*max(percentiles(:,kw));
+        set(hw(kw),'YData',YData);
+    end
+end
+
+% CASE 2 'Lower Whisker'
+hw = flipud(findobj(gca,'Tag','Lower Whisker'));
+% Replace whiskers with 95% CI values
+for kw = 1:length(hw),
+    XData = get(hw(kw),'XData');
+    YData = get(hw(kw),'YData');
+    if XData(1)~=XData(2),
+        XData(1) = min(percentiles(:,kw));
+        set(hw(kw),'XData',XData);
+    else
+        YData(1) = min(percentiles(:,kw));
+        set(hw(kw),'YData',YData);
+    end
+end
+
+% CASE 2 'Lower Adjacent Value'
+hw = flipud(findobj(gca,'Tag','Lower Adjacent Value'));
+% Replace whiskers with 95% CI values
+for kw = 1:length(hw),
+    XData = get(hw(kw),'XData');
+    YData = get(hw(kw),'YData');
+    if XData(1)==XData(2),
+        XData = [1 1]*min(percentiles(:,kw));
+        set(hw(kw),'XData',XData);
+    else
+        YData = [1 1]*min(percentiles(:,kw));
+        set(hw(kw),'YData',YData);
+    end
+end
+
+% Plot text about ticks into the figure
+XLim = get(gca,'XLim');
+YLim = get(gca,'YLim');
+if ~axisij,
+    text(XLim(2),YLim(1),sprintf('Boxplot ticks: %g%%,25%%,50%%,75%%,%g%%',perc(1),perc(2)),'FontSize',10,'HorizontalAlign','right','VerticalAlign','bottom');
+else
+    text(XLim(2),YLim(2),sprintf('Boxplot ticks: %g%%,25%%,50%%,75%%,%g%%',perc(1),perc(2)),'FontSize',10,'HorizontalAlign','right','VerticalAlign','bottom');
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/SBPOPplotCovarianceCat.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/SBPOPplotCovarianceCat.m
new file mode 100644
index 0000000000000000000000000000000000000000..2cce909082acaba506be682db394a662ef579757
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/SBPOPplotCovarianceCat.m
@@ -0,0 +1,174 @@
+function [] = SBPOPplotCovarianceCat(data,contNames,catNames,options)
+% [DESCRIPTION]
+% This function plots the covariance relationship between a list of 
+% continuous variables (contNames) and a list of categorical variabels
+% (catNames), passed in "data".  
+%
+% [SYNTAX]
+% [] = SBPOPplotCovarianceCat(data,contNames,catNames)
+% [] = SBPOPplotCovarianceCat(data,contNames,catNames,options)
+%
+% [INPUT]
+% data:         Matlab dataset. Each column corresponds to a variable
+%               and each row to a sample. The columns with the names
+%               defined in "contNames" and "catNames" need to be present in
+%               the dataset. 
+% contNames:    Cell-array with names of continuous variables
+% catNames:     Cell-array with names of categorical variables
+% options:      MATLAB structure with optional arguments
+%
+%                   options.LogFlag:   =1 do log transform the variables,
+%                                      =0 do not transform (default: 0)
+%
+% [OUTPUT]
+% Plot
+%
+% [AUTHOR]
+% Original author: Andy Stein
+% Adaptation to SBPOP: Henning Schmidt
+%
+% [DATE]
+% 8th February 2013
+%
+% [PLATFORM]
+% Windows XP Engine, MATLAB R2009a, MATLAB
+%
+% [KEYWORDS]
+% MATLAB, SBPOP
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+LogFlag = 0;
+try LogFlag = options.LogFlag; catch, end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if dataset contains defined columns
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(contNames),
+    try 
+        data.(contNames{k}); 
+    catch, 
+        error(sprintf('Please check if "%s" is a column in the dataset!',contNames{k}));
+    end
+end
+for k=1:length(catNames),
+    try 
+        data.(catNames{k}); 
+    catch, 
+        error(sprintf('Please check if "%s" is a column in the dataset!',catNames{k}));
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Settings for subaxis
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+Spacing = 0;
+Padding = 0;
+Margin  = .1;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Do the plotting
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ncat = length(catNames);  %rows are the categorical covariates
+ncts = length(contNames);
+for icat=1:ncat    
+    xstr = catNames{icat};
+    x = data.(xstr);
+    
+    % Only plot if x not only NaN
+    if ~isempty(find(isnan(x)==0)),
+        
+        ip=icat;
+        subaxis(ncts+1,ncat,ip,'Spacing',Spacing,'Padding',Padding,'Margin',Margin);
+        
+        xu = unique(x);
+        xu = xu(~isnan(xu));
+        b  = zeros(size(xu));
+        nu = length(xu);
+        for i=1:nu
+            b(i) = sum(x==xu(i));
+        end
+        h = bar(1:nu,b,0.5);
+        set(h,'FaceColor',0.4*[1 1 1])
+        set(gca,'XLim',[0.5 nu+.5]);
+        title(xstr,'Interpreter','none')
+        if icat==1
+            ylabel('#','Interpreter','none');
+        else
+            set(gca,'YTick',[]);
+        end
+        
+        set(gca,'XTick',[]);
+        set(gca,'YLim',[0 length(x)]);
+        
+        for icts=1:ncts
+            ystr = contNames{icts};
+            y = data.(ystr);
+            
+            % Only plot if y not only NaN
+            if ~isempty(find(isnan(y)==0)),
+                if LogFlag==1
+                    y = log(y);
+                    ystr = {'log',ystr};
+                end
+                ip = icat + ncat + (icts-1)*ncat;
+                
+                subaxis(ncts+1,ncat,ip,'Spacing',Spacing,'Padding',Padding,'Margin',Margin);
+                
+                xx = unique(x);
+                xx = xx(~isnan(xx));
+                M  = NaN(length(y),length(xx));
+                for i=1:length(xx)
+                    M(x==xx(i),i) = y(x==xx(i));
+                end
+                OPTIONSbox.NumFlag = 0;
+                OPTIONSbox.BoxColor = 0.4*[1 1 1];
+                OPTIONSbox.BoxWidth = .5;
+                OPTIONSbox.MedianWidth = .7;
+                OPTIONSbox.OutlierColor = 0.4*[1 1 1];
+                OPTIONSbox.OutlierSize  = 5;
+                OPTIONSbox.MedianColor = [0 0 0];
+                plotboxSBPOP(M,1:length(xx),OPTIONSbox);
+                set(gca,'XLim',[.5 length(xx)+.5]);
+                
+                set(gca,'XTick',1:length(xx));
+                if icts<ncts
+                    set(gca,'XTick',[]);
+                else
+                    xxx = unique(x);
+                    xxx = xxx(~isnan(xxx));
+                    set(gca,'XTickLabel',xxx)
+                    xlabel(xstr,'Interpreter','none');
+                end
+                if icat==1
+                    ylabel(ystr,'Interpreter','none');
+                end
+                set(gca,'YTick',[]);
+                if min(y)~=max(y),
+                    set(gca,'YLim',[min(y) max(y)]);
+                else
+                    set(gca,'YLim',[min(y)-1 max(y)+1]);
+                end
+            end
+        end
+        set(gca,'YTick',[]);
+    end
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/SBPOPplotHistogram.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/SBPOPplotHistogram.m
new file mode 100644
index 0000000000000000000000000000000000000000..a4d17971c79fd3c34f636347ddb0d0fb061dab1c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/SBPOPplotHistogram.m
@@ -0,0 +1,255 @@
+function [] = SBPOPplotHistogram(Xdata,varargin)
+% [DESCRIPTION]
+% This function plots histograms of the data provided in X. X can be a vector
+% or a matrix. If a matrix, then histograms are plotted for each column in 
+% separate box-plots. Data can be grouped, resulting in several histograms in the 
+% same plot. The grouping vector needs to have same length as X and consist 
+% of some discrete values. Additionally, standard normal curves can be added,
+% -2,2 range lines also, the number of samples in % outside the -2,2 interval can 
+% be displayed. 
+%
+% [SYNTAX]
+% [] = SBPOPplotHistogram(X)
+% [] = SBPOPplotHistogram(X,options)
+%
+% [INPUT]
+% X:            Vector or Matrix or MATLAB dataset containing the values to plot the 
+%               histograms for (In columns).
+% options:      MATLAB structure with optional arguments
+%
+%                   options.group:    Vector or MATLAB dataset containing discrete information.
+%                                     For each value in it the analysis is grouped and the plots
+%                                     are done in different colors.
+%                   options.groupName: Name of the group variable
+%                   options.Nbins:    Number of bins for the histogram (default: 20)
+%                   options.show2lines: =1: do show the lines at -2 and 2, =0: dont (default: 0)
+%                                     Disabled if groups selected
+%                   options.stdNorm:  =1: show standard normal curve, =0: dont (default: 0)
+%                   options.names:    Cell-array with names of the variables to be plotted.
+%                   options.color:    =1: color, 0: black and white (default: 1)
+%
+% [OUTPUT]
+% Histogram plots
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 15th May 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MATLAB R2009a, MATLAB
+%
+% [KEYWORDS]
+% MATLAB, SBPOP, WRES, histogram, goodness of fit
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% colors
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[colors,lines,dots,bwcolors] = getcolorsSBPOP();
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle varargins
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+options = [];
+if nargin == 1,
+elseif nargin == 2,
+    options = varargin{1};
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle options
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+group = [];
+Nbins = 20;
+show2lines = 0;
+stdNorm = 0;
+names = {};
+color = 1;
+groupName = 'GROUP';
+
+try group = options.group; catch, end
+try Nbins = options.Nbins; catch, end
+try show2lines = options.show2lines; catch, end
+try stdNorm = options.stdNorm; catch, end
+try names = options.names; catch, end
+try color = options.color; catch, end
+try groupName = options.groupName; catch, end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle names
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ischar(names),
+    names = {names};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Convert possible datasets to double
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+Xdata = double(Xdata); 
+group = double(group); 
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Find size of Xdata to determine need for number of subplots
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[nRows,nCols] = size(Xdata);
+% Determine subplot structure
+nTotal = nCols;
+nsubplotCols = ceil(sqrt(nTotal));
+nsubplotRows = ceil(nTotal/nsubplotCols);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Open new Figure
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+figure; clf;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Cycle through all columns and do the plotting
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for kk = 1:nCols,
+    subplot(nsubplotRows, nsubplotCols,kk);
+    
+    XdataColk = Xdata(:,kk);
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Do the plot if group not defined
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    if isempty(group),
+%        NbinsUse = max(Nbins,ceil(Nbins/3*((max(XdataColk)-min(XdataColk)))));
+        NbinsUse = Nbins;
+        [h,x] = hist(XdataColk,NbinsUse);
+        if color == 1,
+            bar(x,h,1,'FaceColor',colors(1,:),'EdgeColor',colors(1,:)); hold on;
+        else
+            bar(x,h,1,'FaceColor',bwcolors(1,:),'EdgeColor',bwcolors(1,:)); hold on;
+        end
+        % Add standard normal curve
+        if stdNorm,
+            maxHIST = max(hist(XdataColk,NbinsUse));
+            XLim = get(gca,'XLim');
+            if XLim(1) > -5,
+                XLim(1) = -5;
+            end
+            if XLim(2) < 5,
+                XLim(2) = 5;
+            end
+            delta = (XLim(2)-XLim(1))/1000;
+            x = [XLim(1):delta:XLim(2)];
+            y = normpdf(x,0,1)/0.4*maxHIST;
+            plot(x,y,'--','Linewidth',2,'Color','black');
+        end
+    else
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        % Do the plot if group is defined
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        % Get unique group values
+        groupall = unique(group);
+        maxHIST = [];
+        % Cycle through all group values
+        for k=1:length(groupall),
+            % Get group value to be handled
+            groupk = groupall(k);
+            % Get all Xdata in this group
+            XdataColkk = XdataColk(group==groupk);
+            % Calculate the histogram
+%             NbinsUse = max(Nbins,ceil(Nbins/3*((max(XdataColkk)-min(XdataColkk)))));
+            NbinsUse = Nbins;            [h,x] = hist(XdataColkk,NbinsUse);
+            % Plot the histogram
+            if color == 1,
+                bar(x,h,1,'FaceColor',colors(k,:),'EdgeColor',colors(k,:)); hold on;
+            else
+                bar(x,h,1,'FaceColor',bwcolors(k,:),'EdgeColor',bwcolors(k,:)); hold on;
+            end                
+            h = findobj(gca,'Type','Patch');
+            if k>1,
+                set(h(1),'FaceAlpha',0.5)
+            end
+            % Determine for std norm curve:
+            maxHIST(end+1) = max(hist(XdataColkk,NbinsUse));
+        end
+        % Add standard normal curve
+        if stdNorm,
+            for k=1:length(groupall),
+                % Add standard normal curve
+                XLim = get(gca,'XLim');
+                if XLim(1) > -5,
+                    XLim(1) = -5;
+                end
+                if XLim(2) < 5,
+                    XLim(2) = 5;
+                end
+                delta = (XLim(2)-XLim(1))/1000;
+                x = [XLim(1):delta:XLim(2)];
+                y = normpdf(x,0,1)/0.4*maxHIST(k);
+                if color == 1,
+                    plot(x,y,'--','Linewidth',2,'Color',colors(k,:));
+                else
+                    plot(x,y,'--','Linewidth',2,'Color',bwcolors(k,:));
+                end
+            end
+        end
+    end
+    
+    % Title etc.
+    name = ['Xdata #' num2str(kk)];
+    if ~isempty(names),
+        try
+            name = names{kk};
+        catch
+        end
+    end        
+    title(['Histogram of ' name],'FontSize',14,'FontWeight','bold','Interpreter','none');
+    xlabel(name,'FontSize',14,'Interpreter','none');
+    ylabel('Number per bin','FontSize',14,'Interpreter','none');
+    set(gca,'FontSize',12) 
+        
+    % -2/2 lines - only if no groups defined
+    if show2lines && isempty(group),
+        YLim = get(gca,'YLim');
+        plot([-2 -2],YLim,'k--');
+        plot([2 2],YLim,'k--');
+        % Get info about % samples outside -2,2 interval and show in plot
+        XLim = get(gca,'XLim');
+        percentXdatakOutside2 = round(length(find(abs(XdataColk) > 2))./length(find(abs(XdataColk) <= 2))*100*10)/10;
+        text(XLim(1)+0.1*(XLim(2)-XLim(1)),0.9*YLim(2),sprintf('Samples outside\n[-2,2] interval:\n%g %%',percentXdatakOutside2),'FontSize',12);
+    end
+
+    % Legend if groups
+    if ~isempty(group),
+        legendtext = {};
+        groupall = unique(group);
+        for k=1:length(groupall),
+            legendtext{end+1} = sprintf('%s: %g',groupName,groupall(k));
+        end
+        legend(legendtext{:},'Location','NorthWest');
+    end
+    
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/SBPOPplotQQ.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/SBPOPplotQQ.m
new file mode 100644
index 0000000000000000000000000000000000000000..516fe5344e3ecb61ab7011e99223446efa5965c5
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/SBPOPplotQQ.m
@@ -0,0 +1,123 @@
+function [] = SBPOPplotQQ(Xdata,varargin)
+% [DESCRIPTION]
+% QQ plot for provided input data.
+%
+% [SYNTAX]
+% [] = SBPOPplotQQ(X)
+% [] = SBPOPplotQQ(X,options)
+%
+% [INPUT]
+% X:            Vector or Matrix or MATLAB dataset containing the values to plot the 
+%               QQplot for (In columns).
+% options:      MATLAB structure with optional arguments
+%
+%                   options.names:    Cell-array with names of the variables to be plotted.
+%
+% [OUTPUT]
+% QQ plot
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 15th May 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MATLAB R2009a, MATLAB
+%
+% [KEYWORDS]
+% MATLAB, SBPOP, WRES, histogram, goodness of fit
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+ 
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle varargins
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+options = [];
+if nargin == 1,
+elseif nargin == 2,
+    options = varargin{1};
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle options
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+names = {};
+try names = options.names; catch, end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle names
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ischar(names),
+    names = {names};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Convert possible datasets to double
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+Xdata = double(Xdata); 
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Find size of Xdata to determine need for number of subplots
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[nRows,nCols] = size(Xdata);
+% Determine subplot structure
+nTotal = nCols;
+nsubplotCols = ceil(sqrt(nTotal));
+nsubplotRows = ceil(nTotal/nsubplotCols);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Open new Figure
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+figure; clf;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Cycle through all columns and do the plotting
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for kk = 1:nCols,
+    subplot(nsubplotRows, nsubplotCols,kk);
+    
+    XdataColk = Xdata(:,kk); 
+    % Do the plot 
+    qqplot(XdataColk);
+
+    % Title etc.
+    name = ['Xdata #' num2str(kk)];
+    if ~isempty(names),
+        try
+            name = names{kk};
+        catch
+        end
+    end
+    
+    title(['QQplot of ' name],'FontSize',14,'FontWeight','bold','Interpreter','none');
+    xlabel('Standard Normal Quantiles','FontSize',14,'Interpreter','none');
+    ylabel(['Quantiles of ' name],'FontSize',14,'Interpreter','none');
+    set(gca,'FontSize',12)
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/SBPOPplotXY.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/SBPOPplotXY.m
new file mode 100644
index 0000000000000000000000000000000000000000..9dc2965e53485b1bf15858ac3a125daaf268eff9
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/SBPOPplotXY.m
@@ -0,0 +1,471 @@
+function [] = SBPOPplotXY(data,nameX,nameY,options)
+% [DESCRIPTION]
+% This function plots pairwise Ydata vs. Xdata. Several optional settings
+% are possible (see below)
+%
+% [SYNTAX]
+% [] = SBPOPplotXY(data,nameX,nameY)
+% [] = SBPOPplotXY(data,nameX,nameY,options)
+%
+% [INPUT]
+% data:         Matlab dataset
+% nameX:        Column name in dataset to plot on X axis
+% nameY:        Cell-array with column names in dataset to plot on Y axis (if more than one name, then do subplots)
+% options:      Structure with optional settings as follows:
+%   options.xlabelText          = String with xlabel text. Default: nameX
+%   options.ylabelText          = Cell-array with names of ylabels instead of nameY
+%   options.nameColorGroup      = Column name in dataset for coloring a certain group differently
+%   options.logX                = 0 if lin, 1 if log X axis (default: 0)
+%   options.logY                = 0 if lin, 1 if log Y axis (default: 0)
+%   options.linetype            = String with MATLAB linetype (default: '.')
+%   options.linecolor           = Color for lines (default: [0.6 0.6 0.6])
+%   options.showmarkers         = 1 shows different linestyles with markers, =0 uses linstyle setting
+%   options.markersize          = numeric value for markersizes (default: 10)
+%   options.linecolorsCustom    = Matrix with 3 comlumns and arbitrary rows. Defines custom color settings to use for color grouping
+%   options.linetypesCustom     = Cell-array with linestyle strings (e.g.: {'x','-.','--'}). If defined it overrides the standard lines from getcolorsSBPOP (only active if color group selected)
+%                                 Only active if "options.showmarkers=1".
+%   options.linewidth           = Numeric value 1-5 (default: 1)
+%   options.sameaxes            = If 0 (default) subplot axes will be scaled to best fit the data, if 1 all axes will have same scaling
+%   options.showgrid            = 0: no grid, 1: grid (no minor grid lines) (default: 1)
+%   options.colortitlebar       = Vector with three values between 0 and 1 to set he titlebar color (default: [1 1 0.8])
+%   options.heighttitlebar      = Height of the titlebar in fraction of subplot (default: 0.04)
+%   options.showtitlebar        = 0: do not show titlebar, 1: show titlebar (default)
+%   options.showmedian           = 0 (default): do not show a median line per group, 1: do show it
+%   options.NbinsMedian          = value between 0 and 100% defining the range of data to take into account (default: 15)
+%   options.showregressionline  = 1: shwows a linear regression line, 0 does not (default)
+%   options.showslope1line      = 1: shows a slope 1 line, 0 (default) does not
+%   options.slope1linecolor     = color of slope1line (default: [0.4 0.4 0.4]) 
+%   options.slope1linestyle     = style of slope1line (default: '--')
+%   options.squareaxes          = sets X and Y limits to same values 
+%   options.showzeroLines       = 1: shows lines at 0X and 0Y, 0 (default) does not   
+%   options.zeroLinescolor      = color of zero lines (default: [0.4 0.4 0.4])  
+%   options.zeroLinesstyle      = style of zero lines (default: '--'))  
+%   options.showlegend          = 0: do not show a legend, 1 (default): show a legend for the color grouping
+%   options.labeltextsize       = Fontsize for x and y labels (default: 10)
+%   options.maxlegendentries    = If more elements in colorgroup then do not show legend (becomes messy). Default: 10
+%   options.ticklabeltextsize   = Fontsize for axes number (default: 10)
+%   options.legendtextsize      = Fontsize for legend (default: 10)
+%   options.nrows               = Number of rows per subplot (default: all groups in one figure)
+%   options.ncols               = Number of columns per subplot (default: all groups in one figure)
+%   options.ylabelfirstonly     = 1: show the ylabel only for first subplot in figure, 0: show for all first in row subplots
+%   options.nameText            = Column name in dataset (text in column) to display next to datapoints
+%   options.textFontsize        = Fontsize for additional text (default: 10)
+%   options.filename            = Filename for PS (windows) or PDF (unix) output
+%   options.axescolor           = Sets the color of axes and grid (default: [0.5 0.5 0.5])
+%   options.windowcolor         = color definition for outside frame of window (default: [1 1 1])
+%
+% [OUTPUT]
+% Figure with Y vs. X plots
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 15th May 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MATLAB R2009a, MATLAB
+%
+% [KEYWORDS]
+% XY plot
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+ 
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check inputs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ischar(nameY),
+    nameY = {nameY};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get default colors and linestyles
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[colorsDefault,notused,linesDefault] = getcolorsSBPOP();
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get optional variables and set defaults if undefined
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try xlabelText          = options.xlabelText;               catch, xlabelText           = nameX;            end; %#ok<*CTCH>
+try ylabelText          = options.ylabelText;               catch, ylabelText           = nameY;            end;
+try nameColorGroup      = options.nameColorGroup;           catch, nameColorGroup       = '';               end; % also used for coloring
+try logX                = options.logX;                     catch, logX                 = 0;                end;
+try logY                = options.logY;                     catch, logY                 = 0;                end;
+try linetype            = options.linetype;                 catch, linetype             = '.';              end; 
+try linecolor           = options.linecolor;                catch, linecolor            = [0.6 0.6 0.6];    end;
+try showmarkers         = options.showmarkers;              catch, showmarkers          = 0;                end;
+try markersize          = options.markersize;               catch, markersize          = 20;                end;
+try linecolorsCustom    = options.linecolorsCustom;         catch, linecolorsCustom     = colorsDefault;    end;
+try linetypesCustom     = options.linetypesCustom;          catch, linetypesCustom      = linesDefault;     end;
+try linewidth           = options.linewidth;                catch, linewidth            = 1;                end;
+try sameaxes            = options.sameaxes;                 catch, sameaxes             = 0;                end;
+try showgrid            = options.showgrid;                 catch, showgrid             = 1;                end;
+try colortitlebar       = options.colortitlebar;            catch, colortitlebar        = [1 1 0.8];        end;
+try heighttitlebar      = options.heighttitlebar;           catch, heighttitlebar       = 0.04;             end;
+try showtitlebar        = options.showtitlebar;             catch, showtitlebar         = 1;                end;
+try showmedian           = options.showmedian;                catch, showmedian            = 0;                end;
+try NbinsMedian          = options.NbinsMedian;               catch, NbinsMedian           = 15;               end;
+try showregressionline  = options.showregressionline;       catch, showregressionline   = 0;                end;
+try showlegend          = options.showlegend;               catch, showlegend           = 1;                end;
+try labeltextsize       = options.labeltextsize;            catch, labeltextsize        = 10;               end;
+try ticklabeltextsize   = options.ticklabeltextsize;        catch, ticklabeltextsize    = 10;               end;
+try legendtextsize      = options.legendtextsize;           catch, legendtextsize       = 10;               end;
+try nrows               = options.nrows;                    catch, nrows                = NaN;              end;
+try ncols               = options.ncols;                    catch, ncols                = NaN;              end;
+try maxlegendentries    = options.maxlegendentries;         catch, maxlegendentries     = 15;               end;
+try nameText            = options.nameText;                 catch, nameText             = '';               end;
+try textFontsize        = options.textFontsize;             catch, textFontsize         = 10;               end;
+try axescolor           = options.axescolor;                catch, axescolor            = 0.5*[1 1 1];      end;
+try windowcolor         = options.windowcolor;              catch, windowcolor          = 1*[1 1 1];        end;
+try showslope1line      = options.showslope1line;           catch, showslope1line       = 0;                end;
+try slope1linecolor     = options.slope1linecolor;          catch, slope1linecolor      = 0.4*[1 1 1];      end;
+try slope1linestyle     = options.slope1linestyle;          catch, slope1linestyle      = '--';             end;
+try squareaxes          = options.squareaxes;               catch, squareaxes           = 0;                end;
+try showzeroLines       = options.showzeroLines;            catch, showzeroLines        = 0;                end;
+try zeroLinescolor      = options.zeroLinescolor;           catch, zeroLinescolor       = 0.4*[1 1 1];      end;
+try zeroLinesstyle      = options.zeroLinesstyle;           catch, zeroLinesstyle       = '--';             end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle nameY as char def
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ischar(nameY),
+    nameY = {nameY};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% If logX / logY than remove negative X, Y values
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if logX,
+    % Remove entries in data with negative X values
+    data(data.(nameX)<=0,:) = [];
+end
+if logY,
+    % Remove entries in data with negative Y values
+    for k=1:length(nameY),
+        data(data.(nameY{k})<=0,:) = [];
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Other options
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ylabelfirstonly = 0;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Settings for making plots nicer when same axes are chosen
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if sameaxes,
+    SpacingHoriz = 0.05;
+    SpacingVert  = 0.05;
+    Padding      = 0.0;
+    Margin       = 0.1;
+else
+    SpacingHoriz = 0.05;
+    SpacingVert  = 0.05;
+    Padding      = 0.0;
+    Margin       = 0.1;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Format the data to match the grouping
+% Each nameY is one element in the group
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get plot data alone
+dataPlot            = dataset();
+for k=1:length(nameY),
+    dataPlotk = dataset();
+    dataPlotk.X          = data.(nameX);
+    dataPlotk.Y          = data.(nameY{k});
+    if ~isempty(nameText),
+        dataPlotk.(nameText) = data.(nameText);
+    end
+    % No group name definition - it is via Yname definition
+    dataPlotk.group  = k*ones(length(dataPlotk),1);
+    % Dont do subgrouping
+    dataPlotk.subgroup = ones(length(dataPlotk),1);
+    % Handle color group
+    if ~isempty(nameColorGroup),
+        dataPlotk.colorgroup = data.(nameColorGroup);
+        dataPlotk.color      = -1*ones(length(dataPlotk),1);
+        allGROUPcolor       = unique(dataPlotk.colorgroup);
+        for k=1:length(allGROUPcolor),
+            dataPlotk.color(dataPlotk.colorgroup == allGROUPcolor(k)) = k;
+        end
+    else
+        % colorgroup same as subgroup
+        dataPlotk.colorgroup = -1*ones(length(dataPlotk),1);
+        dataPlotk.color      = -1*ones(length(dataPlotk),1);
+    end
+    dataPlot = [dataPlot; dataPlotk];
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine the x and y axes ranges if sameaxes selected and
+% adjust the maxY part of the axes settings to allow for title bar
+% Goal is to increase the range of minY to maxY by a fraction of
+% heighttitlebar
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if sameaxes,
+	minX = min(dataPlot.X);
+	maxX = max(dataPlot.X);
+    minY = min(dataPlot.Y);
+    maxY = max(dataPlot.Y);
+    % Adjust maxY for titlebar
+    if logY==1,
+        rangenew =  1/(1-heighttitlebar-0.01)*(log10(maxY)-log10(minY));
+        maxY     = 10.^(log10(minY) + rangenew);
+    else
+        rangenew =  1/(1-heighttitlebar-0.01)*(maxY-minY);
+        maxY     = minY + rangenew;
+    end
+    % handle squareaxes
+    if squareaxes,
+        minX = min(minX,minY);
+        minY = minX;
+        maxX = max(maxX,maxY);
+        maxY = maxX;        
+    end
+    % Define axes limits
+    sameAxesLimits = [minX maxX minY maxY];
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get different group elements - for each subplot
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+allGROUP = unique(dataPlot.group);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get number of possible elements in sub group
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+allGROUPsub = unique(dataPlot.subgroup);    
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get number of possible elements in color group
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+allGROUPcolor = unique(dataPlot.colorgroup);    
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine number of subplot rows/cols per figure
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+nAllGroups = length(allGROUP);
+if isnan(ncols) || isnan(nrows),
+    ncols = ceil(sqrt(nAllGroups));
+    nrows = ceil(nAllGroups/ncols);
+end
+nSubplots = ncols*nrows;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine number of figures needed for the plotting
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+nFigures = ceil(nAllGroups/nSubplots);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Plot the data
+% Plot moving median line if desired
+% moving median is done in each subplot for data within the same color group
+% Subgroup is not considered
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(allGROUP),
+
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Handle multiple figures and subplots
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    
+    plotFigure  = ceil(k/nSubplots);
+    plotSubplot = mod(k-1,nSubplots)+1;  
+
+    % Clear figure if first subplot going to be plotted and set windowcolor
+    if plotSubplot==1, 
+        hfig = figure(); 
+        set(gcf,'Color',windowcolor);
+    else
+        figure(hfig); 
+    end
+    % Choose subplot
+    subaxis(nrows,ncols,plotSubplot,'SpacingVert',SpacingVert,'SpacingHoriz',SpacingHoriz,'Padding',Padding,'Margin',Margin);
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Get group data for each subplot
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    
+    datak = dataPlot(dataPlot.group==allGROUP(k),:);
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Plot single plot using general auxiliary function
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    options.titleText = sprintf('%s vs %s',nameY{k},nameX);
+    if sameaxes,
+        options.axesLimits = sameAxesLimits;
+    else
+        minX = min(datak.X);
+        maxX = max(datak.X);
+        minY = min(datak.Y);
+        maxY = max(datak.Y);
+        % handle squareaxes
+        if squareaxes,
+            minX = min(minX,minY);
+            minY = minX;
+            maxX = max(maxX,maxY);
+            maxY = maxX;     
+        end
+        % Adjust maxY for titlebar
+        if logY==1,
+            rangenew =  1/(1-heighttitlebar-0.01)*(log10(maxY)-log10(minY));
+            maxY     = 10.^(log10(minY) + rangenew);
+        else
+            rangenew =  1/(1-heighttitlebar-0.01)*(maxY-minY);
+            maxY     = minY + rangenew;
+        end
+        options.axesLimits = [minX maxX minY maxY];
+    end
+    options.linetype            = linetype;
+    options.markersize          = markersize;
+    options.linetypesCustom     = linetypesCustom;
+    options.heighttitlebar      = heighttitlebar;
+    options.NbinsMedian         = NbinsMedian;
+    options.sameaxes            = sameaxes;
+    options.axescolor           = axescolor;
+    plotgeneralSBPOP(datak,'X','Y',options);     
+ 
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Handle x labels
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    
+    if plotFigure < nFigures,
+        % All subplots used => xlabel for the last ncols subplots
+        if plotSubplot > nSubplots-ncols,
+            xlabel(xlabelText,'FontUnits','points','FontSize',labeltextsize,'Interpreter','none');
+        end
+    else
+        % Figure only partially filled with subplots - only labels for
+        % the last ncols subplots
+        if k > nAllGroups-ncols,
+            xlabel(xlabelText,'FontUnits','points','FontSize',labeltextsize,'Interpreter','none');
+        end
+    end
+        
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Handle y labels
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    
+    ylabel(ylabelText{k},'FontUnits','points','FontSize',labeltextsize,'Interpreter','none');
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Handle legend - simplistic one
+    % Only do so for color group and median plots
+    % Only show legend if less than maxlegendentries
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    
+    if showlegend && plotSubplot==1 && length(allGROUPcolor)<=maxlegendentries,
+        legendText = {};
+        legendColor = {};
+        % Check if color group chosen
+        if allGROUPcolor(1) ~= -1,
+            for kleg=1:length(allGROUPcolor),
+                % Get text part
+                legendText{kleg} = sprintf('%s=%g',nameColorGroup,allGROUPcolor(kleg));
+                % Get color part
+                legendColor{kleg} = linecolorsCustom(mod(kleg-1,length(linecolorsCustom))+1,:);
+                % Get marker part
+                if showmarkers,
+                    legendText{kleg} = sprintf('%s %s',linetypesCustom{   mod(kleg-1,length(linetypesCustom))+1},legendText{kleg});
+                end
+            end
+        end
+        % Check if moving median lines are shown
+        if showmedian,
+            legendText{end+1} = 'Binned Median'; %#ok<*AGROW>
+            legendColor{end+1} = [0 0 0];
+        end
+        % Check if regression lines are shown
+        if showregressionline,
+            legendText{end+1} = 'Regression lines'; %#ok<*AGROW>
+            legendColor{end+1} = [0 0 0];
+        end
+        
+        % Determine y locations
+        nlegend = length(legendText);
+        YLim = get(gca,'YLim');
+        XLim = get(gca,'XLim');
+        
+        if logY==1,
+            textY = 10.^(log10(YLim(1))+((maxlegendentries:-1:1)/(maxlegendentries+1)-heighttitlebar)*(log10(YLim(2))-log10(YLim(1))));
+        else
+            textY = YLim(1)+((maxlegendentries:-1:1)/(maxlegendentries+1)-heighttitlebar)*(YLim(2)-YLim(1));
+        end
+        if logX==1,
+            textX = 10.^(log10(XLim(1))+0.02*(log10(XLim(2))-log10(XLim(1))));
+        else
+            textX = XLim(1)+0.02*(XLim(2)-XLim(1));
+        end
+        for klegend=1:nlegend,
+            text(textX,textY(klegend),legendText{klegend},'Color',legendColor{klegend},'FontWeight','bold','FontUnits','points','FontSize',legendtextsize,'HorizontalAlignment','Left','Interpreter','none');
+        end
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Handle showslope1line
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    
+    if showslope1line,
+        XLim = get(gca,'XLim');
+        YLim = get(gca,'YLim');
+        % Adjust maxY for titlebar
+        maxY = YLim(2);
+        minY = YLim(1);
+        if logY==1,
+            rangenew =  (1-heighttitlebar)*(log10(maxY)-log10(minY));
+            maxY     = 10.^(log10(minY) + rangenew);
+        else
+            rangenew =  (1-heighttitlebar)*(maxY-minY);
+            maxY     = minY + rangenew;
+        end         
+        plot([min(XLim(1),YLim(1)) min(max(XLim(2),maxY),maxY)], [min(XLim(1),YLim(1)) min(max(XLim(2),maxY),maxY)],slope1linestyle,'Color',slope1linecolor,'LineWidth',2);
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Handle showzeroLines
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+
+    if showzeroLines,
+        XLim = get(gca,'XLim');
+        YLim = get(gca,'YLim');
+        % Adjust maxY for titlebar
+        maxY = YLim(2);
+        minY = YLim(1);
+        if logY==1,
+            rangenew =  (1-heighttitlebar)*(log10(maxY)-log10(minY));
+            maxY     = 10.^(log10(minY) + rangenew);
+        else
+            rangenew =  (1-heighttitlebar)*(maxY-minY);
+            maxY     = minY + rangenew;
+        end 
+        plot([0 0],[minY maxY],zeroLinesstyle,'Color',zeroLinescolor,'LineWidth',1)
+        plot(XLim,[0 0],zeroLinesstyle,'Color',zeroLinescolor,'LineWidth',1)
+    end
+    
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/SBPOPplotfacetgrid.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/SBPOPplotfacetgrid.m
new file mode 100644
index 0000000000000000000000000000000000000000..3f3bcd035d8869154251f94cf9358d0289c69b24
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/SBPOPplotfacetgrid.m
@@ -0,0 +1,533 @@
+function [] = SBPOPplotfacetgrid(data,nameX,nameY,nameGroupX,nameGroupY,options)
+% [DESCRIPTION]
+% This function plots a matrix version of a trellis plot.
+%
+% [SYNTAX]
+% [] = SBPOPplotfacetgrid(data,nameX,nameY,nameGroupX,nameGroupY)
+% [] = SBPOPplotfacetgrid(data,nameX,nameY,nameGroupX,nameGroupY,options)
+%
+% [INPUT]
+% data:         Matlab dataset
+% nameX:        Column name in dataset to plot on X axis
+% nameY:        Column name in dataset to plot on Y axis
+% nameGroupX:   Column name in dataset to use as group variable for each column. 
+% nameGroupY:   Column name in dataset to use as group variable for each row. 
+% options:      Structure with optional settings as follows:
+%   options.xlabelText          = String with xlabel text. Default: nameX
+%   options.ylabelText          = Cell-array with as many entries as groups in nameGroupY
+%   options.nameSubGroup        = Column name in dataset for subgrouping within a group/subplot (nicer line drawing and used for moving median line);
+%   options.nameColorGroup      = Column name in dataset for coloring a certain group differently
+%   options.logX                = 0 if lin, 1 if log X axis (default: 0)
+%   options.logY                = 0 or 1, alternatively a vector with as many 0 or 1 as elements in nameGroupY - allows to set axes differentlty for different nameGroupY elements
+%   options.linetype            = String with MATLAB linetype (default: '.-')
+%   options.linecolor           = Color for lines (default: [0.2 0.2 0.2])
+%   options.showmarkers         = 1 shows different linestyles with markers, =0 uses linstyle setting
+%   options.markersize          = numeric value for markersizes (default: 10)
+%   options.linecolorsCustom    = Matrix with 3 comlumns and arbitrary rows. Defines custom color settings to use for color grouping
+%   options.linetypesCustom     = Cell-array with linestyle strings (e.g.: {'x','-.','--'}). If defined it overrides the standard lines from getcolorsSBPOP (only active if color group selected)
+%                                 Only active if "options.showmarkers=1".
+%   options.linewidth           = Numeric value 1-5 (default: 1)
+%   options.sameaxes            = If 0 (default) all subplot axes will be scaled to best fit the data, if 1 all axes will have same scaling 
+%                                 All rows will always be on same Y axes, as will be all columns on same X axes
+%   options.showgrid            = 0: no grid, 1: grid (no minor grid lines) (default: 1)
+%   options.colortitlebar       = Vector with three values between 0 and 1 to set he titlebar color (default: [1 1 0.8])
+%   options.heighttitlebarX     = Height of the titlebar on top in fraction of subplot (default: determined automatically)
+%   options.widthtitlebarY      = Width of the titlebar on the right in fraction of subplot (default: determined automatically)
+%   options.showmedian           = 0 (default): do not show a moving median line per group, 1: do show it
+%   options.showmean            = 0 (default): do not show a moving mean line per group, 1: do show it
+%   options.NbinsMedian          = value between 0 and 100 defining the range of data to take into account (default: 15)
+%   options.showlegend          = 0: do not show a legend, 1 (default): show a legend for the color grouping
+%   options.labeltextsize       = Fontsize for x and y labels (default: 10)
+%   options.maxlegendentries    = If more elements in colorgroup then do not show legend (becomes messy). Default: 10
+%   options.ticklabeltextsize   = Fontsize for axes number (default: 10)
+%   options.legendtextsize      = Fontsize for legend (default: 10)
+%   options.nameText            = Column name in dataset (text in column) to display next to datapoints
+%   options.textFontsize        = Fontsize for additional text (default: 10)
+%   options.axescolor           = Sets the color of axes and grid (default: [0.2 0.2 0.2])
+%   options.windowcolor         = color definition for outside frame of window (default: [1 1 1])
+%   options.titlefontsize       = Fontsize for title bars (default: 8)
+% 
+% [OUTPUT]
+% This function creates a new figure. 
+%
+% [ASSUMPTIONS]
+% Data for X and Y axes and all groups needs to be numeric. 
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 09th February 2013
+%
+% [TOOLBOXES USED]
+% Statistics Toolbox
+ 
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get default colors and linestyles
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[colorsDefault,linesDefault] = getcolorsSBPOP();
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get optional variables and set defaults if undefined
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try options             = options;                          catch, options              = [];               end;
+try xlabelText          = options.xlabelText;               catch, xlabelText           = nameX;            end; %#ok<*CTCH>
+try ylabelText          = options.ylabelText;               catch, ylabelText           = NaN;              end; % handled later
+try nameSubGroup        = options.nameSubGroup;             catch, nameSubGroup         = '';               end;
+try nameColorGroup      = options.nameColorGroup;           catch, nameColorGroup       = '';               end;
+try logX                = options.logX;                     catch, logX                 = 0;                end;
+try logY                = options.logY;                     catch, logY                 = 0;                end; % Can be vector
+try linetype            = options.linetype;                 catch, linetype             = '.-';             end; %#ok<*NASGU>
+try linecolor           = options.linecolor;                catch, linecolor            = [0.2 0.2 0.2];    end;
+try showmarkers         = options.showmarkers;              catch, showmarkers          = 0;                end;
+try markersize          = options.markersize;               catch, markersize           = 10;               end;
+try linecolorsCustom    = options.linecolorsCustom;         catch, linecolorsCustom     = colorsDefault;    end;
+try linetypesCustom     = options.linetypesCustom;          catch, linetypesCustom      = linesDefault;     end;
+try linewidth           = options.linewidth;                catch, linewidth            = 1;                end;
+try sameaxes            = options.sameaxes;                 catch, sameaxes             = 1;                end;
+try showgrid            = options.showgrid;                 catch, showgrid             = 1;                end;
+try colortitlebar       = options.colortitlebar;            catch, colortitlebar        = [1 1 0.8];        end;
+try heighttitlebarX     = options.heighttitlebarX;          catch, heighttitlebarX      = NaN;              end;
+try widthtitlebarY      = options.widthtitlebarY;           catch, widthtitlebarY       = NaN;              end;
+try showmedian          = options.showmedian;               catch, showmedian           = 0;                end;
+try showmean            = options.showmean;                 catch, showmean             = 0;                end;
+try NbinsMedian         = options.NbinsMedian;              catch, NbinsMedian           = 15;              end;
+try showlegend          = options.showlegend;               catch, showlegend           = 1;                end;
+try labeltextsize       = options.labeltextsize;            catch, labeltextsize        = 10;               end;
+try ticklabeltextsize   = options.ticklabeltextsize;        catch, ticklabeltextsize    = 10;               end;
+try legendtextsize      = options.legendtextsize;           catch, legendtextsize       = 10;               end;
+try maxlegendentries    = options.maxlegendentries;         catch, maxlegendentries     = 10;               end;
+try nameText            = options.nameText;                 catch, nameText             = '';               end;
+try textFontsize        = options.textFontsize;             catch, textFontsize         = 10;               end;
+try axescolor           = options.axescolor;                catch, axescolor            = 0.2*[1 1 1];      end;
+try windowcolor         = options.windowcolor;              catch, windowcolor          = 1*[1 1 1];        end;
+try titlefontsize       = options.titlefontsize;            catch, titlefontsize        = 8;               end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Settings for making plots nicer when same axes are chosen
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SpacingHoriz = 0.002;
+SpacingVert  = 0.003;
+Padding      = 0;
+Margin       = 0.1;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get group information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(nameGroupX),
+    allGroupX = -1;
+else
+    allGroupX = unique(data.(nameGroupX));
+end
+if isempty(nameGroupY),
+    allGroupY = -1;
+else
+    allGroupY = unique(data.(nameGroupY));
+end
+if ~isempty(nameColorGroup),
+    allGROUPcolor   = unique(data.(nameColorGroup));
+    data.colorgroup = data.(nameColorGroup);
+else
+    allGROUPcolor   = -1;
+    data.colorgroup = -1*ones(length(data),1);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Adjust logY settings
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if length(logY)==1,
+    logY = logY*ones(1,length(allGroupY));
+elseif length(logY)~=length(allGroupY),
+    error('options.logY needs to be 0 or 1, or a vector with 0 or 1 of same length as number of Y groups.');
+end
+% If sameaxes, use first setting of logY
+if sameaxes,
+    logY = logY(1)*ones(1,length(allGroupY));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define ylabeltext if not given as option
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~iscell(ylabelText),
+    if isnan(ylabelText),
+        ylabelText = {};
+        for k=1:length(allGroupY),
+            ylabelText{k} = sprintf('%s (%s=%g)',nameY,nameGroupY,allGroupY(k));
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define subplot information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ncols       = length(allGroupX);
+nrows       = length(allGroupY);
+nSubplots   = nrows*ncols;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle title bar sizes
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isnan(heighttitlebarX),
+    heighttitlebarX = 0.04+0.02*nrows;
+end
+if isnan(widthtitlebarY),
+    widthtitlebarY = 3/4*heighttitlebarX/nrows*ncols;
+    if widthtitlebarY > 0.5,
+        widthtitlebarY = 0.5;
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run through the group X and Y, define subplot settings, color settings
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dataPlot            = dataset();
+for kX=1:length(allGroupX),
+    if ~isempty(nameGroupX),
+        dataX = data(data.(nameGroupX)==allGroupX(kX),:);
+    else
+        dataX = data;
+    end
+    
+    for kY=1:length(allGroupY),
+        if ~isempty(nameGroupY),
+            dataXY = dataX(dataX.(nameGroupY)==allGroupY(kY),:);
+        else
+            dataXY = dataX;
+        end
+        
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        % If log X or Y, remove <=0 data from respective parts
+        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        if logX == 1,
+            dataXY(dataXY.(nameX)<=0,:) = [];
+        end
+        if logY(kY) == 1,
+            dataXY(dataXY.(nameY)<=0,:) = [];
+        end
+        
+        for kC=1:length(allGROUPcolor),
+            dataXYC = dataXY(dataXY.colorgroup==allGROUPcolor(kC),:);
+            
+            if ~isempty(dataXYC),
+                
+                datatemp = dataset();
+                datatemp.(nameX)        = dataXYC.(nameX);
+                datatemp.(nameY)        = dataXYC.(nameY);
+                datatemp.groupX         = allGroupX(kX)*ones(length(datatemp),1);
+                datatemp.groupY         = allGroupY(kY)*ones(length(datatemp),1);
+                datatemp.plotSubplot    = ( (kY-1)*ncols + kX )*ones(length(datatemp),1);
+                datatemp.colorgroup     = dataXYC.colorgroup;
+                if ~isempty(nameSubGroup),
+                    datatemp.subgroup   = dataXYC.(nameSubGroup); 
+                else
+                    datatemp.subgroup   = ones(length(datatemp),1); 
+                end
+                if dataXYC.colorgroup(1) == -1,
+                    datatemp.color      = -1*ones(length(datatemp),1); 
+                else
+                    datatemp.color      = find(allGROUPcolor==dataXYC.colorgroup(1))*ones(length(datatemp),1);
+                end
+                if ~isempty(nameText),
+                    datatemp.(nameText) = dataXYC.(nameText);
+                end
+                dataPlot = [dataPlot; datatemp];
+            end
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine the x and y axes ranges if sameaxes selected and
+% adjust the maxY and maxX part of the axes settings to allow for title bar
+% on the X and Y axes.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+minX = min(dataPlot.(nameX));
+maxX = max(dataPlot.(nameX));
+minY = min(dataPlot.(nameY));
+maxY = max(dataPlot.(nameY));
+% Adjust maxY for titlebarX
+if logY(1)==1,
+    rangenew =  1/(1-heighttitlebarX-0.01)*(log10(maxY)-log10(minY));
+    maxY     = 10.^(log10(minY) + rangenew);
+else
+    rangenew =  1/(1-heighttitlebarX-0.01)*(maxY-minY);
+    maxY     = minY + rangenew;
+end
+% Adjust maxX for titlebarY
+if logX==1,
+    rangenew =  1/(1-widthtitlebarY-0.01)*(log10(maxX)-log10(minX));
+    maxX     = 10.^(log10(maxX) + rangenew);
+else
+    rangenew =  1/(1-widthtitlebarY-0.01)*(maxX-minX);
+    maxX     = minX + rangenew;
+end
+sameAxesLimits = [minX maxX minY maxY];
+
+% Determine the axes limits for each row (for each row it should at
+% least be the same) Only for Y axis. X the same as under sameaxes
+rowAxesLimits = [];
+for krow=1:length(allGroupY),
+    datarow = dataPlot(dataPlot.groupY==allGroupY(krow),:);
+    if ~isempty(datarow),
+        minY = min(datarow.(nameY));
+        maxY = max(datarow.(nameY));
+    else
+        minY = eps;
+        maxY = 1;
+    end
+    if minY==maxY,
+        % could happen if all data 0 for a row
+        maxY = minY+1;
+    end
+    % Adjust maxY for titlebarX
+    if logY(krow)==1,
+        rangenew =  1/(1-heighttitlebarX-0.01)*(log10(maxY)-log10(minY));
+        maxY     = 10.^(log10(minY) + rangenew);
+    else
+        rangenew =  1/(1-heighttitlebarX-0.01)*(maxY-minY);
+        maxY     = minY + rangenew;
+    end
+    rowAxesLimits = [rowAxesLimits; sameAxesLimits(1:2) minY maxY];
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Open new figure
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+figure;
+set(gcf,'Color',windowcolor);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Plot the data in the order of subplots
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+for kSubplot=1:nSubplots,
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Choose subplot
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    
+    subaxis(nrows,ncols,kSubplot,'SpacingVert',SpacingVert,'SpacingHoriz',SpacingHoriz,'Padding',Padding,'Margin',Margin);
+
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Get subplot data
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+        
+    dataSk = dataPlot(dataPlot.plotSubplot==kSubplot,:);
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Plot single plot using general auxiliary function
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+            
+    if ~isempty(dataSk),
+        
+        optionsplotgeneral = options;
+        if ~isempty(nameGroupX),
+            optionsplotgeneral.titleText = sprintf('%s=%s',nameGroupX,num2str(dataSk.groupX(1)));
+        else
+            optionsplotgeneral.titleText = 'All Data';
+        end
+        if sameaxes,
+            optionsplotgeneral.axesLimits = sameAxesLimits;
+        else
+            subplotrow = ceil(kSubplot/ncols);
+            optionsplotgeneral.axesLimits = rowAxesLimits(subplotrow,:);
+        end
+        optionsplotgeneral.showtitlebar = 0;
+        optionsplotgeneral.sameaxes     = 1;
+        optionsplotgeneral.logY = logY(ceil(kSubplot/ncols));
+        
+        plotgeneralSBPOP(dataSk,nameX,nameY,optionsplotgeneral);
+
+    else
+        if sameaxes, axis(sameAxesLimits);
+        else subplotrow = ceil(kSubplot/ncols); axis(rowAxesLimits(subplotrow,:)); end
+        hold on
+        if logX, set(gca,'XScale','log'); end
+        if logY(ceil(kSubplot/ncols)), set(gca,'YScale','log'); end
+        if showgrid, grid on; end
+        set(gca,'XMinorGrid','off')
+        set(gca,'YMinorGrid','off')
+        set(gca,'XColor',axescolor);
+        set(gca,'YColor',axescolor);
+        set(gca,'FontUnits','points','FontSize',ticklabeltextsize);    
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Switch off xtick and ytick 
+    % labels if sameaxes is chosen
+    %%%%%%%%%%%%%%%%%%%%%%%%%   
+    
+    if mod(kSubplot-1,ncols)+1 > 1,
+        set(gca,'YtickLabel','');
+    end
+    
+    if kSubplot <= nSubplots-ncols,
+        set(gca,'XtickLabel','');
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Handle x labels
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    
+    if kSubplot > nSubplots-ncols,
+        xlabel(xlabelText,'FontUnits','points','FontSize',labeltextsize,'Interpreter','none');
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Handle y labels
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    
+    if mod(kSubplot-1,ncols)+1 == 1,
+        nrow = ceil(kSubplot/ncols);
+        ylabel(ylabelText{nrow},'FontUnits','points','FontSize',labeltextsize,'Interpreter','none');       
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Handle titlebarX
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    
+    if kSubplot<=ncols,
+        % Get axes limits
+        XLim = get(gca,'XLim');
+        YLim = get(gca,'YLim');
+        % Get X position for text
+        if logX==1,
+            X = 10^(log10(XLim(1)) + 0.5*(log10(XLim(2))-log10(XLim(1))));
+        else
+            X = XLim(1) + 0.5*(XLim(2)-XLim(1));
+        end
+        % Get Y position for text and title bar
+        if logY(ceil(kSubplot/ncols))==1,
+            Y = 10^(log10(YLim(1)) + (1-heighttitlebarX/2)*(log10(YLim(2))-log10(YLim(1))));
+            YtitlebarDN = 10^(log10(YLim(1)) + (1-heighttitlebarX)*(log10(YLim(2))-log10(YLim(1))));
+            YtitlebarUP = 10^(log10(YLim(1)) + 1*(log10(YLim(2))-log10(YLim(1))));
+        else
+            Y = YLim(1) + (1-heighttitlebarX/2)*(YLim(2)-YLim(1));
+            YtitlebarDN = YLim(1) + (1-heighttitlebarX)*(YLim(2)-YLim(1));
+            YtitlebarUP = YLim(1) + 1*(YLim(2)-YLim(1));
+        end
+        % Create a title bar background
+        filled = [YtitlebarUP*[1 1],YtitlebarDN*[1 1]];
+        xpoints=[XLim,fliplr(XLim)];
+        h = fill(xpoints,filled,colortitlebar);
+        set(h,'EdgeColor',axescolor);
+        % Print the title text
+        if length(allGroupX)==1,
+            text(X,Y,'All Data','FontWeight','bold','FontSize',titlefontsize,'HorizontalAlignment','Center');
+        else
+            text(X,Y,sprintf('%s\n%g',nameGroupX,allGroupX(kSubplot)),'FontWeight','bold','FontSize',titlefontsize,'HorizontalAlignment','Center');
+        end
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Handle titlebarY
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    
+    if  mod(kSubplot-1,ncols)+1==ncols,
+        % Get axes limits
+        XLim = get(gca,'XLim');
+        YLim = get(gca,'YLim');
+        % Get Y position for text
+        if logY(ceil(kSubplot/ncols)) == 1,
+            Y = 10^(log10(YLim(1)) + 0.5*(log10(YLim(2))-log10(YLim(1))));
+        else
+            Y = YLim(1) + 0.5*(YLim(2)-YLim(1));
+        end
+        % Get X position for text and title bar
+        if logX==1,
+            X = 10^(log10(XLim(1)) + (1-widthtitlebarY/2)*(log10(XLim(2))-log10(XLim(1))));
+            XtitlebarDN = 10^(log10(XLim(1)) + (1-widthtitlebarY)*(log10(XLim(2))-log10(XLim(1))));
+            XtitlebarUP = 10^(log10(XLim(1)) + 1*(log10(XLim(2))-log10(XLim(1))));
+        else
+            X = XLim(1) + (1-widthtitlebarY/2)*(XLim(2)-XLim(1));
+            XtitlebarDN = XLim(1) + (1-widthtitlebarY)*(XLim(2)-XLim(1));
+            XtitlebarUP = XLim(1) + 1*(XLim(2)-XLim(1));
+        end
+        % Create a title bar background
+        xpoints = [XtitlebarUP*[1 1],XtitlebarDN*[1 1]];
+        filled=[YLim,fliplr(YLim)];
+        h = fill(xpoints,filled,colortitlebar);
+        set(h,'EdgeColor',axescolor);
+        % Print the title text
+        if length(allGroupY)==1,
+            h = text(X,Y,'All Data','FontWeight','bold','FontSize',titlefontsize,'HorizontalAlignment','Center','Rotation',270);
+        else
+            h = text(X,Y,sprintf('%s\n%g',nameGroupY,allGroupY(ceil(kSubplot/ncols))),'FontWeight','bold','FontSize',titlefontsize,'HorizontalAlignment','Center','Rotation',270);
+        end
+    end
+     
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Handle legend - simplistic one
+    % Only do so for color group and median plots
+    % Only show legend if less than maxlegendentries
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    
+    if showlegend && kSubplot==1 && length(allGROUPcolor)<=maxlegendentries,
+        legendText = {};
+        legendColor = {};
+        % Check if color group chosen
+        if allGROUPcolor(1) ~= -1,
+            for kleg=1:length(allGROUPcolor),
+                % Get text part
+                legendText{kleg} = sprintf('%s=%g',nameColorGroup,allGROUPcolor(kleg));
+                % Get color part
+                legendColor{kleg} = linecolorsCustom(mod(kleg-1,length(linecolorsCustom))+1,:);
+                % Get marker part
+                if showmarkers,
+                    legendText{kleg} = sprintf('%s %s',linetypesCustom{   mod(kleg-1,length(linetypesCustom))+1},legendText{kleg});
+                end
+            end
+        end
+        % Check if moving median lines are shown
+        if showmedian,
+            legendText{end+1} = 'Binned median'; %#ok<*AGROW>
+            legendColor{end+1} = [0 0 0];
+        end
+
+        if showmean,
+            legendText{end+1} = 'Binned mean'; %#ok<*AGROW>
+            legendColor{end+1} = [0 0 0];
+        end
+        
+        % Determine y locations
+        nlegend = length(legendText);
+        YLim = get(gca,'YLim');
+        XLim = get(gca,'XLim');
+        
+        if logY==1,
+            textY = 10.^(log10(YLim(1))+((maxlegendentries:-1:1)/(maxlegendentries+1)-heighttitlebarX)*(log10(YLim(2))-log10(YLim(1))));
+        else
+            textY = YLim(1)+((maxlegendentries:-1:1)/(maxlegendentries+1)-heighttitlebarX)*(YLim(2)-YLim(1));
+        end
+        if logX==1,
+            textX = 10.^(log10(XLim(1))+0.98*(log10(XLim(2))-log10(XLim(1))));
+        else
+            textX = XLim(1)+0.98*(XLim(2)-XLim(1));
+        end
+        for klegend=1:nlegend,
+            text(textX,textY(klegend),legendText{klegend},'Color',legendColor{klegend},'FontWeight','bold','FontUnits','points','FontSize',legendtextsize,'HorizontalAlignment','Right','Interpreter','none');
+        end
+    end
+    
+end
+    
+  
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/SBPOPplotfill.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/SBPOPplotfill.m
new file mode 100644
index 0000000000000000000000000000000000000000..c847dcbc5e7e88c84969798b5e91a315b8312c83
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/SBPOPplotfill.m
@@ -0,0 +1,89 @@
+function [fillhandle] = SBPOPplotfill(xpoints,upper,lower,color,transparency,edge,add)
+% [DESCRIPTION]
+% This function will fill a region with a color between the two vectors 
+% provided using the Matlab fill command.
+%
+% [SYNTAX]
+% SBPOPplotfill(xpoints,upper,lower,color,transparency,edge,add)
+%
+% [INPUT]
+% xpoints   = The horizontal data points (ie frequencies). Note length(Upper)
+%             must equal Length(lower)and must equal length(xpoints)!
+% upper     = the upper curve values (data can be less than lower)
+% lower     = the lower curve values (data can be more than upper)
+% color     = the color of the filled area 
+% edge      = the color around the edge of the filled area
+% add       = a flag to add to the current plot or make a new one.
+% transparency is a value ranging from 1 for opaque to 0 for invisible for
+% the filled color only.
+%
+% [OUTPUT]
+% fillhandle is the returned handle to the filled region in the plot.
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% John A. Bockstege November 2006
+% Added to SBPOP by Henning Schmidt 
+%
+% [DATE]
+% 1st December 2010
+%
+% [PLATFORM]
+% Windows XP Engine, MATLAB R2009a, MATLAB, MODESIM
+%
+% [KEYWORDS]
+% MATLAB, plot, fill, region
+% 
+% [TOOLBOXES USED]
+% NONE
+%
+% [VALIDATION HISTORY]
+%
+% [MODIFICATION HISTORY]
+%
+% [EXAMPLE]
+%     a=rand(1,20);%Vector of random data
+%     b=a+2*rand(1,20);%2nd vector of data points;
+%     x=1:20;%horizontal vector
+%     SBPOPplotfill(x,a,b,rand(1,3),rand(1,1),rand(1,3),0);
+%     grid on
+%     legend('Data')
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+if nargin<7;add=1;end     %default is to add to current plot
+if nargin<6;edge='k';end  %dfault edge color is black
+if nargin<5;transparency=.5;end %default is to have a transparency of .5
+if nargin<4;color='b';end %default color is blue
+
+if length(upper)==length(lower) && length(lower)==length(xpoints),
+    msg='';
+    filled=[upper,fliplr(lower)];
+    xpoints=[xpoints,fliplr(xpoints)];
+    if add
+        hold on
+    end
+    fillhandle=fill(xpoints,filled,color);%plot the data
+    set(fillhandle,'EdgeColor',edge,'FaceAlpha',transparency,'EdgeAlpha',transparency);%set edge color
+    if add
+        hold off
+    end
+else
+    error('Must use the same number of points in each vector');
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/SBPOPplotpairwiseCorr.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/SBPOPplotpairwiseCorr.m
new file mode 100644
index 0000000000000000000000000000000000000000..867247514f7b0fed0c3e3d94e88f01e850093750
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/SBPOPplotpairwiseCorr.m
@@ -0,0 +1,185 @@
+function [] = SBPOPplotpairwiseCorr(data,OPTIONS)
+% [DESCRIPTION]
+% This function plots the pairwise correlation between variables passed in
+% columns of a matrix or passed as a dataset.
+%
+% [SYNTAX]
+% [] = SBPOPplotpairwiseCorr(data)
+% [] = SBPOPplotpairwiseCorr(data,OPTIONS)
+%
+% [INPUT]
+% data:         Matrix or dataset. Each column corresponds to a variable
+%               and each row to a sample
+% OPTIONS:      MATLAB structure with optional arguments
+%
+%                   options.names:     cell-array with variable names. In
+%                       case of data as dataset names will be taken from the
+%                       header but can be overwritten with this option. If
+%                       variable values are provided in a matrix, it is better
+%                       to provide the names using this option
+%                   options.LogFlag:   =1 do log transform the variables,
+%                                      =0 do not transform (default: 0)
+%                   options.CorrThres:   Value between 0 and 1 indicating the
+%                       threshold for the Pearson correlation coefficient from which on a
+%                       different color as background should be used (default:
+%                       0.3)
+%                   options.AxisColor:  [r g b] numeric values to use as color 
+%                       for background if Corr>CorrThres =1 do log transform
+%                       the variables (default: [1 0.2 0.2])
+%
+% [OUTPUT]
+% Pairwise correlation plots.
+%
+% [AUTHOR]
+% Original author: Andy Stein
+% Adaptation to SBPOP: Henning Schmidt
+%
+% [DATE]
+% 8th February 2013
+%
+% [PLATFORM]
+% Windows XP Engine, MATLAB R2009a, MATLAB
+%
+% [KEYWORDS]
+% MATLAB, SBPOP
+% 
+% [TOOLBOXES USED]
+% Statistics Toolbox
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+% Check if dataset or if matrix
+% If dataset ten use columnnames as default values for names
+if strcmp(class(data),'dataset'),
+    names = get(data,'VarNames');
+    % Make a matrix out of it
+    data = double(data);
+elseif strcmp(class(data),'double'),
+    names = {};
+    for k=1:size(data,2),
+        names{k} = sprintf('Data#%d',k);
+    end
+end
+
+% Default settings
+% Flag to take log of values
+LogFlag = 0;
+% Coloring
+CorrThres = 0.3; % Pearson correlation coefficient threshold for different background color
+AxisColor = [1 .2 .2]; %color of axis when 
+
+% Get optional values if defined
+try names = OPTIONS.names; catch, end;
+try LogFlag = OPTIONS.LogFlag; catch, end;
+try CorrThres = OPTIONS.CorrThres; catch, end;
+try AxisColor = OPTIONS.AxisColor; catch, end;
+
+% Subindex properties
+Spacing = 0;
+Padding = 0;
+Margin  = .1;
+    
+clf;
+n = length(names);
+for ir=1:n
+    ystr = names{ir};
+    y = data(:,ir);
+    if LogFlag==1
+        y = log(y);
+        ystr = {'log',ystr}; %#ok<*AGROW>
+    end
+    for ic=1:ir
+        xstr = names{ic};
+        x = data(:,ic);
+        if LogFlag==1
+            x = log(x);
+            xstr = {'log',xstr};
+        end
+        ip = (ir-1)*n+ic;
+        subaxis(n,n,ip,'Spacing',Spacing,'Padding',Padding,'Margin',Margin);
+        if ir==ic %plot histogram 
+            % Only do this if not only NaN values are present
+            if ~isempty(find(isnan(x)==0)),
+                [b xbin] = hist(x,20);
+                h = bar(xbin,b,1);
+                if min(x)~=max(x),
+                    set(gca,'XLim',[min(x) max(x)]);
+                else
+                    set(gca,'XLim',[min(x)-1 max(x)+1]);
+                end                    
+            end
+            set(h,'FaceColor',0.4*[1 1 1],'LineStyle','none')
+            title(xstr,'Interpreter','none')
+        else %plot correlation
+            % Only do this is non NaN pairs do exist, which might not
+            % always be the case and then will lead to an error
+            if ~isempty(find(double(isnan(x))+double(isnan(y))==0)),
+                % Determine pearsons coefficient of correlation
+                [rho,pval] = corr(x,y,'type','Pearson','rows','pairwise','tail','both');
+
+                % Plot
+                if abs(rho)>CorrThres
+                    optcorr.Color     = AxisColor;
+                else
+                    optcorr.Color     = 0.4*[1 1 1];
+                end
+                optcorr.LineColor = [0 0 0];
+                optcorr.TitleType = 'none';
+                optcorr.LineStyle = '-';
+                optcorr.LineWidth = 2;
+                optcorr.MarkerSize = 10;
+                plotcorrSBPOP(x,y,optcorr);
+                
+                xt = (min(x)+max(x))/2;
+                yt = min(y)+.6*(max(y)-min(y));
+                if abs(rho)>=0.01
+                    if pval>=0.01,
+                        str = sprintf('corr=%1.2f\np=%1.2f',rho,pval);
+                    else
+                        str = sprintf('corr=%1.2f\np<0.01',rho);
+                    end
+                else
+                    str = '|corr|<0.01';
+                end
+                text(xt,yt,str,'Color',[0 0 0],'Hor','Center','Ver','Middle','FontWeight','Bold','Interpreter','none');
+                
+                if min(x)~=max(x),
+                set(gca,'XLim',[min(x) max(x)]);
+                else
+                set(gca,'XLim',[min(x)-1 max(x)+1]);
+                end
+                if min(y)~=max(y),
+                    set(gca,'YLim',[min(y) max(y)]);
+                else
+                    set(gca,'YLim',[min(y)-1 max(y)+1]);
+                end
+            end
+        end
+        
+        if ic==1
+            ylabel(ystr,'Interpreter','none');
+        end
+        set(gca,'YTick',[]);
+        
+        if ir==n
+            xlabel(xstr,'Interpreter','none');
+        end
+        set(gca,'XTick',[]);
+        
+    end
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/SBPOPplottrellis.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/SBPOPplottrellis.m
new file mode 100644
index 0000000000000000000000000000000000000000..9900ce815b938be701135f7ab47aa2bddc2fcb6d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/SBPOPplottrellis.m
@@ -0,0 +1,545 @@
+function [] = SBPOPplottrellis(data,nameGroup,nameX,nameY,options)
+% [DESCRIPTION]
+% This function plots a Trellis plot. Plenty of options available.
+%
+% [SYNTAX]
+% [] = SBPOPplottrellis(data,nameGroup,nameX,nameY)
+% [] = SBPOPplottrellis(data,nameGroup,nameX,nameY,options)
+%
+% [INPUT]
+% data:         Matlab dataset
+% nameGroup:    Column name in dataset to use as group variable. If empty,
+%               then no grouping is done.
+% nameX:        Column name in dataset to plot on X axis
+% nameY:        Column name in dataset to plot on Y axis
+% options:      Structure with optional settings as follows:
+%   options.xlabelText          = String with xlabel text. Default: nameX
+%   options.ylabelText          = String with ylabel text. Default: nameY
+%   options.nameSubGroup        = Column name in dataset for subgrouping within a group/subplot (nicer line drawing and used for moving median line);
+%   options.nameColorGroup      = Column name in dataset for coloring a certain group differently
+%   options.logX                = 0 if lin, 1 if log X axis (default: 0)
+%   options.logY                = 0 if lin, 1 if log Y axis (default: 0)
+%   options.linetype            = String with MATLAB linetype (default: '.-')
+%   options.linecolor           = Color for lines (default: [0.2 0.2 0.2])
+%   options.showmarkers         = 1 shows different linestyles with markers, =0 uses linstyle setting
+%   options.markersize          = numeric value for markersizes (default: 10)
+%   options.linecolorsCustom    = Matrix with 3 comlumns and arbitrary rows. Defines custom color settings to use for color grouping
+%   options.linetypesCustom     = Cell-array with linestyle strings (e.g.: {'x','-.','--'}). If defined it overrides the standard lines from getcolorsSBPOP (only active if color group selected)
+%                                 Only active if "options.showmarkers=1".
+%   options.linewidth           = Numeric value 1-5 (default: 1)
+%   options.sameaxes            = If 0 (default) subplot axes will be scaled to best fit the data, if 1 all axes will have same scaling
+%   options.showgrid            = 0: no grid, 1: grid (no minor grid lines) (default: 1)
+%   options.colortitlebar       = Vector with three values between 0 and 1 to set he titlebar color (default: [1 1 0.8])
+%   options.heighttitlebar      = Height of the titlebar in fraction of subplot (default: 0.08)
+%   options.showtitlebar        = 0: do not show titlebar, 1: show titlebar (default)
+%   options.showmedian           = 0 (default): do not show a moving median line per group, 1: do show it
+%   options.NbinsMedian          = value between 0 and 100 defining the range of data to take into account (default: 15)
+%   options.showlegend          = 0: do not show a legend, 1 (default): show a legend for the color grouping
+%   options.labeltextsize       = Fontsize for x and y labels (default: 10)
+%   options.maxlegendentries    = If more elements in colorgroup then do not show legend (becomes messy). Default: 10
+%   options.ticklabeltextsize   = Fontsize for axes number (default: 10)
+%   options.legendtextsize      = Fontsize for legend (default: 10)
+%   options.nrows               = Number of rows per subplot (default: all groups in one figure)
+%   options.ncols               = Number of columns per subplot (default: all groups in one figure)
+%   options.ylabelfirstonly     = 1: show the ylabel only for first subplot in figure, 0: show for all first in row subplots
+%   options.nameText            = Column name in dataset (text in column) to display next to datapoints
+%   options.textFontsize        = Fontsize for additional text (default: 10)
+%   options.filename            = Filename for PS (windows) or PDF (unix) output
+%   options.axescolor           = Sets the color of axes and grid (default: [0.2 0.2 0.2])
+%   options.windowcolor         = color definition for outside frame of window (default: [1 1 1])
+%   options.titlefontsize       = Fontsize for title bars (default: 8)
+% 
+%   The "Vertical Line" option allows to draw vertical lines in subplots in
+%   certain places. Practical, e.g., when plotting PK data and wanting to
+%   plot the dosing times additionally. Several lines can be plotted in a
+%   single subplot. A numeric value needs to be provided for each such
+%   line. The maximum value will correspond to a line covering the whole
+%   range. Smaller values will lead to a shorter line. It is possible to
+%   plot the numeric value next to the top of each line.
+%   options.verticallines.linestyle = linestyle string for the vertical line (default: '--')
+%   options.verticallines.linecolor = color vector for the vertical line (default: [0 0 0])
+%   options.verticallines.data      = dataset with info for vertical lines.
+%       This dataset needs:
+%           - same nameGroup column as main data
+%           - same nameX column as main data
+%           - additionally a nameDataVertical to be used to determine the height of the line
+%   options.verticallines.nameDataVertical = string, specifying the column to use to determine the height of the line
+%   options.verticallines.showtext  = 1: shows the value of "nameDataVertical" column next to the top of the line, =1: does not
+%   options.verticallines.textsize  = text size for the printed value (default: 10)
+%   options.verticallines.shownameDataVertical = 1: prints also the name of "nameDataVertical", =0 does not
+%
+% [OUTPUT]
+% This function creates a new figure. If a filename is provided it also can
+% export plots in a PS (windows) or PDF (unix) document.
+%
+% [ASSUMPTIONS]
+% Data for X and Y axes and all groups needs to be numeric. 
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 09th February 2013
+%
+% [TOOLBOXES USED]
+% Statistics Toolbox
+ 
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get default colors and linestyles
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[colorsDefault,linesDefault] = getcolorsSBPOP();
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get optional variables and set defaults if undefined
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try xlabelText          = options.xlabelText;               catch, xlabelText           = nameX;            end; %#ok<*CTCH>
+try ylabelText          = options.ylabelText;               catch, ylabelText           = nameY;            end;
+try nameSubGroup        = options.nameSubGroup;             catch, nameSubGroup         = '';               end;
+try nameColorGroup      = options.nameColorGroup;           catch, nameColorGroup       = '';               end;
+try logX                = options.logX;                     catch, logX                 = 0;                end;
+try logY                = options.logY;                     catch, logY                 = 0;                end;
+try linetype            = options.linetype;                 catch, linetype             = '.-';             end; %#ok<*NASGU>
+try linecolor           = options.linecolor;                catch, linecolor            = [0.2 0.2 0.2];    end;
+try showmarkers         = options.showmarkers;              catch, showmarkers          = 0;                end;
+try markersize          = options.markersize;               catch, markersize           = 10;                end;
+try linecolorsCustom    = options.linecolorsCustom;         catch, linecolorsCustom     = colorsDefault;    end;
+try linetypesCustom     = options.linetypesCustom;          catch, linetypesCustom      = linesDefault;     end;
+try linewidth           = options.linewidth;                catch, linewidth            = 1;                end;
+try sameaxes            = options.sameaxes;                 catch, sameaxes             = 1;                end;
+try showgrid            = options.showgrid;                 catch, showgrid             = 1;                end;
+try colortitlebar       = options.colortitlebar;            catch, colortitlebar        = [1 1 0.8];        end;
+try heighttitlebar      = options.heighttitlebar;           catch, heighttitlebar       = 0.08;             end;
+try showtitlebar        = options.showtitlebar;             catch, showtitlebar         = 1;                end;
+try showmedian           = options.showmedian;              catch, showmedian           = 0;                end;
+try NbinsMedian          = options.NbinsMedian;             catch, NbinsMedian          = 15;               end;
+try showlegend          = options.showlegend;               catch, showlegend           = 1;                end;
+try labeltextsize       = options.labeltextsize;            catch, labeltextsize        = 10;               end;
+try ticklabeltextsize   = options.ticklabeltextsize;        catch, ticklabeltextsize    = 10;               end;
+try legendtextsize      = options.legendtextsize;           catch, legendtextsize       = 10;               end;
+try nrows               = options.nrows;                    catch, nrows                = NaN;              end;
+try ncols               = options.ncols;                    catch, ncols                = NaN;              end;
+try ylabelfirstonly     = options.ylabelfirstonly;          catch, ylabelfirstonly      = 0;                end;
+try maxlegendentries    = options.maxlegendentries;         catch, maxlegendentries     = 10;               end;
+try nameText            = options.nameText;                 catch, nameText             = '';               end;
+try textFontsize        = options.textFontsize;             catch, textFontsize         = 10;               end;
+try filename            = options.filename;                 catch, filename             = '';               end;
+try axescolor           = options.axescolor;                catch, axescolor            = 0.2*[1 1 1];      end;
+try windowcolor         = options.windowcolor;              catch, windowcolor          = 1*[1 1 1];        end;
+try verticallines_linestyle             = options.verticallines.linestyle;              catch, verticallines_linestyle              = '--';             end;
+try verticallines_linecolor             = options.verticallines.linecolor;              catch, verticallines_linecolor              = [0 0 0];          end;
+try verticallines_data                  = options.verticallines.data;                   catch, verticallines_data                   = [];               end;
+try verticallines_nameDataVertical      = options.verticallines.nameDataVertical;       catch, verticallines_nameDataVertical       = [];               end;
+try verticallines_showtext              = options.verticallines.showtext;               catch, verticallines_showtext               = 1;                end;
+try verticallines_textsize              = options.verticallines.textsize;               catch, verticallines_textsize               = 10;               end;
+try verticallines_shownameDataVertical  = options.verticallines.shownameDataVertical;   catch, verticallines_shownameDataVertical   = 0;                end;
+try titlefontsize                       = options.titlefontsize;            catch, titlefontsize        = 8;               end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% If logY chosen then remove all <=0 data
+% Same for logX
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if logY==1,
+    data(data.(nameY)<=0,:) = [];
+end
+if logX==1,
+    data(data.(nameX)<=0,:) = [];
+end
+ 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% If NaN in nameX then remove
+% Do not remove NaN Y values ... this allows to add breaks in the lines
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% data(isnan(data.(nameY)),:) = [];
+data(isnan(data.(nameX)),:) = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Settings for making plots nicer when same axes are chosen
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if sameaxes,
+    SpacingHoriz = 0.002;
+    SpacingVert  = 0.003;
+    Padding      = 0;
+    Margin       = 0.1;
+else
+    SpacingHoriz = 0.05;
+    SpacingVert  = 0.05;
+    Padding      = 0.0;
+    Margin       = 0.1;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Format the data to match the grouping
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get plot data alone
+dataPlot            = dataset();
+dataPlot.(nameX)    = data.(nameX);
+dataPlot.(nameY)    = data.(nameY);
+if ~isempty(nameText),
+    dataPlot.(nameText) = data.(nameText);
+end
+if ~isempty(nameGroup)
+    dataPlot.group  = data.(nameGroup);
+else
+    dataPlot.group  = ones(length(dataPlot),1);
+end
+if ~isempty(nameSubGroup),
+    dataPlot.subgroup = data.(nameSubGroup);
+else
+    dataPlot.subgroup = ones(length(dataPlot),1);
+end
+if ~isempty(nameColorGroup),
+    dataPlot.colorgroup = data.(nameColorGroup);
+    dataPlot.color      = -1*ones(length(dataPlot),1);
+    allGROUPcolor       = unique(dataPlot.colorgroup);    
+    for k=1:length(allGROUPcolor),
+        dataPlot.color(dataPlot.colorgroup == allGROUPcolor(k)) = k;
+    end
+else
+    dataPlot.colorgroup = -1*ones(length(dataPlot),1);
+    dataPlot.color      = -1*ones(length(dataPlot),1);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine the x and y axes ranges if sameaxes selected and
+% adjust the maxY part of the axes settings to allow for title bar
+% Goal is to increase the range of minY to maxY by a fraction of
+% heighttitlebar
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if sameaxes,
+	minX = min(dataPlot.(nameX));
+	maxX = max(dataPlot.(nameX));
+	minY = min(dataPlot.(nameY));
+	maxY = max(dataPlot.(nameY));
+    % Adjust maxY for titlebar
+    if logY==1,
+        rangenew =  1/(1-heighttitlebar-0.01)*(log10(maxY)-log10(minY));
+        maxY     = 10.^(log10(minY) + rangenew);
+    else
+        rangenew =  1/(1-heighttitlebar-0.01)*(maxY-minY);
+        maxY     = minY + rangenew;
+    end
+    sameAxesLimits = [minX maxX minY maxY];
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get different group elements - for each subplot
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+allGROUP = unique(dataPlot.group);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get number of possible elements in sub group
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+allGROUPsub = unique(dataPlot.subgroup);    
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get number of possible elements in color group
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+allGROUPcolor = unique(dataPlot.colorgroup);    
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine number of subplot rows/cols per figure
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+nAllGroups = length(allGROUP);
+if isnan(ncols) || isnan(nrows),
+    ncols = ceil(sqrt(nAllGroups));
+    nrows = ceil(nAllGroups/ncols);
+end
+nSubplots = ncols*nrows;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine number of figures needed for the plotting
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+nFigures = ceil(nAllGroups/nSubplots);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% If output to file desired then start here the file
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(filename),
+    startNewPrintFigureSBPOP(filename);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Plot the data
+% Plot moving median line if desired in each subplot for data within the same color group
+% Subgroup is not considered
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(allGROUP),
+
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Handle multiple figures and subplots
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    
+    plotFigure  = ceil(k/nSubplots);
+    plotSubplot = mod(k-1,nSubplots)+1;  
+
+    % Clear figure if first subplot going to be plotted and set windowcolor
+    if plotSubplot==1, 
+        try close(plotFigure); catch, end
+        figure(plotFigure); 
+        set(gcf,'Color',windowcolor);
+    else
+        figure(plotFigure); 
+    end
+    % Choose subplot
+    subaxis(nrows,ncols,plotSubplot,'SpacingVert',SpacingVert,'SpacingHoriz',SpacingHoriz,'Padding',Padding,'Margin',Margin);
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Get group data for each subplot
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    
+    if isnumeric(allGROUP),
+        datak = dataPlot(dataPlot.group==allGROUP(k),:);
+    else
+        datak = dataPlot(strcmp(dataPlot.group,allGROUP{k}),:);
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Handle correct XLim in case of vertical lines
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    if ~isempty(verticallines_data),
+        if isnumeric(allGROUP),
+            dataVLk = verticallines_data(verticallines_data.(nameGroup)==allGROUP(k),:);
+        else
+            dataVLk = verticallines_data(strcmp(verticallines_data.(nameGroup),allGROUP{k}),:);
+        end            
+        % Get data - check if available in verticallines_data
+        try
+            XVLk = dataVLk.(nameX);
+        catch
+            error(sprintf('Please check settings for vertical lines - nameX and options.verticallines.nameDataVertical\nneed to be set correctly and be present in options.verticallines.data.')); %#ok<SPERR>
+        end
+        % Get X axis if needed because of vertical lines
+        XLimMin = [min(XVLk) max(XVLk)];
+    else
+        XLimMin = [];
+    end        
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Plot single plot using general auxiliary function
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    if ~isempty(nameGroup),
+        if isnumeric(allGROUP),
+            options.titleText = sprintf('%s=%s',nameGroup,num2str(allGROUP(k)));
+        else
+            options.titleText = sprintf('%s',allGROUP{k});
+        end
+    else
+        options.titleText = 'All Data';
+    end    
+    if sameaxes,
+        options.axesLimits = sameAxesLimits;
+    else
+        options.axesLimits = [];
+    end
+    % Set minimum X-axes in options
+    options.XLimMin = XLimMin;
+    
+    % Set axes color
+    options.axescolor = axescolor;
+    
+    options.titlefontsize = titlefontsize;
+    
+    plotgeneralSBPOP(datak,nameX,nameY,options);
+ 
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Switch off xtick and ytick 
+    % labels if sameaxes is chosen
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    if sameaxes,
+        % xticklabels
+        if plotFigure < nFigures,
+            % All subplots used => remove xticklabels in all but last row
+            if plotSubplot <= nSubplots-ncols,
+                set(gca,'XtickLabel','');
+            end
+        else
+            % Figure only partially filled with subplots - only labels for
+            % the last ncols subplots
+            if k <= nAllGroups-ncols,
+                set(gca,'XtickLabel','');
+            end
+        end
+        % yticklabels
+        if mod(plotSubplot-1,ncols)+1 > 1,
+            set(gca,'YtickLabel','');
+        end
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Handle x labels
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    
+    if plotFigure < nFigures,
+        % All subplots used => xlabel for the last ncols subplots
+        if plotSubplot > nSubplots-ncols,
+            xlabel(xlabelText,'FontUnits','points','FontSize',labeltextsize,'Interpreter','none','Color',axescolor);
+        end
+    else
+        % Figure only partially filled with subplots - only labels for
+        % the last ncols subplots
+        if k > nAllGroups-ncols,
+            xlabel(xlabelText,'FontUnits','points','FontSize',labeltextsize,'Interpreter','none','Color',axescolor);
+        end
+    end
+        
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Handle y labels
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    
+    if ylabelfirstonly && plotSubplot==1 && nrows > 1,
+        ylabel(ylabelText,'FontUnits','points','FontSize',labeltextsize,'HorizontalAlignment','Right','Interpreter','none','Color',axescolor);
+    elseif nrows == 1,
+        if plotSubplot==1,
+            ylabel(ylabelText,'FontUnits','points','FontSize',labeltextsize,'Interpreter','none','Color',axescolor);     
+        end
+    elseif ~ylabelfirstonly && mod(plotSubplot-1,ncols)+1==1,
+        ylabel(ylabelText,'FontUnits','points','FontSize',labeltextsize,'Interpreter','none','Color',axescolor);       
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Handle legend - simplistic one
+    % Only do so for color group and median plots
+    % Only show legend if less than maxlegendentries
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    
+    if showlegend && plotSubplot==1 && length(allGROUPcolor)<=maxlegendentries,
+        legendText = {};
+        legendColor = {};
+        % Check if color group chosen
+        if allGROUPcolor(1) ~= -1,
+            for kleg=1:length(allGROUPcolor),
+                % Get text part
+                legendText{kleg} = sprintf('%s=%g',nameColorGroup,allGROUPcolor(kleg));
+                % Get color part
+                legendColor{kleg} = linecolorsCustom(mod(kleg-1,length(linecolorsCustom))+1,:);
+                % Get marker part
+                if showmarkers,
+                    legendText{kleg} = sprintf('%s %s',linetypesCustom{   mod(kleg-1,length(linetypesCustom))+1},legendText{kleg});
+                end
+            end
+        end
+        % Check if moving median lines are shown
+        if showmedian,
+            legendText{end+1} = 'Binned median'; %#ok<*AGROW>
+            legendColor{end+1} = [0 0 0];
+        end
+        
+        % Determine y locations
+        nlegend = length(legendText);
+        YLim = get(gca,'YLim');
+        XLim = get(gca,'XLim');
+        
+        if logY==1,
+            textY = 10.^(log10(YLim(1))+((maxlegendentries:-1:1)/(maxlegendentries+1)-heighttitlebar)*(log10(YLim(2))-log10(YLim(1))));
+        else
+            textY = YLim(1)+((maxlegendentries:-1:1)/(maxlegendentries+1)-heighttitlebar)*(YLim(2)-YLim(1));
+        end
+        if logX==1,
+            textX = 10.^(log10(XLim(1))+0.98*(log10(XLim(2))-log10(XLim(1))));
+        else
+            textX = XLim(1)+0.98*(XLim(2)-XLim(1));
+        end
+        for klegend=1:nlegend,
+            text(textX,textY(klegend),legendText{klegend},'Color',legendColor{klegend},'FontWeight','bold','FontUnits','points','FontSize',legendtextsize,'HorizontalAlignment','Right','Interpreter','none');
+        end
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Handle and plot vertical lines if specified
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    
+    if ~isempty(verticallines_data),
+        if isnumeric(allGROUP),
+            dataVLk = verticallines_data(verticallines_data.(nameGroup)==allGROUP(k),:);
+        else
+            dataVLk = verticallines_data(strcmp(verticallines_data.(nameGroup),allGROUP{k}),:);
+        end
+        % Get data - check if available in verticallines_data
+        try
+            XVLk = dataVLk.(nameX);
+            DVLk = dataVLk.(verticallines_nameDataVertical);
+        catch
+            error(sprintf('Please check settings for vertical lines - nameX and options.verticallines.nameDataVertical\nneed to be set correctly and be present in options.verticallines.data.')); %#ok<SPERR>
+        end
+        % Normalize DVLk - and handle also titlebar
+        DVLknorm = (1-heighttitlebar-0.01)* DVLk/max(DVLk);
+        % Determine Y range for plot
+        YLim = get(gca,'YLim');
+        Ydn = YLim(1);
+        if logY==1,
+            Yup = 10.^(log10(YLim(1))+DVLknorm*(log10(YLim(2))-log10(YLim(1))));
+            Ytext = 10.^(log10(YLim(1))+(DVLknorm-0.05)*(log10(YLim(2))-log10(YLim(1))));
+        else
+            Yup = YLim(1)+DVLknorm*(YLim(2)-YLim(1));
+            Ytext = YLim(1)+(DVLknorm-0.05)*(YLim(2)-YLim(1));
+        end
+        % Plot the lines
+        for kVL=1:length(Yup),
+            plot([XVLk(kVL),XVLk(kVL)],[Ydn,Yup(kVL)],verticallines_linestyle,'Color',verticallines_linecolor);
+        end
+        % Show text if desired - but only first and then when changes
+        if verticallines_showtext,
+            for kVL=1:length(Yup),
+                if kVL==1,
+                    if verticallines_shownameDataVertical,
+                        text(XVLk(kVL),Ytext(kVL),[' ' verticallines_nameDataVertical '=' num2str(DVLk(kVL))],'Color',verticallines_linecolor,'FontSize',verticallines_textsize,'BackgroundColor',windowcolor);
+                    else
+                        text(XVLk(kVL),Ytext(kVL),[' ' num2str(DVLk(kVL))],'Color',verticallines_linecolor,'FontSize',verticallines_textsize,'BackgroundColor',windowcolor);
+                    end
+                elseif Ytext(kVL)~=Ytext(kVL-1),
+                    if verticallines_shownameDataVertical,
+                        text(XVLk(kVL),Ytext(kVL),[' ' verticallines_nameDataVertical '=' num2str(DVLk(kVL))],'Color',verticallines_linecolor,'FontSize',verticallines_textsize,'BackgroundColor',windowcolor);
+                    else
+                        text(XVLk(kVL),Ytext(kVL),[' ' num2str(DVLk(kVL))],'Color',verticallines_linecolor,'FontSize',verticallines_textsize,'BackgroundColor',windowcolor);
+                    end
+                end
+            end
+        end
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % If figure finished and output to file desired then do that
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    if ~isempty(filename),
+        if plotFigure < nFigures,
+            if plotSubplot == nSubplots,
+                printFigureSBPOP(gcf,filename);
+                close(plotFigure);
+            end
+        else
+            if k == nAllGroups,
+                printFigureSBPOP(gcf,filename);
+                close(plotFigure);
+            end
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%
+% If output to file desired then convert to pdf
+%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(filename),
+    convert2pdfSBPOP(filename);
+end
+
+
+
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/auxiliary/plotboxSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/auxiliary/plotboxSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..6921afa8c83f70b5850ef0736a12d4f4447ee10b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/auxiliary/plotboxSBPOP.m
@@ -0,0 +1,175 @@
+function [h] = plotboxSBPOP(Y,tm,OPTIONS)
+% [DESCRIPTION]
+% This function plots boxplots of time course stored in Y structure.
+%
+% This function is an auxiliary function, called by
+% SBPOPplotCovarianceCat
+%
+% [SYNTAX]
+% [h] = plotboxSBPOP(Y,tm,OPTIONS)
+%
+% [INPUT]
+% Y can either be a matrix of size Nxlength(tm) or a structure with
+%    Y(i).t = time variable
+%    Y(i).y = y variable
+% tm     = bin centers
+% OPTIONS:      Structure with optional settings as follows:
+%   OPTIONS.HorOffset = 0
+%   OPTIONS.MedianColor = [0 0 .5]
+%   OPTIONS.MedianWidth = 0.2
+%   OPTIONS.MedianLineWidth = 1
+%   OPTIONS.BoxColor = [0 0 1]
+%   OPTIONS.BoxWidth = 0.1
+%   OPTIONS.LineWidth = 3
+%   OPTIONS.Perc = 10
+%   OPTIONS.OutlierColor = [0 0 1]
+%   OPTIONS.OutlierSize = 6
+%   OPTIONS.NumFlag = 1
+%   OPTIONS.NumColor = 'k'
+%   OPTIONS.NumTextY = 1
+%   OPTIONS.FontColor = 'k'
+%   OPTIONS.XLabel = []
+%   OPTIONS.YLabel = []
+%   OPTIONS.XTick = []
+%   OPTIONS.XLim = []
+%
+% [OUTPUT]
+% Plot
+%
+% [ASSUMPTIONS]
+% 
+% [AUTHOR]
+% Andy Stein
+% Adapted for SBPOP by Henning Schmidt
+%
+% [DATE]
+% 09th February 2013
+%
+% [TOOLBOXES USED]
+% Statistics Toolbox
+ 
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle options and default values
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%positioning properties
+try HorOffset = OPTIONS.HorOffset;              catch,  HorOffset = 0;                  end
+%median line
+try MedianColor = OPTIONS.MedianColor;          catch, MedianColor = [0 0 .5];          end
+try MedianWidth = OPTIONS.MedianWidth;          catch, MedianWidth = 0.2;               end
+try MedianLineWidth = OPTIONS.MedianLineWidth;  catch, MedianLineWidth = 1;             end
+%box properties 25%-75%
+try BoxColor = OPTIONS.BoxColor;                catch, BoxColor = [0 0 1];              end
+try BoxWidth = OPTIONS.BoxWidth;                catch, BoxWidth = 0.1;                  end
+%line properties Perc%-100-Perc%
+try LineWidth = OPTIONS.LineWidth;              catch, LineWidth = 3;                   end %10-90% Line
+try Perc = OPTIONS.Perc;                        catch, Perc = 10;                       end
+%outlier properties
+try OutlierColor = OPTIONS.OutlierColor;        catch, OutlierColor = [0 0 1];          end 
+try OutlierSize = OPTIONS.OutlierSize;          catch, OutlierSize = 6;                 end     
+%text properties (number of pts)
+try NumFlag = OPTIONS.NumFlag;                  catch, NumFlag = 1;                     end 
+try NumColor = OPTIONS.NumColor;                catch, NumColor = 'k';                  end 
+try NumTextY = OPTIONS.NumTextY;                catch, NumTextY = 1;                    end     
+%axis properties
+try FontColor = OPTIONS.FontColor;              catch, FontColor = 'k';                 end 
+try XLabel = OPTIONS.XLabel;                    catch, XLabel = [];                     end 
+try YLabel = OPTIONS.YLabel;                    catch, YLabel = [];                     end 
+try XTick = OPTIONS.XTick;                      catch, XTick = [];                      end 
+try XLim = OPTIONS.XLim;                        catch, XLim = [];                       end 
+
+%bin the variable   
+if isstruct(Y)
+    dt = mean(diff(tm));
+    YY = NaN(length(Y),length(tm));
+    for i=1:length(Y)
+        t = Y(i).t;
+        y = Y(i).y;
+        for j=1:length(tm)
+            [dtij ind] = min(abs(t-tm(j)));
+            if dtij<=dt/2
+                YY(i,j) = y(ind);
+            end
+        end
+    end
+else
+    YY = Y;
+end
+
+%draw the boxplot   
+    hold on
+    for i=1:length(tm)
+        t  = tm(i)+HorOffset;
+        y = YY(:,i);
+            
+        %draw the line (p1%-100-p1%)        
+            y1 = prctile(y,Perc);
+            y2 = prctile(y,100-Perc);        
+            plot([t t],[y1 y2],'Color',BoxColor,'LineWidth',LineWidth);
+
+        %draw the outliers
+            ii = find(y<y1 | y>y2);
+            plot(t*ones(size(ii)),y(ii),'+','Color',OutlierColor,'MarkerSize',OutlierSize);    
+
+        %draw the box (25%-75%)
+            t1 = t-BoxWidth/2;
+            t2 = t+BoxWidth/2;
+
+            y1 = prctile(y,25);
+            y2 = prctile(y,75);
+
+            tt = [t1 t2 t2 t1 t1];
+            yy = [y1 y1 y2 y2 y1];
+
+            h = fill(tt,yy,BoxColor,'LineStyle','none');
+            
+        %draw the line at 50%
+            yi = prctile(y,50);
+            t1= t-MedianWidth/2;
+            t2= t+MedianWidth/2;
+            plot([t1 t2],[yi yi],'Color',MedianColor,'LineWidth',MedianLineWidth);                        
+            
+            
+        %number of patients
+            if NumFlag==1
+                if i==1
+                    s = 'n=';
+                else
+                    s = '';
+                end
+                text(t,NumTextY,sprintf('%s%d',s,sum(~isnan(y))),'Horiz','Center','Color',NumColor,'FontWeight','Bold')        
+            end
+    end
+
+%plot labels        
+    hold on
+    xlim = get(gca,'XLim');
+    
+    if ~isempty(XLabel)
+        xlabel(XLabel,'Color',FontColor,'Interpreter','none')
+    end
+    if ~isempty(YLabel)
+        ylabel(YLabel,'Color',FontColor,'Interpreter','none')
+    end
+    if ~isempty(XTick)
+        set(gca,'XTick',XTick);
+    end
+    if ~isempty(XLim)
+        set(gca,'XLim',XLim);
+    end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/auxiliary/plotcorrSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/auxiliary/plotcorrSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..a3a941ada177779e24ad20324e2a161901efc9a1
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/auxiliary/plotcorrSBPOP.m
@@ -0,0 +1,151 @@
+function[R2 pval slope yint] = plotcorrSBPOP(xvar,yvar,OPTIONS)
+% [DESCRIPTION]
+% This function plots correlation of x variable and y variable.
+%
+% This function is an auxiliary function, called by
+% SBPOPplotpairwiseCorr
+%
+% [SYNTAX]
+% [] = plotcorrSBPOP(xvar,yvar,props)
+%
+% [INPUT]
+% xvar:         Vector with x data
+% yvar:         Vector with y data
+% OPTIONS:      Structure with optional settings as follows:
+%     OPTIONS.Color = 'b';
+%     OPTIONS.TitleType = 'all';
+%     OPTIONS.LineColor = 'k';
+%     OPTIONS.LineStyle = '-';
+%     OPTIONS.LineWidth = 2;
+%     OPTIONS.Marker    = '.';
+%     OPTIONS.MarkerSize = 6;
+%     OPTIONS.MarkerFaceColor = 'none';
+%     OPTIONS.XLabel = '';
+%     OPTIONS.YLabel = '';
+%     OPTIONS.XLim   = [];
+%     OPTIONS.YLim   = [];
+%
+% [OUTPUT]
+% Plot
+%
+% [ASSUMPTIONS]
+% Data for X and Y axes and all groups needs to be numeric. 
+%
+% [AUTHOR]
+% Andy Stein
+% Adapted for SBPOP by Henning Schmidt
+%
+% [DATE]
+% 09th February 2013
+%
+% [TOOLBOXES USED]
+% Statistics Toolbox
+ 
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+%set default values
+    Color = 'b';
+    TitleType = 'all';
+    LineColor = 'k';
+    LineStyle = '-';
+    LineWidth = 2;
+    Marker    = '.';
+    MarkerSize = 6;
+    MarkerFaceColor = 'none';
+    XLabel = '';
+    YLabel = '';
+    XLim   = [];
+    YLim   = [];
+
+    try Color = OPTIONS.Color; catch, end;
+    try TitleType = OPTIONS.TitleType; catch, end;
+    try LineColor = OPTIONS.LineColor; catch, end;
+    try LineStyle = OPTIONS.LineStyle; catch, end;
+    try LineWidth = OPTIONS.LineWidth; catch, end;
+    try Marker = OPTIONS.Marker; catch, end;
+    try MarkerSize = OPTIONS.MarkerSize; catch, end;
+    try MarkerFaceColor = OPTIONS.MarkerFaceColor; catch, end;
+    try XLabel = OPTIONS.XLabel; catch, end;
+    try YLabel = OPTIONS.YLabel; catch, end;
+    try XLim = OPTIONS.XLim; catch, end;
+    try YLim = OPTIONS.YLim; catch, end;
+    
+plot(xvar,yvar,Marker,'Color',Color,'MarkerSize',MarkerSize,'MarkerFaceColor',MarkerFaceColor);    
+hold on
+% Do linear regression
+[b,bint,r,rint,stats] = regress(yvar,[ones(size(xvar)) xvar]);
+xx = linspace(min(xvar),max(xvar),100);
+plot(xx,b(1)+b(2)*xx,'Color',LineColor,'LineWidth',LineWidth,'LineStyle',LineStyle)    
+slope = b(2);
+yint  = b(1);
+
+R2 = stats(1); % R2 = corrcoeff^2 for linear regression
+pval = stats(3);
+switch TitleType
+    case 'all'
+        if b(2)>.0005 && b(2) < 1000 
+            tstr{1} = sprintf('m = %1.3f',b(2));
+        else
+            tstr{1} = sprintf('m = %1.2e',b(2));
+        end
+        if pval > .0001
+            tstr{2} = sprintf('R^2 = %1.3f, pval = %1.4f',R2,pval);%,'Color',Color);
+        else
+            tstr{2} =sprintf('R^2 = %1.3f, pval < .0001',R2);%,'Color',Color);
+        end    
+    case 'p'
+        tstr = sprintf('p=%1.4f',pval);
+    case 'r'
+        tstr = sprintf('R^2=%1.3f',R2);
+    case {'rp','pr'}
+        tstr = sprintf('p=%1.4f, R^2=%1.2f',pval,R2);
+    case {'mr','rm'}
+        tstr = sprintf('m=%1.3f, R^2=%1.2f',b(2),R2);
+    case {'pm','mp'}
+        if pval > .01    
+            tstr = (sprintf('p=%1.2f, m=%1.3f',pval,b(2)));    
+        elseif pval > .001
+            tstr = (sprintf('p<0.01, m=%1.3f',b(2)));    
+        elseif pval > .0001
+            tstr = (sprintf('p<0.001, m=%1.3f',b(2)));    
+        else
+            tstr = (sprintf('p<0.0001, m=%1.3f',b(2)));    
+        end
+    case {'none'}
+        tstr = '';
+    otherwise
+        error('invalid TitleType')
+end    
+title(tstr,'Interpreter','none');
+
+xlabel(XLabel,'Interpreter','none')
+ylabel(YLabel,'Interpreter','none')
+if ~isempty(XLim)
+    set(gca,'XLim',props.XLim) 
+elseif min(xvar)~=max(xvar),
+    set(gca,'XLim',[min(xvar) max(xvar)]);
+else
+    set(gca,'XLim',[min(xvar)-1 max(xvar)+1]);
+end    
+if ~isempty(YLim)
+    set(gca,'YLim',props.YLim) 
+elseif min(yvar)~=max(yvar),
+    set(gca,'YLim',[min(yvar) max(yvar)]);
+else
+    set(gca,'YLim',[min(yvar)-1 max(yvar)+1]);
+end    
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/auxiliary/plotgeneralSBPOP.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/auxiliary/plotgeneralSBPOP.m
new file mode 100644
index 0000000000000000000000000000000000000000..88276522b3636e249a4911d81ce1e15506820656
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBPOP/tools/plots/auxiliary/plotgeneralSBPOP.m
@@ -0,0 +1,470 @@
+function [] = plotgeneralSBPOP(datak,nameX,nameY,options)
+% [DESCRIPTION]
+% This function plots x,y data in different ways. Used as the plot base for
+% SBPOPplottrellis and SBPOPplotXY
+%
+% [SYNTAX]
+% [] = plotgeneralSBPOP(data,nameGroup,nameX,nameY)
+% [] = plotgeneralSBPOP(data,nameGroup,nameX,nameY,options)
+%
+% [INPUT]
+% datak:        Dataset to plot
+%               It is assumed that datak contains a column "subgroup" with
+%               numeric identifiers about different groupings. Also it is
+%               assumed that datak contains a column "colorgroup" with
+%               numeric identifiers selecting the color (-1 being the
+%               default color).
+% nameX:        Column name in dataset to plot on X axis
+% nameY:        Column name in dataset to plot on Y axis
+% options:      Structure with optional settings as follows:
+%   options.logX                = 0 if lin, 1 if log X axis (default: 0)
+%   options.logY                = 0 if lin, 1 if log Y axis (default: 0)
+%   options.linetype            = String with MATLAB linetype (default: '.-')
+%   options.linecolor           = Color for lines (default: [0.6 0.6 0.6])
+%   options.showmarkers         = 1 shows different linestyles with markers, =0 uses linstyle setting
+%   options.markersize          = numeric value for markersizes (default: 10)
+%   options.linecolorsCustom    = Matrix with 3 comlumns and arbitrary rows. Defines custom color settings to use for color grouping
+%   options.linetypesCustom     = Cell-array with linestyle strings (e.g.: {'x','-.','--'}). If defined it overrides the standard lines from getcolorsSBPOP (only active if color group selected)
+%                                 Only active if "options.showmarkers=1".
+%   options.linewidth           = Numeric value 1-5 (default: 1)
+%   options.axesLimits          = [minX maxX minY maxY] can be passed as axes limits. By default the axes are adjusted to the data
+%   options.showgrid            = 0: no grid, 1: grid (no minor grid lines) (default: 1)
+%   options.colortitlebar       = Vector with three values between 0 and 1 to set he titlebar color (default: [1 1 0.8])
+%   options.heighttitlebar      = Height of the titlebar in fraction of subplot (default: 0.08)
+%   options.showtitlebar        = 0: do not show titlebar, 1: show titlebar (default)
+%   options.showmedian           = 0 (default): do not show a moving median line per group, 1: do show it
+%   options.showmean           = 0 (default): do not show a moving mean line per group, 1: do show it
+%   options.NbinsMedian          = value between 0 and 100 defining the range of data to take into account (default: 15)
+%   options.medianlinewidth      = width of moving median line (default: options.linewidth+1)
+%   options.showregressionline  = 1 shows a linear regression line, =0: does not (default)
+%   options.showcorrelations    = 1 shows correlation info, =0 does not (default) - only done if options.showregressionline=1
+%   options.correlationstextsize= text size for correlation information (default: 10)
+%   options.ticklabeltextsize   = Fontsize for axes number (default: 10)
+%   options.nameText            = Column name in dataset (text in column) to display next to datapoints
+%   options.textFontsize        = Fontsize for additional text (default: 10)
+%   options.axescolor           = Sets the color of axes and grid (default: [0.5 0.5 0.5])
+%   options.titleText           = Text in the title bar (default: 'Title')
+%   options.titlefontsize       = FontSize for the title (default: 8)
+%   options.XLimMin             = minimal x-axis range (2 elements 1st: minX, 2nd: maxX)
+%
+% [OUTPUT]
+% This function creates a new figure. If a filename is provided it also can
+% export plots in a PS (windows) or PDF (unix) document.
+%
+% [ASSUMPTIONS]
+% Data for X and Y axes and all groups needs to be numeric. 
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 09th February 2013
+%
+% [TOOLBOXES USED]
+% Statistics Toolbox
+ 
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Get default colors and linestyles
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    [colorsDefault,linesDefault] = getcolorsSBPOP();
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Get optional variables and set defaults if undefined
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    try logX                = options.logX;                     catch, logX                 = 0;                end;
+    try logY                = options.logY;                     catch, logY                 = 0;                end;
+    try linetype            = options.linetype;                 catch, linetype             = '.-';             end;
+    try linecolor           = options.linecolor;                catch, linecolor            = [0.6 0.6 0.6];    end;
+    try showmarkers         = options.showmarkers;              catch, showmarkers          = 0;                end;
+    try markersize          = options.markersize;               catch, markersize          = 10;                end;
+    try linecolorsCustom    = options.linecolorsCustom;         catch, linecolorsCustom     = colorsDefault;    end;
+    try linetypesCustom     = options.linetypesCustom;          catch, linetypesCustom      = linesDefault;     end;
+    try linewidth           = options.linewidth;                catch, linewidth            = 1;                end;
+    try axesLimits          = options.axesLimits;               catch, axesLimits           = [];               end;
+    try showgrid            = options.showgrid;                 catch, showgrid             = 1;                end;
+    try colortitlebar       = options.colortitlebar;            catch, colortitlebar        = [1 1 0.8];        end;
+    try heighttitlebar      = options.heighttitlebar;           catch, heighttitlebar       = 0.08;             end;
+    try showtitlebar        = options.showtitlebar;             catch, showtitlebar         = 1;                end;
+    try showmedian           = options.showmedian;                catch, showmedian            = 0;                end;
+    try showmean           = options.showmean;                catch, showmean            = 0;                end;
+    try NbinsMedian          = options.NbinsMedian;               catch, NbinsMedian           = 15;               end;
+    try medianlinewidth      = options.medianlinewidth;           catch, medianlinewidth       = linewidth+1;      end;
+    try showregressionline  = options.showregressionline;       catch, showregressionline   = 0;                end;
+    try showcorrelations    = options.showcorrelations;         catch, showcorrelations     = 0;                end;
+    try correlationstextsize= options.correlationstextsize;     catch, correlationstextsize = 10;               end;
+    try ticklabeltextsize   = options.ticklabeltextsize;        catch, ticklabeltextsize    = 10;               end;
+    try nameText            = options.nameText;                 catch, nameText             = '';               end;
+    try textFontsize        = options.textFontsize;             catch, textFontsize         = 10;               end;
+    try axescolor           = options.axescolor;                catch, axescolor            = 0.2*[1 1 1];      end;
+    try titleText           = options.titleText;                catch, titleText            = 'title';          end;
+    try legendIdentifier    = options.legendIdentifier;         catch, legendIdentifier     = 'ColorGroup';     end;
+    try XLimMin             = options.XLimMin;                  catch, XLimMin              = [];               end;
+    try titlefontsize       = options.titlefontsize;            catch, titlefontsize        = 8; end;
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Other settings
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    
+    allGROUPsub       = unique(datak.subgroup);
+    allGROUPcolor     = unique(datak.colorgroup);
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Define plottype
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    if logY==1 && logX==1,
+        plottype = 'loglog';
+    elseif logY==1 && logX==0,
+        plottype = 'semilogy';
+    elseif logY==0 && logX==1,
+        plottype = 'semilogx';
+    else
+        plottype = 'plot';
+    end
+
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Plot the data
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    
+    % Get subgroup data
+    for kk=1:length(allGROUPsub),
+        datakk = datak(datak.subgroup==allGROUPsub(kk),:);
+        
+        % Now plot, according to selected color group
+        for kkk=1:length(allGROUPcolor),
+            datakkk = datakk(datakk.colorgroup==allGROUPcolor(kkk),:);
+            
+            if ~isempty(datakkk),
+                % Get color
+                if datakkk.color(1) == -1,
+                    color = linecolor;
+                    line  = linetype;
+                else
+                    color = linecolorsCustom(mod(datakkk.color(1)-1,length(linecolorsCustom))+1,:);
+                    if showmedian,
+%                         color = 1.5*color;
+                    end
+                    if showmarkers,
+                        line  = linetypesCustom{   mod(datakkk.color(1)-1,length(linetypesCustom))+1};
+                    else
+                        line = linetype;
+                    end
+                end
+                feval(plottype,datakkk.(nameX),datakkk.(nameY),line,'Color',color,'LineWidth',linewidth,'MarkerSize',markersize); hold on
+
+                %%%%%%%%%%%%%%%%%%%%%%%%%
+                % Print the text if defined
+                %%%%%%%%%%%%%%%%%%%%%%%%%
+                if ~isempty(nameText),
+                    text(datakkk.(nameX),datakkk.(nameY),datakkk.(nameText),'FontSize',textFontsize,'Color',color);
+                end
+                
+            end
+        end
+    end    
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Plot the moving median line if desired
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+
+    if showmedian,
+        % Get color group data
+        for kkk=1:length(allGROUPcolor),
+            datakkk = datak(datak.colorgroup==allGROUPcolor(kkk),:);
+            if length(datakkk) > 1,
+                % Get X and Y data
+                Xdata = datakkk.(nameX);
+                Ydata = datakkk.(nameY);
+                
+                [XdataMedian,YdataMedian] = binnedmedianSB(Xdata(:),Ydata(:),NbinsMedian,logX);
+                
+                % Handle color, etc.
+                if datakkk.color(1) == -1,
+                    color = 0.6*linecolor;
+                    line  = linetype;
+                else
+                    color = linecolorsCustom(mod(datakkk.color(1)-1,length(linecolorsCustom))+1,:);
+                    if showmarkers,
+                        line  = linetypesCustom{   mod(datakkk.color(1)-1,length(linetypesCustom))+1};
+                    else
+                        line = '--';
+                    end
+                end
+                % Adjust moving median linestyle in case its only dots
+                if length(line) == 1,
+                    line = [line '--'];
+                end
+                % Plot moving median line
+                warning off %#ok<WNOFF>
+                feval(plottype,XdataMedian,YdataMedian,line,'LineWidth',medianlinewidth,'Color',color,'MarkerSize',markersize);
+                warning on %#ok<WNON>
+            end
+        end
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Plot the moving mean line if desired
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+
+    if showmean,
+        % Get color group data
+        for kkk=1:length(allGROUPcolor),
+            datakkk = datak(datak.colorgroup==allGROUPcolor(kkk),:);
+            if length(datakkk) > 1,
+                % Get X and Y data
+                Xdata = datakkk.(nameX);
+                Ydata = datakkk.(nameY);
+                
+                [XdataMean,YdataMean] = binnedmeanSB(Xdata(:),Ydata(:),NbinsMedian,logX);
+                
+                % Handle color, etc.
+                if datakkk.color(1) == -1,
+                    color = 0.6*linecolor;
+                    line  = linetype;
+                else
+                    color = linecolorsCustom(mod(datakkk.color(1)-1,length(linecolorsCustom))+1,:);
+                    if showmarkers,
+                        line  = linetypesCustom{   mod(datakkk.color(1)-1,length(linetypesCustom))+1};
+                    else
+                        line = '--';
+                    end
+                end
+                % Adjust moving mean linestyle in case its only dots
+                if length(line) == 1,
+                    line = [line '--'];
+                end
+                % Plot moving mean line
+                warning off %#ok<WNOFF>
+                feval(plottype,XdataMean,YdataMean,line,'LineWidth',medianlinewidth,'Color',color,'MarkerSize',markersize);
+                warning on %#ok<WNON>
+            end
+        end
+    end    
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Plot the regression line if desired
+    % Also determine correlations - to be plotted later after axes adjustment
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    
+    if showregressionline,
+        corrText = {};
+        corrColor = {};
+        % Get color group data
+        for kkk=1:length(allGROUPcolor),
+            datakkk = datak(datak.colorgroup==allGROUPcolor(kkk),:);
+            if ~isempty(datakkk),
+                % Get X and Y data
+                Xdata = datakkk.(nameX);
+                Ydata = datakkk.(nameY);
+                % Get XLim data
+                XLim = get(gca,'XLim');
+                % Linear regression
+                if logX==0 && logY==0,
+                    B = regress(Ydata,[Xdata ones(size(Xdata))]);
+                    XdataRegress = XLim;
+                    YdataRegress = B(2)+B(1)*XLim;
+                    [rho,pcorr] = corr(Ydata,Xdata,'type','Pearson','rows','pairwise','tail','both');
+                elseif logX==1 && logY==0,
+                    B = regress(Ydata,[log(Xdata) ones(size(Xdata))]);
+                    XdataRegress = XLim;
+                    YdataRegress = B(2)+B(1)*log(XLim);
+                    [rho,pcorr] = corr(Ydata,log(Xdata),'type','Pearson','rows','pairwise','tail','both');
+                elseif logX==0 && logY==1,
+                    B = regress(log(Ydata),[Xdata ones(size(Xdata))]);
+                    XdataRegress = XLim;
+                    YdataRegress = exp(B(2)+B(1)*XLim);
+                    [rho,pcorr] = corr(log(Ydata),Xdata,'type','Pearson','rows','pairwise','tail','both');
+                else
+                    B = regress(log(Ydata),[log(Xdata) ones(size(Xdata))]);
+                    XdataRegress = XLim;
+                    YdataRegress = exp(B(2)+B(1)*log(XLim));
+                    [rho,pcorr] = corr(log(Ydata),log(Xdata),'type','Pearson','rows','pairwise','tail','both');
+                end
+                % Handle color, etc.
+                if datakkk.color(1) == -1,
+                    color = linecolor;
+                    line  = linetype;
+                else
+                    color = linecolorsCustom(mod(datakkk.color(1)-1,length(linecolorsCustom))+1,:);
+                    if showmarkers,
+                        line  = linetypesCustom{   mod(datakkk.color(1)-1,length(linetypesCustom))+1};
+                    else
+                        line = '-.';
+                    end
+                end
+                % Adjust regression linestyle in case its only dots
+                if length(line) == 1,
+                    line = [line '-'];
+                end
+                % Plot regression line
+                warning off %#ok<WNOFF>
+                feval(plottype,XdataRegress,YdataRegress,line,'LineWidth',linewidth+1,'Color',color,'MarkerSize',markersize);
+                warning on %#ok<WNON>
+                % Determine correlation text and color
+                corrText{end+1} = sprintf('corr=%1.4f (p=%1.4f)',rho,pcorr);
+                corrColor{end+1} = color;
+            end
+        end
+    end    
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Set Axes
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    
+    warning off %#ok<WNOFF>
+    if ~isempty(axesLimits),
+        % handle min X-axis limits if defined
+        if ~isempty(XLimMin),
+            if axesLimits(1) > XLimMin(1),
+                axesLimits(1) = XLimMin(1);
+            end
+            if axesLimits(2) < XLimMin(2),
+                axesLimits(2) = XLimMin(2);
+            end
+        end
+            
+        axis(axesLimits);
+    else
+        % Get max min values for x and y for each subplot
+        maxX = max(datak.(nameX));
+        minX = min(datak.(nameX));
+        maxY = max(datak.(nameY));
+        minY = min(datak.(nameY));
+        if minX==maxX,
+            maxX=minX+1;
+        end
+        if minY==maxY,
+            maxY=minY+1;
+        end
+        % Adjust maxY for titlebar
+        if logY==1,
+            rangenew =  1/(1-heighttitlebar-0.01)*(log10(maxY)-log10(minY));
+            maxY     = 10.^(log10(minY) + rangenew);
+        else
+            rangenew =  1/(1-heighttitlebar-0.01)*(maxY-minY);
+            maxY     = minY + rangenew;
+        end
+        
+        % handle min X-axis limits if defined
+        if ~isempty(XLimMin),
+            if minX > XLimMin(1),
+                minX = XLimMin(1);
+            end
+            if maxX < XLimMin(2),
+                maxX = XLimMin(2);
+            end
+        end
+        
+        % Set axes
+        if minX==maxX,
+            maxX = minX+1;
+        end
+        if isnan(minY),
+            minY = 0;
+        end
+        if isnan(maxY),
+            maxY = 0;
+        end
+        if minY==maxY,
+            maxY = minY+1;
+        end
+        axis([minX maxX minY maxY]);
+    end
+    warning on %#ok<WNON>
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Set axes fontsize for ticklabels
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    
+    set(gca,'FontUnits','points','FontSize',ticklabeltextsize);    
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Set axes color
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    
+    set(gca,'XColor',axescolor);    
+    set(gca,'YColor',axescolor);    
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Handle grid setting - switch minor grid off
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    if showgrid,
+        grid on
+        set(gca,'XMinorGrid','off');
+        set(gca,'YMinorGrid','off');
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Handle title (group)
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    if showtitlebar,
+        % Get axes limits
+        XLim = get(gca,'XLim');
+        YLim = get(gca,'YLim');
+        % Get X position for text
+        if logX==1,
+            X = 10^(log10(XLim(1)) + 0.5*(log10(XLim(2))-log10(XLim(1))));
+        else
+            X = XLim(1) + 0.5*(XLim(2)-XLim(1));
+        end
+        % Get Y position for text and title bar
+        if logY==1,
+            Y = 10^(log10(YLim(1)) + (1-heighttitlebar/2)*(log10(YLim(2))-log10(YLim(1))));
+            YtitlebarDN = 10^(log10(YLim(1)) + (1-heighttitlebar)*(log10(YLim(2))-log10(YLim(1))));
+            YtitlebarUP = 10^(log10(YLim(1)) + 1*(log10(YLim(2))-log10(YLim(1))));
+        else
+            Y = YLim(1) + (1-heighttitlebar/2)*(YLim(2)-YLim(1));
+            YtitlebarDN = YLim(1) + (1-heighttitlebar)*(YLim(2)-YLim(1));
+            YtitlebarUP = YLim(1) + 1*(YLim(2)-YLim(1));
+        end
+        % Create a title bar background
+        filled = [YtitlebarUP*[1 1],YtitlebarDN*[1 1]];
+        xpoints=[XLim,fliplr(XLim)];
+        fill(xpoints,filled,colortitlebar);
+        % Print the title text
+        text(X,Y,titleText,'FontWeight','bold','FontSize',titlefontsize,'HorizontalAlignment','Center','Interpreter','none');
+    end
+
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    % Show correlations
+    %%%%%%%%%%%%%%%%%%%%%%%%%
+    
+    if showcorrelations && showregressionline,
+        % Assume a maximum of 15 different lines (should be absolute max)
+        maxcorrtexts = 15; % Needed only for positioning
+        % Determine y locations
+        ncorrs = length(allGROUPcolor);
+        YLim = get(gca,'YLim');
+        XLim = get(gca,'XLim');
+        
+        if logY==1,
+            textY = 10.^(log10(YLim(1))+((1:maxcorrtexts)/(maxcorrtexts+1)-heighttitlebar)*(log10(YLim(2))-log10(YLim(1))));
+        else
+            textY = YLim(1)+((1:maxcorrtexts)/(maxcorrtexts+1)-heighttitlebar)*(YLim(2)-YLim(1));
+        end
+        if logX==1,
+            textX = 10.^(log10(XLim(1))+0.98*(log10(XLim(2))-log10(XLim(1))));
+        else
+            textX = XLim(1)+0.98*(XLim(2)-XLim(1));
+        end
+        for kcorr=1:ncorrs,
+            text(textX,textY(kcorr),corrText{kcorr},'Color',corrColor{kcorr},'FontWeight','bold','FontUnits','points','FontSize',correlationstextsize,'HorizontalAlignment','Right');
+        end
+    end
+    
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/Contents.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/Contents.m
new file mode 100644
index 0000000000000000000000000000000000000000..19a4440fc5d9c0f62fc693474a0514f09f84bb59
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/Contents.m
@@ -0,0 +1,297 @@
+% SBTOOLBOX2
+% Version $Rev: 1618 $ (R2010b-R2014a) $Date: 2014-08-06 11:56:03 +0200 (Wed, 06 Aug 2014) $
+% 
+% Installation of Toolbox
+% =======================
+%   installSB           - Installation script for the SBTOOLBOX2. Edit the 
+%                         script to match your system and run it
+%   lookforSB           - Searches SBTOOLBOX2 functions for strings and
+%                         opens the documents in which these strings appear
+%   checkDependenciesSB - Checks dependencies of SBPOP PACKAGE functions
+%                         from functions in the
+%                         _ACADEMIC/_EXPLORATORY/_DEPRECATED folders
+%                       
+% Model creation and handling
+% ===========================
+%   SBmodel             - Creating a new SBmodel
+%   SBstruct            - Returns the internal data structure of an SBmodel
+%   SBedit              - Graphical user interface for editing SBmodels in 
+%                         an ODE representation
+%   SBeditBC            - Graphical user interface for editing SBmodels in
+%                         a more biochemically oriented representation
+%   isSBmodel           - checks if the given argument is an SBmodel
+%   cleanmodelSB        - Remove unused reactions, variables and parameters
+%                         from an SBmodel
+%   SBmodelnotes        - Returns the notes stored in an SBmodel
+%   SBstates            - Returns information about states in an SBmodel
+%                         (statenames, a cell-array with names of states in model
+%   SBinitialconditions - Sets or returns initial conditions of the states
+%                         in the model
+%   SBalgebraic         - Returns information about algebraic rules in the
+%                         model
+%   SBparameters        - Returns parameter names and values in an SBmodel
+%                         or ODE file model. Also used to change parameter
+%                         values
+%   SBvariables         - Returns information about variables in an
+%                         SBmodel (variable names and formulas, but 
+%                         also the variable values for given state)
+%   SBreactions         - Returns information about reactions in an SBmodel
+%                         (reaction names and formulas of kinetic laws, but 
+%                         also the reaction rates for given state)
+%   SBfunctions         - Returns information about functions in an SBmodel
+%                         (functions names, arguments, and formulas)
+%   SBevents            - Returns information about events in an SBmodel
+%                         (names,triggers,assignment variables, and assignment 
+%                         formulas)
+%   SBfunctionsMATLAB   - Returns information about MATLAB functions in an
+%                         SBmodel
+%
+%   isparameterSB       - checks if a given "name" is a parameter in given model
+%   isstateSB           - checks if a given "name" is a state in given model
+%   isvariableSB        - checks if a given "name" is a variable in given model
+%   isreactionSB        - checks if a given "name" is a reaction in given model
+%
+%   stateindexSB        - returns the number of given state in given model
+%   variableindexSB     - returns the number of given variable in given model
+%   reactionindexSB     - returns the number of given reaction in given model
+%
+%   usedelaySB          - checks if the given model uses delay functions
+%   useeventSB          - checks if the given model uses events
+%   usealgebraicSB      - checks if the given model contains algebraic rules
+%   usefastSB           - checks if the given model contains fast reactions
+%
+%   hasmoietyconservationsSB - checks if the given model contains moiety
+%                              conservations
+%   addparametersSB          - adds a parameter with given name and given value
+%                              to an SBmodel. 
+%   hasonlynumericICsSB      - checks if the model contains only numeric initial
+%                              conditions. The model can be an SBmodel or an
+%                              ODE or MEX file model
+%   SBcalcICvector           - determines an initial condition vector for
+%                              models with non-numeric initial conditions
+%   SBconvertNonNum2NumIC    - converts non-numeric inital conditions to
+%                              numeric initial conditions in the model and
+%                              returns the updated model 
+%   SBoverwriteICs           - sets new initial conditions, specified as
+%                              input argument. If the input model contains
+%                              non-numeric initial conditions, these are
+%                              overwritten (in contrast, the function
+%                              SBinitialconditions only overwrites the ICs
+%                              that are defined by numerical values)
+%
+% Experiment creation and handling
+% ================================
+%   SBexperiment        - Creating a new SBexperiment object
+%   SBstruct            - Returns the internal data structure of an
+%                         SBexperiment object as a MATLAB structure
+%   SBcreateEXPfile     - Exports an SBexperiment object to a text file
+%                         description 
+%   SBmergemodexp       - Merges a model with an experiment description
+%   isSBexperiment      - checks if the given argument is an SBexperiment
+%
+% Measurement creation and handling
+% =================================
+%   SBmeasurement           - Creating a new SBmeasurement
+%   SBstruct                - Returns the internal data structure of an 
+%                             SBmeasurement
+%   SBmeasurementdata       - Allows to extract information about the
+%                             measurement data stored in an SBmeasurement
+%   SBexportCSVmeasurement  - Exporting an SBmeasurement to a CSV file 
+%   SBexportXLSmeasurement  - Exporting an SBmeasurement to an Excel file
+%   SBexportXLSmeasurements - Exporting several SBmeasurement objects to
+%                             the same Excel file 
+%   SBvisualizemeasurement  - Visualizing data in an SBmeasurement graphically 
+%   isSBmeasurement         - checks if the given argument is an
+%                             SBmeasurement
+%
+% Export of SBmodel
+% =================
+%   SBcreateODEfile     - Converting an SBmodel to an ODE file
+%   SBcreateTempODEfile - Same as SBcreateODEfile but ODE file is created
+%                         in the systems temporary directory
+%   deleteTempODEfileSB - Deletes the temporary ODE file 
+%   SBcreateTEXTfile    - Converting an SBmodel to a ODE text file description
+%   SBcreateTEXTBCfile  - Converting an SBmodel to a biochemical oriented text 
+%                         file description
+%   SBexportSBML        - Exporting SBmodel to SBML Level 2 Version 1
+%   SBconvert2MA        - Converting an SBmodel only containing reactions
+%                         with mass action kinetics to a structure
+%                         containing information about stoichiometry,
+%                         kinetic parameters, and initial conditions
+%
+% Simulation Functions
+% ====================
+%   SBsimulate              - Deterministic simulation of an SBmodel or an 
+%                             ODE file
+%   SBstochsim              - Stochastic simulation of SBmodels, only
+%                             containing reactions with mass action
+%                             kinetics. 
+% 
+% Plotting Functions
+% ==================
+%   SBplot                   - (GUI) Plots time-series data
+%   SBplot2                  - (GUI) Plots different kind of data where a bar
+%                              diagram representation is useful. So far mainly
+%                              used for displaying results from parameter
+%                              sensitivity analysis 
+%  createdatastructSBplotSB  - Generates a datastructure based on user defined 
+%                              inputes that can be plotted using SBplot 
+%  createdatastruct2SBplotSB - Generates a datastructure based on
+%                              simulation results returned from SBsimulate
+%                              or SBPDsimulate to be plotted by SBplot
+%  SBbarplotErrors           - Plotting bar plots with error bars
+%
+% Simple Analysis Functions
+% =========================
+%   SBsteadystate           - Determines the steady-state of an SBmodel or an 
+%                             ODE file model, dealing also with singular
+%                             systems
+%   SBjacobian              - Determines the Jacobian of an SBmodel or an ODE 
+%                             file
+%   SBmoietyconservations   - Determines the moitey conservations and/or other 
+%                             conservations that are present in a model
+%   SBreducemodel           - Reduces a singular model to a non-singular by 
+%                             deleting algebraic realtions
+%   SBstoichiometry         - Determines the stoichiometric matrix for the 
+%                             given model
+%   SBreactantstoichiometry - Determines the stoichiometric coefficients
+%                             for the reactants only
+%   SBmakeirreversible      - Converting all reversible reactions in an
+%                             SBmodel to irreversible ones
+%
+% Local Parameter Sensitivity Analysis
+% ====================================
+%   SBsensdataosc       - Generating data for the parameter sensitivity 
+%                         analysis of oscillating systems
+%   SBsensdataoscevents - Generating data for the parameter sensitivity 
+%                         analysis of oscillating systems in the case that
+%                         events are present in the model
+%   SBsensamplitude     - Parameter sensitivity analysis of the oscillation
+%                         amplitude. Uses data generated by SBsensdataosc
+%   SBsensperiod        - Parameter sensitivity analysis of the oscillation
+%                         period. Uses data generated by SBsensdataosc
+%   SBsensdatastat      - Generating data for the parameter sensitivity 
+%                         analysis of the steady-state of systems
+%   SBsensstat          - Parameter sensitivity analysis of the
+%                         steady-state values of states, variables, and 
+%                         reaction rates (can be seen as a generalized MCA)
+%   SBmca               - Metabolic Control Analysis (MCA). Function
+%                         calculating Flux Control Coefficients,
+%                         Concentration Control Coefficients, and
+%                         Elasticity Coefficients 
+%
+% Global Parameter Sensitivity Analysis
+% =====================================
+%   SBsensglobalfast    - Extended FAST 
+%   SBsensglobalprcc    - PRCC (Partial Rank Correlation Coefficient) 
+%   SBsensglobalsobol   - Sobols method
+%   SBsensglobalwals    - WALS (weighted average of local sensitivities)
+%
+% Localization of mechanisms leading to complex behaviors
+% =======================================================
+%   SBlocbehavcomp      - Determines the importance of components in the 
+%                         given biochemical system in the creation of an 
+%                         observed complex behavior such as multiple 
+%                         steady-states and sustained oscillations.
+%   SBlocbehavinteract  - Determines the importance of direct interactions
+%                         between components in the given biochemical system 
+%                         in the creation of an observed complex behavior 
+%                         such as multiple steady-states and sustained 
+%                         oscillations.
+%   SBlocbehavinteract2 - In principle the same as SBlocbehavinteract, but 
+%                         possible to use for open-loop unstable systems.
+%                         See help text for more information.
+%
+% Optimization
+% ============
+%   simplexSB           - Local minimization function using downhill
+%                         simplex method (Nelder-Mead) (constrained)
+%   simannealingSB      - Global minimization function based on simulated
+%                         annealing (constrained)
+%   isresSB             - Stochastic ranking for constrained evolutionary
+%                         minimization algorithm (constrained)
+%   pswarmSB            - Particle swarm pattern search algorithm for
+%                         global optimization (constrained)
+%   SSmSB               - Interface to a global optimization algorithm for
+%                         MINLP's based on Scatter Search (constrained). 
+%   fSSmSB              - Interface to a global optimization algorithm for
+%                         MINLP's based on Scatter Search ("fast" version)
+%                         (constrained). 
+%
+% Solvers
+% =======
+%   fsolveSB            - Solver for nonlinear equations
+%
+% Statistics
+% ==========
+%   clusteringSB        - Performs UPGMA on distance matrix and produces a
+%                         dendrogram plot
+%   pdistSB             - Determines the distance matrix for a set of points whose
+%                         coordinates are given as row-vectors in the data matrix
+%   prctileSB           - Determines the percentiles of a sample, based on interpolation
+%   boxplotSB           - Plots a box-and-whisker diagram for the given data
+%   princompSB          - Compute principal components of a data matrix
+%   other functions     - additional functions useful for statistical
+%                         analysis are present in the
+%                         SBTOOLBOX2/tools/statistic/other folder. 
+%
+% Signal
+% ======
+%   xcorrSB             - Compute correlation R_xy of X and Y for various lags k
+%   resampleSB          - resamples time series x1, which is sampled at the time
+%                         instances t1 to time series x2 using a sampling
+%                         defined by t2
+%   postpadSB           - Extends a vector or matrix in the given dimension
+%                         with given values to a given length by appending
+%                         the values
+%   prepadSB            - Extends a vector or matrix in the given dimension
+%                         with given values to a given length by adding the
+%                         values at the beginning
+%   centeredfftSB       - Uses the fft function of MATLAB to determine a 
+%                         two sided spectrum of a data vector
+%   positivefftSB       - Uses the fft function of MATLAB to determine a 
+%                         one sided spectrum of a data vector
+%
+% String handling functions
+% =========================
+%   explodePCSB         - auxiliary function allowing to decompose a
+%                         string expression into separated elements. The separation 
+%                         character can be specified. Commas within parentheses 
+%                         expressions are not considered
+%   extractPSB          - This function looks for the top level parentheses in the
+%                         given text string and returns the substring that
+%                         is located between these parentheses
+%
+% Special functions that can be used in models
+% ============================================
+%   andSB               - logical "and" to be used in model descriptions
+%   orSB                - logical "or" to be used in model descriptions
+%   piecewiseSB         - implementation of the SBML/MathML piecewise operator
+%   interp0SB           - lookup table with zero-order interpolation
+%   interp1SB           - lookup table with linear interpolation
+%   interpcsSB          - lookup table with cubic spline interpolation
+%   interpcseSB         - lookup table with cubic spline interpolation with
+%                         endpoint slopes
+%   delaySB             - delay function
+%   minSB               - min function for more than 2 arguments
+%   maxSB               - max function for more than 2 arguments
+
+% Information:
+% ============
+% Copyright (C) 2005-2010 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/auxiliary/plotting/xticklabel_rotate.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/auxiliary/plotting/xticklabel_rotate.m
new file mode 100644
index 0000000000000000000000000000000000000000..27de669d2925c947a17ac75794efbfd76b191570
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/auxiliary/plotting/xticklabel_rotate.m
@@ -0,0 +1,203 @@
+function hText = xticklabel_rotate(XTick,rot,varargin)
+%hText = xticklabel_rotate(XTick,rot,XTickLabel,varargin)     Rotate XTickLabel
+%
+% Syntax: xticklabel_rotate
+%
+% Input:    
+% {opt}     XTick       - vector array of XTick positions & values (numeric) 
+%                           uses current XTick values by default (if empty)
+% {opt}     rot         - angle of rotation in degrees, 90� by default
+% {opt}     XTickLabel  - cell array of label strings
+% {opt}     [var]       - "Property-value" pairs passed to text generator
+%                           ex: 'interpreter','none'
+%                               'Color','m','Fontweight','bold'
+%
+% Output:   hText       - handle vector to text labels
+%
+% Example 1:  Rotate existing XTickLabels at their current position by 90�
+%    xticklabel_rotate
+%
+% Example 2:  Rotate existing XTickLabels at their current position by 45�
+%    xticklabel_rotate([],45)
+%
+% Example 3:  Set the positions of the XTicks and rotate them 90�
+%    figure;  plot([1960:2004],randn(45,1)); xlim([1960 2004]);
+%    xticklabel_rotate([1960:2:2004]);
+%
+% Example 4:  Use text labels at XTick positions rotated 45� without tex interpreter
+%    xticklabel_rotate(XTick,45,NameFields,'interpreter','none');
+%
+% Example 5:  Use text labels rotated 90� at current positions
+%    xticklabel_rotate([],90,NameFields);
+%
+% Note : you can not re-run xticklabel_rotate on the same graph
+
+% This is a modified version of xticklabel_rotate90 by Denis Gilbert
+% Modifications include Text labels (in the form of cell array)
+%                       Arbitrary angle rotation
+%                       Output of text handles
+%                       Resizing of axes and title/xlabel/ylabel positions to maintain same overall size 
+%                           and keep text on plot
+%                           (handles small window resizing after, but not well due to proportional placement with 
+%                           fixed font size. To fix this would require a serious resize function)
+%                       Uses current XTick by default
+%                       Uses current XTickLabel is different from XTick values (meaning has been already defined)
+
+% Brian FG Katz
+% bfgkatz@hotmail.com
+% 23-05-03
+
+% Other m-files required: cell2mat
+% Subfunctions: none
+% MAT-files required: none
+%
+% See also: xticklabel_rotate90, TEXT,  SET
+
+% Based on xticklabel_rotate90
+%   Author: Denis Gilbert, Ph.D., physical oceanography
+%   Maurice Lamontagne Institute, Dept. of Fisheries and Oceans Canada
+%   email: gilbertd@dfo-mpo.gc.ca  Web: http://www.qc.dfo-mpo.gc.ca/iml/
+%   February 1998; Last revision: 24-Mar-2003
+
+% check to see if xticklabel_rotate has already been here (no other reasdon for this to happen)
+if isempty(get(gca,'XTickLabel')),
+    error('xticklabel_rotate : can not process, either xticklabel_rotate has already been run or XTickLabel field has been erased')  ;
+end
+
+% if no XTickLabel AND no XTick are defined use the current XTickLabel
+if nargin < 3 & (~exist('XTick') | isempty(XTick)),
+    xTickLabels = get(gca,'XTickLabel')  ; % use current XTickLabel
+    if verLessThan('matlab','8.4'),
+        % remove trailing spaces if exist (typical with auto generated XTickLabel)
+        temp1 = num2cell(xTickLabels,2)         ;
+        for loop = 1:length(temp1),
+            temp1{loop} = deblank(temp1{loop})  ;
+        end
+        xTickLabels = temp1                     ;
+    end
+end
+
+% if no XTick is defined use the current XTick
+if (~exist('XTick') | isempty(XTick)),
+    XTick = get(gca,'XTick')        ; % use current XTick 
+end
+
+%Make XTick a column vector
+XTick = XTick(:);
+
+if ~exist('xTickLabels'),
+	% Define the xtickLabels 
+	% If XtickLabel is passed as a cell array then use the text
+	if (length(varargin)>0) & (iscell(varargin{1})),
+        xTickLabels = varargin{1};
+        varargin = varargin(2:length(varargin));
+	else
+        xTickLabels = num2str(XTick);
+	end
+end    
+
+if length(XTick) ~= length(xTickLabels),
+    error('xticklabel_rotate : must have smae number of elements in "XTick" and "XTickLabel"')  ;
+end
+
+%Set the Xtick locations and set XTicklabel to an empty string
+set(gca,'XTick',XTick,'XTickLabel','')
+
+if nargin < 2,
+    rot = 90 ;
+end
+
+% Determine the location of the labels based on the position
+% of the xlabel
+hxLabel = get(gca,'XLabel');  % Handle to xlabel
+xLabelString = get(hxLabel,'String');
+
+% if ~isempty(xLabelString)
+%    warning('You may need to manually reset the XLABEL vertical position')
+% end
+
+set(hxLabel,'Units','data');
+xLabelPosition = get(hxLabel,'Position');
+y = xLabelPosition(2);
+
+%CODE below was modified following suggestions from Urs Schwarz
+y=repmat(y,size(XTick,1),1);
+% retrieve current axis' fontsize
+fs = get(gca,'fontsize');
+
+% Place the new xTickLabels by creating TEXT objects
+hText = text(XTick, y, xTickLabels,'fontsize',fs);
+
+% Rotate the text objects by ROT degrees
+set(hText,'Rotation',rot,'HorizontalAlignment','right',varargin{:})
+
+% Adjust the size of the axis to accomodate for longest label (like if they are text ones)
+% This approach keeps the top of the graph at the same place and tries to keep xlabel at the same place
+% This approach keeps the right side of the graph at the same place 
+
+set(get(gca,'xlabel'),'units','data')           ;
+    labxorigpos_data = get(get(gca,'xlabel'),'position')  ;
+set(get(gca,'ylabel'),'units','data')           ;
+    labyorigpos_data = get(get(gca,'ylabel'),'position')  ;
+set(get(gca,'title'),'units','data')           ;
+    labtorigpos_data = get(get(gca,'title'),'position')  ;
+
+set(gca,'units','pixel')                        ;
+set(hText,'units','pixel')                      ;
+set(get(gca,'xlabel'),'units','pixel')          ;
+set(get(gca,'ylabel'),'units','pixel')          ;
+
+origpos = get(gca,'position')                   ;
+textsizes = cell2mat(get(hText,'extent'))       ;
+longest =  max(textsizes(:,4))                  ;
+
+laborigext = get(get(gca,'xlabel'),'extent')    ;
+laborigpos = get(get(gca,'xlabel'),'position')  ;
+
+
+labyorigext = get(get(gca,'ylabel'),'extent')   ;
+labyorigpos = get(get(gca,'ylabel'),'position') ;
+leftlabdist = labyorigpos(1) + labyorigext(1)   ;
+
+% assume first entry is the farthest left
+leftpos = get(hText(1),'position')              ;
+leftext = get(hText(1),'extent')                ;
+leftdist = leftpos(1) + leftext(1)              ;
+if leftdist > 0,    leftdist = 0 ; end          % only correct for off screen problems
+
+botdist = origpos(2) + laborigpos(2)            ;
+newpos = [origpos(1)-leftdist longest+botdist origpos(3)+leftdist origpos(4)-longest+origpos(2)-botdist]  ;
+set(gca,'position',newpos)                      ;
+
+% readjust position of nex labels after resize of plot
+set(hText,'units','data')                       ;
+for loop= 1:length(hText),
+    set(hText(loop),'position',[XTick(loop), y(loop)])  ;
+end
+
+
+% adjust position of xlabel and ylabel
+laborigpos = get(get(gca,'xlabel'),'position')  ;
+set(get(gca,'xlabel'),'position',[laborigpos(1) laborigpos(2)-longest 0])   ;
+
+% switch to data coord and fix it all
+set(get(gca,'ylabel'),'units','data')                   ;
+set(get(gca,'ylabel'),'position',labyorigpos_data)      ;
+set(get(gca,'title'),'position',labtorigpos_data)       ;
+
+set(get(gca,'xlabel'),'units','data')                   ;
+    labxorigpos_data_new = get(get(gca,'xlabel'),'position')  ;
+set(get(gca,'xlabel'),'position',[labxorigpos_data(1) labxorigpos_data_new(2)])   ;
+
+
+% Reset all units to normalized to allow future resizing
+set(get(gca,'xlabel'),'units','normalized')          ;
+set(get(gca,'ylabel'),'units','normalized')          ;
+set(get(gca,'title'),'units','normalized')          ;
+set(hText,'units','normalized')                      ;
+set(gca,'units','normalized')                        ;
+
+if nargout < 1,
+    clear hText
+end
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/SBexportSBML.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/SBexportSBML.m
new file mode 100644
index 0000000000000000000000000000000000000000..64bc64b07bc954eecef7952a4f2664c5416d8b9f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/SBexportSBML.m
@@ -0,0 +1,863 @@
+function [] = SBexportSBML(sbm, varargin)
+% SBexportSBML 
+% exports an SBmodel to an SBML Level 2 model using the OutputSBML function
+% from the SBML toolbox. Non-numeric ICs are not handled but converted to
+% numeric ICs.
+%
+% IMPORTANT:
+% ==========
+% To export a model, the user is required to provide correct information in 
+% the "type,compartment,unittype" fields of the internal SBmodel data structure.
+%
+% This information can be added by directly editing the models structure,
+% or by providing the information in the model text representation.
+%
+% 1) Editing the structure
+% ------------------------
+% The model structure is obtained by typing "modelstruct = SBstruct(sbmodel)"
+% The 'states', 'algebraic', 'parameters', and 'variables' fields of the structure have the 
+% following subfields that need to be set to correct values.
+%   subfields       needed content          comment
+%   'type':      	'isSpecie'              in case the state/parameter/variable in
+%                                           the SBmodel is an SBML specie
+%                   'isParameter'           in case the state/parameter/variable in
+%                                           the SBmodel is an SBML
+%                                           parameter
+%                   'isCompartment'         in case the state/parameter/variable in
+%                                           the SBmodel is an SBML compartment
+%
+%   'compartment':  specie compartment      if type='isSpecie' it defines the name of the
+%                                           compartment the specie is located in.
+%                   outside compartment     if type='isCompartment' it defined the name 
+%                                           of the compartment outside
+%                   ''                      if type='isParameter' or type='isCompartment' 
+%                                           and there is no outside compartment or 
+%                                           type='isSpecie' and there is no
+%                                           compartment defined.
+%
+%   'unittype':     'amount'                if type='isSpecie' and the
+%   species units 
+%                                           are in 'amount'
+%                   'concentration'         if type='isSpecie' and the species units 
+%                                           are in 'concentration'
+%                   ''                      if type is not 'isSpecie'                   
+%
+% 2) Providing the information in the model text description, by SBedit,
+%    SBeditBC or directly by editing text files
+% ----------------------------------------------------------------------
+% For each state, parameter, and variable the additional information has
+% the following syntax:
+%
+% {type:compartment:unittype}
+%
+% where 'type', 'compartment', and 'unittype' is defined as above.
+% This argument needs to be placed in each definition of a state,
+% algebraic, parameter, and variable just before the optional comment.
+%
+% Example:
+% --------
+% An example model that has been correctly prepared for SBML export 
+% is defined in the file SBTOOLBOX2/examples/exampleSBMLexport.txt
+%
+% USAGE:
+% ======
+% [] = SBexportSBML(model)
+%
+% model: SBmodel to export to SBML
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+academicWarningSB
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE NON NUMERIC ICs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~hasonlynumericICsSB(sbm),
+    sbm = SBconvertNonNum2NumIC(sbm);
+    disp('Model contains non-numeric initial conditions. For the SBML export');
+    disp('these are converted to numeric ones using the SBconvertNonNum2NumIC function.');
+end
+
+
+skipSBMLpreset = 0;
+if nargin == 2,
+    skipSBMLpreset = varargin{1};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PREPROCESS and CHECK SBmodel (fill type, compartment, unittype fields if possible)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~skipSBMLpreset,
+    sbm = SBmakeSBMLpresets(sbm);
+end
+
+% test wether all name fields are filled and are unique
+namesOK = checkNamesInSBmodel(sbm, 1);
+if ~namesOK,
+    errorMessage{1} = 'SBML export aborted because of errors concerning the names used in the given SBmodel. For further information use "checkNamesInSBmodel" function!';
+    messageOutput(errorMessage, 1);
+    return    
+end
+% if test shows that model isn't SBML compliant abort export
+[sbmlCompliant, onlyCompartmentError] = testSBMLsettings(sbm, 1);
+if ~sbmlCompliant,
+    if onlyCompartmentError,
+        sbm = addDefaultCompartment(sbm);
+    else
+        errorMessage{1} = 'SBML export aborted because of errors concerning the SBML compliance. For further information use "testSBMLsettings" function!';
+        messageOutput(errorMessage, 1);
+        return
+    end
+end
+
+% convert object to structure
+ms = struct(sbm);  
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF MODEL CONTAINS MATLAB FUNCTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(ms.functionsMATLAB),
+    error('Model contains MATLAB functions. Such functions are not supported in SBML.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE STOICHIOMETRIX MATRIX and related stuff (to determine if
+% boundary species or species)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[StoichiometricMatrix,SBMLspeciesNames,SBMLreactionNames,SBMLreversibleFlag] = SBstoichiometry(sbm,1,1);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CREATE AN EMPTY SBML MATLAB STRUCTURE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create empty SBMLstructure
+% functionDefinition substructure
+functionDefinitionStruct = struct('typecode', {}, 'metaid', '', 'notes', {}, 'annotation', {}, 'name', {}, 'id', {}, 'math', {});
+% unitDefinition substructure
+unitDefinitionStruct = struct('typecode',{}, 'metaid', '','notes',{},'annotation',{}, 'name', {}, 'id', {}, 'unit', {});
+% compartment substructure
+compartmentStruct = struct('typecode', {}, 'metaid', '', 'notes', {}, 'annotation', {}, 'name', {}, 'id', {}, 'spatialDimensions', {}, 'size', {}, 'units', {}, 'outside', {}, 'constant', {}, 'isSetSize', {}, 'isSetVolume', {});
+% species substructure
+speciesStruct = struct('typecode', {}, 'metaid', '', 'notes', {}, 'annotation', {}, 'name', {},'id', {}, 'compartment', {}, 'initialAmount', {}, 'initialConcentration', {}, 'substanceUnits', {}, 'spatialSizeUnits', {}, 'hasOnlySubstanceUnits', {}, 'boundaryCondition', {}, 'charge', {}, 'constant', {}, 'isSetInitialAmount', {}, 'isSetInitialConcentration', {}, 'isSetCharge', {});
+% parameter substructure
+parameterStruct = struct('typecode', {}, 'metaid', '', 'notes', {}, 'annotation', {}, 'name', {}, 'id', {}, 'value', {}, 'units', {}, 'constant', {}, 'isSetValue', {});
+% rule substructure
+ruleStruct = struct('typecode', {}, 'metaid', '', 'notes', {}, 'annotation', {}, 'formula', {}, 'variable', {}, 'species', {}, 'compartment', {}, 'name', {}, 'units', {});
+% reaction substructure
+reactantStruct = struct('typecode', {}, 'metaid', '', 'notes', {}, 'annotation', {}, 'species', {}, 'stoichiometry', {}, 'denominator', {}, 'stoichiometryMath', {});
+productStruct = struct('typecode', {}, 'metaid', '', 'notes', {}, 'annotation', {}, 'species', {}, 'stoichiometry', {}, 'denominator', {}, 'stoichiometryMath', {});
+modifierStruct = struct('typecode', {}, 'metaid', '', 'notes', {}, 'annotation', {}, 'species', {});
+kineticLawParameterStruct = struct('typecode', {}, 'metaid', '', 'notes', {}, 'annotation', {}, 'name', {}, 'id', {}, 'value', {}, 'units', {}, 'constant', {}, 'isSetValue', {});
+kineticLawStruct = struct('typecode', {}, 'metaid', '', 'notes', {}, 'annotation', {}, 'formula', {}, 'math', {}, 'parameter', kineticLawParameterStruct, 'timeUnits', {}, 'substanceUnits', {});
+reactionStruct = struct('typecode', {}, 'metaid', '', 'notes', {}, 'annotation', {}, 'name', {}, 'id', {}, 'reactant', reactantStruct, 'product', productStruct, 'modifier', modifierStruct, 'kineticLaw', kineticLawStruct, 'reversible', {}, 'fast', {}, 'isSetFast', {});
+eventStruct = struct('typecode', {}, 'metaid', '', 'notes', {}, 'annotation', {}, 'name', {}, 'id', {}, 'trigger', {}, 'delay', {}, 'timeUnits', {}, 'eventAssignment', {});
+namespaceStruct = struct('prefix', '', 'uri', 'http://www.sbml.org/sbml/level2');
+% Create SBstructure
+SBMLstructure = struct('typecode', 'SBML_MODEL',...
+                       'metaid', '', ...
+                       'notes', '', ...
+                       'annotation', '', ...
+                       'SBML_level', 2, ...
+                       'SBML_version', 1, ...
+                       'name', '', ...
+                       'id', '', ...
+                       'functionDefinition', functionDefinitionStruct, ...
+                       'unitDefinition', unitDefinitionStruct, ...
+                       'compartment', compartmentStruct, ...
+                       'species', speciesStruct, ...
+                       'parameter', parameterStruct, ...
+                       'rule', ruleStruct, ...
+                       'reaction', reactionStruct, ...
+                       'event', eventStruct, ...
+                       'time_symbol', 'time', ...
+                       'delay_symbol', '', ...
+                       'namespaces', namespaceStruct);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SOME VARIABLES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%                       
+ruleIndex = 1;
+parameterIndex = 1;
+compartmentIndex = 1;
+specieIndex = 1;
+                       
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% COPY NAME AND NOTES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%                       
+SBMLstructure.name = ms.name;
+SBMLstructure.notes = convert2SBMLNotes(ms.notes);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS COMPARTMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%                       
+% compartments can be defined as parameters, variables or states. 
+% If the field 'type' is set to 'isCompartment' it indicates a compartment. 
+% check parameters for compartments
+for k = 1:length(ms.parameters),
+    if strcmp(ms.parameters(k).type,'isCompartment'),
+        % current parameter determines compartment size
+        % always use spatial dimensions 3
+        SBMLstructure.compartment(compartmentIndex).typecode = 'SBML_COMPARTMENT';
+        SBMLstructure.compartment(compartmentIndex).metaid = '';
+        SBMLstructure.compartment(compartmentIndex).notes = convert2SBMLNotes(ms.parameters(k).notes);
+        SBMLstructure.compartment(compartmentIndex).annotation = '';
+        SBMLstructure.compartment(compartmentIndex).name = ms.parameters(k).name;
+        SBMLstructure.compartment(compartmentIndex).id = ms.parameters(k).name;
+        SBMLstructure.compartment(compartmentIndex).spatialDimensions = 3;
+        SBMLstructure.compartment(compartmentIndex).size = ms.parameters(k).value;
+        SBMLstructure.compartment(compartmentIndex).units = '';
+        SBMLstructure.compartment(compartmentIndex).outside = ms.parameters(k).compartment;
+        SBMLstructure.compartment(compartmentIndex).constant = 1;
+        SBMLstructure.compartment(compartmentIndex).isSetSize = 1;
+        SBMLstructure.compartment(compartmentIndex).isSetVolume = 1;
+        compartmentIndex = compartmentIndex + 1;
+    end
+end
+% check states for compartments
+for k = 1:length(ms.states),
+    if strcmp(ms.states(k).type,'isCompartment'),
+        % current state determines compartment size
+        % set size to initial condition of state
+        SBMLstructure.compartment(compartmentIndex).typecode = 'SBML_COMPARTMENT';
+        SBMLstructure.compartment(compartmentIndex).metaid = '';
+        SBMLstructure.compartment(compartmentIndex).notes = convert2SBMLNotes(ms.states(k).notes);
+        SBMLstructure.compartment(compartmentIndex).annotation = '';
+        SBMLstructure.compartment(compartmentIndex).name = ms.states(k).name;
+        SBMLstructure.compartment(compartmentIndex).id = ms.states(k).name;
+        SBMLstructure.compartment(compartmentIndex).spatialDimensions = 3;
+        SBMLstructure.compartment(compartmentIndex).size = ms.states(k).initialCondition;
+        SBMLstructure.compartment(compartmentIndex).units = '';
+        SBMLstructure.compartment(compartmentIndex).outside = ms.states(k).compartment;
+        SBMLstructure.compartment(compartmentIndex).constant = 0;
+        SBMLstructure.compartment(compartmentIndex).isSetSize = 1;
+        SBMLstructure.compartment(compartmentIndex).isSetVolume = 1;
+        compartmentIndex = compartmentIndex + 1;
+        % Compartment defined by a rule. Include this rule in the structure
+        SBMLstructure.rule(ruleIndex).typecode = 'SBML_RATE_RULE';
+        SBMLstructure.rule(ruleIndex).metaid = '';
+        SBMLstructure.rule(ruleIndex).notes = convert2SBMLNotes(ms.states(k).notes);
+        SBMLstructure.rule(ruleIndex).annotation = '';
+        SBMLstructure.rule(ruleIndex).formula = replaceMATLABexpressions(ms.states(k).ODE);
+        SBMLstructure.rule(ruleIndex).variable = ms.states(k).name;
+        SBMLstructure.rule(ruleIndex).species = '';
+        SBMLstructure.rule(ruleIndex).compartment = '';
+        SBMLstructure.rule(ruleIndex).name = '';
+        SBMLstructure.rule(ruleIndex).units = '';
+        ruleIndex = ruleIndex + 1;        
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS PARAMETERS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
+% parameters can be defined as parameters, variables or states. If the
+% field 'type' is set to 'isParameter' it indicates an SBML parameter.  
+% we only will have global parameters in the SBML model.
+% check parameters for parameters
+for k = 1:length(ms.parameters),
+    if strcmp(ms.parameters(k).type,'isParameter'),
+        % current parameter determines compartment size
+        SBMLstructure.parameter(parameterIndex).typecode = 'SBML_PARAMETER';
+        SBMLstructure.parameter(parameterIndex).metaid = '';
+        SBMLstructure.parameter(parameterIndex).notes = convert2SBMLNotes(ms.parameters(k).notes);
+        SBMLstructure.parameter(parameterIndex).annotation = '';
+        SBMLstructure.parameter(parameterIndex).name = ms.parameters(k).name;
+        SBMLstructure.parameter(parameterIndex).id = ms.parameters(k).name;
+        SBMLstructure.parameter(parameterIndex).value = ms.parameters(k).value;
+        SBMLstructure.parameter(parameterIndex).units = '';
+        SBMLstructure.parameter(parameterIndex).constant = 1;
+        SBMLstructure.parameter(parameterIndex).isSetValue = 1;
+        parameterIndex = parameterIndex + 1;
+    end
+end
+% check states for parameters
+for k = 1:length(ms.states),
+    if strcmp(ms.states(k).type,'isParameter'),
+        % current state determines compartment size
+        SBMLstructure.parameter(parameterIndex).typecode = 'SBML_PARAMETER';
+        SBMLstructure.parameter(parameterIndex).metaid = '';
+        SBMLstructure.parameter(parameterIndex).notes = convert2SBMLNotes(ms.states(k).notes);
+        SBMLstructure.parameter(parameterIndex).annotation = '';
+        SBMLstructure.parameter(parameterIndex).name = ms.states(k).name;
+        SBMLstructure.parameter(parameterIndex).id = ms.states(k).name;
+        SBMLstructure.parameter(parameterIndex).value = ms.states(k).initialCondition;
+        SBMLstructure.parameter(parameterIndex).units = '';
+        SBMLstructure.parameter(parameterIndex).constant = 0;
+        SBMLstructure.parameter(parameterIndex).isSetValue = 1;
+        parameterIndex = parameterIndex + 1;        
+        % Parameter defined by a rule. Include this rule in the structure
+        SBMLstructure.rule(ruleIndex).typecode = 'SBML_RATE_RULE';
+        SBMLstructure.rule(ruleIndex).metaid = '';
+        SBMLstructure.rule(ruleIndex).notes = convert2SBMLNotes(ms.states(k).notes);
+        SBMLstructure.rule(ruleIndex).annotation = '';
+        SBMLstructure.rule(ruleIndex).formula = replaceMATLABexpressions(ms.states(k).ODE);
+        SBMLstructure.rule(ruleIndex).variable = ms.states(k).name;
+        SBMLstructure.rule(ruleIndex).species = '';
+        SBMLstructure.rule(ruleIndex).compartment = '';
+        SBMLstructure.rule(ruleIndex).name = '';
+        SBMLstructure.rule(ruleIndex).units = '';
+        ruleIndex = ruleIndex + 1;        
+    end
+end            
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS FUNCTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
+% add functions
+for k = 1:length(ms.functions),
+    SBMLstructure.functionDefinition(k).typecode = 'SBML_FUNCTION_DEFINITION';
+    SBMLstructure.functionDefinition(k).metaid = '';
+    SBMLstructure.functionDefinition(k).notes = convert2SBMLNotes(ms.functions(k).notes);
+    SBMLstructure.functionDefinition(k).annotation = '';
+    SBMLstructure.functionDefinition(k).name = ms.functions(k).name;
+    SBMLstructure.functionDefinition(k).id = ms.functions(k).name;
+    SBMLstructure.functionDefinition(k).math = sprintf('lambda(%s,%s)',ms.functions(k).arguments,replaceMATLABexpressions(ms.functions(k).formula));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS CONSTANT (BOUNDARY) SPECIES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
+% constant species can only be defined as parameters.
+% If the field 'type' of a parameter is set to 'isSpecie' we assume that
+% this indicates a constant boundary species.
+for k = 1:length(ms.parameters),
+    if strcmp(ms.parameters(k).type,'isSpecie'),
+        % Determine if amount or concentration
+        if strcmp(ms.parameters(k).unittype,'amount'), 
+            isAmount = 1;
+            isConcentration = 0;
+            hasOnlySubstanceUnits = 1;
+        elseif strcmp(ms.parameters(k).unittype,'concentration'),
+            isAmount = 0;
+            isConcentration = 1;
+            hasOnlySubstanceUnits = 0;
+        end
+        % import constant boundary species
+        SBMLstructure.species(specieIndex).typecode = 'SBML_SPECIES';
+        SBMLstructure.species(specieIndex).metaid = '';
+        SBMLstructure.species(specieIndex).notes = convert2SBMLNotes(ms.parameters(k).notes);
+        SBMLstructure.species(specieIndex).annotation = '';
+        SBMLstructure.species(specieIndex).name = ms.parameters(k).name;
+        SBMLstructure.species(specieIndex).id = ms.parameters(k).name;
+        SBMLstructure.species(specieIndex).compartment = ms.parameters(k).compartment;
+        SBMLstructure.species(specieIndex).initialAmount = ms.parameters(k).value;
+        SBMLstructure.species(specieIndex).initialConcentration = ms.parameters(k).value;
+        SBMLstructure.species(specieIndex).substanceUnits = '';         % no units!
+        SBMLstructure.species(specieIndex).spatialSizeUnits = '';       % no units!
+        SBMLstructure.species(specieIndex).hasOnlySubstanceUnits = hasOnlySubstanceUnits;
+        SBMLstructure.species(specieIndex).boundaryCondition = 1;       % boundary 
+        SBMLstructure.species(specieIndex).charge = 0;                  
+        SBMLstructure.species(specieIndex).constant = 1;                % species is set constant
+        SBMLstructure.species(specieIndex).isSetInitialAmount = isAmount;
+        SBMLstructure.species(specieIndex).isSetInitialConcentration = isConcentration;
+        SBMLstructure.species(specieIndex).isSetCharge = 0;             % charge not supported
+        specieIndex = specieIndex + 1;
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS BOUNDARY SPECIES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
+% boundary species can be defined variables or states (not as parameters,
+% since then they become constant boundary species).
+% The difference between species and boundary species is here that species
+% are only defined by reactions, while boundary species are defined by
+% rules. The variable "SBMLspeciesNames" contains the names of all states
+% that are defined only by reactions.
+% now check states (boundary if isSpecie and not in the SBMLspeciesNames list)
+for k = 1:length(ms.states),
+    if strcmp(ms.states(k).type,'isSpecie') && isempty(strmatchSB(ms.states(k).name,SBMLspeciesNames)),
+        % Determine if amount or concentration
+        if strcmp(ms.states(k).unittype,'amount') 
+            isAmount = 1;
+            isConcentration = 0;
+            hasOnlySubstanceUnits = 1;
+        elseif strcmp(ms.states(k).unittype,'concentration') 
+            isAmount = 0;
+            isConcentration = 1;
+            hasOnlySubstanceUnits = 0;
+        end
+        % import boundary species
+        SBMLstructure.species(specieIndex).typecode = 'SBML_SPECIES';
+        SBMLstructure.species(specieIndex).metaid = '';
+        SBMLstructure.species(specieIndex).notes = convert2SBMLNotes(ms.states(k).notes);
+        SBMLstructure.species(specieIndex).annotation = '';
+        SBMLstructure.species(specieIndex).name = ms.states(k).name;
+        SBMLstructure.species(specieIndex).id = ms.states(k).name;
+        SBMLstructure.species(specieIndex).compartment = ms.states(k).compartment;
+        SBMLstructure.species(specieIndex).initialAmount = ms.states(k).initialCondition;
+        SBMLstructure.species(specieIndex).initialConcentration = ms.states(k).initialCondition;
+        SBMLstructure.species(specieIndex).substanceUnits = '';         % no units!
+        SBMLstructure.species(specieIndex).spatialSizeUnits = '';       % no units!
+        SBMLstructure.species(specieIndex).hasOnlySubstanceUnits = hasOnlySubstanceUnits;
+        SBMLstructure.species(specieIndex).boundaryCondition = 1;       % boundary 
+        SBMLstructure.species(specieIndex).charge = 0;                  
+        SBMLstructure.species(specieIndex).constant = 0;                % species is not set constant
+        SBMLstructure.species(specieIndex).isSetInitialAmount = isAmount;
+        SBMLstructure.species(specieIndex).isSetInitialConcentration = isConcentration;
+        SBMLstructure.species(specieIndex).isSetCharge = 0;             % charge not supported
+        specieIndex = specieIndex + 1;
+        % Boundary species defined by a rule. Include this rule in the structure
+        SBMLstructure.rule(ruleIndex).typecode = 'SBML_RATE_RULE';
+        SBMLstructure.rule(ruleIndex).metaid = '';
+        SBMLstructure.rule(ruleIndex).notes = convert2SBMLNotes(ms.states(k).notes);
+        SBMLstructure.rule(ruleIndex).annotation = '';
+        SBMLstructure.rule(ruleIndex).formula = replaceMATLABexpressions(ms.states(k).ODE);
+        SBMLstructure.rule(ruleIndex).variable = ms.states(k).name;
+        SBMLstructure.rule(ruleIndex).species = '';
+        SBMLstructure.rule(ruleIndex).compartment = '';
+        SBMLstructure.rule(ruleIndex).name = '';
+        SBMLstructure.rule(ruleIndex).units = '';
+        ruleIndex = ruleIndex + 1;
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS SPECIES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
+% we assume that species are only defined as states and determined by
+% reactions
+% check simple species defined by reactions
+% save the species name and the species ODE for use when processing the
+% reactions
+speciesReactions = [];
+for k = 1:length(ms.states),
+    if strcmp(ms.states(k).type,'isSpecie') && ~isempty(strmatchSB(ms.states(k).name,SBMLspeciesNames)),
+        % Determine if amount or concentration
+        if strcmp(ms.states(k).unittype,'amount') 
+            isAmount = 1;
+            isConcentration = 0;
+            hasOnlySubstanceUnits = 1;
+        elseif strcmp(ms.states(k).unittype,'concentration') 
+            isAmount = 0;
+            isConcentration = 1;
+            hasOnlySubstanceUnits = 0;
+        end
+        % import constant species
+        SBMLstructure.species(specieIndex).typecode = 'SBML_SPECIES';
+        SBMLstructure.species(specieIndex).metaid = '';
+        SBMLstructure.species(specieIndex).notes = convert2SBMLNotes(ms.states(k).notes);
+        SBMLstructure.species(specieIndex).annotation = '';
+        SBMLstructure.species(specieIndex).name = ms.states(k).name;
+        SBMLstructure.species(specieIndex).id = ms.states(k).name;
+        SBMLstructure.species(specieIndex).compartment = ms.states(k).compartment;
+        SBMLstructure.species(specieIndex).initialAmount = ms.states(k).initialCondition;
+        SBMLstructure.species(specieIndex).initialConcentration = ms.states(k).initialCondition;
+        SBMLstructure.species(specieIndex).substanceUnits = '';         % no units!
+        SBMLstructure.species(specieIndex).spatialSizeUnits = '';       % no units!
+        SBMLstructure.species(specieIndex).hasOnlySubstanceUnits = hasOnlySubstanceUnits;
+        SBMLstructure.species(specieIndex).boundaryCondition = 0;       % not boundary 
+        SBMLstructure.species(specieIndex).charge = 0;                  
+        SBMLstructure.species(specieIndex).constant = 0;                % species is not set constant
+        SBMLstructure.species(specieIndex).isSetInitialAmount = isAmount;
+        SBMLstructure.species(specieIndex).isSetInitialConcentration = isConcentration;
+        SBMLstructure.species(specieIndex).isSetCharge = 0;             % charge not supported
+        specieIndex = specieIndex + 1;
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS ASSIGNMENT RULES ... NEED TO BE ORDERED ... THUS HERE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k = 1:length(ms.variables),
+    if strcmp(ms.variables(k).type,'isCompartment'),
+        % current variable determines compartment size
+        % set size to 1 (not important, since not used)
+        SBMLstructure.compartment(compartmentIndex).typecode = 'SBML_COMPARTMENT';
+        SBMLstructure.compartment(compartmentIndex).metaid = '';
+        SBMLstructure.compartment(compartmentIndex).notes = convert2SBMLNotes(ms.variables(k).notes);
+        SBMLstructure.compartment(compartmentIndex).annotation = '';
+        SBMLstructure.compartment(compartmentIndex).name = ms.variables(k).name;
+        SBMLstructure.compartment(compartmentIndex).id = ms.variables(k).name;
+        SBMLstructure.compartment(compartmentIndex).spatialDimensions = 3;
+        SBMLstructure.compartment(compartmentIndex).size = 1;
+        SBMLstructure.compartment(compartmentIndex).units = '';
+        SBMLstructure.compartment(compartmentIndex).outside = ms.variables(k).compartment;
+        SBMLstructure.compartment(compartmentIndex).constant = 0;
+        SBMLstructure.compartment(compartmentIndex).isSetSize = 1;
+        SBMLstructure.compartment(compartmentIndex).isSetVolume = 1;
+        compartmentIndex = compartmentIndex + 1;
+        % Compartment defined by a rule. Include this rule in the structure
+        SBMLstructure.rule(ruleIndex).typecode = 'SBML_ASSIGNMENT_RULE';
+        SBMLstructure.rule(ruleIndex).metaid = '';
+        SBMLstructure.rule(ruleIndex).notes = convert2SBMLNotes(ms.variables(k).notes);
+        SBMLstructure.rule(ruleIndex).annotation = '';
+        SBMLstructure.rule(ruleIndex).formula = replaceMATLABexpressions(ms.variables(k).formula);
+        SBMLstructure.rule(ruleIndex).variable = ms.variables(k).name;
+        SBMLstructure.rule(ruleIndex).species = '';
+        SBMLstructure.rule(ruleIndex).compartment = '';
+        SBMLstructure.rule(ruleIndex).name = '';
+        SBMLstructure.rule(ruleIndex).units = '';
+        ruleIndex = ruleIndex + 1;
+    end
+    if strcmp(ms.variables(k).type,'isParameter'),
+        % current variable determines compartment size
+        % value set to zero (not needed)
+        SBMLstructure.parameter(parameterIndex).typecode = 'SBML_PARAMETER';
+        SBMLstructure.parameter(parameterIndex).metaid = '';
+        SBMLstructure.parameter(parameterIndex).notes = convert2SBMLNotes(ms.variables(k).notes);
+        SBMLstructure.parameter(parameterIndex).annotation = '';
+        SBMLstructure.parameter(parameterIndex).name = ms.variables(k).name;
+        SBMLstructure.parameter(parameterIndex).id = ms.variables(k).name;
+        SBMLstructure.parameter(parameterIndex).value = 0;  % no value needed (assignment rule)
+        SBMLstructure.parameter(parameterIndex).units = '';
+        SBMLstructure.parameter(parameterIndex).constant = 0;
+        SBMLstructure.parameter(parameterIndex).isSetValue = 1;
+        parameterIndex = parameterIndex + 1;        
+        % Parameter defined by a rule. Include this rule in the structure
+        SBMLstructure.rule(ruleIndex).typecode = 'SBML_ASSIGNMENT_RULE';
+        SBMLstructure.rule(ruleIndex).metaid = '';
+        SBMLstructure.rule(ruleIndex).notes = convert2SBMLNotes(ms.variables(k).notes);
+        SBMLstructure.rule(ruleIndex).annotation = '';
+        SBMLstructure.rule(ruleIndex).formula = replaceMATLABexpressions(ms.variables(k).formula);
+        SBMLstructure.rule(ruleIndex).variable = ms.variables(k).name;
+        SBMLstructure.rule(ruleIndex).species = '';
+        SBMLstructure.rule(ruleIndex).compartment = '';
+        SBMLstructure.rule(ruleIndex).name = '';
+        SBMLstructure.rule(ruleIndex).units = '';
+        ruleIndex = ruleIndex + 1;
+    end
+    if strcmp(ms.variables(k).type,'isSpecie'),
+        % Determine if amount or concentration
+        if strcmp(ms.variables(k).unittype,'amount'), 
+            isAmount = 1;
+            isConcentration = 0;
+            hasOnlySubstanceUnits = 1;
+        elseif strcmp(ms.variables(k).unittype,'concentration'), 
+            isAmount = 0;
+            isConcentration = 1;
+            hasOnlySubstanceUnits = 0;
+        end
+        % import boundary species
+        SBMLstructure.species(specieIndex).typecode = 'SBML_SPECIES';
+        SBMLstructure.species(specieIndex).metaid = '';
+        SBMLstructure.species(specieIndex).notes = convert2SBMLNotes(ms.variables(k).notes);
+        SBMLstructure.species(specieIndex).annotation = '';
+        SBMLstructure.species(specieIndex).name = ms.variables(k).name;
+        SBMLstructure.species(specieIndex).id = ms.variables(k).name;
+        SBMLstructure.species(specieIndex).compartment = ms.variables(k).compartment;
+        SBMLstructure.species(specieIndex).initialAmount = 0;  % not set (assignment rule)
+        SBMLstructure.species(specieIndex).initialConcentration = 0; % not set (assignment rule)
+        SBMLstructure.species(specieIndex).substanceUnits = '';         % no units!
+        SBMLstructure.species(specieIndex).spatialSizeUnits = '';       % no units!
+        SBMLstructure.species(specieIndex).hasOnlySubstanceUnits = hasOnlySubstanceUnits;
+        SBMLstructure.species(specieIndex).boundaryCondition = 1;       % boundary 
+        SBMLstructure.species(specieIndex).charge = 0;                  
+        SBMLstructure.species(specieIndex).constant = 0;                % species is not set constant
+        SBMLstructure.species(specieIndex).isSetInitialAmount = isAmount;
+        SBMLstructure.species(specieIndex).isSetInitialConcentration = isConcentration;
+        SBMLstructure.species(specieIndex).isSetCharge = 0;             % charge not supported
+        specieIndex = specieIndex + 1;
+        % Boundary species defined by a rule. Include this rule in the structure
+        SBMLstructure.rule(ruleIndex).typecode = 'SBML_ASSIGNMENT_RULE';
+        SBMLstructure.rule(ruleIndex).metaid = '';
+        SBMLstructure.rule(ruleIndex).notes = convert2SBMLNotes(ms.variables(k).notes);
+        SBMLstructure.rule(ruleIndex).annotation = '';
+        SBMLstructure.rule(ruleIndex).formula = replaceMATLABexpressions(ms.variables(k).formula);
+        SBMLstructure.rule(ruleIndex).variable = ms.variables(k).name;
+        SBMLstructure.rule(ruleIndex).species = '';
+        SBMLstructure.rule(ruleIndex).compartment = '';
+        SBMLstructure.rule(ruleIndex).name = '';
+        SBMLstructure.rule(ruleIndex).units = '';
+        ruleIndex = ruleIndex + 1;
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS REACTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Before processing the reactions we are checking for moiety conservations
+% and reversing them into the stoichiometric matrix (to be able to draw the
+% full picture)
+[StoichiometricMatrix,SBMLspeciesNames] = reverseMoietyConservationsSB(sbm, 1);
+for k1 = 1:length(ms.reactions),
+    reactionName = ms.reactions(k1).name;
+    reactionFormula = ms.reactions(k1).formula;
+    % get needed information about reaction
+    [reactant, product, modifier] = getReactionInfo(reactionName,StoichiometricMatrix,SBMLspeciesNames,SBMLreactionNames,SBMLreversibleFlag,sbm,ms);
+    % add reaction to the structure
+    SBMLstructure.reaction(k1).typecode = 'SBML_REACTION';
+    SBMLstructure.reaction(k1).metaid = '';
+    SBMLstructure.reaction(k1).notes = convert2SBMLNotes(ms.reactions(k1).notes);
+    SBMLstructure.reaction(k1).annotation = '';
+    SBMLstructure.reaction(k1).name = reactionName;
+    SBMLstructure.reaction(k1).id = reactionName;
+    
+    SBMLstructure.reaction(k1).reactant = reactant;
+    SBMLstructure.reaction(k1).product = product;
+    SBMLstructure.reaction(k1).modifier = modifier; 
+    
+    SBMLstructure.reaction(k1).kineticLaw.typecode = 'SBML_KINETIC_LAW';
+    SBMLstructure.reaction(k1).kineticLaw.metaid = '';
+    SBMLstructure.reaction(k1).kineticLaw.notes = '';
+    SBMLstructure.reaction(k1).kineticLaw.annotation = '';
+    SBMLstructure.reaction(k1).kineticLaw.formula = replaceMATLABexpressions(reactionFormula);
+    SBMLstructure.reaction(k1).kineticLaw.math = replaceMATLABexpressions(reactionFormula);
+    SBMLstructure.reaction(k1).kineticLaw.parameter = kineticLawParameterStruct;    % no local parameters
+    
+    SBMLstructure.reaction(k1).kineticLaw.timeUnits = '';
+    SBMLstructure.reaction(k1).kineticLaw.substanceUnits = '';
+    
+    SBMLstructure.reaction(k1).reversible = ms.reactions(k1).reversible;
+    
+    % handle set the fast flag
+    if ms.reactions(k1).fast == 0,
+        SBMLstructure.reaction(k1).fast = 0;
+        SBMLstructure.reaction(k1).isSetFast = 0;
+    else
+        SBMLstructure.reaction(k1).fast = 1;
+        SBMLstructure.reaction(k1).isSetFast = 1;
+    end        
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% LEAVE UNITDEFINITIONS EMPTY
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%                       
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Process Events
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%                       
+for k1=1:length(ms.events),
+    SBMLstructure.event(k1).typecode = 'SBML_EVENT';
+    SBMLstructure.event(k1).metaid = '';
+    SBMLstructure.event(k1).notes = convert2SBMLNotes(ms.events(k1).notes);
+    SBMLstructure.event(k1).annotation = '';
+    SBMLstructure.event(k1).name = ms.events(k1).name;
+    SBMLstructure.event(k1).id = ms.events(k1).name;
+    SBMLstructure.event(k1).trigger = replaceMATLABexpressions(ms.events(k1).trigger);
+    SBMLstructure.event(k1).delay = '0'; % always zero
+    SBMLstructure.event(k1).timeUnits = '';
+    for k2 = 1:length(ms.events(k1).assignment),
+        SBMLstructure.event(k1).eventAssignment(k2).typecode = 'SBML_EVENT_ASSIGNMENT';
+        SBMLstructure.event(k1).eventAssignment(k2).metaid = '';
+        SBMLstructure.event(k1).eventAssignment(k2).notes = '';
+        SBMLstructure.event(k1).eventAssignment(k2).annotation = '';
+        SBMLstructure.event(k1).eventAssignment(k2).variable = ms.events(k1).assignment(k2).variable;
+        SBMLstructure.event(k1).eventAssignment(k2).math =  replaceMATLABexpressions(ms.events(k1).assignment(k2).formula);
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Process Algebraic Rules
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%                       
+% algebraic rules are just added. names NEED to be present otherwise it
+% makes no sense
+for k=1:length(ms.algebraic),
+    name = ms.algebraic(k).name;
+    formula = ms.algebraic(k).formula;
+    initialCondition = ms.algebraic(k).initialCondition;
+    type = ms.algebraic(k).type;
+    compartment = ms.algebraic(k).compartment;
+    unittype = ms.algebraic(k).unittype;
+    notes = ms.algebraic(k).notes;
+    % add the rule
+    SBMLstructure.rule(end+1).typecode = 'SBML_ALGEBRAIC_RULE';
+    SBMLstructure.rule(end).metaid = '';
+    SBMLstructure.rule(end).notes = convert2SBMLNotes(notes);
+    SBMLstructure.rule(end).annotation = '';
+    SBMLstructure.rule(end).formula = formula;
+    SBMLstructure.rule(end).variable = '';
+    SBMLstructure.rule(end).species = '';
+    SBMLstructure.rule(end).compartment = '';
+    SBMLstructure.rule(end).name = '';
+    SBMLstructure.rule(end).units = '';
+    % add name as specie, parameter, or compartment
+    if strcmp(type,'isSpecie'),
+        SBMLstructure.species(end+1).typecode = 'SBML_SPECIES';
+        SBMLstructure.species(end).metaid = '';
+        SBMLstructure.species(end).notes = convert2SBMLNotes(notes);
+        SBMLstructure.species(end).annotation = '';
+        SBMLstructure.species(end).name = name;
+        SBMLstructure.species(end).id = name;
+        SBMLstructure.species(end).compartment = compartment;
+        SBMLstructure.species(end).initialAmount = initialCondition;
+        SBMLstructure.species(end).initialConcentration = initialCondition;
+        SBMLstructure.species(end).substanceUnits = '';         % no units!
+        SBMLstructure.species(end).spatialSizeUnits = '';       % no units!
+        SBMLstructure.species(end).hasOnlySubstanceUnits = strcmp(unittype,'amount');
+        SBMLstructure.species(end).boundaryCondition = 1;       % set boundary cond (det. by rule) 
+        SBMLstructure.species(end).charge = 0;                  
+        SBMLstructure.species(end).constant = 0;                % species is not set constant
+        SBMLstructure.species(end).isSetInitialAmount = strcmp(unittype,'amount');
+        SBMLstructure.species(end).isSetInitialConcentration = strcmp(unittype,'concentration');
+        SBMLstructure.species(end).isSetCharge = 0;             % charge not supported       
+    end
+    if strcmp(type,'isParameter'),
+        SBMLstructure.parameter(end+1).typecode = 'SBML_PARAMETER';
+        SBMLstructure.parameter(end).metaid = '';
+        SBMLstructure.parameter(end).notes = convert2SBMLNotes(notes);
+        SBMLstructure.parameter(end).annotation = '';
+        SBMLstructure.parameter(end).name = name;
+        SBMLstructure.parameter(end).id = name;
+        SBMLstructure.parameter(end).value = initialCondition;
+        SBMLstructure.parameter(end).units = '';
+        SBMLstructure.parameter(end).constant = 0;
+        SBMLstructure.parameter(end).isSetValue = 1;
+    end
+    if strcmp(type,'isCompartment'),
+        SBMLstructure.compartment(end+1).typecode = 'SBML_COMPARTMENT';
+        SBMLstructure.compartment(end).metaid = '';
+        SBMLstructure.compartment(end).notes = convert2SBMLNotes(notes);
+        SBMLstructure.compartment(end).annotation = '';
+        SBMLstructure.compartment(end).name = name;
+        SBMLstructure.compartment(end).id = name;
+        SBMLstructure.compartment(end).spatialDimensions = 3;
+        SBMLstructure.compartment(end).size = initialCondition;
+        SBMLstructure.compartment(end).units = '';
+        SBMLstructure.compartment(end).outside = compartment;
+        SBMLstructure.compartment(end).constant = 0;
+        SBMLstructure.compartment(end).isSetSize = 1;
+        SBMLstructure.compartment(end).isSetVolume = 1;
+    end    
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% WRITE SBML FILE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%                       
+result = SBMLstructure;
+try 
+    OutputSBML(SBMLstructure);
+catch
+    if ~strcmp(lasterr, 'Cannot copy filename'),
+        warning(sprintf('Error occurred: %s\n',lasterr));
+    end
+end
+return
+
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE REACTION INFORMATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%                       
+% we look through all ODEs where the gioven reaction is involved in.
+% we determine reversibility, reactants, products, and modifiers.
+function [reactant, product, modifier] = getReactionInfo(reactionName,StoichiometricMatrix,SBMLspeciesNames,SBMLreactionNames,SBMLreversibleFlag,sbm,ms)
+    % initialize the structures
+    reactant = struct('typecode', {}, 'metaid', {}, 'notes', {}, 'annotation', {}, 'species', {}, 'stoichiometry', {}, 'denominator', {}, 'stoichiometryMath', {});
+    product = struct('typecode', {}, 'metaid', {}, 'notes', {}, 'annotation', {}, 'species', {}, 'stoichiometry', {}, 'denominator', {}, 'stoichiometryMath', {});
+    modifier = struct('typecode', {}, 'metaid', {}, 'notes', {}, 'annotation', {}, 'species', {});
+    % get index of current reaction
+    reactionIndex = strmatchSB(reactionName,SBMLreactionNames,'exact');
+    % get corresponding stoichiometries
+    [stoichRows, stoichCols] = size(StoichiometricMatrix);
+    if (stoichCols >= reactionIndex),
+        Nreaction = StoichiometricMatrix(:,reactionIndex);
+    else
+        % for the current reaction there's no stoichiometry
+        % or products, reactants or modifierer found
+        return
+    end
+    % get reactant indices (Nreaction < 0)
+    reactantIndices = find(Nreaction < 0);
+    % get product indices (Nreaction > 0)
+    productIndices = find(Nreaction > 0);
+    % add reactants
+    for k = 1:length(reactantIndices),
+        reactant(k).typecode = 'SBML_SPECIES_REFERENCE';
+        reactant(k).metaid = '';
+        reactant(k).notes = '';
+        reactant(k).annotation = '';
+        reactant(k).species = SBMLspeciesNames{reactantIndices(k)};
+        reactant(k).stoichiometry = abs(Nreaction(reactantIndices(k)));
+        reactant(k).denominator = 1;
+        reactant(k).stoichiometryMath = '';
+    end
+    % add products
+    for k = 1:length(productIndices),
+        product(k).typecode = 'SBML_SPECIES_REFERENCE';
+        product(k).metaid = '';
+        product(k).notes = '';
+        product(k).annotation = '';
+        product(k).species = SBMLspeciesNames{productIndices(k)};
+        product(k).stoichiometry = Nreaction(productIndices(k));
+        product(k).denominator = 1;
+        product(k).stoichiometryMath = '';
+    end
+    % search for modifiers among the non reactants and non products and add them
+    specieListPossible = SBMLspeciesNames(find(Nreaction == 0));
+    modifierList = {};
+    modifierList = search4Modifiers(modifierList,ms.reactions(reactionIndex).formula,specieListPossible,{ms.variables.name},sbm,ms);
+    modifierList = unique(modifierList);
+    for k = 1:length(modifierList),
+        modifier(k).typecode = 'SBML_MODIFIER_SPECIES_REFERENCE';
+        modifier(k).metaid = '';
+        modifier(k).notes = '';
+        modifier(k).annotation = '';
+        modifier(k).species = modifierList{k};
+    end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE REACTION INFORMATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%                       
+% we go through all reactions and eventually variables to determine the
+% modifiers (recursively)
+function [modifierList] = search4Modifiers(modifierList,formula,specieListPossible,variableNames,sbm,ms)
+    % search in current formula for modifiers
+    formula = strcat('#',formula,'#');
+    for k=1:length(specieListPossible),
+        if ~isempty(regexp(formula,strcat('\W',specieListPossible{k},'\W'))),
+            modifierList{end+1} = specieListPossible{k};
+        end
+    end
+    % search in current formula for variable names
+    searchVariablesIndices = [];
+    for k=1:length(variableNames),
+        if ~isempty(regexp(formula,strcat('\W',variableNames{k},'\W'))),
+            searchVariablesIndices(end+1) = k;
+        end
+    end
+    % loop through variable names and search for modifiers
+    for k=1:length(searchVariablesIndices),
+        formula = ms.variables(searchVariablesIndices(k)).formula;
+        modifierList = search4Modifiers(modifierList,formula,specieListPossible,variableNames,sbm,ms);
+    end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXCHANGE MATLAB FUNCTION NAMES TO MATHML FUNCTION NAMES IN ALL FORMULAS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% MathML functions can have different names than MATLAB function names
+% we need to exchange them in the formula strings. The term 'MathML
+% expression' relates to what is required by OutputSBML!
+function [formula] = replaceMATLABexpressions(formula)
+% MathML expressions 
+MathMLexpressions = {'arccos(','arcsin(','arctan(','ceiling(','ln(','log(10,',...
+    'pow(','arccos(','arccosh(','arccot(','arccoth(','arccsc(','arccsch(',...
+    'arcsec(','arcsech(','arcsin(','arcsinh(','arctan(','arctanh(',...
+    'exponentiale','log(','piecewise(','leq(','geq(','and(','or('};
+% Corresponding MATLAB expressions
+MATLABexpressions = {'acos(','asin(','atan(','ceil(','log(','log10(',...
+    'power(','acos(','acosh(','acot(','acoth(','acsc(','acsch(',...
+    'asec(','asech(','asin(','asinh(','atan(','atanh('...
+    'exp(1)','logbase(','piecewiseSB(','le(','ge(','andSB(','orSB('};
+% do the simple replace
+for k = 1:length(MathMLexpressions),
+    formula = strrep(formula,MATLABexpressions{k},MathMLexpressions{k});
+end
+return
+
+
+    
+    
+    
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/SBmakeSBMLpresets.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/SBmakeSBMLpresets.m
new file mode 100644
index 0000000000000000000000000000000000000000..8aaa06b2e739d7287ee53b5cf289865ba06d291b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/SBmakeSBMLpresets.m
@@ -0,0 +1,860 @@
+function [changedModel] = SBmakeSBMLpresets(model, varargin)
+% SBmakeSBMLpresets
+% Special function for the SBML export of models. The function preprocesses
+% SBmodels to preset the unset "type", "compartment", and "unittype" fields
+% in the structure.
+%
+% USAGE:
+% ======
+% [changedModel] = SBmakeSBMLpresets(model)
+%
+% model: SBmodel to preset SBML fields
+% changedModel: SBmodel with preseted SBML fields
+
+% Information:
+% ============
+% Author: Gunnar Drews, gunnar.drews@uni-rostock.de
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF SBmodel
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~strcmp('SBmodel',class(model)),
+    error('Function only defined for SBmodels.');
+end
+% get the datastructure of the model
+sbm = SBstruct(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK EXTRA INPUT ARGUMENT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% the first extra input argument is used to force the SBstoichiometry function
+% not to correct the elements of the stoichiometric matrix for the
+% compartment information in cases where species are given in
+% concentrations. This is needed for model construction (BC type of
+% representation and for other things)
+% the second is used for silent use of the function
+% both flags are not further documented and should not be used by others
+% unless they fully understand their meaning
+
+silentFlag = 0;
+debugFlag = 0;
+if nargin == 2,
+    silentFlag = varargin{1};
+elseif nargin == 3,
+    silentFlag = varargin{1};
+    debugFlag = varargin{2};
+end
+
+% get all reactions from SBmodel
+reactionNames = {sbm.reactions.name};
+reactionNames = reactionNames(:);
+reversibleFlag = {sbm.reactions.reversible};
+reversibleFlag = reversibleFlag(:);
+reactionCount = length(reactionNames);
+if debugFlag,
+    reactionNames
+end
+% get all States from SBmodel
+stateNames = { sbm.states.name };
+stateNames = stateNames(:);
+stateCount = length(stateNames);
+if debugFlag,
+    stateNames
+end
+
+% test wehter there are predefined compartments in the model
+compartmentList = [];
+compartmentFrom = [];
+compartmentOrigIndex = [];
+compartmentsPredefined = 0;
+[compartmentList, compartmentFrom, compartmentOrigIndex] = fetchCompartments(model);
+if isempty(compartmentList),
+    compartmentsPredefined=0;
+else
+    compartmentsPredefined=1;
+end
+
+% fallback mechanism for ODEs which are given in concentration
+% if no compartments are predefined we have to check parameter names
+% and variable names, too
+parameterNames = { sbm.parameters.name };
+parameterNames = parameterNames(:);
+variableNames = { sbm.variables.name };
+variableNames = variableNames(:);
+variableCount = length(variableNames);
+
+% begin of extraction of ODE information
+% 2 nested for loops:
+% one for the states and
+% one that searches the ODE for reactions etc.
+
+warnings = {};
+warnIndex = 1;
+errors = {};
+
+% run through states ODEs to look for suitable SBML presets
+for currentStateIndex = 1 : stateCount,
+    doProcessState = true;
+    if strcmp(sbm.states(currentStateIndex).type,'isSpecie') && ~isempty(sbm.states(currentStateIndex).compartment) && (strcmp(sbm.states(currentStateIndex).unittype,'amount') || strcmp(sbm.states(currentStateIndex).unittype,'concentration')),
+        doProcessState = false;
+    end
+    if strcmp(sbm.states(currentStateIndex).type,'isCompartment'),
+        doProcessState = false;
+    end
+    if strcmp(sbm.states(currentStateIndex).type,'isParameter'),
+        doProcessState = false;
+    end
+
+    if doProcessState,
+
+        % get the ODE for the specific specie
+        odeString = sbm.states(currentStateIndex).ODE;
+
+        % only for testing reasons
+        if debugFlag,
+            odeString
+        end
+
+        % test wether reaction contains brackets and if yes test for good bracket expression
+        bracketsDetected = 0;
+        if isBracketstring(odeString),
+            bracketsDetected = 1;
+            if ~isBracketstringWellformed(odeString),
+                % something went wrong in the ODE; ask the user to take care
+                errors{1} = char([double('A mistake concerning brackets within the ODE string of state "'), double(sbm.states(currentStateIndex).name), double('" was detected.\n')]);
+                errors{2} = 'Please correct this on your own!';
+                messageOutput(errors, 1);
+                error('\n');
+            end
+        end
+
+        globalStoichiometry = '';
+        localStoichiometry = '';
+        compartmentExpected = 0;
+        constantFound = 0;
+        reacTermCount = 0;
+        firstReacTermStart = 0;
+        identifierBeginDetected = 0;
+        identifierStart = 0;
+        identifierEnd = 0;
+        bracketIndexForSign = [];
+        lastBracketIndexField = 1;
+        for currentCharIndex = 1 : length(odeString),
+            character = odeString(currentCharIndex);
+            if isspace(character),
+                % blanks do not change anything
+                continue;
+            end
+            if ~identifierBeginDetected && (isSign(character) || isNumber(character)),
+                % some part for the stoichiometry matrix was found
+                % append it to Stoichiometry
+                localStoichiometry = char([double(localStoichiometry), double(character)]);
+                % if the last part of the ODE is a constant
+                if (currentCharIndex == length(odeString)),
+                    constantFound = 1;
+                end
+                continue;
+            end
+            if ~identifierBeginDetected && isLetter2(character),
+                % the beginning of an identifier was found
+                if strcmp(localStoichiometry, '/'),
+                    % we expect definitions of concentration with correct
+                    % parentheses
+                    % dS/dt = R1/Compartment => SBML Specie
+                    % dS/dt = R1 + R2/Compartment => SBML Parameter
+                    if ((reacTermCount == 1) || ( (~isempty(strfind(odeString(1:firstReacTermStart), '('))) && (odeString(currentCharIndex-2)==')'))),
+                        compartmentExpected = 1;
+                    else
+                        sbm.states(currentStateIndex).type = 'isParameter';
+                        sbm.states(currentStateIndex).unittype = '';
+                        sbm.states(currentStateIndex).compartment = '';
+                    end
+                else
+                    if constantFound,
+                        [unimportant, localStoichiometry] = testForConstants(localStoichiometry);
+                    else
+                        [constantFound, localStoichiometry] = testForConstants(localStoichiometry);
+                    end
+                end
+                identifierBeginDetected = 1;
+                identifierStart = currentCharIndex;
+                % for the case that a reactionname consists of only one letter
+                identifierEnd = currentCharIndex;
+                % if detected letter is the last one in an ODE
+                if currentCharIndex == length(odeString),
+                    identifier = odeString(identifierStart : identifierEnd);
+                    % test wether found literal is a reaction
+                    checkIdentifierODE(identifier, currentStateIndex);
+                end
+                continue;
+            end
+            if bracketsDetected,
+                if isOpenedBracket(character),
+                    % if a reaction term is detected in front of a bracket this is assumed to be an error
+                    if identifierBeginDetected,
+                        identifier = odeString(identifierStart : identifierEnd);
+                        if ~isFunctionIdentifier(identifier, model),
+                            warnings{warnIndex} = char([double('A term ("'), double(identifier), double('") that seems not to be a function identifier was detected in front of a bracket, see SBmodel state "'), double(sbm.states(currentStateIndex).name), double('".')]);
+                            warnIndex = warnIndex + 1;
+                            warnings{warnIndex} = '';
+                            warnIndex = warnIndex + 1;
+                        end
+                    else
+                        if strcmp(localStoichiometry, '/'),
+                            compartmentExpected = 1;
+                        else
+                            if constantFound,
+                                [unimportant, localStoichiometry] = testForConstants(localStoichiometry);
+                            else
+                                [constantFound, localStoichiometry] = testForConstants(localStoichiometry);
+                            end
+                        end
+                    end
+                    bracketIndexForSign(lastBracketIndexField) = length(globalStoichiometry);
+                    globalStoichiometry = char([double(globalStoichiometry), double(localStoichiometry)]);
+                    localStoichiometry = '';
+                    lastBracketIndexField = lastBracketIndexField + 1;
+                    identifierBeginDetected = 0;
+                    continue;
+                end
+                if isClosedBracket(character),
+                    if identifierBeginDetected,
+                        if debugFlag,
+                            fprintf('closing bracketDetected');
+                            localStoichiometry
+                            globalStoichiometry
+                        end
+                        identifier = odeString(identifierStart : identifierEnd);
+                        % if we expect a compartment but know that this will
+                        % not be the last component in the ode string it has to
+                        % be exported as SBML Parameter
+                        if compartmentExpected && (length(odeString)>(currentCharIndex + lastBracketIndexField - 1)),
+                            sbm.states(currentStateIndex).type = 'isParameter';
+                            sbm.states(currentStateIndex).unittype = '';
+                            sbm.states(currentStateIndex).compartment = '';
+                            % because we expect the rest of the ode to be a
+                            % nasty expression we skip parsing it
+                            break;
+                        end
+                        % test identifier origin
+                        checkIdentifierODE(identifier, currentStateIndex);
+                        identifierBeginDetected = 0;
+                    else
+                        if ~isempty(localStoichiometry),
+                            constantFound = 1;
+                        end
+                    end
+                    lastBracketIndexField = lastBracketIndexField - 1;
+                    if lastBracketIndexField > 1,
+                        globalStoichiometry = globalStoichiometry(1:bracketIndexForSign(lastBracketIndexField-1));
+                    else
+                        globalStoichiometry = '';
+                    end
+                    localStoichiometry = '';
+                    continue;
+                end
+            end
+            if identifierBeginDetected,
+                if isLetter2(character) || isNumber(character),
+                    identifierEnd = currentCharIndex;
+                    if currentCharIndex == length(odeString),
+                        identifier = odeString(identifierStart : identifierEnd);
+                        % test identifier origin
+                        checkIdentifierODE(identifier, currentStateIndex);
+                    end
+                else
+                    if debugFlag,
+                        fprintf('identifierBeginDetected');
+                        localStoichiometry
+                        constantFound
+                    end
+                    identifier = odeString(identifierStart : identifierEnd);
+                    % if we expect a compartment but know that this will
+                    % not be the last component in the ode string it has to
+                    % be exported as SBML Parameter
+                    if compartmentExpected && (length(odeString)>currentCharIndex),
+                        sbm.states(currentStateIndex).type = 'isParameter';
+                        sbm.states(currentStateIndex).unittype = '';
+                        sbm.states(currentStateIndex).compartment = '';
+                        % because we expect the rest of the ode to be a
+                        % nasty expression we skip parsing it
+                        break;
+                    end
+                    % test wether found literal is a reaction
+                    checkIdentifierODE(identifier, currentStateIndex);
+                    % if identifier was surrounded by brackets remove
+                    % multiplier from stoichiometry for current pair of
+                    % brackets
+                %{
+                if lastBracketIndexField > 1,
+                    globalStoichiometry = globalStoichiometry(1:bracketIndexForSign(lastBracketIndexField-1));
+                else
+                    globalStoichiometry = '';
+                end
+                %}
+                localStoichiometry = '';
+                localStoichiometry = char([double(localStoichiometry), double(character)]);
+                identifierBeginDetected = 0;
+            end
+        end
+    end % end of parsing ODE string
+
+    % if one or more constant terms have been found in ODE
+    % this state is exported as SBML Parameter
+    if (constantFound && ~strcmp(sbm.states(currentStateIndex).type, 'isCompartment')),
+        sbm.states(currentStateIndex).type = 'isParameter';
+        sbm.states(currentStateIndex).unittype = '';
+        sbm.states(currentStateIndex).compartment = '';
+    end
+
+    % preset fallback for states
+    % if states aren't claimed to be SBML Compartments or SBML
+    % Parameters we assign them to Species
+    type = sbm.states(currentStateIndex).type;
+    if (~strcmp(type, 'isSpecie') && ~strcmp(type, 'isParameter') && ~strcmp(type, 'isCompartment')) || strcmp(type, ''),
+        sbm.states(currentStateIndex).type = 'isSpecie';
+    end
+    % if no SBML unit type assignment was possible
+    unittype = sbm.states(currentStateIndex).unittype;
+    if strcmp(sbm.states(currentStateIndex).type, 'isSpecie') && ~strcmp(unittype, 'concentration'),
+        sbm.states(currentStateIndex).unittype = 'amount';
+    end
+
+end
+end % of run through states
+
+% begin of extraction of formula information
+% 2 nested for loops:
+% one for the variables and
+% one that searches the formulae for reactions etc.
+
+% run through variables formulae to find suitable SBML presets
+for currentVariableIndex = 1 : variableCount,
+    doProcessVariable  = true;
+    if strcmp(sbm.variables(currentVariableIndex).type,'isSpecie') && ~isempty(sbm.variables(currentVariableIndex).compartment) && (strcmp(sbm.variables(currentVariableIndex).unittype,'amount') || strcmp(sbm.variables(currentVariableIndex).unittype,'concentration')),
+        doProcessVariable  = false;
+    end
+    if strcmp(sbm.variables(currentVariableIndex).type,'isCompartment'),
+        doProcessVariable  = false;
+    end
+    if strcmp(sbm.variables(currentVariableIndex).type,'isParameter'),
+        doProcessVariable  = false;
+    end
+    
+    if doProcessVariable ,
+        % get the ODE for the specific specie
+        formulaString = sbm.variables(currentVariableIndex).formula;
+
+        % only for testing reasons
+        if debugFlag,
+            formulaString
+        end
+
+        % test wether reaction contains brackets and if yes test for good bracket expression
+        bracketsDetected = 0;
+        if isBracketstring(formulaString),
+            bracketsDetected = 1;
+            if ~isBracketstringWellformed(formulaString),
+                % something went wrong in the ODE; ask the user to take care
+                errors{1} = char([double('A mistake concerning brackets within the formula string of variable "'), double(sbm.variables(currentVariableIndex).name), double('" was detected.\n')]);
+                errors{2} = 'Please correct this on your own!';
+                messageOutput(errors, 1);
+                error('\n');
+            end
+        end
+        globalFactor = '';
+        localFactor = '';
+        compartmentExpected = 0;
+        constantFound = 0;
+        reacTermCount = 0;
+        firstReacTermStart = 0;
+        identifierBeginDetected = 0;
+        identifierStart = 0;
+        identifierEnd = 0;
+        bracketIndexForSign = [];
+        lastBracketIndexField = 1;
+        for currentCharIndex = 1 : length(formulaString),
+            character = formulaString(currentCharIndex);
+            if isspace(character),
+                % blanks do not change anything
+                continue;
+            end
+            if ~identifierBeginDetected && (isSign(character) || isNumber(character)),
+                % some part of a factor was found append it to localFactor
+                % string
+                localFactor = char([double(localFactor), double(character)]);
+                %stoichiometry = char([double(stoichiometry), double(character)]);
+                % if the last part of the ODE is a constant
+                if (currentCharIndex == length(formulaString)),
+                    constantFound = 1;
+                end
+                continue;
+            end
+            if ~identifierBeginDetected && isLetter2(character),
+                % the beginning of an identifier was found
+                if strcmp(localFactor, '/'),
+                    % we expect definitions of concentration with correct
+                    % parentheses
+                    % formula = R1/Compartment => SBML Specie
+                    % formula = R1 + R2/Compartment => SBML Parameter
+                    if ((reacTermCount == 1) || ( (~isempty(strfind(formulaString(1:firstReacTermStart), '('))) && (formulaString(currentCharIndex-2)==')'))),
+                        compartmentExpected = 1;
+                    else
+                        sbm.variables(currentVariableIndex).type = 'isParameter';
+                        sbm.variables(currentVariableIndex).unittype = '';
+                        sbm.variables(currentVariableIndex).compartment = '';
+                    end
+                else
+                    if constantFound,
+                        [unimportant, localFactor] = testForConstants(localFactor);
+                    else
+                        [constantFound, localFactor] = testForConstants(localFactor);
+                    end
+                end
+                identifierBeginDetected = 1;
+                identifierStart = currentCharIndex;
+                % for the case that a reactionname consists of only one letter
+                identifierEnd = currentCharIndex;
+                % if detected letter is the last one in an ODE
+                if currentCharIndex == length(formulaString),
+                    identifier = formulaString(identifierStart : identifierEnd);
+                    % test wether found literal is a reaction
+                    checkIdentifierFormula(identifier, currentVariableIndex);
+                end
+                continue;
+            end
+            if bracketsDetected,
+                if isOpenedBracket(character),
+                    % if a reaction term is detected in front of a bracket this is assumed to be an error
+                    if identifierBeginDetected,
+                        identifier = formulaString(identifierStart : identifierEnd);
+                        if ~isFunctionIdentifier(identifier, model),
+                            warnings{warnIndex} = char([double('A term ("'), double(identifier), double('") that seems not to be a function identifier was detected in front of a bracket, see SBmodel variable "'), double(sbm.variables(currentVariableIndex).name), double('".')]);
+                            warnIndex = warnIndex + 1;
+                            warnings{warnIndex} = '';
+                            warnIndex = warnIndex + 1;
+                        end
+                    else
+                        if strcmp(localFactor, '/'),
+                            compartmentExpected = 1;
+                        else
+                            if constantFound,
+                                [unimportant, localFactor] = testForConstants(localFactor);
+                            else
+                                [constantFound, localFactor] = testForConstants(localFactor);
+                            end
+                        end
+                    end
+                    bracketIndexForSign(lastBracketIndexField) = length(globalFactor);
+                    globalFactor = char([double(globalFactor), double(localFactor)]);
+                    localFactor = '';
+                    lastBracketIndexField = lastBracketIndexField + 1;
+                    identifierBeginDetected = 0;
+                    continue;
+                end
+                if isClosedBracket(character),
+                    if identifierBeginDetected,
+                        if debugFlag,
+                            fprintf('closing bracketDetected');
+                            localFactor
+                            globalFactor
+                        end
+                        identifier = formulaString(identifierStart : identifierEnd);
+                        % if we expect a compartment but know that this will
+                        % not be the last component in the ode string it has to
+                        % be exported as SBML Parameter
+                        if compartmentExpected && (length(formulaString)>(currentCharIndex + lastBracketIndexField - 1)),
+                            sbm.variables(currentVariableIndex).type = 'isParameter';
+                            sbm.variables(currentVariableIndex).unittype = '';
+                            sbm.variables(currentVariableIndex).compartment = '';
+                            % because we expect the rest of the ode to be a
+                            % nasty expression we skip parsing it
+                            break;
+                        end
+                        % test identifier origin
+                        checkIdentifierFormula(identifier, currentVariableIndex);
+                        identifierBeginDetected = 0;
+                    else
+                        if ~isempty(localFactor),
+                            constantFound = 1;
+                        end
+                    end
+                    lastBracketIndexField = lastBracketIndexField - 1;
+                    if lastBracketIndexField > 1,
+                        globalFactor = globalFactor(1:bracketIndexForSign(lastBracketIndexField-1));
+                    else
+                        globalFactor = '';
+                    end
+                    localFactor = '';
+                    continue;
+                end
+            end
+            if identifierBeginDetected,
+                if isLetter2(character) || isNumber(character),
+                    identifierEnd = currentCharIndex;
+                    if currentCharIndex == length(formulaString),
+                        identifier = formulaString(identifierStart : identifierEnd);
+                        % test identifier origin
+                        checkIdentifierFormula(identifier, currentVariableIndex);
+                    end
+                else
+                    if debugFlag,
+                        fprintf('identifierBeginDetected');
+                        localFactor
+                        globalFactor
+                    end
+                    identifier = formulaString(identifierStart : identifierEnd);
+                    % if we expect a compartment but know that this will
+                    % not be the last component in the ode string it has to
+                    % be exported as SBML Parameter
+                    if compartmentExpected && (length(formulaString)>currentCharIndex),
+                        sbm.variables(currentVariableIndex).type = 'isParameter';
+                        sbm.variables(currentVariableIndex).unittype = '';
+                        sbm.variables(currentVariableIndex).compartment = '';
+                        % because we expect the rest of the ode to be a
+                        % nasty expression we skip parsing it
+                        break;
+                    end
+                    % test wether found literal is a reaction
+                    checkIdentifierFormula(identifier, currentVariableIndex);
+                    % if identifier was surrounded by brackets remove
+                    % multiplier from stoichiometry for current pair of
+                    % brackets
+                %{
+                if lastBracketIndexField > 1,
+                    globalFactor = globalFactor(1:bracketIndexForSign(lastBracketIndexField-1));
+                else
+                    globalFactor = '';
+                end
+                %}
+                localFactor = '';
+                localFactor = char([double(localFactor), double(character)]);
+                identifierBeginDetected = 0;
+            end
+        end
+    end % end of formula parsing string
+    % if one or more constant terms have been found in ODE
+    % this state is exported as SBML Parameter
+    if (constantFound && ~strcmp(sbm.variables(currentVariableIndex).type, 'isCompartment')),
+        sbm.variables(currentVariableIndex).type = 'isParameter';
+        sbm.variables(currentVariableIndex).unittype = '';
+        sbm.variables(currentVariableIndex).compartment = '';
+    end
+
+    % preset fallback for variables
+    % if variables aren't claimed to be SBML Compartments or SBML
+    % Parameters we assign them to Species
+    type = sbm.variables(currentVariableIndex).type;
+    if (~strcmp(type, 'isSpecie') && ~strcmp(type, 'isParameter') && ~strcmp(type, 'isCompartment')) || strcmp(type, ''),
+        sbm.variables(currentVariableIndex).type = 'isSpecie';
+    end
+    % if no SBML unit type assignment was possible
+    unittype = sbm.variables(currentVariableIndex).unittype;
+    if strcmp(sbm.variables(currentVariableIndex).type, 'isSpecie') && ~strcmp(unittype, 'concentration'),
+        sbm.variables(currentVariableIndex).unittype = 'amount';
+    end
+
+end
+end % of variables run
+
+
+
+
+
+
+
+
+
+
+% run through SBmodel parameters
+for currentParameterIndex = 1 : length(parameterNames),
+
+doProcessParameter  = true;
+if strcmp(sbm.parameters(currentParameterIndex).type,'isSpecie') && ~isempty(sbm.parameters(currentParameterIndex).compartment) && (strcmp(sbm.parameters(currentParameterIndex).unittype,'amount') || strcmp(sbm.parameters(currentParameterIndex).unittype,'concentration')),
+    doProcessParameter  = false;
+end
+if strcmp(sbm.parameters(currentParameterIndex).type,'isCompartment'),
+    doProcessParameter  = false;
+end
+if strcmp(sbm.parameters(currentParameterIndex).type,'isParameter'),
+    doProcessParameter  = false;
+end
+
+if doProcessParameter,
+    % preset fallback for parameters
+    % if parameters aren't claimed to be SBML Compartments or SBML
+    % Species we assign them to SBML Parameters
+    type = sbm.parameters(currentParameterIndex).type;
+    if (~strcmp(type, 'isSpecie') && ~strcmp(type, 'isParameter') && ~strcmp(type, 'isCompartment')) || strcmp(type, ''),
+        sbm.parameters(currentParameterIndex).type = 'isParameter';
+        sbm.parameters(currentParameterIndex).unittype = '';
+        sbm.parameters(currentParameterIndex).compartment = '';
+    end
+
+end
+end
+
+changedModel = SBmodel(sbm);
+
+if ~silentFlag && (warnIndex>1),
+    messageOutput(warnings, 2);
+end
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% new code for identifier handling within states ODE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    function checkIdentifierODE(identifier, currentStateIndex)
+
+    if compartmentExpected,
+        % if SBmodel State is already set to SBML Parameter
+        % a concentration definition is not possible/necessary
+        if strcmp(sbm.states(currentStateIndex).type, 'isParameter'),
+            return;
+        end
+        % check compartments for identifier
+        compaHit = matchStringOnArray(identifier, compartmentList);
+        if (compaHit~=0),
+            % compartment was expected and has been found
+            % check unittype for concentration
+            if ~strcmp(sbm.states(currentStateIndex).unittype, 'concentration'),
+                warnings{warnIndex} = char([double(sbm.states(currentStateIndex).name), double(' seems to be defined as concentration per time by ODE, but unit type is set to "'), double(sbm.states(currentStateIndex).unittype), double('" this will be changed to "concentration"!')]);
+                warnIndex = warnIndex + 1;
+                warnings{warnIndex} = char([double(sbm.states(currentStateIndex).name), double(' is also going to be assigned to compartment: '), double(identifier), double('.')]);
+                warnIndex = warnIndex + 1;
+                warnings{warnIndex} = '';
+                warnIndex = warnIndex + 1;
+                sbm.states(currentStateIndex).unittype = 'concentration';
+                sbm.states(currentStateIndex).compartment = identifier;
+            end
+            return
+        end
+        % check reactions
+        reacHit = matchStringOnArray(identifier, reactionNames);
+        if (reacHit~=0),
+            errors{1} = char([double(identifier), double(' in '), double(sbm.states(currentStateIndex).name), double(' is to be expected a compartment, but was defined as reaction. This is not possible!')]);
+            messageOutput(errors, 1);
+            error('\n');
+        end
+        % check first wether identifier is a reaction (this should be standard
+        % case)
+        stateHit = matchStringOnArray(identifier, stateNames);
+        if (stateHit~=0),
+            warnings{warnIndex} = char([double(identifier), double(' is used as compartment in '), double(sbm.states(currentStateIndex).name), double(' defining concentration per time!')]);
+            warnIndex = warnIndex + 1;
+            warnings{warnIndex} = char([double('SBML type of '), double(sbm.states(stateHit).name), double(' is set to "SBML COMPARTMENT" and unit type of '), double(sbm.states(currentStateIndex).name), double(' is set to "concentration"!')]);
+            warnIndex = warnIndex + 1;
+            warnings{warnIndex} = char([double(sbm.states(currentStateIndex).name), double(' is also going to be assigned to compartment: '), double(identifier), double('.')]);
+            warnIndex = warnIndex + 1;
+            warnings{warnIndex} = '';
+            warnIndex = warnIndex + 1;
+            sbm.states(stateHit).type = 'isCompartment';
+            sbm.states(currentStateIndex).unittype = 'concentration';
+            sbm.states(currentStateIndex).compartment = identifier;
+            % now we update the compartment list to avoid false warnings
+            [compartmentList, compartmentFrom, compartmentOrigIndex] = fetchCompartments(SBmodel(sbm));
+            return;
+        end
+        paramHit = matchStringOnArray(identifier, parameterNames);
+        if (paramHit~=0),
+            warnings{warnIndex} = char([double(identifier), double(' is used as compartment in '), double(sbm.states(currentStateIndex).name), double(' defining concentration per time!')]);
+            warnIndex = warnIndex + 1;
+            warnings{warnIndex} = char([double('SBML type of '), double(sbm.parameters(paramHit).name), double(' is set to "SBML COMPARTMENT" and unit type of '), double(sbm.states(currentStateIndex).name), double(' is set to "concentration"!')]);
+            warnIndex = warnIndex + 1;
+            warnings{warnIndex} = char([double(sbm.states(currentStateIndex).name), double(' is also going to be assigned to compartment: '), double(identifier), double('.')]);
+            warnIndex = warnIndex + 1;
+            warnings{warnIndex} = '';
+            warnIndex = warnIndex + 1;
+            sbm.parameters(paramHit).type = 'isCompartment';
+            sbm.states(currentStateIndex).unittype = 'concentration';
+            sbm.states(currentStateIndex).compartment = identifier;
+            % now we update the compartment list to avoid false warnings
+            [compartmentList, compartmentFrom, compartmentOrigIndex] = fetchCompartments(SBmodel(sbm));
+            return;
+        end
+        variaHit = matchStringOnArray(identifier, variableNames);
+        if (variaHit~=0),
+            warnings{warnIndex} = char([double(identifier), double(' is used as compartment in '), double(sbm.states(currentStateIndex).name), double(' defining concentration per time!')]);
+            warnIndex = warnIndex + 1;
+            warnings{warnIndex} = char([double('SBML type of '), double(sbm.variables(variaHit).name), double(' is set to "SBML COMPARTMENT" and unit type of '), double(sbm.states(currentStateIndex).name), double(' is set to "concentration"!')]);
+            warnIndex = warnIndex + 1;
+            warnings{warnIndex} = char([double(sbm.states(currentStateIndex).name), double(' is also going to be assigned to compartment: '), double(identifier), double('.')]);
+            warnIndex = warnIndex + 1;
+            warnings{warnIndex} = '';
+            warnIndex = warnIndex + 1;
+            sbm.variables(variaHit).type = 'isCompartment';
+            sbm.states(currentStateIndex).unittype = 'concentration';
+            sbm.states(currentStateIndex).compartment = identifier;
+            % now we update the compartment list to avoid false warnings
+            [compartmentList, compartmentFrom, compartmentOrigIndex] = fetchCompartments(SBmodel(sbm));
+            return;
+        end
+        compartmentExpected = 0;
+    else % identifier is not expected to be a compartment
+        % check first wether identifier is a reaction (this should be standard
+        % case)
+        reacHit = matchStringOnArray(identifier, reactionNames);
+        if (reacHit==0),
+            % the current state doesn't consist only of reactions (type -> SBML
+            % Parameter)
+            if ~strcmp(sbm.states(currentStateIndex).type, 'isParameter'),
+                warnings{warnIndex} = char([double(sbm.states(currentStateIndex).name), double(' contains not only reactions therefor the type is changed to "SBML Parameter"!')]);
+                warnIndex = warnIndex + 1;
+                warnings{warnIndex} = '';
+                warnIndex = warnIndex + 1;
+                sbm.states(currentStateIndex).type = 'isParameter';
+                sbm.states(currentStateIndex).unittype = '';
+                sbm.states(currentStateIndex).compartment = '';
+            end
+        else
+            reacTermCount = reacTermCount + 1;
+            % keep position of first reaction occurence
+            % if we have more than one reaction we have to check right
+            % usage of parentheses in case of definition as concentration
+            if (reacTermCount==1),
+                firstReacTermStart = currentCharIndex - length(identifier);
+            end
+        end
+    end
+end % of checkIdentifierODE function
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% new code for identifier handling within variables Formula
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    function checkIdentifierFormula(identifier, currentVariableIndex)
+
+    if compartmentExpected,
+        % if SBmodel Variable is already set to SBML Parameter
+        % a concentration definition is not possible/necessary
+        if strcmp(sbm.variables(currentVariableIndex).type, 'isParameter'),
+            return;
+        end
+        % check compartments for identifier
+        compaHit = matchStringOnArray(identifier, compartmentList);
+        if (compaHit~=0),
+            % compartment was expected and has been found
+            % check unittype for concentration
+            if ~strcmp(sbm.variables(currentVariableIndex).unittype, 'concentration'),
+                warnings{warnIndex} = char([double(sbm.variables(currentVariableIndex).name), double(' seems to be defined as concentration per time by formula, but unit type is set to "'), double(sbm.variables(currentVariableIndex).unittype), double('" this will be changed to "concentration"!')]);
+                warnIndex = warnIndex + 1;
+                warnings{warnIndex} = char([double(sbm.variables(currentVariableIndex).name), double(' is also going to be assigned to compartment: '), double(identifier), double('.')]);
+                warnIndex = warnIndex + 1;
+                warnings{warnIndex} = '';
+                warnIndex = warnIndex + 1;
+                sbm.variables(currentVariableIndex).unittype = 'concentration';
+                sbm.variables(currentVariableIndex).compartment = identifier;
+            end
+            return
+        end
+        % check reactions
+        reacHit = matchStringOnArray(identifier, reactionNames);
+        if (reacHit~=0),
+            errors{1} = char([double(identifier), double(' in '), double(sbm.variables(currentVariableIndex).name), double(' is to be expected a compartment, but was defined as reaction. This is not possible!')]);
+            messageOutput(errors, 1);
+            error('\n');
+        end
+
+        stateHit = matchStringOnArray(identifier, stateNames);
+        if (stateHit~=0),
+            warnings{warnIndex} = char([double(identifier), double(' is used as compartment in '), double(sbm.variables(currentVariableIndex).name), double(' defining concentration per time!')]);
+            warnIndex = warnIndex + 1;
+            warnings{warnIndex} = char([double('SBML type of '), double(sbm.states(stateHit).name), double(' is set to "SBML COMPARTMENT" and unit type of '), double(sbm.variables(currentVariableIndex).name), double(' is set to "concentration"!')]);
+            warnIndex = warnIndex + 1;
+            warnings{warnIndex} = char([double(sbm.variables(currentVariableIndex).name), double(' is also going to be assigned to compartment: '), double(identifier), double('.')]);
+            warnIndex = warnIndex + 1;
+            warnings{warnIndex} = '';
+            warnIndex = warnIndex + 1;
+            sbm.states(stateHit).type = 'isCompartment';
+            sbm.variables(currentVariableIndex).unittype = 'concentration';
+            sbm.variables(currentVariableIndex).compartment = identifier;
+            % now we update the compartment list to avoid false warnings
+            [compartmentList, compartmentFrom, compartmentOrigIndex] = fetchCompartments(SBmodel(sbm));
+            return;
+        end
+        paramHit = matchStringOnArray(identifier, parameterNames);
+        if (paramHit~=0),
+            warnings{warnIndex} = char([double(identifier), double(' is used as compartment in '), double(sbm.variables(currentVariableIndex).name), double(' defining concentration per time!')]);
+            warnIndex = warnIndex + 1;
+            warnings{warnIndex} = char([double('SBML type of '), double(sbm.parameters(paramHit).name), double(' is set to "SBML COMPARTMENT" and unit type of '), double(sbm.variables(currentVariableIndex).name), double(' is set to "concentration"!')]);
+            warnIndex = warnIndex + 1;
+            warnings{warnIndex} = char([double(sbm.variables(currentVariableIndex).name), double(' is also going to be assigned to compartment: '), double(identifier), double('.')]);
+            warnIndex = warnIndex + 1;
+            warnings{warnIndex} = '';
+            warnIndex = warnIndex + 1;
+            sbm.parameters(paramHit).type = 'isCompartment';
+            sbm.variables(currentVariableIndex).unittype = 'concentration';
+            sbm.variables(currentVariableIndex).compartment = identifier;
+            % now we update the compartment list to avoid false warnings
+            [compartmentList, compartmentFrom, compartmentOrigIndex] = fetchCompartments(SBmodel(sbm));
+            return;
+        end
+        variaHit = matchStringOnArray(identifier, variableNames);
+        if (variaHit~=0),
+            warnings{warnIndex} = char([double(identifier), double(' is used as compartment in '), double(sbm.variables(currentVariableIndex).name), double(' defining concentration per time!')]);
+            warnIndex = warnIndex + 1;
+            warnings{warnIndex} = char([double('SBML type of '), double(sbm.variables(variaHit).name), double(' is set to "SBML COMPARTMENT" and unit type of '), double(sbm.variables(currentVariableIndex).name), double(' is set to "concentration"!')]);
+            warnIndex = warnIndex + 1;
+            warnings{warnIndex} = char([double(sbm.variables(currentVariableIndex).name), double(' is also going to be assigned to compartment: '), double(identifier), double('.')]);
+            warnIndex = warnIndex + 1;
+            warnings{warnIndex} = '';
+            warnIndex = warnIndex + 1;
+            sbm.variables(variaHit).type = 'isCompartment';
+            sbm.variables(currentVariableIndex).unittype = 'concentration';
+            sbm.variables(currentVariableIndex).compartment = identifier;
+            % now we update the compartment list to avoid false warnings
+            [compartmentList, compartmentFrom, compartmentOrigIndex] = fetchCompartments(SBmodel(sbm));
+            return;
+        end
+        compartmentExpected = 0;
+    else % identifier is not expected to be a compartment
+        % check first wether identifier is a reaction (this should be standard
+        % case)
+        reacHit = matchStringOnArray(identifier, reactionNames);
+        if (reacHit==0),
+            % the current variable is best described as parameter
+            % (type -> SBML Parameter)
+            if ~strcmp(sbm.variables(currentVariableIndex).type, 'isParameter'),
+                warnings{warnIndex} = char([double(sbm.variables(currentVariableIndex).name), double(' seems to be best described as "SBML Parameter"!')]);
+                warnIndex = warnIndex + 1;
+                warnings{warnIndex} = '';
+                warnIndex = warnIndex + 1;
+                sbm.variables(currentVariableIndex).type = 'isParameter';
+                sbm.variables(currentVariableIndex).unittype = '';
+                sbm.variables(currentVariableIndex).compartment = '';
+            end
+        else
+            reacTermCount = reacTermCount + 1;
+            % keep position of first reaction occurence
+            % if we have more than one reaction we have to check right
+            % usage of parentheses in case of definition as concentration
+            if (reacTermCount==1),
+                firstReacTermStart = currentCharIndex - length(identifier);
+            end
+        end
+    end
+    end % of checkIdentifierFormula function
+
+    function [constantFound, newExpression] = testForConstants(expression)
+        constantFound = false;
+        newExpression = expression;
+        rhsFactor = false;
+        lastChar = '';
+        for charIndex = 1 : length(expression),
+            if isFOSign(expression(charIndex)),
+                if ~isempty(lastChar) && ~isSOSign(lastChar),
+                    newExpression = expression(charIndex:length(expression));
+                    if rhsFactor,
+                        rhsFactor = false;
+                    else
+                        constantFound = true;
+                    end
+                end
+            elseif ((charIndex==1) && (isSOSign(expression(charIndex)))),
+                rhsFactor = true;
+            end
+            lastChar = expression(charIndex);
+        end
+    end % of testForConstants function
+
+end % of SBmakeSBMLpresets function
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/addDefaultCompartment.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/addDefaultCompartment.m
new file mode 100644
index 0000000000000000000000000000000000000000..19b9e8510435c163e6dde267d26f17d4465894f7
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/addDefaultCompartment.m
@@ -0,0 +1,208 @@
+function [changedModel] = addDefaultCompartment(model, varargin)
+% addDefaultCompartment
+% checks wether a SBmodel contains any compartments, if not a default
+% compartment (a SBML Parameter with size 1) will be added, so that the
+% model can be exported to SBML
+%
+%
+% USAGE:
+% ======
+% [changedModel] = addDefaultCompartment(model)
+% [changedModel] = addDefaultCompartment(model, compartmentName)
+%
+% model: SBmodel where a default SBML compartment is to add
+% compartmentName (optional): if you want to provide a name for the
+%                             compartment by yourself
+% 
+% changedModel: SBmodel with added default (root) compartment
+%
+
+% Information:
+% ============
+% Author: Gunnar Drews, gunnar.drews@uni-rostock.de
+
+modelORIGINAL = model;
+
+compartmentName = '';
+silentFlag = 0;
+if (nargin == 1),
+    silentFlag = 0;
+elseif (nargin == 2),
+    compartmentName = varargin{1};
+    silentFlag = 0;
+elseif (nargin == 3),
+    compartmentName = varargin{1};
+    silentFlag = varargin{2};
+end
+
+if isSBmodelName(compartmentName),
+    error{1} = char([double('Sorry, but "'), double(compartmentName), double('" is not a valid SBmodel identifier!')]);
+    error{2} = 'Please provide another compartment name.';
+    messageOutput(error, 1);
+    return
+end
+
+if existsNameInSBmodel(model, compartmentName),
+    error{1} = char([double('Sorry, but "'), double(compartmentName), double('" is already used as Identifier in the given SBmodel!')]);
+    error{2} = 'Please provide another compartment name.';
+    messageOutput(error, 1);
+    return;
+end
+    
+
+rootCompartments = 0;
+compartmentCount = 0;
+notCompartmentCount = 0;
+
+boolvalue = false;
+foundError = false;
+errorMessages = [];
+errorNumber = 0;
+
+modelStruct = SBstruct(model);
+stateCount = length(modelStruct.states);
+parameterCount = length(modelStruct.parameters);
+variableCount = length(modelStruct.variables);
+
+% at first we perform a check for all compartments
+for n = 1 : stateCount
+    if strcmp(modelStruct.states(n).type, 'isCompartment')
+        compartmentCount = compartmentCount + 1;
+        compartmentList{compartmentCount} = modelStruct.states(n).name;
+        if strcmp(modelStruct.states(n).compartment, '')
+            rootCompartments = rootCompartments + 1;
+        end
+    else
+        notCompartmentCount = notCompartmentCount + 1;
+        componentList{notCompartmentCount} = modelStruct.states(n).name;
+    end
+end
+for n = 1 : parameterCount
+    if strcmp(modelStruct.parameters(n).type, 'isCompartment')
+        compartmentCount = compartmentCount + 1;
+        compartmentList{compartmentCount} = modelStruct.parameters(n).name;
+        if strcmp(modelStruct.parameters(n).compartment, '')
+            rootCompartments = rootCompartments + 1;
+        end
+    else
+        notCompartmentCount = notCompartmentCount + 1;
+        componentList{notCompartmentCount} = modelStruct.parameters(n).name;
+    end
+end
+for n = 1 : variableCount
+    if strcmp(modelStruct.variables(n).type, 'isCompartment')
+        compartmentCount = compartmentCount + 1;
+        compartmentList{compartmentCount} = modelStruct.variables(n).name;
+        if strcmp(modelStruct.variables(n).compartment, '')
+            rootCompartments = rootCompartments + 1;
+        end
+    else
+        notCompartmentCount = notCompartmentCount + 1;
+        componentList{notCompartmentCount} = modelStruct.variables(n).name;
+    end
+end
+
+if compartmentCount > 0
+    if ~silentFlag,
+        error{1} = 'This SBmodel contains already compartments!';
+        error{2} = 'In this case it is not the best way to add a compartment by default. But if you want to, all not assigned components can be added to a default compartment.';
+        messageOutput(error, 1);
+    end
+    while (true),
+        answer = input('Add default compartment to model (needed for export)? [y/n] ?', 's');
+        if (strcmp(answer, 'y') || strcmp(answer, 'Y')),
+            break;
+        elseif (strcmp(answer, 'n') || strcmp(answer, 'N')),
+            disp('Adding of DefaultCompartment aborted.');
+            changedModel = modelORIGINAL;
+            return;
+        end
+    end
+end
+
+% the given SBmodel matches the requirements of this function
+% now we can check which name can be used
+if isempty(compartmentName),
+    if ~existsNameInSBmodel(model, 'rootCompartment')
+        compartmentName = 'rootCompartment';
+    elseif ~existsNameInSBmodel(model, 'defaultCompartment')
+        compartmentName = 'defaultCompartment';
+    else
+        if ~silentFlag,
+            error{1} = 'It was not possible to create a default compartment with the names "rootCompartment" or "defaultCompartment" because they are already in use!';
+            error{2} = 'Please provide a name by your own, with: "addDefaultCompartment(model, compartmentName)"';
+            error{3} = ' ';
+            messageOutput(error, 1);
+        end
+        return;
+    end
+end
+
+% now that we've got the name we can add the other components to the
+% default compartment
+for n = 1 : stateCount
+    if strcmp(modelStruct.states(n).type, 'isSpecie'),
+        if isempty(modelStruct.states(n).compartment),
+            modelStruct.states(n).compartment = compartmentName;
+        end
+    elseif strcmp(modelStruct.states(n).type, 'isCompartment'),
+        if isempty(modelStruct.states(n).compartment),
+            modelStruct.states(n).compartment = compartmentName;
+        end
+    elseif  strcmp(modelStruct.states(n).type, ''),
+        % for testing reasons I have to provide several standard SBML
+        % parameters
+        modelStruct.states(n).type = 'isSpecie';
+        modelStruct.states(n).unittype = 'amount';
+        modelStruct.states(n).compartment = compartmentName;
+    end
+end
+for n = 1 : parameterCount
+    if strcmp(modelStruct.parameters(n).type, 'isSpecie'),
+        if isempty(modelStruct.parameters(n).compartment),
+            modelStruct.parameters(n).compartment = compartmentName;
+        end
+    elseif strcmp(modelStruct.parameters(n).type, 'isCompartment'),
+        if isempty(modelStruct.parameters(n).compartment),
+            modelStruct.parameters(n).compartment = compartmentName;
+        end
+    elseif strcmp(modelStruct.parameters(n).type, ''),
+        % for testing reasons I have to provide several standard SBML
+        % parameters
+        modelStruct.parameters(n).type = 'isParameter';
+        modelStruct.parameters(n).unittype = '';
+        modelStruct.parameters(n).compartment = '';
+    end
+end
+for n = 1 : variableCount
+    if strcmp(modelStruct.variables(n).type, 'isSpecie'),
+        if isempty(modelStruct.variables(n).compartment),
+            modelStruct.variables(n).compartment = compartmentName;
+        end
+    elseif strcmp(modelStruct.variables(n).type, 'isCompartment'),
+        if isempty(modelStruct.variables(n).compartment),
+            modelStruct.variables(n).compartment = compartmentName;
+        end
+    elseif  strcmp(modelStruct.variables(n).type, ''),
+        modelStruct.variables(n).type = 'isParameter';
+        modelStruct.variables(n).unittype = '';
+        modelStruct.variables(n).compartment = '';
+    end
+end
+% now we add the default compartment as SBmodel parameter with value = 1
+% and type = 'isCompartment'
+modelStruct.parameters(parameterCount+1).name = compartmentName;
+modelStruct.parameters(parameterCount+1).value = 1;
+modelStruct.parameters(parameterCount+1).type = 'isCompartment';
+modelStruct.parameters(parameterCount+1).compartment = '';
+
+if ~silentFlag,
+    message{1} = 'Success!';
+    message{2} = char([double('Default compartment "'), double(compartmentName), double('" has been added to the SBmodel as:')]);
+    message{3} = char([double('Parameter No.'), double(num2str(parameterCount+1)), double(' value = 1 and type = isCompartment')]);
+    messageOutput(message, 3);
+end
+
+changedModel = SBmodel(modelStruct);
+
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/checkCompartmentsForLoop.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/checkCompartmentsForLoop.m
new file mode 100644
index 0000000000000000000000000000000000000000..cbdce0653b1ae6adfb6f18ca2991085fe6a4170b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/checkCompartmentsForLoop.m
@@ -0,0 +1,133 @@
+function [loopFound] = checkCompartmentsForLoop(model, varargin)
+% checkCompartmentsForLoop
+% Helper function for the SBML export of models. The function preprocesses
+% SBmodels compartment definitions and prints out error message if
+% a loop is constructed over outside compartment elements.
+%
+% USAGE:
+% ======
+% [loopFound] = checkCompartmentsForLoop(model)
+%
+% model: SBmodel with compartment defintions to check
+%
+% loopFound: boolean value, true if loop is detected
+
+% Information:
+% ============
+% Author: Gunnar Drews, gunnar.drews@uni-rostock.de
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF SBmodel
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~strcmp('SBmodel',class(model)),
+    error('Function only defined for SBmodels.');
+end
+% get the datastructure of the model
+sbm = SBstruct(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK EXTRA INPUT ARGUMENT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+silentFlag = 0;
+if nargin == 2,
+   silentFlag = varargin{1};
+end
+
+loopFound = true;
+
+    [compartmentList, sbmodelCompartmentKind, sbmodelKindIndex] = fetchCompartments(model);
+    
+    % try to find way till root Compartment for all defined compartments
+    for startCompartmentIndex = 1 : length(compartmentList),
+        passedCompartments = [];
+        compartmentList(startCompartmentIndex);
+        found = way2RootCompartment(startCompartmentIndex);
+        if ~found,
+            return
+        end
+    end
+    
+    loopFound = false;
+
+
+
+    function [found] = way2RootCompartment(compartmentIndex)
+    
+        found = false;
+        
+        % look wether compartment is defined as state, parameter or
+        % variable
+        switch(sbmodelCompartmentKind(compartmentIndex))
+            case 0
+                kind = 'state';
+                outsideCompartment = sbm.states(sbmodelKindIndex(compartmentIndex)).compartment;
+            case 1
+                kind = 'parameter';
+                outsideCompartment = sbm.parameters(sbmodelKindIndex(compartmentIndex)).compartment;
+            case 2
+                kind = 'variable';
+                outsideCompartment = sbm.variables(sbmodelKindIndex(compartmentIndex)).compartment;
+        end
+        
+        % determine wether start compartment has been passed already (if
+        % loop is constructed) if yes print error and stop
+        result = find(passedCompartments == startCompartmentIndex);
+        if ~isempty(result),
+            % loop detected construct error message
+            if ~silentFlag,
+                errorIndex = 1;
+                error{errorIndex} = 'On the way to root compartment a loop has been detected for compartment: ';
+                errorIndex = errorIndex + 1;
+                startCompartmentName = char(compartmentList(startCompartmentIndex));
+                sbmodelCompartmentIndex = num2str(sbmodelKindIndex(startCompartmentIndex));
+                error{errorIndex} = char([double(startCompartmentName), double(' ('), double(kind), double(' No.'), double(sbmodelCompartmentIndex), double(')')]);
+                errorIndex = errorIndex + 1;
+                error{errorIndex} =  'Defined relationships:';
+                errorIndex = errorIndex + 1;
+                error{errorIndex} = char(double(startCompartmentName));
+                for index = 1 : length(passedCompartments),
+                    switch(sbmodelCompartmentKind(passedCompartments(index))),
+                        case 0
+                            kind = 'state';
+                        case 1
+                            kind = 'parameter';
+                        case 2
+                            kind = 'variable';
+                    end
+                    passedCompartmentName = char(compartmentList(passedCompartments(index)));
+                    sbmodelCompartmentIndex = num2str(sbmodelKindIndex(passedCompartments(index)));
+                    error{errorIndex} = char([double(error{errorIndex}), double(' -> '), double(passedCompartmentName), double(' ('), double(kind), double(' No.'), double(sbmodelCompartmentIndex), double(')')]);
+                end
+                messageOutput(error, 1);
+            end
+            return
+        end
+        
+                
+        % recursive abort condition (root compartment found)
+        if isempty(outsideCompartment),
+            found = true;
+            return
+        else % outsideCompartment is not root, test upper level compartment
+            
+            newCompartmentIndex = matchStringOnArray(outsideCompartment, compartmentList);
+            if newCompartmentIndex,
+                passedCompartments((length(passedCompartments)+1)) = newCompartmentIndex;
+                found = way2RootCompartment(newCompartmentIndex);
+            else
+                % found outside compartment is not valid
+                if ~silentFlag,
+                    errorIndex = 1;
+                    error{errorIndex} = 'On the way to root compartment an invalid outside compartment definition has been detected for compartment: ';
+                    errorIndex = errorIndex + 1;
+                    error{errorIndex} = char([double(char(compartmentList(startCompartmentIndex))), double(' ('), double(kind), double(' No.'), double(num2str(sbmodelKindIndex(startCompartmentIndex))), double(')')]);
+                    errorIndex = 1;
+                    error{errorIndex} = char([double('Invalid outside compartment: '), double(outsideCompartment)]);
+                    messageOutput(error, 1);
+                end
+                return
+            end
+        end
+    end % way2RootCompartment
+
+end % of testSBMLCompartmentSettings
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/checkNamesInSBmodel.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/checkNamesInSBmodel.m
new file mode 100644
index 0000000000000000000000000000000000000000..ba3b93c06730ddd07f09650f213a10ce1d37faa0
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/checkNamesInSBmodel.m
@@ -0,0 +1,283 @@
+function [namesOK] = checkNamesInSBmodel(model, varargin)
+% checkNamesInSBmodel
+% checks the used names in the given SBmodel (empty name fields and names
+% used more than once)
+%
+%
+% USAGE:
+% ======
+% [namesOK] = checkSBmodelNamesForDoublets(model)
+%
+% model: SBmodel where names are to test
+% 
+% namesOK: true if no errors in name definitions where found
+%          otherwise false
+%
+
+% Information:
+% ============
+% Author: Gunnar Drews, gunnar.drews@uni-rostock.de
+
+silentFlag = 0;
+if (nargin == 2)
+    silentFlag = varargin{1};
+end
+
+
+namesOK = false;
+emptyNames = {};
+emptyNamesIndex = 1;
+nameError = false;
+errorGroup = {};
+errorName = '';
+nameDoubletError = false;
+modelStruct = SBstruct(model);
+variableCount = length(modelStruct.variables);
+
+% check names of SBmodel states 
+stateNames = {};
+index = 1;
+for n = 1 : length(modelStruct.states),
+    name = modelStruct.states(n).name;
+    if strcmp(name, ''),
+        emptyNames{emptyNamesIndex} = char([double('State No. '), double(numstr(n))]);
+        emptyNamesIndex = emptyNamesIndex + 1;
+        nameError = true;
+    else
+        if matchStringOnArray(name, stateNames),
+            errorGroup{1} = 'States';
+            errorGroup{2} = 'States';
+            errorName = name;
+            nameDoubletError = true;
+        else
+            stateNames{index} = name;
+            index = index + 1;
+        end
+    end
+end
+% check names of SBmodel parameters
+parameterNames = {};
+index = 1;
+if ~nameDoubletError,
+    for n = 1 : length(modelStruct.parameters),
+        name = modelStruct.parameters(n).name;
+        if strcmp(name, ''),
+            emptyNames{emptyNamesIndex} = char([double('Parameter No. '), double(numstr(n))]);
+            emptyNamesIndex = emptyNamesIndex + 1;
+            nameError = true;
+        else
+            if matchStringOnArray(name, stateNames),
+                errorGroup{1} = 'States';
+                errorGroup{2} = 'Parameters';
+                errorName = name;
+                nameDoubletError = true;
+            elseif matchStringOnArray(name, parameterNames),
+                errorGroup{1} = 'Parameters';
+                errorGroup{2} = 'Parameters';
+                errorName = name;
+                nameDoubletError = true;
+            else
+                parameterNames{index} = name;
+                index = index + 1;
+            end
+        end
+    end
+end
+% check names of SBmodel variables
+variableNames = {};
+index = 1;
+if ~nameDoubletError,
+    for n = 1 : length(modelStruct.variables),
+        name = modelStruct.variables(n).name;
+        if strcmp(name, ''),
+            emptyNames{emptyNamesIndex} = char([double('Variable No. '), double(numstr(n))]);
+            emptyNamesIndex = emptyNamesIndex + 1;
+            nameError = true;
+        else
+            if matchStringOnArray(name, stateNames),
+                errorGroup{1} = 'States';
+                errorGroup{2} = 'Variables';
+                errorName = name;
+                nameDoubletError = true;
+            elseif matchStringOnArray(name, parameterNames),
+                errorGroup{1} = 'Parameters';
+                errorGroup{2} = 'Variables';
+                errorName = name;
+                nameDoubletError = true;
+            elseif matchStringOnArray(name, variableNames),
+                errorGroup{1} = 'Variables';
+                errorGroup{2} = 'Variables';
+                errorName = name;
+                nameDoubletError = true;
+            else
+                variableNames{index} = name;
+                index = index + 1;
+            end
+        end
+    end
+end
+% check names of SBmodel reactions
+reactionNames = {};
+index = 1;
+if ~nameDoubletError,
+    for n = 1 : length(modelStruct.reactions),
+        name = modelStruct.reactions(n).name;
+        if strcmp(name, ''),
+            emptyNames{emptyNamesIndex} = char([double('Reaction No. '), double(numstr(n))]);
+            emptyNamesIndex = emptyNamesIndex + 1;
+            nameError = true;
+        else
+            if matchStringOnArray(name, stateNames),
+                errorGroup{1} = 'States';
+                errorGroup{2} = 'Reactions';
+                errorName = name;
+                nameDoubletError = true;
+            elseif matchStringOnArray(name, parameterNames),
+                errorGroup{1} = 'Parameters';
+                errorGroup{2} = 'Reactions';
+                errorName = name;
+                nameDoubletError = true;
+            elseif matchStringOnArray(name, variableNames),
+                errorGroup{1} = 'Variables';
+                errorGroup{2} = 'Reactions';
+                errorName = name;
+                nameDoubletError = true;
+            elseif matchStringOnArray(name, reactionNames),
+                errorGroup{1} = 'Reactions';
+                errorGroup{2} = 'Reactions';
+                errorName = name;
+                nameDoubletError = true;
+            else
+                reactionNames{index} = name;
+                index = index + 1;
+            end
+        end
+    end
+end
+% check names of SBmodel functions
+functionNames = {};
+index = 1;
+if ~nameDoubletError,
+    for n = 1 : length(modelStruct.functions),
+        name = modelStruct.functions(n).name;
+        if strcmp(name, ''),
+            emptyNames{emptyNamesIndex} = char([double('Function No. '), double(numstr(n))]);
+            emptyNamesIndex = emptyNamesIndex + 1;
+            nameError = true;
+        else
+            if matchStringOnArray(name, stateNames),
+                errorGroup{1} = 'States';
+                errorGroup{2} = 'Functions';
+                errorName = name;
+                nameDoubletError = true;
+            elseif matchStringOnArray(name, parameterNames),
+                errorGroup{1} = 'Parameters';
+                errorGroup{2} = 'Functions';
+                errorName = name;
+                nameDoubletError = true;
+            elseif matchStringOnArray(name, variableNames),
+                errorGroup{1} = 'Variables';
+                errorGroup{2} = 'Functions';
+                errorName = name;
+                nameDoubletError = true;
+            elseif matchStringOnArray(name, reactionNames),
+                errorGroup{1} = 'Reactions';
+                errorGroup{2} = 'Functions';
+                errorName = name;
+                nameDoubletError = true;
+            elseif matchStringOnArray(name, functionNames),
+                errorGroup{1} = 'Reactions';
+                errorGroup{2} = 'Functions';
+                errorName = name;
+                nameDoubletError = true;
+            else
+                functionNames{index} = name;
+                index = index + 1;
+            end
+        end
+    end
+end
+% check names of SBmodel events
+eventNames = {};
+index = 1;
+if ~nameDoubletError,
+    for n = 1 : length(modelStruct.events),
+        name = modelStruct.events(n).name;
+        if strcmp(name, ''),
+            emptyNames{emptyNamesIndex} = char([double('Event No. '), double(numstr(n))]);
+            emptyNamesIndex = emptyNamesIndex + 1;
+            nameError = true;
+        else
+            if matchStringOnArray(name, stateNames),
+                errorGroup{1} = 'States';
+                errorGroup{2} = 'Events';
+                errorName = name;
+                nameDoubletError = true;
+            elseif matchStringOnArray(name, parameterNames),
+                errorGroup{1} = 'Parameters';
+                errorGroup{2} = 'Events';
+                errorName = name;
+                nameDoubletError = true;
+            elseif matchStringOnArray(name, variableNames),
+                errorGroup{1} = 'Variables';
+                errorGroup{2} = 'Events';
+                errorName = name;
+                nameDoubletError = true;
+            elseif matchStringOnArray(name, reactionNames),
+                errorGroup{1} = 'Reactions';
+                errorGroup{2} = 'Events';
+                errorName = name;
+                nameDoubletError = true;
+            elseif matchStringOnArray(name, functionNames),
+                errorGroup{1} = 'Reactions';
+                errorGroup{2} = 'Events';
+                errorName = name;
+                nameDoubletError = true;
+            elseif matchStringOnArray(name, eventNames),
+                errorGroup{1} = 'Events';
+                errorGroup{2} = 'Events';
+                errorName = name;
+                nameDoubletError = true;
+            else
+                eventNames{index} = name;
+                index = index + 1;
+            end
+        end
+    end
+end
+
+errorMessage = {};
+errorIndex = 1;
+if nameError,
+    errorMessage{errorIndex} = 'The following SBmodel components have no defined name(s):';
+    errorIndex = errorIndex + 1;
+    for n = 1 : length(emptyNames),
+        errorMessage{errorIndex} = emptyNames(n);
+        errorIndex = errorIndex + 1;
+    end
+    errorMessage{errorIndex} = '';
+    errorIndex = errorIndex + 1;
+end
+if nameDoubletError,
+    errorMessage{errorIndex} = char([double('The SBmodel component "'), double(errorName), double('" has been found ')]);
+    errorIndex = errorIndex + 1;
+    if strcmp(errorGroup{1}, errorGroup{2}),
+        errorMessage{errorIndex} = char([double(' twice in SBmodel '), double(errorGroup{1}), double('.')]);
+        errorIndex = errorIndex + 1;
+    else
+        errorMessage{errorIndex} = char([double(' in SBmodel '), double(errorGroup{1}), double('and SBmodel '), double(errorGroup{2}), double('.')]);
+        errorIndex = errorIndex + 1;
+    end
+    errorMessage{errorIndex} = '';
+    errorIndex = errorIndex + 1;
+end
+
+if (nameError || nameDoubletError),
+    if ~silentFlag,
+        messageOutput(errorMessage, 1);
+    end
+else    
+    namesOK = true;
+end
+
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/convert2SBMLNotes.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/convert2SBMLNotes.m
new file mode 100644
index 0000000000000000000000000000000000000000..e46ba5f2f71977a7acfd044589991adc26bb836f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/convert2SBMLNotes.m
@@ -0,0 +1,48 @@
+function [SBMLNotes] = convert2SBMLNotes(SBmodelNotes)
+% convert2SBMLNotes
+% converts the notes string given by SBTOOLBOX that they can be used
+% through the SBML Toolbox (conversion to XHTML)
+%
+% USAGE:
+% ======
+% SBMLNotes = convert2SBMLNotes(SBmodelNotes)
+%
+% SBmodelNotesString: a notes string created manually at the commmand
+%                     window or in one of the GUIs
+% SBMLNotes: a string in XHTML format that can be converted by SBML Toolbox
+
+% Information:
+% ============
+% Author: Gunnar Drews, gunnar.drews@uni-rostock.de
+
+SBMLNotes = '';
+newline = sprintf('\n');
+notesStart = char([double('<html xmlns="http://www.w3.org/1999/xhtml">'), double(newline), double('<body>'), double(newline)]);
+notesEnd = char([double('</body>'), double(newline), double('</html>')]);
+
+% test wether input string is empty
+if (~isempty(SBmodelNotes)),
+    % test wether notes do already contain xhtml tags
+   if ((~isempty(strfind(SBmodelNotes, '<html'))) || (~isempty(strfind(SBmodelNotes, '<body')))), 
+       disp(sprintf('WARNING: "SBmodelNotes" already contain XHTML tags, conversion aborted!\nNotes are passed through without changes.'));
+       SBMLNotes = SBmodelNotes;
+   else
+       % test wether notes field contains several lines
+       linebreaks = strfind(SBmodelNotes, newline);
+       if (isempty(linebreaks)),
+           % build single line SBML notes
+           SBMLNotes = char([double(notesStart), double(SBmodelNotes), double(notesEnd)]);
+       else
+           % build multiple line SBML notes
+           SBMLNotes = notesStart;
+           startPos = 1;
+           for index = 1 : length(linebreaks),
+               endPos = linebreaks(index)-1;
+               SBMLNotes = char([double(SBMLNotes), double('<p>'), double(SBmodelNotes(startPos:endPos)), double('</p>'), double(newline)]);
+               startPos = linebreaks(index)+1;
+           end
+           SBMLNotes = char([double(SBMLNotes), double('<p>'), double(SBmodelNotes(startPos:length(SBmodelNotes))), double('</p>'), double(newline), double(notesEnd)]);
+       end
+   end
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/existsNameInSBmodel.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/existsNameInSBmodel.m
new file mode 100644
index 0000000000000000000000000000000000000000..eb2c6952045c5725d4f691b9f7bbdbbf41d61948
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/existsNameInSBmodel.m
@@ -0,0 +1,45 @@
+function [boolvalue] = existsNameInSBmodel(model, name, varargin)
+% existsNameInSBmodel
+% checks wether a given name is already used in the given SBmodel
+%
+%
+% USAGE:
+% ======
+% [boolvalue] = existsNameInSBmodel(model, name)
+%
+% model: SBmodel
+% name: string to test model for existence
+% 
+% boolvalue: true if there is already defined a component with the given
+%            name otherwise false
+%
+
+% Information:
+% ============
+% Author: Gunnar Drews, gunnar.drews@uni-rostock.de
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF SBmodel
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~strcmp('SBmodel',class(model)),
+    error('Function only defined for SBmodels.');
+end
+
+silentFlag = 0;
+if (nargin == 2)
+    silentFlag = 0;
+elseif (nargin == 3)
+    silentFlag = varargin{1};
+end
+
+boolvalue = false;
+
+% fetch all names used within given SBmodel and test wether given name is
+% already present
+names = getAllNamesFromSBmodel(model);
+rowPos = matchStringOnArray(name, names);
+if (rowPos > 0)
+    boolvalue = true;
+end
+
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/fetchCompartments.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/fetchCompartments.m
new file mode 100644
index 0000000000000000000000000000000000000000..191be1afdab4cbb5e667716e4f8b0c31a6f056ed
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/fetchCompartments.m
@@ -0,0 +1,96 @@
+function [compartmentList, origin, origIndex] = fetchCompartments(model)
+% getCompartments
+% looks wether there are predefined compartments in a SBmodel
+%
+%
+% USAGE:
+% ======
+% [compartmentList, origin, origIndex] = getCompartments(model)
+%
+% model: search for preefined compartments within this SBmodel
+% 
+% compartmentList: list of predefined compartments found in the model
+%
+% origin: number that indicates where there compartment is defined
+%         0 -> states
+%         1 -> parameters
+%         2 -> variables
+%
+% origIndex: index of the array structure where the compartment is to
+%            find within SBmodel
+
+% Information:
+% ============
+% Author: Gunnar Drews, gunnar.drews@uni-rostock.de
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF SBmodel
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~strcmp('SBmodel',class(model)),
+    error('Function only defined for SBmodels.');
+end
+
+componentNames = [];
+compartmentList = [];
+origin = [];
+origIndex = [];
+nameIndex = 1;
+cindex = 1;
+aindex = 1;
+assignedCompartments = [];
+
+% get model structure
+sbm = SBstruct(model);
+statesCount=length(sbm.states);
+parametersCount=length(sbm.parameters);
+variablesCount=length(sbm.variables);
+
+% search states for compartments
+for k1 = 1 : statesCount,
+    componentNames{nameIndex} = sbm.states(k1).name;
+    nameIndex = nameIndex + 1;
+    if (strcmp(sbm.states(k1).type, 'isCompartment')),
+        compartmentList{cindex} = sbm.states(k1).name;
+        origin(cindex)=0;
+        origIndex(cindex)=k1;
+        cindex = cindex + 1;
+    end
+    if ~strcmp(sbm.states(k1).compartment, ''),
+        assignedCompartments{aindex}=sbm.states(k1).compartment;
+        aindex = aindex + 1;
+    end
+end
+
+% search parameters for compartments
+for k1 = 1 : parametersCount,
+    componentNames{nameIndex} = sbm.parameters(k1).name;
+    nameIndex = nameIndex + 1;
+    if (strcmp(sbm.parameters(k1).type, 'isCompartment')),
+        compartmentList{cindex} = sbm.parameters(k1).name;
+        origin(cindex)=1;
+        origIndex(cindex)=k1;
+        cindex = cindex + 1;
+    end
+    if ~strcmp(sbm.parameters(k1).compartment, ''),
+        assignedCompartments{aindex}=sbm.parameters(k1).compartment;
+        aindex = aindex + 1;
+    end
+end
+
+% search variables for compartments
+for k1 = 1 : variablesCount,
+    componentNames{nameIndex} = sbm.variables(k1).name;
+    nameIndex = nameIndex + 1;
+    if (strcmp(sbm.variables(k1).type, 'isCompartment')),
+        compartmentList{cindex} = sbm.variables(k1).name;
+        origin(cindex)=2;
+        origIndex(cindex)=k1;
+        cindex = cindex + 1;
+    end
+    if ~strcmp(sbm.variables(k1).compartment, ''),
+        assignedCompartments{aindex}=sbm.variables(k1).compartment;
+        aindex = aindex + 1;
+    end
+end
+
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/getAllNamesFromSBmodel.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/getAllNamesFromSBmodel.m
new file mode 100644
index 0000000000000000000000000000000000000000..9b60e6d9366c52a68bc99b085d56a8e1628439bc
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/getAllNamesFromSBmodel.m
@@ -0,0 +1,82 @@
+function [nameList] = getAllNamesFromSBmodel(model, varargin)
+% getAllNamesFromSBmodel
+% collects the names of all components used in the given SBmodel
+%
+%
+% USAGE:
+% ======
+% [nameList] = getAllNamesFromSBmodel(model)
+%
+% model: SBmodel
+% 
+% nameList: list of component names used in the model
+%
+
+% Information:
+% ============
+% Author: Gunnar Drews, gunnar.drews@uni-rostock.de
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF SBmodel
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~strcmp('SBmodel',class(model)),
+    error('Function only defined for SBmodels.');
+end
+
+silentFlag = 0;
+if nargin == 1,
+    silentFlag = 0;
+elseif nargin == 2,
+    silentFlag = varargin{1};
+end
+
+componentNames = [];
+nameIndex = 1;
+
+% get model structure and count model components
+sbm = SBstruct(model);
+statesCount = length(sbm.states);
+parametersCount = length(sbm.parameters);
+variablesCount = length(sbm.variables);
+reactionsCount = length(sbm.reactions);
+eventsCount = length(sbm.events);
+functionsCount = length(sbm.functions);
+
+% fetch state names
+for k1 = 1 : statesCount,
+    componentNames{nameIndex} = sbm.states(k1).name;
+    nameIndex = nameIndex + 1;
+end
+
+% fetch parameter names
+for k1 = 1 : parametersCount,
+    componentNames{nameIndex} = sbm.parameters(k1).name;
+    nameIndex = nameIndex + 1;
+end
+
+% fetch variable names
+for k1 = 1 : variablesCount,
+    componentNames{nameIndex} = sbm.variables(k1).name;
+    nameIndex = nameIndex + 1;
+end
+
+% fetch reaction names
+for k1 = 1 : reactionsCount,
+    componentNames{nameIndex} = sbm.reactions(k1).name;
+    nameIndex = nameIndex + 1;
+end
+
+% fetch event names
+for k1 = 1 : eventsCount,
+    componentNames{nameIndex} = sbm.events(k1).name;
+    nameIndex = nameIndex + 1;
+end
+
+% fetch functions names
+for k1 = 1 : functionsCount,
+    componentNames{nameIndex} = sbm.functions(k1).name;
+    nameIndex = nameIndex + 1;
+end
+
+nameList = componentNames;
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/getSBmodelFunctionNames.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/getSBmodelFunctionNames.m
new file mode 100644
index 0000000000000000000000000000000000000000..6084fa23f224ac6bef200fbb62b0f14df6dc805c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/getSBmodelFunctionNames.m
@@ -0,0 +1,31 @@
+function [modelFunctionNames] = getSBmodelFunctionNames(model)
+% getSBmodelFunctionNames
+% gives back a structure containing all function names defined
+% in this SBmodel
+%
+% USAGE:
+% ======
+% [modelFunctionNames] = getSBmodelFunctionNames(SBmodel) 
+%
+% SBmodel: SBmodel 
+%
+% modelFunctionNames: structure with all function names
+
+% Information:
+% ============
+% Author: Gunnar Drews, gunnar.drews@uni-rostock.de
+
+% CHECK IF SBmodel
+if ~strcmp('SBmodel',class(model)),
+    error('Function only defined for SBmodels.');
+end
+% get the datastructure of the model
+sbm = SBstruct(model);
+
+modelFunctionNames = {};
+% fetch all names of defined function within given SBmodel
+for index = 1 : length(sbm.functions),
+    modelFunctionNames{index} = sbm.functions(index).name;
+end
+
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/isSBmodelName.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/isSBmodelName.m
new file mode 100644
index 0000000000000000000000000000000000000000..bc50645750446afa84a615005c9a1e98ec6ea10d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/isSBmodelName.m
@@ -0,0 +1,37 @@
+function [boolvalue] = isSBmodelName(name, varargin)
+% isSBmodelName
+% checks wether a given name complies with the used name standard
+% of the SBmodel
+%
+%
+% USAGE:
+% ======
+% [boolvalue] = isSBmodelName(name)
+%
+% name: string to test SBmodel compliance
+% 
+% boolvalue: true if the given name complies with the SBmodel name
+%            conventions 
+%
+
+% Information:
+% ============
+% Author: Gunnar Drews, gunnar.drews@uni-rostock.de
+
+silentFlag = 0;
+if (nargin == 2)
+    silentFlag = 0;
+elseif (nargin == 3)
+    silentFlag = varargin{1};
+end
+
+boolvalue = false;
+
+%use regular expression to test, wether given name complies with SBmodel
+%name conventions
+result=regexp(name, '([A-Z]|[a-z]|_)+([A-Z]|[a-z]|[0-9]|_)*');
+if (result == 1)
+    boolvalue = true;
+end
+
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/testSBMLsettings.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/testSBMLsettings.m
new file mode 100644
index 0000000000000000000000000000000000000000..edc3289c01b63c2ae616538adffda23320358a2f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/modeltools/testSBMLsettings.m
@@ -0,0 +1,420 @@
+function [sbmlCompliant, onlyDefaultCompartmentError] = testSBMLsettings(model, varargin)
+% testSBMLSettings
+% checks wether all SBML setings in a given SBmodel are made
+%
+%
+% USAGE:
+% ======
+% [sbmlCompliant, onlyCompartmentError] = testSBMLsettings(model)
+%
+% model: SBmodel where SBML settings are to test
+% 
+% sbmlCompliant: true if all SBML settings have been made and are correct
+% onlyDefaultCompartmentError: true if only errors concerning a missing default
+%                              compartment have been found
+%
+
+% Information:
+% ============
+% Author: Gunnar Drews, gunnar.drews@uni-rostock.de
+
+silentFlag = 0;
+if (nargin == 2)
+    silentFlag = varargin{1};
+end
+
+rootCompartments = 0;
+compartmentCount = 0;
+compartmentList = {};
+notCompartmentCount = 0;
+componentList = {};
+
+sbmlCompliant = false;
+onlyDefaultCompartmentError = false;
+errorMessages = [];
+errorNumber = 0;
+
+modelStruct = SBstruct(model);
+stateCount = length(modelStruct.states);
+parameterCount = length(modelStruct.parameters);
+variableCount = length(modelStruct.variables);
+
+% at first we perform a check for all compartments
+for n = 1 : stateCount
+    if strcmp(modelStruct.states(n).type, 'isCompartment')
+        compartmentCount = compartmentCount + 1;
+        compartmentList{compartmentCount} = modelStruct.states(n).name;
+        if strcmp(modelStruct.states(n).compartment, '')
+            rootCompartments = rootCompartments + 1;
+        end
+    else
+        notCompartmentCount = notCompartmentCount + 1;
+        componentList{notCompartmentCount} = modelStruct.states(n).name;
+    end
+end
+for n = 1 : parameterCount
+    if strcmp(modelStruct.parameters(n).type, 'isCompartment')
+        compartmentCount = compartmentCount + 1;
+        compartmentList{compartmentCount} = modelStruct.parameters(n).name;
+        if strcmp(modelStruct.parameters(n).compartment, '')
+            rootCompartments = rootCompartments + 1;
+        end
+    else
+        notCompartmentCount = notCompartmentCount + 1;
+        componentList{notCompartmentCount} = modelStruct.parameters(n).name;
+    end
+end
+for n = 1 : variableCount
+    if strcmp(modelStruct.variables(n).type, 'isCompartment')
+        compartmentCount = compartmentCount + 1;
+        compartmentList{compartmentCount} = modelStruct.variables(n).name;
+        if strcmp(modelStruct.variables(n).compartment, '')
+            rootCompartments = rootCompartments + 1;
+        end
+    else
+        notCompartmentCount = notCompartmentCount + 1;
+        componentList{notCompartmentCount} = modelStruct.variables(n).name;
+    end
+end
+
+if (compartmentCount == 0),
+    if ~silentFlag,
+        compartmentError{1} = 'This SBmodel contains no compartments!';
+        compartmentError{2} = 'That means that an SBML export is not possible at the moment because at least one compartment is needed that "stores" all components described in your model.';
+        compartmentError{3} = 'If there are no special requirements to the surrounding compartment you can use the "addDefaultCompartment" function.';
+        messageOutput(compartmentError, 1);
+    end
+    onlyDefaultCompartmentError = true;
+elseif (rootCompartments == 0),
+    if ~silentFlag,
+        compartmentError{1} = 'This SBmodel contains no root compartment!';
+        compartmentError{2} = 'SBML needs one root compartment that "stores" all components described in your model.';
+        messageOutput(compartmentError, 1);
+    end
+    onlyDefaultCompartmentError = true;
+elseif (rootCompartments > 1),
+    if ~silentFlag,
+        compartmentError{1} = 'This SBmodel contains too many root compartments!';
+        compartmentError{2} = 'SBML supports only one root compartment, to bypass this circumstance give function: "addDefaultCompartment" a try.';
+        messageOutput(compartmentError, 1);
+    end
+    onlyDefaultCompartmentError = true;
+end
+foundLoop = checkCompartmentsForLoop(model, 1);
+if foundLoop,
+    compartmentError{1} = 'A loop has been detected within the compartment definitions. This cannot be fixed automatically.';
+    compartmentError{2} = 'Use "checkCompartmentsForLoop(SBmodel)" to find out what might be the problem.';
+    compartmentError{3} = 'SBML export would not be possible under that circumstances.';
+    messageOutput(compartmentError, 1);
+    onlyDefaultCompartmentError = false;
+    return
+end
+
+for n = 1 : stateCount
+    name = modelStruct.states(n).name;
+    type = modelStruct.states(n).type;
+    unittype = modelStruct.states(n).unittype;
+    compartment = modelStruct.states(n).compartment;
+    localError = false;
+    if strcmp(type, 'isSpecie')
+        % test wether the unittype definitions match the SBML conventions
+        if ~(strcmp(unittype, 'amount') || strcmp(unittype, 'concentration'))
+            localError = true;
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = char([double(name), double(' -> SBmodel state No.: '), double(num2str(n))]);
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = 'contains a bad unittype definition! ("model.states(no).unittype" can be "amount" or "concentration")';
+        elseif isempty(compartment)
+            localError = true;
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = char([double(name), double(' -> SBmodel state No.: '), double(num2str(n))]);
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = 'this specie is not assigned to a compartment, this is not allowed for a SBML export! ("model.states(no).compartment" has to be filled)';
+        elseif ~isempty(compartment),
+            % test wether the compartment the actual component is located
+            % in is assigned as compartment
+            % afterwards test wether the compartment doesn't exists or
+            % wasn't not assigned to be a compartment
+            if (isempty(compartmentList) || ~matchStringOnArray(compartment, compartmentList))
+                localError = true;
+                if matchStringOnArray(compartment, componentList)
+                    errorNumber = errorNumber + 1;
+                    errorMessages{errorNumber} = char([double(name), double(' -> SBmodel state No.: '), double(num2str(n))]);
+                    errorNumber = errorNumber + 1;
+                    errorMessages{errorNumber} = char([double('This '), double(type(3:length(type))), double(' is assigned to the compartment "'), double(compartment), double('" which is not marked as one.')]);
+                else
+                    errorNumber = errorNumber + 1;
+                    errorMessages{errorNumber} = char([double(name), double(' -> SBmodel state No.: '), double(num2str(n))]);
+                    errorNumber = errorNumber + 1;
+                    errorMessages{errorNumber} = char([double('The compartment "'), double(compartment), double('" this '), double(type(3:length(type))), double(' is assigned to, doesn''t exist in this SBmodel')]);
+                end    
+            end
+        end       
+    elseif strcmp(type, 'isCompartment')
+        if ~isempty(unittype),
+            localError = true;
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = char([double(name), double(' -> SBmodel state No.: '), double(num2str(n)), double('  '),double(unittype)]);
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = 'components marked as SBML Compartments are not allowed to have a unittype (clear "model.states(no).unittype" field)';
+        elseif isempty(compartment),
+            % not needed at the moment, because if number of root
+            % compartments is wrong the functions is stopped in an ealier
+            % state
+        elseif ~isempty(compartment),
+            % test wether the compartment the actual component is located
+            % in is assigned as compartment
+            % afterwards test wether the compartment doesn't exists or
+            % wasn't not assigned to be a compartment
+            if (isempty(compartmentList) || ~matchStringOnArray(compartment, compartmentList))
+                localError = true;
+                if matchStringOnArray(compartment, componentList)
+                    errorNumber = errorNumber + 1;
+                    errorMessages{errorNumber} = char([double(name), double(' -> SBmodel state No.: '), double(num2str(n))]);
+                    errorNumber = errorNumber + 1;
+                    errorMessages{errorNumber} = char([double('This '), double(type(3:length(type))), double(' is assigned to the compartment "'), double(compartment), double('" which is not marked as one.')]);
+                else
+                    errorNumber = errorNumber + 1;
+                    errorMessages{errorNumber} = char([double(name), double(' -> SBmodel state No.: '), double(num2str(n))]);
+                    errorNumber = errorNumber + 1;
+                    errorMessages{errorNumber} = char([double('The compartment "'), double(compartment), double('" this '), double(type(3:length(type))), double(' is assigned to, doesn''t exist in this SBmodel')]);
+                end    
+            end
+        end
+    elseif strcmp(type, 'isParameter')
+        if (length(unittype) ~= 0)
+            localError = true;
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = char([double(name), double(' -> SBmodel state No.: '), double(num2str(n))]);
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = 'components marked as SBML Parameter are not allowed to have a unittype (clear "model.states(no).unittype" field)';
+        elseif ~isempty(compartment),
+            localError = true;
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = char([double(name), double(' -> SBmodel state No.: '), double(num2str(n))]);
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = 'components marked as SBML Parameter are not allowed to be located within a compartment (clear (clear "model.states(no).compartment" field)';
+        end 
+    else
+        localError = true;
+        errorNumber = errorNumber + 1;
+        errorMessages{errorNumber} = char([double(name), double(' -> SBmodel state No.: '), double(num2str(n))]);
+        errorNumber = errorNumber + 1;
+        errorMessages{errorNumber} = 'no SBML type information found (possibilities for "model.states(no).type" are "isSpecie", "isParameter", "isCompartment")';
+    end
+    if localError,
+        errorNumber = errorNumber + 1;
+        errorMessages{errorNumber} = ' ';
+        localError = false;
+    end
+end
+
+for n = 1 : parameterCount
+    name = modelStruct.parameters(n).name;
+    type = modelStruct.parameters(n).type;
+    unittype = modelStruct.parameters(n).unittype;
+    compartment = modelStruct.parameters(n).compartment;
+    localError = false;
+    if strcmp(type, 'isSpecie')
+        % test wether the unittype definitions match the SBML conventions
+        if ~(strcmp(unittype, 'amount') || strcmp(unittype, 'concentration'))
+            localError = true;
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = char([double(name), double(' -> SBmodel parameter No.: '), double(num2str(n))]);
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = 'contains a bad unittype definition! ("model.parameters(no).unittype" can be "amount" or "concentration")';
+        elseif isempty(compartment),
+            localError = true;
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = char([double(name), double(' -> SBmodel parameter No.: '), double(num2str(n))]);
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = 'this specie is not assigned to a compartment, this is not allowed for a SBML export! ("model.parameters(no).compartment" has to be filled)';
+        elseif ~isempty(compartment),
+            % test wether the compartment the actual component is located
+            % in is assigned as compartment
+            % afterwards test wether the compartment doesn't exists or
+            % wasn't not assigned to be a compartment
+            if (isempty(compartmentList) || ~matchStringOnArray(compartment, compartmentList))
+                localError = true;
+                if matchStringOnArray(compartment, componentList)
+                    errorNumber = errorNumber + 1;
+                    errorMessages{errorNumber} = char([double(name), double(' -> SBmodel parameter No.: '), double(num2str(n))]);
+                    errorNumber = errorNumber + 1;
+                    errorMessages{errorNumber} = char([double('This '), double(type(3:length(type))), double(' is assigned to the compartment "'), double(compartment), double('" which is not marked as one.')]);
+                else
+                    errorNumber = errorNumber + 1;
+                    errorMessages{errorNumber} = char([double(name), double(' -> SBmodel parameter No.: '), double(num2str(n))]);
+                    errorNumber = errorNumber + 1;
+                    errorMessages{errorNumber} = char([double('The compartment "'), double(compartment), double('" this '), double(type(3:length(type))), double(' is assigned to, doesn''t exist in this SBmodel')]);
+                end    
+            end
+        end       
+    elseif strcmp(type, 'isCompartment')
+        if ~isempty(unittype),
+            localError = true;
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = char([double(name), double(' -> SBmodel parameter No.: '), double(num2str(n))]);
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = 'components marked as SBML Compartments are not allowed to have a unittype (clear "model.parameters(no).unittype" field)';
+        elseif isempty(compartment),
+            % not needed at the moment, because if number of root
+            % compartments is wrong the functions is stopped in an ealier
+            % state
+        elseif ~isempty(compartment),
+            % test wether the compartment the actual component is located
+            % in is assigned as compartment
+            % afterwards test wether the compartment doesn't exists or
+            % wasn't not assigned to be a compartment
+            if (isempty(compartmentList) || ~matchStringOnArray(compartment, compartmentList))
+                localError = true;
+                if matchStringOnArray(compartment, componentList)
+                    errorNumber = errorNumber + 1;
+                    errorMessages{errorNumber} = char([double(name), double(' -> SBmodel parameter No.: '), double(num2str(n))]);
+                    errorNumber = errorNumber + 1;
+                    errorMessages{errorNumber} = char([double('This '), double(type(3:length(type))), double(' is assigned to the compartment "'), double(compartment), double('" which is not marked as one.')]);
+                else
+                    errorNumber = errorNumber + 1;
+                    errorMessages{errorNumber} = char([double(name), double(' -> SBmodel parameter No.: '), double(num2str(n))]);
+                    errorNumber = errorNumber + 1;
+                    errorMessages{errorNumber} = char([double('The compartment "'), double(compartment), double('" this '), double(type(3:length(type))), double(' is assigned to, doesn''t exist in this SBmodel')]);
+                end    
+            end
+        end
+    elseif strcmp(type, 'isParameter')
+        if ~isempty(unittype),
+            localError = true;
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = char([double(name), double(' -> SBmodel parameter No.: '), double(num2str(n))]);
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = 'components marked as SBML Parameter are not allowed to have a unittype (clear "model.parameters(no).unittype" field)';
+        elseif ~isempty(compartment),
+            localError = true;
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = char([double(name), double(' -> SBmodel parameter No.: '), double(num2str(n))]);
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = 'components marked as SBML Parameter are not allowed to be located within a compartment (clear (clear "model.parameters(no).compartment" field)';
+        end 
+    else
+        localError = true;
+        errorNumber = errorNumber + 1;
+        errorMessages{errorNumber} = char([double(name), double(' -> SBmodel parameter No.: '), double(num2str(n))]);
+        errorNumber = errorNumber + 1;
+        errorMessages{errorNumber} = 'no SBML type information found (possibilities for "model.parameters(no).type" are "isSpecie", "isParameter", "isCompartment")';
+    end
+    if localError
+        errorNumber = errorNumber + 1;
+        errorMessages{errorNumber} = ' ';
+        localError = false;
+    end
+end
+
+for n = 1 : variableCount
+    name = modelStruct.variables(n).name;
+    type = modelStruct.variables(n).type;
+    unittype = modelStruct.variables(n).unittype;
+    compartment = modelStruct.variables(n).compartment;
+    localError = false;
+    if strcmp(type, 'isSpecie')
+        % test wether the unittype definitions match the SBML conventions
+        if ~(strcmp(unittype, 'amount') || strcmp(unittype, 'concentration'))
+            localError = true;
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = char([double(name), double(' -> SBmodel variable No.: '), double(num2str(n))]);
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = 'contains a bad unittype definition! ("model.variables(no).unittype" can be "amount" or "concentration")';
+        elseif isempty(compartment),
+            localError = true;
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = char([double(name), double(' -> SBmodel variable No.: '), double(num2str(n))]);
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = 'this specie is not assigned to a compartment, this is not allowed for a SBML export! ("model.variables(no).compartment" has to be filled)';
+        elseif ~isempty(compartment),
+            % test wether the compartment the actual component is located
+            % in is assigned as compartment
+            % afterwards test wether the compartment doesn't exists or
+            % wasn't not assigned to be a compartment
+            if (isempty(compartmentList) || ~matchStringOnArray(compartment, compartmentList))
+                localError = true;
+                if matchStringOnArray(compartment, componentList)
+                    errorNumber = errorNumber + 1;
+                    errorMessages{errorNumber} = char([double(name), double(' -> SBmodel variable No.: '), double(num2str(n))]);
+                    errorNumber = errorNumber + 1;
+                    errorMessages{errorNumber} = char([double('This '), double(type(3:length(type))), double(' is assigned to the compartment "'), double(compartment), double('" which is not marked as one.')]);
+                else
+                    errorNumber = errorNumber + 1;
+                    errorMessages{errorNumber} = char([double(name), double(' -> SBmodel variable No.: '), double(num2str(n))]);
+                    errorNumber = errorNumber + 1;
+                    errorMessages{errorNumber} = char([double('The compartment "'), double(compartment), double('" this '), double(type(3:length(type))), double(' is assigned to, doesn''t exist in this SBmodel')]);
+                end    
+            end
+        end       
+    elseif strcmp(type, 'isCompartment')
+        if ~isempty(unittype),
+            localError = true;
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = char([double(name), double(' -> SBmodel variable No.: '), double(num2str(n))]);
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = 'components marked as SBML Compartments are not allowed to have a unittype (clear "model.variables(no).unittype" field)';
+        elseif isempty(compartment),
+            % not needed at the moment, because if number of root
+            % compartments is wrong the functions is stopped in an ealier
+            % state
+        elseif ~isempty(compartment),
+            % test wether the compartment the actual component is located
+            % in is assigned as compartment
+            % afterwards test wether the compartment doesn't exists or
+            % wasn't not assigned to be a compartment
+            if (isempty(compartmentList) || ~matchStringOnArray(compartment, compartmentList))
+                localError = true;
+                if matchStringOnArray(compartment, componentList)
+                    errorNumber = errorNumber + 1;
+                    errorMessages{errorNumber} = char([double(name), double(' -> SBmodel variable No.: '), double(num2str(n))]);
+                    errorNumber = errorNumber + 1;
+                    errorMessages{errorNumber} = char([double('This '), double(type(3:length(type))), double(' is assigned to the compartment "'), double(compartment), double('" which is not marked as one.')]);
+                else
+                    errorNumber = errorNumber + 1;
+                    errorMessages{errorNumber} = char([double(name), double(' -> SBmodel variable No.: '), double(num2str(n))]);
+                    errorNumber = errorNumber + 1;
+                    errorMessages{errorNumber} = char([double('The compartment "'), double(compartment), double('" this '), double(type(3:length(type))), double(' is assigned to, doesn''t exist in this SBmodel')]);
+                end    
+            end
+        end
+    elseif strcmp(type, 'isParameter')
+        if ~isempty(unittype),
+            localError = true;
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = char([double(name), double(' -> SBmodel variable No.: '), double(num2str(n))]);
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = 'components marked as SBML Parameter are not allowed to have a unittype (clear "model.variables(no).unittype" field)';
+        elseif ~isempty(compartment),
+            localError = true;
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = char([double(name), double(' -> SBmodel variable No.: '), double(num2str(n))]);
+            errorNumber = errorNumber + 1;
+            errorMessages{errorNumber} = 'components marked as SBML Parameter are not allowed to be located within a compartment (clear (clear "model.variables(no).compartment" field)';
+        end 
+    else
+        localError = true;
+        errorNumber = errorNumber + 1;
+        errorMessages{errorNumber} = char([double(name), double(' -> SBmodel variable No.: '), double(num2str(n))]);
+        errorNumber = errorNumber + 1;
+        errorMessages{errorNumber} = 'no SBML type information found (possibilities for "model.variables(no).type" are "isSpecie", "isParameter", "isCompartment")';
+    end
+    if localError
+        errorNumber = errorNumber + 1;
+        errorMessages{errorNumber} = ' ';
+        localError = false;
+    end
+end
+
+if (errorNumber > 0),
+    if (~silentFlag),
+        messageOutput(errorMessages, 1);
+    end
+elseif onlyDefaultCompartmentError,
+    return
+else    
+    sbmlCompliant = true;
+end
+
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isBracketstring.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isBracketstring.m
new file mode 100644
index 0000000000000000000000000000000000000000..13527ce6c84e547dc01bbc2f57a091a1c35e3ecc
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isBracketstring.m
@@ -0,0 +1,45 @@
+function [isBracketstring] = isBracketstring(string)
+%isBracketstring
+% a simple test wether the given string contains squared brackets, curly
+% brackets or parenthesis
+%
+% USAGE:
+% ======
+%
+% [boolean] = isBracketString(string)
+%
+% string: test string
+%
+% boolean: true if string contains (, ), {, }, [ or ]
+%          false otherwise
+
+% Information:
+% ============
+% Author: Gunnar Drews, gunnar.drews@uni-rostock.de
+
+    if strfind(string, '('),
+        isBracketstring = 1;
+        return;
+    end
+    if strfind(string, ')'),
+        isBracketstring = 1;
+        return;
+    end
+    if strfind(string, '['),
+        isBracketstring = 1;
+        return;
+    end
+    if strfind(string, ']'),
+        isBracketstring = 1;
+        return;
+    end
+    if strfind(string, '{'),
+        isBracketstring = 1;
+        return;
+    end
+    if strfind(string, '}'),
+        isBracketstring = 1;
+        return;
+    end
+    isBracketstring = 0;
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isBracketstringWellformed.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isBracketstringWellformed.m
new file mode 100644
index 0000000000000000000000000000000000000000..d5bae1eb0fb584fd80b2fe60c78e1e91320990a5
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isBracketstringWellformed.m
@@ -0,0 +1,44 @@
+function [wellFormed] = isBracketstringWellformed(string)
+%isBracketStringWellformed
+% checks wether the order of opened and closed braces as well as
+% their count is valid
+%
+% USAGE:
+% ======
+%
+% [wellFormed] = isBracketstringWellformed(string)
+%
+% string: i.e. a formula where correct bracketing is to test
+%
+% wellFormed: true or false
+
+% Information:
+% ============
+% Author: Gunnar Drews, gunnar.drews@uni-rostock.de
+
+    wellFormed = 0;
+    openedBrackets={'{','[','('};
+    closedBrackets={'}',']',')'};
+    stack='';
+    index=1;
+    for k = 1 : length(string),
+        if ~isempty(strmatchSB(string(k), openedBrackets)),
+            stack(index) = string(k);
+            % stack
+            index = index + 1;
+        elseif ~isempty(strmatchSB(string(k), closedBrackets)),
+            if isempty(stack),
+                return;
+            elseif (int8(string(k))-1 == int8(stack(index-1))) || (int8(string(k))-2 == int8(stack(index-1))),
+                index = index - 1;
+                stack = stack(1:index-1);
+                % stack
+            else
+                return;
+            end
+        end
+    end
+    if isempty(stack),
+        wellFormed = 1;
+    end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isClosedBracket.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isClosedBracket.m
new file mode 100644
index 0000000000000000000000000000000000000000..b361b6fbded090d0ec6c06d3c0251fd0a6066a1f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isClosedBracket.m
@@ -0,0 +1,27 @@
+function [isClosedBracket] = isClosedBracket(character)
+%isClosedBracket
+% checks wether the given character is a closing bracket
+%
+%
+% USAGE:
+% ======
+%
+% boolean = isClosedBracket(character)
+%
+% character: a letter or sign
+%
+% boolean: 1 if character is ']', '}' or ')'
+%          otherwise 0
+
+% Information:
+% ============
+% Author: Gunnar Drews, gunnar.drews@uni-rostock.de
+
+    closedBrackets=['}',']',')'];
+    if strfind(closedBrackets, character),
+        isClosedBracket = 1;
+        return;
+    else
+        isClosedBracket = 0;
+    end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isFOSign.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isFOSign.m
new file mode 100644
index 0000000000000000000000000000000000000000..fe8475e4c835c61d3e35cba14446cb0665b11049
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isFOSign.m
@@ -0,0 +1,25 @@
+function [boolean] = isFOSign(character)
+% isFOSign
+% checks, wether character is sign of "First Order" (+ or -)
+%
+% USAGE:
+% ======
+%
+% [boolean] = isFOSign(character)
+%
+% character: test character
+%
+% boolean: true if character is mathematical operator of first order (+ or -)
+%          otherwise false
+
+% Information:
+% ============
+% Author: Gunnar Drews, gunnar.drews@uni-rostock.de
+
+boolean = false;
+
+if (strcmp(character, '+') || strcmp(character, '-')),
+    boolean = true;
+end
+
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isFunctionIdentifier.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isFunctionIdentifier.m
new file mode 100644
index 0000000000000000000000000000000000000000..aa4db7f7a0d670ba4cabbb6f7ff2fb2fc33ffcc6
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isFunctionIdentifier.m
@@ -0,0 +1,59 @@
+function [isFunctionIdentifier] = isFunctionIdentifier(identifier, varargin)
+%isFunctionIdentifier
+% checks wether identifier is a reserved function identifier
+%
+% USAGE:
+% ======
+% [boolean] = isFunctionIdentifier(identifier)
+% identifier: test token
+%
+% boolean: true if identifier is a reserved MATLAB function identifier
+%          false otherwise
+%
+% [boolean] = isFunctionIdentifier(identifier, SBmodel) 
+% identifier: test token
+% SBmodel: SBmodel 
+%
+% boolean: true if identifier is a reserved MATLAB function identifier or
+%          if identifier is already used in the supplied SBmodel
+%          false otherwise
+%
+% For a list of reserved function identifiers take a look at the code,
+% please!
+
+% Information:
+% ============
+% Author: Gunnar Drews, gunnar.drews@uni-rostock.de
+
+modelGiven = false;
+if nargin == 2,
+    % get all function names from given model
+    sbmodel = varargin{1};
+    modelGiven = true;
+end
+
+    isFunctionIdentifier = false;
+    % Corresponding MATLAB expressions
+    FunctionExpressions = {'acos', 'asin', 'atan', 'ceil', 'log',...
+        'log10', 'power', 'acos', 'acosh', 'acot', 'acoth', 'acsc',...
+        'acsch', 'asec', 'asech', 'asin', 'asinh', 'atan', 'atanh',...
+        'exp', 'logbase', 'piecewise', 'and', 'or', 'gt', 'lt', 'eq',...
+        'ge', 'le', 'mod', 'piecewiseSB', 'andSB', 'orSB'};
+    for index = 1 : length(FunctionExpressions),
+        if strcmp(identifier, FunctionExpressions{index}),
+            isFunctionIdentifier = true;
+            return;
+        end
+    end
+    
+    % if SBmodel given, test function names there, too
+    if modelGiven,
+        functionNames = getSBmodelFunctionNames(sbmodel);
+        for index = 1 : length(functionNames),
+            if strcmp(identifier, functionNames{index}),
+                isFunctionIdentifier = true;
+                return;
+            end
+        end
+    end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isLetter2.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isLetter2.m
new file mode 100644
index 0000000000000000000000000000000000000000..f622b0f2a3300ef31f2ff472373e0658fc413816
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isLetter2.m
@@ -0,0 +1,35 @@
+function [isLetter] = isLetter2(character)
+%isLetter2
+% tests wether a given character is a Letter
+% (it's a simpler and faster implementation for stringhandling)
+%
+% USAGE:
+% ======
+%
+% [boolean]= isLetter2(character)
+%
+% character: character to test
+%
+% boolean: true if character is A, ..., Z, a, ..., z, "_"
+%          otherwise false
+%
+% For more details take a look at the code, please!
+
+% Information:
+% ============
+% Author: Gunnar Drews, gunnar.drews@uni-rostock.de
+
+    % Option 1: letterMatrix = ['a':'z','A':'Z','_'];
+    %           if strfind(letterMatrix, character),
+    %
+    % the latter variant could be usefull if reactionnames can consist of
+    % more special characters i.e. ('#', '_', '%', '$', ...)
+    % 
+    %at the moment this one is the fastest
+    if isstrprop(character, 'alpha') || (character == '_'),
+        isLetter = 1;
+    else
+        isLetter = 0;
+    end
+
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isNumber.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isNumber.m
new file mode 100644
index 0000000000000000000000000000000000000000..812ca609997019bf600e269475a02e995bcabb89
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isNumber.m
@@ -0,0 +1,36 @@
+function [isNumber] = isNumber(character)
+%isNumber
+% tests wether a given character belongs to a digit or float
+% (it's a simpler and faster implementation for stringhandling)
+%
+% USAGE:
+% ======
+%
+% [boolean]= isNumber(character)
+%
+% character: character to test
+%
+% boolean: true if character is 0, ..., 9, "."
+%          otherwise false
+%
+% For more details take a look at the code, please!
+
+% Information:
+% ============
+% Author: Gunnar Drews, gunnar.drews@uni-rostock.de
+
+    % if isstrprop(character, 'digit'),
+    % => slowest implementation for our needs
+    %
+    % if isnumeric(character),
+    % => seems to be fast for it self, but slows down the complete
+    % function!?!
+    % the following one showed the best results in "Profiler" runs
+    numberMatrix = ['0':'9','.'];
+    if strfind(numberMatrix, character),
+        isNumber = 1;
+    else
+        isNumber = 0;
+    end
+
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isOpenedBracket.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isOpenedBracket.m
new file mode 100644
index 0000000000000000000000000000000000000000..46d5ac0c42038b0ee31d931342d789727a311f56
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isOpenedBracket.m
@@ -0,0 +1,27 @@
+function [isOpenedBracket] = isOpenedBracket(character)
+%isOpenedBracket
+% checks wether the given character is an opening bracket
+%
+%
+% USAGE:
+% ======
+%
+% boolean = isOpenedBracket(character)
+%
+% character: a letter or sign
+%
+% boolean: 1 if character is '[', '{' or '('
+%          otherwise 0
+
+% Information:
+% ============
+% Author: Gunnar Drews, gunnar.drews@uni-rostock.de
+
+    openedBrackets = ['{','[','('];
+    if strfind(openedBrackets, character),
+        isOpenedBracket = 1;
+        return;
+    else
+        isOpenedBracket = 0;
+    end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isSOSign.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isSOSign.m
new file mode 100644
index 0000000000000000000000000000000000000000..e3dd07a41737aad97fb2725b592543eb3ea09e47
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isSOSign.m
@@ -0,0 +1,25 @@
+function [boolean] = isSOSign(character)
+% isSOSign
+% checks, wether character is sign of "Second Order" (* or /)
+%
+% USAGE:
+% ======
+%
+% [boolean] = isSOSign(character)
+%
+% character: test character
+%
+% boolean: true if character is mathematical operator of second order
+%          (* or /) otherwise false
+
+% Information:
+% ============
+% Author: Gunnar Drews, gunnar.drews@uni-rostock.de
+
+boolean = false;
+
+if (strcmp(character, '*') || strcmp(character, '/')),
+    boolean = true;
+end
+
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isSign.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isSign.m
new file mode 100644
index 0000000000000000000000000000000000000000..29ec7a19dfa031ec2e1b13ab404dc9c2075372df
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/isSign.m
@@ -0,0 +1,27 @@
+function [isSign] = isSign(character)
+%isSign
+% checks wether the given character is an maths operator
+%
+%
+% USAGE:
+% ======
+%
+% boolean = isSign(character)
+%
+% character: a letter or sign
+%
+% boolean: 1 if character is '+', '-', '*', '/' or '^'
+%          otherwise 0
+
+% Information:
+% ============
+% Author: Gunnar Drews, gunnar.drews@uni-rostock.de
+
+    matchMatrix = ['+','-','*','/','^'];
+    if strfind(matchMatrix, character),
+        isSign = 1;
+    else
+        isSign = 0;
+    end
+
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/matchStringOnArray.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/matchStringOnArray.m
new file mode 100644
index 0000000000000000000000000000000000000000..c8d8dff78807e8a6a9c3b2d92780a73da2316dda
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/matchStringOnArray.m
@@ -0,0 +1,29 @@
+function [rowPos] = matchStringOnArray(patternString, matchingArray)
+%matchStringOnArray
+% A string match function which gives back the row number of the
+% first occurence of the pattern string within the matching array.
+% (it's a simpler and faster implementation for stringhandling)
+%
+% USAGE:
+% ======
+% [rowPos] = matchStringOnArray(patternString, matchingArray)
+%
+% matchingArray: an array of String
+% patternString: a string to test for occurance in the array
+%
+% rowPos: 0 if string doesn't occur in array
+%         >0 (row number) otherwise -> can be used as boolean value
+
+% Information:
+% ============
+% Author: Gunnar Drews, gunnar.drews@uni-rostock.de
+
+rowPos = 0;
+searchResult = strcmp(patternString, matchingArray);
+for n1 = 1 : length(searchResult),
+    if searchResult(n1),
+        rowPos = n1;
+        break;
+    end
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/messageOutput.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/messageOutput.m
new file mode 100644
index 0000000000000000000000000000000000000000..1b0d5061d4f0442ee89ef35e7ea8a55aad42ec22
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBMLexport/stringtools/messageOutput.m
@@ -0,0 +1,117 @@
+function [success] = messageOutput(messages, varargin)
+% messageOutput
+% prints a formated page containing all messages given through the cell
+% array contained in the variable messages
+%
+%
+% USAGE:
+% ======
+% [success] = messageOutput(messages)
+% [success] = messageOutput(messages, type)
+%
+% messages: cell array with output messages
+% type:     kind of messages (1 -> error, 2 -> warning, 3 -> info)
+%           if the user doesn't provide a type variable the messagetype
+%           will be set to info
+% 
+% success: boolean value, false in case that something went wrong
+%
+
+% Information:
+% ============
+% Author: Gunnar Drews, gunnar.drews@uni-rostock.de
+
+%test function parameter
+silentFlag = 0;
+messageType = '';
+if (nargin == 1)
+    silentFlag = 0;
+    messageType = 'Info: ';
+elseif (nargin == 2)
+    switch varargin{1}
+        case 1 
+            messageType = 'Error: ';
+        case 2
+            messageType = 'Warning: ';
+        case 3
+            messageType = 'Info: ';
+        otherwise
+            disp('Sorry, but this message type is not supported!');
+            success = false;
+            return
+    end    
+elseif (nargin == 3)
+    silentFlag = varargin{2};
+end
+
+% prepare line start
+lineStart = [32, 32, 35, 32];
+
+%prepare line end
+lineEnd = [32, 35, 32, 32];
+
+%prepare titleline
+%fetch calling M-file
+[ST, I] = dbstack;
+title = [double(messageType), double(ST(2).name)];
+titleline = [lineStart, title, getBlanks(length(lineStart) + length(title)), lineEnd];
+
+% prepare borderline
+for column = 1 : 90
+    if (column < 3 || column > 88)
+        borderline(column) = 32;
+    else
+        borderline(column) = 35;
+    end
+end
+
+% message output header
+sprintf('\n');
+disp(char(borderline));
+disp(char(titleline));
+disp(char(borderline));
+% message output body
+for lineNo = 1 : length(messages)
+    % build output message line
+    if length(messages{lineNo}) < 82
+        line = [lineStart, double(messages{lineNo}), getBlanks(length(lineStart) + length(messages{lineNo})), lineEnd];
+    else
+        % in case that line exceeds 82 letters split the line at a blank at
+        % the latest possible position in front of column 82
+        help = messages{lineNo};
+        while (length(help) > 82)
+            splitIndices = regexp(help, ' ');
+            lastIndex = 1;
+            for index = 2 : length(splitIndices)
+                if (splitIndices(index) > 82)
+                    text = help(1:splitIndices(lastIndex));
+                    help = help((splitIndices(lastIndex) + 1) : length(help));
+                    break;
+                elseif (index == length(splitIndices))
+                    text = help(1:splitIndices(index));
+                    help = help((splitIndices(index) + 1) : length(help));
+                    break;
+                end
+                lastIndex = index;
+            end
+            line = [lineStart, double(text), getBlanks(length(lineStart) + length(text)), lineEnd];
+            disp(char(line));
+        end
+        line = [lineStart, double(help), getBlanks(length(lineStart) + length(help)), lineEnd];
+    end
+    disp(char(line));
+end
+disp(char(borderline));
+
+success = true;
+return
+
+
+% helper function to get number of blanks
+function [blanks] = getBlanks(start)
+blankscount = 86 - start;
+blanks = [];
+for i = 1 : blankscount
+    blanks(i) = 32;
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBconvertName2Id.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBconvertName2Id.m
new file mode 100644
index 0000000000000000000000000000000000000000..64e28a07e7ce524cb7cef42be8bfbe567a48d5e1
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBconvertName2Id.m
@@ -0,0 +1,281 @@
+function [newSBMLmodel] = SBconvertName2Id(SBMLmodel)
+% Convert all ids and corresponding names
+% for compartments, species, parameters, reactions
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+newIds = {};
+oldIds = {};
+names = {};
+
+% COMPARTMENTS
+for k=1:length(SBMLmodel.compartment),
+    if ~isempty(SBMLmodel.compartment(k).name),
+        testid_base = regexprep(SBMLmodel.compartment(k).name,'\W','_');
+        testid = testid_base;
+        % check if testid exists already as new ids
+        ext = 1;
+        while 1,
+            if ~isempty(strmatchSB(testid,newIds,'exact')),
+                testid = sprintf('%s_%d',testid_base,ext);
+            else
+                break;
+            end
+            ext = ext+1;
+        end
+        % check if numeric or underscore as first character then add something
+        x = double(testid(1));
+        if x == double('_') || (x >= 48 && x <= 57),
+            testid = ['C' testid];
+        end       
+        % go on
+        names{end+1} = SBMLmodel.compartment(k).name;
+        oldIds{end+1} = SBMLmodel.compartment(k).id;
+        newIds{end+1} = testid;
+        SBMLmodel.compartment(k).id = testid;
+    end
+end
+
+% SPECIES
+for k=1:length(SBMLmodel.species),
+    if ~isempty(SBMLmodel.species(k).name),
+        testid_base = regexprep(SBMLmodel.species(k).name,'\W','_');
+        testid = testid_base;
+        % check if testid exists already as new ids
+        ext = 1;
+        while 1,
+            if ~isempty(strmatchSB(testid,newIds,'exact')),
+                testid = sprintf('%s_%d',testid_base,ext);
+            else
+                break;
+            end
+            ext = ext+1;
+        end
+        % check if numeric or underscore as first character then add something
+        x = double(testid(1));
+        if x == double('_') || (x >= 48 && x <= 57),
+            testid = ['S_' testid];
+        end       
+        % go on        
+        names{end+1} = SBMLmodel.species(k).name;
+        oldIds{end+1} = SBMLmodel.species(k).id;
+        newIds{end+1} = testid;
+        SBMLmodel.species(k).id = testid;        
+    end
+end
+
+% PARAMETERS
+for k=1:length(SBMLmodel.parameter),
+    if ~isempty(SBMLmodel.parameter(k).name),
+        testid_base = regexprep(SBMLmodel.parameter(k).name,'\W','_');
+        testid = testid_base;
+        % check if testid exists already as new ids
+        ext = 1;
+        while 1,
+            if ~isempty(strmatchSB(testid,newIds,'exact')),
+                testid = sprintf('%s_%d',testid_base,ext);
+            else
+                break;
+            end
+            ext = ext+1;
+        end
+        % check if numeric or underscore as first character then add something
+        x = double(testid(1));
+        if x == double('_') || (x >= 48 && x <= 57),
+            testid = ['P_' testid];
+        end       
+        % go on           
+        names{end+1} = SBMLmodel.parameter(k).name;
+        oldIds{end+1} = SBMLmodel.parameter(k).id;
+        newIds{end+1} = testid;
+        SBMLmodel.parameter(k).id = testid;        
+    end
+end
+
+% REACTIONS
+for k=1:length(SBMLmodel.reaction),
+    if ~isempty(SBMLmodel.reaction(k).name),
+        testid_base = regexprep(SBMLmodel.reaction(k).name,'\W','_');
+        testid = testid_base;
+        % check if testid exists already as new ids
+        ext = 1;
+        while 1,
+            if ~isempty(strmatchSB(testid,newIds,'exact')),
+                testid = sprintf('%s_%d',testid_base,ext);
+            else
+                break;
+            end
+            ext = ext+1;
+        end
+        % check if numeric or underscore as first character then add something
+        x = double(testid(1));
+        if x == double('_') || (x >= 48 && x <= 57),
+            testid = ['R_' testid];
+        end       
+        % go on            
+        names{end+1} = SBMLmodel.reaction(k).name;
+        oldIds{end+1} = SBMLmodel.reaction(k).id;
+        newIds{end+1} = testid;
+        SBMLmodel.reaction(k).id = testid;                
+    end
+end
+
+% EVENTS
+for k=1:length(SBMLmodel.event),
+    if ~isempty(SBMLmodel.event(k).name),
+        testid_base = regexprep(SBMLmodel.event(k).name,'\W','_');
+        testid = testid_base;
+        % check if testid exists already as new ids
+        ext = 1;
+        while 1,
+            if ~isempty(strmatchSB(testid,newIds,'exact')),
+                testid = sprintf('%s_%d',testid_base,ext);
+            else
+                break;
+            end
+            ext = ext+1;
+        end
+        % check if numeric or underscore as first character then add something
+        x = double(testid(1));
+        if x == double('_') || (x >= 48 && x <= 57),
+            testid = ['E_' testid];
+        end       
+        % go on                
+        names{end+1} = SBMLmodel.event(k).name;
+        oldIds{end+1} = SBMLmodel.event(k).id;
+        newIds{end+1} = testid;
+        SBMLmodel.event(k).id = testid;                
+    end
+end
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add regexp logic to oldIds
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(oldIds),
+    oldIds{k} = strcat('\<',oldIds{k},'\>');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Exchange all oldIds agaist new Ids
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% Compartment ids in species
+for k=1:length(SBMLmodel.species),
+    SBMLmodel.species(k).compartment = regexprep(SBMLmodel.species(k).compartment,oldIds,newIds);
+end
+
+% Species ids in reactions 
+for k=1:length(SBMLmodel.reaction),
+    % Reactants
+    for k2=1:length(SBMLmodel.reaction(k).reactant)
+        SBMLmodel.reaction(k).reactant(k2).species = regexprep(SBMLmodel.reaction(k).reactant(k2).species,oldIds,newIds);
+    end
+    % Products
+    for k2=1:length(SBMLmodel.reaction(k).product)
+        SBMLmodel.reaction(k).product(k2).species = regexprep(SBMLmodel.reaction(k).product(k2).species,oldIds,newIds);
+    end
+    % Modifiers
+    for k2=1:length(SBMLmodel.reaction(k).modifier)
+        SBMLmodel.reaction(k).modifier(k2).species = regexprep(SBMLmodel.reaction(k).modifier(k2).species,oldIds,newIds);
+    end
+    % Kinetic Law
+    if ~isempty(SBMLmodel.reaction(k).kineticLaw),
+        SBMLmodel.reaction(k).kineticLaw.formula = regexprep(SBMLmodel.reaction(k).kineticLaw.formula,oldIds,newIds);
+        SBMLmodel.reaction(k).kineticLaw.math = regexprep(SBMLmodel.reaction(k).kineticLaw.math,oldIds,newIds);
+    end
+end
+
+% Ids in rule definitions
+for k=1:length(SBMLmodel.rule),
+    % variable
+    SBMLmodel.rule(k).variable = regexprep(SBMLmodel.rule(k).variable,oldIds,newIds);
+    % species
+    SBMLmodel.rule(k).species = regexprep(SBMLmodel.rule(k).species,oldIds,newIds);
+    % compartment
+    SBMLmodel.rule(k).compartment = regexprep(SBMLmodel.rule(k).compartment,oldIds,newIds);
+    % formula
+    SBMLmodel.rule(k).formula = regexprep(SBMLmodel.rule(k).formula,oldIds,newIds);    
+end
+
+% Ids in event definitions
+for k=1:length(SBMLmodel.event),
+    % variable
+    SBMLmodel.event(k).trigger = regexprep(SBMLmodel.event(k).trigger,oldIds,newIds);
+    % assignments
+    for k2=1:length(SBMLmodel.event(k).eventAssignment),
+        SBMLmodel.event(k).eventAssignment(k2).variable = regexprep(SBMLmodel.event(k).eventAssignment(k2).variable,oldIds,newIds);
+        SBMLmodel.event(k).eventAssignment(k2).math = regexprep(SBMLmodel.event(k).eventAssignment(k2).math,oldIds,newIds);
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE LOCAL PARAMETERS IN REACTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% LOCAL PARAMETERS IN REACTIONS
+for k=1:length(SBMLmodel.reaction),
+    if ~isempty(SBMLmodel.reaction(k).kineticLaw),
+        newIds = {};
+        oldIds = {};
+        names = {};
+        for k2 = 1:length(SBMLmodel.reaction(k).kineticLaw.parameter)
+            if ~isempty(SBMLmodel.reaction(k).kineticLaw.parameter(k2).name),
+                testid_base = regexprep(SBMLmodel.reaction(k).kineticLaw.parameter(k2).name,'\W','_');
+                testid = testid_base;
+                % check if correct first character and fix it eventually
+                if double(testid(1))>=48 && double(testid(1))<=57,
+                    testid = sprintf('para_%s',testid);
+                end
+                % check if testid exists already as new ids
+                ext = 1;
+                while 1,
+                    if ~isempty(strmatchSB(testid,newIds,'exact')),
+                        testid = sprintf('%s_%d',testid_base,ext);
+                    else
+                        break;
+                    end
+                    ext = ext+1;
+                end
+                names{end+1} = SBMLmodel.reaction(k).kineticLaw.parameter(k2).name;
+                oldIds{end+1} = SBMLmodel.reaction(k).kineticLaw.parameter(k2).id;
+                newIds{end+1} = testid;
+                SBMLmodel.reaction(k).kineticLaw.parameter(k2).id = testid;
+            end
+        end
+        for k2=1:length(oldIds),
+            oldIds{k2} = strcat('\<',oldIds{k2},'\>');
+        end
+        SBMLmodel.reaction(k).kineticLaw.formula = regexprep(SBMLmodel.reaction(k).kineticLaw.formula,oldIds,newIds);
+        SBMLmodel.reaction(k).kineticLaw.math = regexprep(SBMLmodel.reaction(k).kineticLaw.math,oldIds,newIds);
+    end
+end
+
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% RETURN result
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+newSBMLmodel = SBMLmodel;
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBconvertSBML1.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBconvertSBML1.m
new file mode 100644
index 0000000000000000000000000000000000000000..c0af80e831ad63e654db6a3a9c01664ba18e266b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBconvertSBML1.m
@@ -0,0 +1,1045 @@
+function [SBstructure,errorMsg] = SBconvertSBML1(SBMLmodel)
+% SBconvertSBML1
+% Converting a SBML Level 1 MATLAB structure to the object model structure
+% used in the toolbox. Works for SBML Level 1, versions 1 and 2
+%
+% Private method 
+%
+% [SBstructure,errorMsg] = SBconvertSBML1(SBMLmodel);
+%
+% Simple error checking is provided. In the case of an error an empty
+% structure is returned. 
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INITIALIZE ERROR MESSAGES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+errorMsg = '';
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CREATE AN EMPTY SBSTRUCTURE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBstructure = struct(SBmodel());
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% NAME AND NOTES (INCLUDE IN STRUCTURE)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp(SBMLmodel.name,''),
+    % No name provided by the SBML model
+    SBstructure.name = 'Unknown name';
+else
+    % Use the name and the notes supplied in the SBMLmodel
+    SBstructure.name = SBMLmodel.name;
+end
+% Indicate in notes that the model has been created by import from SBML.
+SBstructure.notes = SBMLmodel.notes;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SOME COUNTER DEFINITIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% States and parameters are included in the structure in their order of
+% appearance. For variables no counters are needed, since their order 
+% is defined by the ordering of the scalar rules and not by their order of 
+% appearance (see below)
+numberStates = 1;
+numberParameters = 1;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ORDERING OF VARIABLES (SCALAR RULES)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Scalar rules lead always to the definition of variables. The order of
+% appearance of the rules is important and thus the order of appearance of
+% the variables should reflect the ordering of the rules. We determine an
+% array in which the the index i determines the priority of the scalar rule, and
+% the i-th array element the index of the corresponding scalar rule. Rate
+% rules do not have to be considered since they are evaluated at last
+% anyway
+orderScalarRules = strmatchSB('SBML_ASSIGNMENT_RULE',{SBMLmodel.rule.typecode});
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SPECIES (INCLUDE IN STRUCTURE)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Species of the model are included in the structure as follows:
+% Non-boundary species:
+%   - rate rule: as state (not supported by libSBML yet)
+%   - scalar rule: as variable 
+%   - no rule: as state
+%
+% Boundary species:
+%   - rate rule: as states (not supported by libSBML yet)
+%   - scalar rule: as variable
+%   - no rule: as parameter
+%
+% Initial values for species are assumed to be given in amount units.
+% They are converted to concentration units by dividing with the
+% compartment size. Specie values set by rules are not converted and taken
+% as they are.
+%
+speciesODElist = [];
+speciesODElistIndex = 1;
+% Check if there are any species. Otherwise an error message is set
+if isempty(SBMLmodel.species),
+%    errorMsg = sprintf('%s\n%s\n',errorMsg,'No species are defined in the SBML model');
+    warning('No species are defined in the SBML model - uncertain if model conversion will lead to a working SBmodel!');
+end
+% Cycle through all the species and determine how they are to be included
+% in the model structure
+for k1 = 1:length(SBMLmodel.species),
+    speciesName = SBMLmodel.species(k1).name;
+    initialAmount = SBMLmodel.species(k1).initialAmount;
+    speciesCompartmentName = SBMLmodel.species(k1).compartment;
+    % get the compartment size for this species
+    for k2 = 1:length(SBMLmodel.compartment),
+        if strcmp(speciesCompartmentName, SBMLmodel.compartment(k2).name),
+            compartmentSize = SBMLmodel.compartment(k2).volume;
+            if isempty(compartmentSize),
+                errorMsg = sprintf('%s\nNo compartment size defined for compartment ''%s''\n',errorMsg,speciesCompartmentName);
+                compartmentSize = 1; % set to whatever, error will still occurr!
+            end
+            break;
+        end
+    end
+    % Check the number of rules the species is in and get the index
+    % of the last rule the species is used in together with its type
+    % ('rate' or 'scalar') and the right hand side expression 'formula'
+    [numberRulesSpecies,lastRuleIndex,lastRuleType,lastRuleFormula,errorMsg] = getRules(speciesName,SBMLmodel,errorMsg);
+    if numberRulesSpecies > 1,
+        % Species defined by more than one rule => error
+        errorMsg = sprintf('%s\nSpecies ''%s'' defined by more than one rule\n',errorMsg,speciesName);
+    end
+    if SBMLmodel.species(k1).boundaryCondition == 0,
+        % Process all the species that DO NOT have a boundary condition
+        if numberRulesSpecies == 0,
+            % add species to the ODE list (for use below in ODE
+            % construction)
+            speciesODElist(speciesODElistIndex).name = speciesName;
+            speciesODElist(speciesODElistIndex).stateIndex = numberStates;
+            speciesODElistIndex = speciesODElistIndex + 1;
+            % Include species as state
+            SBstructure.states(numberStates).name = speciesName;
+            % Check if an initial amount is set for a species
+            if isempty(initialAmount),
+                errorMsg = sprintf('%s\nNo initial amount defined for species ''%s''\n',errorMsg,speciesName);
+            end           
+            % Convert initialAmount to concentration and include in SBstructure
+            SBstructure.states(numberStates).initialCondition = initialAmount/compartmentSize;
+            % Note that this state is a 'species'
+            % Notes are not used by the toolbox for other things as
+            % documentation
+            SBstructure.states(numberStates).notes = '';
+            % initialize type, compartment, and unittype fields
+            SBstructure.states(numberStates).type = 'isSpecie';
+            SBstructure.states(numberStates).compartment = SBMLmodel.species(k1).compartment;
+            SBstructure.states(numberStates).unittype = 'concentration';                
+            % Initialize the ODE field for this state
+            SBstructure.states(numberStates).ODE = '';
+            % Increment
+            numberStates = numberStates+1;
+        elseif numberRulesSpecies == 1,
+            % One rule has been detected for this species
+            % Before including the species in the model structure we have
+            % to check if this species is also used in reactions as product
+            % or reactant. In this case an error message will be issued.
+            reactionSpeciesPresent = checkReactionsForSpecies(speciesName,SBMLmodel);
+            if reactionSpeciesPresent,
+                % Species is also present in a reaction. This means the SBML
+                % model is inconsistent. => error
+                errorMsg = sprintf('%s\nSpecies ''%s'' defined by rule and altered by reactions\n',errorMsg,speciesName);
+            end
+            % Even in the case of an error we continue here with the
+            % processing - The error message will take care of returning
+            % an empty model structure at the end
+            if strcmp(lastRuleType,'rate'),
+                % Species added as a state, since rule of type 'rate'
+                SBstructure.states(numberStates).name = speciesName;
+                % check if an initial amount is set for a species
+                if isempty(initialAmount),
+                    errorMsg = sprintf('%s\nNo initial amount defined for species ''%s''\n',errorMsg,speciesName);
+                end           
+                % Convert initialAmount to concentration and include in SBstructure
+                SBstructure.states(numberStates).initialCondition = initialAmount/compartmentSize;
+                % Include the RHS formula as the ODE for this species state
+                SBstructure.states(numberStates).ODE = lastRuleFormula;
+                % Set a note that type of state is 'species'
+                SBstructure.states(numberStates).notes = '';
+                % initialize type, compartment, and unittype fields
+                SBstructure.states(numberStates).type = 'isParameter';
+                SBstructure.states(numberStates).compartment = '';
+                SBstructure.states(numberStates).unittype = '';                
+                % Increment
+                numberStates = numberStates+1;
+            else
+                % Species added as a variable, since rule of type 'scalar'
+                % Determine the index where to include the variable (based
+                % on the ordering of the scalar rules)
+                indexVariable = find(orderScalarRules==lastRuleIndex);
+                SBstructure.variables(indexVariable).name = speciesName;
+                SBstructure.variables(indexVariable).formula = lastRuleFormula;
+                SBstructure.variables(indexVariable).notes = '';
+                % initialize type, compartment, and unittype fields
+                SBstructure.variables(indexVariable).type = 'isParameter';
+                SBstructure.variables(indexVariable).compartment = '';
+                SBstructure.variables(indexVariable).unittype = '';
+            end
+        end
+        % The case where numberRulesSpecies > 1 does not have to be treated 
+        % here since already an error message is set above. This error
+        % message will lead to an empty model structure at the end. Even 
+        % if the error is set the rest of the model will be processed.
+        % This has the advantage that all errors can be
+        % detected at once and makes the control structure of this script
+        % simpler.
+    else
+        % Process all the species that DO have a boundary condition
+        if numberRulesSpecies == 0,
+            % Include boundary species as a parameter
+            SBstructure.parameters(numberParameters).name = speciesName;
+            % Check if an initial amount is set for a species
+            if isempty(initialAmount),
+                errorMsg = sprintf('%s\nNo initial amount defined for species ''%s''\n',errorMsg,speciesName);
+            end           
+            % Convert initialAmount to concentration and include in SBstructure
+            SBstructure.parameters(numberParameters).value = initialAmount/compartmentSize;
+            % Set note that type of the parameter is 'boundaey species'
+            SBstructure.parameters(numberParameters).notes = '';
+            % initialize type, compartment, and unittype fields
+            SBstructure.parameters(numberParameters).type = 'isParameter';
+            SBstructure.parameters(numberParameters).compartment = '';
+            SBstructure.parameters(numberParameters).unittype = '';
+            % Increment
+            numberParameters = numberParameters+1;
+        elseif numberRulesSpecies == 1,
+            % One rule has been detected for this species
+            % Boundary species may appear as products and reactants in
+            % reactions but they dont have to
+            if strcmp(lastRuleType,'rate'),
+                % Boundary species added as a state, since rule of type 'rate'
+                SBstructure.states(numberStates).name = speciesName;
+                % check if an initial amount is set for a species
+                if isempty(initialAmount),
+                    errorMsg = sprintf('%s\nNo initial amount defined for species ''%s''\n',errorMsg,speciesName);
+                end           
+                % Convert initialAmount to concentration and include in SBstructure
+                SBstructure.states(numberStates).initialCondition = initialAmount/compartmentSize;
+                % Include the RHS formula as the ODE for this species state
+                SBstructure.states(numberStates).ODE = lastRuleFormula;
+                % Set note that type of the state is 'boundary species'
+                SBstructure.states(numberStates).notes = '';
+                % initialize type, compartment, and unittype fields
+                SBstructure.states(numberStates).type = 'isParameter';
+                SBstructure.states(numberStates).compartment = '';
+                SBstructure.states(numberStates).unittype = '';
+                % Increment
+                numberStates = numberStates+1;
+            else
+                % Boundary species added as a variable, since rule of type 'scalar'
+                % Determine the index where to include the variable (based
+                % on the ordering of the scalar rules)
+                indexVariable = find(orderScalarRules==lastRuleIndex);
+                SBstructure.variables(indexVariable).name = speciesName;
+                SBstructure.variables(indexVariable).formula = lastRuleFormula;
+                SBstructure.variables(indexVariable).notes = '';
+                % initialize type, compartment, and unittype fields
+                SBstructure.variables(indexVariable).type = 'isParameter';
+                SBstructure.variables(indexVariable).compartment = '';
+                SBstructure.variables(indexVariable).unittype = '';
+            end
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PARAMETERS (INCLUDE IN STRUCTURE)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% First process the global parameters and check if rules exist for them
+%   - rate rule: as state
+%   - scalar rule: as variable
+%   - no rule: as parameter
+%
+% Then process the local parameters. They can only be parameters, no 
+% rules can exist for them. In case of collisions:
+%
+% parameter-parameter: colliding parameters are prefixed by their reaction 
+%                      names (global parameters are not prefixed)
+%
+% parameter-species: are prefixed by reaction name
+%
+% parameter-compartment: are prefixed by reaction name
+%
+% Start with global parameters
+for k = 1:length(SBMLmodel.parameter),
+    parameterName = SBMLmodel.parameter(k).name;
+    parameterValue = SBMLmodel.parameter(k).value;
+    % Check the number of rules the parameter is in and get the index
+    % of the last rule the parameter is used in together with its type
+    % ('rate' or 'scalar') and the right hand side expression 'formula'
+    [numberRulesParameter,lastRuleIndex,lastRuleType,lastRuleFormula,errorMsg] = getRules(parameterName,SBMLmodel,errorMsg);
+    if numberRulesParameter > 1,
+        % Parameter defined by more than one rule => error
+        errorMsg = sprintf('%s\nParameter ''%s'' defined by more than one rule\n',errorMsg,parameterName);
+    end
+    if numberRulesParameter == 0,
+        % Include parameter as parameter
+        SBstructure.parameters(numberParameters).name = parameterName;
+        % Check if a value is set for the parameter
+        if isempty(parameterValue),
+            errorMsg = sprintf('%s\nNo value defined defined for parameter ''%s''\n',errorMsg,parameterName);
+        end
+        % Include value in SBstructure
+        SBstructure.parameters(numberParameters).value = parameterValue;
+        % Set note that type of the parameter is 'global'
+        SBstructure.parameters(numberParameters).notes = '';
+        % initialize type, compartment, and unittype fields
+        SBstructure.parameters(numberParameters).type = 'isParameter';
+        SBstructure.parameters(numberParameters).compartment = '';
+        SBstructure.parameters(numberParameters).unittype = '';                
+        % Increment
+        numberParameters = numberParameters+1;
+    elseif numberRulesParameter == 1,
+        % One rule has been detected for this parameter
+        if strcmp(lastRuleType,'rate'),
+            % Parameter added as a state, since rule of type 'rate'
+            SBstructure.states(numberStates).name = parameterName;
+            % check if an initial amount is set for the parameter
+            if isempty(parameterValue),
+                errorMsg = sprintf('%s\nNo value defined for parameter ''%s''\n',errorMsg,parameterName);
+            end
+            % Include value as initial value in SBstructure
+            SBstructure.states(numberStates).initialCondition = parameterValue;
+            % Include the RHS formula as the ODE for this parameter state
+            SBstructure.states(numberStates).ODE = lastRuleFormula;
+            % Set note that type of the state is 'parameter rule'
+            SBstructure.states(numberStates).notes = '';
+            % initialize type, compartment, and unittype fields
+            SBstructure.states(numberStates).type = 'isParameter';
+            SBstructure.states(numberStates).compartment = '';
+            SBstructure.states(numberStates).unittype = '';                
+            % Increment
+            numberStates = numberStates+1;
+        else
+            % Parameter added as a variable, since rule of type 'scalar'
+            % Determine the index where to include the variable (based
+            % on the ordering of the scalar rules)
+            indexVariable = find(orderScalarRules==lastRuleIndex);
+            SBstructure.variables(indexVariable).name = parameterName;
+            SBstructure.variables(indexVariable).formula = lastRuleFormula;
+            SBstructure.variables(indexVariable).notes = '';
+            % initialize type, compartment, and unittype fields
+            SBstructure.variables(indexVariable).type = 'isParameter';
+            SBstructure.variables(indexVariable).compartment = '';
+            SBstructure.variables(indexVariable).unittype = '';               
+        end
+    end
+end
+% Then include the local parameters within the different reactions
+% If a parameter name collision has been detected, prefix the parameter
+% with the reaction name it is used in 
+for k1 = 1:length(SBMLmodel.reaction),
+    reactionName = SBMLmodel.reaction(k1).name;
+    if ~isempty(SBMLmodel.reaction(k1).kineticLaw),
+        for k2 = 1:length(SBMLmodel.reaction(k1).kineticLaw.parameter),
+            parameterName = SBMLmodel.reaction(k1).kineticLaw.parameter(k2).name;
+            parameterValue = SBMLmodel.reaction(k1).kineticLaw.parameter(k2).value;
+            % check if a value is set for the parameter
+            if isempty(parameterValue),
+                errorMsg = sprintf('%s\nNo value defined for parameter ''%s'' in reaction ''%s''\n',errorMsg,parameterName,reactionName);
+            end
+            % add the reaction name to the parameter and update the kinetic rate law
+            parameterName = char([double(reactionName) double('_') double(parameterName)]);  % fastest strcat ;)
+            % Include parameter in the structure
+            SBstructure.parameters(numberParameters).name = parameterName;
+            SBstructure.parameters(numberParameters).value = parameterValue;
+            SBstructure.parameters(numberParameters).notes = '';
+            % initialize type, compartment, and unittype fields
+            SBstructure.parameters(numberParameters).type = 'isParameter';
+            SBstructure.parameters(numberParameters).compartment = '';
+            SBstructure.parameters(numberParameters).unittype = '';
+            numberParameters = numberParameters+1;
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% COMPARTMENTS (INCLUDE IN STRUCTURE)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Include compartments
+% No rule => as parameters
+%
+% Scalar rule => as variables
+%       
+% Rate rule => as states
+%
+for k = 1:length(SBMLmodel.compartment),
+    compartmentName = SBMLmodel.compartment(k).name;
+    compartmentValue = SBMLmodel.compartment(k).volume;
+    % Check the number of rules the compartment is in and get the index
+    % of the last rule the compartment is used in together with its type
+    % ('rate' or 'scalar') and the right hand side expression 'formula'
+    [numberRulesCompartment,lastRuleIndex,lastRuleType,lastRuleFormula,errorMsg] = getRules(compartmentName,SBMLmodel,errorMsg);
+    if numberRulesCompartment > 1,
+        % Compartment defined by more than one rule => error
+        errorMsg = sprintf('%s\nCompartment ''%s'' defined by more than one rule\n',errorMsg,compartmentName);
+    end
+    if numberRulesCompartment == 0,
+        % Include compartment as parameter
+        SBstructure.parameters(numberParameters).name = compartmentName;
+        % Check if a value is set for the parameter
+        if isempty(compartmentValue),
+            errorMsg = sprintf('%s\nNo value defined defined for compartment ''%s''\n',errorMsg,compartmentName);
+        end
+        % Include value in SBstructure
+        SBstructure.parameters(numberParameters).value = compartmentValue;
+        % Set note that type of the parameter is 'compartment size'
+        SBstructure.parameters(numberParameters).notes = '';
+        % initialize type, compartment, and unittype fields
+        SBstructure.parameters(numberParameters).type = 'isCompartment';
+        SBstructure.parameters(numberParameters).compartment = SBMLmodel.compartment(k).outside;
+        SBstructure.parameters(numberParameters).unittype = '';
+        % Increment
+        numberParameters = numberParameters+1;
+    elseif numberRulesCompartment == 1,
+        % One rule has been detected for this compartment
+        if strcmp(lastRuleType,'rate'),
+            % Compartment added as a state, since rule of type 'rate'
+            SBstructure.states(numberStates).name = compartmentName;
+            % check if an initial amount is set for the compartment
+            if isempty(compartmentValue),
+                errorMsg = sprintf('%s\nNo value defined for compartment ''%s''\n',errorMsg,compartmentName);
+            end
+            % Include value as initial value in SBstructure
+            SBstructure.states(numberStates).initialCondition = compartmentValue;
+            % Include the RHS formula as the ODE for this compartment state
+            SBstructure.states(numberStates).ODE = lastRuleFormula;
+            % Set note that type of the state is 'compartment size'
+            SBstructure.states(numberStates).notes = '';
+            % initialize type, compartment, and unittype fields
+            SBstructure.states(numberStates).type = 'isCompartment';
+            SBstructure.states(numberStates).compartment = SBMLmodel.compartment(k).outside;
+            SBstructure.states(numberStates).unittype = '';
+            % Increment
+            numberStates = numberStates+1;
+            % compartment_rate variable right hand side
+            compartmentDotRHS = lastRuleFormula;
+        else
+            % Compartment added as a variable, since rule of type 'scalar'
+            % Determine the index where to include the variable (based
+            % on the ordering of the scalar rules)
+            indexVariable = find(orderScalarRules==lastRuleIndex);
+            SBstructure.variables(indexVariable).name = compartmentName;
+            SBstructure.variables(indexVariable).formula = lastRuleFormula;
+            SBstructure.variables(indexVariable).notes = '';
+            % initialize type, compartment, and unittype fields
+            SBstructure.variables(indexVariable).type = 'isCompartment';
+            SBstructure.variables(indexVariable).compartment = SBMLmodel.compartment(k).outside;
+            SBstructure.variables(indexVariable).unittype = '';
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% REACTIONS (INCLUDE IN STRUCTURE)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Read in reaction information into the model structure. Replace colliding 
+% parameter names with their prefixed versions (reaction name). Reactions 
+% are included into the model structure in the 'reactions' field. This leads 
+% to shorter ODE definitions for the specie states, which then contain the 
+% reaction names with the correct stoichiometries. The 'reactions' field
+% contains three fields: 'name', 'formula', 'notes'
+%
+% Cycle through all reactions
+for k1 = 1:length(SBMLmodel.reaction),
+    reactionName = SBMLmodel.reaction(k1).name;
+    kineticLaw = SBMLmodel.reaction(k1).kineticLaw;
+    % check if a kineticLaw is given
+    if isempty(kineticLaw),
+        errorMsg = sprintf('%s\nNo kinetic law is given for reaction ''%s''\n',errorMsg,reactionName);
+    elseif isempty(kineticLaw.formula),
+        errorMsg = sprintf('%s\nNo kinetic formula law given for reaction ''%s''\n',errorMsg,reactionName);
+    end
+    % Process the kineticLaw formula by replacing the local parameter names
+    % by reactionname_parameternames and replace the mathml expressions
+    if ~isempty(kineticLaw),
+        formula = kineticLaw.formula;
+        if ~isempty(kineticLaw.parameter),
+            for k2 = 1:length(kineticLaw.parameter),
+                parameterName = kineticLaw.parameter(k2).name;
+                newParameterName = char([double(reactionName) double('_') double(parameterName)]); % fastest strcat
+                formula = exchangeStringInString(formula,parameterName,newParameterName);
+            end
+        end
+    else
+        formula = '';
+    end
+    % replace MathML expressions in formula against MATLAB expressions
+    [formula] = replaceMathMLexpressions(formula);
+    % Include reaction information in the structure
+    SBstructure.reactions(k1).name = reactionName;
+    SBstructure.reactions(k1).formula = formula;
+    SBstructure.reactions(k1).notes = '';
+    SBstructure.reactions(k1).reversible = SBMLmodel.reaction(k1).reversible;
+    if SBMLmodel.reaction(k1).fast == 1,
+        SBstructure.reactions(k1).fast = 1;    
+    else
+        SBstructure.reactions(k1).fast = 0;
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS REACTION ODES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add the reaction variable names with correct stoichiometries to the 'ODE' field
+% for the correct species. The 'correct' species are only non-boundary and 
+% non-constant species for which no rules exist. These are listed in
+% the 'speciesODElist'
+%
+for k1 = 1:length(speciesODElist),
+    % get name of species and the index of the corresponding state
+    speciesName = speciesODElist(k1).name;
+    stateIndex = speciesODElist(k1).stateIndex;
+    % cycle through all the reactions and look in which reactions the
+    % species is changed
+    for k2 = 1:length(SBstructure.reactions),
+        % get reaction name for inclusion in ODEstring
+        reactionName = SBstructure.reactions(k2).name;
+        % cycle through the reactants of the current reaction
+        % (ordering of reactions in SBstructure and SBMLmodel are equal)
+        for k3 = 1:length(SBMLmodel.reaction(k2).reactant),
+            reactantName = SBMLmodel.reaction(k2).reactant(k3).species;
+            reactantStoichiometry = abs(double(SBMLmodel.reaction(k2).reactant(k3).stoichiometry) / double(SBMLmodel.reaction(k2).reactant(k3).denominator));
+            % If species name and reactant name are equal then add reaction
+            % to species ODE
+            if strcmp(reactantName,speciesName),
+                % construct the string to add to the ODE of the current reactant
+                if reactantStoichiometry > 1,
+                    ODEstringAdd = sprintf('-%s*%s',num2str(reactantStoichiometry),reactionName);
+                else
+                    ODEstringAdd = sprintf('-%s',reactionName);
+                end
+                % add the ODEstringAdd to the 'ODE' field of this species
+                SBstructure.states(stateIndex).ODE = strcat(SBstructure.states(stateIndex).ODE,ODEstringAdd);
+                break;
+            end
+        end
+        % cycle through the products of the current reaction
+        % (ordering of reactions in SBstructure and SBMLmodel are equal)
+        for k3 = 1:length(SBMLmodel.reaction(k2).product),
+            productName = SBMLmodel.reaction(k2).product(k3).species;
+            productStoichiometry = abs(double(SBMLmodel.reaction(k2).product(k3).stoichiometry) / double(SBMLmodel.reaction(k2).product(k3).denominator));
+            % If species name and product name are equal then add reaction
+            % to species ODE
+            if strcmp(productName,speciesName),
+                % construct the string to add to the ODE of the current product
+                if productStoichiometry > 1,
+                    ODEstringAdd = sprintf('+%s*%s',num2str(productStoichiometry),reactionName);
+                else
+                    ODEstringAdd = sprintf('+%s',reactionName);
+                end
+                % add the ODEstringAdd to the 'ODE' field of this species
+                SBstructure.states(stateIndex).ODE = strcat(SBstructure.states(stateIndex).ODE,ODEstringAdd);
+                break;
+            end
+        end
+    end
+end
+% Now all ODEs should be defined - check if everything is correct!
+% Finally cycle through all the states and check if all ODEs have been defined
+for k = 1:length(SBstructure.states),
+    stateName = SBstructure.states(k).name;
+    stateODE = SBstructure.states(k).ODE;
+    if isempty(stateODE),
+        % Issue a warning only and set ODE to 0
+        disp(sprintf('No ODE defined for state ''%s''',stateName));
+        SBstructure.states(k).ODE = '0';
+    end
+end
+% After initial construction of the ODEs their units need to be changed.
+% Since species are in concentrations and the rate laws from the reactions
+% return amount/time it is necessary to convert the odes from amount/time to
+% concentration/time. This is done here.
+%
+% We differentiate the case where:
+%   - single compartment model with constant compartment size = 1
+%     (nothing is done additionally)
+%   - multi compartment model or single compartment model with compartment 
+%     size different from one. In this case each complete ode is divided by the
+%     compartment size the species is in
+%
+compartmentddtdonelist = {};
+for k1 = 1:length(speciesODElist),
+    % get name of species and the index of the corresponding state
+    speciesName = speciesODElist(k1).name;
+    stateIndex = speciesODElist(k1).stateIndex;
+    % check if the model has only one compartment with volume 1 and 
+    % constant volume => if yes then leave ODE as it is.
+    convertODE = 1;
+    if length(SBMLmodel.compartment) == 1,
+        % only one compartment
+        if SBMLmodel.compartment(1).volume == 1,
+            % size of compartment is 1
+            for k = 1:length(SBstructure.parameters),
+                % check is compartment size is constant (then it is defined as
+                % a parameter)
+                if strcmp(SBMLmodel.compartment(1).name,SBstructure.parameters(k).name),
+                    % compartment defined as a parameter and thus no species
+                    % names need to be exchanged
+                    convertODE = 0;
+                    % return directly to the main function
+                end
+            end
+        end
+    end
+    if convertODE,
+        % convert the ODE expression
+        % get compartment name for species
+        compartmentName = getCompartmentNameSpecies(speciesName,SBMLmodel);
+        ODEstring = SBstructure.states(stateIndex).ODE;
+        if ~strcmp(ODEstring,'0')
+            % construct new ODE string
+            newODEstring = char([double('(') double(ODEstring) double(')/') double(compartmentName)]); % fastest strcat
+            % include the new ODE string in structure
+            SBstructure.states(stateIndex).ODE = newODEstring;
+        end
+    end
+
+% HANDLE TIME VARYING COMPARTMENT SIZES
+    [changingFlag,ddtCompartment] = getCompartmentInfoChanging(compartmentName,SBstructure,compartmentddtdonelist);
+    if changingFlag,
+        % append the second derivative term
+        SBstructure.states(stateIndex).ODE = sprintf('%s - %s*ddt_%s/%s',SBstructure.states(stateIndex).ODE,speciesName,compartmentName,compartmentName);
+
+        % add the time derivative of the compartment to variables
+        % (if not done already)
+        if isempty(strmatchSB(compartmentName,compartmentddtdonelist,'exact')),
+            SBstructure.variables(end+1).name = ['ddt_' compartmentName];
+            SBstructure.variables(end).formula = ddtCompartment;
+            SBstructure.variables(end).type = 'isParameter';
+            SBstructure.variables(end).compartment = '';
+            SBstructure.variables(end).unittype = '';
+            SBstructure.variables(end).notes = 'Time derivative of compartment';
+            compartmentddtdonelist{end+1} = compartmentName;
+        end
+    end
+
+
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% IMPORT ALGEBRAIC RULES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% prepare the import
+% 1)need to find all species, compartments, and (global) parameters that are
+% NOT constant. These are the candidates for the determination by an
+% algebraic rule (in this order of priority)
+% In SBML L1 all can be non constant!
+nonConstantSpecies = {SBMLmodel.species.name};
+nonConstantParameters = {SBMLmodel.parameter.name};
+nonConstantCompartments = {SBMLmodel.compartment.name};
+% 2) now we need to make a list of all states determined by ODEs and
+% variables determined by formulas. 
+allStates = {};
+for k=1:length(SBstructure.states),
+    if SBstructure.states(k).ODE ~= '0',
+        % Only non constant states (would also require the check of event 
+        % assignments ... but in my opinion, SBML should simply define the
+        % variable which is affected by an algebraic rule ... so much
+        % cleaner!
+        allStates{end+1} = SBstructure.states(k).name;
+    end
+end
+allVariables = {};
+for k=1:length(SBstructure.variables),
+    if ~isnan(str2double(SBstructure.variables(k).formula)),
+        % If variable has not a numeric assignment ... 
+        allVariables{end+1} = SBstructure.variables(k).name;
+    end
+end
+% 3) The names of the states and variables need to be deleted from the
+% nonConstantSpecies, nonConstantCompartments, and nonConstantParameters,
+% because only the remaining ones can be determined by algebraic rules
+possibleSpecies = setdiff(nonConstantSpecies,allStates);
+possibleSpecies = setdiff(possibleSpecies,allVariables);
+possibleParameters = setdiff(nonConstantParameters,allStates);
+possibleParameters = setdiff(possibleParameters,allVariables);
+possibleCompartments = setdiff(nonConstantCompartments,allStates);
+possibleCompartments = setdiff(possibleCompartments,allVariables);
+% 4) now we check if at least as many possibilities as there are ARs
+% (otherwise certainly overdetermined).
+ARindices = strmatchSB('SBML_ALGEBRAIC_RULE',{SBMLmodel.rule.typecode},'exact');
+nrARs = length(ARindices);
+if length(possibleSpecies) + length(possibleParameters) + length(possibleCompartments) < nrARs,
+    error('The model is certainly overdetermined. To many algebraic rules!');
+end
+% 5) Now check which of the possible elements appear in the ARs. If at
+% least a number of nrARs do appear there its fine ... if not put out a
+% warning and select whatever.
+ARs = SBMLmodel.rule(ARindices);
+ReallyPossibleSpecies = {};
+ReallyPossibleParameters = {};
+ReallyPossibleCompartments = {};
+for k=1:nrARs,
+    species = regexp(ARs(k).formula,possibleSpecies,'match');
+    for k2=1:length(species),
+        if ~isempty(species{k2}),
+            ReallyPossibleSpecies{end+1} = species{k2}{1};
+        end
+    end
+    parameters = regexp(ARs(k).formula,possibleParameters,'match');
+    for k2=1:length(parameters),
+        if ~isempty(parameters{k2}),
+            ReallyPossibleParameters{end+1} = parameters{k2}{1};
+        end
+    end
+    compartments = regexp(ARs(k).formula,possibleCompartments,'match');
+    for k2=1:length(compartments),
+        if ~isempty(compartments{k2}),
+            ReallyPossibleCompartments{end+1} = compartments{k2}{1};
+        end
+    end
+end
+% make unique (it might not be)
+ReallyPossibleSpecies = unique(ReallyPossibleSpecies);
+ReallyPossibleParameters = unique(ReallyPossibleParameters);
+ReallyPossibleCompartments = unique(ReallyPossibleCompartments);
+nrPossible = length(ReallyPossibleSpecies) + length(ReallyPossibleParameters) + length(ReallyPossibleCompartments);
+if nrPossible < nrARs,
+    error('The model is overdetermined or at least it is unclear which variables are to be determined using the algebraic rules.');
+end
+% get the indices in the SBML model for the really possible ones
+indexspecies = [];
+indexparameters = [];
+indexcompartments = [];
+for k=1:length(ReallyPossibleSpecies),
+    indexspecies(end+1) = strmatchSB(ReallyPossibleSpecies{k},{SBMLmodel.species.name},'exact');
+end
+for k=1:length(ReallyPossibleParameters),
+    indexparameters(end+1) = strmatchSB(ReallyPossibleParameters{k},{SBMLmodel.parameter.name},'exact');
+end
+for k=1:length(ReallyPossibleCompartments),
+    indexcompartments(end+1) = strmatchSB(ReallyPossibleCompartments{k},{SBMLmodel.compartment.name},'exact');
+end
+% 6) Add the algebraic rules and delete the corresponding parameters from
+% the SBmodel structure
+for k=1:length(ARindices),
+    rule = SBMLmodel.rule(ARindices);
+    % determine the name (it needs to be one of the elements in
+    % indexspecies, indexparameters, or indexcompartments
+    if ~isempty(indexspecies),
+        index = indexspecies(1);
+        name = SBMLmodel.species(index).name;
+        type = 'isSpecie';
+        compartment = SBMLmodel.species(index).compartment;
+        if SBMLmodel.species(index).isSetInitialAmount,
+            unittype = 'amount';        
+        else
+            unittype = 'concentration';
+        end
+        % remove the used species
+        indexspecies(1) = [];             
+    elseif ~isempty(indexparameters),
+        index = indexparameters(1);
+        name = SBMLmodel.parameter(index).name;
+        type = 'isParameter';
+        compartment = '';
+        unittype = '';
+        % remove the used parameter
+        indexparameters(1) = [];      
+    elseif ~isempty(indexcompartments),
+        index = indexcompartments(1);
+        name = SBMLmodel.compartment(index).name;
+        type = 'isCompartment';
+        compartment = SBMLmodel.compartment(index).outside;
+        unittype = '';        
+        % remove the used compartment
+        indexcompartments(1) = [];      
+    else
+        error('Should not get to this :)');
+    end
+    % get initial condition (can be state, parameter, or variable .... YEEEESSS!)
+    % and delete the corresponding component from the model (now determined
+    % by algebraic rule).
+    allStates = {SBstructure.states.name};    
+    allParams = {SBstructure.parameters.name};
+    allVars = {SBstructure.variables.name};
+    indexstate = strmatchSB(name,allStates,'exact');
+    indexparam = strmatchSB(name,allParams,'exact');
+    indexvar = strmatchSB(name,allVars,'exact');
+    if ~isempty(indexstate),
+        initialCondition = SBstructure.states(indexstate).initialCondition;    
+        SBstructure.states(indexstate) = [];
+    elseif ~isempty(indexparam),
+        initialCondition = SBstructure.parameters(indexparam).value;
+        SBstructure.parameters(indexparam) = [];
+    elseif ~isempty(indexvar),
+        initialCondition = str2double(SBstructure.variables(indexvar).formula);    
+        SBstructure.variables(indexvar) = [];
+    else
+        error('Should not get to this :) ... 2');
+    end
+    % add algebraic rule
+    SBstructure.algebraic(k).name = name;
+    SBstructure.algebraic(k).formula = rule(k).formula;
+    SBstructure.algebraic(k).initialCondition = initialCondition;
+    SBstructure.algebraic(k).type = type;
+    SBstructure.algebraic(k).compartment = compartment;
+    SBstructure.algebraic(k).unittype = unittype;
+    SBstructure.algebraic(k).notes = rule(k).notes;
+end
+% 7) Its DONE!
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK ALL COMPONENTNAMES AND REMOVE TRAILING "_"
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% get names to exchange
+oldnames = {};
+newnames = {};
+% states
+for k=1:length(SBstructure.states),
+    [oldnames,newnames,changed,SBstructure.states(k).name] = removeUnderscores(oldnames,newnames,SBstructure.states(k).name);    
+end
+% algebraic
+for k=1:length(SBstructure.algebraic),
+    [oldnames,newnames,changed,SBstructure.algebraic(k).name] = removeUnderscores(oldnames,newnames,SBstructure.algebraic(k).name);    
+end
+% parameters
+for k=1:length(SBstructure.parameters),
+    [oldnames,newnames,changed,SBstructure.parameters(k).name] = removeUnderscores(oldnames,newnames,SBstructure.parameters(k).name);
+end
+% variables
+for k=1:length(SBstructure.variables),
+    [oldnames,newnames,changed,SBstructure.variables(k).name] = removeUnderscores(oldnames,newnames,SBstructure.variables(k).name);
+end
+% reactions
+for k=1:length(SBstructure.reactions),
+    [oldnames,newnames,changed,SBstructure.reactions(k).name] = removeUnderscores(oldnames,newnames,SBstructure.reactions(k).name);   
+end
+% ok, if names changed then handle formulas
+if ~isempty(oldnames),
+    % states
+    for k=1:length(SBstructure.states),
+        SBstructure.states(k).ODE = regexprep(SBstructure.states(k).ODE,oldnames,newnames);
+        SBstructure.states(k).compartment = regexprep(SBstructure.states(k).compartment,oldnames,newnames);
+    end
+    % algebraic
+    for k=1:length(SBstructure.algebraic),
+        SBstructure.algebraic(k).formula = regexprep(SBstructure.algebraic(k).formula,oldnames,newnames);
+        SBstructure.algebraic(k).compartment = regexprep(SBstructure.algebraic(k).compartment,oldnames,newnames);
+    end
+    % parameters
+    for k=1:length(SBstructure.parameters),
+        SBstructure.parameters(k).compartment = regexprep(SBstructure.parameters(k).compartment,oldnames,newnames);
+    end    
+    % variables
+    for k=1:length(SBstructure.variables),
+        SBstructure.variables(k).formula = regexprep(SBstructure.variables(k).formula,oldnames,newnames);
+        SBstructure.variables(k).compartment = regexprep(SBstructure.variables(k).compartment,oldnames,newnames);
+    end
+    % reactions
+    for k=1:length(SBstructure.reactions),
+        SBstructure.reactions(k).formula = regexprep(SBstructure.reactions(k).formula,oldnames,newnames);
+    end
+end
+
+
+% return from main function
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE TIME VARYING COMPARTMENTS ... get changing flag and the
+% time-derivative of the compartment size.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [changingFlag,ddtCompartment] = getCompartmentInfoChanging(compartmentName,SBstructure,compartmentddtdonelist)
+changingFlag = 0; 
+ddtCompartment = '';
+% go through states and variables to check if the compartment name appears
+% there ... then just do it
+indexState = strmatchSB(compartmentName,{SBstructure.states.name},'exact');
+indexVariable = strmatchSB(compartmentName,{SBstructure.variables.name},'exact');
+indexAlgebraic = strmatchSB(compartmentName,{SBstructure.algebraic.name},'exact');
+if ~isempty(indexState),
+    changingFlag = 1; 
+    ddtCompartment = SBstructure.states(indexState).ODE;
+elseif ~isempty(indexVariable),
+    changingFlag = 1;
+    Compartment = SBstructure.variables(indexVariable).formula;
+    % ddtCompartment needs only to be determined once for each compartment.
+    % So not per species in this compartment. We make it simple here (since
+    % it mainly matters when determining and adding it manually):
+    if isempty(strmatchSB(compartmentName,compartmentddtdonelist,'exact')),
+        if symbolicpresentSB(),
+            ddtCompartment = char(diff(Compartment,'time'));
+        else
+            disp('For the handling of time varying compartments the time derivative of the');
+            disp('compartment size needs to be determined. Since the symbolic toolbox is not');
+            disp('present you need to do that manually.');
+            disp(' ');
+            disp(sprintf('C(time) = %s',Compartment));
+            disp(' ');
+            ddtCompartment = input('d/dtime(C(time)) = ','s');
+        end
+    end
+elseif ~isempty(indexAlgebraic),
+    error(sprintf('Size of compartment ''%s'' defined by an algebraic rule! Cant determine\nthe analytic rate of change of the size.',compartmentName));
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HELP FUNCTION TO REMOVE __ at the start of element names
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [oldnames,newnames,changed,newname] = removeUnderscores(oldnames,newnames,name)
+changed = 0;
+newname = regexprep(name,'^([_]?)','underscore_');
+if length(name) ~= length(newname),
+    changed = 1;
+    oldnames{end+1} = sprintf('\\<%s\\>',name);
+    newnames{end+1} = newname;
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% FIND RULES FOR A CERTAIN VARIABLE NAME
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Cycle through all the rules and check if the given variable name
+% (species or parameter or compartment) appears as left hand side (LHS) in a rule
+%
+% numberRulesVariable: number of rules the name appears in as LHS
+% lastRuleIndex: the index of the rule the name was last detected
+% lastRuleType: 'scalar' or 'rate'
+% lastRuleFormula: the RHS expression for the variable
+%
+% We assume that the name of the variable can appear in the
+% 'variable' field, in the 'species' field, in the 'compartment' field,
+% or in the 'name' field of the 'rule' field. 
+% Some SBML example models had species in the 'variable' field!
+%
+function [numberRulesVariable,lastRuleIndex,lastRuleType,lastRuleFormula,errorMsg] = getRules(variableName,SBMLmodel,errorMsg)
+% Initialize return values
+numberRulesVariable = 0;
+lastRuleIndex = [];
+lastRuleType = '';
+lastRuleFormula = '';
+for k = 1:length(SBMLmodel.rule),
+    % DO NOT PROCESS ALGEBRAIC RULES HERE ... WE DO THAT AT A DIFFERENT PLACE
+    if isempty(strfind(SBMLmodel.rule(k).typecode,'ALGEBRAIC')),
+        if strcmp(variableName,SBMLmodel.rule(k).variable) || strcmp(variableName,SBMLmodel.rule(k).species) || strcmp(variableName,SBMLmodel.rule(k).name) || strcmp(variableName,SBMLmodel.rule(k).compartment),
+            % The name was found as LHS in a rule
+            numberRulesVariable = numberRulesVariable+1;
+            lastRuleIndex = k;
+            if ~isempty(strfind(SBMLmodel.rule(k).typecode,'RATE')) || ~isempty(strfind(SBMLmodel.rule(k).type,'rate')),
+                % Rule is a rate rule
+                lastRuleType = 'rate';
+            else
+                % Rule is a scalar rule
+                lastRuleType = 'scalar';
+            end
+            % get the RHS expression of the rule
+            lastRuleFormula = SBMLmodel.rule(k).formula;
+        end
+    end
+end
+% replace MathML expressions against MATLAB expressions
+[lastRuleFormula] = replaceMathMLexpressions(lastRuleFormula);
+%return
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF A CERTAIN SPECIES APPEARS AS PRODUCT AND/OR REACTANT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% In the case that a non-boundary species is defined by a rule
+% we need to check if it is also present as product or reactant in any
+% reaction. In this case the SBML model is not correctly defined and
+% reactionSpeciesPresent = 1
+function [reactionSpeciesPresent] = checkReactionsForSpecies(speciesName,SBMLmodel)
+% Initialize return value
+reactionSpeciesPresent = 0;
+reactionComponents = {};
+for k = 1:length(SBMLmodel.reaction),
+    reactionComponents = {reactionComponents{:},SBMLmodel.reaction(k).reactant.species,SBMLmodel.reaction(k).product.species};
+end
+if ~isempty(strmatchSB(speciesName,reactionComponents,'exact')),
+    reactionSpeciesPresent = 1;
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DELETE WHITESPACES IN STRINGS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Useful for taking away whitespaces in kineticLaw formulas, as
+% seen in some example models
+function [outputString] = removeWhiteSpace(inputString)
+outputString = strrep(inputString,' ','');
+% return
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET COMPARTMENT NAME FOR SPECIES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [compartmentName] = getCompartmentNameSpecies(species,SBMLmodel)
+compartmentName = SBMLmodel.species(strmatchSB(species,{SBMLmodel.species.name},'exact')).compartment;
+% return
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXCHANGE STRING IN STRING - WITH CHECK OF ALLOWED CHARACTERS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% find occurrences of stringOld in fullString and exchange it with
+% stringNew. 
+function [processedString] = exchangeStringInString(fullString,stringOld,stringNew);
+% really simple!!!
+processedString = regexprep(fullString,strcat('\<',stringOld,'\>'),stringNew);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXCHANGE MATHML FUNCTION NAMES IN ALL FORMULAS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% MathML functions can have different names than MATLAB function names
+% we need to exchange them in the formula strings. The term 'MathML
+% expression' relates to what is returned by TranslateSBML!
+function [newFormula] = replaceMathMLexpressions(formula)
+% MathML expressions that need simple exchange with corresponding MATLAB
+% expressions:
+MathMLexpressions = {'\<piecewise\>','\<and\>','\<or\>','\<arccos\>','\<arcsin\>','\<arctan\>','\<ceiling\>','\<ln\>',...
+    '\<pow\>','\<arccos\>','\<arccosh\>','\<arccot\>','\<arccoth\>','\<arccsc\>','\<arccsch\>',...
+    '\<arcsec\>','\<arcsech\>','\<arcsin\>','\<arcsinh\>','\<arctan\>','\<arctanh\>',...
+    '\<exponentiale','\<geq\>','\<leq\>','\<xor\>','\<multiply\>'};
+MATLABexpressions = {'piecewiseSB','andSB','orSB','acos','asin','atan','ceil','log', ...
+    'power','acos','acosh','acot','acoth','acsc','acsch',...
+    'asec','asech','asin','asinh','atan','atanh'...
+    'exp(1)','ge','le','xorSB','multiplySB'};
+% find indices
+newFormula = regexprep(formula,MathMLexpressions,MATLABexpressions);
+return
+
+
+
+
+
+
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBconvertSBML2.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBconvertSBML2.m
new file mode 100644
index 0000000000000000000000000000000000000000..8fb8c02acac345eb00f9122bade7c55b561bca6c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBconvertSBML2.m
@@ -0,0 +1,1339 @@
+function [SBstructure,errorMsg] = SBconvertSBML2(SBMLmodel)
+% SBconvertSBML2
+% Converting a SBML Level 2 MATLAB structure to the object model structure
+% used in the toolbox
+%
+% Private method 
+%
+% [SBstructure,errorMsg] = SBconvertSBML2(SBMLmodel);
+%
+% Simple error checking is provided. In the case of an error an empty
+% structure is returned.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+global SBMLtimesymbol
+
+% additional global variable to record species that have amount initial
+% units but are converted to concentration ... and the corresponding
+% compartment
+global amount2concentration
+amount2concentration = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INITIALIZE ERROR MESSAGES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+errorMsg = '';
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CREATE AN EMPTY SBSTRUCTURE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBstructure = struct(SBmodel());
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK TIME SYMBOL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% From SBML Toolbobx 2.0.2 on a time_symbol field exists in the
+% SBMLmodel. We need to get the time symbol if it is there and replace
+% all occurrences in the model with 'time'.
+if isfield(SBMLmodel,'time_symbol'),
+    SBMLtimesymbol = SBMLmodel.time_symbol;
+else
+    SBMLtimesymbol = '';
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% NAME AND NOTES (INCLUDE IN STRUCTURE)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~strcmp(SBMLmodel.name,''),
+    SBstructure.name = SBMLmodel.name;
+elseif ~strcmp(SBMLmodel.id,''),
+    SBstructure.name = SBMLmodel.id;
+else
+    SBstructure.name = 'Unknown model';
+end
+% Indicate in notes that the model has been created by import from SBML.
+SBstructure.notes = strtrim(convert2SBNotes(SBMLmodel.notes,0));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% FUNCTIONS (INCLUDE IN STRUCTURE)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k = 1:length(SBMLmodel.functionDefinition),
+    functionName = SBMLmodel.functionDefinition(k).id;
+    functionMath = SBMLmodel.functionDefinition(k).math;
+    % take away the lambda( ... ) and only leave the ...
+    expression = removeWhiteSpace(functionMath(8:length(functionMath)-1));
+    % take away power functions
+    expression = exchangepowerexp(expression);
+    % explode at the comma (not within parentheses)
+    [elements] = explodePCSB(expression);
+    % last element is the formula, the others are the arguments
+    functionFormula = elements{end};
+    functionArguments = expression(1:end-length(functionFormula)-1);
+    % replace eventual MathML expressions by MATLAB expressions
+    [functionFormula] = replaceMathMLexpressions(functionFormula);
+    % include function into structure
+    
+    SBstructure.functions(k).name = functionName;
+    SBstructure.functions(k).arguments = functionArguments;
+    SBstructure.functions(k).formula = functionFormula;
+    SBstructure.functions(k).notes = convert2SBNotes(SBMLmodel.functionDefinition(k).notes,1);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SOME COUNTER DEFINITIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% States and parameters are included in the structure in their order of
+% appearance. For variables no counters are needed, since their order 
+% is defined by the ordering of the scalar rules and not by their order of 
+% appearance (see below)
+numberStates = 1;
+numberParameters = 1;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ORDERING OF VARIABLES (SCALAR RULES)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Scalar rules lead always to the definition of variables. The order of
+% appearance of the rules is important and thus the order of appearance of
+% the variables should reflect the ordering of the rules. We determine an
+% array in which the the index i determines the priority of the scalar rule, and
+% the i-th array element the index of the corresponding scalar rule. Rate
+% rules do not have to be considered since they are evaluated at last
+% anyway
+orderScalarRules = strmatchSB('SBML_ASSIGNMENT_RULE',{SBMLmodel.rule.typecode});
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SPECIES (INCLUDE IN STRUCTURE)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Species of the model are included in the structure as follows:
+%
+% Non-boundary species:
+%   - rate rule: as state
+%   - scalar rule: as variable
+%   - no rule: as state
+%
+% Boundary species:
+%   - rate rule: as states
+%   - scalar rule: as variable
+%   - no rule: as parameter
+%
+% If initial values of species given as concentrations:
+%   - They will be treated as concentrations, this means the ODE will be
+%     adjusted by diving the amount rate with the corresponding compartment
+%     volume.
+%
+% If initial values of species given as amounts:
+%   - They will be treated as amounts, this means the ODE will NOT be
+%     adjusted!
+%
+% The rate formulas in the kinetic laws are just taken as they are. This
+% means a mix of concentration and amount species might occur - the user 
+% has him/herself to take care to have the correct rate laws!
+%
+speciesODElist = [];
+speciesODElistIndex = 1;
+% Check if there are any species. 
+if isempty(SBMLmodel.species),
+%    errorMsg = sprintf('%s\n%s\n',errorMsg,'No species are defined in the SBML model');
+%     warning('No species are defined in the SBML model - uncertain if model conversion will lead to a working SBmodel!');
+end
+% Cycle through all the species and determine how they are to be included
+% in the model structure
+for k1 = 1:length(SBMLmodel.species),
+    speciesName = SBMLmodel.species(k1).id;
+    speciesCompartmentName = SBMLmodel.species(k1).compartment;
+    speciesNotes = convert2SBNotes(SBMLmodel.species(k1).notes,1);
+    % get the compartment size for this species
+    makeItAmountAnyway = 0;
+    for k2 = 1:length(SBMLmodel.compartment),
+        if strcmp(speciesCompartmentName, SBMLmodel.compartment(k2).id),
+            compartmentSize = SBMLmodel.compartment(k2).size;
+            if isempty(compartmentSize),
+                errorMsg = sprintf('%s\nNo compartment size defined for compartment ''%s''\n',errorMsg,speciesCompartmentName);
+                compartmentSize = 1; % set to whatever, error will still occurr!
+            end
+            spatialDimensions = SBMLmodel.compartment(k2).spatialDimensions;
+            if spatialDimensions == 0 || compartmentSize == 0,
+                makeItAmountAnyway = 1;
+            end
+            break;
+        end
+    end
+    % determine the initial value for species
+    initialCondition = [];
+    if SBMLmodel.species(k1).isSetInitialAmount,
+        if SBMLmodel.species(k1).hasOnlySubstanceUnits || makeItAmountAnyway,
+            initialCondition = SBMLmodel.species(k1).initialAmount;
+            speciesUnits = 'amount';
+        else
+            initialCondition = SBMLmodel.species(k1).initialAmount/compartmentSize;
+            speciesUnits = 'concentration';
+            amount2concentration(end+1).species = speciesName;
+            amount2concentration(end).compartment = speciesCompartmentName;
+        end
+    elseif SBMLmodel.species(k1).isSetInitialConcentration,
+        % convert concentration to amount
+        initialCondition = SBMLmodel.species(k1).initialConcentration;
+        speciesUnits = 'concentration';
+    else
+        % if nothing is chosen, assume concentration units
+        speciesUnits = 'concentration';
+    end
+    % Check the number of rules the species is in and get the index
+    % of the last rule the species is used in together with its type
+    % ('rate' or 'scalar') and the right hand side expression 'formula'
+    [numberRulesSpecies,lastRuleIndex,lastRuleType,lastRuleFormula,errorMsg] = getRules(speciesName,SBMLmodel,errorMsg);
+    if numberRulesSpecies > 1,
+        % Species defined by more than one rule => error
+        errorMsg = sprintf('%s\nSpecies ''%s'' defined by more than one rule\n',errorMsg,speciesName);
+    end
+    % Process all the species that DO NOT have a boundary condition
+    % In case the species is non-constant it is included as for Level 1
+    % In case the species is constant it is included as parameter
+    if SBMLmodel.species(k1).constant == 0,
+        if SBMLmodel.species(k1).boundaryCondition == 0,
+            if numberRulesSpecies == 0,
+                % add species to the ODE list (for use below in ODE
+                % construction)
+                speciesODElist(speciesODElistIndex).name = speciesName;
+                speciesODElist(speciesODElistIndex).stateIndex = numberStates;
+                speciesODElist(speciesODElistIndex).units = speciesUnits;
+                speciesODElistIndex = speciesODElistIndex + 1;
+                % Include species as state
+                SBstructure.states(numberStates).name = speciesName;
+                % Check if an initial value is set for a species
+                if isempty(initialCondition),
+%                     errorMsg = sprintf('%s\nNo initial value defined for species ''%s''\n',errorMsg,speciesName);
+                    initialCondition = 0;
+                end
+                SBstructure.states(numberStates).initialCondition = initialCondition;
+                % Note that this state is a 'species'
+                % Notes are not used by the toolbox for other things as
+                % documentation
+                SBstructure.states(numberStates).notes = speciesNotes;
+                SBstructure.states(numberStates).type = 'isSpecie';
+                SBstructure.states(numberStates).compartment = SBMLmodel.species(k1).compartment;
+                SBstructure.states(numberStates).unittype = speciesUnits;                
+                % Initialize the ODE field for this state
+                SBstructure.states(numberStates).ODE = '';
+                % Increment
+                numberStates = numberStates+1;
+            elseif numberRulesSpecies == 1,
+                % Before including the species in the model structure we have
+                % to check if this species is also used in reactions as product
+                % or reactant. In this case an error message will be issued,
+                % since non-boundary species are not allowed to appear in
+                % reactions and rules.
+                reactionSpeciesPresent = checkReactionsForSpecies(speciesName,SBMLmodel);
+                if reactionSpeciesPresent,
+                    % Species is also present in a reaction. This means the SBML
+                    % model is inconsistent. => error
+                    errorMsg = sprintf('%s\nSpecies ''%s'' defined by rule and altered by reactions\n',errorMsg,speciesName);
+                end
+                % Even in the case of an error we continue here with the
+                % processing - The error message will take care of returning
+                % an empty model structure at the end
+                if strcmp(lastRuleType,'rate'),
+                    % Species added as a state, since rule of type 'rate'
+                    SBstructure.states(numberStates).name = speciesName;
+                    % check if an initial value is set for a species
+                    if isempty(initialCondition),
+%                         errorMsg = sprintf('%s\nNo initial value defined for species ''%s''\n',errorMsg,speciesName);
+                        initialCondition = 0;
+                    end
+                    % Include initial value into structure
+                    SBstructure.states(numberStates).initialCondition = initialCondition;
+                    % Include the RHS formula as the ODE for this species state
+                    % in case of speciesUnits='concentration' divide the
+                    % ODE by the compartmentsize
+                    SBstructure.states(numberStates).ODE = lastRuleFormula;
+                    % Set a note that type of state is 'species'
+                    SBstructure.states(numberStates).notes = speciesNotes;
+                    % initialize type, compartment, and unittype fields
+                    SBstructure.states(numberStates).type = 'isSpecie';
+                    SBstructure.states(numberStates).compartment = SBMLmodel.species(k1).compartment;
+                    SBstructure.states(numberStates).unittype = speciesUnits;                
+                    % Increment
+                    numberStates = numberStates+1;
+                else
+                    % Species added as a variable, since rule of type 'scalar'
+                    % Determine the index where to include the variable (based
+                    % on the ordering of the scalar rules)
+                    indexVariable = find(orderScalarRules==lastRuleIndex);
+                    SBstructure.variables(indexVariable).name = speciesName;
+                    SBstructure.variables(indexVariable).formula = lastRuleFormula;
+                    SBstructure.variables(indexVariable).notes = speciesNotes;
+                    % initialize type, compartment, and unittype fields
+                    SBstructure.variables(indexVariable).type = 'isSpecie';
+                    SBstructure.variables(indexVariable).compartment = SBMLmodel.species(k1).compartment;
+                    SBstructure.variables(indexVariable).unittype = speciesUnits;
+                end
+            end
+            % The case where numberRulesSpecies > 1 does not have to be treated
+            % here since already an error message is set above. This error
+            % message will lead to an empty model structure at the end. Even
+            % if the error is set the rest of the model will be processed.
+            % This has the advantage that all errors can be
+            % detected at once and makes the control structure of this script
+            % simpler.
+        else
+            % Process all the species that DO have a boundary condition
+            if numberRulesSpecies == 0,
+                % Include boundary species as a parameter
+                SBstructure.parameters(numberParameters).name = speciesName;
+                % Check if an initial amount is set for a species
+                if isempty(initialCondition),
+%                     errorMsg = sprintf('%s\nNo initial value defined for species ''%s''\n',errorMsg,speciesName);
+                    initialCondition = 0;
+                end
+                % Include initial value
+                SBstructure.parameters(numberParameters).value = initialCondition;
+                % Set note that type of the parameter is 'boundaey species'
+                SBstructure.parameters(numberParameters).notes = speciesNotes;
+                % initialize type, compartment, and unittype fields
+                SBstructure.parameters(numberParameters).type = 'isSpecie';
+                SBstructure.parameters(numberParameters).compartment = SBMLmodel.species(k1).compartment;
+                SBstructure.parameters(numberParameters).unittype = speciesUnits;
+                % Increment
+                numberParameters = numberParameters+1;
+            elseif numberRulesSpecies == 1,
+                % Boundary species may appear as products and reactants in
+                % reactions.
+                if strcmp(lastRuleType,'rate'),
+                    % Boundary species added as a state, since rule of type 'rate'
+                    SBstructure.states(numberStates).name = speciesName;
+                    % check if an initial amount is set for a species
+                    if isempty(initialCondition),
+%                         errorMsg = sprintf('%s\nNo initial value defined for species ''%s''\n',errorMsg,speciesName);
+                        initialCondition = 0;
+                    end
+                    % Include initial value in structure
+                    SBstructure.states(numberStates).initialCondition = initialCondition;
+                    % Include the RHS formula as the ODE for this species state
+                    SBstructure.states(numberStates).ODE = lastRuleFormula;
+                    % Set note that type of the state is 'boundary species'
+                    SBstructure.states(numberStates).notes = speciesNotes;
+                    % initialize type, compartment, and unittype fields
+                    SBstructure.states(numberStates).type = 'isSpecie';
+                    SBstructure.states(numberStates).compartment = SBMLmodel.species(k1).compartment;
+                    SBstructure.states(numberStates).unittype = speciesUnits;
+                    % Increment
+                    numberStates = numberStates+1;
+                else
+                    % Boundary species added as a variable, since rule of type 'scalar'
+                    % Determine the index where to include the variable (based
+                    % on the ordering of the scalar rules)
+                    indexVariable = find(orderScalarRules==lastRuleIndex);
+                    SBstructure.variables(indexVariable).name = speciesName;
+                    SBstructure.variables(indexVariable).formula = lastRuleFormula;
+                    SBstructure.variables(indexVariable).notes = speciesNotes;
+                    % initialize type, compartment, and unittype fields
+                    SBstructure.variables(indexVariable).type = 'isSpecie';
+                    SBstructure.variables(indexVariable).compartment = SBMLmodel.species(k1).compartment;
+                    SBstructure.variables(indexVariable).unittype = speciesUnits;
+                end
+            end
+        end
+    else
+        % Species defined as being constant!
+        % Thus include it as parameter
+        SBstructure.parameters(numberParameters).name = speciesName;
+        % Check if an initial amount is set for species
+        if isempty(initialCondition),
+%             errorMsg = sprintf('%s\nNo initial value defined for species ''%s''\n',errorMsg,speciesName);
+            initialCondition = 0;
+        end
+        % Include Initial value in SBstructure
+        SBstructure.parameters(numberParameters).value = initialCondition;
+        % Set note that type of the parameter is 'constant species'
+        SBstructure.parameters(numberParameters).notes = speciesNotes;
+        % initialize type, compartment, and unittype fields
+        SBstructure.parameters(numberParameters).type = 'isSpecie';
+        SBstructure.parameters(numberParameters).compartment = SBMLmodel.species(k1).compartment;
+        SBstructure.parameters(numberParameters).unittype = speciesUnits;
+        % Increment
+        numberParameters = numberParameters+1;
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PARAMETERS (INCLUDE IN STRUCTURE)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% First process the global parameters and check if rules exist for them
+%   - rate rule: as state
+%   - scalar rule: as variable
+%   - no rule: as parameter
+%
+% Then process the local parameters. They can only be parameters, no 
+% rules can exist for them. In case of collisions:
+%
+% parameter-parameter: colliding parameters are prefixed by their reaction 
+%                      names (global parameters are not prefixed)
+%
+% parameter-species: are prefixed by reaction name
+%
+% parameter-compartment: are prefixed by reactio name
+%
+% Start with global parameters
+for k = 1:length(SBMLmodel.parameter),
+    parameterName = SBMLmodel.parameter(k).id;
+    parameterValue = SBMLmodel.parameter(k).value;
+    parameterNotes = convert2SBNotes(SBMLmodel.parameter(k).notes,1);
+    % Check the number of rules the parameter is in and get the index
+    % of the last rule the parameter is used in together with its type
+    % ('rate' or 'scalar') and the right hand side expression 'formula'
+    [numberRulesParameter,lastRuleIndex,lastRuleType,lastRuleFormula,errorMsg] = getRules(parameterName,SBMLmodel,errorMsg);
+    if numberRulesParameter > 1,
+        % Parameter defined by more than one rule => error
+        errorMsg = sprintf('%s\nParameter ''%s'' defined by more than one rule\n',errorMsg,parameterName);
+    end
+    if numberRulesParameter == 0 || SBMLmodel.parameter(k).constant,
+        % Include parameter as parameter
+        SBstructure.parameters(numberParameters).name = parameterName;
+        % Check if a value is set for the parameter
+        if length(parameterValue)==0,
+            errorMsg = sprintf('%s\nNo value defined defined for parameter ''%s''\n',errorMsg,parameterName);
+        end
+        % Include value in SBstructure
+        SBstructure.parameters(numberParameters).value = parameterValue;
+        % Set note that type of the parameter is 'global'
+        SBstructure.parameters(numberParameters).notes = parameterNotes; 
+        % initialize type, compartment, and unittype fields
+        SBstructure.parameters(numberParameters).type = 'isParameter';
+        SBstructure.parameters(numberParameters).compartment = '';
+        SBstructure.parameters(numberParameters).unittype = '';                
+        % Increment
+        numberParameters = numberParameters+1;
+    elseif numberRulesParameter == 1,
+        % One rule has been detected for this parameter
+        if strcmp(lastRuleType,'rate'),
+            % Parameter added as a state, since rule of type 'rate'
+            SBstructure.states(numberStates).name = parameterName;
+            % check if an initial amount is set for the parameter
+            if length(parameterValue)==0,
+                errorMsg = sprintf('%s\nNo value defined for parameter ''%s''\n',errorMsg,parameterName);
+            end
+            % Include value as initial value in SBstructure
+            SBstructure.states(numberStates).initialCondition = parameterValue;
+            % Include the RHS formula as the ODE for this parameter state
+            SBstructure.states(numberStates).ODE = lastRuleFormula;
+            % Set note that type of the state is 'parameter rule'
+            SBstructure.states(numberStates).notes = parameterNotes;
+            % initialize type, compartment, and unittype fields
+            SBstructure.states(numberStates).type = 'isParameter';
+            SBstructure.states(numberStates).compartment = '';
+            SBstructure.states(numberStates).unittype = '';                
+            % Increment
+            numberStates = numberStates+1;
+        else
+            % Parameter added as a variable, since rule of type 'scalar'
+            % Determine the index where to include the variable (based
+            % on the ordering of the scalar rules)
+            indexVariable = find(orderScalarRules==lastRuleIndex);
+            SBstructure.variables(indexVariable).name = parameterName;
+            SBstructure.variables(indexVariable).formula = lastRuleFormula;
+            SBstructure.variables(indexVariable).notes = parameterNotes;
+            % initialize type, compartment, and unittype fields
+            SBstructure.variables(indexVariable).type = 'isParameter';
+            SBstructure.variables(indexVariable).compartment = '';
+            SBstructure.variables(indexVariable).unittype = '';               
+        end
+    end
+end
+% Then include the local parameters within the different reactions
+% Name collisions are avoided by adding the reaction name in front of each
+% local parameter.
+for k1 = 1:length(SBMLmodel.reaction),
+    % get the current reaction name
+    reactionName = SBMLmodel.reaction(k1).id;
+    if ~isempty(SBMLmodel.reaction(k1).kineticLaw),
+        for k2 = 1:length(SBMLmodel.reaction(k1).kineticLaw.parameter),
+            % get the current local parameter in reaction reactionName
+            parameterName = SBMLmodel.reaction(k1).kineticLaw.parameter(k2).id;
+            parameterValue = SBMLmodel.reaction(k1).kineticLaw.parameter(k2).value;
+            parameterNotes = convert2SBNotes(SBMLmodel.reaction(k1).kineticLaw.parameter(k2).notes,1);
+            % check if a value is set for the parameter
+            if length(parameterValue)==0,
+                errorMsg = sprintf('%s\nNo value defined for parameter ''%s'' in reaction ''%s''\n',errorMsg,parameterName,reactionName);
+            end
+            % add the reaction name to the parameter and update the kinetic rate law
+            parameterName = char([double(reactionName) double('_') double(parameterName)]);  % fastest strcat ;)
+            % Include parameter in the structure
+            SBstructure.parameters(numberParameters).name = parameterName;
+            SBstructure.parameters(numberParameters).value = parameterValue;
+            SBstructure.parameters(numberParameters).notes = parameterNotes;
+            % initialize type, compartment, and unittype fields
+            SBstructure.parameters(numberParameters).type = 'isParameter';
+            SBstructure.parameters(numberParameters).compartment = '';
+            SBstructure.parameters(numberParameters).unittype = '';
+            numberParameters = numberParameters+1;
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% COMPARTMENTS (INCLUDE IN STRUCTURE)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Include compartments
+% No rule => as parameters
+%
+% Scalar rule => as variables
+%       
+% Rate rule => as states
+%
+for k = 1:length(SBMLmodel.compartment),
+    compartmentName = SBMLmodel.compartment(k).id;
+    compartmentValue = SBMLmodel.compartment(k).size;
+    compartmentNotes = convert2SBNotes(SBMLmodel.compartment(k).notes,1);
+    % Check the number of rules the compartment is in and get the index
+    % of the last rule the compartment is used in together with its type
+    % ('rate' or 'scalar') and the right hand side expression 'formula'
+    [numberRulesCompartment,lastRuleIndex,lastRuleType,lastRuleFormula,errorMsg] = getRules(compartmentName,SBMLmodel,errorMsg);
+    if numberRulesCompartment > 1,
+        % Compartment defined by more than one rule => error
+        errorMsg = sprintf('%s\nCompartment ''%s'' defined by more than one rule\n',errorMsg,compartmentName);
+    end
+    if numberRulesCompartment == 1 && SBMLmodel.compartment(k).constant,
+        % compartment defined as constant, but rule defined for it
+        errorMsg = sprintf('%s\nCompartment ''%s'' defined as having constant size but rule exists for it.\n',errorMsg,compartmentName);
+    end
+    if numberRulesCompartment == 0 || SBMLmodel.compartment(k).constant,
+        % check compartment size and return an error in case it is "NaN"
+        if isnan(compartmentValue),
+%            errorMsg = sprintf('%s\nNo size for compartment ''%s'' given\n',errorMsg,compartmentName);
+             compartmentValue = 1;   
+        end
+        % Include compartment as parameter
+        SBstructure.parameters(numberParameters).name = compartmentName;
+        % Check if a value is set for the parameter
+        if isempty(compartmentValue),
+%             errorMsg = sprintf('%s\nNo value defined defined for compartment ''%s''\n',errorMsg,compartmentName);
+            compartmentValue = 1;
+        end
+        % Include value in SBstructure
+        SBstructure.parameters(numberParameters).value = compartmentValue;
+        % Set note that type of the parameter is 'compartment size'
+        SBstructure.parameters(numberParameters).notes = compartmentNotes;
+        % initialize type, compartment, and unittype fields
+        SBstructure.parameters(numberParameters).type = 'isCompartment';
+        SBstructure.parameters(numberParameters).compartment = SBMLmodel.compartment(k).outside;
+        SBstructure.parameters(numberParameters).unittype = '';
+        % Increment
+        numberParameters = numberParameters+1;
+    elseif numberRulesCompartment == 1,
+        % One rule has been detected for this compartment
+        if strcmp(lastRuleType,'rate'),
+            % check compartment size and return an error in case it is "NaN"
+            if isnan(compartmentValue),
+%                 errorMsg = sprintf('%s\nNo size for compartment ''%s'' given\n',errorMsg,compartmentName);
+                compartmentValue = 1;
+            end
+            % Compartment added as a state, since rule of type 'rate'
+            SBstructure.states(numberStates).name = compartmentName;
+            % check if an initial amount is set for the compartment
+            if isempty(compartmentValue),
+%                 errorMsg = sprintf('%s\nNo value defined for compartment ''%s''\n',errorMsg,compartmentName);
+                compartmentValue = 1;
+            end
+            % Include value as initial value in SBstructure
+            SBstructure.states(numberStates).initialCondition = compartmentValue;
+            % Include the RHS formula as the ODE for this compartment state
+            SBstructure.states(numberStates).ODE = lastRuleFormula;
+            % Set note that type of the state is 'compartment size'
+            SBstructure.states(numberStates).notes = compartmentNotes;
+            % initialize type, compartment, and unittype fields
+            SBstructure.states(numberStates).type = 'isCompartment';
+            SBstructure.states(numberStates).compartment = SBMLmodel.compartment(k).outside;
+            SBstructure.states(numberStates).unittype = '';
+            % Increment
+            numberStates = numberStates+1;
+            % compartment_rate variable right hand side
+            compartmentDotRHS = lastRuleFormula;
+        else
+            % Compartment added as a variable, since rule of type 'scalar'
+            % Determine the index where to include the variable (based
+            % on the ordering of the scalar rules)
+            indexVariable = find(orderScalarRules==lastRuleIndex);
+            SBstructure.variables(indexVariable).name = compartmentName;
+            SBstructure.variables(indexVariable).formula = lastRuleFormula;
+            SBstructure.variables(indexVariable).notes = compartmentNotes;
+            % initialize type, compartment, and unittype fields
+            SBstructure.variables(indexVariable).type = 'isCompartment';
+            SBstructure.variables(indexVariable).compartment = SBMLmodel.compartment(k).outside;
+            SBstructure.variables(indexVariable).unittype = '';
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% REACTIONS (INCLUDE IN STRUCTURE)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Read in reaction information into the model structure. Replace colliding 
+% parameter names with their prefixed versions (reaction name). Reactions 
+% are included into the model structure in the 'reactions' field. This leads 
+% to shorter ODE definitions for the specie states, which then contain the 
+% reaction names with the correct stoichiometries. The 'reactions' field
+% contains three fields: 'name', 'formula', 'notes'
+%
+% We differentiate the case where:
+%   - single compartment model with constant compartment size = 1
+%     (nothing is done additionally)
+%   - multi compartment model or single compartment model with compartment 
+%     size different from one. In this case all species names in the
+%     reactions are exchanged agains speciesname/speciesCompartmentSize
+%
+% Cycle through all reactions
+for k1 = 1:length(SBMLmodel.reaction),
+    reactionName = SBMLmodel.reaction(k1).id;
+    kineticLaw = SBMLmodel.reaction(k1).kineticLaw;
+    % check if a kineticLaw is given
+    if isempty(kineticLaw),
+        errorMsg = sprintf('%s\nNo kinetic law is given for reaction ''%s''\n',errorMsg,reactionName);
+    elseif isempty(kineticLaw.formula) || isempty(kineticLaw.math),
+        errorMsg = sprintf('%s\nNo kinetic formula law given for reaction ''%s''\n',errorMsg,reactionName);
+    end
+    % Process the kineticLaw formula by replacing the local parameter names
+    % by reactionname_parameternames and replace the mathml expressions
+    if ~isempty(kineticLaw),
+        if length(kineticLaw.formula) >= length(kineticLaw.math),
+            formula = kineticLaw.formula;
+        else
+            formula = kineticLaw.math;
+        end
+        if ~isempty(kineticLaw.parameter),
+            % SBML 2 can have formula in formula or math. Check which string is
+            % longer and use this one (quick and dirty fix - since it has been
+            % observer that TranslateSBML can return strange stuff in the math
+            % field sometimes)
+            for k2 = 1:length(kineticLaw.parameter),
+                parameterName = kineticLaw.parameter(k2).id;
+                newParameterName = char([double(reactionName) double('_') double(parameterName)]); % fastest strcat
+                formula = exchangeStringInString(formula,parameterName,newParameterName);
+            end
+        end
+    else
+        formula = '';
+    end
+    % replace MathML expressions in formula against MATLAB expressions
+    [formula] = replaceMathMLexpressions(formula);
+    % Include reaction information in the structure
+    SBstructure.reactions(k1).name = reactionName;
+    SBstructure.reactions(k1).formula = formula;
+    SBstructure.reactions(k1).notes = convert2SBNotes(SBMLmodel.reaction(k1).notes,1);
+    SBstructure.reactions(k1).reversible = SBMLmodel.reaction(k1).reversible;    
+    if (SBMLmodel.reaction(k1).isSetFast == 1) && (SBMLmodel.reaction(k1).fast == 1),
+        SBstructure.reactions(k1).fast = 1;    
+    else
+        SBstructure.reactions(k1).fast = 0;
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS REACTION ODES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add the reaction variable names with correct stoichiometries to the 'ODE' field
+% for the correct species. The 'correct' species are only non-boundary and 
+% non-constant species for which no rules exist. These are listed in
+% the 'speciesODElist'
+%
+for k1 = 1:length(speciesODElist),
+    % get name of species and the index of the corresponding state
+    speciesName = speciesODElist(k1).name;
+    stateIndex = speciesODElist(k1).stateIndex;
+    % cycle through all the reactions and look in which reactions the
+    % species is changed
+    for k2 = 1:length(SBstructure.reactions),
+        % get reaction name for inclusion in ODEstring
+        reactionName = SBstructure.reactions(k2).name;
+        % cycle through the reactants of the current reaction
+        % (ordering of reactions in SBstructure and SBMLmodel are equal)
+        for k3 = 1:length(SBMLmodel.reaction(k2).reactant),
+            reactantName = SBMLmodel.reaction(k2).reactant(k3).species;
+            if ~isempty(SBMLmodel.reaction(k2).reactant(k3).stoichiometryMath),
+                reactantStoichiometry = SBMLmodel.reaction(k2).reactant(k3).stoichiometryMath; 
+                isunitystoich = 0;
+            else
+                reactantStoichiometry_num = abs(double(SBMLmodel.reaction(k2).reactant(k3).stoichiometry) / double(SBMLmodel.reaction(k2).reactant(k3).denominator));
+                isunitystoich = reactantStoichiometry_num == 1;
+                reactantStoichiometry = num2str(reactantStoichiometry_num);
+            end
+            % If species name and reactant name are equal then add reaction
+            % to species ODE
+            if strcmp(reactantName,speciesName),
+                % construct the string to add to the ODE of the current reactant
+                if isunitystoich == 0,
+                    ODEstringAdd = char([double('-') double(reactantStoichiometry) double('*') double(reactionName)]); % fastest strcat
+                else
+                    ODEstringAdd = char([double('-') double(reactionName)]); % fastest strcat
+                end
+                % add the ODEstringAdd to the 'ODE' field of this species
+                SBstructure.states(stateIndex).ODE = char([double(SBstructure.states(stateIndex).ODE) double(ODEstringAdd)]); % fastest strcat
+                break;
+            end
+        end
+        % cycle through the products of the current reaction
+        % (ordering of reactions in SBstructure and SBMLmodel are equal)
+        for k3 = 1:length(SBMLmodel.reaction(k2).product),
+            productName = SBMLmodel.reaction(k2).product(k3).species;
+            if ~isempty(SBMLmodel.reaction(k2).product(k3).stoichiometryMath),
+                productStoichiometry = SBMLmodel.reaction(k2).product(k3).stoichiometryMath; 
+                isunitystoich = 0;
+            else
+                productStoichiometry_num = abs(double(SBMLmodel.reaction(k2).product(k3).stoichiometry) / double(SBMLmodel.reaction(k2).product(k3).denominator));
+                isunitystoich = productStoichiometry_num == 1;
+                productStoichiometry = num2str(productStoichiometry_num);
+            end
+            % If species name and product name are equal then add reaction
+            % to species ODE
+            if strcmp(productName,speciesName),
+                % construct the string to add to the ODE of the current product
+                if isunitystoich == 0,
+                    ODEstringAdd = char([double('+') double(productStoichiometry) double('*') double(reactionName)]); % fastest strcat
+                else
+                    ODEstringAdd = char([double('+') double(reactionName)]); % fastest strcat
+                end
+                % add the ODEstringAdd to the 'ODE' field of this species
+                SBstructure.states(stateIndex).ODE = char([double(SBstructure.states(stateIndex).ODE) double(ODEstringAdd)]); % fastest strcat
+                break;
+            end
+        end
+    end
+end
+% Now all ODEs should be defined - check if everything is correct!
+% Finally cycle through all the states and check if all ODEs have been defined
+for k = 1:length(SBstructure.states),
+    stateName = SBstructure.states(k).name;
+    stateODE = SBstructure.states(k).ODE;
+    if isempty(stateODE),
+%         % Issue a warning only and set ODE to 0
+%         disp(sprintf('No ODE defined for state ''%s''',stateName));
+        SBstructure.states(k).ODE = '0';
+    end
+end
+% After initial construction of the ODEs their units need to be changed (or
+% not) since the rate laws are assumed to have amount/time units.
+%
+% - species defined as 'amount' => no change necessary!
+% - species defined as 'concentration' => divide the ode expression by the
+%   compartment size the species is in.
+%
+% We differentiate the case where:
+%   - single compartment model with constant compartment size = 1
+%     (nothing is done additionally)
+%   - multi compartment model or single compartment model with compartment 
+%     size different from one. In this case the conversion is done for the
+%     concentration species.
+%
+compartmentddtdonelist = {};
+for k1 = 1:length(speciesODElist),
+    % get name of species and the index of the corresponding state
+    speciesName = speciesODElist(k1).name;
+    speciesUnits = speciesODElist(k1).units;
+    stateIndex = speciesODElist(k1).stateIndex;
+    % only do the conversion if species in concentration units!
+    if strcmp(speciesUnits,'concentration'),
+        % check if the model has only one compartment with volume 1 and
+        % constant volume => if yes then leave ODE as it is.
+        convertODE = 1;
+%         if length(SBMLmodel.compartment) == 1,
+%             % only one compartment
+%             if SBMLmodel.compartment(1).size == 1,
+%                 % size of compartment is 1
+%                 for k = 1:length(SBstructure.parameters),
+%                     % check if compartment size is constant (then it is defined as
+%                     % a parameter)
+%                     if strcmp(SBMLmodel.compartment(1).id,SBstructure.parameters(k).name),
+%                         % compartment defined as a parameter and thus no species
+%                         % names need to be exchanged
+%                         convertODE = 0;
+%                         % return directly to the main function
+%                     end
+%                 end
+%             end
+%         end
+        if convertODE,
+            % convert the ODE expression
+            % get compartment name for species
+            compartmentName = getCompartmentNameSpecies(speciesName,SBMLmodel);
+            ODEstring = SBstructure.states(stateIndex).ODE;
+            if ~strcmp(ODEstring,'0')
+                % construct new ODE string
+                newODEstring = char([double('(') double(ODEstring) double(')/') double(compartmentName)]); % fastest strcat 
+                % include the new ODE string in structure
+                SBstructure.states(stateIndex).ODE = newODEstring;
+            end
+            
+            
+% HANDLE TIME VARYING COMPARTMENT SIZES
+            [changingFlag,ddtCompartment] = getCompartmentInfoChanging(compartmentName,SBstructure,compartmentddtdonelist);
+            if changingFlag,
+                % append the second derivative term
+                SBstructure.states(stateIndex).ODE = sprintf('%s - %s*ddt_%s/%s',SBstructure.states(stateIndex).ODE,speciesName,compartmentName,compartmentName);
+                
+                % add the time derivative of the compartment to variables
+                % (if not done already)
+                if isempty(strmatchSB(compartmentName,compartmentddtdonelist,'exact')),
+                    SBstructure.variables(end+1).name = ['ddt_' compartmentName];
+                    SBstructure.variables(end).formula = ddtCompartment;
+                    SBstructure.variables(end).type = 'isParameter';
+                    SBstructure.variables(end).compartment = '';
+                    SBstructure.variables(end).unittype = '';
+                    SBstructure.variables(end).notes = 'Time derivative of compartment';
+                    compartmentddtdonelist{end+1} = compartmentName;
+                end
+            end
+
+            
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EVENTS (INCLUDE IN STRUCTURE)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k1 = 1:length(SBMLmodel.event),
+    % get the name of the event
+    if ~isempty(SBMLmodel.event(k1).id),
+        eventName = SBMLmodel.event(k1).id;
+    else 
+        eventName = sprintf('Event_%d',k1);
+    end
+    % check event trigger is present
+    if isempty(SBMLmodel.event(k1).trigger),
+        errorMsg = sprintf('%s\nNo trigger condition defined for event ''%s''.',errorMsg,eventName);
+    end
+    % get delay and check if it is not given or given
+    delay = SBMLmodel.event(k1).delay;
+    if isempty(delay),
+        delay = '0';
+    end
+    delay = replaceMathMLexpressions(delay);
+    % fill structure with basic event information
+    SBstructure.events(k1).name = eventName;
+    % check the trigger expression and handle delay if present
+    trigger = SBMLmodel.event(k1).trigger;
+    trigger = removeWhiteSpace(trigger);
+    trigger = replaceMathMLexpressions(trigger);
+    if ~strcmp(delay,'0'),
+        trigger = ['delaySB(' trigger ',' delay ')'];
+    end
+    SBstructure.events(k1).trigger = trigger;
+    SBstructure.events(k1).notes = convert2SBNotes(SBMLmodel.event(k1).notes,1);
+    % fill in data for event assignments
+    for k2 = 1:length(SBMLmodel.event(k1).eventAssignment),
+        variableName = SBMLmodel.event(k1).eventAssignment(k2).variable;
+        variableValue = SBMLmodel.event(k1).eventAssignment(k2).math;
+        % check that the name is the name of a state in the model
+        nameFound = 0;
+        for k3 = 1:length(SBstructure.states),
+            if strcmp(variableName,SBstructure.states(k3).name),
+                nameFound = 1;
+                break;
+            end
+        end
+        if nameFound == 0,
+            % events on parameters are now allowed
+            %errorMsg = sprintf('%s\nThe variable affected by event ''%s'' is not a state.',errorMsg,eventName);
+        end
+        % check that the variable value is set
+        if isempty(variableValue),
+            errorMsg = sprintf('%s\nNo math element given for event ''%s''.',errorMsg,eventName);
+        end
+        % update SBstructure
+        SBstructure.events(k1).assignment(k2).variable = variableName;
+        assignformula = replaceMathMLexpressions(variableValue);
+        % if delay not 0 then add delay information
+        if ~strcmp(delay,'0'),
+            assignformula = ['delaySB(' assignformula ',' delay ')'];
+        end
+        SBstructure.events(k1).assignment(k2).formula = assignformula;
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXCHANGE NaN VALUES AGAINST 0
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(SBstructure.states),
+    if isnan(SBstructure.states(k).initialCondition),
+        SBstructure.states(k).initialCondition = 0;
+    end
+end
+for k=1:length(SBstructure.parameters),
+    if isnan(SBstructure.parameters(k).value),
+        SBstructure.parameters(k).value = 0;
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% IMPORT ALGEBRAIC RULES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% prepare the import
+% 1)need to find all species, compartments, and (global) parameters that are
+% NOT constant. These are the candidates for the determination by an
+% algebraic rule (in this order of priority)
+nonConstantSpecies = {};
+nonConstantParameters = {};
+nonConstantCompartments = {};
+for k=1:length(SBMLmodel.species),
+    if SBMLmodel.species(k).constant == 0,
+        nonConstantSpecies{end+1} = SBMLmodel.species(k).id;
+    end
+end
+for k=1:length(SBMLmodel.parameter),
+    if SBMLmodel.parameter(k).constant == 0,
+        nonConstantParameters{end+1} = SBMLmodel.parameter(k).id;
+    end
+end
+for k=1:length(SBMLmodel.compartment),
+    if SBMLmodel.compartment(k).constant == 0,
+        nonConstantCompartments{end+1} = SBMLmodel.compartment(k).id;
+    end
+end
+% 2) now we need to make a list of all states determined by ODEs and
+% variables determined by formulas. 
+allStates = {};
+for k=1:length(SBstructure.states),
+    if SBstructure.states(k).ODE ~= '0',
+        % Only non constant states (would also require the check of event 
+        % assignments ... but in my opinion, SBML should simply define the
+        % variable which is affected by an algebraic rule ... so much
+        % cleaner!
+        allStates{end+1} = SBstructure.states(k).name;
+    end
+end
+allVariables = {};
+for k=1:length(SBstructure.variables),
+    if ~isnan(str2double(SBstructure.variables(k).formula)),
+        % If variable has not a numeric assignment ... 
+        allVariables{end+1} = SBstructure.variables(k).name;
+    end
+end
+% 3) The names of the states and variables need to be deleted from the
+% nonConstantSpecies, nonConstantCompartments, and nonConstantParameters,
+% because only the remaining ones can be determined by algebraic rules
+possibleSpecies = setdiff(nonConstantSpecies,allStates);
+possibleSpecies = setdiff(possibleSpecies,allVariables);
+possibleParameters = setdiff(nonConstantParameters,allStates);
+possibleParameters = setdiff(possibleParameters,allVariables);
+possibleCompartments = setdiff(nonConstantCompartments,allStates);
+possibleCompartments = setdiff(possibleCompartments,allVariables);
+% 4) now we check if at least as many possibilities as there are ARs
+% (otherwise certainly overdetermined).
+ARindices = strmatchSB('SBML_ALGEBRAIC_RULE',{SBMLmodel.rule.typecode},'exact');
+nrARs = length(ARindices);
+if length(possibleSpecies) + length(possibleParameters) + length(possibleCompartments) < nrARs,
+    error('The model is certainly overdetermined. To many algebraic rules!');
+end
+% 5) Now check which of the possible elements appear in the ARs. If at
+% least a number of nrARs do appear there its fine ... if not put out a
+% warning and select whatever.
+ARs = SBMLmodel.rule(ARindices);
+ReallyPossibleSpecies = {};
+ReallyPossibleParameters = {};
+ReallyPossibleCompartments = {};
+for k=1:nrARs,
+    species = regexp(ARs(k).formula,possibleSpecies,'match');
+    for k2=1:length(species),
+        if ~isempty(species{k2}),
+            ReallyPossibleSpecies{end+1} = species{k2}{1};
+        end
+    end
+    parameters = regexp(ARs(k).formula,possibleParameters,'match');
+    for k2=1:length(parameters),
+        if ~isempty(parameters{k2}),
+            ReallyPossibleParameters{end+1} = parameters{k2}{1};
+        end
+    end
+    compartments = regexp(ARs(k).formula,possibleCompartments,'match');
+    for k2=1:length(compartments),
+        if ~isempty(compartments{k2}),
+            ReallyPossibleCompartments{end+1} = compartments{k2}{1};
+        end
+    end
+end
+% make unique (it might not be)
+ReallyPossibleSpecies = unique(ReallyPossibleSpecies);
+ReallyPossibleParameters = unique(ReallyPossibleParameters);
+ReallyPossibleCompartments = unique(ReallyPossibleCompartments);
+nrPossible = length(ReallyPossibleSpecies) + length(ReallyPossibleParameters) + length(ReallyPossibleCompartments);
+if nrPossible < nrARs,
+    error('The model is overdetermined or at least it is unclear which variables are to be determined using the algebraic rules.');
+end
+% get the indices in the SBML model for the really possible ones
+indexspecies = [];
+indexparameters = [];
+indexcompartments = [];
+for k=1:length(ReallyPossibleSpecies),
+    indexspecies(end+1) = strmatchSB(ReallyPossibleSpecies{k},{SBMLmodel.species.id},'exact');
+end
+for k=1:length(ReallyPossibleParameters),
+    indexparameters(end+1) = strmatchSB(ReallyPossibleParameters{k},{SBMLmodel.parameter.id},'exact');
+end
+for k=1:length(ReallyPossibleCompartments),
+    indexcompartments(end+1) = strmatchSB(ReallyPossibleCompartments{k},{SBMLmodel.compartment.id},'exact');
+end
+% 6) Add the algebraic rules and delete the corresponding parameters from
+% the SBmodel structure
+for k=1:length(ARindices),
+    rule = SBMLmodel.rule(ARindices);
+    % determine the name (it needs to be one of the elements in
+    % indexspecies, indexparameters, or indexcompartments
+    if ~isempty(indexspecies),      
+        index = indexspecies(1);
+        name = SBMLmodel.species(index).id;
+        type = 'isSpecie';
+        compartment = SBMLmodel.species(index).compartment;
+        if SBMLmodel.species(index).isSetInitialAmount,
+            if SBMLmodel.species(index).hasOnlySubstanceUnits,
+                unittype = 'amount';        
+            else
+                unittype = 'concentration';
+                amount2concentration(end+1).species = name;
+                amount2concentration(end).compartment = compartment;                
+            end
+        else
+            unittype = 'concentration';
+        end
+        % remove the used species
+        indexspecies(1) = [];             
+    elseif ~isempty(indexparameters),
+        index = indexparameters(1);
+        name = SBMLmodel.parameter(index).id;
+        type = 'isParameter';
+        compartment = '';
+        unittype = '';
+        % remove the used parameter
+        indexparameters(1) = [];      
+    elseif ~isempty(indexcompartments),
+        index = indexcompartments(1);
+        name = SBMLmodel.compartment(index).id;
+        type = 'isCompartment';
+        compartment = SBMLmodel.compartment(index).outside;
+        unittype = '';        
+        % remove the used compartment
+        indexcompartments(1) = [];      
+    else
+        error('Should not get to this :)');
+    end
+    % get initial condition (can be state, parameter, or variable .... YEEEESSS!)
+    % and delete the corresponding component from the model (now determined
+    % by algebraic rule).
+    allStates = {SBstructure.states.name};    
+    allParams = {SBstructure.parameters.name};
+    allVars = {SBstructure.variables.name};
+    indexstate = strmatchSB(name,allStates,'exact');
+    indexparam = strmatchSB(name,allParams,'exact');
+    indexvar = strmatchSB(name,allVars,'exact');
+    if ~isempty(indexstate),
+        initialCondition = SBstructure.states(indexstate).initialCondition;    
+        SBstructure.states(indexstate) = [];
+    elseif ~isempty(indexparam),
+        initialCondition = SBstructure.parameters(indexparam).value;
+        SBstructure.parameters(indexparam) = [];
+    elseif ~isempty(indexvar),
+        initialCondition = str2double(SBstructure.variables(indexvar).formula);    
+        SBstructure.variables(indexvar) = [];
+    else
+        error('Should not get to this :) ... 2');
+    end
+    % add algebraic rule
+    SBstructure.algebraic(k).name = name;
+    SBstructure.algebraic(k).formula = rule(k).formula;
+    SBstructure.algebraic(k).initialCondition = initialCondition;
+    SBstructure.algebraic(k).type = type;
+    SBstructure.algebraic(k).compartment = compartment;
+    SBstructure.algebraic(k).unittype = unittype;
+    SBstructure.algebraic(k).notes = rule(k).notes;
+end
+% 7) Its DONE!
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK ALL COMPONENTNAMES AND REMOVE TRAILING "_"
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% get names to exchange
+oldnames = {};
+newnames = {};
+% states
+for k=1:length(SBstructure.states),
+    [oldnames,newnames,changed,SBstructure.states(k).name] = removeUnderscores(oldnames,newnames,SBstructure.states(k).name);    
+end
+% algebraic
+for k=1:length(SBstructure.algebraic),
+    [oldnames,newnames,changed,SBstructure.algebraic(k).name] = removeUnderscores(oldnames,newnames,SBstructure.algebraic(k).name);    
+end
+% parameters
+for k=1:length(SBstructure.parameters),
+    [oldnames,newnames,changed,SBstructure.parameters(k).name] = removeUnderscores(oldnames,newnames,SBstructure.parameters(k).name);
+end
+% variables
+for k=1:length(SBstructure.variables),
+    [oldnames,newnames,changed,SBstructure.variables(k).name] = removeUnderscores(oldnames,newnames,SBstructure.variables(k).name);
+end
+% reactions
+for k=1:length(SBstructure.reactions),
+    [oldnames,newnames,changed,SBstructure.reactions(k).name] = removeUnderscores(oldnames,newnames,SBstructure.reactions(k).name);   
+end
+% functions
+for k=1:length(SBstructure.functions),
+    [oldnames,newnames,changed,SBstructure.functions(k).name] = removeUnderscores(oldnames,newnames,SBstructure.functions(k).name);   
+end
+% ok, if names changed then handle formulas
+if ~isempty(oldnames),
+    % states
+    for k=1:length(SBstructure.states),
+        SBstructure.states(k).ODE = regexprep(SBstructure.states(k).ODE,oldnames,newnames);
+        SBstructure.states(k).compartment = regexprep(SBstructure.states(k).compartment,oldnames,newnames);
+    end
+    % algebraic
+    for k=1:length(SBstructure.algebraic),
+        SBstructure.algebraic(k).formula = regexprep(SBstructure.algebraic(k).formula,oldnames,newnames);    
+        SBstructure.algebraic(k).compartment = regexprep(SBstructure.algebraic(k).compartment,oldnames,newnames);
+    end
+    % parameters
+    for k=1:length(SBstructure.parameters),
+        SBstructure.parameters(k).compartment = regexprep(SBstructure.parameters(k).compartment,oldnames,newnames);
+    end    
+    % variables
+    for k=1:length(SBstructure.variables),
+        SBstructure.variables(k).formula = regexprep(SBstructure.variables(k).formula,oldnames,newnames);
+        SBstructure.variables(k).compartment = regexprep(SBstructure.variables(k).compartment,oldnames,newnames);
+    end
+    % reactions
+    for k=1:length(SBstructure.reactions),
+        SBstructure.reactions(k).formula = regexprep(SBstructure.reactions(k).formula,oldnames,newnames);
+    end
+    % functions
+    for k=1:length(SBstructure.functions),
+        SBstructure.functions(k).formula = regexprep(SBstructure.functions(k).formula,oldnames,newnames);
+    end
+    % events
+    for k=1:length(SBstructure.events),
+        SBstructure.events(k).trigger = regexprep(SBstructure.events(k).trigger,oldnames,newnames);
+        for k2=1:length(SBstructure.events(k).assignment),
+            SBstructure.events(k).assignment(k2).variable = regexprep(SBstructure.events(k).assignment(k2).variable,oldnames,newnames);
+            SBstructure.events(k).assignment(k2).formula = regexprep(SBstructure.events(k).assignment(k2).formula,oldnames,newnames);
+        end
+    end
+end
+
+% return from main function
+return
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE TIME VARYING COMPARTMENTS ... get changing flag and the
+% time-derivative of the compartment size.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [changingFlag,ddtCompartment] = getCompartmentInfoChanging(compartmentName,SBstructure,compartmentddtdonelist)
+changingFlag = 0; 
+ddtCompartment = '';
+% go through states and variables to check if the compartment name appears
+% there ... then just do it
+indexState = strmatchSB(compartmentName,{SBstructure.states.name},'exact');
+indexVariable = strmatchSB(compartmentName,{SBstructure.variables.name},'exact');
+indexAlgebraic = strmatchSB(compartmentName,{SBstructure.algebraic.name},'exact');
+if ~isempty(indexState),
+    changingFlag = 1; 
+    ddtCompartment = SBstructure.states(indexState).ODE;
+elseif ~isempty(indexVariable),
+    changingFlag = 1;
+    Compartment = SBstructure.variables(indexVariable).formula;
+    % ddtCompartment needs only to be determined once for each compartment.
+    % So not per species in this compartment. We make it simple here (since
+    % it mainly matters when determining and adding it manually):
+    if isempty(strmatchSB(compartmentName,compartmentddtdonelist,'exact')),
+        if symbolicpresentSB(),
+            ddtCompartment = char(diff(Compartment,'time'));
+        else
+            disp('For the handling of time varying compartments the time derivative of the');
+            disp('compartment size needs to be determined. Since the symbolic toolbox is not');
+            disp('present you need to do that manually.');
+            disp(' ');
+            disp(sprintf('C(time) = %s',Compartment));
+            disp(' ');
+            ddtCompartment = input('d/dtime(C(time)) = ','s');
+        end
+    end
+elseif ~isempty(indexAlgebraic),
+    error(sprintf('Size of compartment ''%s'' defined by an algebraic rule! Cant determine\nthe analytic rate of change of the size.',compartmentName));
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HELP FUNCTION TO REMOVE __ at the start of element names
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [oldnames,newnames,changed,newname] = removeUnderscores(oldnames,newnames,name)
+changed = 0;
+newname = regexprep(name,'^([_]?)','underscore_');
+if length(name) ~= length(newname),
+    changed = 1;
+    oldnames{end+1} = sprintf('\\<%s\\>',name);
+    newnames{end+1} = newname;
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% FIND RULES FOR A CERTAIN VARIABLE NAME
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Cycle through all the rules and check if the given variable name
+% (species or parameter or compartment) appears as left hand side (LHS) in a rule
+%
+% numberRulesVariable: number of rules the name appears in as LHS
+% lastRuleIndex: the index of the rule the name was last detected
+% lastRuleType: 'scalar' or 'rate'
+% lastRuleFormula: the RHS expression for the variable
+%
+% We assume that the name of the variable can appear in the
+% 'variable' field, in the 'species' field, in the 'compartment' field,
+% or in the 'name' field of the 'rule' field. 
+% Some SBML example models had species in the 'variable' field!
+%
+function [numberRulesVariable,lastRuleIndex,lastRuleType,lastRuleFormula,errorMsg] = getRules(variableName,SBMLmodel,errorMsg)
+% Initialize return values
+numberRulesVariable = 0;
+lastRuleIndex = [];
+lastRuleType = '';
+lastRuleFormula = '';
+for k = 1:length(SBMLmodel.rule),
+    % DO NOT PROCESS ALGEBRAIC RULES HERE ... WE DO THAT AT A DIFFERENT PLACE
+    if isempty(strfind(SBMLmodel.rule(k).typecode,'ALGEBRAIC')),
+        if strcmp(variableName,SBMLmodel.rule(k).variable) || strcmp(variableName,SBMLmodel.rule(k).species) || strcmp(variableName,SBMLmodel.rule(k).name) || strcmp(variableName,SBMLmodel.rule(k).compartment),
+            % The name was found as LHS in a rule
+            numberRulesVariable = numberRulesVariable+1;
+            lastRuleIndex = k;
+            if isempty(strfind(SBMLmodel.rule(k).typecode,'RATE')),
+                % Rule is a scalar rule
+                lastRuleType = 'scalar';
+            else
+                % Rule is a rate rule
+                lastRuleType = 'rate';
+            end
+            % get the RHS expression of the rule
+            lastRuleFormula = SBMLmodel.rule(k).formula;
+        end
+    end
+end
+% replace MathML expressions against MATLAB expressions
+[lastRuleFormula] = replaceMathMLexpressions(lastRuleFormula);
+% return
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF A CERTAIN SPECIES APPEARS AS PRODUCT AND/OR REACTANT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% In the case that a non-boundary species is defined by a rule
+% we need to check if it is also present as product or reactant in any
+% reaction. In this case the SBML model is not correctly defined and
+% reactionSpeciesPresent = 1
+function [reactionSpeciesPresent] = checkReactionsForSpecies(speciesName,SBMLmodel)
+% Initialize return value
+reactionSpeciesPresent = 0;
+reactionComponents = {};
+for k = 1:length(SBMLmodel.reaction),
+    reactionComponents = {reactionComponents{:},SBMLmodel.reaction(k).reactant.species,SBMLmodel.reaction(k).product.species};
+end
+if ~isempty(strmatchSB(speciesName,reactionComponents,'exact')),
+    reactionSpeciesPresent = 1;
+end
+return
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DELETE WHITESPACES IN STRINGS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Useful for taking away whitespaces in kineticLaw formulas, as
+% seen in some example models
+function [outputString] = removeWhiteSpace(inputString)
+outputString = strrep(inputString,' ','');
+% return
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET COMPARTMENT NAME FOR SPECIES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [compartmentName] = getCompartmentNameSpecies(species,SBMLmodel)
+compartmentName = SBMLmodel.species(strmatchSB(species,{SBMLmodel.species.id},'exact')).compartment;
+% return
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXCHANGE STRING IN STRING - WITH CHECK OF ALLOWED CHARACTERS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% find occurrences of stringOld in fullString and exchange it with
+% stringNew. 
+function [processedString] = exchangeStringInString(fullString,stringOld,stringNew);
+% really simple!!!
+exprString = char([double('\<') double(stringOld) double('\>')]);
+processedString = regexprep(fullString, exprString, stringNew);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXCHANGE MATHML FUNCTION NAMES IN ALL FORMULAS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% MathML functions can have different names than MATLAB function names
+% we need to exchange them in the formula strings. The term 'MathML
+% expression' relates to what is returned by TranslateSBML!
+function [newFormula] = replaceMathMLexpressions(formula)
+% MathML expressions that need simple exchange with corresponding MATLAB
+% expressions:
+MathMLexpressions = {'\<delay\>','\<piecewise\>','\<and\>','\<or\>','\<arccos\>','\<arcsin\>','\<arctan\>','\<ceiling\>','\<ln\>',...
+    '\<pow\>','\<arccos\>','\<arccosh\>','\<arccot\>','\<arccoth\>','\<arccsc\>','\<arccsch\>',...
+    '\<arcsec\>','\<arcsech\>','\<arcsin\>','\<arcsinh\>','\<arctan\>','\<arctanh\>',...
+    '\<exponentiale','\<geq\>','\<leq\>','\<xor\>','\<multiply\>'};
+MATLABexpressions = {'delaySB','piecewiseSB','andSB','orSB','acos','asin','atan','ceil','log', ...
+    'power','acos','acosh','acot','acoth','acsc','acsch',...
+    'asec','asech','asin','asinh','atan','atanh'...
+    'exp(1)','ge','le','xorSB','multiplySB'};
+% find indices
+newFormula = regexprep(formula,MathMLexpressions,MATLABexpressions);
+% replace the time_symbol with 'time' if a time_symbol is defined and not
+% 'time'.
+newFormula = exchangeTimeSymbol(newFormula);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% exchange time symbol if needed
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [expression] = exchangeTimeSymbol(expression)
+global SBMLtimesymbol
+if ~isempty(SBMLtimesymbol) && ~strcmp(SBMLtimesymbol,'time'),
+    expression = regexprep(expression,strcat('\<',SBMLtimesymbol,'\>'),'time');
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% regexprep command doing the replacement
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [formula] = exchangepowerexp(formula)
+global changeFlag
+oldformula = formula;
+formula = regexprep(['#' formula],'([\W]+)',' $1 ');
+formula = regexprep(formula,'[\s]power[\s]*\(([^,]+),([^,]+)\)','($1)^($2)');
+formula = regexprep(formula,'\s','');
+formula = formula(2:end);
+if ~strcmp(oldformula,formula),
+    changeFlag = 1;
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBexportSBMLcheckSBmodel.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBexportSBMLcheckSBmodel.m
new file mode 100644
index 0000000000000000000000000000000000000000..2c99f852d3722cfcf6f9f6c3eaa0ce2fd08479f8
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBexportSBMLcheckSBmodel.m
@@ -0,0 +1,157 @@
+function [] = SBexportSBMLcheckSBmodel(sbm)
+% SBexportSBMLcheckSBmodel
+% Special function for the SBML export of models. The function checks if
+% the SBmodel fields "type", "compartment", and "unittype" are all set.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+
+errorMessage = '';
+
+% get a list of all compartments defined in the species and by
+% isCompartment
+compartmentListSpecies = {};
+compartmentDefinitionList = {};
+for k=1:length(sbm.states),
+    if ~isempty(sbm.states(k).compartment),
+        compartmentListSpecies{end+1} = sbm.states(k).compartment;
+    end
+    if strcmp(sbm.states(k).type,'isCompartment'),
+        compartmentDefinitionList{end+1} = sbm.states(k).name;
+    end
+end
+for k=1:length(sbm.parameters),
+    if ~isempty(sbm.parameters(k).compartment),
+        compartmentListSpecies{end+1} = sbm.parameters(k).compartment;
+    end
+    if strcmp(sbm.parameters(k).type,'isCompartment'),
+        compartmentDefinitionList{end+1} = sbm.parameters(k).name;
+    end
+end
+for k=1:length(sbm.variables),
+    if ~isempty(sbm.variables(k).compartment),
+        compartmentListSpecies{end+1} = sbm.variables(k).compartment;
+    end
+    if strcmp(sbm.variables(k).type,'isCompartment'),
+        compartmentDefinitionList{end+1} = sbm.variables(k).name;
+    end
+end
+compartmentListSpecies = unique(compartmentListSpecies);
+compartmentDefinitionList = unique(compartmentDefinitionList);
+wrongCompartments = union(setdiff(compartmentDefinitionList,compartmentListSpecies),setdiff(compartmentListSpecies,compartmentDefinitionList));
+% wrongCompartments might contain 'default' but thats ok
+if ~(length(wrongCompartments) == 1 && strcmp(wrongCompartments{1},'default'))
+    for k = 1:length(wrongCompartments),
+        errorMessage = sprintf('%sWrongly defined compartment ''%s'' (either ''isCompartment'' missing\n    or compartment defined but no species in it.\n',errorMessage,wrongCompartments{k});
+    end
+end
+compartmentList = compartmentDefinitionList;
+
+% cycle through the SBmodel structure and check the type, unittype, and
+% compartment field
+% states 
+for k=1:length(sbm.states),
+    typeResult = checkType(sbm.states(k).type);
+    if isempty(typeResult),
+        errorMessage = sprintf('%sUndefined ''type'' field for state ''%s''.\n',errorMessage,sbm.states(k).name);
+    end
+    compartmentResult = checkCompartment(sbm.states(k).compartment, compartmentList, typeResult);
+    if isempty(compartmentResult),
+        errorMessage = sprintf('%sWrongly defined ''compartment'' field for state ''%s''.\n',errorMessage,sbm.states(k).name);
+    end
+    unittypeResult = checkUnittype(sbm.states(k).unittype, typeResult);
+    if isempty(unittypeResult),
+        errorMessage = sprintf('%sWrongly defined ''unittype'' field for state ''%s''.\n',errorMessage,sbm.states(k).name);
+    end   
+end
+
+% parameters
+for k=1:length(sbm.parameters),
+    typeResult = checkType(sbm.parameters(k).type);
+    if isempty(typeResult),
+        errorMessage = sprintf('%sUndefined ''type'' field for parameter ''%s''.\n',errorMessage,sbm.parameters(k).name);
+    end
+    compartmentResult = checkCompartment(sbm.parameters(k).compartment, compartmentList, typeResult);
+    if isempty(compartmentResult),
+        errorMessage = sprintf('%sWrongly defined ''compartment'' field for parameter ''%s''.\n',errorMessage,sbm.parameters(k).name);
+    end
+    unittypeResult = checkUnittype(sbm.parameters(k).unittype, typeResult);
+    if isempty(unittypeResult),
+        errorMessage = sprintf('%sWrongly defined ''unittype'' field for parameter ''%s''.\n',errorMessage,sbm.parameters(k).name);
+    end   
+end
+
+% variables
+for k=1:length(sbm.variables),
+    typeResult = checkType(sbm.variables(k).type);
+    if isempty(typeResult),
+        errorMessage = sprintf('%sUndefined ''type'' field for variable ''%s''.\n',errorMessage,sbm.variables(k).name);
+    end
+    compartmentResult = checkCompartment(sbm.variables(k).compartment, compartmentList, typeResult);
+    if isempty(compartmentResult),
+        errorMessage = sprintf('%sWrongly defined ''compartment'' field for variable ''%s''.\n',errorMessage,sbm.variables(k).name);
+    end
+    unittypeResult = checkUnittype(sbm.variables(k).unittype, typeResult);
+    if isempty(unittypeResult),
+        errorMessage = sprintf('%sWrongly defined ''unittype'' field for variable ''%s''.\n',errorMessage,sbm.variables(k).name);
+    end   
+end
+
+% error message
+if ~isempty(errorMessage),
+    errorMessage = sprintf('%s\nFor information on how to correctly define an SBmodel prior to SBML export,\nplease type: >> help SBexportSBML\n',errorMessage);
+    error(errorMessage);
+end
+return
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Help function for type
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [result] = checkType(type),
+result = strmatchSB(type,{'isSpecie','isParameter','isCompartment'},'exact');
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Help function for compartment
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [result] = checkCompartment(compartment, compartmentList, typeResult),
+    result = 1;
+    if typeResult == 1,
+        % type = isSpecie: check if compartment in compartment List
+        result = strmatchSB(compartment, compartmentList, 'exact');
+    end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Help function for unittype
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [result] = checkUnittype(unittype, typeResult),
+    result = 1;
+    if typeResult == 1,
+        % type = isSpecie: check if 'concentration' or 'amount'
+        result = strmatchSB(unittype, {'concentration','amount'}, 'exact');
+    end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBimportSBML.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBimportSBML.m
new file mode 100644
index 0000000000000000000000000000000000000000..39c18ca41c9baa45810f7f1479d23a1cc38c13bc
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBimportSBML.m
@@ -0,0 +1,68 @@
+function [SBstructure,errorMsg] = SBimportSBML(SBMLmodelFile)
+% SBimportSBML 
+% imports a SBML model using the TranslateSBML function from libSBML
+% Supported SBML levels: 1 and 2
+%
+% SBMLmodelFile: SBMLmodelfilename.xml (string)
+%
+% SBstructure: empty if error occurred
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+academicWarningSB
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INITIALIZATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+errorMsg = '';
+SBstructure = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SBML -> MATLAB
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Use the TranslateSBML function from libSBML
+try
+    SBMLmodel = TranslateSBML(SBMLmodelFile);
+catch
+    errTxt = sprintf('An error during the SBML import using the SBML Toolbox occurred.\nThis might be due to the fact that you have an outdated installation\nof the SBML Toolbox. Please have a look at www.sbtoolbox2.org for which\nversion of the SBML Toolbox is required.\n\nLast error message:\n\n%s',lasterr);
+    error(errTxt);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONVERT INTO OWN SB STRUCTURE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~strcmp(SBMLmodel.typecode,'SBML_MODEL'),
+    errorMsg = 'Model is not an SBML model';
+    return;
+end
+if SBMLmodel.SBML_level == 1,
+    % Convert level 1
+    [SBstructure,errorMsg] = SBconvertSBML1(SBMLmodel);
+elseif SBMLmodel.SBML_level == 2 && SBMLmodel.SBML_version == 1,
+    % Convert level 2
+    [SBstructure,errorMsg] = SBconvertSBML2(SBMLmodel);
+else
+    % Not supported SBML level
+    errorMsg = sprintf('Level %d Version %d of SBML not yet implemented',SBMLmodel.SBML_level,SBMLmodel.SBML_version);
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBimportSBMLCD.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBimportSBMLCD.m
new file mode 100644
index 0000000000000000000000000000000000000000..577fed2ce2cdc48521d34c4d1d0d31b96e150af3
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/SBimportSBMLCD.m
@@ -0,0 +1,68 @@
+function [SBstructure,errorMsg] = SBimportSBMLCD(SBMLmodelFile)
+% SBimportSBMLCD 
+% Special function for the import of CellDesigner models. Does conversion 
+% of names to ids. Supported SBML level: 2
+%
+% SBMLmodelFile: SBMLmodelfilename.xml (string)
+%
+% SBstructure: empty if error occurred
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+academicWarningSB
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INITIALIZATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+errorMsg = '';
+SBstructure = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SBML -> MATLAB
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Use the TranslateSBML function from libSBML
+try
+    SBMLmodel = TranslateSBML(SBMLmodelFile);
+catch
+    errTxt = sprintf('An error during the SBML import using the SBML Toolbox occurred.\nThis might be due to the fact that you have an outdated installation\nof the SBML Toolbox. Please have a look at www.sbtoolbox2.org for which\nversion of the SBML Toolbox is required.\n\nLast error message:\n\n%s',lasterr);
+    error(errTxt);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONVERT INTO OWN SB STRUCTURE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~strcmp(SBMLmodel.typecode,'SBML_MODEL'),
+    error('Model is not a SBML model');
+    return;
+end
+if SBMLmodel.SBML_level == 2 && SBMLmodel.SBML_version == 1,
+    % Convert names to ids
+    SBMLmodel = SBconvertName2Id(SBMLmodel);
+    % Convert SBMl model to SBmodel structure
+    [SBstructure,errorMsg] = SBconvertSBML2(SBMLmodel);
+    
+else
+    % Not supported SBML level
+    error('The flag for the SBmodel function can only be used for SBML Level 2 Version 1 models.');
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/convert2SBNotes.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/convert2SBNotes.m
new file mode 100644
index 0000000000000000000000000000000000000000..8d1f83518a6a723fa004394808aaf436227477bf
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/classeshandling/modelhandling/methods/auxiliary/convert2SBNotes.m
@@ -0,0 +1,52 @@
+function [SBNotes] = convert2SBNotes(SBMLmodelNotes,flag)
+% convert2SBNotes
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+SBNotes = regexprep(SBMLmodelNotes,'<html xmlns="http://www.w3.org/1999/xhtml">','');
+SBNotes = regexprep(SBNotes,'</html>','');
+SBNotes = regexprep(SBNotes,'<body xmlns="http://www.w3.org/1999/xhtml">','');
+SBNotes = regexprep(SBNotes,'<body>','');
+SBNotes = regexprep(SBNotes,'</body>','');
+SBNotes = regexprep(SBNotes,'<p>','');
+SBNotes = regexprep(SBNotes,'<p/>','');
+SBNotes = regexprep(SBNotes,'</p>','');
+SBNotes = regexprep(SBNotes,'<br>','');
+SBNotes = regexprep(SBNotes,'<br/>','');
+SBNotes = regexprep(SBNotes,'</br>','');
+SBNotes = regexprep(SBNotes,'<h1>','');
+SBNotes = regexprep(SBNotes,'</h1>','');
+SBNotes = regexprep(SBNotes,'<h2>','');
+SBNotes = regexprep(SBNotes,'</h2>','');
+SBNotes = regexprep(SBNotes,'<h3>','');
+SBNotes = regexprep(SBNotes,'</h3>','');
+SBNotes = regexprep(SBNotes,'<notes>','');
+SBNotes = regexprep(SBNotes,'</notes>','');
+SBNotes = regexprep(SBNotes,'<p xmlns="http://www.w3.org/1999/xhtml">','');
+SBNotes = regexprep(SBNotes,'<br xmlns="http://www.w3.org/1999/xhtml">','');
+SBNotes = regexprep(SBNotes,'=','');
+if flag,
+    SBNotes = regexprep(SBNotes,'\n','');
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/behaviorlocalization/SBlocbehavcomp.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/behaviorlocalization/SBlocbehavcomp.m
new file mode 100644
index 0000000000000000000000000000000000000000..0fc58c38d85daa42085a4152fb83740929833e07
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/behaviorlocalization/SBlocbehavcomp.m
@@ -0,0 +1,402 @@
+function [varargout] = SBlocbehavcomp(varargin)
+% SBlocbehavcomp: Determines the importance of components in the
+% given biochemical system in the creation of an observed complex behavior,
+% such as multiple steady-states and sustained oscillations. Read below to
+% get more insight into the method.
+% 
+% Important: the analyzed model needs to be time-invariant, unstable, and 
+% non-singular. The last two are checked prior to performing the analysis
+% and a descriptive error message is returned.
+% If the model is not time-invariant some MATLAB error message will appear.
+%
+% THE METHOD
+% ==========
+% Central functions in the cell are often linked to complex dynamic 
+% behaviors, such as sustained oscillations and multistability, in a 
+% biochemical reaction network. Determination of the specific mechanisms 
+% underlying such behaviors is important, e.g., to determine sensitivity, 
+% robustness, and modelling requirements of given cell functions. 
+% 
+% The aim of the "SBlocbehavcomp" function is to identify the 
+% components (states) in a biochemical reaction network, described by a set of 
+% ordinary differential equations, that are mainly involved in creating an
+% observed complex dynamic behavior, such as sustained oscillations or 
+% multiple steady-states. 
+% 
+% Rather than analyzing the biochemical system in a state corresponding to 
+% the complex nonlinear behavior, the system is considered at its 
+% underlying unstable steady-state. This is motivated by the fact that all 
+% complex behaviors in unforced systems can be traced to destabilization 
+% (bifurcation) of some steady-state, and hence enables the use of tools 
+% from Linear System Theory to qualitatively analyze the sources of given 
+% network behaviors.
+% 
+% A full description of this method can be found in 
+% "Linear systems approach to analysis of complex dynamic behaviours 
+% in biochemical networks", IEE Systems Biology, 1, 149-158 (2004) and
+% "Identifying feedback mechanisms behind complex cell behavior", IEEE
+% Control Systems Magazine, 24 (4), 91-102 (2004)
+%
+% USAGE
+% =====
+% [] = SBlocbehavcomp(sbm, steadystate)  
+% [] = SBlocbehavcomp(sbm, steadystate, OPTIONS)  
+% [importance, stateNames] = SBlocbehavcomp(sbm, steadystate)  
+% [importance, stateNames] = SBlocbehavcomp(sbm, steadystate, OPTIONS)  
+%
+% sbm: SBmodel or ODE file to perform the analysis on
+% steadystate: steady-state at which to perform the analysis
+% OPTIONS: structure containing options
+%          OPTIONS.orderDataFlag: =0: non ordered data, =1: ordered data after
+%               importance (only used for plotting purpose)
+%          OPTIONS.plotTypeFlag: =0: linear y-axis, =1: logarithmic y-axis
+%          OPTIONS.minEpsilonValue, OPTIONS.maxEspilonValue: Definition of
+%                  the range of values for checking the epsilons.
+%               [-maxEspilonValue ... -minEpsilonValue ... minEpsilonValue ... maxEpsilonValue] 
+%          OPTIONS.nrPoints: number of points in the range above.
+%
+% DEFAULT VALUES:
+% ===============
+% OPTIONS.orderDataFlag: 0
+% OPTIONS.plotTypeFlag: 0
+% OPTIONS.minEpsilonValue: 0.0001
+% OPTIONS.maxEspilonValue: 1000
+% OPTIONS.nrPoints: 5000
+%
+% Output Arguments:
+% =================
+% If no output arguments are given, the result of the analysis is plotted. 
+% The importances are color-coded. Blue color is used for positive
+% importances, red color for negative importances that are smaller than
+% -1, and black color for negative importances that are between 0 and -1.
+% Since the determined epsilon perturbations are relative perturbations and
+% therefor values for epsilon < -1 (0 > importances > -1) lead to a change
+% of sign in the corresponding feedback loop, the two different colors for
+% negative importances are used to distinguish these two cases.
+%
+% importance and stateNames: to the i-th component (state) name corresponds
+%       the i-th importance value, defined by importance_i = 1/epsilon_i,
+%       where epsilon_i is the relative change in the feedback
+%       interconnection in the i-th  state (stateNames{i}) that
+%       stabilizes the considered unstable steady-state. The smaller the
+%       absolute value of the required perturbation, this means, the larger
+%       importance_i, the more important role plays state i in the
+%       creation of the observed complex behavior. In case the stabilizing
+%       value of epsilon_i has a magnitude larger than maxEpsilonValue,
+%       zero is returned for the corresponding importance.
+
+% Information:
+% ============
+% Copyright (C) 2003-2004 Henning Schmidt, henning@hschmidt.de
+% Adapted for the SBTOOLBOX by Henning Schmidt, March 2005
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+academicWarningSB
+
+
+global minEpsilonValue maxEpsilonValue nrPoints
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF SBMODEL OR FILENAME
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isSBmodel(varargin{1}),
+    % SBmodel
+    sbm = varargin{1};
+    % check delays and events
+    if usedelaySB(sbm),
+        error('The model contains delays. These can not be handled by this function.');
+    end
+    if useeventSB(sbm),
+        error('The model contains events. These can not be handled by this function.');
+    end    
+    % Create temporary ODE file
+    [ODEfctname, ODEfilefullpath] = SBcreateTempODEfile(sbm);    
+else
+    % ODEfctname of ODE file
+    ODEfctname = varargin{1};
+    % Check if file exists
+    if exist(strcat(ODEfctname,'.m')) ~= 2,
+        error('ODE file could not be found.');
+    end
+end
+
+% Default values
+orderDataFlag   = 0;
+plotTypeFlag    = 0;
+minEpsilonValue = 0.0001;
+maxEpsilonValue = 1000;
+nrPoints        = 5000;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 2,
+    steadystate = varargin{2};
+elseif nargin == 3,
+    steadystate = varargin{2};
+    % get options for analysis method
+    OPTIONS = varargin{3};
+    % handle the options
+    % orderDataFlag
+    if isfield(OPTIONS,'orderDataFlag'),
+        if ~isempty(OPTIONS.orderDataFlag),
+            orderDataFlag = OPTIONS.orderDataFlag;
+        end
+    end
+    % plotTypeFlag
+    if isfield(OPTIONS,'plotTypeFlag'),
+        if ~isempty(OPTIONS.plotTypeFlag),
+            plotTypeFlag = OPTIONS.plotTypeFlag;
+        end
+    end
+    % minEpsilonValue
+    if isfield(OPTIONS,'minEpsilonValue'),
+        if ~isempty(OPTIONS.minEpsilonValue),
+            minEpsilonValue = OPTIONS.minEpsilonValue;
+        end
+    end
+    % maxEspilonValue
+    if isfield(OPTIONS,'maxEpsilonValue'),
+        if ~isempty(OPTIONS.maxEpsilonValue),
+            maxEpsilonValue = OPTIONS.maxEpsilonValue;
+        end
+    end
+    % nrPoints
+    if isfield(OPTIONS,'nrPoints'),
+        if ~isempty(OPTIONS.nrPoints),
+            nrPoints = OPTIONS.nrPoints;
+        end
+    end
+else
+    error('Incorrect number of input arguments.');
+end
+
+% check that the maxEpsilonValue is larger than the minEpsilonValue
+if minEpsilonValue >= maxEpsilonValue,
+    error('The max epsilon value in the options should be larger than the min epsilon value!');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK CORRECT NUMBER OF OUTPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargout ~= 0 && nargout ~= 2,
+    error('Incorrect number of output arguments');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF MODEL IS UNSTABLE AND NON SINGULAR
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% check eigenvalues for instability
+Jacobian = SBjacobian(ODEfctname,steadystate);
+if max(real(eig(Jacobian))) < 0,
+    error(sprintf('The ODEfctname is stable - this analysis function only works with unstable models.\nIn case you are looking at a system having multiple steady-states\nyou need to specify a starting guess for the steady-state very close to the unstable steady-state.'));
+end
+% check non singularity
+Jacobian = SBjacobian(ODEfctname,rand*ones(length(steadystate)));
+if rank(Jacobian) < length(Jacobian),
+    error(sprintf('The ODEfctname is singular. This function only works with non-singular models.\nYou might consider the use of ''SBreducemodel''.'));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HERE COMES THE MAIN ANALYSIS PART
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+epsilon_i = analyzeImportantStates(ODEfctname, steadystate);
+% convert epsilon_i to importance_i
+importance = 1./epsilon_i;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABLE OUTPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargout == 0,
+    plotResults(importance, ODEfctname, plotTypeFlag, orderDataFlag);
+elseif nargout == 2,
+    varargout{1} = importance;
+    varargout{2} = SBstates(ODEfctname);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DELETE FILE IF SBMODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp('SBmodel',class(varargin{1})),
+    deleteTempODEfileSB(ODEfilefullpath);
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Implementation of the method described in 
+% "Identifying mechanisms underlying complex behaviors in biochemical 
+% reaction networks", IEE Systems Biology, 1, 149-158 (2004) and
+% "Identifying feedback mechanisms behind complex cell behavior", IEEE
+% Control Systems Magazine, 24 (4), 91-102 (2004)
+%
+% for the determination of important states in biochemical networks,
+% that are the source of an observed complex behavior.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [epsilon_i] = analyzeImportantStates(ODEfctname, steadystate)
+global minEpsilonValue maxEpsilonValue nrPoints
+% determine the Jacobian
+A = SBjacobian(ODEfctname,steadystate);
+n = length(A); I = eye(n);
+% check that the maxEpsilonValue is larger than the minEpsilonValue
+if minEpsilonValue >= maxEpsilonValue,
+    error('The max epsilon value in the options should be larger than the min epsilon value!');
+end
+% Instead of using the approach, proposed in the above mentioned articles,
+% here a simpler method is used to determine the sensitivity of the systems
+% stability to variations in the different feedback connections. This
+% method is based on perturbing directly the Jacobian of the system, at the
+% considered unstable steady-state. The feedback of component (state) number i on itself 
+% is not perturbed, only the feedback of state i on all other states,
+% corresponding to perturbations only on the interactions in the network.
+%
+% cycle through all the states and check values between minEpsilonValue and
+% maxEpsilonValue
+epsilonRange = logspace(log(minEpsilonValue)/log(10),log(maxEpsilonValue)/log(10),floor(nrPoints/2));
+epsilon_i = [];  % array to collect the epsilon_i values for the different states
+for i = 1:n,
+    % search first from zero to positive epsilon values
+    epsilon_i_temp = inf; % initialize value with maximum 
+    for j = 1:length(epsilonRange),
+        epsilon = epsilonRange(j);
+        % determine the perturbed Jacobian Ahat
+        Ahat = A; Ahat(:,i) = Ahat(:,i)*(1+epsilon); Ahat(i,i) = A(i,i);
+        % determine the max real part of the eigenvalues of the perturbed Jacobian
+        if max(real(eig(Ahat))) <= 0,
+            % since the nominal Jacobian (epsilon_i = 0) is unstable,
+            % a maximum negative realpart indicates that the system has
+            % been stabilized and the smallest positive epsilon_i value has
+            % been found. this value is now given by the "epsilon" variable
+            % break the loop and search in negative direction
+            epsilon_i_temp = epsilon;
+            break; 
+        end
+    end
+    % now search from zero to negative epsilon values
+    for j = 1:length(epsilonRange),
+        epsilon = -epsilonRange(j);
+        % check if current epsilon has magnitude larger than previously
+        % found (epsilon_i_tem). if yes then break the loop and take
+        % previously found as epsilon_i
+        if abs(epsilon) > abs(epsilon_i_temp),
+            break;
+        end
+        % otherwise continue with search        
+        % determine the perturbed Jacobian Ahat
+        Ahat = A; Ahat(:,i) = Ahat(:,i)*(1+epsilon); Ahat(i,i) = A(i,i);
+        % determine the max real part of the eigenvalues of the perturbed Jacobian
+        if max(real(eig(Ahat))) <= 0,
+            % since the nominal Jacobian (epsilon_i = 0) is unstable,
+            % a maximum negative realpart indicates that the system has
+            % been stabilized and the smallest positive epsilon_i value has
+            % been found.
+            epsilon_i_temp = epsilon;
+            break; % break the loop and search in negative direction
+        end
+    end
+    % save the determined epsilon_i value for the i-th state 
+    epsilon_i = [epsilon_i epsilon_i_temp];
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Plot the analysis results
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [] = plotResults(importance, ODEfctname, plotTypeFlag, orderDataFlag)
+% getting the names of the states in the network
+stateNames = SBstates(ODEfctname);
+n = length(importance);
+% ordering the data after decreasing importance (if orderDataFlag = 1)
+if orderDataFlag == 1,
+    data = [abs(importance(:)), importance(:), [1:length(stateNames)]'];
+    data = sortrows(data,-1);
+    % get reordered data
+    importance = data(:,2);
+    % reorder the parameters
+    stateNamesOrdered = cell(1,length(stateNames));
+    neworder = data(:,3);
+    for k = 1:length(stateNames),
+        stateNamesOrdered{k} = stateNames{neworder(k)};
+    end
+    stateNames = stateNamesOrdered;
+else
+    neworder = [1:n];
+end
+figH = figure; clf;
+axesH = gca(figH);
+% plot importances - different colors for:
+% blue: positive stabilizing perturbations (epsilon)
+% red: negative stabilizing perturbations (epsilon > -1 => no sign change)
+% black:  negative stabilizing perturbations (epsilon < -1 => sign change)
+if plotTypeFlag == 0,
+    for k = 1:n,
+        if importance(k) >= 0,
+            bar(k,importance(k),'b'); hold on;
+        elseif importance(k) < 0 && importance(k) >= -1,
+            bar(k,-importance(k),'k'); hold on;
+        else    
+            bar(k,-importance(k),'r'); hold on;
+        end
+    end
+else
+    for k = 1:n,
+        if importance(k) >= 0,
+            handle = plot(k,importance(k),'ob'); hold on;
+            set(handle,'LineWidth',2);
+            set(handle,'MarkerFaceColor','b');            
+        elseif importance(k) < 0 && importance(k) >= -1,
+            handle = plot(k,-importance(k),'ok'); hold on;
+            set(handle,'LineWidth',2);
+            set(handle,'MarkerFaceColor','k');            
+        else    
+            handle = plot(k,-importance(k),'or'); hold on;
+            set(handle,'LineWidth',2);
+            set(handle,'MarkerFaceColor','r');            
+        end
+    end
+end    
+absImportance = abs(importance);
+yMax = 1.5*max(absImportance);
+if plotTypeFlag,
+    % min value in case of semilogy plot
+    help = sort(absImportance)';
+    help = help(find(help>0))';
+    yMin = 0.75*help(1);
+else
+    % min value to zero in case of linear plot
+    yMin = 0;
+end
+axis([0 n+1 yMin yMax]);
+set(axesH,'XTick',[1:n]);
+set(axesH,'XTickLabel',neworder);
+if plotTypeFlag == 1,
+    set(axesH,'YScale','log');
+    text([1:n]-0.4,1.4*absImportance,stateNames);
+else
+    set(axesH,'YScale','linear');
+    text([1:n]-0.4,0.02*(yMax-yMin)+absImportance,stateNames);
+end
+% plot bar at 1
+hold on
+plot([0 n+1],[1 1],'k--');
+
+% writing the axis descriptions
+xlabel('States (components) in biochemical network');
+ylabel('Importance for considered behavior (1/| \epsilon-value|)');
+return
+
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/behaviorlocalization/SBlocbehavinteract.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/behaviorlocalization/SBlocbehavinteract.m
new file mode 100644
index 0000000000000000000000000000000000000000..4e2ccac2eaf6380f00730ded7ab214bc0f4e6122
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/behaviorlocalization/SBlocbehavinteract.m
@@ -0,0 +1,668 @@
+function [varargout] = SBlocbehavinteract(varargin)
+% SBlocbehavinteract: Determines the importance of direct interactions 
+% (e.g., reactions) between components (states) in the given biochemical
+% system in the creation of an observed complex behavior, such as multiple 
+% steady-states and sustained oscillations. Read below to get more insight 
+% into the method.
+% 
+% Important: the analyzed model needs to be time-invariant, unstable, and 
+% non-singular. The last two are checked prior to performing the analysis
+% and a descriptive error message is returned.
+% If the model is not time-invariant some MATLAB error message will appear.
+%
+% THE METHOD
+% ==========
+% Central functions in the cell are often linked to complex dynamic 
+% behaviors, such as sustained oscillations and multistability, in a 
+% biochemical reaction network. Determination of the specific mechanisms 
+% underlying such behaviors is important, e.g., to determine sensitivity, 
+% robustness, and modelling requirements of given cell functions. 
+% 
+% The aim of the "SBlocbehavinteract" function is to identify the mechanism
+% in a biochemical reaction network, described by a set of ordinary 
+% differential equations, that are mainly involved in creating an observed 
+% complex dynamic behavior, such as sustained oscillations or multiple 
+% steady-states. 
+% 
+% Rather than analyzing the biochemical system in a state corresponding to 
+% the complex nonlinear behavior, the system is considered at its 
+% underlying unstable steady-state. This is motivated by the fact that all 
+% complex behaviors in unforced systems can be traced to destabilization 
+% (bifurcation) of some steady-state, and hence enables the use of tools 
+% from Linear System Theory to qualitatively analyze the sources of given 
+% network behaviors.
+% 
+% A full description of this method can be found in 
+% "Linear systems approach to analysis of complex dynamic behaviours 
+% in biochemical networks", IEE Systems Biology, 1, 149-158 (2004) and
+% "Identifying feedback mechanisms behind complex cell behavior", IEEE
+% Control Systems Magazine, 24 (4), 91-102 (2004)
+%
+% USAGE
+% =====
+% [] = SBlocbehavinteract(sbm, steadystate)  
+% [] = SBlocbehavinteract(sbm, steadystate, OPTIONS)  
+% [importance,stateNames] = SBlocbehavinteract(sbm, steadystate)  
+% [importance,stateNames] = SBlocbehavinteract(sbm, steadystate, OPTIONS)  
+%
+% sbm: SBmodel or ODE file to perform the analysis on
+% steadystate: steady-state at which to perform the analysis
+% OPTIONS: structure containing options
+%          OPTIONS.plotTypeFlag: =0: linear y-axis, =1: logarithmic y-axis
+%          OPTIONS.visualizeFlag: =0: nothing, =1: setting this flag to 1 allows to monitor the
+%                   continuation of the critical locus and to see if the 
+%                   values for criticalLocusTolerance and criticalLocusNrPoints
+%                   are set acceptably.
+%          OPTIONS.omegaRange: to determine the critical frequency omega0 the function
+%                   searches in a range from omega_star/omegaRange ...
+%                   omega_star*omegaRange, where omega_star is the positive
+%                   imaginary part of the unstable pole in the linearized
+%                   system.
+%          OPTIONS.omegaRangePoints: the above range is discretized in so many steps,
+%                   allowing to find a lower and upper bound for omega0
+%          OPTIONS.bisectionThreshold: omega0 is then determined by bisection until
+%                   the bounds have a distance less than this option value
+%          OPTIONS.criticalLocusTolerance: each determined perturbation Delta_ij is
+%                   checked if it is stabilizing. This is done by
+%                   continuation. If the final value of the critical locus
+%                   is less than this option away from +1 it is a
+%                   stabilizing perturbation.
+%          OPTIONS.criticalLocusNrPoints: the number of points used for the
+%                   continuation of the critical locus (larger=>slower,
+%                   more exact, smaller => faster, eventually problems)
+% 
+% DEFAULT VALUES:
+% ===============
+% OPTIONS.plotTypeFlag: 0
+% OPTIONS.visualizeFlag: 0
+% OPTIONS.omegaRange: 10
+% OPTIONS.omegaRangePoints: 50
+% OPTIONS.bisectionThreshold: 1e-14
+% OPTIONS.criticalLocusTolerance: 1e-5
+% OPTIONS.criticalLocusNrPoints: 10
+%
+% Output Arguments:
+% =================
+% If no output arguments are given, the results of the analysis are plotted.
+% The result is color coded. Blue color corresponds to positive elements of
+% the corresponding nominal Jacobian, red color corresponds to negative elements.
+%
+% importance: each row corresponds to a direct interaction between states
+%       in the considered system. The first element in a row determines the
+%       index of the affected and the second the index of the affecting
+%       state. The third element in a row determines the inverse of the
+%       magnitude of the corresponding delta_ij value. delta_ij is the
+%       value for the relative perturbation in the direct interaction from
+%       state j to state i that stabilizes the considered steady-state.
+%       The larger this inverse is, the more important is the direct effect
+%       from state j on state i for the creation of the analyzed behavior.
+% stateNames: the name of the states corresponding to the numbering
+%       of columns and rows. 
+%
+% If no output arguments are given, the result is instead plotted.
+
+% Information:
+% ============
+% Copyright (C) 2003-2004 Henning Schmidt, henning@hschmidt.de
+% Adapted for the SBTOOLBOX by Henning Schmidt, March 2005
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+academicWarningSB
+
+
+global omegaRange omegaRangePoints bisectionThreshold criticalLocusTolerance criticalLocusNrPoints
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF SBMODEL OR FILENAME
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isSBmodel(varargin{1}),
+    % SBmodel
+    sbm = varargin{1};
+    % check delays and events
+    if usedelaySB(sbm),
+        error('The model contains delays. These can not be handled by this function.');
+    end
+    if useeventSB(sbm),
+        error('The model contains events. These can not be handled by this function.');
+    end       
+    % Create temporary ODE file
+    [ODEfctname, ODEfilefullpath] = SBcreateTempODEfile(sbm);    
+else
+    % ODEfctname of ODE file
+    ODEfctname = varargin{1};
+    % Check if file exists
+    if exist(strcat(ODEfctname,'.m')) ~= 2,
+        error('ODE file could not be found.');
+    end
+end
+
+% default values
+plotTypeFlag = 0;
+visualizeFlag = 0;
+omegaRange = 10;
+omegaRangePoints = 50;
+bisectionThreshold = 1e-14;
+criticalLocusTolerance = 1e-5;
+criticalLocusNrPoints = 10;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 2,
+    steadystate = varargin{2};
+elseif nargin == 3,
+    steadystate = varargin{2};
+    % get options for analysis method
+    OPTIONS = varargin{3};
+    % handle the options
+    % plotTypeFlag
+    if isfield(OPTIONS,'plotTypeFlag'),
+        if ~isempty(OPTIONS.plotTypeFlag),
+            plotTypeFlag = OPTIONS.plotTypeFlag;
+        end
+    end
+    % visualizeFlag
+    if isfield(OPTIONS,'visualizeFlag'),
+        if ~isempty(OPTIONS.visualizeFlag),
+            visualizeFlag = OPTIONS.visualizeFlag;
+        end
+    end
+    % omegaRange
+    if isfield(OPTIONS,'omegaRange'),
+        if ~isempty(OPTIONS.omegaRange),
+            omegaRange = OPTIONS.omegaRange;
+        end
+    end
+    % omegaRangePoints
+    if isfield(OPTIONS,'omegaRangePoints'),
+        if ~isempty(OPTIONS.omegaRangePoints),
+            omegaRangePoints = OPTIONS.omegaRangePoints;
+        end
+    end
+    % bisectionThreshold
+    if isfield(OPTIONS,'bisectionThreshold'),
+        if ~isempty(OPTIONS.bisectionThreshold),
+            bisectionThreshold = OPTIONS.bisectionThreshold;
+        end
+    end
+    % criticalLocusTolerance
+    if isfield(OPTIONS,'criticalLocusTolerance'),
+        if ~isempty(OPTIONS.criticalLocusTolerance),
+            criticalLocusTolerance = OPTIONS.criticalLocusTolerance;
+        end
+    end
+    % criticalLocusNrPoints
+    if isfield(OPTIONS,'criticalLocusNrPoints'),
+        if ~isempty(OPTIONS.criticalLocusNrPoints),
+            criticalLocusNrPoints = OPTIONS.criticalLocusNrPoints;
+        end
+    end
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK CORRECT NUMBER OF OUTPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargout ~= 0 && nargout ~= 2,
+    error('Incorrect number of output arguments');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF MODEL IS NON SINGULAR
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% check non singularity
+Jacobian = SBjacobian(ODEfctname,rand*ones(length(steadystate)));
+if rank(Jacobian) < length(Jacobian),
+    error(sprintf('The ODEfctname is singular. This function only works with non-singular models.\nYou might consider the use of ''SBreducemodel''.'));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HERE COMES THE MAIN ANALYSIS PART
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+result = analyzeImportantInteractions(ODEfctname, steadystate, visualizeFlag);
+% The first column in result contains the row number
+% The second column contains the column number
+% The third contains the magnitude of the required perturbation for stabilization
+%
+% Convert the required perturbations to importance measure by inverting them
+importance = result;
+importance(:,3) = 1./importance(:,3);
+stateNames = SBstates(ODEfctname);
+% take out importances below a certain limit
+minShowImportance = 1e-6*max(importance(:,3));
+indexTakeOutStart = find(importance(:,3)<minShowImportance);
+if ~isempty(indexTakeOutStart),
+    importance = importance(1:indexTakeOutStart(1)-1,:);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABLE OUTPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargout == 0,
+    plotResults(importance, ODEfctname, plotTypeFlag, steadystate);
+elseif nargout == 2,
+    varargout{1} = importance;
+    varargout{2} = stateNames;
+    % set acceptable format for output
+    format short g
+else 
+    error('Incorrect number of output arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DELETE FILE IF SBMODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp('SBmodel',class(varargin{1})),
+    deleteTempODEfileSB(ODEfilefullpath);
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Plot the results of the analysis
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [] = plotResults(importance, ODEfctname, plotTypeFlag, steadystate)
+% determine Jacobian at given steadystate (signs of elements needed for
+% choosing plot color)
+J = SBjacobian(ODEfctname,steadystate);
+% get number of rows in importance matrix
+n = size(importance,1);
+% open new figure
+figH = figure; clf; axesH = gca(figH);
+% plot the data - blue if Jacobian element positive, red if Jacobian
+% element negative
+if plotTypeFlag == 0,
+    for k = 1:n,
+        if J(importance(k,1),importance(k,2)) >= 0,
+            bar(k,importance(k,3),'b'); hold on;
+        else
+            bar(k,importance(k,3),'r'); hold on;
+        end
+    end    
+else
+    for k = 1:n,
+        if J(importance(k,1),importance(k,2)) >= 0,
+            handle = plot(k,importance(k,3),'ob'); hold on;
+            set(handle,'LineWidth',2);
+            set(handle,'MarkerFaceColor','b');            
+        else
+            handle = plot(k,importance(k,3),'or'); hold on;
+            set(handle,'LineWidth',2);
+            set(handle,'MarkerFaceColor','r');            
+        end
+    end
+end    
+% set y-axis properties
+yMax = 1.5*max(importance(:,3));
+if plotTypeFlag,
+    % min value in case of semilogy plot
+    help = sort(importance(:,3))';
+    help = help(find(help>0))';
+    yMin = 0.75*help(1);
+else
+    % min value to zero in case of linear plot
+    yMin = 0;
+end
+axis([0 n+1 yMin yMax]);
+set(axesH,'XTick',[]);
+% construct plot text and plot it
+importanceText = {};
+for k = 1:n,
+    importanceText{k} = sprintf('%d->%d',importance(k,2),importance(k,1));
+end
+if plotTypeFlag == 1,
+    set(axesH,'YScale','log');
+    textH = text([1:n]-0.4,1.4*importance(:,3),importanceText);
+else
+    set(axesH,'YScale','linear');
+    textH = text([1:n]-0.4,0.02*(yMax-yMin)+importance(:,3),importanceText);
+end
+set(textH,'fontsize',7);    
+% write axes labels
+xlabel('Interactions ordered in decreasing importance for complex bahvior');
+ylabel('Inverse of the magnitude of stabilizing perturbations (1/| \Delta_{ij}|)');
+% return information about numbers and states in matlab workspace
+% getting the names of the states in the network
+stateNames = feval(ODEfctname,'states');
+numbersInfoText = 'The numbers and the states in the ODEfctname are related as follows:';
+for k = 1:length(stateNames),
+    numbersInfoText = sprintf('%s\n%d: %s',numbersInfoText,k,stateNames{k});
+end
+disp(numbersInfoText);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Implementation of the method described in 
+% "Identifying mechanisms underlying complex behaviors in biochemical 
+% reaction networks", IEE Systems Biology, 1, 149-158 (2004) and
+% "Identifying feedback mechanisms behind complex cell behavior", IEEE
+% Control Systems Magazine, 24 (4), 91-102 (2004)
+%
+% for the determination of important interactions between states 
+% in biochemical networks, that are the source of an observed complex 
+% behavior.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [result] = analyzeImportantInteractions(ODEfctname, steadystate, visualizeFlag)
+global omegaRange omegaRangePoints bisectionThreshold criticalLocusTolerance criticalLocusNrPoints
+% determine the Jacobian
+A = SBjacobian(ODEfctname,steadystate);
+n = length(steadystate); I = eye(n);
+
+% what the method does - and in which order
+% 0) check that closed loop system is unstable and open loop system is stable
+% 1) determine omega0 - the frequency at which the critical eigenlocus
+%    crosses the real axis right of +1
+% 2) determine the [DELTA]_ij RGA measures for the importance of the interactions
+% 3) check if the determined delta_ij move the critical eigenlocus to +1
+% 4) return the result (delta_ijs that stabilize the system)
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check in/stability of A/Atilde
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% the closed loop system A needs to be unstable and the open loop system
+% Atilde = diag(A) need to be stable - otherwise the method is not
+% applicable 
+if max(real(eig(A))) < 0,
+    error(sprintf('The ODEfctname is stable - this analysis function only works with unstable models.\nIn case you are looking at a system having multiple steady-states\nyou need to specify a starting guess for the steady-state very close to the unstable steady-state.'));
+end
+Atilde = diag(diag(A));
+if max(real(eig(Atilde))) > 0,
+    error(sprintf('The linear open loop system is unstable. This method only works when the\ninteractionfree system is stable, and thus the instability is due to\ninteractions between components (states). You might consider the use of SBlocbehavinteract2 instead.'));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determination of omega0
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% if static instability then omega0 = 0
+% else w0 is given by the frequency at which the critical eigenlocus 
+% crosses the real axis right of +1
+eigA = eig(A);
+test = sortrows([real(eigA), imag(eigA)],1);
+maxRealEigA = test(length(test),:);
+if maxRealEigA(2) == 0,
+    % static instability, since unstable eigenvalue has zero imaginary part
+    omega0 = 0;
+    eigenLoci = [];
+else
+    % dynamic instability, since unstable eigenvalue has nonzero imaginary part
+    omega_star = abs(maxRealEigA(2));
+    % now we need to determine omega0 by determining the frequency at which
+    % the critical eigenlocus crosses the real axis right of +1. this is
+    % done by optimization using omega_star as starting guess for omega_0.
+    % first determine the critical eigenlocus and a bound for optimization
+    omega_range = logspace(log10(omega_star/omegaRange), log10(omegaRange*omega_star), omegaRangePoints);
+    eigenLoci = [eig(L(A,omega_range(1)))]; % initialize with a first entry
+    for k1 = 2:length(omega_range),
+        omega = omega_range(k1);
+        eigL = eig(L(A,omega));
+        % Need to reorder eigL before adding to eigenLoci, since ordering
+        % can be different. Use least squares to determine the order
+        newEigenLoci = inf*ones(n,1);
+        minSquareValue = inf;
+        for k2 = 1:n,
+            eigLk2 = eigL(k2);  % the value to order
+            order = sortrows([[1:n]', abs(eigenLoci(:,k1-1)-eigLk2)],2);
+            newEigenLoci(order(1,1)) = eigLk2;
+        end
+        % add reordered eigenloci to vector
+        eigenLoci = [eigenLoci newEigenLoci];
+    end
+    % go through all the eigenLoci and determine the index of the critical eigenlocus
+    % and an upper and lower bound for the frequency at which it crosses
+    maxRealPart = -inf;
+    criticalEigenLocusIndex = NaN;
+    for k1 = 1:n,
+        eigenLocus = eigenLoci(k1,:);
+        % check if the maximum magnitude over the frequencies is at least > 1
+        if max(abs(eigenLocus)) > 1,
+            imagEigenLocus = imag(eigenLocus);
+            realCrossing = max(real(eigenLocus(find(imagEigenLocus(1:end-1).*imagEigenLocus(2:end) < 0))));
+            if realCrossing > maxRealPart,
+                maxRealPart = realCrossing;
+                criticalEigenLocusIndex = k1;
+            end
+        end
+    end
+    if isnan(criticalEigenLocusIndex),
+        error(sprintf('The critical eigenlocus could not be determined. Please increase the value\nof the option "omegaRange" and/or the value of the option "omegaRangePoints".'));
+    end
+    criticalEigenLocus = eigenLoci(criticalEigenLocusIndex,:);
+    index = find(real(criticalEigenLocus) == maxRealPart);
+    imagValue = imag(criticalEigenLocus(index));
+    imagValueUp = imag(criticalEigenLocus(index+1));
+    imagValueDn = imag(criticalEigenLocus(index-1));
+    if imagValue*imagValueUp < 0, 
+        omegaUp = omega_range(index+1);
+        omegaDn = omega_range(index);
+    end
+    if imagValue*imagValueDn < 0,
+        omegaUp = omega_range(index);
+        omegaDn = omega_range(index-1);
+    end
+    % use bisection between omegaUp and omegaDn to determine the value of
+    % omega0
+    omega0 = bisectOmega0(A,omegaDn,omegaUp,bisectionThreshold);
+    % plot the result of the omega0 determination
+    figH = figure; clf;
+    plotEigenLociCheck(eigenLoci,A,omega0,1);
+    % wait for user to continue 
+    disp('Press any key to continue!');
+    pause;
+    try, close(figH); catch, end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determination of the delta_ij RGA measures
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+returnDifference = (I-L(A,omega0));
+Lambda = rga(returnDifference);
+
+warning off MATLAB:divideByZero
+DELTA = 1./Lambda;
+warning on MATLAB:divideByZero
+% set the elements that are zero in Lambda to zero in DELTA
+DELTA(find(Lambda==0))=0;
+DELTA = DELTA-diag(diag(DELTA));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check which of the RGA elements do stabilize
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% This is done by applying the determined needed changes at omega0
+% for each of the non-zero elements in DELTA and see if the critical
+% eigenlocus is moved to +1 at this frequency - if an element is not
+% stabilizing it is set to 0
+for row = 1:n, 
+    for col = 1:n,
+        % check if element is not zero, otherwise go to next element
+        if abs(DELTA(row,col)) ~= 0,
+            delta_ij = DELTA(row,col);  
+            if ~isStabilizing(row,col,delta_ij,omega0,A,bisectionThreshold,criticalLocusTolerance,criticalLocusNrPoints,eigenLoci,visualizeFlag),
+                DELTA(row,col) = 0;
+            end
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Return the result of the analysis
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% order the elements in DELTA after their magnitude and determine row and
+% column for them - discard zero elements - this is the result
+result = sort_cut(DELTA);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Plotting check figure for omega0 determination
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [] = plotEigenLociCheck(eigenLoci,A,omega0,textFlag);
+plot(real(eigenLoci), imag(eigenLoci), 'co'); hold on;
+eigL0 = eig(L(A,omega0)); 
+eigLcrit0 = selectRightEigenLocus(eigL0);
+handle = plot(real(eigLcrit0),imag(eigLcrit0),'rx');
+set(handle,'LineWidth',2);
+handle = plot(1,0,'kx');
+set(handle,'LineWidth',2);
+V = axis; minX = V(1); maxX = V(2); minY = V(3); maxY = V(4);
+plot([minX maxX],[0 0],'k--');
+plot([0 0],[minY maxY],'k--');
+if textFlag,
+    textX = (maxX-minX)*0.05+minX;
+    textY = maxY - 0.05*(maxY-minY);
+    texttext = sprintf('Please check that the red cross appears\nwhere the critical eigenlocus crosses\nthe real axis to the right of +1.\n\nIf this is not the case then you should\nstop the function and increase the value of the "omegaRange" option.\n\nTo continue press any key!');
+    text(textX,textY,texttext,'VerticalAlignment','top');
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Select the "right" eigenlocus :)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% from a vector with eigenloci at one frequency
+% select the one which lies right from +1 as close
+% as possible on the real axis
+function [rightEL] = selectRightEigenLocus(EL)
+    % split value in real and imag part
+    EL = [real(EL) imag(EL)];
+    % take away all the values with negative real part
+    EL = EL(find(EL(:,1)>0),:);
+    % sort the values after ascending imaginary part
+    EL = [EL abs(EL(:,2))];
+    EL = sortrows(EL,3);
+    % search for the element with the smallest imaginary part (magnitude)
+    % that has a real part > 0.99  (use 0.99 instead of 1 = quick fix)
+    for k = 1:size(EL,1),
+        if EL(k,1) > 0.99, break; end
+    end
+    % assemble the result
+    rightEL = EL(k,1)+i*EL(k,2);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if a delta_ij is stabilizing or not
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% This is done by applying the delta_ij at omega0 to L and checked
+% if the critical eigenlocus is moved to +1 at this frequency - if yes
+% 1 is returned, otherwise 0
+function [result] = isStabilizing(row,col,delta_ij,omega0,A,bisectionThreshold,criticalLocusTolerance,criticalLocusNrPoints,eigenLoci,visualizeFlag)
+    n = length(A);
+    % get nominal open loop at omega0
+    Lnom = L(A,omega0);
+    % get nominal eigenlocus at omega0
+    eigenLocus = eig(Lnom);
+    % get value of critical eigenLocus (has real part > 1 and imag part < 10*bisectionThreshold)
+    criticalLocus = eigenLocus(find((real(eigenLocus) > 1) & (abs(imag(eigenLocus)) < 10*bisectionThreshold)));
+    perturbationVector = delta_ij*[1/criticalLocusNrPoints:1/criticalLocusNrPoints:1];
+    if visualizeFlag,
+        % allows to visualize the determination if a delta_ij is
+        % stabilizing or not and to get an idea if options need to be
+        % changed
+        figH = figure(1); clf;    
+        plotEigenLociCheck(eigenLoci,A,omega0,0);
+    end  
+    for k1 = 1:length(perturbationVector),
+        % get next perturbation
+        delta = perturbationVector(k1);
+        % perturb the open loop system
+        Lpert = Lnom; 
+        Lpert(row,col) = Lpert(row,col)*(1-delta);
+        % determine eigenloci of the perturbed system
+        eigenLocus = eig(Lpert);
+        % check which eigenlocus is closest to the previous criticalLocus
+        sortedHelp = sortrows([[1:n]' abs(eigenLocus-criticalLocus)],2);
+        % get new criticalLocus
+        criticalLocus = eigenLocus(sortedHelp(1));
+        % visualize the determined critical locus
+        if visualizeFlag,
+            plot(real(criticalLocus),imag(criticalLocus),'kx');        
+        end
+    end
+    % check if the perturbed critical locus gets to +1
+    if abs(1-criticalLocus) < criticalLocusTolerance,
+        result = 1;
+    else 
+        result = 0;
+    end
+    % visualize all eigenloci for the full perturbation
+    if visualizeFlag,
+        plot(real(eigenLocus),imag(eigenLocus),'*g');    
+        disp('Press any key!');
+        pause;
+        close(figH);    
+    end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Order matrix elements after there magnitude
+% and determine row and column number, and index
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [X] = sort_cut(matrix)
+vector = matrix(:)';
+n = sqrt(length(vector));
+Y = 1:n^2;
+row = mod(Y,n); row(find(row==0))=n;
+col = ceil(Y/n);
+X = sortrows([row' col' abs(vector)'],3);
+[nx,mx] = size(X);
+INDEX = find(X(:,3)==0); INDEX = INDEX(length(INDEX))+1;
+X = X(INDEX:nx,:);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% RGA calculation
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [Lambda] = rga(matrix)
+    Lambda = matrix.*transpose(inv(matrix));
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OPTIMIZE omega0 using bisection
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [omega0] = bisectOmega0(A,omegaDn,omegaUp,bisectionThreshold)
+    eigLup = eig(L(A,omegaUp));
+    eigLdn = eig(L(A,omegaDn));
+    count = 0;
+    while (abs(omegaUp-omegaDn)>bisectionThreshold),
+        omegaTest = (omegaDn+omegaUp)/2;
+        eigLtest = eig(L(A,omegaTest));
+        if imag(selectRightEigenLocus(eigLup))*imag(selectRightEigenLocus(eigLtest)) < 0,
+            omegaUp = omegaUp;
+            omegaDn = omegaTest;
+            eigLup = eigLup;
+            eigLdn = eigLtest;
+        end
+        if imag(selectRightEigenLocus(eigLdn))*imag(selectRightEigenLocus(eigLtest)) < 0,
+            omegaUp = omegaTest;
+            omegaDn = omegaDn;
+            eigLup = eigLtest;
+            eigLdn = eigLdn;
+        end
+        count = count + 1;
+        if count >= 100,
+            error(sprintf('Please use a larger value for the "bisectionThreshold" option.'));
+        end
+    end
+    omega0 = omegaTest;
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CALCULATE L(jomega) FROM A AND omega 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [LofOmega] = L(A,omega)
+I = eye(size(A));
+s = i*omega;
+Atilde = diag(diag(A));
+LofOmega = inv(s*I-Atilde)*(A-Atilde);
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/behaviorlocalization/SBlocbehavinteract2.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/behaviorlocalization/SBlocbehavinteract2.m
new file mode 100644
index 0000000000000000000000000000000000000000..08545532152a762c65fddfecfafb7cbc75a62d33
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/behaviorlocalization/SBlocbehavinteract2.m
@@ -0,0 +1,338 @@
+function [varargout] = SBlocbehavinteract2(varargin)
+% SBlocbehavinteract2: does in principle the same as SBlocbehavinteract.
+% The differences are:
+%       - the value assumed for omega0 = omega_star (the imaginary part of 
+%         the unstable eigenvalue(s))                       
+%       - no check is done if the determined perturbations actually
+%         stabilize the system
+%
+% SBlocbehavinteract2 might be used in the case where the open loop system
+% is unstable. 
+%
+% USAGE
+% =====
+% [] = SBlocbehavinteract2(sbm, steadystate)  
+% [] = SBlocbehavinteract2(sbm, steadystate, OPTIONS)  
+% [importance,stateNames] = SBlocbehavinteract2(sbm, steadystate)  
+% [importance,stateNames] = SBlocbehavinteract2(sbm, steadystate, OPTIONS)  
+%
+% sbm: SBmodel or ODE file to perform the analysis on
+% steadystate: the steady-state at which to perform the analysis
+% OPTIONS: structure containing options
+%          OPTIONS.plotTypeFlag: =0: linear y-axis, =1: logarithmic y-axis
+% 
+% DEFAULT VALUES:
+% ===============
+% OPTIONS.plotTypeFlag: 0 (linear y-axis)
+%
+% Output Arguments:
+% =================
+% If no output argumentsd are given, the results are plotted.
+%
+% importance: each row corresponds to a direct interaction between states
+%       in the considered system. The first element in a row determines the
+%       index of the affected and the second the index of the affecting
+%       state. The third element in a row determines the inverse of the
+%       magnitude of the corresponding delta_ij value. delta_ij is the
+%       value for the relative perturbation in the corresponding
+%       interaction that will move a pole pair of the linearized system
+%       onto the imaginary axis. This might lead to stabilization of the
+%       underlying steady-state. However, it is not checked if it really is
+%       a stabilizing interaction. The function SBlocbehavinteract does
+%       this check. The 2nd version of this function can therefor only
+%       give a hint.
+%       The larger this inverse is, the more important the direct effect
+%       from state j on state i might be for the creation of the analyzed
+%       behavior (if stabilizing). 
+% stateNames: the name of the states corresponding to the numbering
+%       of columns and rows. 
+%
+% If no output arguments are given, the result is instead plotted.
+
+% Information:
+% ============
+% Copyright (C) 2003-2004 Henning Schmidt, henning@hschmidt.de
+% Adapted for the SBTOOLBOX by Henning Schmidt, March 2005
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+academicWarningSB
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF SBMODEL OR FILENAME
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isSBmodel(varargin{1}),
+    % SBmodel
+    sbm = varargin{1};
+    % check delays and events
+    if usedelaySB(sbm),
+        error('The model contains delays. These can not be handled by this function.');
+    end
+    if useeventSB(sbm),
+        error('The model contains events. These can not be handled by this function.');
+    end   
+    % Create temporary ODE file
+    [ODEfctname, ODEfilefullpath] = SBcreateTempODEfile(sbm);    
+else
+    % ODEfctname of ODE file
+    ODEfctname = varargin{1};
+    % Check if file exists
+    if exist(strcat(ODEfctname,'.m')) ~= 2,
+        error('ODE file could not be found.');
+    end
+end
+
+% default values
+plotTypeFlag = 0;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 2,
+    steadystate = varargin{2};
+elseif nargin == 3,
+    steadystate = varargin{2};
+    % get options for analysis method
+    OPTIONS = varargin{3};
+    % handle the options
+    % plotTypeFlag
+    if isfield(OPTIONS,'plotTypeFlag'),
+        if ~isempty(OPTIONS.plotTypeFlag),
+            plotTypeFlag = OPTIONS.plotTypeFlag;
+        end
+    end    
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK CORRECT NUMBER OF OUTPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargout ~= 0 && nargout ~= 2,
+    error('Incorrect number of output arguments');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF MODEL IS NON SINGULAR
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% check non singularity
+Jacobian = SBjacobian(ODEfctname,rand*ones(length(steadystate)));
+if rank(Jacobian) < length(Jacobian),
+    error(sprintf('The ODEfctname is singular. This function only works with non-singular models.\nYou might consider the use of ''SBreducemodel''.'));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HERE COMES THE MAIN ANALYSIS PART
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+result = analyzeImportantInteractions(ODEfctname, steadystate);
+% The first column in result contains the row number
+% The second column contains the column number
+% The third contains the magnitude of the required perturbation for stabilization
+%
+% Convert the required perturbations to importance measure by inverting them
+importance = result;
+importance(:,3) = 1./importance(:,3);
+% take out importances below a certain limit
+minShowImportance = 1e-6*max(importance(:,3));
+indexTakeOutStart = find(importance(:,3)<minShowImportance);
+if ~isempty(indexTakeOutStart),
+    importance = importance(1:indexTakeOutStart(1)-1,:);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABLE OUTPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargout == 0,
+    plotResults(importance, ODEfctname, plotTypeFlag, steadystate);
+else
+    varargout{1} = importance;
+    varargout{2} = stateNames;
+    % set acceptable format for output
+    format short g
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DELETE FILE IF SBMODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp('SBmodel',class(varargin{1})),
+    deleteTempODEfileSB(ODEfilefullpath);
+end
+return
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Plot the results of the analysis
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [] = plotResults(importance, ODEfctname, plotTypeFlag, steadystate)
+% determine Jacobian at given steadystate (signs of elements needed for
+% choosing plot color)
+J = SBjacobian(ODEfctname,steadystate);
+% get number of rows in importance matrix
+n = size(importance,1);
+% open new figure
+figH = figure; clf; axesH = gca(figH);
+% plot the data - blue if Jacobian element positive, red if Jacobian
+% element negative
+if plotTypeFlag == 0,
+    for k = 1:n,
+        if J(importance(k,1),importance(k,2)) >= 0,
+            bar(k,importance(k,3),'b'); hold on;
+        else
+            bar(k,importance(k,3),'r'); hold on;
+        end
+    end    
+else
+    for k = 1:n,
+        if J(importance(k,1),importance(k,2)) >= 0,
+            handle = plot(k,importance(k,3),'ob'); hold on;
+            set(handle,'LineWidth',2);
+            set(handle,'MarkerFaceColor','b');            
+        else
+            handle = plot(k,importance(k,3),'or'); hold on;
+            set(handle,'LineWidth',2);
+            set(handle,'MarkerFaceColor','r');            
+        end
+    end
+end    
+% set y-axis properties
+yMax = 1.5*max(importance(:,3));
+if plotTypeFlag,
+    % min value in case of semilogy plot
+    help = sort(importance(:,3))';
+    help = help(find(help>0))';
+    yMin = 0.75*help(1);
+else
+    % min value to zero in case of linear plot
+    yMin = 0;
+end
+axis([0 n+1 yMin yMax]);
+set(axesH,'XTick',[]);
+% construct plot text and plot it
+importanceText = {};
+for k = 1:n,
+    importanceText{k} = sprintf('%d->%d',importance(k,2),importance(k,1));
+end
+if plotTypeFlag == 1,
+    set(axesH,'YScale','log');
+    textH = text([1:n]-0.4,1.4*importance(:,3),importanceText);
+else
+    set(axesH,'YScale','linear');
+    textH = text([1:n]-0.4,0.02*(yMax-yMin)+importance(:,3),importanceText);
+end
+set(textH,'fontsize',7);    
+% write axes labels
+xlabel('Interactions ordered in decreasing importance for complex bahvior');
+ylabel('Inverse of the magnitude of perturbations (1/| \Delta_{ij}|)');
+% return information about numbers and states in matlab workspace
+% getting the names of the states in the network
+stateNames = feval(ODEfctname,'states');
+numbersInfoText = 'The numbers and the states in the ODEfctname are related as follows:';
+for k = 1:length(stateNames),
+    numbersInfoText = sprintf('%s\n%d: %s',numbersInfoText,k,stateNames{k});
+end
+disp(numbersInfoText);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Implementation of the method described in 
+% "Identifying mechanisms underlying complex behaviors in biochemical 
+% reaction networks", IEE Systems Biology, 1, 149-158 (2004) and
+% "Identifying feedback mechanisms behind complex cell behavior", IEEE
+% Control Systems Magazine, 24 (4), 91-102 (2004)
+%
+% for the determination of important interactions between states 
+% in biochemical networks, that are the source of an observed complex 
+% behavior.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [result] = analyzeImportantInteractions(ODEfctname, steadystate)
+% determine the Jacobian
+A = SBjacobian(ODEfctname,steadystate);
+n = length(steadystate); I = eye(n);
+
+% what the method does - and in which order
+% 1) determine omega0 - just use the imaginary part of the unstable eigenvalues
+% 2) determine the [DELTA]_ij RGA measures for the importance of the interactions
+% 3) check if the determined delta_ij move the critical eigenlocus to +1
+% 4) return the result (delta_ijs that stabilize the system)
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determination of omega0
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% if static instability then omega0 = 0
+% else w0 is given by the frequency at which the critical eigenlocus 
+% crosses the real axis right of +1
+eigA = eig(A);
+test = sortrows([real(eigA), imag(eigA)],1);
+maxRealEigA = test(length(test),:);
+if maxRealEigA(2) == 0,
+    % static instability, since unstable eigenvalue has zero imaginary part
+    omega0 = 0;
+else
+    omega0 = abs(maxRealEigA(2)); 
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determination of the delta_ij RGA measures
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+returnDifference = (I-L(A,omega0));
+Lambda = rga(returnDifference);
+warning off MATLAB:divideByZero
+DELTA = 1./Lambda;
+warning on MATLAB:divideByZero
+% set the elements that are zero in Lambda to zero in DELTA
+DELTA(find(Lambda==0))=0;
+DELTA = DELTA-diag(diag(DELTA));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Return the result of the analysis
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% order the elements in DELTA after their magnitude and determine row and
+% column for them - discard zero elements - this is the result
+result = sort_cut(DELTA);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Order matrix elements after there magnitude
+% and determine row and column number, and index
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [X] = sort_cut(matrix)
+vector = matrix(:)';
+n = sqrt(length(vector));
+Y = 1:n^2;
+row = mod(Y,n); row(find(row==0))=n;
+col = ceil(Y/n);
+X = sortrows([row' col' abs(vector)'],3);
+[nx,mx] = size(X);
+INDEX = find(X(:,3)==0); INDEX = INDEX(length(INDEX))+1;
+X = X(INDEX:nx,:);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% RGA calculation
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [Lambda] = rga(matrix)
+    Lambda = matrix.*transpose(inv(matrix));
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CALCULATE L(jomega) FROM A AND omega 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [LofOmega] = L(A,omega)
+I = eye(size(A));
+s = i*omega;
+Atilde = diag(diag(A));
+LofOmega = inv(s*I-Atilde)*(A-Atilde);
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/SBsensglobalfast.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/SBsensglobalfast.m
new file mode 100644
index 0000000000000000000000000000000000000000..d974c910e99a6730460ed3d45a18a3a6cb03e918
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/SBsensglobalfast.m
@@ -0,0 +1,380 @@
+function [varargout] = SBsensglobalfast(model,timevector,varargin)
+% Global sensitivity analysis method: Extended FAST method
+%
+% For more information see:
+%
+% Y. Zheng and A. Rundell (2006) Comparative study of parameter sensitivity
+% analyses of the TCR-activated Erk-MAPK signalling pathway, IEE
+% Proc.-Syst. Biol., Vol. 153, No. 4, 201-211
+%
+% Saltelli, A., Tarantola, S., and Chan, K.P.S. (1999) A quantitative
+% model-independent method for global sensitivity analysis of model
+% output, Technometrics, 41, 39�56
+%
+% USAGE:
+% ======
+% SBsensglobalfast(model,timevector)
+% SBsensglobalfast(model,timevector,paramNames)
+% SBsensglobalfast(model,timevector,paramNames,OPTIONS)
+% [output] = SBsensglobalfast(model,timevector)
+% [output] = SBsensglobalfast(model,timevector,paramNames)
+% [output] = SBsensglobalfast(model,timevector,paramNames,OPTIONS)
+%
+% model: SBmodel to perform the global sensitivity analysis for
+% timevector: vector of timeinstants to consider
+% paramNames: cell-array with names of the parameters to consider
+% OPTIONS: structure with optional settings:
+%   OPTIONS.statenames: cell-array with state names which to consider as
+%       model outputs
+%   OPTIONS.variablenames: cell-array with variable names which to consider
+%       as model outputs
+%   OPTIONS.reactionnames: cell-array with reaction names which to consider
+%       as model outputs
+%   OPTIONS.Nsim: Number of simulation to carry out (approximate value)
+%   OPTIONS.range: Order of magnitude of parameter perturbations
+%   OPTIONS.firstorder: =0: use total effect, =1: use first order approx.
+%   OPTIONS.objectivefunction: ='relative': the differences between nominal
+%       and perturbed model are normalized to represent relative changes in
+%       each considered variable. ='absolute': no normalization is done.
+%       Alternatively, the user can provide the name for an own objective
+%       function to use. As template you can have a look at the two
+%       objectivefunctions in the folder:
+%       SBTOOLBOX2/analysis/globalparametersensitivity/auxiliary
+%   OPTIONS.integrator: Structure with optional settings for the integrator
+%
+% DEFAULT VALUES:
+% ===============
+% paramNames: Consider all parameters in the model
+% OPTIONS.statenames: Consider all states in the model
+% OPTIONS.variablenames: {} (no variables)
+% OPTIONS.reactionnames: {} (no reactions)
+% OPTIONS.Nsim: 1000
+% OPTIONS.range: 1
+% OPTIONS.firstorder: 0 (use total effect)
+% OPTIONS.objectivefunction: 'relative'
+% OPTIONS.integrator: [] (default integrator settings)
+%
+% Output Arguments:
+% =================
+% If no output argument is specified, the result is plotted.
+% Otherwise, the output is a structure with the following fields:
+%
+% output.Nsim: Number of performed simulations
+% output.method: Name of the global sensitivity method
+% output.parameters: Considered parameters 
+% output.overallmeasure: Sensitivity indices for overall model output
+% output.overallparamranking: Parameter ranking regarding overall model output
+% output.singlecomponents: Names of the components, considered outputs
+% output.singlemeasure: Single sensitivity indices for all considered model outputs
+% output.singleparamranking: Parameter ranking for each considered model output
+
+% Information:
+% ============
+% Copyright (C) 2007 Ann Rundell, rundell@purdue.edu
+% Adapted for the SBTOOLBOX2 by Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+global Ncount 
+Ncount = 0;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE NON-NUMERIC INITIAL CONDITIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% just by replacing them
+model = SBconvertNonNum2NumIC(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF SBPD IS PRESENT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBPDpresent = ver('SBPD');
+if isempty(SBPDpresent),
+    error(sprintf('The SBPD package is not installed. For the global sensitivity analysis\nfunctions, however, this package is needed, since it considerably speeds up the computations\nThe SBPD can be downloaded from www.sbtoolbox2.org.'));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 2,
+    paramNames = SBparameters(model);
+    OPTIONS = [];
+elseif nargin == 3,
+    paramNames = varargin{1};
+    OPTIONS = [];
+elseif nargin == 4,
+    paramNames = varargin{1};
+    OPTIONS = varargin{2};
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DEFAULT OPTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+statenames = SBstates(model);
+variablenames = {};
+reactionnames = {};
+Nsim = 1000;
+range = 1;
+firstorder = 0;
+integratoroptions = [];
+objectivefunction = 'relative';
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try statenames = OPTIONS.statenames; catch, end
+try variablenames = OPTIONS.variablenames; catch, end
+try reactionnames = OPTIONS.reactionnames; catch, end
+try Nsim = OPTIONS.Nsim; catch, end
+try range = OPTIONS.range; catch, end
+try firstorder = OPTIONS.firstorder; catch, end
+try integratoroptions = OPTIONS.integrator; catch, end
+try objectivefunction = OPTIONS.objectivefunction; catch, end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS objecticefunction CHOICE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp(objectivefunction,'relative'),
+    objectivefunction = 'rel_sensglobaldefaultobjectiveSB';
+elseif strcmp(objectivefunction,'absolute'),
+    objectivefunction = 'abs_sensglobaldefaultobjectiveSB';
+else
+    % user defined objective functions
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET INDICES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+stateindices = stateindexSB(model,statenames);
+variableindices = variableindexSB(model,variablenames);
+reactionindices = reactionindexSB(model,reactionnames);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% MAKE MEX MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[MEXmodel, MEXmodelfullpath] = makeTempMEXmodelSBPD(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GENERATE NOMINAL SOLUTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+paramValuesNominal = SBparameters(model,paramNames);
+nomsimdata = SBPDsimulate(MEXmodel,timevector,SBinitialconditions(model),paramNames,paramValuesNominal,integratoroptions);
+Ncount = Ncount + 1;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK FOR ZERO NOMINAL PARAMETERS and exclude them from the analysis
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+indexZero = find(paramValuesNominal == 0);
+if ~isempty(indexZero),
+    text = sprintf('%s, ',paramNames{indexZero});
+    disp(sprintf('Some parameters have nominal values of zero. They are excluded from the analysis.\nParameters: %s\n',text(1:end-2)));
+    paramValuesNominal(indexZero) = [];
+    paramNames = paramNames(setdiff(1:length(paramNames),indexZero));
+end
+
+nrparam = length(paramNames);
+
+PS=[];% reset PS
+output=[];% reset output
+%frequency and phase selection keeps # of model simulations ~ Nsim
+M = 6; % interference factor (usually 4 or 6) corresponds to higher harmonics
+%Find max frequency: there is a trade off between computation numbers
+%  and optimal ratio of max/number of phase shift evaluations
+stor_C = inf;  % initialize with very large number so always updates on first pass
+for target = 16:64  % evaluate all target levels in range, see figure 7 of ref 15 (Saltelli, Tarantola, Chan 1999)
+    y = [M;Nsim;nrparam;target];  % input vector to find max frequency
+    [W,FVAL,EXITFLAG] = fsolveSB(@(W)FAST_max_W(W,y),nrparam*2);  % find highest frequency of interest (req from ref 15)
+    Wmax = ceil(W);  % make optimal an integer
+    if Wmax/2 ~= floor(Wmax/2), % force Wmax to be even!!
+        Wmax = Wmax + 1;
+    end
+    Ns = 2*M*Wmax+1;  % number of samples along s from -pi to pi
+    Nph = ceil(Nsim/(nrparam*Ns)); % number of random phase shift curves that keeps ~ Nsim total model evals
+    C = Ns*Nph*nrparam;  % computational costs
+    if C < stor_C  % store smallest computational cost solution
+        stor_C = C;
+        stor_W = Wmax;
+    end
+end
+Wmax = ceil(stor_W);  % make optimal value an integer
+Ns = 2*M*Wmax+1;  % number of samples along s from -pi to pi
+Nph = ceil(Nsim/(nrparam*Ns)); % number of random phase shift curves that keeps ~ Nsim total model evals
+
+%Determine maximum for complmentary frequencies
+maxw_c = floor(Wmax/(2*M));  % prevents aliasing
+wvec = ones(1,nrparam);  % construct frequency vector
+step = ceil(maxw_c/nrparam);  % want largest possible steps between freqeunces
+for i = 2:nrparam
+    wvec(i)=wvec(i-1)+step;  % exhaust frequency range between (1 and maxw_i)
+    if wvec(i)>maxw_c  % check for exceeding max allowable freq
+        wvec(i)=1;   % assign the same frequency as seldom as possible
+    end
+end
+
+%Determine parameter space for compuations
+phi = 2*pi*rand(nrparam,Nph);
+
+s = [];  % scalar variable for parameter space
+for i = 1:Ns
+    s(i) = pi/Ns*(2*i-Ns-1);  % space out sampled parameter space between -pi to pi
+end
+for k = 1:Ns % for each s sample
+    for i = 1:Nph % for each phase shift
+        for j = 1:nrparam % for each parameter
+            w = wvec; % assign freq of variations to all paramNames
+            w(j) = Wmax; % fix freq of var for parameter of interest at max freq
+            temp = 10.^(2/pi*asin(sin(w*s(k)+phi(j,i))).*range).*paramValuesNominal(:)';
+            PS(k,:,j,i)=temp;  % define parameter space for analysis
+        end
+    end
+end
+
+%Determine output for different parameter sets
+try
+    for k = 1:Ns  % for each s sample
+        for i = 1:Nph % for each phase shift
+            for j = 1:nrparam % for each parameter
+                paramValuesPerturbed = PS(k,:,j,i);  % assign parameter values from parameter space
+                %compute model output and objective function for kp
+                tic;
+                output(k,:,j,i)=feval(objectivefunction,MEXmodel,timevector,paramNames,paramValuesPerturbed,SBinitialconditions(model),nomsimdata,stateindices,variableindices,reactionindices,integratoroptions);
+                deltaT_ = toc;
+                if k*i*j == 1,
+                    disp(sprintf('FAST: Approximate time for analysis: %d minutes',ceil(deltaT_*Ns*Nph*nrparam/60)));
+                end
+            end
+        end
+    end
+catch
+    error('Simulation failed. Please consider a reduction of the ''range'' option.');
+end
+% compute FS coefficients indices
+m = size(output,2);  % # of outputs
+A = zeros(M*Wmax,m,nrparam,Nph);  % vector for coef of FS
+B = zeros(M*Wmax,m,nrparam,Nph);  % vector for coef of FS
+for i = 1:Nph  % for each phase shift
+    for j = 1:nrparam % for each parameter
+        for f = 1:M*Wmax % for harmonic frequencies below Nyquist: ~(Ns-1)/2
+            for k = 1:Ns % for each s sample
+                A(f,:,j,i)=A(f,:,j,i)+output(k,:,j,i)*cos(f*s(k))/Ns;  %compute FS cos coef
+                B(f,:,j,i)=B(f,:,j,i)+output(k,:,j,i)*sin(f*s(k))/Ns;  %compute FS sin coef
+            end
+        end
+    end
+end
+
+%compute sensitivity indices from FS coef
+Amp = A.^2+B.^2;  % Magnitude of frequency content
+Dtot = sum(2*sum(Amp,1),4)/Nph;
+Dtot=squeeze(Dtot);
+Di = sum(2*sum(Amp(Wmax:Wmax:M*Wmax,:,:,:),1),4)/Nph;
+Di = squeeze(Di);
+D_i=sum(2*sum(Amp(1:Wmax/2,:,:,:),1),4)/Nph;
+D_i=squeeze(D_i);
+
+% take care of zeros (mostly trough states that are not affected by
+% parameters).
+indexzeros = find(Dtot==0);
+Dtot(indexzeros) = 1;
+D_i(indexzeros) = 1;
+eFAST_1 = (Di./Dtot)';
+eFAST_t = (1-D_i./Dtot)';
+
+%sort sensitivity rankings
+%rank_eFAST_1: sorted first order rankings in terms of ascending magnitude
+%rank_eFAST_1p: paramNames ranked in assending order via first order values
+[rank_eFAST_1, rank_eFAST_1p] = sort(abs(eFAST_1),1,'descend');
+%rank_eFAST_t: sorted total effect order rankings in terms of ascending magnitude
+%rank_eFAST_tp: paramNames ranked in assending order via total effect values
+[rank_eFAST_t, rank_eFAST_tp] = sort(abs(eFAST_t),1,'descend');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE OUTPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output = [];
+output.Nsim = Ncount;
+if firstorder == 1, output.method = 'FAST First Order';
+else output.method = 'FAST Total Effect'; end
+output.parameters = paramNames(:)';
+if firstorder == 1, output.overallmeasure = eFAST_1(:,end);
+else output.overallmeasure = eFAST_t(:,end); end
+if firstorder == 1, output.overallparamranking = rank_eFAST_1p(:,end);
+else output.overallparamranking = rank_eFAST_tp(:,end); end
+output.singlecomponents = {statenames{:}, variablenames{:}, reactionnames{:}};
+if firstorder == 1, output.singlemeasure = eFAST_1(:,1:end-1);
+else output.singlemeasure = eFAST_t(:,1:end-1); end
+if firstorder == 1, output.singleparamranking = rank_eFAST_1p(:,1:end-1);
+else output.singleparamranking = rank_eFAST_tp(:,1:end-1); end
+
+% generate plotting datastructure (for SBplot2)
+datastruct = [];
+datastruct.name = sprintf('Global Sensitivities: %s method',output.method);
+datastruct.xnames = output.parameters;
+datastruct.ynames = {'OVERALL MEASURE', output.singlecomponents{:}};    % cell-array with names of y-axis data
+datastruct.data =  [output.overallmeasure output.singlemeasure]'; %  matrix with y-axis data in rows and x-axis data in columns
+datastruct.title = sprintf('Global Sensitivities: %s method',output.method);
+datastruct.xlabel = 'Parameters';
+datastruct.xaxistitle = 'X';
+datastruct.yaxistitle = 'Y';
+% add it to the output variable
+output.plotdatastruct = datastruct;
+
+if nargout == 1,
+    varargout{1} = output;
+elseif nargout == 0,
+    % Plot the sensitivities using SBplot2
+    SBplot2(datastruct)
+else
+    error('Incorrect number of output arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DELETE MEX MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+clear mex;
+delete(MEXmodelfullpath);
+clear global Ncount
+
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function fval = FAST_max_W(W,y)
+
+% W is highest frequency of interest
+M = y(1);  % inteference factor (usually 4 or 6) corresponds to higher harmonics
+N = y(2);  % approximate total number of model evaluations
+n_p = y(3);  % number of factors
+target = y(4);  % target value for ratio
+
+Ns = 2*M*W+1;  % number of samples along s from -pi to pi
+Nph = ceil(N/(n_p*Ns)); % number of random phase shift curves that keeps ~ N total model evals
+ratio = W/Nph;  % compute ratio
+% desired range of ration is between 16 and 64
+%For more info:  see figure 7 of ref 15 (Saltelli, Tarantola, Chan 1999)
+fval = ratio-target;  % compute difference between ratio and target
+penalty = 10;
+if ratio < 64
+    if ratio < 16
+        fval =penalty*fval;  % ratio not in desired range penalize for too small
+    end
+else
+    fval = penalty*fval; % ratio not in desired range penalize for too large
+end
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/SBsensglobalprcc.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/SBsensglobalprcc.m
new file mode 100644
index 0000000000000000000000000000000000000000..94353d0ebf07cd8410e884b4ba4da342fb108362
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/SBsensglobalprcc.m
@@ -0,0 +1,287 @@
+function [varargout] = SBsensglobalprcc(model,timevector,varargin)
+% Global sensitivity analysis method: PRCC method
+%
+% For more information see:
+%
+% Y. Zheng and A. Rundell (2006) Comparative study of parameter sensitivity
+% analyses of the TCR-activated Erk-MAPK signalling pathway, IEE
+% Proc.-Syst. Biol., Vol. 153, No. 4, 201-211
+%
+% Draper, N., and Smith, H. (1981) Applied regression analysis, Wiley,
+% New York, 2nd edn.
+%
+% USAGE:
+% ======
+% SBsensglobalprcc(model,timevector)
+% SBsensglobalprcc(model,timevector,paramNames)
+% SBsensglobalprcc(model,timevector,paramNames,OPTIONS)
+% [output] = SBsensglobalprcc(model,timevector)
+% [output] = SBsensglobalprcc(model,timevector,paramNames)
+% [output] = SBsensglobalprcc(model,timevector,paramNames,OPTIONS)
+%
+% model: SBmodel to perform the global sensitivity analysis for
+% timevector: vector of timeinstants to consider
+% paramNames: cell-array with names of the parameters to consider
+% OPTIONS: structure with optional settings:
+%   OPTIONS.statenames: cell-array with state names which to consider as
+%       model outputs
+%   OPTIONS.variablenames: cell-array with variable names which to consider
+%       as model outputs
+%   OPTIONS.reactionnames: cell-array with reaction names which to consider
+%       as model outputs
+%   OPTIONS.Nsim: Number of simulation to carry out (approximate value)
+%   OPTIONS.range: Order of magnitude of parameter perturbations
+%   OPTIONS.objectivefunction: ='relative': the differences between nominal
+%       and perturbed model are normalized to represent relative changes in
+%       each considered variable. ='absolute': no normalization is done.
+%       Alternatively, the user can provide the name for an own objective
+%       function to use. As template you can have a look at the two
+%       objectivefunctions in the folder:
+%       SBTOOLBOX2/analysis/globalparametersensitivity/auxiliary
+%   OPTIONS.integrator: Structure with optional settings for the integrator
+%
+% DEFAULT VALUES:
+% ===============
+% paramNames: Consider all parameters in the model
+% OPTIONS.statenames: Consider all states in the model
+% OPTIONS.variablenames: {} (no variables)
+% OPTIONS.reactionnames: {} (no reactions)
+% OPTIONS.Nsim: 1000
+% OPTIONS.range: 1
+% OPTIONS.objectivefunction: 'relative'
+% OPTIONS.integrator: [] (default integrator settings)
+%
+% Output Arguments:
+% =================
+% If no output argument is specified, the result is plotted.
+% Otherwise, the output is a structure with the following fields:
+%
+% output.Nsim: Number of performed simulations
+% output.method: Name of the global sensitivity method
+% output.parameters: Considered parameters 
+% output.overallmeasure: Sensitivity indices for overall model output
+% output.overallparamranking: Parameter ranking regarding overall model output
+% output.singlecomponents: Names of the components, considered outputs
+% output.singlemeasure: Single sensitivity indices for all considered model outputs
+% output.singleparamranking: Parameter ranking for each considered model output
+
+% Information:
+% ============
+% Copyright (C) 2007 Ann Rundell, rundell@purdue.edu
+% Adapted for the SBTOOLBOX2 by Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+global Ncount 
+Ncount = 0;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE NON-NUMERIC INITIAL CONDITIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% just by replacing them
+model = SBconvertNonNum2NumIC(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF SBPD IS PRESENT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBPDpresent = ver('SBPD');
+if isempty(SBPDpresent),
+    error(sprintf('The SBPD package is not installed. For the global sensitivity analysis\nfunctions, however, this package is needed, since it considerably speeds up the computations\nThe SBPD can be downloaded from www.sbtoolbox2.org.'));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 2,
+    paramNames = SBparameters(model);
+    OPTIONS = [];
+elseif nargin == 3,
+    paramNames = varargin{1};
+    OPTIONS = [];
+elseif nargin == 4,
+    paramNames = varargin{1};
+    OPTIONS = varargin{2};
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DEFAULT OPTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+statenames = SBstates(model);
+variablenames = {};
+reactionnames = {};
+Nsim = 1000;
+range = 1;
+integratoroptions = [];
+objectivefunction = 'relative';
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try statenames = OPTIONS.statenames; catch, end
+try variablenames = OPTIONS.variablenames; catch, end
+try reactionnames = OPTIONS.reactionnames; catch, end
+try Nsim = OPTIONS.Nsim; catch, end
+try range = OPTIONS.range; catch, end
+try integratoroptions = OPTIONS.integrator; catch, end
+try objectivefunction = OPTIONS.objectivefunction; catch, end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS objecticefunction CHOICE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp(objectivefunction,'relative'),
+    objectivefunction = 'rel_sensglobaldefaultobjectiveSB';
+elseif strcmp(objectivefunction,'absolute'),
+    objectivefunction = 'abs_sensglobaldefaultobjectiveSB';
+else
+    % user defined objective functions
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET INDICES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+stateindices = stateindexSB(model,statenames);
+variableindices = variableindexSB(model,variablenames);
+reactionindices = reactionindexSB(model,reactionnames);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% MAKE MEX MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[MEXmodel, MEXmodelfullpath] = makeTempMEXmodelSBPD(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GENERATE NOMINAL SOLUTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+paramValuesNominal = SBparameters(model,paramNames);
+nomsimdata = SBPDsimulate(MEXmodel,timevector,SBinitialconditions(model),paramNames,paramValuesNominal,integratoroptions);
+Ncount = Ncount + 1;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK FOR ZERO NOMINAL PARAMETERS and exclude them from the analysis
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+indexZero = find(paramValuesNominal == 0);
+if ~isempty(indexZero),
+    text = sprintf('%s, ',paramNames{indexZero});
+    disp(sprintf('Some parameters have nominal values of zero. They are excluded from the analysis.\nParameters: %s\n',text(1:end-2)));
+    paramValuesNominal(indexZero) = [];
+    paramNames = paramNames(setdiff(1:length(paramNames),indexZero));
+end
+
+
+nrparam = length(paramNames); % number of model paramNames to perform sensitivity analysis on
+
+%Determine parameter space for compuations
+%latin hypercube sampling of parameter space
+LHS = lhsu(zeros(1,nrparam),ones(1,nrparam),Nsim); %matlab command to generate LHS sampling (using a free LHS tool)
+
+% Nsim equal intervals from 0 to 1 for each parameter
+% scale to cover full parameter space with uniform distribution in log space
+PS = 10.^((LHS-.5).*2*range).*(ones(Nsim,1)*paramValuesNominal(:)');
+
+%compute model output and evaluate objective function for each set of paramNames
+try
+    for i = 1:Nsim
+        paramValuesPerturbed = PS(i,:);  %evaluate objective function for each parameter set
+        tic;
+        output(i,:) = feval(objectivefunction,MEXmodel,timevector,paramNames,paramValuesPerturbed,SBinitialconditions(model),nomsimdata,stateindices,variableindices,reactionindices,integratoroptions);
+        deltaT_ = toc;
+        if i == 1,
+            disp(sprintf('PRCC: Approximate time for analysis: %d minutes',ceil(deltaT_*Nsim/60)));
+        end
+    end
+catch
+    error('Simulation failed. Please consider a reduction of the ''range'' option.');
+end
+%Perform rank transformation
+%rank output of objective function evaluations with different parameter values
+[sorted_val, rownum] = sort([PS,output]);  %sort each column in ascending order, keep track or row number in column
+[indvalue, ranking] = sort(rownum); % sort rownum to get ranking of output
+
+%compute rank transformed Pearson's correlation coeffients for each parameter set
+am = (1+Nsim)/2;  %arithmatic mean of rankings for Nsim independent runs
+n_out = size(output,2);  %size of output of objective function
+PEAR_p=zeros(nrparam,nrparam);
+PEAR_out=zeros(nrparam,n_out);
+for i = 1:nrparam
+    normp = norm(ranking(:,i)-am);  %sqrt of sum of squares for all paramNames in set
+    for j = 1:(nrparam)  % compute correlation coef for paramNames
+        numerator = sum((ranking(:,i)-am).*(ranking(:,j)-am));
+        denominator = normp*norm(ranking(:,j)-am);
+        PEAR_p(i,j)=numerator./denominator;  % PEAR correlation coefficients
+        PEAR_p(j,i)=PEAR_p(i,j); %make this a symmetric matrix
+    end
+    for j = 1:n_out  % compute correlation coef for outputs of obj func
+        numerator = sum((ranking(:,i)-am).*(ranking(:,j+nrparam)-am));
+        denominator = normp*norm(ranking(:,j+nrparam)-am);
+        PEAR_out(i,j)=numerator./denominator;  % PEAR correlation coefficients
+    end
+end
+
+%compute PRCC (-1 to 1) from rank transformed Pearson Correlation Coef
+% PRCC:  matrix with PRCC computed sensitivity indicies
+PRCC = zeros(nrparam,n_out);
+for k = 1:n_out  % for each output compute PRCC for the paramNames
+    mat = [[PEAR_p, PEAR_out(:,k)];[PEAR_out(:,k)',1]];  %append row and column of output of interest
+    imat = inv(mat);  %take inverse of matrix
+    PRCC(1:nrparam,k) = -imat(1:nrparam,nrparam+1)./sqrt(diag(imat(1:nrparam,1:nrparam)*imat(nrparam+1, nrparam+1)));
+end
+
+%sort PRCC rankings
+%rank_PRCC_p: paramNames ranked in assending order via PRCC values
+[temp rank_PRCC_p] = sort(abs(PRCC));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE OUTPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output = [];
+output.Nsim = Ncount;
+output.method = 'PRCC';
+output.parameters = paramNames(:)';
+output.overallmeasure = PRCC(:,end);
+output.overallparamranking = rank_PRCC_p(:,end);
+output.singlecomponents = {statenames{:}, variablenames{:}, reactionnames{:}};
+output.singlemeasure = PRCC(:,1:end-1);
+output.singleparamranking = rank_PRCC_p(:,1:end-1);
+
+% generate plotting datastructure (for SBplot2)
+datastruct = [];
+datastruct.name = 'Global Sensitivities: PRCC method';
+datastruct.xnames = output.parameters;
+datastruct.ynames = {'OVERALL MEASURE', output.singlecomponents{:}};    % cell-array with names of y-axis data
+datastruct.data =  [output.overallmeasure output.singlemeasure]'; %  matrix with y-axis data in rows and x-axis data in columns
+datastruct.title = 'Global Sensitivities: PRCC method';
+datastruct.xlabel = 'Parameters';
+datastruct.xaxistitle = 'X';
+datastruct.yaxistitle = 'Y';
+% add it to the output variable
+output.plotdatastruct = datastruct;
+
+if nargout == 1,
+    varargout{1} = output;
+elseif nargout == 0,
+    SBplot2(datastruct)
+else
+    error('Incorrect number of output arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DELETE MEX MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+clear mex;
+delete(MEXmodelfullpath);
+clear global Ncount
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/SBsensglobalsobol.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/SBsensglobalsobol.m
new file mode 100644
index 0000000000000000000000000000000000000000..c2d3091aec21396e4882769094fe886f21c5901d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/SBsensglobalsobol.m
@@ -0,0 +1,341 @@
+function [varargout] = SBsensglobalsobol(model,timevector,varargin)
+% Global sensitivity analysis method: SOBOL's method
+%
+% For more information see:
+%
+% Y. Zheng and A. Rundell (2006) Comparative study of parameter sensitivity
+% analyses of the TCR-activated Erk-MAPK signalling pathway, IEE
+% Proc.-Syst. Biol., Vol. 153, No. 4, 201-211
+%
+% Sobol, I.M. (2001) Global sensitivity indices for nonlinear mathematical
+% models and their Monte Carlo estimates, Math. Comp. Simul., 55, 271�280
+%
+% USAGE:
+% ======
+% SBsensglobalsobol(model,timevector)
+% SBsensglobalsobol(model,timevector,paramNames)
+% SBsensglobalsobol(model,timevector,paramNames,OPTIONS)
+% [output] = SBsensglobalsobol(model,timevector)
+% [output] = SBsensglobalsobol(model,timevector,paramNames)
+% [output] = SBsensglobalsobol(model,timevector,paramNames,OPTIONS)
+%
+% model: SBmodel to perform the global sensitivity analysis for
+% timevector: vector of timeinstants to consider
+% paramNames: cell-array with names of the parameters to consider
+% OPTIONS: structure with optional settings:
+%   OPTIONS.statenames: cell-array with state names which to consider as
+%       model outputs
+%   OPTIONS.variablenames: cell-array with variable names which to consider
+%       as model outputs
+%   OPTIONS.reactionnames: cell-array with reaction names which to consider
+%       as model outputs
+%   OPTIONS.Nsim: Number of simulation to carry out (approximate value)
+%   OPTIONS.range: Order of magnitude of parameter perturbations
+%   OPTIONS.firstorder: =0: use total effect, =1: use first order approx.
+%   OPTIONS.objectivefunction: ='relative': the differences between nominal
+%       and perturbed model are normalized to represent relative changes in
+%       each considered variable. ='absolute': no normalization is done.
+%       Alternatively, the user can provide the name for an own objective
+%       function to use. As template you can have a look at the two
+%       objectivefunctions in the folder:
+%       SBTOOLBOX2/analysis/globalparametersensitivity/auxiliary
+%   OPTIONS.integrator: Structure with optional settings for the integrator
+%
+% DEFAULT VALUES:
+% ===============
+% paramNames: Consider all parameters in the model
+% OPTIONS.statenames: Consider all states in the model
+% OPTIONS.variablenames: {} (no variables)
+% OPTIONS.reactionnames: {} (no reactions)
+% OPTIONS.Nsim: 1000
+% OPTIONS.range: 1
+% OPTIONS.firstorder: 0 (use total effect)
+% OPTIONS.objectivefunction: 'relative'
+% OPTIONS.integrator: [] (default integrator settings)
+%
+% Output Arguments:
+% =================
+% If no output argument is specified, the result is plotted.
+% Otherwise, the output is a structure with the following fields:
+%
+% output.Nsim: Number of performed simulations
+% output.method: Name of the global sensitivity method
+% output.parameters: Considered parameters 
+% output.overallmeasure: Sensitivity indices for overall model output
+% output.overallparamranking: Parameter ranking regarding overall model output
+% output.singlecomponents: Names of the components, considered outputs
+% output.singlemeasure: Single sensitivity indices for all considered model outputs
+% output.singleparamranking: Parameter ranking for each considered model output
+
+% Information:
+% ============
+% Copyright (C) 2007 Ann Rundell, rundell@purdue.edu
+% Adapted for the SBTOOLBOX2 by Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+global Ncount 
+Ncount = 0;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE NON-NUMERIC INITIAL CONDITIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% just by replacing them
+model = SBconvertNonNum2NumIC(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF SBPD IS PRESENT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBPDpresent = ver('SBPD');
+if isempty(SBPDpresent),
+    error(sprintf('The SBPD package is not installed. For the global sensitivity analysis\nfunctions, however, this package is needed, since it considerably speeds up the computations\nThe SBPD can be downloaded from www.sbtoolbox2.org.'));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 2,
+    paramNames = SBparameters(model);
+    OPTIONS = [];
+elseif nargin == 3,
+    paramNames = varargin{1};
+    OPTIONS = [];
+elseif nargin == 4,
+    paramNames = varargin{1};
+    OPTIONS = varargin{2};
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DEFAULT OPTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+statenames = SBstates(model);
+variablenames = {};
+reactionnames = {};
+Nsim = 1000;
+range = 1;
+firstorder = 0;
+integratoroptions = [];
+objectivefunction = 'relative';
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try statenames = OPTIONS.statenames; catch, end
+try variablenames = OPTIONS.variablenames; catch, end
+try reactionnames = OPTIONS.reactionnames; catch, end
+try Nsim = OPTIONS.Nsim; catch, end
+try range = OPTIONS.range; catch, end
+try firstorder = OPTIONS.firstorder; catch, end
+try integratoroptions = OPTIONS.integrator; catch, end
+try objectivefunction = OPTIONS.objectivefunction; catch, end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS objecticefunction CHOICE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp(objectivefunction,'relative'),
+    objectivefunction = 'rel_sensglobaldefaultobjectiveSB';
+elseif strcmp(objectivefunction,'absolute'),
+    objectivefunction = 'abs_sensglobaldefaultobjectiveSB';
+else
+    % user defined objective functions
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET INDICES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+stateindices = stateindexSB(model,statenames);
+variableindices = variableindexSB(model,variablenames);
+reactionindices = reactionindexSB(model,reactionnames);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% MAKE MEX MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[MEXmodel, MEXmodelfullpath] = makeTempMEXmodelSBPD(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GENERATE NOMINAL SOLUTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+paramValuesNominal = SBparameters(model,paramNames);
+nomsimdata = SBPDsimulate(MEXmodel,timevector,SBinitialconditions(model),paramNames,paramValuesNominal,integratoroptions);
+Ncount = Ncount + 1;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK FOR ZERO NOMINAL PARAMETERS and exclude them from the analysis
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+indexZero = find(paramValuesNominal == 0);
+if ~isempty(indexZero),
+    text = sprintf('%s, ',paramNames{indexZero});
+    disp(sprintf('Some parameters have nominal values of zero. They are excluded from the analysis.\nParameters: %s\n',text(1:end-2)));
+    paramValuesNominal(indexZero) = [];
+    paramNames = paramNames(setdiff(1:length(paramNames),indexZero));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% NUMBERS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+nrparam = length(paramNames); 
+n_base = ceil(Nsim/nrparam); % base number of simulations so total number of model evals ~ Nsim
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INITIALIZATION 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output = [];
+c_out_1 = [];
+c_out_t = [];
+
+% compute objective function outputs for base and complementary parameter sets
+NR_FAILED = 0;
+i = 1;
+
+while i<=n_base,
+    disp(sprintf('Running: %d / %d',i,n_base));
+
+    %Determine parameter space for compuations
+    %random sampling of parameter space
+    randorder1 = 2*range*(rand(1,nrparam)-0.5);
+    randorder2 = 2*range*(rand(1,nrparam)-0.5);
+    PS = paramValuesNominal(:)'.*10.^randorder1;
+    comp_PS = paramValuesNominal(:)'.*10.^randorder2;
+    try
+        tic;
+        output(i,:)=feval(objectivefunction,MEXmodel,timevector,paramNames,PS,SBinitialconditions(model),nomsimdata,stateindices,variableindices,reactionindices,integratoroptions);
+        deltaT_ = toc;
+        if i == 1,
+            disp(sprintf('SOBOL: Approximate time for analysis: %d minutes',ceil(deltaT_*n_base*(1+nrparam*2)/60)));
+        end
+        for j = 1:nrparam
+            %c_out_1:  use to compute 1st order sensitivity indices
+            paramValuesPerturbed = [comp_PS(1:j-1),PS(j),comp_PS(j+1:nrparam)];  %use complementary parameter set for all but pj
+            x = feval(objectivefunction,MEXmodel,timevector,paramNames,paramValuesPerturbed,SBinitialconditions(model),nomsimdata,stateindices,variableindices,reactionindices,integratoroptions);
+            if sum(sum(isnan(x))) ~= 0,
+                error('NaN');
+            end
+            c_out_1(i,:,j)= x;
+            %c_out_t:  use to compute total effects sensitivity indices
+            paramValuesPerturbed = [PS(1:j-1),comp_PS(j),PS(j+1:nrparam)];  %use complementary parameter set for pj
+            x = feval(objectivefunction,MEXmodel,timevector,paramNames,paramValuesPerturbed,SBinitialconditions(model),nomsimdata,stateindices,variableindices,reactionindices,integratoroptions);
+            if sum(sum(isnan(x))) ~= 0,
+                error('NaN');
+            end
+            c_out_t(i,:,j) = x;
+        end
+        i = i+1;
+    catch
+        disp('Simulation failed due to random parameter settings. Trying new point.');
+        NR_FAILED = NR_FAILED + 1;
+        if NR_FAILED > Nsim/5,
+            error('Simulation failed to often. Please consider a reduction of the ''range'' option.');
+        end 
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% compute variances
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+n_out = size(output,2);  %size of output of objective function
+f0 = zeros(1,n_out);  % integral of model output
+D=zeros(1,n_out); % total variance
+%monte carlo integrations to estimate integral functions
+for i = 1:n_base
+    f0 = f0+output(i,:)/n_base;  % estiamte integral of model output
+    D = D+output(i,:).^2/n_base; % start computation of total variance of model output
+end
+D=D-f0.^2;
+Dj=ones(nrparam,1)*D;% partial variances associated with parameter j
+Dtotj=zeros(nrparam,n_out); % total partial variance associated with parameter j
+for i = 1:n_base
+    for j = 1:nrparam
+        Dj(j,:)=Dj(j,:)-(output(i,:)-c_out_1(i,:,j)).^2/(2*n_base);  %start computation of partial variances
+        Dtotj(j,:)=Dtotj(j,:)+(output(i,:)-c_out_t(i,:,j)).^2/(2*n_base); %total variance due to pj
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% compute sensitivity indices from variances
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+components = {statenames{:}, variablenames{:}, reactionnames{:}};
+% take care of zero elements in D by deleting corresponding single components
+D(find(D==0)) = 1; % just use a one, since it is a non-sensitive output anyway. alternatively remove it:
+% if ~isempty(zeroindices),
+%     text = sprintf('%s, ',components{zeroindices});
+%     disp(sprintf('The following components are removed from consideration (not affected by param changes):\n%s',text(1:end-2)));
+%     components = components(setdiff(1:length(components),zeroindices));
+%     Dj(:,zeroindices) = [];
+%     Dtotj(:,zeroindices) = [];
+%     D(zeroindices) = [];
+% end
+Sob_1 = Dj./(ones(nrparam,1)*D);  %first order
+Sob_t = Dtotj./(ones(nrparam,1)*D);  % total effect
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% sort sensitivity rankings
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% rank_Sob_1j: sorted Sobol first order rankings in terms of ascending magnitude
+% rank_Sob_1jp: paramNames ranked in assending order via Sobol first order values
+[rank_Sob_1 rank_Sob_1p] = sort(abs(Sob_1),1,'descend');
+% rank_Sob_tj: sorted Sobol total effect rankings in terms of ascending magnitude
+% rank_Sob_tjp: paramNames ranked in assending order via Sobol total effect values
+[rank_Sob_t rank_Sob_tp] = sort(abs(Sob_t),1,'descend');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE OUTPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output = [];
+output.Nsim = Ncount;
+if firstorder == 1, output.method = 'SOBOL First Order';
+else output.method = 'SOBOL Total Effect'; end
+output.parameters = paramNames(:)';
+if firstorder == 1, output.overallmeasure = Sob_1(:,end);
+else output.overallmeasure = Sob_t(:,end); end
+if firstorder == 1, output.overallparamranking = rank_Sob_1p(:,end);
+else output.overallparamranking = rank_Sob_tp(:,end); end
+output.singlecomponents = components;
+if firstorder == 1, output.singlemeasure = Sob_1(:,1:end-1);
+else output.singlemeasure = Sob_t(:,1:end-1); end
+if firstorder == 1, output.singleparamranking = rank_Sob_1p(:,1:end-1);
+else output.singleparamranking = rank_Sob_tp(:,1:end-1); end
+
+% generate plotting datastructure (for SBplot2)
+datastruct = [];
+datastruct.name = sprintf('Global Sensitivities: %s method',output.method);
+datastruct.xnames = output.parameters;
+datastruct.ynames = {'OVERALL MEASURE', output.singlecomponents{:}};    % cell-array with names of y-axis data
+datastruct.data =  [output.overallmeasure output.singlemeasure]'; %  matrix with y-axis data in rows and x-axis data in columns
+datastruct.title = sprintf('Global Sensitivities: %s method',output.method);
+datastruct.xlabel = 'Parameters';
+datastruct.xaxistitle = 'X';
+datastruct.yaxistitle = 'Y';
+% add it to the output variable
+output.plotdatastruct = datastruct;
+
+if nargout == 1,
+    varargout{1} = output;
+elseif nargout == 0,
+    % Plot the sensitivities using SBplot2
+    SBplot2(datastruct)
+else
+    error('Incorrect number of output arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DELETE MEX MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+clear mex;
+delete(MEXmodelfullpath);
+clear global Ncount
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/SBsensglobalwals.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/SBsensglobalwals.m
new file mode 100644
index 0000000000000000000000000000000000000000..81a2c9511fc8e58ff6661a8f7887c35c89d1a349
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/SBsensglobalwals.m
@@ -0,0 +1,317 @@
+function [varargout] = SBsensglobalwals(model,timevector,varargin)
+% Global sensitivity analysis method: WALS (weighted average of local
+% sensitivities)
+%
+% For more information see:
+%
+% Y. Zheng and A. Rundell (2006) Comparative study of parameter sensitivity
+% analyses of the TCR-activated Erk-MAPK signalling pathway, IEE
+% Proc.-Syst. Biol., Vol. 153, No. 4, 201-211
+%
+% Bentele, M., Lavrik, I., Ulrich, M., St��er, S., Heermann, D.W.,
+% Kalthoff, H., Krammer, P.H., and Eils, R. (2004) Mathematical modeling
+% reveals threshold mechanism in CD95-induced apoptosis, J. Cell
+% Biol., 166, (6), pp. 839�851
+%
+% USAGE:
+% ======
+% SBsensglobalwals(model,timevector)
+% SBsensglobalwals(model,timevector,paramNames)
+% SBsensglobalwals(model,timevector,paramNames,OPTIONS)
+% [output] = SBsensglobalwals(model,timevector)
+% [output] = SBsensglobalwals(model,timevector,paramNames)
+% [output] = SBsensglobalwals(model,timevector,paramNames,OPTIONS)
+%
+% model: SBmodel to perform the global sensitivity analysis for
+% timevector: vector of timeinstants to consider
+% paramNames: cell-array with names of the parameters to consider
+% OPTIONS: structure with optional settings:
+%   OPTIONS.statenames: cell-array with state names which to consider as
+%       model outputs
+%   OPTIONS.variablenames: cell-array with variable names which to consider
+%       as model outputs
+%   OPTIONS.reactionnames: cell-array with reaction names which to consider
+%       as model outputs
+%   OPTIONS.Nsim: Number of simulation to carry out (approximate value)
+%   OPTIONS.range: Order of magnitude of parameter perturbations
+%   OPTIONS.deltaPert: relative perturbation for determining local
+%       sensitivities. If a parameters nominal value is zero a warning will 
+%       appear.
+%   OPTIONS.objectivefunction: ='relative': the differences between nominal
+%       and perturbed model are normalized to represent relative changes in
+%       each considered variable. ='absolute': no normalization is done.
+%       Alternatively, the user can provide the name for an own objective
+%       function to use. As template you can have a look at the two
+%       objectivefunctions in the folder:
+%       SBTOOLBOX2/analysis/globalparametersensitivity/auxiliary
+%   OPTIONS.integrator: Structure with optional settings for the integrator
+%
+% DEFAULT VALUES:
+% ===============
+% paramNames: Consider all parameters in the model
+% OPTIONS.statenames: Consider all states in the model
+% OPTIONS.variablenames: {} (no variables)
+% OPTIONS.reactionnames: {} (no reactions)
+% OPTIONS.Nsim: 1000
+% OPTIONS.range: 1
+% OPTIONS.deltaPert: 0.02 (2 percent)
+% OPTIONS.objectivefunction: 'relative'
+% OPTIONS.integrator: [] (default integrator settings)
+%
+% Output Arguments:
+% =================
+% If no output argument is specified, the result is plotted.
+% Otherwise, the output is a structure with the following fields:
+%
+% output.Nsim: Number of performed simulations
+% output.method: Name of the global sensitivity method
+% output.parameters: Considered parameters 
+% output.overallmeasure: Sensitivity indices for overall model output
+% output.overallparamranking: Parameter ranking regarding overall model output
+% output.singlecomponents: Names of the components, considered outputs
+% output.singlemeasure: Single sensitivity indices for all considered model outputs
+% output.singleparamranking: Parameter ranking for each considered model output
+
+% Information:
+% ============
+% Copyright (C) 2007 Ann Rundell, rundell@purdue.edu
+% Adapted for the SBTOOLBOX2 by Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+global Ncount 
+Ncount = 0;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE NON-NUMERIC INITIAL CONDITIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% just by replacing them
+model = SBconvertNonNum2NumIC(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF SBPD IS PRESENT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBPDpresent = ver('SBPD');
+if isempty(SBPDpresent),
+    error(sprintf('The SBPD package is not installed. For the global sensitivity analysis\nfunctions, however, this package is needed, since it considerably speeds up the computations\nThe SBPD can be downloaded from www.sbtoolbox2.org.'));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 2,
+    paramNames = SBparameters(model);
+    OPTIONS = [];
+elseif nargin == 3,
+    paramNames = varargin{1};
+    OPTIONS = [];
+elseif nargin == 4,
+    paramNames = varargin{1};
+    OPTIONS = varargin{2};
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DEFAULT OPTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+statenames = SBstates(model);
+variablenames = {};
+reactionnames = {};
+Nsim = 1000;
+range = 1;
+deltaPert = 0.02;
+integratoroptions = [];
+objectivefunction = 'relative';
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try statenames = OPTIONS.statenames; catch, end
+try variablenames = OPTIONS.variablenames; catch, end
+try reactionnames = OPTIONS.reactionnames; catch, end
+try Nsim = OPTIONS.Nsim; catch, end
+try range = OPTIONS.range; catch, end
+try deltaPert = OPTIONS.deltaPert; catch, end
+try integratoroptions = OPTIONS.integrator; catch, end
+try objectivefunction = OPTIONS.objectivefunction; catch, end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS objecticefunction CHOICE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp(objectivefunction,'relative'),
+    objectivefunction = 'rel_sensglobaldefaultobjectiveSB';
+elseif strcmp(objectivefunction,'absolute'),
+    objectivefunction = 'abs_sensglobaldefaultobjectiveSB';
+else
+    % user defined objective functions
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET INDICES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+stateindices = stateindexSB(model,statenames);
+variableindices = variableindexSB(model,variablenames);
+reactionindices = reactionindexSB(model,reactionnames);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% MAKE MEX MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[MEXmodel, MEXmodelfullpath] = makeTempMEXmodelSBPD(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GENERATE NOMINAL SOLUTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+paramValuesNominal = SBparameters(model,paramNames);
+nomsimdata = SBPDsimulate(MEXmodel,timevector,SBinitialconditions(model),paramNames,paramValuesNominal,integratoroptions);
+Ncount = Ncount + 1;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK FOR ZERO NOMINAL PARAMETERS and exclude them from the analysis
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+indexZero = find(paramValuesNominal == 0);
+if ~isempty(indexZero),
+    text = sprintf('%s, ',paramNames{indexZero});
+    disp(sprintf('Some parameters have nominal values of zero. They are excluded from the analysis.\nParameters: %s\n',text(1:end-2)));
+    paramValuesNominal(indexZero) = [];
+    paramNames = paramNames(setdiff(1:length(paramNames),indexZero));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% NUMBERS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+nrparam = length(paramNames);
+nLocal = ceil(Nsim/nrparam); 
+nSensVariables = length(stateindices) + length(variableindices) + length(reactionindices) + 1;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INITIALIZATION 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+CSSSE = zeros(nLocal,1);
+WALSmeasure = zeros(nrparam,nSensVariables);
+localSensitivities = zeros(nLocal,nrparam,nSensVariables);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% RUNNING THE SENSITIVITY ANALYSIS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+NR_FAILED = 0;
+k = 1;
+while k<=nLocal,
+    % Determine a random point in the global parameter space and perform a
+    % local sensitivity analysis around it.
+    % Use a logarithmic distribution for randomizing the global point.
+    % 1) Generate nrparam random values between -range and range
+    randorder = 2*range*(rand(1,nrparam)-0.5);
+    % 2) Generate the global point around which to perform the local
+    % analysis
+    globalparamValues = paramValuesNominal(:)'.*10.^randorder;
+    % 3) Generate nominal solution around the global point 
+    try
+        tic;
+        nomResult = feval(objectivefunction,MEXmodel,timevector,paramNames,globalparamValues,SBinitialconditions(model),nomsimdata,stateindices,variableindices,reactionindices,integratoroptions);
+        deltaT_ = toc;
+        if k == 1,
+            disp(sprintf('WALS: Approximate time for analysis: %d minutes',ceil(deltaT_*nLocal*(1+nrparam)/60)));
+        end
+        CSSSE(k) = nomResult(end);
+        for k2 = 1:nrparam;
+            % Do a local sensitivity analysis around the random point
+            paramValuesPerturbed = globalparamValues;
+            % Do a relative perturbation in one parameter
+            paramValuesPerturbed(k2) = paramValuesPerturbed(k2)*(1+deltaPert);
+            if paramValuesPerturbed(k2) == 0,
+                disp(sprintf('The nominal value of parameter ''%s'' is zero! The relative perturbation has no effect.',paramNames{k2}));
+            end
+            % Determine the perturbed result
+            pertResult = feval(objectivefunction,MEXmodel,timevector,paramNames,paramValuesPerturbed,SBinitialconditions(model),nomsimdata,stateindices,variableindices,reactionindices,integratoroptions);
+            % Calculate the local sensitivity values
+            % But first check and handle zero nominal and perturbation results
+            % (happens in the case that a parameter has no effect on the
+            % considered model output)
+            indexzero = find(nomResult==0);
+            nomResultTemp = nomResult;
+            nomResultTemp(indexzero) = 1;
+            pertResultTemp = pertResult;
+            pertResultTemp(indexzero) = 1;
+            help = (pertResultTemp-nomResultTemp)./nomResultTemp/deltaPert;
+            localSensitivities(k,k2,:) = help;
+        end
+        k = k+1;
+    catch
+        disp('Simulation failed due to random parameter settings. Trying new point.');
+        NR_FAILED = NR_FAILED + 1;
+        if NR_FAILED > Nsim/5,
+            error('Simulation failed to often. Please consider a reduction of the ''range'' option.');
+        end
+    end
+end
+% Get the weight vector
+if min(CSSSE) ~= 0,
+    weight = exp(-CSSSE/(min(CSSSE)));
+else
+    % If the minimum CSSE is 0 then replace it by 1 (after all the divisor
+    % is pretty much arbitrary).
+    weight = exp(-CSSSE);
+end
+% Do the weighting of the local sensitivities using the above weights
+for k=1:nLocal
+    WALSmeasure = WALSmeasure + weight(k)*squeeze(localSensitivities(k,:,:));  
+end
+% Do the ordering of the results
+[dummy ordering] = sort(abs(WALSmeasure),1,'descend');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE OUTPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output = [];
+output.Nsim = Ncount;
+output.method = 'WALS';
+output.parameters = paramNames(:)';
+output.overallmeasure = WALSmeasure(:,end);
+output.overallparamranking = ordering(:,end);
+output.singlecomponents = {statenames{:}, variablenames{:}, reactionnames{:}};
+output.singlemeasure = WALSmeasure(:,1:end-1);
+output.singleparamranking = ordering(:,1:end-1);
+
+% generate plotting datastructure (for SBplot2)
+datastruct = [];
+datastruct.name = 'Global Sensitivities: WALS method';
+datastruct.xnames = output.parameters;
+datastruct.ynames = {'OVERALL MEASURE', output.singlecomponents{:}};    % cell-array with names of y-axis data
+datastruct.data =  [output.overallmeasure output.singlemeasure]'; %  matrix with y-axis data in rows and x-axis data in columns
+datastruct.title = 'Global Sensitivities: WALS method';
+datastruct.xlabel = 'Parameters';
+datastruct.xaxistitle = 'X';
+datastruct.yaxistitle = 'Y';
+% add it to the output variable
+output.plotdatastruct = datastruct;
+
+if nargout == 1,
+    varargout{1} = output;
+elseif nargout == 0,
+    % Plot the sensitivities using SBplot2
+    SBplot2(datastruct)
+else
+    error('Incorrect number of output arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DELETE MEX MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+clear mex;
+delete(MEXmodelfullpath);
+clear global Ncount
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/abs_sensglobaldefaultobjectiveSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/abs_sensglobaldefaultobjectiveSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..53a53b5dadd22b329b716ce1a357653fc4e5888a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/abs_sensglobaldefaultobjectiveSB.m
@@ -0,0 +1,32 @@
+function [rawsensitivities] = abs_sensglobaldefaultobjectiveSB(MEXmodel,timevector,paramNames,paramValues,ICs,nomsimdata,stateindices,variableindices,reactionindices,integratoroptions)
+% abs_sensglobaldefaultobjectiveSB: Default global sensitivity analysis
+% objective function. This function determines the sqrt of the sum of
+% ABSOLUTE squared errors (SSSE), between simulations of the nominal model
+% and the perturbed model.
+%
+% The output argument contains both the SSSEs of the Single components (SSSSE)
+% (states, variables, and reactions) and a Combined version (CSSSE), which 
+% appears as last element in the output vector.
+
+global Ncount
+Ncount = Ncount + 1;
+
+% Simulate the model for given perturbations in the parameters
+pertsimdata = SBPDsimulate(MEXmodel,timevector,ICs,paramNames,paramValues,integratoroptions);
+% Get the nominal and perturbed elements for comparison
+nomstatevalues = nomsimdata.statevalues(:,stateindices);
+pertstatevalues = pertsimdata.statevalues(:,stateindices);
+nomvariablevalues = nomsimdata.variablevalues(:,variableindices);
+pertvariablevalues = pertsimdata.variablevalues(:,variableindices);
+nomreactionvalues = nomsimdata.reactionvalues(:,reactionindices);
+pertreactionvalues = pertsimdata.reactionvalues(:,reactionindices);
+allnomvalues = [nomstatevalues nomvariablevalues nomreactionvalues];
+allpertvalues = [pertstatevalues pertvariablevalues pertreactionvalues];
+% get the absolute differences
+absolutevalues = allpertvalues-allnomvalues;
+% get the squared and summed differences
+SSSSE = sqrt(sum((absolutevalues).^2));
+CSSSE = sqrt(sum(sum((absolutevalues).^2))); 
+% return the data
+rawsensitivities = [SSSSE CSSSE]; 
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/rel_sensglobaldefaultobjectiveSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/rel_sensglobaldefaultobjectiveSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..a138d1d6c1671afd17ad7899c734b2886536f4b9
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/rel_sensglobaldefaultobjectiveSB.m
@@ -0,0 +1,40 @@
+function [rawsensitivities] = rel_sensglobaldefaultobjectiveSB(MEXmodel,timevector,paramNames,paramValues,ICs,nomsimdata,stateindices,variableindices,reactionindices,integratoroptions)
+% rel_sensglobaldefaultobjectiveSB: Default global sensitivity analysis
+% objective function. This function determines the sqrt of the sum of
+% RELATIVE squared errors (SSSE), between simulations of the nominal model
+% and the perturbed model.
+%
+% The output argument contains both the SSSEs of the Single components (SSSSE)
+% (states, variables, and reactions) and a Combined version (CSSSE), which 
+% appears as last element in the output vector.
+
+global Ncount
+Ncount = Ncount + 1;
+
+% Simulate the model for given perturbations in the parameters
+pertsimdata = SBPDsimulate(MEXmodel,timevector,ICs,paramNames,paramValues,integratoroptions);
+% Get the nominal and perturbed elements for comparison
+nomstatevalues = nomsimdata.statevalues(:,stateindices);
+pertstatevalues = pertsimdata.statevalues(:,stateindices);
+nomvariablevalues = nomsimdata.variablevalues(:,variableindices);
+pertvariablevalues = pertsimdata.variablevalues(:,variableindices);
+nomreactionvalues = nomsimdata.reactionvalues(:,reactionindices);
+pertreactionvalues = pertsimdata.reactionvalues(:,reactionindices);
+allnomvalues = [nomstatevalues nomvariablevalues nomreactionvalues];
+allpertvalues = [pertstatevalues pertvariablevalues pertreactionvalues];
+% get the relative differences
+% For this we need to handle zero nominal values. We do that by replacing
+% these zero nominal values by "1". The rational is that zero nominal
+% values happen 
+%   a) due to initial conditions (but then also the pert values are 0)
+%   b) an output is always zero (but then so are the pert values)
+%   c) well and otherwise it will become an approximation ...
+allnomvaluesNonZero = allnomvalues;
+allnomvaluesNonZero(find(allnomvalues==0)) = 1;
+relativevalues = (allpertvalues-allnomvalues)./allnomvaluesNonZero;
+% get the squared and summed differences
+SSSSE = sqrt(sum((relativevalues).^2));
+CSSSE = sqrt(sum(sum((relativevalues).^2))); 
+% return the data
+rawsensitivities = [SSSSE CSSSE]; 
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/LHS.pdf b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/LHS.pdf
new file mode 100644
index 0000000000000000000000000000000000000000..311bc9d604809dcab477b384d614a0709dd97548
Binary files /dev/null and b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/LHS.pdf differ
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/contents.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/contents.m
new file mode 100644
index 0000000000000000000000000000000000000000..4d1a52f8f3878df17fc844204663f449b1f3067e
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/contents.m
@@ -0,0 +1,30 @@
+%   Sampling utilities
+%   Contents
+%
+%   Multivariate distribution, no correlation
+%   latin_hs    : latin hypercube sampling (LHS) of multivariate normal
+%                   distribution
+%   lhsu        : LHS of multivariate uniform distribution
+%   lhs_empir   : LHS of multivariate empirical distribution
+%
+%   Multivariate distribution, with correlation
+%   lhs_iman    : LHS multivariate normal distribution, method of Iman &
+%                   Conover
+%   lhs_iman_n  : LHS multivariate normal distribution, method of Iman &
+%                   Conover, for large correlation matrix 
+%   lhs_stein   : LHS multivariate normal distribution, method of Stein
+%   ransamp     : random sampling from multivariate normal distribution
+%   lhs_empirco : LHS of multivariate empirical distribution
+%
+%   utilities:
+%   ltqnorm     : inverse of normal CDF (from Peter J. Acklam)
+%                   http://home.online.no/~pjacklam/notes/invnorm/index.html
+%   mchol       : modified Cholesky factorization for matrices that are not 
+%                 quite positive definite (from Brian Borchers)
+%   ranking     : ranking of data
+%   rank_corr   : inducing rank correlation 
+%
+%   test_sampling   : test the sampling utilities
+%   test_sampling2  : example of sampling with corr matrix that is not positive definite
+%
+%   Budiman (2004)  budiman@acss.usyd.edu.au    Revised: Nov 2004
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/latin_hs.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/latin_hs.m
new file mode 100644
index 0000000000000000000000000000000000000000..a078ae929801db161f9b2ba20d9024e280b6df0d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/latin_hs.m
@@ -0,0 +1,31 @@
+function s=latin_hs(xmean,xsd,nsample,nvar)
+% s=latin_hs(xmean,xsd,nsample,nvar)
+% LHS from normal distribution, no correlation
+% method of Stein
+% Stein, M. 1987. Large Sample Properties of Simulations Using Latin Hypercube Sampling. 
+%                 Technometrics 29:143-151
+% Input:
+%   xmean   :  mean of data (1,nvar)
+%   xsd     : std.dev of data (1,nvar)
+%   nsample : no. of samples
+%   nvar    : no. of variables
+% Output:
+%   s       : random sample (nsample,nvar)
+%
+% Uses Peter Acklam inverse normal CDF
+%
+%   Budiman (2003)
+% References:
+% Iman, R. L., and W. J. Conover. 1980. Small Sample Sensitivity Analysis Techniques for Computer Models, 
+% with an Application to Risk Assessment.Communications in Statistics: Theory and Methods A9: 1749-1874
+% McKay, M. D., W. J. Conover and R. J. Beckman. 1979.A Comparison of Three Methods for Selecting Values
+% of Input Variables in the Analysis of Output from a Computer Code. Technometrics 21: 239-245
+%
+ran=rand(nsample,nvar);
+s=zeros(nsample,nvar);
+% method of Stein
+for j=1: nvar
+   idx=randperm(nsample);
+   P=(idx'-ran(:,j))/nsample;       % probability of the cdf
+   s(:,j) = xmean(j) + ltqnorm(P).* xsd(j); % this can be replaced by any inverse distribution function
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/lhs_empir.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/lhs_empir.m
new file mode 100644
index 0000000000000000000000000000000000000000..5923b3f160ead11143407df11a7499c9e3e03d18
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/lhs_empir.m
@@ -0,0 +1,19 @@
+function s=lhs_empir(data,nsample)
+% s=lhs_empir(data,nsample)
+% perform lhs on multivariate empirical distribution
+%   assume no correlation
+% Input:
+%   data    : data matrix (ndata,nvar)
+%   nsample : no. of samples
+% Output:
+%   s       : random sample (nsample,nvar)
+%   Budiman (2003)
+
+[m,nvar]=size(data);
+ran=rand(nsample,nvar);
+s=zeros(nsample,nvar);
+for j=1: nvar
+   idx=randperm(nsample);
+   P=((idx'-ran(:,j))/nsample).*100;
+   s(:,j)=prctile(data(:,j),P);
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/lhs_empirco.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/lhs_empirco.m
new file mode 100644
index 0000000000000000000000000000000000000000..f218551b2de90d2476777deb112452e67ccc3e36
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/lhs_empirco.m
@@ -0,0 +1,24 @@
+function s=lhs_empirco(data,nsample)
+% s=lhs_empirco(data,nsample)
+% perform lhs on multivariate empirical distribution
+% with correlation
+% Input:
+%   data    : data matrix (ndata,nvar)
+%   nsample : no. of samples
+% Output:
+%   s       : random sample (nsample,nvar)
+%   Budiman (2003)
+
+[m,nvar]=size(data);
+corr=corrcoef(data);
+rc=rank_corr(corr,nsample); % induce correlation
+  
+for j=1:nvar
+    r=rc(:,j);
+    % draw random no.
+    u=rand(nsample,1);
+    % calc. percentile
+    p=((r-u)./nsample).*100;
+    % inverse from empirical distribution
+    s(:,j)=prctile(data(:,j),p);
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/lhs_iman.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/lhs_iman.m
new file mode 100644
index 0000000000000000000000000000000000000000..714d456162eabde2f4b76e729364e8b36c091cd0
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/lhs_iman.m
@@ -0,0 +1,53 @@
+function z=lhs_iman(xmean,xsd,corr,nsample,ntry)
+% z=lhs_iman(xmean,xsd,corr,nsample,nloop)
+% LHS with correlation, normal distribution 
+% method of Iman & Conover
+% Iman, R. L., and W. J. Conover. 1982. A Distribution-free Approach to Inducing Rank Correlation 
+%      Among Input Variables. Communications in Statistics B 11:311-334
+%
+% Input:
+%   xmean   : mean of data (1,nvar)
+%   xsd     : std.dev of data (1,nvar)
+%   corr    : correlation matrix of the variables (nvar,nvar)
+%   nsample : no. of samples
+%   ntry    : optional, no of trial to get a close correlation matrix
+% Output:
+%   z       : random sample (nsample,nvar)
+%   Budiman (2004)
+
+nvar=length(xmean);
+
+if(nargin==4), ntry=1; end;
+
+% induce data with correlation
+P = chol(corr);
+P=P';
+
+xm=zeros(1,nvar);
+xs=ones(1,nvar);
+R=latin_hs(xm,xs,nsample,nvar);
+T = corrcoef(R);
+Q=chol(T);
+Q=Q';
+    
+S = P * inv(Q);
+RB= R*S';
+
+amin=realmax;
+for il=1:ntry
+    for j=1:nvar    
+        % rank RB
+        [r,id]=ranking(RB(:,j));
+        % sort R
+        [RS,id]=sort(R(:,j));
+        % permute RS so has the same rank as RB
+        z(:,j) = RS(r).*xsd(j)+xmean(j); 
+    end
+    ae=sum(sum(abs(corrcoef(z)-corr)));
+    if(ae<amin),
+        zb=z;
+        amin=ae;
+    end;
+end
+
+z=zb;
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/lhs_iman_n.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/lhs_iman_n.m
new file mode 100644
index 0000000000000000000000000000000000000000..7fb60b32ac9c7cee724412562e23802d7da98b2f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/lhs_iman_n.m
@@ -0,0 +1,57 @@
+function z=lhs_iman_n(xmean,xsd,corr,nsample,ntry)
+% z=lhs_iman_n(xmean,xsd,corr,nsample,ntry)
+% LHS with correlation, normal distribution 
+% Method of Iman & Conover
+% using mchol for Cholesky decomposition so that corr. matrix is positive definite  
+% 
+% Iman, R. L., and W. J. Conover. 1982. A Distribution-free Approach to Inducing Rank Correlation 
+%      Among Input Variables. Communications in Statistics B 11:311-334
+%
+% Input:
+%   xmean   : mean of data (1,nvar)
+%   xsd     : std.dev of data (1,nvar)
+%   corr    : correlation matrix of the variables (nvar,nvar)
+%   nsample : no. of samples
+%   ntry    : optional, no of trial to get a close correlation matrix
+% Output:
+%   z       : random sample (nsample,nvar)
+%   Budiman (2004)
+% using mchol from Brian Borchers
+nvar=length(xmean);
+
+if(nargin==4), ntry=1; end;
+
+% induce data with correlation
+[L,D,E]=mchol(corr);  
+%P = chol(corr+E)';
+P=L*sqrt(D);
+
+xm=zeros(1,nvar);
+xs=ones(1,nvar);
+R=latin_hs(xm,xs,nsample,nvar);
+T = corrcoef(R);
+[L,D,E]=mchol(T);  
+%Q=chol(T+E)';
+Q=L*sqrt(D);
+   
+S = P * inv(Q);
+RB= R*S';
+
+amin=realmax;
+for il=1:ntry
+    for j=1:nvar    
+        % rank RB
+        [r,id]=ranking(RB(:,j));
+        % sort R
+        [RS,id]=sort(R(:,j));
+        % permute RS so has the same rank as RB
+        z(:,j) = RS(r).*xsd(j)+xmean(j); 
+    end
+    ae=sum(sum(abs(corrcoef(z)-corr)));
+    if(ae<amin),
+        zb=z;
+        amin=ae;
+    end;
+end
+
+z=zb;
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/lhs_stein.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/lhs_stein.m
new file mode 100644
index 0000000000000000000000000000000000000000..300355e032aa204c6fc8bf36b8fd4e67662a705d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/lhs_stein.m
@@ -0,0 +1,41 @@
+function z=lhs_stein(xmean,xsd,corr,nsample,ntry)
+% z=lhs_stein(xmean,xsd,corr,nsample)
+% LHS with correlation, normal distribution
+% method of Stein (1987)
+% Stein, M. 1987. Large Sample Properties of Simulations Using Latin Hypercube Sampling. 
+%                 Technometrics 29:143-151
+% Input:
+%   xmean   : mean of data (1,nvar)
+%   xsd     : std.dev of data (1,nvar)
+%   corr    : correlation matrix of the variables (nvar,nvar)
+%   nsample : no. of samples
+%   ntry    : optional, no of trial to get a close correlation matrix
+% Output:
+%   z       : random sample (nsample,nvar)
+%   Budiman (2004)
+
+nvar=length(xmean);
+if(nargin==4), ntry=1; end;
+
+rc=rank_corr(corr,nsample); % calculate rank correlation
+
+amin=realmax;
+for il=1:ntry
+    for j=1:nvar
+        % rank correlation
+        r=rc(:,j);
+        % draw random no.
+        u=rand(nsample,1);
+        % calc. probability
+        p=(r-u)./nsample;
+        % inverse from normal distribution
+        z(:,j)=(ltqnorm(p).*xsd(j))+xmean(j);    
+    end
+    ae=sum(sum(abs(corrcoef(z)-corr)));
+    if(ae<amin),
+        zb=z;
+        amin=ae;
+    end;
+end
+
+z=zb;
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/lhsu.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/lhsu.m
new file mode 100644
index 0000000000000000000000000000000000000000..8f8cc856fceac9fa355f06b34cfa8fa4fa13d3b4
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/lhsu.m
@@ -0,0 +1,19 @@
+function s=lhsu(xmin,xmax,nsample)
+% s=lhsu(xmin,xmax,nsample)
+% LHS from uniform distribution
+% Input:
+%   xmin    : min of data (1,nvar)
+%   xmax    : max of data (1,nvar)
+%   nsample : no. of samples
+% Output:
+%   s       : random sample (nsample,nvar)
+%   Budiman (2003)
+
+nvar=length(xmin);
+ran=rand(nsample,nvar);
+s=zeros(nsample,nvar);
+for j=1: nvar
+   idx=randperm(nsample);
+   P =(idx'-ran(:,j))/nsample;
+   s(:,j) = xmin(j) + P.* (xmax(j)-xmin(j));
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/ltqnorm.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/ltqnorm.m
new file mode 100644
index 0000000000000000000000000000000000000000..fbedf414d5b9f352fa442dd8dc1506daab17721f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/ltqnorm.m
@@ -0,0 +1,86 @@
+function z = ltqnorm(p)
+%LTQNORM Lower tail quantile for standard normal distribution.
+%
+%   Z = LTQNORM(P) returns the lower tail quantile for the standard normal
+%   distribution function.  I.e., it returns the Z satisfying Pr{X < Z} = P,
+%   where X has a standard normal distribution.
+%
+%   LTQNORM(P) is the same as SQRT(2) * ERFINV(2*P-1), but the former returns a
+%   more accurate value when P is close to zero.
+
+%   The algorithm uses a minimax approximation by rational functions and the
+%   result has a relative error less than 1.15e-9.  A last refinement by
+%   Halley's rational method is applied to achieve full machine precision.
+
+%   Author:      Peter J. Acklam
+%   Time-stamp:  2003-04-23 08:26:51 +0200
+%   E-mail:      pjacklam@online.no
+%   URL:         http://home.online.no/~pjacklam
+
+   % Coefficients in rational approximations.
+   a = [ -3.969683028665376e+01  2.209460984245205e+02 ...
+         -2.759285104469687e+02  1.383577518672690e+02 ...
+         -3.066479806614716e+01  2.506628277459239e+00 ];
+   b = [ -5.447609879822406e+01  1.615858368580409e+02 ...
+         -1.556989798598866e+02  6.680131188771972e+01 ...
+         -1.328068155288572e+01 ];
+   c = [ -7.784894002430293e-03 -3.223964580411365e-01 ...
+         -2.400758277161838e+00 -2.549732539343734e+00 ...
+         4.374664141464968e+00  2.938163982698783e+00 ];
+   d = [  7.784695709041462e-03  3.224671290700398e-01 ...
+          2.445134137142996e+00  3.754408661907416e+00 ];
+
+   % Define break-points.
+   plow  = 0.02425;
+   phigh = 1 - plow;
+
+   % Initialize output array.
+   z = zeros(size(p));
+
+   % Rational approximation for central region:
+   k = plow <= p & p <= phigh;
+   if any(k(:))
+      q = p(k) - 0.5;
+      r = q.*q;
+      z(k) = (((((a(1)*r+a(2)).*r+a(3)).*r+a(4)).*r+a(5)).*r+a(6)).*q ./ ...
+             (((((b(1)*r+b(2)).*r+b(3)).*r+b(4)).*r+b(5)).*r+1);
+   end
+
+   % Rational approximation for lower region:
+   k = 0 < p & p < plow;
+   if any(k(:))
+      q  = sqrt(-2*log(p(k)));
+      z(k) = (((((c(1)*q+c(2)).*q+c(3)).*q+c(4)).*q+c(5)).*q+c(6)) ./ ...
+             ((((d(1)*q+d(2)).*q+d(3)).*q+d(4)).*q+1);
+   end
+
+   % Rational approximation for upper region:
+   k = phigh < p & p < 1;
+   if any(k(:))
+      q  = sqrt(-2*log(1-p(k)));
+      z(k) = -(((((c(1)*q+c(2)).*q+c(3)).*q+c(4)).*q+c(5)).*q+c(6)) ./ ...
+             ((((d(1)*q+d(2)).*q+d(3)).*q+d(4)).*q+1);
+   end
+
+   % Case when P = 0:
+   z(p == 0) = -Inf;
+
+   % Case when P = 1:
+   z(p == 1) = Inf;
+
+   % Cases when output will be NaN:
+   k = p < 0 | p > 1 | isnan(p);
+   if any(k(:))
+      z(k) = NaN;
+   end
+
+   % The relative error of the approximation has absolute value less
+   % than 1.15e-9.  One iteration of Halley's rational method (third
+   % order) gives full machine precision.
+   k = 0 < p & p < 1;
+   if any(k(:))
+      e = 0.5*erfc(-z(k)/sqrt(2)) - p(k);          % error
+      u = e * sqrt(2*pi) .* exp(z(k).^2/2);        % f(z)/df(z)
+      %z(k) = z(k) - u;                             % Newton's method
+      z(k) = z(k) - u./( 1 + z(k).*u/2 );          % Halley's method
+   end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/mchol.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/mchol.m
new file mode 100644
index 0000000000000000000000000000000000000000..512368a7937d64ca2104b7ea77cdab9510247b99
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/mchol.m
@@ -0,0 +1,126 @@
+%
+%  [L,D,E,pneg]=mchol1(G)
+%
+%  Given a symmetric matrix G, find a matrix E of "small" norm and c
+%  L, and D such that  G+E is Positive Definite, and 
+%
+%      G+E = L*D*L'
+%
+%  Also, calculate a direction pneg, such that if G is not PD, then
+%
+%      pneg'*G*pneg < 0
+%
+%  Note that if G is PD, then the routine will return pneg=[]. 
+%
+%  Reference: Gill, Murray, and Wright, "Practical Optimization", p111.
+%  Author: Brian Borchers (borchers@nmt.edu)
+%
+function [L,D,E,pneg]=mchol(G)
+%
+%  n gives the size of the matrix.
+%
+n=size(G,1);
+%
+%  gamma, zi, nu, and beta2 are quantities used by the algorithm.  
+%
+gamma=max(diag(G));
+zi=max(max(G-diag(diag(G))));
+nu=max([1,sqrt(n^2-1)]);
+beta2=max([gamma, zi/nu, 1.0E-15]);
+%
+%  Initialize diag(C) to diag(G).
+%
+C=diag(diag(G));
+%
+%  Loop through, calculating column j of L for j=1:n
+%
+
+L=zeros(n);
+D=zeros(n);
+E=zeros(n);
+
+for j=1:n,
+    bb=[1:j-1];
+    ee=[j+1:n];
+
+    %
+    %  Calculate the jth row of L.  
+    %
+    if (j > 1),
+        L(j,bb)=C(j,bb)./diag(D(bb,bb))';
+    end;
+    %
+    %  Update the jth column of C.
+    %
+    if (j >= 2),
+        if (j < n), 
+            C(ee,j)=G(ee,j)-(L(j,bb)*C(ee,bb)')';
+        end;
+    else
+        C(ee,j)=G(ee,j);
+    end;
+    %
+    % Update theta. 
+    %
+    if (j == n)
+        theta(j)=0;
+    else
+        theta(j)=max(abs(C(ee,j)));
+    end;
+    %
+    %  Update D
+    %
+    D(j,j)=max([eps,abs(C(j,j)),theta(j)^2/beta2]');
+    %
+    % Update E.
+    %
+    E(j,j)=D(j,j)-C(j,j);
+
+    
+    %
+    %  Update C again...
+    % 
+    %%%%%%%% M.Zibulevsky: begin of changes, old version is commented %%%%%%%%%%%%%
+    
+    %for i=j+1:n,
+    %    C(i,i)=C(i,i)-C(i,j)^2/D(j,j);
+    %end;
+    
+    ind=[j*(n+1)+1 : n+1 : n*n]';
+    C(ind)=C(ind)-(1/D(j,j))*C(ee,j).^2;
+
+
+end;
+
+%
+% Put 1's on the diagonal of L
+%
+%for j=1:n,
+%    L(j,j)=1;
+%end;
+
+ind=[1 : n+1 : n*n]';
+L(ind)=1;
+
+%%%%%%%%%%%%%%%%%%%%%%%% M.Zibulevsky: end of changes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%
+%  if needed, find a descent direction.  
+%
+if ((nargout == 4) & (min(diag(C)) < 0.0))
+    [m,col]=min(diag(C));
+    rhs=zeros(n,1);
+    rhs(col)=1;
+    pneg=L'\rhs;
+else
+  pneg=[];
+end;
+
+
+return
+
+
+
+
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/rank_corr.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/rank_corr.m
new file mode 100644
index 0000000000000000000000000000000000000000..2caaba9ba0ac26a064882e1d595b1f2d5771c4d3
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/rank_corr.m
@@ -0,0 +1,38 @@
+function rc=rank_corr(corr,nsample)
+% rc=rank_corr(corr,nsample)
+% induce rank correlation
+% method of Iman & Conover
+% Iman, R. L., and W. J. Conover. 1982. A Distribution-free Approach to
+% Inducing Rank Correlation Among Input Variables.
+% Communications in Statistics B 11:311-334.
+% Input:
+%   corr    : correlation matrix of the variables (nvar,nvar)
+%   nsample : no. of samples
+% Output:
+%   rc       : rank (nsample,nvar)
+%   Budiman (2004)
+
+nvar=length(corr);
+
+% induce data with correlation
+xm=zeros(1,nvar);
+xs=ones(1,nvar);
+R=latin_hs(xm,xs,nsample,nvar);
+T = corrcoef(R);
+P = chol(corr)';
+Q = chol(T)';
+
+% use modified cholesky for corr matrix that is not quite positive definite
+%[L,D,E]=mchol(corr);  
+%P=L*sqrt(D);
+%[L,D,E]=mchol(T);  
+%Q=L*sqrt(D);
+
+S = P * inv(Q);
+RB= R*S';
+
+for j=1:nvar    
+    % rank RB
+    [r,id]=ranking(RB(:,j));
+    rc(:,j) = r; 
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/ranking.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/ranking.m
new file mode 100644
index 0000000000000000000000000000000000000000..beb163264fd0206f8c55a930a49597a33e62d39c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/ranking.m
@@ -0,0 +1,12 @@
+function [r,i]=ranking(x)   
+% [r,i]=ranking(x)   
+% Ranking of a vector  
+% input:
+%   x   : vector (nrow,1)  
+% output:
+% r : rank of the vector  (nrow,1)                                                
+% i : index vector from the sort routine  (nrow,1)                                  
+%                                                                               
+n=length(x);                                                                         
+[s,i]=sort(x);                                                             
+r(i,1)=[1:n]';
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/ransamp.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/ransamp.m
new file mode 100644
index 0000000000000000000000000000000000000000..60bad4dc7f11750699d5177aeb59379b24f1e92e
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/ransamp.m
@@ -0,0 +1,19 @@
+function s=ransamp(xmean,xsd,corr,nsample)
+% s=ransamp(xmean,xsd,corr,nsample)
+% random sampling with correlation
+% Input:
+%   xmean     : mean of data (1,nvar)
+%   xsd       : std.dev of data (1,nvar)
+%   corr      : correlation matrix of the variables (nvar,nvar)
+%   nsample   : no. of samples
+% Output:
+%   s       : random sample (nsample,nvar)
+% Uses Matlab function: randn
+%   Budiman (2003)
+
+nvar=length(xmean);
+% random sampling 
+L = chol(corr);
+z = randn(nvar,nsample);
+y = L' * z ;
+s = (y'.*repmat(xsd,nsample,1))+ repmat(xmean,nsample,1);
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/test_sampling.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/test_sampling.m
new file mode 100644
index 0000000000000000000000000000000000000000..b9bb477334da57b9a33a3f3e1feafef5bfd33a85
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/test_sampling.m
@@ -0,0 +1,49 @@
+% example of sampling
+clear all
+
+nsample=100;        % no of random samples to be drawn
+nvar=6;             % no of variables
+
+xmean=[10  5  4   3    20   10];    % mean
+xsd=[0.1   1  0.1   1    1   1];    % std. deviation
+%   correlation matrix
+corr=[
+    1.00  0    0     0       0     0
+    0    1.00  0     0       0     0
+    0    0     1.00  0       0     0
+    0    0     0     1.00   0.75  -0.70
+    0    0     0     0.75   1.00  -0.95
+    0    0     0    -0.70  -0.95   1.00];
+
+% first sample assume no correlation with LHS
+s=latin_hs(xmean,xsd,nsample,nvar);
+mean(s)
+std(s)
+
+pause
+% sample assume correlation with random sampling
+r=ransamp(xmean,xsd,corr,nsample);
+corrcoef(r)
+mean(r)
+std(r)
+% error in the corr. 
+ae=mean(abs(corrcoef(r)-corr))
+
+pause
+% sample assume correlation with LHS Stein
+z=lhs_stein(xmean,xsd,corr,nsample);
+corrcoef(z)
+mean(z)
+std(z)
+% error in the corr. 
+ae=mean(abs(corrcoef(z)-corr))
+
+pause
+% sample assume correlation with LHS Iman
+z=lhs_iman(xmean,xsd,corr,nsample);
+mean(z)
+std(z)
+corrcoef(z)
+% error in the corr. 
+ae=mean(abs(corrcoef(z)-corr))
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/test_sampling2.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/test_sampling2.m
new file mode 100644
index 0000000000000000000000000000000000000000..d43b05a05822e23b375e63536e0f4da5c0ad49cb
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/globalparametersensitivity/auxiliary/sampling/test_sampling2.m
@@ -0,0 +1,26 @@
+% example of sampling with corr matrix that is not positive definite
+clear all
+
+nsample=100;        % no of random samples to be drawn
+nvar=8;             % no of variables
+
+xmean=[10  5  4     3   20   10  50  2];    % mean
+xsd=  [1   1  0.1   1    1    2   5  1];    % std. deviation
+%   correlation matrix
+corr=[
+1.00	0.45	-0.85	0.27	0.27	0.22	-0.38	0.37
+0.45	1.00	-0.85	-0.08	0.18	0.09	-0.21	0.20
+-0.85	-0.85	1.00	-0.10	-0.27	-0.18	0.34	-0.33
+0.27	-0.08	-0.10	1.00	0.33	0.33	-0.36	0.37
+0.27	0.18	-0.27	0.33	1.00	0.94	0.46	-0.45
+0.22	0.09	-0.18	0.33	0.94	1.00	0.54	-0.53
+-0.38	-0.21	0.34	-0.36	0.46	0.54	1.00	-1.00
+0.37	0.20	-0.33	0.37	-0.45	-0.53	-1.00	1.00];
+
+T=chol(corr);   % correlation matrix is not quite positive definite
+
+%use lhs_iman_n
+z=lhs_iman_n(xmean,xsd,corr,nsample);
+mean(z)
+std(z)
+corrcoef(z)
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/localparametersensitivity/SBmca.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/localparametersensitivity/SBmca.m
new file mode 100644
index 0000000000000000000000000000000000000000..986ced5bf90cb69e7d7d4bcf501009c3680b484f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/localparametersensitivity/SBmca.m
@@ -0,0 +1,229 @@
+function [varargout] = SBmca(model, varargin)
+% SBmca: Metabolic control analysis
+% This function uses the steady state sensitivity analysis functions of the
+% SBTOOLBOX2 to determine flux control coefficients and concentration
+% control coefficients. Additionally it computes elasticity coefficients.
+% It is important to note that all states in the analyzed SBmodel are
+% assumed to represent concentrations of substrates and all reactions
+% enzymatic reactions. If this is not the case for certain states and/or
+% reactions the user needs to postprocess the results by deleting the
+% corresponding columns and rows in the matrices FCC, CCC, EC. Furthermore,
+% the model should only contain irreversible reactions (consider the use of
+% SBmakeirreversible). 
+%
+% USAGE:
+% ======
+% [] = SBmca(model)
+% [output] = SBmca(model)
+% [] = SBmca(model,OPTIONS)
+% [output] = SBmca(model,OPTIONS)
+%
+% model: SBmodel
+% OPTIONS: structure containing options for the function:
+%           OPTIONS.pertsize: size of the perturbation that is used to
+%               determine the sensitivities. Scalar value => same
+%               perturbation for all perturbed parameters.
+%           OPTIONS.absRel: scalar value 1 or 0. =1: The perturbation
+%               chosen in the previous option is interpreted as a relative
+%               perturbation and assumed to be given in percent. =0: The
+%               perturbation in the previous option is interpreted as an
+%               absolute perturbation.
+%
+% DEFAULT VALUES:
+% ===============
+% The default perturbation is +1 percent, obtained by the following default
+% options:
+% OPTIONS.pertsize: 1 
+% OPTIONS.absRel: 1 
+%
+% Output Arguments:
+% =================
+% If no output argument is given, the determined MCA data (FCC, CCC, EC)
+% are plotted using the function SBplot2. 
+%
+% The output argument 'output' is a MATLAB struct element with the
+% following structure:
+%
+%   output.states           cell-array with the names of the states
+%                           (substrates)
+%   output.reactions        cell-array with the name of the reaction/enzyme
+%                           names
+%   output.FCC              Matrix containing the Flux Control Coefficients
+%                           (One row per flux and one column per enzyme)
+%   output.CCC              Matrix containing the Concentration Control
+%                           Coefficients (One row per substrate and one
+%                           column per enzyme)
+%   output.EC               Matrix containing the Elasticity Coefficients
+%                           (One row per enzyme and one column per
+%                           substrate)
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE NON-NUMERIC INITIAL CONDITIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% just by replacing them
+model = SBconvertNonNum2NumIC(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 2,
+    OPTIONS = varargin{1};
+else 
+    OPTIONS = [];
+end
+% default values
+pertsize = 1;
+absRel = 1;
+% read out options
+if isfield(OPTIONS,'pertsize'),
+    if ~isempty(OPTIONS.pertsize),
+        pertsize = OPTIONS.pertsize;
+    end
+end
+if isfield(OPTIONS,'absRel'),
+    if ~isempty(OPTIONS.absRel),
+        absRel = OPTIONS.absRel;
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check that reactions are irreversible
+%%%%%%%%%%%%%%%%%%%%%%%%%
+modelx = SBmakeirreversible(model);
+test1 = SBreactions(model);
+test2 = SBreactions(modelx);
+if length(test2) > length(test1),
+    error('The model contains reversible reactions. You might consider the use of SBmakeirreversible.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add extra multiplicative factors in front of all reactions
+% and add them as parameters in the model
+%%%%%%%%%%%%%%%%%%%%%%%%%
+% parameters: mca_factor_Reactionname
+modelstruct = SBstruct(model);
+mcaparameters = {};
+for k = 1:length(modelstruct.reactions),
+    formula = modelstruct.reactions(k).formula;
+    mcaparameters{end+1} = sprintf('mca_factor_%s',modelstruct.reactions(k).name);
+    newformula = sprintf('%s*(%s)',mcaparameters{k},formula);
+    modelstruct.reactions(k).formula = newformula;
+    paramindex = length(modelstruct.parameters)+1;
+    modelstruct.parameters(paramindex).name = mcaparameters{k};
+    modelstruct.parameters(paramindex).value = 1;
+    modelstruct.parameters(paramindex).notes = 'Parameter used for MCA';
+end
+% convert back to SBmodel
+mcamodel = SBmodel(modelstruct);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%
+% Perform parameter sensitivity analysis based on mca parameters
+% This calculates Flux Control Coefficients and Concentration Control
+% Coefficients
+%%%%%%%%%%%%%%%%%%%%%%%%%
+mcasensdata = SBsensdatastat(mcamodel,mcaparameters,pertsize,absRel);
+mcadata = SBsensstat(mcasensdata);
+
+% Split data in Flux Control Coefficients and Concentration Control
+% Coefficients
+nameStates = SBstates(mcamodel);
+nameReactions = SBreactions(mcamodel);
+numberStates = length(nameStates);
+numberReactions = length(nameReactions);
+% Concentration Control Coefficients
+CCC = mcadata.Sn(1:numberStates,:);
+% Flux Control Coefficients
+FCC = mcadata.Sn(numberStates+1:end,:);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine the Elasticity Coefficients
+%%%%%%%%%%%%%%%%%%%%%%%%%
+EC = [];
+statesNom = mcasensdata.xssnom;
+reactionsNom = mcasensdata.rssnom;
+
+for k = 1:numberStates,
+    perturbedstate = statesNom;
+    if absRel == 0,
+        % absolute perturbation
+        deltastate = pertsize;
+    else
+        % relative perturbation
+        deltastate = statesNom(k) * pertsize/100;
+    end
+    perturbedstate(k) = perturbedstate(k) + deltastate;
+    [dummy1,dummy2,dummy3,dummy4,reactionrates] = SBreactions(mcamodel,perturbedstate);
+    % determination of reactions sensitivities to states
+    reactionsSens = (reactionrates - reactionsNom)/deltastate;
+    % determination of normalized sensitivities (ECs)
+    ECk = inv(diag(reactionsNom))*reactionsSens*statesNom(k);
+    EC(:,k) = ECk;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%
+% Generate output data
+%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargout == 0,
+    % FCC
+    FCCplot.name = 'Flux Control Coefficients';
+    FCCplot.xnames = nameReactions;
+    FCCplot.ynames = nameReactions;
+    FCCplot.data = FCC;
+    FCCplot.title = 'Flux Control Coefficients C_e^J';
+    FCCplot.xlabel = 'Enzymes e';
+    FCCplot.xaxistitle = 'Enzymes e';
+    FCCplot.yaxistitle = 'Fluxes J';
+    % CCC
+    CCCplot.name = 'Concentration Control Coefficients';
+    CCCplot.xnames = nameReactions;
+    CCCplot.ynames = nameStates;
+    CCCplot.data = CCC;
+    CCCplot.title = 'Concentration Control Coefficients C_e^s';
+    CCCplot.xlabel = 'Enzyme e';
+    CCCplot.xaxistitle = 'Enzyme e';
+    CCCplot.yaxistitle = 'Substrate s';
+    % EC
+    ECplot.name = 'Elasticity Coefficients';
+    ECplot.xnames = nameStates;
+    ECplot.ynames = nameReactions;
+    ECplot.data = EC;
+    ECplot.title = 'Elasticity Coefficients E_s^e';
+    ECplot.xlabel = 'Substrate s';
+    ECplot.xaxistitle = 'Substrate s';
+    ECplot.yaxistitle = 'Enzyme e';
+    % do plot!
+    SBplot2(FCCplot,CCCplot,ECplot);
+else
+    output = [];
+    output.states = nameStates;
+    output.reactions = nameReactions;
+    output.FCC = FCC;
+    output.CCC = CCC;
+    output.EC = EC;
+    varargout{1} = output;
+end
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/localparametersensitivity/SBsensamplitude.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/localparametersensitivity/SBsensamplitude.m
new file mode 100644
index 0000000000000000000000000000000000000000..b7a6f494748e3cfde7e7d676abcfbce18603434c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/localparametersensitivity/SBsensamplitude.m
@@ -0,0 +1,197 @@
+function [varargout] = SBsensamplitude(datastructure)
+% SBsensamplitude: Function evaluating local first order amplitude
+% sensitivities.
+%
+% USAGE:
+% ======
+% [output,plotDataS,plotDataSn] = SBsensamplitude(datastructure)
+% [] = SBsensamplitude(datastructure)
+%
+% datastructure: output, returned by the function SBsensdataosc
+%
+% Output Arguments:
+% =================
+% If no output argument is given, the determined data are plotted using the
+% function SBplot2. 
+%
+% The output argument 'output' is a MATLAB struct element with the
+% following structure:
+%
+%   output.S                matrix, with elements S_ij, defined below
+%   output.namesS           cell-array with state names for 
+%                           which the analysis has been done (for the
+%                           non-normalized sensitivities)
+%   output.parametersS      cell-array with names of parameters used in
+%                           analysis (for the non-normalized sensitivities)
+%   output.Sn               same as S, but the sensitivities are normalized
+%   output.namesSn          cell-array with state names for 
+%                           which the analysis has been done (for the
+%                           normalized sensitivities)
+%   output.parametersSn     cell-array with names of parameters used in
+%                           analysis (for the normalized sensitivities)
+%
+% The reason for having different fields for parameters and names for the
+% non-normalized and normalized sensitivities is due to the fact that zero
+% nominal parameter values lead to zero normalized sensitivities for these
+% parameters, and that zero nominal steady-state values of states lead to
+% infinite normalized sensitivities. In these cases the normalized
+% sensitivities for these parameters and states are not determined. 
+%
+% The plotDataS and plotDataSn output arguments are datastructures that 
+% can directly be used as input arguments for SBplot2 for visualization
+% of the sensitivity analysis results. For information about how this data 
+% structure is defined please refer to the help text provided for the
+% SBplot2 function.
+%
+% Theory:
+% =======
+% The amplitude A is defined as half the distance between the maximum 
+% (xmax) and the minimum (xmin) peak of an oscillating signal. 
+%
+% A = (xmax-xmin) / 2
+%
+% The amplitude sensitivity for the i-th component x_i wrt to the 
+% parameter p_j is defined by:
+%
+% S_ij = [ A_i(p_j+delta_p_j) - A_i(p_j) ] / delta_p_j
+%
+% The normalized sensitivity index is defined by
+%
+% Sn_ij = p_j/A_i(p_j) * S_ij
+%
+% The function A(p) is called an objective function (Varma et al. 
+% (1999) Parametric Sensitivity in Chemical Systems, Cambridge 
+% University Press, New York) and has been used in this form, e.g., by 
+% Stelling et al. (2004) Robustness properties of circadian clock 
+% architectures, PNAS, vol 101 (36), 13210-13215.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+states = datastructure.states;
+parameters = datastructure.parameters;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Output some information about the algorithm
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+disp(sprintf('Determination of amplitude sensitivities'));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determining amplitude sensitivities
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% determine the amplitudes of the signals of the nominal and the 
+% perturbed system and their difference - transpose the rows to obtain the 
+% components in rows and the parameter corresponding to the columns
+% nominal value
+Anom = ((max(datastructure.xnom)-min(datastructure.xnom)) / 2)';
+% initialize difference matrix
+Adif = [];
+for k = 1:length(datastructure.xpert),
+    xpertk = datastructure.xpert{k};
+    % determine the perturbed amplitudes
+    Apertk = ((max(xpertk)-min(xpertk))/2)';
+    % determine the difference
+    Adif = [Adif Apertk-Anom];
+end
+% now scale the elements in the columns with 1/deltaPert, where deltaPert
+% is the absolute perturbation to the corresponding parameter
+pertVector = [];
+for k = 1:length(datastructure.nomvalues),
+    % Determination of the absolute size of the perturbation
+    if datastructure.absRel(k) == 0,
+        % absolute perturbation
+        deltaPert = datastructure.pertSize(k);
+    else
+        % relative perturbation
+        deltaPert = datastructure.nomvalues(k) * datastructure.pertSize(k)/100;
+    end
+    pertVector = [pertVector deltaPert];
+end    
+% do the scaling
+S = Adif * inv(diag(pertVector));
+% determine the normalized sensitivity
+% in case of zero nominal values for parameters take out those parameters
+% in case of zero nominal values for states and/or reactions take out those
+% states or reactions
+% first do the scaling
+Sn = [];
+help = S*diag(datastructure.nomvalues);
+for k = 1:size(S,1),
+    Anomk = Anom(k);
+    if Anomk ~= 0,
+        Snrowk = help(k,:)/Anomk;
+    else
+        Snrowk = 0*ones(1,size(S,2));
+    end
+    Sn(k,:) = Snrowk;
+end
+% now retain only the elements in Sn that correspond to non-zero nominal 
+% values of parameters and Tnom
+parametersNonZeroIndex = find(datastructure.nomvalues~=0);
+statesNonZeroIndex = find(Anom~=0);
+Sn = Sn(statesNonZeroIndex,parametersNonZeroIndex);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Construct output variable
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output.S = S;
+output.statesS = states;
+output.parametersS = parameters;
+output.Sn = Sn;
+output.statesSn = states(statesNonZeroIndex);
+output.parametersSn = parameters(parametersNonZeroIndex);
+
+plotdatastruct.name = 'Normalized Amplitude Sensitivities';
+plotdatastruct.xnames = output.parametersSn;
+plotdatastruct.ynames = output.statesSn;
+plotdatastruct.data = output.Sn;
+plotdatastruct.title = 'Normalized Amplitude Sensitivities';
+plotdatastruct.xlabel = 'Parameters';
+plotdatastruct.xaxistitle = 'Parameters';
+plotdatastruct.yaxistitle = 'States';
+
+plotdatastruct2.name = 'Amplitude Sensitivities';
+plotdatastruct2.xnames = output.parametersS;
+plotdatastruct2.ynames = output.statesS;
+plotdatastruct2.data = output.S;
+plotdatastruct2.title = 'Amplitude Sensitivities';
+plotdatastruct2.xlabel = 'Parameters';
+plotdatastruct2.xaxistitle = 'Parameters';
+plotdatastruct2.yaxistitle = 'States';
+
+if nargout == 1,
+    varargout{1} = output;
+elseif nargout == 2,
+    varargout{1} = output;
+    varargout{2} = plotdatastruct2;
+elseif nargout == 3,
+    varargout{1} = output;
+    varargout{2} = plotdatastruct2;
+    varargout{3} = plotdatastruct;
+elseif nargout == 0,
+    SBplot2(plotdatastruct,plotdatastruct2);
+else
+    error('Incorrect number of output arguments.');
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/localparametersensitivity/SBsensdataosc.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/localparametersensitivity/SBsensdataosc.m
new file mode 100644
index 0000000000000000000000000000000000000000..19480a881794aaa082c0be26f466338e01ceed1d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/localparametersensitivity/SBsensdataosc.m
@@ -0,0 +1,433 @@
+function [output] = SBsensdataosc(varargin)
+% SBsensdataosc: Function allowing to generate data that subsequently can be 
+% used for different kinds of parametric sensitivity analyses. Used only
+% for oscillating systems! This function can only be used in the case that
+% no events are present in the model. A similar function handling models
+% with events is: 'SBsensdataoscevents'.
+%
+% The data is obtained by simulation of the nominal and perturbed systems.
+% In each simulation of a perturbed system only a single parameter is
+% perturbed.
+%
+% The used integrator for this is 'ode23s'.
+%
+% As initial state for the simulation the initial conditions stored in the
+% model are used. As nominal parameter values the parameter values stored
+% in the model are used.
+%  
+% USAGE:
+% ======
+% [output] = SBsensdataosc(model,timeData)
+% [output] = SBsensdataosc(model,timeData,parameters)
+% [output] = SBsensdataosc(model,timeData,parameters,pertSize,absRel)
+% [output] = SBsensdataosc(model,timeData,parameters,pertSize,absRel,integratorOptions)
+% [output] = SBsensdataosc(model,timeData,parameters,pertSize,absRel,integratorOptions,eventFunction)
+%
+% model: SBmodel (not useable with ODE model file)
+% timeData: this argument can be a scalar, a vector of length 2, or of length 3:
+%       timeData = [timeHorizont]
+%       timeData = [timeHorizont, nrTransientHorizonts]
+%       timeData = [timeHorizont, nrTransientHorizonts, deltaT]
+%       timeHorizont: determines the time over which data is collected for
+%           later analysis.
+%       nrTransientHorizonts: before collecting data the systems is
+%           simulated over a time nrTransientHorizonts*timeHorizont. A
+%           value larger than 0 should be chosen in order to allow
+%           transients to die out.
+%       deltaT: the simulated data is returned in discrete time-steps of
+%           size deltaT
+% parameters: a cell-array with parameter names, determining the parameters
+%       that are to be considered in the analysis.
+% pertSize: either a scalar value, determining the perturbation to be
+%       applied to each of the parameters, or a vector of same length as
+%       the number of considered parameters, allowing to choose a different 
+%       perturbation for each parameter.
+% absRel: either a scalar (0 or 1), or a vector of the same length as
+%       pertSize. 0 means that the corresponding element in pertSize
+%       determines an absolute perturbatiom, 1 means it determines a
+%       relative perturbation in percent.
+% integratorOptions: standard MATLAB integrator options that can be set
+%       using the 'odeset' function.
+% eventFunction: the user can specify an event function (given by a string 
+%       with its name) that allows to collect additional data (in terms of 
+%       time-instants at which certain events occurr) for different 
+%       kinds of sensitivity analyses. Per default the event function
+%       'periodeventfunctionSB' is used and allows to determine the 
+%       period of the oscillating system.
+%       A custom event function should be realized as an m file and be
+%       available in the MATLAB path. If you want to write a custom event
+%       function please have a look at the 'periodeventfunctionSB'
+%       first.
+%
+% DEFAULT VALUES:
+% ===============
+%   The only required input arguments are 'model' and
+%   'timeData=[timeHorizont]'. If not specified otherwise, following
+%   default values are used: 
+%
+%   nrTransientHorizonts = 2
+%   deltaT = timeHorizont/1000
+%   parameters = all parameters in the model
+%   pertSize = 1 (percent)
+%   absRel = 1 (relative perturbation)
+%   integratorOptions = []
+%   eventFunction = 'periodeventfunctionSB' 
+%
+% OUTPUT:
+% =======
+% The output argument 'output' is a MATLAB struct element with the
+% following structure:
+%
+%   output.model            model as obtained as input argument
+%   output.time             simulation time vector 
+%   output.tenom            time-steps for nominal system - time-steps used
+%                           to determine the period of eventual
+%                           oscillations in the system 
+%   output.tepert           cell-array, where each entry corresponds to
+%                           time-steps for a perturbed system - time-steps
+%                           used to determine the period of eventual
+%                           oscillations in the system 
+%   output.states           cell-array with statenames as elements (same
+%                           ordering as for the simulation data)
+%   output.xnom             matrix containing time instants in rows and
+%                           state values in columns
+%   output.xpert            cell-array, where each entry correponds to the 
+%                           simulation result for a single perturbed
+%                           parameter. The format of the elements is the
+%                           same as for xnom
+%   output.parameters       same as the input argument 'parameters' -
+%                           either its default or the passed values
+%   output.nomvalues        nominal values of parameters in above field
+%   output.pertSize         same as the input argument 'pertSize' -
+%                           either its default or the passed values
+%   output.absRel           same as the input argument 'absRel' -
+%                           either its default or the passed values
+%
+% The reason of using a struct element as output is that the output of 
+% SBsensdataosc usually needs to be processed by other functions, and the
+% calling of these functions is considerably simplified by passing all
+% important data by one element only.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GLOBAL VARIABLES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+global eventValues 
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK MODEL TYPE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+sbm = varargin{1};
+if ~strcmp('SBmodel',class(sbm)),
+    error('This function can only be used with SBmodels, not with ODE file models!');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE NON-NUMERIC INITIAL CONDITIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% just by replacing them
+sbm = SBconvertNonNum2NumIC(sbm);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF MODEL CONTAINS EVENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(SBevents(sbm)),
+    error('The model contains events. Please use the function ''SBsensdataoscevents'' instead.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLING VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 2,
+    timeData = varargin{2};
+    parameters = SBparameters(sbm);
+    pertSize = [];
+    absRel = [];
+    integratorOptions = [];
+    eventFunction = 'periodeventfunctionSB';
+elseif nargin == 3,
+    timeData = varargin{2};
+    parameters = varargin{3};
+    pertSize = [];
+    absRel = [];
+    integratorOptions = [];
+    eventFunction = 'periodeventfunctionSB';
+elseif nargin == 5,
+    timeData = varargin{2};
+    parameters = varargin{3};
+    pertSize = varargin{4};
+    absRel = varargin{5};
+    integratorOptions = [];
+    eventFunction = 'periodeventfunctionSB';
+elseif nargin == 6,
+    timeData = varargin{2};
+    parameters = varargin{3};
+    pertSize = varargin{4};
+    absRel = varargin{5};
+    integratorOptions = varargin{6};
+    eventFunction = 'periodeventfunctionSB';
+elseif nargin == 7,
+    timeData = varargin{2};
+    parameters = varargin{3};
+    pertSize = varargin{4};
+    absRel = varargin{5};
+    integratorOptions = varargin{6};
+    eventFunction = varargin{7};
+else
+    error('Incorrect number of input arguments.');
+end
+% check if parameters defined by a cell-array 
+% if not then convert
+if ischar(parameters),
+    parameters = {parameters};
+end
+if isempty(absRel) || isempty(pertSize),
+    pertSize = ones(1,length(parameters));
+    absRel = ones(1,length(parameters));    
+end
+% Checking and handling timeData variable
+if length(timeData) == 1,
+    timeHorizont = timeData(1); 
+    nrTransientHorizonts = 2;
+    deltaT = timeHorizont/1000;
+elseif length(timeData) == 2,
+    timeHorizont = timeData(1); 
+    nrTransientHorizonts = timeData(2);
+    deltaT = timeHorizont/1000;
+elseif length(timeData) == 3,
+    timeHorizont = timeData(1); 
+    nrTransientHorizonts = timeData(2);
+    deltaT = timeData(3);    
+else
+    error('Incorrect number of elements in ''timeData'' input argument.');
+end
+% adjust scalar elements in pertSize and absRel to number of parameters
+if length(pertSize) == 1,
+    pertSize = pertSize*ones(1,length(parameters));
+end
+if length(absRel) == 1,
+    absRel = absRel*ones(1,length(parameters));
+end
+% check length of parameters, pertSize and absRel
+if length(parameters) ~= length(pertSize) || length(parameters) ~= length(absRel),
+    error('Check the number of elements in ''parameters'', ''pertSize'', and ''absRel''\ninput arguments. They should have the same number of elements!');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SETTING OTHER VARIABLES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Select the integrator to use
+integrator = 'ode23s';
+% get state data
+[states,stateODEs,initialCondition] = SBstates(sbm);
+% determining the nominal values for the parasmeters
+[allParameters, allParameterValues] = SBparameters(sbm);
+nomValues = [];
+errorText = '';
+for k1 = 1:length(parameters),
+    parameterFound = 0;
+    for k2 = 1:length(allParameters),
+        if strcmp(parameters{k1},allParameters{k2}),
+            nomValues = [nomValues, allParameterValues(k2)];
+            parameterFound = 1;
+            break;
+        end
+    end
+    if parameterFound == 0,
+        errorText = sprintf('%sParameter ''%s'', given in input arguments could not be found in the model.\n',errorText,parameters{k1});
+    end
+end
+if ~isempty(errorText),
+    errorText = sprintf('%sThe available parameters in the model are:\n',errorText);
+    for k = 1:length(allParameters),
+        errorText = sprintf('%s\n%s',errorText,allParameters{k});
+    end    
+    error(errorText);    
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INFO MESSAGE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+disp('Please make sure that the system is oscillating in a stationary state');
+disp('prior to collect data for period and amplitude determination.');
+disp('You can do this by specifying a long enough pre data collection');
+disp('horizont (nrTransientHorizonts).');
+disp(' ');
+disp('Collecting data for sensitivity analysis by simulation of the system.');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Construct time vectors for simulation
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% time vector for transients to die out
+if nrTransientHorizonts == 0,
+    time_transient = [];
+else
+    time_transient = [0:deltaT:nrTransientHorizonts*timeHorizont]; 
+end
+time_precollect = [nrTransientHorizonts*timeHorizont:deltaT:(nrTransientHorizonts+1)*timeHorizont];
+% time vector for data collection
+time = [(nrTransientHorizonts+1)*timeHorizont:deltaT:(nrTransientHorizonts+2)*timeHorizont];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Simulate and collect data for nominal model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+tic
+% creating nominal model ODE file
+[ODEfctname, ODEfilefullpath] = SBcreateTempODEfile(sbm);
+% adding event function to intergrator options
+eventIntegratorOptions = odeset(integratorOptions,'Events',eventFunction);
+disp('Simulating nominal system');
+% simulate over transient time horizont
+[t,x] = feval(integrator,ODEfctname,time_transient,initialCondition,integratorOptions);
+% simulate over one time horizont to collect data for time events
+precollectInitialCondition = x(end,:);
+[tpre,xpre] = feval(integrator,ODEfctname,time_precollect,precollectInitialCondition,integratorOptions);
+% now prepare for the simulation to collect data - first get the initial condition for the simulation
+collectDataInitialCondition = xpre(end,:); 
+eventValues = min(xpre)+0.6*(max(xpre)-min(xpre));
+% simulate the nominal system
+[t2,xnom,tenom,xenom,ienom] = eval(sprintf('feval(@%s,@%s,time,collectDataInitialCondition,eventIntegratorOptions);',integrator,ODEfctname));
+if length(tenom) < 5,
+    error(sprintf('Oscillation periods could not be detected reliably.\nPlease check if the system is oscillating.\nIt might be necessary to increase the time horizont\nand/or to increase the number of transient horizonts.'));
+end
+time_elapsed = toc;
+% delete all temporary m files
+deleteTempODEfileSB(ODEfilefullpath);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONVERTING EVENT DATA NOMINAL CASE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% time-events from event data is collected as column vector where the
+% time-instants of all events are listed. the data needs to be converted 
+% in order to easily determine which time instant corresponds to which
+% event
+tenomConverted = cell(1,length(collectDataInitialCondition));
+nrLongerThanTwo = 0;
+for k = 1:length(ienom),
+    indexEvent = ienom(k);
+    element = tenomConverted{indexEvent};
+    element = [element tenom(k)];
+    tenomConverted{indexEvent} = element;
+    if length(element)>2,
+        % check how many results are there with more than 2 detected
+        % time period events
+        nrLongerThanTwo = nrLongerThanTwo + 1;
+    end
+end
+tenomOutput = tenomConverted;
+if nrLongerThanTwo == 0,
+    error(sprintf('Oscillation periods could not be detected reliably.\nPlease check if the system is oscillating.\nIt might be necessary to increase the time horizont\nand/or to increase the number of transient horizonts.'));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Simulate and collect data for perturbed model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+disp('Simulating perturbed systems');
+time_estimated = (time_elapsed*length(parameters))/60;
+disp(sprintf('Estimated time for simulations: %5.1f minutes.\n',time_estimated));
+xpert = {};
+tepert = {};
+iepert = {};
+for k = 1:length(parameters),
+    % determine the absolute perturbation for current parameter
+    if absRel(k) == 0 || nomValues(k) == 0,
+        % absolute perturbation
+        if nomValues(k) == 0,
+            pertParamValue = nomValues(k) + pertSize(k)/100;
+        else
+            pertParamValue = nomValues(k) + pertSize(k);
+        end
+        disp(sprintf('%d) Absolute perturbation (%+g) of parameter ''%s''. Nominal: %g, perturbed: %g',k,pertSize(k),parameters{k},nomValues(k),pertParamValue));
+        if nomValues(k) == 0,
+            disp(sprintf('\tNominal value of parameter ''%s'' is zero. Using absolute perturbation instead of relative.',parameters{k}));
+            absRel(k) = 0;
+            pertSize(k) = pertSize(k)/100;
+        end
+    else
+        % relative perturbation
+        pertParamValue = nomValues(k) * (1 + pertSize(k)/100);
+        disp(sprintf('%d) Relative perturbation (%+g%%) of parameter ''%s''. Nominal: %g, perturbed: %g',k,pertSize(k),parameters{k},nomValues(k),pertParamValue));
+    end
+    % sbm is the original model - determine a perturbed model modelpert -
+    % and create an ODE file for it. rehash the path
+    sbmpert = SBparameters(sbm,parameters{k},pertParamValue);
+    [ODEfctname, ODEfilefullpath] = SBcreateTempODEfile(sbmpert);
+    % simulate over transient time horizont
+    [t,x] = feval(integrator,ODEfctname,time_transient,initialCondition,integratorOptions);
+    precollectInitialCondition = x(end,:);
+    [tpre,xpre] = feval(integrator,ODEfctname,time_precollect,precollectInitialCondition,integratorOptions);
+    % now prepare for the simulation to collect data - first get the initial condition for the simulation
+    collectDataInitialCondition = xpre(end,:); 
+    eventValues = min(xpre)+0.6*(max(xpre)-min(xpre));
+    % simulate the nominal system
+    [t2,xpertk,tepertk,xepertk,iepertk] = eval(sprintf('feval(@%s,@%s,time,collectDataInitialCondition,eventIntegratorOptions);',integrator,ODEfctname));
+    xpert{k} = xpertk;
+    tepert{k} = tepertk;
+    iepert{k} = iepertk;
+    % delete all temporary m files
+    deleteTempODEfileSB(ODEfilefullpath); 
+end
+ 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONVERTING EVENT DATA PERTURBED CASE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% time-events from event data is collected as column vector where the
+% time-instants of all events are listed. the data needs to be converted 
+% in order to easily determine which time instant corresponds to which
+% event
+tepertOutput = {};
+for k1 = 1:length(parameters),
+    tepertConvertedElement = cell(1,length(collectDataInitialCondition));
+    iepertk = iepert{k1};
+    tepertk = tepert{k1};
+    for k2 = 1:length(iepertk),
+        indexEvent = iepertk(k2);
+        element = tepertConvertedElement{indexEvent};
+        element = [element tepertk(k2)];
+        tepertConvertedElement{indexEvent} = element;
+    end
+    tepertOutput{k1} = tepertConvertedElement;
+end
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONSTRUCT OUTPUT STRUCTURE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output = [];
+output.model = sbm;
+output.time = time;
+output.tenom = tenomOutput;
+output.tepert = tepertOutput;
+output.states = states;
+output.xnom = xnom;
+output.xpert = xpert;
+output.parameters = parameters;
+output.nomvalues = nomValues;
+output.pertSize = pertSize;
+output.absRel = absRel;
+return
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/localparametersensitivity/SBsensdataoscevents.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/localparametersensitivity/SBsensdataoscevents.m
new file mode 100644
index 0000000000000000000000000000000000000000..7ab8203ed3042f8ca18b922556e1f2d47e14ed01
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/localparametersensitivity/SBsensdataoscevents.m
@@ -0,0 +1,453 @@
+function [output] = SBsensdataoscevents(varargin)
+% SBsensdataoscevents: Function allowing to generate data that subsequently can be 
+% used for different kinds of parametric sensitivity analyses. Used only
+% for oscillating systems! This function should be used in the case that events 
+% are present in the system. It will not work if no events are present.
+%
+% The data is obtained by simulation of the nominal and perturbed systems.
+% In each simulation of a perturbed system only a single parameter is
+% perturbed.
+%
+% The used integrator for this is 'ode23s'.
+%
+% As initial state for the simulation the initial conditions stored in the
+% model are used. As nominal parameter values the parameter values stored
+% in the model are used.
+%  
+% USAGE:
+% ======
+% [output] = SBsensdataoscevents(model,timeData)
+% [output] = SBsensdataoscevents(model,timeData,parameters)
+% [output] = SBsensdataoscevents(model,timeData,parameters,pertSize,absRel)
+% [output] = SBsensdataoscevents(model,timeData,parameters,pertSize,absRel,integratorOptions)
+% [output] = SBsensdataosc(model,timeData,parameters,pertSize,absRel,integratorOptions,eventFunction)
+%
+% model: SBmodel (not useable with ODE model file)
+% timeData: this argument can be a scalar, a vector of length 2, or of length 3:
+%       timeData = [timeHorizont]
+%       timeData = [timeHorizont, nrTransientHorizonts]
+%       timeData = [timeHorizont, nrTransientHorizonts, deltaT]
+%       timeHorizont: determines the time over which data is collected for
+%           later analysis.
+%       nrTransientHorizonts: before collecting data the systems is
+%           simulated over a time nrTransientHorizonts*timeHorizont. A
+%           value larger than 0 should be chosen in order to allow
+%           transients to die out.
+%       deltaT: the simulated data is returned in discrete time-steps of
+%           size deltaT
+% parameters: a cell-array with parameter names, determining the parameters
+%       that are to be considered in the analysis.
+% pertSize: either a scalar value, determining the perturbation to be
+%       applied to each of the parameters, or a vector of same length as
+%       the number of considered parameters, allowing to choose a different 
+%       perturbation for each parameter.
+% absRel: either a scalar (0 or 1), or a vector of the same length as
+%       pertSize. 0 means that the corresponding element in pertSize
+%       determines an absolute perturbatiom, 1 means it determines a
+%       relative perturbation in percent.
+% integratorOptions: standard MATLAB integrator options that can be set
+%       using the 'odeset' function.
+% eventFunction: the user can specify an event function (given by a string 
+%       with its name) that allows to collect additional data (in terms of 
+%       time-instants at which certain events occurr) for different 
+%       kinds of sensitivity analyses. Per default the event function
+%       'periodeventfunctioneventsSB' is used and allows to determine the 
+%       period of the oscillating system.
+%       A custom event function should be realized as an m file and be
+%       available in the MATLAB path. If you want to write a custom event
+%       function please have a look at the 'periodeventfunctioneventsSB'
+%       first.
+%
+% DEFAULT VALUES:
+% ===============
+%   The only required input arguments are 'model' and
+%   'timeData=[timeHorizont]'. If not specified otherwise, following
+%   default values are used: 
+%
+%   nrTransientHorizonts = 2
+%   deltaT = timeHorizont/1000
+%   parameters = all parameters in the model
+%   pertSize = 1 (percent)
+%   absRel = 1 (relative perturbation)
+%   integratorOptions = []
+%   eventFunction = 'periodeventfunctioneventsSB' 
+%
+% OUTPUT:
+% =======
+% The output argument 'output' is a MATLAB struct element with the
+% following structure:
+%
+%   output.model            model as obtained as input argument
+%   output.time             simulation time vector 
+%   output.tenom            time-steps for nominal system - time-steps used
+%                           to determine the period of eventual
+%                           oscillations in the system 
+%   output.tepert           cell-array, where each entry corresponds to
+%                           time-steps for a perturbed system - time-steps
+%                           used to determine the period of eventual
+%                           oscillations in the system 
+%   output.states           cell-array with statenames as elements (same
+%                           ordering as for the simulation data)
+%   output.xnom             matrix containing time instants in rows and
+%                           state values in columns
+%   output.xpert            cell-array, where each entry correponds to the 
+%                           simulation result for a single perturbed
+%                           parameter. The format of the elements is the
+%                           same as for xnom
+%   output.parameters       same as the input argument 'parameters' -
+%                           either its default or the passed values
+%   output.nomvalues        nominal values of parameters in above field
+%   output.pertSize         same as the input argument 'pertSize' -
+%                           either its default or the passed values
+%   output.absRel           same as the input argument 'absRel' -
+%                           either its default or the passed values
+%
+% The reason of using a struct element as output is that the output of 
+% SBsensdataoscevents usually needs to be processed by other functions, and the
+% calling of these functions is considerably simplified by passing all
+% important data by one element only.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GLOBAL VARIABLES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+global eventValues EVENTfctname
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK MODEL TYPE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+sbm = varargin{1};
+if ~strcmp('SBmodel',class(sbm)),
+    error('This function can only be used with SBmodels, not with ODE file models!');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE NON-NUMERIC INITIAL CONDITIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% just by replacing them
+sbm = SBconvertNonNum2NumIC(sbm);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF MODEL CONTAINS EVENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(SBevents(sbm)),
+    error('The model contains no events. Please use the function ''SBsensdataosc'' instead.');
+end
+numberModelEvents = length(SBevents(sbm));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLING VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 2,
+    timeData = varargin{2};
+    parameters = SBparameters(sbm);
+    pertSize = [];
+    absRel = [];
+    integratorOptions = [];
+    eventFunction = 'periodeventfunctioneventsSB';
+elseif nargin == 3,
+    timeData = varargin{2};
+    parameters = varargin{3};
+    pertSize = [];
+    absRel = [];
+    integratorOptions = [];
+    eventFunction = 'periodeventfunctioneventsSB';
+elseif nargin == 5,
+    timeData = varargin{2};
+    parameters = varargin{3};
+    pertSize = varargin{4};
+    absRel = varargin{5};
+    integratorOptions = [];
+    eventFunction = 'periodeventfunctioneventsSB';
+elseif nargin == 6,
+    timeData = varargin{2};
+    parameters = varargin{3};
+    pertSize = varargin{4};
+    absRel = varargin{5};
+    integratorOptions = varargin{6};
+    eventFunction = 'periodeventfunctioneventsSB';
+elseif nargin == 6,
+    timeData = varargin{2};
+    parameters = varargin{3};
+    pertSize = varargin{4};
+    absRel = varargin{5};
+    integratorOptions = varargin{6};
+    eventFunction = varargin{7};
+else
+    error('Incorrect number of input arguments.');
+end
+% check if parameters defined by a cell-array 
+% if not then convert
+if ischar(parameters),
+    parameters = {parameters};
+end
+if isempty(absRel) || isempty(pertSize),
+    pertSize = ones(1,length(parameters));
+    absRel = ones(1,length(parameters));    
+end
+% Checking and handling timeData variable
+if length(timeData) == 1,
+    timeHorizont = timeData(1); 
+    nrTransientHorizonts = 2;
+    deltaT = timeHorizont/1000;
+elseif length(timeData) == 2,
+    timeHorizont = timeData(1); 
+    nrTransientHorizonts = timeData(2);
+    deltaT = timeHorizont/1000;
+elseif length(timeData) == 3,
+    timeHorizont = timeData(1); 
+    nrTransientHorizonts = timeData(2);
+    deltaT = timeData(3);    
+else
+    error('Incorrect number of elements in ''timeData'' input argument.');
+end
+% adjust scalar elements in pertSize and absRel to number of parameters
+if length(pertSize) == 1,
+    pertSize = pertSize*ones(1,length(parameters));
+end
+if length(absRel) == 1,
+    absRel = absRel*ones(1,length(parameters));
+end
+% check length of parameters, pertSize and absRel
+if length(parameters) ~= length(pertSize) || length(parameters) ~= length(absRel),
+    error('Check the number of elements in ''parameters'', ''pertSize'', and ''absRel''\ninput arguments. They should have the same number of elements!');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SETTING OTHER VARIABLES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Select the integrator to use
+integrator = 'ode23s';
+% get state data
+[states,stateODEs,initialCondition] = SBstates(sbm);
+% determining the nominal values for the parasmeters
+[allParameters, allParameterValues] = SBparameters(sbm);
+nomValues = [];
+errorText = '';
+for k1 = 1:length(parameters),
+    parameterFound = 0;
+    for k2 = 1:length(allParameters),
+        if strcmp(parameters{k1},allParameters{k2}),
+            nomValues = [nomValues, allParameterValues(k2)];
+            parameterFound = 1;
+            break;
+        end
+    end
+    if parameterFound == 0,
+        errorText = sprintf('%sParameter ''%s'', given in input arguments could not be found in the model.\n',errorText,parameters{k1});
+    end
+end
+if ~isempty(errorText),
+    errorText = sprintf('%sThe available parameters in the model are:\n',errorText);
+    for k = 1:length(allParameters),
+        errorText = sprintf('%s\n%s',errorText,allParameters{k});
+    end    
+    error(errorText);    
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INFO MESSAGE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+disp('Please make sure that the system is oscillating in a stationary state');
+disp('prior to collect data for period and amplitude determination.');
+disp('You can do this by specifying a long enough pre data collection');
+disp('horizont (nrTransientHorizonts).');
+disp(' ');
+disp('Collecting data for sensitivity analysis by simulation of the system.');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Construct time vectors for simulation
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% time vector for transients to die out
+if nrTransientHorizonts == 0,
+    time_transient = [];
+else
+    time_transient = [0:deltaT:nrTransientHorizonts*timeHorizont]; 
+end
+time_precollect = [nrTransientHorizonts*timeHorizont:deltaT:(nrTransientHorizonts+1)*timeHorizont];
+% time vector for data collection
+time = [(nrTransientHorizonts+1)*timeHorizont:deltaT:(nrTransientHorizonts+2)*timeHorizont];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Simulate and collect data for nominal model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+tic
+% creating nominal model ODE file and event functions
+[ODEfctname, ODEfilefullpath, DATAfctname, EVENTfctname, EVENTASSGNfctname] = SBcreateTempODEfile(sbm,0,1);
+% initialize variable eventValues (not needed in the beginning but must be defined)
+eventValues = zeros(1,length(initialCondition));
+disp('Simulating nominal system');
+% simulate over transient time horizont
+[t,x]=eventsimulateSB(ODEfctname,integrator,time_transient,initialCondition,integratorOptions,eventFunction,EVENTASSGNfctname);
+% simulate over one time horizont to collect data for time events
+precollectInitialCondition = x(end,:);
+[tpre,xpre]=eventsimulateSB(ODEfctname,integrator,time_precollect,precollectInitialCondition,integratorOptions,eventFunction,EVENTASSGNfctname);
+% now prepare for the simulation to collect data - first get the initial condition for the simulation
+collectDataInitialCondition = xpre(end,:); 
+eventValues = min(xpre)+0.6*(max(xpre)-min(xpre));
+% simulate the nominal system
+[t2,xnom,tenom,xenom,ienom]=eventsimulateSB(ODEfctname,integrator,time,collectDataInitialCondition,integratorOptions,eventFunction,EVENTASSGNfctname);
+% process tenom,xenom, and ienom to only keep the event data that belongs
+% to events from the event function that is important for the sensitivity
+% analysis
+eventData = [tenom xenom ienom];
+modelEventIndices = find(ismember(ienom,[1:numberModelEvents]));
+eventFunctionEvents = setdiff(1:length(ienom),modelEventIndices);
+eventData = eventData(eventFunctionEvents,:);
+if size(eventData,1) < 5,
+    error(sprintf('Oscillation periods could not be detected reliably.\nPlease check if the system is oscillating.\nIt might be necessary to increase the time horizont\nand/or to increase the number of transient horizonts.'));
+end
+tenom = eventData(:,1);
+xenom = eventData(:,2:end-1);
+ienom = eventData(:,end)-numberModelEvents;
+time_elapsed = toc;
+% delete all temporary m files
+deleteTempODEfileSB(ODEfilefullpath);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONVERTING EVENT DATA NOMINAL CASE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% time-events from event data is collected as column vector where the
+% time-instants of all events are listed. the data needs to be converted 
+% in order to easily determine which time instant corresponds to which
+% event
+tenomConverted = cell(1,length(collectDataInitialCondition));
+nrLongerThanTwo = 0;
+for k = 1:length(ienom),
+    indexEvent = ienom(k);
+    element = tenomConverted{indexEvent};
+    element = [element tenom(k)];
+    tenomConverted{indexEvent} = element;
+    if length(element)>2,
+        % check how many results are there with more than 2 detected
+        % time period events
+        nrLongerThanTwo = nrLongerThanTwo + 1;
+    end
+end
+tenomOutput = tenomConverted;
+if nrLongerThanTwo == 0,
+    error(sprintf('Oscillation periods could not be detected reliably.\nPlease check if the system is oscillating.\nIt might be necessary to increase the time horizont\nand/or to increase the number of transient horizonts.'));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Simulate and collect data for perturbed model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+disp('Simulating perturbed systems');
+time_estimated = (time_elapsed*length(parameters))/60;
+disp(sprintf('Estimated time for simulations: %5.1f minutes.\n',time_estimated));
+xpert = {};
+tepert = {};
+iepert = {};
+for k = 1:length(parameters),
+    % determine the absolute perturbation for current parameter
+    if absRel(k) == 0 || nomValues(k) == 0,
+        % absolute perturbation
+        if nomValues(k) == 0,
+            pertParamValue = nomValues(k) + pertSize(k)/100;
+        else
+            pertParamValue = nomValues(k) + pertSize(k);
+        end
+        disp(sprintf('%d) Absolute perturbation (%+g) of parameter ''%s''. Nominal: %g, perturbed: %g',k,pertSize(k),parameters{k},nomValues(k),pertParamValue));
+        if nomValues(k) == 0,
+            disp(sprintf('\tNominal value of parameter ''%s'' is zero. Using absolute perturbation instead of relative.',parameters{k}));
+            absRel(k) = 0;
+            pertSize(k) = pertSize(k)/100;
+        end
+    else
+        % relative perturbation
+        pertParamValue = nomValues(k) * (1 + pertSize(k)/100);
+        disp(sprintf('%d) Relative perturbation (%+g%%) of parameter ''%s''. Nominal: %g, perturbed: %g',k,pertSize(k),parameters{k},nomValues(k),pertParamValue));
+    end
+    % sbm is the original model - determine a perturbed model modelpert -
+    % and create an ODE file and event functions for it
+    sbmpert = SBparameters(sbm,parameters{k},pertParamValue);
+    [ODEfctname, ODEfilefullpath, DATAfctname, EVENTfctname, EVENTASSGNfctname] = SBcreateTempODEfile(sbmpert,0,1);
+    % simulate over transient time horizont
+    [t,x]=eventsimulateSB(ODEfctname,integrator,time_transient,initialCondition,integratorOptions,eventFunction,EVENTASSGNfctname);
+    precollectInitialCondition = x(end,:);
+    [tpre,xpre]=eventsimulateSB(ODEfctname,integrator,time_precollect,precollectInitialCondition,integratorOptions,eventFunction,EVENTASSGNfctname);
+    % now prepare for the simulation to collect data - first get the initial condition for the simulation
+    collectDataInitialCondition = xpre(end,:); 
+    eventValues = min(xpre)+0.6*(max(xpre)-min(xpre));
+    % simulate the nominal system
+    [t2,xpertk,tepertk,xepertk,iepertk]=eventsimulateSB(ODEfctname,integrator,time,collectDataInitialCondition,integratorOptions,eventFunction,EVENTASSGNfctname);
+    % process tepertk,xepertk, and iepertk to only keep the event data that belongs
+    % to events from the event function that is important for the sensitivity
+    % analysis
+    eventData = [tepertk xepertk iepertk];
+    modelEventIndices = find(ismember(iepertk,[1:numberModelEvents]));
+    eventFunctionEvents = setdiff(1:length(iepertk),modelEventIndices);
+    eventData = eventData(eventFunctionEvents,:);
+    tepertk = eventData(:,1);
+    xepertk = eventData(:,2:end-1);
+    iepertk = eventData(:,end)-numberModelEvents;
+    % select only the components specified in componentNames
+    xpert{k} = xpertk;
+    tepert{k} = tepertk;
+    iepert{k} = iepertk;
+    % delete all temporary m files
+    deleteTempODEfileSB(ODEfilefullpath);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONVERTING EVENT DATA PERTURBED CASE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% time-events from event data is collected as column vector where the
+% time-instants of all events are listed. the data needs to be converted 
+% in order to easily determine which time instant corresponds to which
+% event
+tepertOutput = {};
+for k1 = 1:length(parameters),
+    tepertConvertedElement = cell(1,length(collectDataInitialCondition));
+    iepertk = iepert{k1};
+    tepertk = tepert{k1};
+    for k2 = 1:length(iepertk),
+        indexEvent = iepertk(k2);
+        element = tepertConvertedElement{indexEvent};
+        element = [element tepertk(k2)];
+        tepertConvertedElement{indexEvent} = element;
+    end
+    tepertOutput{k1} = tepertConvertedElement;
+end
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONSTRUCT OUTPUT STRUCTURE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output = [];
+output.model = sbm;
+output.time = time;
+output.tenom = tenomOutput;
+output.tepert = tepertOutput;
+output.states = states;
+output.xnom = xnom;
+output.xpert = xpert;
+output.parameters = parameters;
+output.nomvalues = nomValues;
+output.pertSize = pertSize;
+output.absRel = absRel;
+return
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/localparametersensitivity/SBsensdatastat.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/localparametersensitivity/SBsensdatastat.m
new file mode 100644
index 0000000000000000000000000000000000000000..7a13730954513bff03403f15f7a5a21899b6c079
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/localparametersensitivity/SBsensdatastat.m
@@ -0,0 +1,297 @@
+function [output] = SBsensdatastat(varargin)
+% SBsensdatastat: Function allowing to generate steady-state data that 
+% subsequently can be used for different kinds of parametric sensitivity 
+% analyses. 
+%
+% The data is obtained by determining the steady-states of the nominal 
+% and perturbed systems. In each calculation of a perturbed system only 
+% a single parameter is perturbed.
+% As initial guess for the steady-state the initial conditions stored in the
+% model are used. As nominal parameter values the parameter values stored
+% in the model are used.
+% In case the considered steady-state is unstable at least a good guess of
+% the steady-state needs to be given in the model.
+%  
+% USAGE:
+% ======
+% [output] = SBsensdatastat(model)
+% [output] = SBsensdatastat(model,parameters)
+% [output] = SBsensdatastat(model,parameters,pertSize,absRel)
+% [output] = SBsensdatastat(model,parameters,pertSize,absRel,options)
+%
+% model: SBmodel (not useable with ODE model file)
+% parameters: a cell-array with parameter names, determining the parameters
+%       that are to be considered in the analysis.
+% pertSize: either a scalar value, determining the perturbation to be
+%       applied to each of the parameters, or a vector of same length as
+%       the number of considered parameters, allowing to choose a different 
+%       perturbation for each parameter.
+% absRel: either a scalar (0 or 1), or a vector of the same length as
+%       pertSize. 0 means that the corresponding element in pertSize
+%       determines an absolute perturbatiom, 1 means it determines a
+%       relative perturbation in percent.
+% OPTIONS: this is a data structure defining the options for the
+%       SBsteadystate function that is used here. 
+%          OPTIONS.TolFun: Tolerance for max element in function evaluation
+%          OPTIONS.tol: Tolerance for the determination of the number of algebraic
+%               relationships in the model. If the method fails than this
+%               might be due to a wrong rank computation and in this case
+%               the tolerance should be increased. If set, the same tolerance
+%               setting is used when determining the indices of the
+%               dependent variables.
+%          OPTIONS.MaxIter: Maximum number of iterations
+%          OPTIONS.Delta: Step length for numerical differentiation to obtain 
+%               the Jacobian.
+%
+% DEFAULT VALUES:
+% ===============
+%   The only required input argument is 'model'.
+%   If not specified otherwise, following default values are used:
+%
+%   parameters = all parameters in the model
+%   pertSize = 1 (percent)
+%   absRel = 1 (relative perturbation)
+%   OPTIONS = [] (default options of the SBsteadystate function)
+%
+% OUTPUT:
+% =======
+% The output argument 'output' is a MATLAB struct element with the
+% following structure:
+%
+%   output.model            model as obtained as input argument
+%   output.states           cell-array with names of states as elements
+%   output.xssnom           vector containing the steady-state values of
+%                           the states of the nominal system 
+%   output.xsspert          cell-array, where each entry correponds to 
+%                           a vector containing the steady-state of the
+%                           states of the perturbed systems
+%   output.reactions        cell-array with names of reactions as elements
+%   output.rssnom           vector containing the steady-state values of
+%                           the reaction rates of the nominal system 
+%   output.rsspert          cell-array, where each entry correponds to 
+%                           a vector containing the steady-state of the
+%                           reaction rates of the perturbed systems
+%   output.parameters       same as the input argument 'parameters' -
+%                           either its default or the passed values
+%   output.nomvalues        nominal values of parameters in above field
+%   output.pertSize         same as the input argument 'pertSize' -
+%                           either its default or the passed values
+%   output.absRel           same as the input argument 'absRel' -
+%                           either its default or the passed values
+%
+% The reason of using a struct element as output is that the output of 
+% SBsensdatastat usually needs to be processed by other functions, and the
+% calling of these functions is considerably simplified by passing all
+% important data by one element only.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK SBMODEL 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+sbm = varargin{1};
+if ~strcmp('SBmodel',class(sbm)),
+    error('This function can only be used with SBmodels, not with ODE file models!');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE NON-NUMERIC INITIAL CONDITIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% just by replacing them
+sbm = SBconvertNonNum2NumIC(sbm);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET NAME FOR ODE FILE AND MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% path to systems temporary directory
+TEMPDIR = tempdirSB;  
+% add path to temporary directory
+addpath(TEMPDIR);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLING VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 1,
+    parameters = SBparameters(sbm);
+    pertSize = ones(1,length(parameters));
+    absRel = ones(1,length(parameters));
+    states = SBstates(sbm);
+    OPTIONS = [];
+elseif nargin == 2,
+    parameters = varargin{2};
+    if ischar(parameters),
+        % adjusting for the case where just one parameter is given as a
+        % string
+        parameters = {parameters};
+    end
+    pertSize = ones(1,length(parameters));
+    absRel = ones(1,length(parameters));
+    states = SBstates(sbm);
+    OPTIONS = [];
+elseif nargin == 4,
+    parameters = varargin{2};
+    pertSize = varargin{3};
+    absRel = varargin{4};
+    states = SBstates(sbm);
+    OPTIONS = [];
+elseif nargin == 5,
+    parameters = varargin{2};
+    pertSize = varargin{3};
+    absRel = varargin{4};
+    states = SBstates(sbm);
+    OPTIONS = varargin{5};
+else
+    error('Incorrect number of input arguments.');
+end
+% check if parameters defined by a cell-array 
+% if not then convert
+if ischar(parameters),
+    parameters = {parameters};
+end
+% adjust scalar elements in pertSize and absRel to number of parameters
+if length(pertSize) == 1,
+    pertSize = pertSize*ones(1,length(parameters));
+end
+if length(absRel) == 1,
+    absRel = absRel*ones(1,length(parameters));
+end
+% check length of parameters, pertSize and absRel
+if length(parameters) ~= length(pertSize) || length(parameters) ~= length(absRel),
+    error(sprintf('Check the number of elements in ''parameters'', ''pertSize'', and ''absRel''\ninput arguments. They should have the same number of elements!'));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SETTING OTHER VARIABLES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% determining the nominal values for the parameters
+[allParameters, allParameterValues] = SBparameters(sbm);
+nomValues = [];
+errorText = '';
+for k1 = 1:length(parameters),
+    parameterFound = 0;
+    for k2 = 1:length(allParameters),
+        if strcmp(parameters{k1},allParameters{k2}),
+            nomValues = [nomValues, allParameterValues(k2)];
+            parameterFound = 1;
+            break;
+        end
+    end
+    if parameterFound == 0,
+        errorText = sprintf('%sParameter ''%s'', given in input arguments could not be found in the model.\n',errorText,parameters{k1});
+    end
+end
+if ~isempty(errorText),
+    errorText = sprintf('%sThe available parameters in the model are:\n',errorText);
+    for k = 1:length(allParameters),
+        errorText = sprintf('%s\n%s',errorText,allParameters{k});
+    end    
+    error(errorText);    
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INFO MESSAGE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+disp('Collecting data for sensitivity analysis by steady-state calculations.');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine steady-state for nominal model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+tic
+disp('Steady-state computation for nominal system');
+[xnom,residual,message] = SBsteadystate(sbm,SBinitialconditions(sbm),OPTIONS);
+if isempty(xnom),
+    error('No steady-state could be found. Please try another starting guess.');
+end
+[dummy1,dummy2,dummy3,dummy4,rnom] = SBreactions(sbm,xnom);
+rnom(find(abs(rnom)<eps)) = 0;
+time_elapsed = toc;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine steady-states for perturbed models
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+disp('Steady-state computation for perturbed systems');
+time_estimated = (time_elapsed*length(parameters))/60;
+disp(sprintf('Estimated time for calculations: %5.1f minutes.\n',time_estimated));
+xpert = {};
+rpert = {};
+nanindices = [];
+for k = 1:length(parameters),
+    % determine the absolute perturbation for current parameter
+    if absRel(k) == 0 || nomValues(k) == 0,
+        % absolute perturbation
+        if nomValues(k) == 0,
+            pertParamValue = nomValues(k) + pertSize(k)/100;
+        else
+            pertParamValue = nomValues(k) + pertSize(k);
+        end
+        disp(sprintf('%d) Absolute perturbation (%+g) of parameter ''%s''. Nominal: %g, perturbed: %g',k,pertSize(k),parameters{k},nomValues(k),pertParamValue));
+        if nomValues(k) == 0,
+            disp(sprintf('\tNominal value of parameter ''%s'' is zero. Using absolute perturbation instead of relative.',parameters{k}));
+            absRel(k) = 0;
+            pertSize(k) = pertSize(k)/100;
+        end
+    else
+        % relative perturbation
+        pertParamValue = nomValues(k) * (1 + pertSize(k)/100);
+        disp(sprintf('%d) Relative perturbation (%+g%%) of parameter ''%s''. Nominal: %g, perturbed: %g',k,pertSize(k),parameters{k},nomValues(k),pertParamValue));
+    end
+    % sbm is the original model - determine a perturbed model modelpert -
+    % and create an ODE file for it. rehash the path
+    sbmpert = SBparameters(sbm,parameters{k},pertParamValue);
+    % get steady-state for perturbed system
+    [xpertk,residual,message] = SBsteadystate(sbmpert,SBinitialconditions(sbmpert),OPTIONS);
+    % handle the case when the steady-state computation does not converge
+    if isempty(xpertk),
+        disp(sprintf('\nNo convergence for parameter ''%s''. Check shown residual and eventually modify the options.\n',parameters{k}));
+        xpertk = NaN(length(SBinitialconditions(sbmpert)),1);
+        nanindices(end+1) = k;
+    end
+    xpert{k} = real(xpertk);
+    [dummy1,dummy2,dummy3,dummy4,rpertk] = SBreactions(sbmpert,xpert{k});
+    rpertk(find(abs(rpertk)<eps)) = 0;
+    rpert{k} = rpertk;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% REMOVE NaN Elements
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+keepindices = setdiff([1:length(parameters)],nanindices);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONSTRUCT OUTPUT STRUCTURE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output = [];
+output.model = sbm;
+output.states = states;
+output.xssnom = xnom;
+output.xsspert = xpert(keepindices);   
+output.reactions = SBreactions(sbm);     
+output.rssnom = rnom;          
+output.rsspert = rpert(keepindices);         
+output.parameters = parameters(keepindices);  
+output.nomvalues = nomValues(keepindices);
+output.pertSize = pertSize(keepindices);      
+output.absRel = absRel(keepindices);          
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/localparametersensitivity/SBsensperiod.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/localparametersensitivity/SBsensperiod.m
new file mode 100644
index 0000000000000000000000000000000000000000..1cc1a0993dd318b20961484914b95397e01ae571
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/localparametersensitivity/SBsensperiod.m
@@ -0,0 +1,214 @@
+function [varargout] = SBsensperiod(datastructure)
+% SBsensperiod: Function evaluating local first order period sensitivities.
+% 
+% USAGE:
+% ======
+% [output,plotDataS,plotDataSn] = SBsensperiod(datastructure)
+% [] = SBsensperiod(datastructure)
+%
+% datastructure: output, returned by the function SBsensdataosc
+%
+% Output Arguments:
+% =================
+% If no output argument is given, the determined data are plotted using the
+% function SBplot2. 
+%
+% The output argument 'output' is a MATLAB struct element with the
+% following structure:
+%
+%   output.S                matrix, with elements S_ij, defined below
+%   output.namesS           cell-array with state names for 
+%                           which the analysis has been done (for the
+%                           non-normalized sensitivities)
+%   output.parametersS      cell-array with names of parameters used in
+%                           analysis (for the non-normalized sensitivities)
+%   output.Sn               same as S, but the sensitivities are normalized
+%   output.namesSn          cell-array with state names for 
+%                           which the analysis has been done (for the
+%                           normalized sensitivities)
+%   output.parametersSn     cell-array with names of parameters used in
+%                           analysis (for the normalized sensitivities)
+%
+% The reason for having different fields for parameters and names for the
+% non-normalized and normalized sensitivities is due to the fact that zero
+% nominal parameter values lead to zero normalized sensitivities for these
+% parameters, and that zero nominal steady-state values of states lead to
+% infinite normalized sensitivities. In these cases the normalized
+% sensitivities for these parameters and states are not determined. 
+%
+% The plotDataS and plotDataSn output arguments are datastructures that 
+% can directly be used as input arguments for SBplot2 for visualization
+% of the sensitivity analysis results. For information about how this data 
+% structure is defined please refer to the help text provided for the
+% SBplot2 function.
+%
+% Theory:
+% =======
+% The period sensitivity wrt to the parameter p_j is defined by:
+%
+% S_j = [ T(p_j+delta_p_j) - T(p_j) ] / delta_p_j
+%
+% where T(p) defines the period of the system for a given parameter
+% setting. The period is determined from the input arguments tenom and
+% tepert. tenom and tepert are determined by the function SBsensdata. The
+% elements in these variables determine time instants at which the first
+% component in componentNames passes in the same direction through the
+% value that this component has at the end of the transient period.
+%
+% The normalized sensitivity index is defined by
+%
+% Sn_j = p_j/T(p_j) * S_j(t)
+%
+% The function T(p) is called an objective function (Varma et al. 
+% (1999) Parametric Sensitivity in Chemical Systems, Cambridge 
+% University Press, New York) and has been used in this form, e.g., by 
+% Stelling et al. (2004) Robustness properties of circadian clock 
+% architectures, PNAS, vol 101 (36), 13210-13215.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+states = datastructure.states;
+parameters = datastructure.parameters;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Output some information about the algorithm
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+disp(sprintf('Determination of period sensitivities'));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determining period sensitivities
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% determine the period for the nominal case (for the chosen state only)
+tenom = datastructure.tenom;
+Tnom = [];
+for k = 1:length(tenom)
+    tenomk = tenom{k};
+    Tnomk = sum(tenomk(2:end)-tenomk(1:end-1))/(length(tenomk)-1);
+    Tnom = [Tnom, Tnomk];
+end
+% determine the period for the perturbed cases (for the chosen state only)
+Tpert = [];
+tepert = datastructure.tepert;
+for k1 = 1:length(tepert),
+    tepertk1 = tepert{k1};
+    Tpertk1 = [];
+    for k2 = 1:length(tepertk1),
+        tepertk2 = tepertk1{k2};
+        if length(tepertk2) < 2,
+            Tpertk2 = 0;
+        else
+            Tpertk2 = sum(tepertk2(2:end)-tepertk2(1:end-1))/(length(tepertk2)-1);
+        end
+        Tpertk1 = [Tpertk1, Tpertk2];
+    end
+    Tpert = [Tpert; Tpertk1];
+end
+% determine the difference of the periods
+Tdif = [];
+for k = 1:size(Tpert,1),
+    Tdifk = Tpert(k,:)-Tnom;
+    Tdif = [Tdif; Tdifk];
+end
+% now scale the elements of Tdif with 1/deltaPert, where deltaPert
+% is the absolute perturbation to the corresponding parameter
+pertVector = [];
+for k = 1:length(datastructure.nomvalues),
+    % Determination of the absolute size of the perturbation
+    if datastructure.absRel(k) == 0,
+        % absolute perturbation
+        deltaPert = datastructure.pertSize(k);
+    else
+        % relative perturbation
+        deltaPert = datastructure.nomvalues(k) * datastructure.pertSize(k)/100;
+    end
+    pertVector = [pertVector deltaPert];
+end    
+% do the scaling
+S = [inv(diag(pertVector)) * Tdif]';
+% determine the normalized sensitivity
+% in case of zero nominal values for parameters take out those parameters
+% in case of zero nominal values for states and/or reactions take out those
+% states or reactions
+% first do the scaling
+Sn = [];
+help = S*diag(datastructure.nomvalues);
+for k = 1:size(S,1),
+    Tnomk = Tnom(k);
+    if Tnomk ~= 0,
+        Snrowk = help(k,:)/Tnomk;
+    else
+        Snrowk = 0*ones(1,size(S,2));
+    end
+    Sn(k,:) = Snrowk;
+end
+% now retain only the elements in Sn that correspond to non-zero nominal 
+% values of parameters and Tnom
+parametersNonZeroIndex = find(datastructure.nomvalues~=0);
+statesNonZeroIndex = find(Tnom~=0);
+Sn = Sn(statesNonZeroIndex,parametersNonZeroIndex);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Construct output variable
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output.S = S;
+output.statesS = datastructure.states;
+output.parametersS = parameters;
+output.Sn = Sn;
+output.statesSn = datastructure.states(statesNonZeroIndex);
+output.parametersSn = parameters(parametersNonZeroIndex);
+
+plotdatastruct.name = 'Normalized Period Sensitivities';
+plotdatastruct.xnames = output.parametersSn;
+plotdatastruct.ynames = output.statesSn;
+plotdatastruct.data = output.Sn;
+plotdatastruct.title = 'Normalized Period Sensitivities';
+plotdatastruct.xlabel = 'Parameters';
+plotdatastruct.xaxistitle = 'Parameters';
+plotdatastruct.yaxistitle = 'States';
+
+plotdatastruct2.name = 'Period Sensitivities';
+plotdatastruct2.xnames = output.parametersSn;
+plotdatastruct2.ynames = output.statesSn;
+plotdatastruct2.data = output.S;
+plotdatastruct2.title = 'Period Sensitivities';
+plotdatastruct2.xlabel = 'Parameters';
+plotdatastruct2.xaxistitle = 'Parameters';
+plotdatastruct2.yaxistitle = 'States';
+
+if nargout == 1,
+    varargout{1} = output;
+elseif nargout == 2,
+    varargout{1} = output;
+    varargout{2} = plotdatastruct2;
+elseif nargout == 3,
+    varargout{1} = output;
+    varargout{2} = plotdatastruct2;
+    varargout{3} = plotdatastruct;
+elseif nargout == 0,
+    SBplot2(plotdatastruct,plotdatastruct2);
+else
+    error('Incorrect number of output arguments.');
+end
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/localparametersensitivity/SBsensstat.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/localparametersensitivity/SBsensstat.m
new file mode 100644
index 0000000000000000000000000000000000000000..4059967f3f7fea436e8b8ffd86aec16df97813ba
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/localparametersensitivity/SBsensstat.m
@@ -0,0 +1,219 @@
+function [varargout] = SBsensstat(datastructure)
+% SBsensstat: Function evaluating local first order parameter sensitivities
+% of the steady-state values of states and reaction rates.
+%
+% USAGE:
+% ======
+% [output,plotDataS,plotDataSn] = SBsensstat(datastructure)
+% [] = SBsensstat(datastructure)
+%
+% datastructure: output, returned by the function SBsensdatastat
+%
+% Output Arguments:
+% =================
+% If no output argument is given, the determined data are plotted using the
+% function SBplot2. 
+%
+% The output argument 'output' is a MATLAB struct element with the
+% following structure:
+%
+%   output.S                matrix, with elements S_ij, defined below
+%   output.namesS           cell-array with state and reaction names for 
+%                           which the analysis has been done (for the
+%                           non-normalized sensitivities)
+%   output.parametersS      cell-array with names of parameters used in
+%                           analysis (for the non-normalized sensitivities)
+%   output.Sn               same as S, but the sensitivities are normalized
+%   output.namesSn          cell-array with state and reaction names for 
+%                           which the analysis has been done (for the
+%                           normalized sensitivities)
+%   output.parametersSn     cell-array with names of parameters used in
+%                           analysis (for the normalized sensitivities)
+%
+% The reason for having different fields for parameters and names for the
+% non-normalized and normalized sensitivities is due to the fact that zero
+% nominal parameter values lead to zero normalized sensitivities for these
+% parameters, and that zero nominal steady-state values of states or
+% reaction rates lead to infinite normalized sensitivities. In these cases
+% the normalized sensitivities for these parameters and states/reaction
+% rates are not determined.
+%
+% The plotDataS and plotDataSn output arguments are datastructures that 
+% can directly be used as input arguments for SBplot2 for visualization
+% of the sensitivity analysis results. For information about how this data 
+% structure is defined please refer to the help text provided for the
+% SBplot2 function.
+%
+% Theory:
+% =======
+% The steady-state sensitivity for the i-th element (state or reaction rate)
+% x_i wrt to the parameter p_j is defined by:
+%
+% S_ij = [ Xss_i(p_j+delta_p_j) - Xss_i(p_j) ] / delta_p_j
+%
+% where Xss_i is the function returning the steady-state for this element
+% (state or reaction rate) for the given parameters.
+%
+% The normalized sensitivity index is defined by
+%
+% Sn_ij = p_j/Xss_i(p_j) * S_ij
+%
+% The function Xss(p) is here used as objective function (Varma et al. 
+% (1999) Parametric Sensitivity in Chemical Systems, Cambridge 
+% University Press, New York).
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+states = datastructure.states;
+reactions = datastructure.reactions;
+parameters = datastructure.parameters;
+% combine states and reactions into elements
+elements = {};
+elementindex = 1;
+for k = 1:length(states),
+    elements{elementindex} = sprintf('%s (state)',states{k});
+    elementindex = elementindex + 1;
+end
+for k = 1:length(reactions),
+    elements{elementindex} = sprintf('%s (reaction rate)',reactions{k});
+    elementindex = elementindex + 1;
+end
+elementsdatanom = [datastructure.xssnom; datastructure.rssnom];
+elementsdatapert = {};
+for k = 1:length(parameters),
+    statespert = datastructure.xsspert{k};
+    reactionratespert = datastructure.rsspert{k};
+    elementsdatapert{k} = [statespert(:); reactionratespert(:)];
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Output some information about the algorithm
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+disp(sprintf('Determination of steady-state sensitivities'));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determining steady-state sensitivities
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% nominal values
+Xssnom = elementsdatanom;
+% initialize difference matrix
+Xssdif = [];
+for k = 1:length(elementsdatapert),
+    xsspertk = elementsdatapert{k};
+    % determine the difference
+    Xssdif = [Xssdif xsspertk-Xssnom];
+end
+% now scale the elements in the columns with 1/deltaPert, where deltaPert
+% is the absolute perturbation to the corresponding parameter
+pertVector = [];
+for k = 1:length(datastructure.nomvalues),
+    % Determination of the absolute size of the perturbation
+    if datastructure.absRel(k) == 0,
+        % absolute perturbation
+        deltaPert = datastructure.pertSize(k);
+    else
+        % relative perturbation
+        deltaPert = datastructure.nomvalues(k) * datastructure.pertSize(k)/100;
+    end
+    pertVector = [pertVector deltaPert];
+end    
+% determine the sensitivities
+S = Xssdif * inv(diag(pertVector));
+% determine the normalized sensitivity
+% in case of zero nominal values for parameters take out those parameters
+% in case of zero nominal values for states and/or reactions take out those
+% states or reactions
+% first do the scaling
+Sn = [];
+help = S*diag(datastructure.nomvalues);
+for k = 1:size(S,1),
+    Xssnomk = Xssnom(k);
+    if Xssnomk ~= 0,
+        Snrowk = help(k,:)/Xssnomk;
+    else
+        Snrowk = 0*ones(1,size(S,2));
+    end
+    Sn(k,:) = Snrowk;
+end
+% now all parameters with zero nominal values correspond to zero columns in
+% Sn and all elements with zero nominal steady-state values correspond to 
+% zero rows
+if size(Sn,2) > 1,
+    parametersNonZeroIndex = find(sum(abs(Sn))~=0);
+    elementsNonZeroIndex = find(sum(abs(Sn'))~=0);
+    Sn = Sn(elementsNonZeroIndex,parametersNonZeroIndex);
+else
+    parametersNonZeroIndex = find(datastructure.nomvalues~=0);
+    elementsNonZeroIndex = find(abs(Sn)~=0);
+end    
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Construct output variable
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output.S = S;
+output.namesS = elements;
+output.parametersS = parameters;
+output.Sn = Sn;
+output.namesSn = elements(elementsNonZeroIndex);
+output.parametersSn = parameters(parametersNonZeroIndex);
+
+plotdatastruct.name = 'Normalized Steady-State Sensitivities';
+plotdatastruct.xnames = output.parametersSn;
+plotdatastruct.ynames = output.namesSn;
+plotdatastruct.data = output.Sn;
+plotdatastruct.title = 'Normalized Steady-State Sensitivities';
+plotdatastruct.xlabel = 'Parameters';
+plotdatastruct.xaxistitle = 'Parameters';
+plotdatastruct.yaxistitle = 'States and Reaction Rates';
+
+plotdatastruct2.name = 'Steady-State Sensitivities';
+plotdatastruct2.xnames = output.parametersS;
+plotdatastruct2.ynames = output.namesS;
+plotdatastruct2.data = output.S;
+plotdatastruct2.title = 'Steady-State Sensitivities';
+plotdatastruct2.xlabel = 'Parameters';
+plotdatastruct2.xaxistitle = 'Parameters';
+plotdatastruct2.yaxistitle = 'States and Reaction Rates';
+
+if nargout == 1,
+    varargout{1} = output;
+elseif nargout == 2,
+    varargout{1} = output;
+    varargout{2} = plotdatastruct2;
+elseif nargout == 3,
+    varargout{1} = output;
+    varargout{2} = plotdatastruct2;
+    varargout{3} = plotdatastruct;
+elseif nargout == 0,
+    % Check if at least any non-zero sensitivity - otherwise don't plot
+    if sum(sum(abs(S))) > eps,
+        SBplot2(plotdatastruct,plotdatastruct2);
+    else
+        disp('All sensitivities are zero');
+    end
+else
+    error('Incorrect number of output arguments.');
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/localparametersensitivity/auxiliary/periodeventfunctionSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/localparametersensitivity/auxiliary/periodeventfunctionSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..2dbf510be21e704e83bd5527d85a5757c7200c6b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/localparametersensitivity/auxiliary/periodeventfunctionSB.m
@@ -0,0 +1,53 @@
+function [value,isterminal,direction] = periodeventfunctionSB(t,x)
+% periodeventfunctionSB: The purpose of this function is to collect
+% time information during simulation that allows to determine
+% the period of an oscillating system. This is realized by letting the
+% intergrator check for events that correspond to state values crossing a
+% certain threshold in positive direction.  
+% 
+% USAGE:
+% ======
+% This function is used by the function 'SBsensdataosc'
+%
+% The function requires the presence of 1 global variable that is defined
+% in 'SBsensdataosc':
+% 
+% eventValues: that are values of the states at which an event is triggered
+%              if the current state values pass these values in positive direction.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+% instead of having this global variable one also can hardcode certain
+% values of interest, when considering a certain problem.
+global eventValues 
+
+% Locate the time when the states determined by the out-indices  
+% pass the value defined by 'eventValues' in positive direction
+% The next three lines can be changed in order to customize the event
+% handling and to collect other data for sensitivity analysis
+value = eventValues(:)-x(:);
+isterminal = zeros(length(x),1);    % never stop the integration due to events
+direction =  ones(length(x),1);     % positive direction
+return
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/localparametersensitivity/auxiliary/periodeventfunctioneventsSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/localparametersensitivity/auxiliary/periodeventfunctioneventsSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..1fdd064a0bf3a78514fb996b7c6390ffedef3b54
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/analysis/localparametersensitivity/auxiliary/periodeventfunctioneventsSB.m
@@ -0,0 +1,70 @@
+function [value,isterminal,direction] = periodeventfunctioneventsSB(t,x,varargin)
+% periodeventfunctioneventsSB: This function has two purposes. The main
+% purpose is to collect information time information during simulation that
+% allows to determine the period of an oscillating system. This is realized
+% by letting the intergrator check for events that correspond to state
+% values crossing a certain threshold in positive direction. 
+% The second purpose is to generate events at which integrator has to be
+% stopped, the states reinitialized (according to the events that are
+% present in the model) and restarted.
+% 
+% USAGE:
+% ======
+% This function is used by the function 'SBsensdataoscevents'
+%
+% The function requires the presence of 2 global variables that are defined
+% in 'SBsensdataoscevents':
+% 
+% eventValues: that are values of the states at which an event is triggered
+%              if the current state values pass these values in positive direction.
+% eventHandleFunction: this is the name (string) of a function that handles
+%              the events that are present in the model
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+% instead of 'eventValues' as global variable one also can hardcode certain
+% values of interest, when considering a certain problem.
+global eventValues EVENTfctname
+
+% First implement the event handling for the events that are present in the model
+% This line should not be changed in custom event handling functions that
+% are to be used when doing sensitivity analysis
+
+% pass empty elements for the parameters and parametervalues functions
+[valueModel,isterminalModel,directionModel] = feval(EVENTfctname,t,x,varargin{:});
+
+% Now implement the events that are required to determine the period time
+% Locate the time when the states determined by the out-indices  
+% pass the values in 'eventValues' in positive direction
+% The next three lines can be changed in order to customize the event
+% handling and to collect other data for sensitivity analysis
+valuePeriod = eventValues(:)'-x(:)';
+isterminalPeriod = zeros(1,length(x));    % never stop the integration due to these events
+directionPeriod =  ones(1,length(x));     % positive direction
+
+% Combine the two event functions
+value = [valueModel valuePeriod];
+isterminal = [isterminalModel isterminalPeriod];
+direction = [directionModel directionPeriod];
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/gui/SBeditBC_dir/SBeditBC.fig b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/gui/SBeditBC_dir/SBeditBC.fig
new file mode 100644
index 0000000000000000000000000000000000000000..73dd3659ef6fa60e5a16420999e937f336e5959d
Binary files /dev/null and b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/gui/SBeditBC_dir/SBeditBC.fig differ
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/gui/SBeditBC_dir/SBeditBC.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/gui/SBeditBC_dir/SBeditBC.m
new file mode 100644
index 0000000000000000000000000000000000000000..158de1b64c33e6a785c1afabfd9550a28a7c4491
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/gui/SBeditBC_dir/SBeditBC.m
@@ -0,0 +1,778 @@
+function varargout = SBeditBC(varargin)
+% SBeditBC: GUI for editing SBmodels in a more biochemically oriented format
+%
+% USAGE:
+% ======
+% [model] = SBeditBC()
+% [model] = SBeditBC(modelin)
+%
+% modelin: input SBmodel for editing
+%
+% Output Arguments:
+% =================
+% model: edited SBmodel as output
+%
+%
+% Explanation of differences between an ODE based model and a model in 
+% biochemical representation =========================================
+% ===========================
+% - All states in the biochemical representation correspond to species.
+% - In the "STATE INFORMATION"-part of the model description initial
+% conditions and optional information is entered. Additionally ODEs for
+% states can be defined just as in SBedit (except that the additional
+% information and the comment then is added after the initial condition and
+% not after the ODE).
+% - In the "REACTIONS"-part of the model reaction equations are defined,
+% instead of reaction rates. Please refer to the help text in the SBeditBC
+% GUI for more information about the syntax.
+% - All reaction rates are expected to have amount/time units. As long as
+% no compartments are present in the model or that all compartment sizes
+% are equal to 1, amount/time and concentration/time will give the same
+% result.
+%
+% Explanation of the OPTIONAL INFORMATION 
+% =======================================
+% States, parameters, and variables can be provided with additional
+% information that is optional. This information is required for the export
+% to SBML and for the conversion of an ODE based description of an SBmodel
+% to a biochemical representation of an SBmodel and vice versa.
+%
+% For species the additional information has the following syntax:
+%     {'isSpecie':speciescompartment:speciesunittype}
+% the speciescompartment is a string with the name of the compartment the
+% species is located in. this compartment name has to be the name of a
+% variable, or a parameter that is defined as a compartment (see
+% below). The speciesunittype is either 'amount' or 'concentration'. 
+%
+% For compartments the additional information has the following syntax:
+%     {'isCompartment':nameoutsidecompartment}
+% where nameoutsidecompartment is a string with the name of the outside
+% compartment. if there is no outside compartment the name should be
+% represented by an empty string. example - correct: {'isCompartment':}. 
+% example - wrong: {'isCompartment'} (missing ':').
+%
+% For constant values (parameters) the additional information has the following syntax:
+%     {'isParameter'}
+%
+% As long as no compartments are present in the model and the model is not
+% supposed to be exported to SBML the optional infomation is not required
+% to be present.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+% Begin initialization code - DO NOT EDIT
+gui_Singleton = 1;
+gui_State = struct('gui_Name',       mfilename, ...
+                   'gui_Singleton',  gui_Singleton, ...
+                   'gui_OpeningFcn', @SBeditBC_OpeningFcn, ...
+                   'gui_OutputFcn',  @SBeditBC_OutputFcn, ...
+                   'gui_LayoutFcn',  [], ...
+                   'gui_Callback',   []);
+if nargin && ischar(varargin{1})
+   gui_State.gui_Callback = str2func(varargin{1});
+end
+if nargout
+    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
+else
+    gui_mainfcn(gui_State, varargin{:});
+end
+% End initialization code - DO NOT EDIT
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GUI STANDARD FUNCTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OPENING FUNCTION (AFTER CREATION)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function SBeditBC_OpeningFcn(hObject, eventdata, handles, varargin)
+academicWarningSB
+
+% Process input argument
+nvarargin = nargin-3;
+textModel = 0;
+if nvarargin == 0,
+    % start with empty SBmodel
+    sbm = SBmodel();
+else
+    if strcmp('SBmodel',class(varargin{1})),
+        sbm = varargin{1};
+    else 
+        error('Input argument of unknown type');
+        delete(hObject);
+    end
+end
+try
+    handles.editText = convertModelToTextBCSB(sbm);  
+catch
+    if nvarargin ~= 0,
+        handles.editText.name = sprintf('Error converting the SBmodel to the biochemical representation!\n%s',lasterr);
+    else 
+        handles.editText.name = '';
+    end
+    handles.editText. notes = '';
+    handles.editText.states = '';
+    handles.editText.parameters = '';
+    handles.editText.variables = '';
+    handles.editText.reactions = '';
+    handles.editText.events = '';
+    handles.editText.functions = '';
+    handles.editText.functionsMATLAB = '';
+end
+handles.output = sbm;               
+% Create data used by the different callbacks
+handles.helpText = getHelpText();
+handles.activeView = 'complete';
+handles.SBplotHandle = [];
+% Initialize the SBeditBC window with initial content
+set(handles.editor,'String',setPartsToCompleteTextBCSB(handles.editText));
+set(handles.helptext,'String',handles.helpText.complete);
+set(handles.headline,'String','Complete Model View');
+set(handles.time,'String','20');
+% Update handles structure
+guidata(hObject, handles);
+uiwait;
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OUTPUT TO COMMAND LINE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function varargout = SBeditBC_OutputFcn(hObject, eventdata, handles)
+% varargout  cell array for returning output args (see VARARGOUT);
+varargout{1} = handles.output;
+% close the GUI
+delete(hObject);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CLOSE CALLBACK
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function SBeditBC_CloseRequestFcn(hObject, eventdata, handles)
+% warn that last changes will get lost 
+% and let the user choose
+selection = questdlg(sprintf('Close SBeditBC?\nChanges made in the last window will get lost!\nIf you want to keep changes press the ''Exit''\nbutton instead.'),...
+                     'Close Request Function',...
+                     'Yes','No','Yes');
+switch selection,
+    case 'Yes',
+        uiresume;
+    case 'No'
+        return
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GUI SPECIALIZED FUNCTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SIMULATE CALLBACK
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function simulate_Callback(hObject, eventdata, handles)
+    global lastSimulationValue
+    errorSimulation = 0;
+    % Update all views
+    handles = updateAllViews(handles);
+    % convert the text description into an SBmodel
+    [sbm, errorFlag] = convertTextToModel(handles);
+    if ~errorFlag,
+        % get the simulation time
+        timeString = get(handles.time,'String');
+        time = str2double(timeString);
+        % Simulate SBmodel for given time
+        % catch all possible errors
+        try
+            tspan = [0:time/1000:time];
+            % handles also non-numeric ics
+            outputSimulation = SBsimulate(sbm,'ode23s',tspan,SBcalcICvector(sbm));
+        catch
+            % Process the simulation error
+            processError(lasterr,'Error during simulation');
+            errorSimulation = 1;
+        end
+        if ~errorSimulation,
+            % Try to close previous SBplot figure
+            try
+                close handles.SBplotHandle;
+            catch
+            end
+            % prepare data for plotting
+            time = outputSimulation.time;
+            datanames = {};
+            dataindex = 1;
+            for k = 1:length(outputSimulation.states),
+                datanames{dataindex} = char([double(outputSimulation.states{k}) double(' (state)')]); % fastest strcat
+                dataindex = dataindex + 1;
+            end
+            for k = 1:length(outputSimulation.variables),
+                datanames{dataindex} = char([double(outputSimulation.variables{k}) double(' (variable)')]); % fastest strcat 
+                dataindex = dataindex + 1;
+            end
+            for k = 1:length(outputSimulation.reactions),
+                datanames{dataindex} = char([double(outputSimulation.reactions{k}) double(' (reaction)')]); % fastest strcat  
+                dataindex = dataindex + 1;
+            end
+            datavalues = [outputSimulation.statevalues, outputSimulation.variablevalues, outputSimulation.reactionvalues];
+            handles.SBplotHandle = SBplot(createdatastructSBplotSB(time,datavalues,datanames));
+            % make button for updating initial conditions visible
+            set(handles.updateICsimulate,'Visible','on');
+            lastSimulationValue = outputSimulation.statevalues(end,:);
+        end
+    end
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% UPDATE INITIAL CONDITIONS WITH LAST VALUE OF SIMULATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function updateICsimulate_Callback(hObject, eventdata, handles)
+    global lastSimulationValue
+    % Update all views
+    handles = updateAllViews(handles);
+    % convert the text description into an SBmodel
+    [sbm, errorFlag] = convertTextToModel(handles);
+    if ~errorFlag,
+        % set new initial conditions (handle also non-numeric initial
+        % conditions)
+        sbm = SBoverwriteICs(sbm,lastSimulationValue);
+        % convert model to text again 
+        handles.editText = convertModelToTextBCSB(sbm); 
+        % rewrite the data in the current view (only needed if the view
+        % shows state or complete information)
+        if strcmp(handles.activeView,'states'),
+            % Update editor content with state information
+            set(handles.editor,'String',handles.editText.states);
+        elseif strcmp(handles.activeView,'complete'),
+            % Update editor content with complete information
+            completeEditText = setPartsToCompleteTextBCSB(handles.editText);
+            set(handles.editor,'String',completeEditText);
+        end
+    end
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% STEADY-STATE CALLBACK
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function steadystate_Callback(hObject, eventdata, handles)
+    global steadyStateValues
+    errorSteadyState = 0;
+    % Update all views
+    handles = updateAllViews(handles);
+    % convert the text description into an SBmodel
+    [sbm, errorFlag] = convertTextToModel(handles);
+    if ~errorFlag,
+        % get the steady-state
+        try
+            [steadystate,residual,message] = SBsteadystate(sbm);
+        catch
+            % Process the steadystate error
+            processError(lasterr,'Error during steady-state computation');
+            errorSteadyState = 1;
+        end
+        if ~errorSteadyState,
+            % construct result text and display it in the editor window
+            resultText = sprintf('%s',message);
+            if ~isempty(steadystate),
+                resultText = sprintf('%s\nThe steady-state is given by:\n',message);
+                SBstructure = SBstruct(sbm);
+                for k = 1:length(SBstructure.states),
+                    stateName = SBstructure.states(k).name;
+                    resultText = sprintf('%s\n%s = %g',resultText,stateName,steadystate(k));
+                end
+                % make button for updating initial conditions visible
+                set(handles.updateIC,'Visible','on');
+                steadyStateValues = steadystate;
+            else
+                resultText = sprintf('%s\nIn order to start at a different steady-state you can change to initial conditions for the states. Changing the options of the steady-state solver is only possible from the command line version of SBsteadystate',resultText);
+            end
+            set(handles.editor,'String',resultText);
+            % Update help text with complete help
+            set(handles.helptext,'String',handles.helpText.steadystate);
+            % Update headline text
+            set(handles.headline,'String','Steady State of Model');
+            % Set new active view
+            handles.activeView = 'steadystate';
+        end
+    end
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% UPDATE INITIAL CONDITIONS WITH STEADY STATE INFORMATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function updateIC_Callback(hObject, eventdata, handles)
+    global steadyStateValues
+    % Update all views
+    handles = updateAllViews(handles);
+    % convert the text description into an SBmodel
+    [sbm, errorFlag] = convertTextToModel(handles);
+    if ~errorFlag,
+        % set new initial conditions (handle also non-numeric initial
+        % conditions)
+        sbm = SBoverwriteICs(sbm,steadyStateValues);
+        % convert model to text again 
+        handles.editText = convertModelToTextBCSB(sbm);  
+    end
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXPORT TEXTBC CALLBACK
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function exportTextBC_Callback(hObject, eventdata, handles)
+    % Update all views
+    handles = updateAllViews(handles);
+    % get filename for the TXTBC file
+    [filename, pathname] = uiputfile('*.txtbc', 'Save SBmodel as .txtbc file');
+    % check if a filename returned
+    if filename ~= 0,
+        % cut of the extension from the filename
+        [path,filename,ext] = fileparts(filename);
+        % remove whitespaces from filename
+        filename = strrep(filename,' ','');
+        % add the extension
+        filepathname = strcat(pathname,'/',filename,'.txtbc');
+        % save the TextFile
+        completeEditText = setPartsToCompleteTextBCSB(handles.editText);
+        fid = fopen(filepathname,'w');
+        fwrite(fid,completeEditText);
+        status = fclose(fid);
+    end
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXPORT TEXT CALLBACK
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function exportText_Callback(hObject, eventdata, handles)
+    % Update all views
+    handles = updateAllViews(handles);
+    % get filename for the TXT file
+    [filename, pathname] = uiputfile('*.txt', 'Save SBmodel as .txt file');
+    % check if a filename returned
+    if filename ~= 0,
+        % cut of the extension from the filename
+        [path,filename,ext] = fileparts(filename);
+        % remove whitespaces from filename
+        filename = strrep(filename,' ','');
+        % add the extension
+        filepathname = strcat(pathname,'/',filename,'.txt');
+        % convert the text description into an SBmodel
+        [sbm, errorFlag] = convertTextToModel(handles);
+        if ~errorFlag,
+            % convert the model into a TEXT description
+            [modelTextStructure] = convertModelToTextSB(sbm);
+            [completeText] = setPartsToCompleteTextSB(modelTextStructure);
+            % save the text
+            fid = fopen(filepathname,'w');
+            fwrite(fid,completeText);
+            status = fclose(fid);
+        end
+    end
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXIT SBEDITBC CALLBACK
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function exit_Callback(hObject, eventdata, handles)
+    % Update all views
+    handles = updateAllViews(handles);
+    % convert the text description into an SBmodel
+    [sbm, errorFlag] = convertTextToModel(handles);
+    if ~errorFlag,
+        % set edited SBmodel as output
+        handles.output = sbm;
+    end
+    % Update handles structure
+    guidata(hObject, handles);
+    uiresume;
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GUI EDITOR BUTTONS FUNCTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EDIT COMPLETE MODEL DESCRIPTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function complete_Callback(hObject, eventdata, handles)
+    % Update all views
+    handles = updateAllViews(handles);
+    % Update editor content with complete information
+    completeEditText = setPartsToCompleteTextBCSB(handles.editText);
+    set(handles.editor,'String',completeEditText);
+    % Update help text with complete help
+    set(handles.helptext,'String',handles.helpText.complete);    
+    % Update headline text
+    set(handles.headline,'String','Complete Model View');
+    % Set new active view
+    handles.activeView = 'complete';
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EDIT NAME MODEL DESCRIPTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function name_Callback(hObject, eventdata, handles)
+    % Update all views
+    handles = updateAllViews(handles);
+    % Update editor content with name information
+    set(handles.editor,'String',handles.editText.name);
+    % Update help text with name help
+    set(handles.helptext,'String',handles.helpText.name);    
+    % Update headline text
+    set(handles.headline,'String','Model Name View');
+    % Set new active view
+    handles.activeView = 'name';
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EDIT NOTES MODEL DESCRIPTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function notes_Callback(hObject, eventdata, handles)
+    % Update all views
+    handles = updateAllViews(handles);
+    % Update editor content with notes information
+    set(handles.editor,'String',handles.editText.notes);
+    % Update help text with notes help
+    set(handles.helptext,'String',handles.helpText.notes);    
+    % Update headline text
+    set(handles.headline,'String','Model Notes View');
+    % Set new active view
+    handles.activeView = 'notes';
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% VIEW HTML NOTES CALLBACK
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function htmlnotes_Callback(hObject, eventdata, handles)
+    % Update all views
+    handles = updateAllViews(handles);
+    % Update editor content with notes information
+    set(handles.editor,'String',handles.editText.notes);
+    % Update help text with notes help
+    set(handles.helptext,'String',handles.helpText.notes);    
+    % Update headline text
+    set(handles.headline,'String','Model Notes View');
+    % Set new active view
+    handles.activeView = 'notes';
+    % get the text in the notes
+    notesText = handles.editText.notes;
+    % write this text to a temporary html file
+    filefullpath = strcat(tempnameSB,'.html');
+    fid = fopen(filefullpath,'w');
+    fprintf(fid,notesText);
+    status = fclose(fid);
+    % open and display the file
+    open(filefullpath);
+    % Update handles structure
+    guidata(hObject, handles);    
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EDIT STATES MODEL DESCRIPTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function states_Callback(hObject, eventdata, handles)
+    % Update all views
+    handles = updateAllViews(handles);
+    % Update editor content with states information
+    set(handles.editor,'String',handles.editText.states);
+    % Update help text with states help
+    set(handles.helptext,'String',handles.helpText.states);    
+    % Update headline text
+    set(handles.headline,'String','Model States View');
+    % Set new active view
+    handles.activeView = 'states';
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EDIT PARAMETERS MODEL DESCRIPTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function parameters_Callback(hObject, eventdata, handles)
+    % Update all views
+    handles = updateAllViews(handles);
+    % Update editor content with parameters information
+    set(handles.editor,'String',handles.editText.parameters);
+    % Update help text with parameters help
+    set(handles.helptext,'String',handles.helpText.parameters);    
+    % Update headline text
+    set(handles.headline,'String','Model Parameters View');
+    % Set new active view
+    handles.activeView = 'parameters';
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EDIT VARIABLES MODEL DESCRIPTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function variables_Callback(hObject, eventdata, handles)
+    % Update all views
+    handles = updateAllViews(handles);
+    % Update editor content with variables information
+    set(handles.editor,'String',handles.editText.variables);
+    % Update help text with variables help
+    set(handles.helptext,'String',handles.helpText.variables);    
+    % Update headline text
+    set(handles.headline,'String','Model Variables View');
+    % Set new active view
+    handles.activeView = 'variables';
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EDIT REACTIONS MODEL DESCRIPTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function reactions_Callback(hObject, eventdata, handles)
+    % Update all views
+    handles = updateAllViews(handles);
+    % Update editor content with reactions information
+    set(handles.editor,'String',handles.editText.reactions);
+    % Update help text with reactions help
+    set(handles.helptext,'String',handles.helpText.reactions);    
+    % Update headline text
+    set(handles.headline,'String','Model Reactions View');
+    % Set new active view
+    handles.activeView = 'reactions';
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EDIT FUNCTIONS MODEL DESCRIPTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function functions_Callback(hObject, eventdata, handles)
+    % Update all views
+    handles = updateAllViews(handles);
+    % Update editor content with functions information
+    set(handles.editor,'String',handles.editText.functions);
+    % Update help text with functions help
+    set(handles.helptext,'String',handles.helpText.functions);    
+    % Update headline text
+    set(handles.headline,'String','Model Functions View');
+    % Set new active view
+    handles.activeView = 'functions';
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EDIT EVENTS MODEL DESCRIPTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function events_Callback(hObject, eventdata, handles)
+    % Update all views
+    handles = updateAllViews(handles);
+    % Update editor content with events information
+    set(handles.editor,'String',handles.editText.events);
+    % Update help text with events help
+    set(handles.helptext,'String',handles.helpText.events);    
+    % Update headline text
+    set(handles.headline,'String','Model Events View');
+    % Set new active view
+    handles.activeView = 'events';
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EDIT MATLAB FUNCTIONS MODEL DESCRIPTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function functionsMATLAB_Callback(hObject, eventdata, handles)
+    % Update all views
+    handles = updateAllViews(handles);
+    % Update editor content with functions information
+    set(handles.editor,'String',handles.editText.functionsMATLAB);
+    % Update help text with functions help
+    set(handles.helptext,'String',handles.helpText.functionsMATLAB);    
+    % Update headline text
+    set(handles.headline,'String','Model MATLAB Functions View');
+    % Set new active view
+    handles.activeView = 'functionsMATLAB';
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OTHER FUNCTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% UPDATE ALL VIEWS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Update the views data variables and restructure matrix text to string text
+function [handles] = updateAllViews(handles)
+% set the update IC buttons to invisible 
+    set(handles.updateIC,'Visible','off');
+    set(handles.updateICsimulate,'Visible','off');    
+    % do the rest
+    if ~strcmp(handles.activeView,'steadystate') && ~strcmp(handles.activeView,'exportsbml'),
+        % Do this only if active view has been some model text
+        if ~strcmp(handles.activeView,'complete'),
+            % Get editor content in variable corresponding to the active view
+            evalString = sprintf('matrixText = get(handles.editor,''String'');',handles.activeView);
+            eval(evalString);
+            % Restructure the content from matrix to string
+            stringText = convertMatrixToStringText(matrixText);
+            % Update view content with string text
+            evalString = sprintf('handles.editText.%s = stringText;',handles.activeView);
+            eval(evalString);
+        elseif strcmp(handles.activeView,'complete'),
+            % Get the text in the complete view
+            matrixText = get(handles.editor,'String');
+            % Restructure the content from matrix to string
+            completeEditText = convertMatrixToStringText(matrixText);
+            % Cut text in pieces and update the different views
+            handles.editText = getPartsFromCompleteTextBCSB(completeEditText);
+        end
+    end
+return
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONVERT MATRIX TEXT TO STRING
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [stringText] = convertMatrixToStringText(matrixText)
+    % convert text to numbers
+    doubleText = double(matrixText);
+    % exchange all "LF" and "CR" against "32"
+    doubleText(find(doubleText==10)) = 32;
+    doubleText(find(doubleText==13)) = 32;
+    % add new line character to each line, then transpose the matrix
+    doubleText = [doubleText 10*ones(size(doubleText,1),1)]';
+    % vectorize the matrix and transpose again
+    vectorDoubleText = doubleText(:)';
+    % get the text
+    stringText = char(vectorDoubleText);
+return
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONVERT TEXT DESCRIPTION TO SBMODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [sbm, errorFlag] = convertTextToModel(handles)
+    % convert the text description to an SBmodel
+    errorFlag = 0;
+    completeEditText = setPartsToCompleteTextBCSB(handles.editText);
+    [SBstructure,errorMsg] = convertTextBCToModelSB(completeEditText);
+    if ~isempty(errorMsg),
+        errordlg(errorMsg,'Error','On');
+        errorFlag = 1;
+        sbm = [];
+    else
+        %%%%%%%%%%%%%%%%%% Construct model and return
+        sbm = SBmodel(SBstructure);
+    end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DEFINE HELP TEXTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [helpText] = getHelpText()
+    % Define the help texts for the different sections
+    helpText.complete = sprintf('The editor shows a view of the complete model. You can edit the model using this view or the other views (Name, Notes, States, etc.). More information about the syntax of the model description can be found in the help text for the different views.\n\nIMPORTANT: Do not change the limiters (e.g., "********** MODEL PARAMETERS") between the different parts of the model. The order of the different parts IS important and should not be changed.');
+    helpText.name = 'Here you can enter the name of the model. All spaces and line breaks are being ignored but displayed. Allowed characters are characters you would expect a MATLAB function to consist of (a-z,A-Z,0-9,-,_)';
+    helpText.notes = 'Here you can enter notes about the model. Any characters are allowed';
+    helpText.states = sprintf('In this view you enter the initial conditions for the species in the model. Initial conditions are in principle optional. If no initial condition is given for a species, it is set to zero by default. Definitions of initial conditions start always in a new line but can go over several lines. The syntax is "statename(0) = initial value {optional information} %% optional comment". Spaces and line breaks are ignored. Furthermore, you can add ODEs using the same syntax as in SBedit ("d/dt(statename) = ODE expression"). Note that in SBeditBC the additional information and the comment are added after the initial conditions. To learn more about the optional information, please type "help SBeditBC".\nThe optional comment is not allowed to contain any square brackets or the strings "d/dt(" and "(0)".\n\nAlgebraic Rules: They are defined between the ODEs and the initialconditions. Their syntax is as follows: "0 = mathematical expression : variable %% optional comment". The �variable� is the one which is determined by the AR.');
+    helpText.parameters = 'In this view you can enter the models parameters. A new parameter definition starts always in a new line. The syntax is "parametername = numerical value {optional information} %% optional comment". Spaces and line breaks are ignored. The "parametername" needs to consist of characters that are allowed for MATLAB variables. Parameter names are not allowed to have the same name as states, variables, reactions, or functions.\nThe optional information is placed in square brackets. To learn more about the optional information, please type "help SBeditBC". The optional comment is not allowed to contain the character "=".';
+    helpText.variables = 'In this view you can enter the models variables. A new variable definition starts always in a new line, but can go over several lines. The syntax is "variablename = expression {optional information} %% optional comment". Spaces and line breaks are ignored. The "variablename" needs to consist of characters that are allowed for MATLAB variables. The expression can contain states, variables that have been declared before, and parameters. Variable names are not allowed to have the same name as states, parameters, reactions, or functions.\nThe optional information is placed in square brackets. To learn more about the optional information, please type "help SBeditBC".\nThe optional comment is not allowed to contain the character "=".';
+    helpText.reactions = sprintf('In this view you can enter the models reaction equations. A new reaction equation definition starts always in a new line but can go over several lines. The syntax for reversible reactions is:\n  substrate terms <=> product terms : reactionname {fast} %% optional comment"\n      vf = forward reaction rate formula\n      vr = reverse reaction rate formula\nand the syntax for irreversible reactions is:\n  substrate terms => product terms : reactionname %% optional comment."\n      vf = forward reaction rate formula\nThe substrate and product terms are defined by "stoichiometry1*species1 + stoichiometry2*species2+...". Spaces and line breaks are ignored. The "reactionname" and the species names need to consist of characters that are allowed for MATLAB variables. In the reaction comments the characters "=", "=>", "<=>", ":", "vf=", and "vr=" are NOT ALLOWED!\nThe identifier "{fast}" indicates that a reaction happens infinitely fast and should only be present in this case.');
+    helpText.functions = 'In this view you can enter functions that are used in the mathematical expressions of the model. A new function definition starts always in a new line, but can go over several lines. The syntax is "functionname(argumentname1, argumentname2, ...) = expression %% optional comment". Spaces and line breaks are ignored. The "functionname" and the names of the arguments needs to consist of characters that are allowed for MATLAB variables. Function names are not allowed to have the same name as states, parameters, variables, or reactions. The optional comment is not allowed to contain the character "=".';        
+    helpText.events = 'In this view you can enter events that are used to set state variables of the model to certain values when a certain condition is fulfilled. The syntax for an event is: "eventname=trigger,variable1,value1,...,variablen,valuen %% optional comment". The values can be numerical but also be represented by a formula that is allowed to contain states, parameters, etc. The trigger expression is an arbitrary boolean expression which goes from false to true in the case that an event should be fired. The event is only fired when the trigger function goes from false to true. The optional comment is not allowed to contain the character "=".';
+    helpText.functionsMATLAB = 'In this view you can enter functions in the standard MATLAB syntax. This feature is used, e.g., to implement the SBML piecewise operator, but it can also be used to implement events such as changing a certain parameter at a certain time, etc. States, however, can not be changed. Calls for the defined functions have then to be placed correctly in the other parts of the model.';
+    helpText.steadystate = 'This view shows the result of the steady-state computation. The steady-state computation uses the initial conditions of the models states as starting guess. If the steady-state computation fails you can try to change the initial conditions of the model. The steady-state computation also gives information over possible linear dependencies between the ODEs, resulting in algebraic relations between certain states, of the model.';
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS ERRORS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Errors occurr due to errors in the created m file (undefined 
+% identifiers mainly). Here we interprete the error message and inform
+% the user. If error reason can't be found then just print the initial
+% error message
+function [] = processError(lasterr, title)
+    errorString = lasterr;
+    % parse the error string
+    if ~isempty(strfind(errorString,'Error:')),
+        % cut off error substring
+        errorString = errorString(8:end);
+        if ~isempty(strfind(errorString,'File:')),
+            errorString = errorString(7:end);
+            temp = strfind(errorString,'Line:');
+            if ~isempty(temp),
+                % extract the filename
+                filename = strtrim(errorString(1:temp(1)-1));
+                % extract line number
+                temp2 = strfind(errorString,'Column:');
+                linenumber = str2num(strtrim(errorString(temp(1)+6:temp2(1)-1)));
+                % open the ODE file and extract the line "linenumber"
+                fid = fopen(filename, 'r');
+                for k = 1:linenumber,
+                    linecontent = fgetl(fid);
+                end
+                fclose(fid);
+                % replace all characters < 32 by 32
+                temp = double(linecontent);
+                temp(find(temp<32)) = 32;
+                linecontent = char(temp);
+                errordlg(sprintf('%s\n\n%s',title,linecontent),'Error','on');
+            else
+                errordlg(sprintf('%s\n\n%s',title,errorString),'Error','on');
+            end
+        else
+            errordlg(sprintf('%s\n\n%s',title,lasterr),'Error','on');
+        end
+    else
+        errordlg(sprintf('%s\n\n%s',title,lasterr),'Error','on');
+    end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DELETE WHITESPACES IN STRINGS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Useful for taking away whitespaces in kineticLaw formulas, as
+% seen in some example models
+function [outputString] = removeWhiteSpace(inputString)
+outputString = strrep(inputString,' ','');
+% return
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/gui/SBedit_dir/SBedit.fig b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/gui/SBedit_dir/SBedit.fig
new file mode 100644
index 0000000000000000000000000000000000000000..9ee9b55e8c7187136fe2cc177b31e889b27068b1
Binary files /dev/null and b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/gui/SBedit_dir/SBedit.fig differ
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/gui/SBedit_dir/SBedit.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/gui/SBedit_dir/SBedit.m
new file mode 100644
index 0000000000000000000000000000000000000000..ea2d5a3f61d5fd9166423397c1a97b0e979f43da
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/gui/SBedit_dir/SBedit.m
@@ -0,0 +1,767 @@
+function varargout = SBedit(varargin)
+% SBedit: GUI for editing SBmodels
+%
+% USAGE:
+% ======
+% [model] = SBedit()
+% [model] = SBedit(modelin)
+%
+% modelin: input SBmodel for editing
+%
+% Output Arguments:
+% =================
+% model: edited SBmodel as output
+%
+% Requirements for an ODE representation to be converted to a biochemical
+% representation of an SBmodel =========================================
+% =============================
+% - All states in the biochemical representation correspond to species,
+% this means in the ODE representation no states are allowed whose ODEs are
+% not defined in terms of reaction rates.
+% - Reversible reactions need to be identified as such by setting the
+% "[reversible]" identifier. The reaction rate expression is then required
+% to have the format:    ReactionName = ForwardRate - ReverseRate
+% - In case that compartments are present in the model, the optional
+% information for the states (see below) is not anymore optional.
+% Furthermore, then the reaction rates are assumed to represent amount
+% rates (as is done in SBML).
+% 
+% As long as no compartments are present in the model (or that all
+% compartment sizes are equal to 1) the optional information might be
+% neglected.
+%
+% Explanation of the OPTIONAL INFORMATION
+% =======================================
+% States, parameters, and variables can be provided with additional
+% information that is optional. This information is required for the export
+% to SBML and for the conversion of an ODE based description of an SBmodel
+% to an biochemical representation of an SBmodel.
+%
+% States, parameters, and variables can have different biochemical interpretations:
+% They can represent species, compartment sizes, and/or parameters. Each of
+% these three can be defined by ODEs, static relationships, or constant
+% values.
+%
+% For species the additional information has the following syntax:
+%     {'isSpecie':speciescompartment:speciesunittype}
+% the speciescompartment is a string with the name of the compartment the
+% species is located in. this compartment name has to be the name of a
+% state, a variable, or a parameter that is defined as a compartment (see
+% below). the speciesunittype is either 'amount' or 'concentration'
+%
+% For compartments the additional information has the following syntax:
+%     {'isCompartment':nameoutsidecompartment}
+% where nameoutsidecompartment is a string with the name of the outside
+% compartment. if there is no outside compartment the name should be
+% represented by an empty string. example - correct: {'isCompartment':}. 
+% example - wrong: {'isCompartment'} (missing ':').
+%
+% For constant values (parameters) the additional information has the following syntax:
+%     {'isParameter'}
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+% Begin initialization code - DO NOT EDIT
+gui_Singleton = 1;
+gui_State = struct('gui_Name',       mfilename, ...
+                   'gui_Singleton',  gui_Singleton, ...
+                   'gui_OpeningFcn', @SBedit_OpeningFcn, ...
+                   'gui_OutputFcn',  @SBedit_OutputFcn, ...
+                   'gui_LayoutFcn',  [], ...
+                   'gui_Callback',   []);
+if nargin && ischar(varargin{1})
+   gui_State.gui_Callback = str2func(varargin{1});
+end
+if nargout
+    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
+else
+    gui_mainfcn(gui_State, varargin{:});
+end
+% End initialization code - DO NOT EDIT
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GUI STANDARD FUNCTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OPENING FUNCTION (AFTER CREATION)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function SBedit_OpeningFcn(hObject, eventdata, handles, varargin)
+academicWarningSB
+
+% Process input argument
+nvarargin = nargin-3;
+textModel = 0;
+if nvarargin == 0,
+    % start with empty SBmodel
+    sbm = SBmodel();
+else
+    if strcmp('SBmodel',class(varargin{1})),
+        sbm = varargin{1};
+    else 
+        error('Input argument of unknown type');
+        delete(hObject);
+    end
+end
+handles.editText = convertModelToTextSB(sbm);
+handles.output = sbm;               
+
+% Create data used by the different callbacks
+handles.helpText = getHelpText();
+handles.activeView = 'complete';
+handles.SBplotHandle = [];
+% Initialize the SBedit window with initial content
+set(handles.editor,'String',setPartsToCompleteTextSB(handles.editText));
+set(handles.helptext,'String',handles.helpText.complete);
+set(handles.headline,'String','Complete Model View');
+set(handles.time,'String','20');
+% Update handles structure
+guidata(hObject, handles);
+uiwait;
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OUTPUT TO COMMAND LINE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function varargout = SBedit_OutputFcn(hObject, eventdata, handles)
+% varargout  cell array for returning output args (see VARARGOUT);
+varargout{1} = handles.output;
+% close the GUI
+delete(hObject);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CLOSE CALLBACK
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function SBedit_CloseRequestFcn(hObject, eventdata, handles)
+% warn that last changes will get lost 
+% and let the user choose
+selection = questdlg(sprintf('Close SBedit?\nLast changes might get lost. If you want to\nkeep all changes press the ''Exit'' button instead.'),...
+                     'Close Request Function',...
+                     'Yes','No','Yes');
+switch selection,
+    case 'Yes',
+        uiresume;
+    case 'No'
+        return
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GUI SPECIALIZED FUNCTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SIMULATE CALLBACK
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function simulate_Callback(hObject, eventdata, handles)
+    global lastSimulationValue
+    errorSimulation = 0;
+    % Update all views
+    handles = updateAllViews(handles);
+    % convert the text description into an SBmodel
+    [sbm, errorFlag] = convertTextToModel(handles);
+    if ~errorFlag,
+        % get the simulation time
+        timeString = get(handles.time,'String');
+        time = str2double(timeString);
+        % Simulate SBmodel for given time
+        % catch all possible errors
+        try
+            tspan = [0:time/1000:time];
+            % handles also non-numeric ics
+            outputSimulation = SBsimulate(sbm,'ode23s',tspan,SBcalcICvector(sbm));
+        catch
+            % Process the simulation error
+            processError(lasterr,'Error during simulation');
+            errorSimulation = 1;
+        end
+        if ~errorSimulation,
+            % Try to close previous SBplot figure
+            try
+                close handles.SBplotHandle;
+            catch
+            end
+            % prepare data for plotting
+            time = outputSimulation.time;
+            datanames = {};
+            dataindex = 1;
+            for k = 1:length(outputSimulation.states),
+                datanames{dataindex} = char([double(outputSimulation.states{k}) double(' (state)')]); % fastest strcat
+                dataindex = dataindex + 1;
+            end
+            for k = 1:length(outputSimulation.variables),
+                datanames{dataindex} = char([double(outputSimulation.variables{k}) double(' (variable)')]); % fastest strcat 
+                dataindex = dataindex + 1;
+            end
+            for k = 1:length(outputSimulation.reactions),
+                datanames{dataindex} = char([double(outputSimulation.reactions{k}) double(' (reaction)')]); % fastest strcat  
+                dataindex = dataindex + 1;
+            end
+            datavalues = [outputSimulation.statevalues, outputSimulation.variablevalues, outputSimulation.reactionvalues];
+            handles.SBplotHandle = SBplot(createdatastructSBplotSB(time,datavalues,datanames));
+            % make button for updating initial conditions visible
+            set(handles.updateICsimulate,'Visible','on');
+            lastSimulationValue = outputSimulation.statevalues(end,:);
+        end
+    end
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% UPDATE INITIAL CONDITIONS WITH LAST VALUE OF SIMULATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function updateICsimulate_Callback(hObject, eventdata, handles)
+    global lastSimulationValue
+    % Update all views
+    handles = updateAllViews(handles);
+    % convert the text description into an SBmodel
+    [sbm, errorFlag] = convertTextToModel(handles);
+    if ~errorFlag,
+        % set new initial conditions (handle also non-numeric initial
+        % conditions)
+        sbm = SBoverwriteICs(sbm,lastSimulationValue);
+        % convert model to text again 
+        handles.editText = convertModelToTextSB(sbm); 
+        % rewrite the data in the current view (only needed if the view
+        % shows state or complete information)
+        if strcmp(handles.activeView,'states'),
+            % Update editor content with state information
+            set(handles.editor,'String',handles.editText.states);
+        elseif strcmp(handles.activeView,'complete'),
+            % Update editor content with complete information
+            completeEditText = setPartsToCompleteTextSB(handles.editText);
+            set(handles.editor,'String',completeEditText);
+        end
+    end
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% STEADY-STATE CALLBACK
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function steadystate_Callback(hObject, eventdata, handles)
+    global steadyStateValues
+    errorSteadyState = 0;
+    % Update all views
+    handles = updateAllViews(handles);
+    % convert the text description into an SBmodel
+    [sbm, errorFlag] = convertTextToModel(handles);
+    if ~errorFlag,
+        % get the steady-state
+        try
+            [steadystate,residual,message] = SBsteadystate(sbm);
+        catch
+            % Process the steadystate error
+            processError(lasterr,'Error during steady-state computation');
+            errorSteadyState = 1;
+        end
+        if ~errorSteadyState,
+            % construct result text and display it in the editor window
+            resultText = sprintf('%s',message);
+            if ~isempty(steadystate),
+                resultText = sprintf('%s\nThe steady-state is given by:\n',message);
+                SBstructure = SBstruct(sbm);
+                for k = 1:length(SBstructure.states),
+                    stateName = SBstructure.states(k).name;
+                    resultText = sprintf('%s\n%s = %g',resultText,stateName,steadystate(k));
+                end
+                % make button for updating initial conditions visible
+                set(handles.updateIC,'Visible','on');
+                steadyStateValues = steadystate;
+            else
+                resultText = sprintf('%s\nIn order to start at a different steady-state you can change to initial conditions for the states. Changing the options of the steady-state solver is only possible from the command line version of SBsteadystate',resultText);
+            end
+            set(handles.editor,'String',resultText);
+            % Update help text with complete help
+            set(handles.helptext,'String',handles.helpText.steadystate);
+            % Update headline text
+            set(handles.headline,'String','Steady State of Model');
+            % Set new active view
+            handles.activeView = 'steadystate';
+        end
+    end
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% UPDATE INITIAL CONDITIONS WITH STEADY STATE INFORMATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function updateIC_Callback(hObject, eventdata, handles)
+    global steadyStateValues
+    % Update all views
+    handles = updateAllViews(handles);
+    % convert the text description into an SBmodel
+    [sbm, errorFlag] = convertTextToModel(handles);
+    if ~errorFlag,
+        % set new initial conditions (handle also non-numeric initial
+        % conditions)
+        sbm = SBoverwriteICs(sbm,steadyStateValues);
+        % convert model to text again 
+        handles.editText = convertModelToTextSB(sbm);  
+    end
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXPORT TEXT CALLBACK
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function exportText_Callback(hObject, eventdata, handles)
+    % Update all views
+    handles = updateAllViews(handles);
+    % get filename for the TXT file
+    [filename, pathname] = uiputfile('*.txt', 'Save SBmodel as .txt file');
+    % check if a filename returned
+    if filename ~= 0,
+        % cut of the extension from the filename
+        [path,filename,ext] = fileparts(filename);
+        % remove whitespaces from filename
+        filename = strrep(filename,' ','');
+        % add the extension
+        filepathname = strcat(pathname,'/',filename,'.txt');
+        % save the TextFile
+        completeEditText = setPartsToCompleteTextSB(handles.editText);
+        fid = fopen(filepathname,'w');
+        fwrite(fid,completeEditText);
+        status = fclose(fid);
+    end
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXPORT TEXTBC CALLBACK
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function exportTextBC_Callback(hObject, eventdata, handles)
+    % Update all views
+    handles = updateAllViews(handles);
+    % get filename for the TXTBC file
+    [filename, pathname] = uiputfile('*.txtbc', 'Save SBmodel as .txtbc file');
+    % check if a filename returned
+    if filename ~= 0,
+        % cut of the extension from the filename
+        [path,filename,ext] = fileparts(filename);
+        % remove whitespaces from filename
+        filename = strrep(filename,' ','');
+        % add the extension
+        filepathname = strcat(pathname,'/',filename,'.txtbc');
+        % convert the text description into an SBmodel
+        [sbm, errorFlag] = convertTextToModel(handles);
+        if ~errorFlag,
+            % convert the model into a TEXTBC description
+            [modelTextBCStructure] = convertModelToTextBCSB(sbm);
+            [completeTextBC] = setPartsToCompleteTextBCSB(modelTextBCStructure);
+            % save the text
+            fid = fopen(filepathname,'w');
+            fwrite(fid,completeTextBC);
+            status = fclose(fid);
+        end
+    end
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXIT SBEDIT CALLBACK
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function exit_Callback(hObject, eventdata, handles)
+    % Update all views
+    handles = updateAllViews(handles);
+    % convert the text description into an SBmodel
+    [sbm, errorFlag] = convertTextToModel(handles);
+    if ~errorFlag,
+        % set edited SBmodel as output
+        handles.output = sbm;
+    end
+    % Update handles structure
+    guidata(hObject, handles);
+    uiresume;
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GUI EDITOR BUTTONS FUNCTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EDIT COMPLETE MODEL DESCRIPTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function complete_Callback(hObject, eventdata, handles)
+    % Update all views
+    handles = updateAllViews(handles);
+    % Update editor content with complete information
+    completeEditText = setPartsToCompleteTextSB(handles.editText);
+    set(handles.editor,'String',completeEditText);
+    % Update help text with complete help
+    set(handles.helptext,'String',handles.helpText.complete);    
+    % Update headline text
+    set(handles.headline,'String','Complete Model View');
+    % Set new active view
+    handles.activeView = 'complete';
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EDIT NAME MODEL DESCRIPTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function name_Callback(hObject, eventdata, handles)
+    % Update all views
+    handles = updateAllViews(handles);
+    % Update editor content with name information
+    set(handles.editor,'String',handles.editText.name);
+    % Update help text with name help
+    set(handles.helptext,'String',handles.helpText.name);    
+    % Update headline text
+    set(handles.headline,'String','Model Name View');
+    % Set new active view
+    handles.activeView = 'name';
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EDIT NOTES MODEL DESCRIPTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function notes_Callback(hObject, eventdata, handles)
+    % Update all views
+    handles = updateAllViews(handles);
+    % Update editor content with notes information
+    set(handles.editor,'String',handles.editText.notes);
+    % Update help text with notes help
+    set(handles.helptext,'String',handles.helpText.notes);    
+    % Update headline text
+    set(handles.headline,'String','Model Notes View');
+    % Set new active view
+    handles.activeView = 'notes';
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% VIEW HTML NOTES CALLBACK
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function htmlnotes_Callback(hObject, eventdata, handles)
+    % Update all views
+    handles = updateAllViews(handles);
+    % Update editor content with notes information
+    set(handles.editor,'String',handles.editText.notes);
+    % Update help text with notes help
+    set(handles.helptext,'String',handles.helpText.notes);    
+    % Update headline text
+    set(handles.headline,'String','Model Notes View');
+    % Set new active view
+    handles.activeView = 'notes';
+    % get the text in the notes
+    notesText = handles.editText.notes;
+    % write this text to a temporary html file
+    filefullpath = strcat(tempnameSB,'.html');
+    fid = fopen(filefullpath,'w');
+    fprintf(fid,notesText);
+    status = fclose(fid);
+    % open and display the file
+    open(filefullpath);
+    % Update handles structure
+    guidata(hObject, handles);    
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EDIT STATES MODEL DESCRIPTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function states_Callback(hObject, eventdata, handles)
+    % Update all views
+    handles = updateAllViews(handles);
+    % Update editor content with states information
+    set(handles.editor,'String',handles.editText.states);
+    % Update help text with states help
+    set(handles.helptext,'String',handles.helpText.states);    
+    % Update headline text
+    set(handles.headline,'String','Model States View');
+    % Set new active view
+    handles.activeView = 'states';
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EDIT PARAMETERS MODEL DESCRIPTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function parameters_Callback(hObject, eventdata, handles)
+    % Update all views
+    handles = updateAllViews(handles);
+    % Update editor content with parameters information
+    set(handles.editor,'String',handles.editText.parameters);
+    % Update help text with parameters help
+    set(handles.helptext,'String',handles.helpText.parameters);    
+    % Update headline text
+    set(handles.headline,'String','Model Parameters View');
+    % Set new active view
+    handles.activeView = 'parameters';
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EDIT VARIABLES MODEL DESCRIPTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function variables_Callback(hObject, eventdata, handles)
+    % Update all views
+    handles = updateAllViews(handles);
+    % Update editor content with variables information
+    set(handles.editor,'String',handles.editText.variables);
+    % Update help text with variables help
+    set(handles.helptext,'String',handles.helpText.variables);    
+    % Update headline text
+    set(handles.headline,'String','Model Variables View');
+    % Set new active view
+    handles.activeView = 'variables';
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EDIT REACTIONS MODEL DESCRIPTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function reactions_Callback(hObject, eventdata, handles)
+    % Update all views
+    handles = updateAllViews(handles);
+    % Update editor content with reactions information
+    set(handles.editor,'String',handles.editText.reactions);
+    % Update help text with reactions help
+    set(handles.helptext,'String',handles.helpText.reactions);    
+    % Update headline text
+    set(handles.headline,'String','Model Reactions View');
+    % Set new active view
+    handles.activeView = 'reactions';
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EDIT FUNCTIONS MODEL DESCRIPTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function functions_Callback(hObject, eventdata, handles)
+    % Update all views
+    handles = updateAllViews(handles);
+    % Update editor content with functions information
+    set(handles.editor,'String',handles.editText.functions);
+    % Update help text with functions help
+    set(handles.helptext,'String',handles.helpText.functions);    
+    % Update headline text
+    set(handles.headline,'String','Model Functions View');
+    % Set new active view
+    handles.activeView = 'functions';
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EDIT EVENTS MODEL DESCRIPTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function events_Callback(hObject, eventdata, handles)
+    % Update all views
+    handles = updateAllViews(handles);
+    % Update editor content with events information
+    set(handles.editor,'String',handles.editText.events);
+    % Update help text with events help
+    set(handles.helptext,'String',handles.helpText.events);    
+    % Update headline text
+    set(handles.headline,'String','Model Events View');
+    % Set new active view
+    handles.activeView = 'events';
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EDIT MATLAB FUNCTIONS MODEL DESCRIPTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function functionsMATLAB_Callback(hObject, eventdata, handles)
+    % Update all views
+    handles = updateAllViews(handles);
+    % Update editor content with functions information
+    set(handles.editor,'String',handles.editText.functionsMATLAB);
+    % Update help text with functions help
+    set(handles.helptext,'String',handles.helpText.functionsMATLAB);    
+    % Update headline text
+    set(handles.headline,'String','Model MATLAB Functions View');
+    % Set new active view
+    handles.activeView = 'functionsMATLAB';
+    % Update handles structure
+    guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OTHER FUNCTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% UPDATE ALL VIEWS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Update the views data variables and restructure matrix text to string text
+function [handles] = updateAllViews(handles)
+    % set the update IC buttons to invisible 
+    set(handles.updateIC,'Visible','off');
+    set(handles.updateICsimulate,'Visible','off');    
+    % do the rest
+    if ~strcmp(handles.activeView,'steadystate') && ~strcmp(handles.activeView,'exportsbml'),
+        % Do this only if active view has been some model text
+        if ~strcmp(handles.activeView,'complete'),
+            % Get editor content in variable corresponding to the active view
+            evalString = sprintf('matrixText = get(handles.editor,''String'');',handles.activeView);
+            eval(evalString);
+            % Restructure the content from matrix to string
+            stringText = convertMatrixToStringText(matrixText);
+            % Update view content with string text
+            evalString = sprintf('handles.editText.%s = stringText;',handles.activeView);
+            eval(evalString);
+        elseif strcmp(handles.activeView,'complete'),
+            % Get the text in the complete view
+            matrixText = get(handles.editor,'String');
+            % Restructure the content from matrix to string
+            completeEditText = convertMatrixToStringText(matrixText);
+            % Cut text in pieces and update the different views
+            handles.editText = getPartsFromCompleteTextSB(completeEditText);
+        end
+    end
+return
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONVERT MATRIX TEXT TO STRING
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [stringText] = convertMatrixToStringText(matrixText)   
+    % convert text to numbers
+    doubleText = double(matrixText);
+    % exchange all "LF" and "CR" against "32"
+    doubleText(find(doubleText==10)) = 32;
+    doubleText(find(doubleText==13)) = 32;
+    % add new line character to each line, then transpose the matrix
+    doubleText = [doubleText 10*ones(size(doubleText,1),1)]';
+    % vectorize the matrix and transpose again
+    vectorDoubleText = doubleText(:)';
+    % get the text
+    stringText = char(vectorDoubleText);
+return
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONVERT TEXT DESCRIPTION TO SBMODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [sbm, errorFlag] = convertTextToModel(handles)
+    % convert the text description to an SBmodel
+    errorFlag = 0;
+    completeEditText = setPartsToCompleteTextSB(handles.editText);
+    [SBstructure,errorMsg] = convertTextToModelSB(completeEditText);
+    if ~isempty(errorMsg),
+        errordlg(errorMsg,'Error','On');
+        errorFlag = 1;
+        sbm = [];
+    else
+        %%%%%%%%%%%%%%%%%% Construct model and return
+        sbm = SBmodel(SBstructure);
+    end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DEFINE HELP TEXTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [helpText] = getHelpText()
+    % Define the help texts for the different sections
+    helpText.complete = sprintf('The editor shows a view of the complete model. You can edit the model using this view or the other views (Name, Notes, States, etc.). More information about the syntax of the model description can be found in the help text for the different views.\n\nIMPORTANT: Do not change the limiters (e.g., "********** MODEL PARAMETERS") between the different parts of the model. The order of the different parts IS important and should not be changed.');
+    helpText.name = 'Here you can enter the name of the model. All spaces and line breaks are being ignored but displayed. Allowed characters are characters you would expect a MATLAB function to consist of (a-z,A-Z,0-9,-,_)';
+    helpText.notes = 'Here you can enter notes about the model. Any characters are allowed';
+    helpText.states = sprintf('In this view you enter the models ODEs and initial conditions for the states. A new ODE starts always in a new line, but can go over several lines. The syntax is: "d/dt(statename) = ODE expression {optional information} %% optional comment". Spaces and line breaks are ignored. The "statename" needs to consist of characters that are allowed for MATLAB variables. The expression can contain variables, reactions, states, and parameters. The optional information is placed in square brackets. To learn more about the optional information, please type "help SBedit".\nInitial conditions are optional. If no initial condition is given for a state, it is zero by default. Definitions of initial conditions start always in a new line but can go over several lines. The syntax is "statename(0) = initial value". Spaces and line breaks are ignored. The order of the initial conditions does not need to match the order of the ODEs.\nIMPORTANT: Define first the ODEs, then the initial conditions. The optional comment is not allowed to contain any square brackets or the strings "d/dt(" and "(0)"\n\nAlgebraic Rules: They are defined between the ODEs and the initialconditions. Their syntax is as follows: "0 = mathematical expression : variable %% optional comment". The �variable� is the one which is determined by the AR.');
+    helpText.parameters = 'In this view you can enter the models parameters. A new parameter definition starts always in a new line. The syntax is "parametername = numerical value {optional information} %% optional comment". Spaces and line breaks are ignored. The "parametername" needs to consist of characters that are allowed for MATLAB variables. Parameter names are not allowed to have the same name as states, variables, reactions, or functions.\nThe optional information is placed in square brackets. To learn more about the optional information, please type "help SBedit". The optional comment is not allowed to contain the character "=".';
+    helpText.variables = 'In this view you can enter the models variables. A new variable definition starts always in a new line, but can go over several lines. The syntax is "variablename = expression {optional information} %% optional comment". Spaces and line breaks are ignored. The "variablename" needs to consist of characters that are allowed for MATLAB variables. The expression can contain states, variables that have been declared before, and parameters. Variable names are not allowed to have the same name as states, parameters, reactions, or functions.\nThe optional information is placed in square brackets. To learn more about the optional information, please type "help SBedit".\nThe optional comment is not allowed to contain the character "=".';
+    helpText.reactions = sprintf('In this view you can enter the models reactions. A new reaction definition starts always in a new line, but can go over several lines. The syntax is "reactionname = expression {reversible} %% optional comment". Spaces and line breaks are ignored. The "reactionname" needs to consist of characters that are allowed for MATLAB variables. The expression can contain states, variables, and parameters. Reaction names are not allowed to have the same name as states, parameters, variables, or functions. The identifier "{reversible}" should be present when a reaction is reversible only. The identifier "{fast}" indicates that a reaction happens infinitely fast. The comment is separated from the rest by "%%". In the reaction comments the character "=" is NOT ALLOWED!\nYou can specify the ODEs for species in terms of reactions or by directly using kinetic formulas in the ODEs. In the latter case reactions do not need to be specified. A combination of both approaches is possible but not very consistent, and should therefore be avoided.');
+    helpText.functions = 'In this view you can enter functions that are used in the mathematical expressions of the model. A new function definition starts always in a new line, but can go over several lines. The syntax is "functionname(argumentname1, argumentname2, ...) = expression %% optional comment". Spaces and line breaks are ignored. The "functionname" and the names of the arguments needs to consist of characters that are allowed for MATLAB variables. Function names are not allowed to have the same name as states, parameters, variables, or reactions. The optional comment is not allowed to contain the character "=".';        
+    helpText.events = 'In this view you can enter events that are used to set state variables of the model to certain values when a certain condition is fulfilled. The syntax for an event is: "eventname=trigger,variable1,value1,...,variablen,valuen %% optional comment". The values can be numerical but also be represented by a formula that is allowed to contain states, parameters, etc. The trigger expression is an arbitrary boolean expression which goes from false to true in the case that an event should be fired. The event is only fired when the trigger function goes from false to true. The optional comment is not allowed to contain the character "=".';
+    helpText.functionsMATLAB = 'In this view you can enter functions in the standard MATLAB syntax. This feature is used, e.g., to implement the SBML piecewise operator, but it can also be used to implement events such as changing a certain parameter at a certain time, etc. States, however, can not be changed. Calls for the defined functions have then to be placed correctly in the other parts of the model.';
+    helpText.steadystate = 'This view shows the result of the steady-state computation. The steady-state computation uses the initial conditions of the models states as starting guess. If the steady-state computation fails you can try to change the initial conditions of the model. The steady-state computation also gives information over possible linear dependencies between the ODEs, resulting in algebraic relations between certain states, of the model.';
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS ERRORS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Errors occurr due to errors in the created m file (undefined 
+% identifiers mainly). Here we interprete the error message and inform
+% the user. If error reason can't be found then just print the initial
+% error message
+function [] = processError(lasterr, title)
+    errorString = lasterr;
+    % parse the error string
+    if ~isempty(strfind(errorString,'Error:')),
+        % cut off error substring
+        errorString = errorString(8:end);
+        if ~isempty(strfind(errorString,'File:')),
+            errorString = errorString(7:end);
+            temp = strfind(errorString,'Line:');
+            if ~isempty(temp),
+                % extract the filename
+                filename = strtrim(errorString(1:temp(1)-1));
+                % extract line number
+                temp2 = strfind(errorString,'Column:');
+                linenumber = str2num(strtrim(errorString(temp(1)+6:temp2(1)-1)));
+                % open the ODE file and extract the line "linenumber"
+                fid = fopen(filename, 'r');
+                for k = 1:linenumber,
+                    linecontent = fgetl(fid);
+                end
+                fclose(fid);
+                % replace all characters < 32 by 32
+                temp = double(linecontent);
+                temp(find(temp<32)) = 32;
+                linecontent = char(temp);
+                errordlg(sprintf('%s\n\n%s',title,linecontent),'Error','on');
+            else
+                errordlg(sprintf('%s\n\n%s',title,errorString),'Error','on');
+            end
+        else
+            errordlg(sprintf('%s\n\n%s',title,lasterr),'Error','on');
+        end
+    else
+        errordlg(sprintf('%s\n\n%s',title,lasterr),'Error','on');
+    end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DELETE WHITESPACES IN STRINGS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Useful for taking away whitespaces in kineticLaw formulas, as
+% seen in some example models
+function [outputString] = removeWhiteSpace(inputString)
+outputString = strrep(inputString,' ','');
+% return
+return
+
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/gui/SBplot2_dir/SBplot2.fig b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/gui/SBplot2_dir/SBplot2.fig
new file mode 100644
index 0000000000000000000000000000000000000000..dab25e96dc37275b90a0cbb33cd4ac925c01087d
Binary files /dev/null and b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/gui/SBplot2_dir/SBplot2.fig differ
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/gui/SBplot2_dir/SBplot2.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/gui/SBplot2_dir/SBplot2.m
new file mode 100644
index 0000000000000000000000000000000000000000..40d2cace22ddffcf7ee7f303574c1005c486c316
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/gui/SBplot2_dir/SBplot2.m
@@ -0,0 +1,550 @@
+function varargout = SBplot2(varargin)
+% SBplot2 - plots bar diagrams for given data.
+%
+% USAGE:
+% ======
+%
+% [] = SBplot2(datastruct1)
+% [] = SBplot2(datastruct1,datastruct2)
+% [] = SBplot2(datastruct1,datastruct2, ..., datastruct10)
+%
+% datastruct1-10: structure with datasets information. SBplot2 can accept up
+%   to  10 different datastructures which can be displayed. The structure
+%   of the input arguments is defined as follows:
+%
+%       datastruct.name                 descriptive name for the
+%                                       datastructure
+%       datastruct.xnames:              cell-array with names of x-axis data
+%       datastruct.ynames:              cell-array with names of y-axis data 
+%       datastruct.data:                matrix with y-axis data in rows and
+%                                       x-axis data in columns 
+%       datastruct.title:               a title for the plot
+%       datastruct.xlabel:              label for the x-axis
+%       datastruct.xaxistitle:          text describing the x-axis
+%                                       selection box 
+%       datastruct.yaxistitle:          text describing the y-axis
+%                                       selection box 
+%
+%   All fields of the structure need to be correctly initialized
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+% Begin initialization code - DO NOT EDIT
+gui_Singleton = 1;
+gui_State = struct('gui_Name',       mfilename, ...
+                   'gui_Singleton',  gui_Singleton, ...
+                   'gui_OpeningFcn', @SBplot2_OpeningFcn, ...
+                   'gui_OutputFcn',  @SBplot2_OutputFcn, ...
+                   'gui_LayoutFcn',  [] , ...
+                   'gui_Callback',   []);
+if nargin && ischar(varargin{1})
+    gui_State.gui_Callback = str2func(varargin{1});
+end
+if nargout
+    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
+else
+    gui_mainfcn(gui_State, varargin{:});
+end
+% End initialization code - DO NOT EDIT
+
+% --- Executes just before SBplot2 is made visible.
+function SBplot2_OpeningFcn(hObject, eventdata, handles, varargin)
+% determine number of arguments passed to SBplot2 by the
+% user. Each argument is assumed to correspond to one datastructure
+nvarargin = nargin-3;
+% process variable arguments
+if nvarargin > 10,
+    error('To many input arguments (max. is 10).');
+end
+handles.dataSets = varargin;            % save all datasets in handles
+handles = switchDataSet(handles,1);     % switch to first dataset
+% Initialize datasets pulldown menu
+datasetnames = {};
+for k = 1:length(handles.dataSets),
+    datasetnames{k} = handles.dataSets{k}.name;
+end
+set(handles.datasets,'String',datasetnames);
+% Initialize export figure handle
+handles.exportFigureHandle = [];
+% do not plot magnitudes per default
+handles.magnitudeFlag = 1;
+set(handles.magnitude,'Value',1);
+% no grid per default 
+handles.grid = 0;
+% set plot option data
+set(handles.minmax,'Value',1);
+set(handles.mean,'Value',0);
+set(handles.median,'Value',1);
+set(handles.ordered,'Value',0);
+% Initialize figure with minmax data
+set(handles.xaxisselection,'Value',[1:length(handles.xnames)]);
+set(handles.yaxisselection,'Value',[1:length(handles.ynames)]);
+handles.plotType = 'MinMax';
+doAllPlot(handles);
+% Initialize output of function
+handles.output = hObject;
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OUTPUT FUNCTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function varargout = SBplot2_OutputFcn(hObject, eventdata, handles) 
+varargout{1} = handles.output;
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DATASETS SELECTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function datasets_Callback(hObject, eventdata, handles)
+dataSetIndex = get(handles.datasets,'Value');
+handles = switchDataSet(handles,dataSetIndex); 
+set(handles.xaxisselection,'Value',[1:length(handles.xnames)]);
+set(handles.yaxisselection,'Value',[1:length(handles.ynames)]);
+handles.plotType = 'MinMax';
+doAllPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% X-AXIS SELECTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function xaxisselection_Callback(hObject, eventdata, handles)
+doAllPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Y-AXIS SELECTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function yaxisselection_Callback(hObject, eventdata, handles)
+doAllPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% MIN-MAX PLOT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function minmaxplot_Callback(hObject, eventdata, handles)
+if strcmp(handles.plotType,'MinMax'),
+    handles.plotType = 'Plot';
+else
+    handles.plotType = 'MinMax';
+end
+doAllPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ALLOW MIN MAX BARS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function minmax_Callback(hObject, eventdata, handles)
+doAllPlot(handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ALLOW MEAN VALUES PLOTTED
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function mean_Callback(hObject, eventdata, handles)
+doAllPlot(handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ALLOW MEAN VALUES PLOTTED
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function median_Callback(hObject, eventdata, handles)
+doAllPlot(handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ORDER PLOT VALUES 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function ordered_Callback(hObject, eventdata, handles)
+orderedFlag = get(handles.ordered,'Value');
+if orderedFlag == 1,
+    set(handles.ordered,'Value',1)
+else
+    set(handles.ordered,'Value',0)
+end
+doAllPlot(handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% TOGGLE MAGNITUDE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function magnitude_Callback(hObject, eventdata, handles)
+if handles.magnitudeFlag == 1,
+    handles.magnitudeFlag = 0;
+else
+    handles.magnitudeFlag = 1;
+end
+doAllPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% TOGGLE ZOOM
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function zoombutton_Callback(hObject, eventdata, handles)
+% toogle the zoom in the figure
+zoom
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% TOGGLE GRID
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function gridbutton_Callback(hObject, eventdata, handles)
+% toogle the grid in the figure
+grid
+if handles.grid == 1,
+    handles.grid = 0;
+else 
+    handles.grid = 1;
+end
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXPORT FIGURE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function export_Callback(hObject, eventdata, handles)
+if isempty(handles.exportFigureHandle),
+    figH = figure;
+    handles.exportFigureHandle = figH;
+    % Update handles structure
+    guidata(hObject, handles);
+else
+    figH = handles.exportFigureHandle;
+    figure(figH);
+end
+nrow = str2num(get(handles.nrow,'String'));
+ncol = str2num(get(handles.ncol,'String'));
+nnumber = str2num(get(handles.nnumber,'String'));
+subplot(nrow,ncol,nnumber);
+doAllPlot(handles);
+titlestring = handles.titletext;
+if strcmp(handles.plotType,'MinMax'),
+    titlestring = sprintf('%s (MinMax View)',titlestring);
+end
+if handles.magnitudeFlag == 1,
+    titlestring = sprintf('Magnitude of %s',titlestring);
+end
+hlhlx = title(titlestring);
+set(hlhlx,'Interpreter','none');
+if handles.grid == 1,
+    grid;
+end
+hlhlx = xlabel(handles.xlabeltext);
+set(hlhlx,'Interpreter','none');
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% REQUEST NEW EXPORT FIGURE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function newexportfigure_Callback(hObject, eventdata, handles)
+handles.exportFigureHandle = [];
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SWITCH GIVEN DATASETS 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [handles] = switchDataSet(handles,indexDataSet)
+dataSet = handles.dataSets{indexDataSet};
+handles.name = dataSet.name;
+handles.xnames = dataSet.xnames;
+handles.ynames = dataSet.ynames;
+handles.data = dataSet.data;
+handles.titletext = dataSet.title;
+handles.xlabeltext = dataSet.xlabel;
+handles.xaxistitle = dataSet.xaxistitle;
+handles.yaxistitle = dataSet.yaxistitle;
+% set information in the selection fields and figure descriptions
+set(handles.xaxisselection,'String',handles.xnames);
+set(handles.yaxisselection,'String',handles.ynames);
+set(handles.xaxistext,'Title',handles.xaxistitle);
+set(handles.yaxistext,'Title',handles.yaxistitle);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GLOBAL PLOT FUNCTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function doAllPlot(handles)
+if strcmp(handles.plotType,'MinMax'),
+    set(handles.ordered,'Visible','on');
+    set(handles.minmaxplot,'Value',1);
+    set(handles.minmax,'Visible','on');
+    set(handles.mean,'Visible','on');
+    set(handles.median,'Visible','on');
+    doPlotMinMax(handles);
+else
+    nx = length(get(handles.xaxisselection,'Value'));
+    ny = length(get(handles.yaxisselection,'Value'));
+    if nx == 1 || ny == 1,
+        set(handles.ordered,'Visible','on');
+    else
+        set(handles.ordered,'Visible','off');
+    end
+    set(handles.minmaxplot,'Value',0);
+    set(handles.minmax,'Visible','off');
+    set(handles.mean,'Visible','off');
+    set(handles.median,'Visible','off');
+    doPlot(handles);
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PLOT FUNCTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function doPlot(handles)
+hold off;
+colormap default;
+if handles.magnitudeFlag == 1,
+    set(handles.title,'String',sprintf('Magnitude of %s',handles.titletext));
+else
+    set(handles.title,'String',handles.titletext);
+end
+set(handles.xlabel,'String',handles.xlabeltext);
+xnames = handles.xnames;
+ynames = handles.ynames;
+data = handles.data;
+% use magnitudes if desired
+if handles.magnitudeFlag == 1,
+    data = abs(data);
+end
+% get variables that are chosen for the y-axis
+xindex = get(handles.xaxisselection,'Value');
+n = length(xindex);
+% get variables that are chosen for the y-axis
+yindex = get(handles.yaxisselection,'Value');
+% get corresponding data values
+xydata = data(yindex,xindex);
+% adjust for the case where single parameter chosen (bar function then has
+% problems)
+if n == 1,
+    xindex = [xindex xindex+1];
+    xydata = [xydata zeros(size(xydata))];
+    n = 2;
+    nold = 1;
+else
+    nold = n;
+end
+% check if ordering necessary
+orderedVisible = get(handles.ordered,'Visible');
+orderedFlag = get(handles.ordered,'Value');
+nx = length(get(handles.xaxisselection,'Value'));
+ny = length(get(handles.yaxisselection,'Value'));
+xindexordered = xindex;
+yindexordered = yindex;
+if strcmp(orderedVisible,'on') && orderedFlag == 1 && ~( nx == 1 && ny == 1 ),
+    % do order the data for display
+    if ny == 1,
+        ordering = [[1:nx]',xydata'];
+        ordering = sortrows(ordering,-2);
+        neworder = ordering(:,1)';
+        xydata = ordering(:,2:end)';
+        xindexordered = xindex(neworder);
+        yindexordered = yindex;
+    end
+    if nx == 1,
+        ordering = [[1:ny]',xydata];
+        ordering = sortrows(ordering,-2);
+        neworder = ordering(:,1)';
+        xydata = ordering(:,2:end);
+        xindexordered = xindex;
+        yindexordered = yindex(neworder);
+    end
+end
+bar([1:n], xydata');
+% draw a legend
+hlhlx=legend(ynames{yindexordered});
+set(hlhlx,'Interpreter','none');
+% get axes handle
+axesH = gca;
+% use magnitudes if desired
+if handles.magnitudeFlag == 1,
+    yMax = 1.5*max(max(xydata));
+    yMin = 0;
+else
+    yMax = 1.5*max(max(xydata));
+    yMin = 1.5*min(min(xydata));
+end
+if yMax == 0, yMax = yMin+1; end
+axis([0 n+1 yMin yMax]);
+set(axesH,'XTick',1:n);
+if nold == 1,
+    set(axesH,'XTickLabel',{xnames{xindex(1)}, ''});
+else 
+    set(axesH,'XTickLabel',xnames(xindexordered));
+end
+set(axesH,'YScale','linear');
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% MinMax PLOT FUNCTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function doPlotMinMax(handles)
+hold off;
+if handles.magnitudeFlag == 1,
+    set(handles.title,'String',sprintf('Magnitude of %s (MinMax View)',handles.titletext));
+else
+    set(handles.title,'String',sprintf('%s (MinMax View)',handles.titletext));
+end
+set(handles.xlabel,'String',handles.xlabeltext);
+% plot min max and median value for all given data
+xnames = handles.xnames;
+ynames = handles.ynames;
+data = handles.data;
+% get variables that are chosen for the y-axis
+xindex = get(handles.xaxisselection,'Value');
+xnames = xnames(xindex);
+% get variables that are chosen for the y-axis
+yindex = get(handles.yaxisselection,'Value');
+ynames = ynames(yindex);
+% get corresponding data values
+data = data(yindex,xindex);
+if length(ynames) == 1,
+    ynames = {ynames, ''};
+    data = [data; zeros(1,length(data))];
+    nold = 1;
+else
+    nold = length(ynames);
+end
+% use magnitudes if desired
+if handles.magnitudeFlag == 1,
+    data = abs(data);
+    yMax = 1.5*max(max(data));
+    yMin = 0;
+else
+    yMax = 1.5*max(max(data));
+    yMin = 1.5*min(min(data));
+end 
+if yMax == 0, yMax = yMin+1; end
+% determine min, max, ans median values of the data for each point on the x-axis
+% catch the case where only one row of data (corresponds to one component only)
+% then need to multiply all values by 2
+maxData = max(data);
+minData = min(data);
+medianData = median(data);
+meanData = mean(data);
+if nold == 1,
+    maxData = 2*maxData;
+    minData = 2*minData;
+    medianData = 2*medianData;
+    meanData = 2*meanData;
+end
+% check if ordering necessary
+orderedVisible = get(handles.ordered,'Visible');
+orderedFlag = get(handles.ordered,'Value');
+nx = length(xnames);
+ny = length(ynames);
+xindexordered = 1:nx;
+if strcmp(orderedVisible,'on') && orderedFlag == 1 && nx > 1 && ny > 1,
+    % do order the data for display
+    ordering = [[1:nx]' maxData(:) minData(:) medianData(:) meanData(:)];
+    % sort after mean value if mean and median or nothing checked
+    % otherwise sort after the checked one
+    meanFlag = get(handles.mean,'Value');
+    medianFlag = get(handles.median,'Value');
+    if (meanFlag == 1 && medianFlag == 1) || (meanFlag == 0 && medianFlag == 0)
+        % sort after mean value
+        ordering = sortrows(ordering,-5);
+    elseif meanFlag == 1,
+        % sort after mean value
+        ordering = sortrows(ordering,-5);
+    else
+        % sort after median value
+        ordering = sortrows(ordering,-4);
+    end
+    neworder = ordering(:,1);
+    maxData = ordering(:,2);
+    minData = ordering(:,3);
+    medianData = ordering(:,4);
+    meanData = ordering(:,5);
+    xindexordered = xindexordered(neworder);
+end
+if nold == 1,
+    maxData = meanData;
+    minData = meanData;
+    medianData = meanData;
+end
+% do the plotting
+n = length(maxData);
+axesH = gca;
+mybar(minData,medianData,meanData,maxData,handles);
+axis([0 n+1 yMin yMax]);
+set(axesH,'XTick',1:n);
+set(axesH,'XTickLabel',xnames(xindexordered));
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% mybar plot function
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [] = mybar(minData,medianData,meanData,maxData,handles)
+n = length(minData);
+% plot the bars indicating min and max values of the sensitivities
+minmaxFlag = get(handles.minmax,'Value');
+meanFlag = get(handles.mean,'Value');
+medianFlag = get(handles.median,'Value');
+if minmaxFlag,
+    for k = 1:n,
+        fill([k-0.4,k+0.4,k+0.4,k-0.4],[minData(k) minData(k) maxData(k) maxData(k)],[1 0.9 0.8]); hold on;
+    end
+end
+if medianFlag,
+    for k = 1:n,
+        plot([k-0.4 k+0.4],[medianData(k) medianData(k)],'r'); hold on;
+    end
+end
+if meanFlag,
+    for k = 1:n,
+        plot([k-0.4 k+0.4],[meanData(k) meanData(k)],'b'); hold on;
+    end
+end
+return
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/modelreduction/SBprepredreac.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/modelreduction/SBprepredreac.m
new file mode 100644
index 0000000000000000000000000000000000000000..3c58ae4245297a89c68be056457594300b09759b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/modelreduction/SBprepredreac.m
@@ -0,0 +1,233 @@
+function [output] = SBprepredreac(model,timevectors,experiments,varargin)
+% SBprepredreac: prepares a model for subsequent reduction of reaction rate
+% expressions. Eventual "power(x,y)" expressions are exchanged against
+% "x^y". Reaction rates are expanded by substituting in variables. Ununsed
+% elements (reactions, variables, and parameters) are deleted from the
+% model. Furthermore reference simulations are performed based on which the
+% models reactions can be reduced in following steps.
+%
+% USAGE:
+% ======
+% [output] = SBprepredreac(model, timevectors, experiments)
+% [output] = SBprepredreac(model, timevectors, experiments, extravariables)
+%
+% model:            SBmodel to consider for reduction
+% timevectors:      time vectors of interest (one for each experiment)
+% experiments:      cell-array with experiment definitions 
+% extravariables:   cellarray with names of parameters that should be taken
+%                   into account as species belonging to the M vector
+%                   or parameters that are set to different values during
+%                   experiments (then they need to be kept in the reduced model)
+%
+% Output Arguments:
+% =================
+% output:   structure with necessary information
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+academicWarningSB
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE NON-NUMERIC INITIAL CONDITIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% just by replacing them
+model = SBconvertNonNum2NumIC(model);
+if ~hasonlynumericICsSB(model),
+    disp('Non-numeric initial conditions will be removed in the reduced model. You can replace them after reduction if you like.');
+end
+    
+output.model = [];
+output.extravariables = [];
+output.timevectors = timevectors;
+output.reference = [];
+output.reference.experiments = experiments;
+output.reference.data = [];
+output.reference.datavalues = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% check if SBPD is present
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBPDisPresent = 1;
+if exist('SBPDsimulate') ~= 2,
+    SBPDisPresent = 0;
+    warning('Installation of the SBPD package, found on www.sbtoolbox2.org, will speed up the model reduction considerably.');
+end  
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% check if symbolic toolbox is present
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~symbolicpresentSB,
+    error('The model reduction feature requires the presence of the symbolic toolbox.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% check cells
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~iscell(timevectors),
+    timevectors = {timevectors};
+end
+if ~iscell(experiments),
+    experiments = {experiments};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+extravariables = {};
+if nargin > 3,
+    extravariables = varargin{1};
+end
+output.extravariables = extravariables;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% check if first argument is a model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBmodel(model),
+    error('First argument needs to be an SBmodel.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% expand reaction expressions by substituting in all variables
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+model = substitutevarsSB(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% check and replace power expressions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[model,changeFlag] = depowerSB(model);
+% if changeFlag == 1,
+% %    disp('Power operators are present. Support for Hill-type rate equations is only experimental at present.');
+%     model = fixExp(model);
+% end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% finally clean the model from unnecessary parameters, reactions, variables
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output.model = cleanmodelSB(model,1);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% simulate the experiments and save the data
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% simulate all the experiments and collect the numeric values for states
+% and reactions and additionally also the parameters (extravariables)
+states = SBstates(output.model)';
+reactions = SBreactions(output.model)';
+parameters = SBparameters(output.model);
+statevalues = [];
+reactionvalues = [];
+parametervalues = [];
+for k = 1:length(experiments),
+    disp(sprintf('Simulating experiment %d/%d ...',k,length(experiments)));
+    modelexp = SBmergemodexp(output.model,experiments{k});
+    % set maxstep options
+    options.maxstep = max(output.timevectors{k})/length(output.timevectors{k});
+    options.maxnumsteps = 10000;
+    if SBPDisPresent,
+        simdata = SBPDsimulate(modelexp,timevectors{k},[],[],[],options);
+    else
+        simdata = SBsimulate(modelexp,timevectors{k});
+    end
+    statevalues = [statevalues; simdata.statevalues];
+    reactionvalues = [reactionvalues; simdata.reactionvalues];
+    % get values for the extra variables that are parameters (can change
+    % during experiments)
+    parametervaluesscalar = SBparameters(modelexp,extravariables)';
+    parametervalues = [parametervalues; parametervaluesscalar(ones(length(timevectors{k}),1),:)];
+end
+% add states extravariables and reactions together
+output.reference.data = {states{:} extravariables{:} reactions{:}};
+output.reference.datavalues = [statevalues parametervalues reactionvalues];
+return
+
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% % fixExp: for all exponential parameters, eg x^p1, fix them to the value
+% % specified in the model => x^4 if p1=4. Do this ONLY for the reaction 
+% % expressions.
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% function model = fixExp(model)
+% global parameterNames parameterValues
+% [parameterNames, parameterValues] = SBparameters(model);
+% sbs = struct(model);
+% for k = 1:length(sbs.reactions),
+%     sbs.reactions(k).formula = fixHelper(sbs.reactions(k).formula);
+% end
+% model = SBmodel(sbs);    
+% return
+% 
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% % fixHelper: subfunction to fixExp
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% function finalString = fixHelper(string)
+% global parameterNames parameterValues;
+% startIndex = strfind(string, '^');
+% finalString = string; index = 0;
+% if ~isempty(startIndex)
+%     finalString = string(1:startIndex(1)-1);
+%     for i = 1:length(startIndex)
+%         openParenthesis = 0;
+%         for j = startIndex(i)+1:length(string)
+%             if string(j) == '(',
+%                 openParenthesis = openParenthesis + 1;
+%             elseif string(j) == ')',
+%                 openParenthesis = openParenthesis - 1;
+%             end
+%             if openParenthesis == 0
+%                 if i == length(startIndex)
+%                     if index < i
+%                         selectedString = string([startIndex(i)+2:j-1]);
+%                         match = findsym(sym(selectedString));
+%                         [found, ia, ib] = intersect(parameterNames, match);
+%                         for k = 1:length(found)
+%                             selectedString = num2str(subs(selectedString, parameterNames(ia(k)), parameterValues(ia(k))));
+%                         end
+%                         finalString = strcat(finalString, '^(', selectedString, ')',string([j+1:end]));
+%                         break;
+%                     end
+%                 elseif j < startIndex(i+1)
+%                     if index < i
+%                         selectedString = string([startIndex(i)+2:j-1]);
+%                         match = findsym(sym(selectedString));
+%                         [found, ia, ib] = intersect(parameterNames, match);
+%                         for k = 1:length(found)
+%                             selectedString = num2str(subs(selectedString, parameterNames(ia(k)), parameterValues(ia(k))));
+%                         end
+%                         finalString = strcat(finalString, '^(', selectedString, ')', string([j+1:startIndex(i+1)-1]));
+%                         break;
+%                     end
+%                 else
+%                     index = find(startIndex > j, 1);
+%                     if isempty(index)
+%                         index = length(startIndex)+1;
+%                     end
+%                     
+%                     rep = fixHelper(string([startIndex(i)+2:j-1]));
+%                     match = regexp(rep, '(.+)[,](.+)', 'tokens');
+%                     finalString = strcat(finalString, '^(', rep, ')');
+%                     break;
+%                 end
+%             end
+%         end
+%     end
+% end
+% return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/modelreduction/SBredallreac.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/modelreduction/SBredallreac.m
new file mode 100644
index 0000000000000000000000000000000000000000..9dcb3efc706d6edce724c9088dcbcee299016668
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/modelreduction/SBredallreac.m
@@ -0,0 +1,195 @@
+function [modelred] = SBredallreac(model,experiments,timevectors,varargin)
+% SBredallreac: Wrapper for the SBredreac function allowing to easily
+% go through a whole model and reduce all reactions that are possible to
+% reduce.
+% 
+% USAGE:
+% ======
+% [modelred] = SBredallreac(model,experiments,timevectors)
+% [modelred] = SBredallreac(model,experiments,timevectors,OPTIONS)
+% [modelred] = SBredallreac(model,experiments,timevectors,OPTIONS,extravariables)
+%
+% model:            SBmodel to consider for reduction
+% timevectors:      cell-array with time vectors of interest (one for each experiment)
+% experiments:      cell-array with experiment definitions 
+% extravariables:   cellarray with names of parameters that should be taken
+%                   into account as species belonging to the M vector
+%                   or parameters that are set to different values during
+%                   experiments (then they need to be kept in the reduced model)
+% OPTIONS: structure containing options for the algorithm:
+%        OPTIONS.tol: tolerance for singularity detection (smallest SV)
+%        OPTIONS.keeporigparameters: =0: do not keep original parameters
+%                                    =2: do always keep original parameters
+%                                    =1: keep original parameters only if
+%                                        it leads to fewer parameters
+%        OPTIONS.numeratorweighting: =1: weight numerator terms and denumerator terms 
+%                                    such that numerators are kept
+%                                    =0: dont do any weighting
+%
+% DEFAULT VALUES:
+% ===============
+% extravariables:               {}
+% OPTIONS.tol:                  1e-6
+% OPTIONS.keeporigparameters:   0
+% OPTIONS.numeratorweighting:   0
+%
+% Output Arguments:
+% =================
+% modelred: SBmodel in which the defined reaction is reduced
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+academicWarningSB
+
+global SBPDisPresent
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% check if SBPD is present
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBPDisPresent = 1;
+if exist('SBPDsimulate') ~= 2,
+    SBPDisPresent = 0;
+    warning('Installation of the SBPD package, found on www.sbtoolbox2.org, will speed up the model reduction considerably.');
+end  
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% check cell-arrays in input
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~iscell(experiments),
+    experiments = {experiments};
+end
+if ~iscell(timevectors),
+    timevectors = {timevectors};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+OPTIONS = [];
+extravariables = {};
+if nargin >= 4,
+    OPTIONS = varargin{1};
+end
+if nargin >= 5,
+    extravariables = varargin{2};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% prepare reduction - DOES ALSO HANDLE NON-NUMERIC ICs ... by converting
+% them to NUMERIC ICs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+disp('Preparing data for reduction ...');
+output = SBprepredreac(model,timevectors,experiments,extravariables);
+[reactions, formulas] = SBreactions(output.model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Go through all reactions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+disp('Going through all reactions ...');
+modelred = output.model;
+for k = 1:length(reactions),
+    clc;
+    reaction = reactions{k};
+    formula = formulas{k};
+    text = sprintf('%s = %s\n',reaction,formula);
+    disp(text);
+    while 1,
+        choose = input('Reduce this reaction (1) or not (0)? ');
+        if choose == 1 || choose == 0,
+            break;
+        end
+    end
+    if choose == 1,
+        % run
+        modelsave = modelred;
+        while 1,
+            try
+                [modelred] = SBredreac(output,reaction,OPTIONS);
+                output.model = modelred;
+            catch
+                disp(lasterr);
+            end
+            try
+                runcomparison(model,modelred,experiments,timevectors);
+            catch
+                disp(lasterr);
+                disp('Something went wrong ... you should press 0!');
+            end
+            while 1,
+                check = input('Does this look ok (1) or not (0)?');
+                if check == 1 || check == 0,
+                    break;
+                end
+            end
+            if check == 0,
+                output.model = modelsave;
+                modelred = modelsave;
+            else
+                break;
+            end
+        end
+    end
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% run comparison with original model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [] = runcomparison(model,modelred,experiments,timevectors)
+global SBPDisPresent
+figure(1); clf;
+for k = 1:length(experiments),
+    subplot(length(experiments),1,k);
+    % perform experiment
+    modexp = SBmergemodexp(model,experiments{k});
+    % set maxstep options
+    options.maxstep = max(timevectors{k})/length(timevectors{k});
+    options.maxnumsteps = 10000;
+    if SBPDisPresent,
+        expdata = SBPDsimulate(modexp,timevectors{k},[],[],[],options);
+    else
+        expdata = SBsimulate(modexp,timevectors{k});
+    end
+    modredexp = SBmergemodexp(modelred,experiments{k});
+    if SBPDisPresent,
+        redexpdata = SBPDsimulate(modredexp,timevectors{k},[],[],[],options);
+    else
+        redexpdata = SBsimulate(modredexp,timevectors{k});
+    end
+    % plot results
+    plot(expdata.time,expdata.statevalues); hold on; 
+    plot(redexpdata.time,redexpdata.statevalues,'o');
+    % legend
+    if k == 1,
+        hlhlx = legend(SBstates(model),'Location','NorthEastOutside');
+        set(hlhlx,'Interpreter','none');
+    end
+    title(sprintf('Comparison for Experiment %d',k));
+
+    % At this point the user can add whatever comparison test between the
+    % original and reduced model that is necessary ...
+
+end
+return
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/modelreduction/SBredreac.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/modelreduction/SBredreac.m
new file mode 100644
index 0000000000000000000000000000000000000000..30a27271d14e3407fac079464b550e1d761e9ffe
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/modelreduction/SBredreac.m
@@ -0,0 +1,288 @@
+function [modelred] = SBredreac(output,reaction,varargin)
+% SBredreac: Reduction of single reaction expressions with the goal of reducing
+% complexity and number of parameters. This function requires the prior
+% execution of the SBprepredreac.
+% 
+% USAGE:
+% ======
+% [modelred] = SBredreac(output,reaction)
+% [modelred] = SBredreac(output,reaction,OPTIONS)
+%
+% output: Result returned from prepredreacSB
+% reaction: Name of the reaction that should be reduced
+% OPTIONS: structure containing options for the algorithm:
+%        OPTIONS.tol: tolerance for singularity detection (smallest SV)
+%        OPTIONS.keeporigparameters: =0: do not keep original parameters
+%                                    =2: do always keep original parameters
+%                                    =1: keep original parameters only if
+%                                        it leads to fewer parameters
+%        OPTIONS.numeratorweighting: =1: weight numerator terms and denumerator terms 
+%                                    such that numerators are kept
+%                                    =0: dont do any weighting
+%
+% DEFAULT VALUES:
+% ===============
+% OPTIONS.tol:                  1e-6
+% OPTIONS.keeporigparameters:   0
+% OPTIONS.numeratorweighting:   0
+%
+% Output Arguments:
+% =================
+% modelred: SBmodel in which the defined reaction is reduced
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+academicWarningSB
+
+% open needed figure that is to be updates during the whole reduction
+% procedure of the given reaction
+figH2 = figure(2); clf;
+yaxismax = 0;
+xplot = -1;
+yplot = -1;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% check if symbolic toolbox is present
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~symbolicpresentSB,
+    error('The model reduction feature requires the presence of the symbolic toolbox.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle variable input arguments (options)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+OPTIONS = [];
+if nargin == 3,
+    OPTIONS = varargin{1};
+end
+% default values
+tol = 1e-6;              % tolerance for singularity detection (smalles SV)
+keeporigparameters = 0;  % do not keep original parameters
+numeratorweighting = 0;  % do not weight numerators/denumerators depending on their number
+% tol
+if isfield(OPTIONS,'tol'),
+    if ~isempty(OPTIONS.tol),
+        tol = OPTIONS.tol;
+    end
+end
+% keeporigparameters
+if isfield(OPTIONS,'keeporigparameters'),
+    if ~isempty(OPTIONS.keeporigparameters),
+        keeporigparameters = OPTIONS.keeporigparameters;
+    end
+end
+% numeratorweighting
+if isfield(OPTIONS,'numeratorweighting'),
+    if ~isempty(OPTIONS.numeratorweighting),
+        numeratorweighting = OPTIONS.numeratorweighting;
+    end
+end
+
+disp(' ');
+disp('#####################################################################');
+disp(sprintf('# Reduction of reaction:  %s', reaction));
+disp('#####################################################################');
+
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine reduction information for specified reaction
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output2 = reducereactionprepSB(output,reaction);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine which terms to reduce
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% number terms in original equation
+nrorig = size(output2.reaction_trans.A,2);
+indexkeep = [1:nrorig];
+indexkeep_backup = {};
+while 1,
+    try
+        % Reduce (do this also for the case where indexkeep contains all terms)
+        output3 = reducereacSB(output2,indexkeep,keeporigparameters);
+    catch
+        % catch errors that can occurr in cases when no reduction is possible
+        % example: reaction only defined by constant rate
+        %          ...
+        
+        disp('************************** All nominators might have been cancelled ... try nominator weighting!');
+    end
+    % Optimize parameter values
+    output4 = reduceoptimSB(output3);
+    % check if optimization successful (do it by looking at it!)
+    orig = output3.reaction_orig.reactionvalues;
+    redopt = output4.reaction_opt.reactionvalues;
+    figH = figure(1); clf; 
+    plot(orig); hold on; plot(redopt,'r--'); 
+    
+    
+    
+    % also plot the obtained costfunction value against the ratio between the 
+    % number of parameters in the reduced and original model. Divide the
+    % cost by the mean
+    nrorigterms = length(output4.reaction_trans.c);
+    nrredterms = length(indexkeep);
+    costred_scaled = output4.reaction_opt.cost/mean(orig);
+    figure(figH2);
+    xoldplot = xplot;
+    yoldplot = yplot;
+    xplot = nrredterms/nrorigterms;
+    yplot = costred_scaled;
+    plot(xplot,yplot,'r*'); hold on;
+    if xoldplot >= 0,
+        plot(xoldplot,yoldplot,'w*'); hold on;
+        plot(xoldplot,yoldplot,'bo'); hold on;
+    end
+    yaxismax = max(yaxismax, yplot*1.1);
+    axis([0 1 0 yaxismax]);    
+    xlabel('#redterms/#origterms');
+    ylabel('optimal cost');
+    
+    
+    
+    % plot some info
+disp(' ');
+if length(indexkeep) > 1,
+    disp('Linear dependency and approximation measures');
+    disp('############################################');
+    [Us,Ss,Vs] = svd(output3.reductioninfo.Anumscaled(:,indexkeep));
+    disp(sprintf('Singular values Mscaled: %s', sprintf('%g ',diag(Ss))));
+    disp(sprintf('Elements v*(Mscaled): %s',sprintf('%g ',Vs(:,end))));
+    disp(' ');
+    [Uc,Sc,Vc] = svd(output3.reductioninfo.AnumC(:,indexkeep));
+    disp(sprintf('Singular values Mc: %s', sprintf('%g ',diag(Sc))));
+    disp(sprintf('Elements v*(Mc): %s',sprintf('%g ',Vc(:,end))));
+    disp(' ');
+end
+disp('Statistics and preliminary result ');
+disp('#################################');
+    text = sprintf('Nr parameters in original/reduced expression: %d/%d\n',length(output2.reaction_orig.parameters),length(output3.reaction_red.parameters));
+    indexdelete = setdiff([1:nrorig],indexkeep);
+    deleteText = '';
+    for k = 1:length(indexdelete),
+        deleteText = strcat(deleteText, ', ', output3.reaction_trans.A{indexdelete(k)});
+    end
+    text = sprintf('%sDeleted terms: %s\n',text,deleteText(2:end));
+    text = sprintf('%s%s_red = %s\n',text,output2.reaction,output3.reaction_red.formula);
+    disp(text);
+    % Decide what to do next
+    if length(indexkeep_backup) == 0,
+        while 1,
+            check = input('Continue (2), or end (0) (switch num weighting: 99): ');
+            if check == 2 || check == 0,
+                break;
+            elseif check == 99,
+                numeratorweighting = ~numeratorweighting;
+                disp(sprintf('numeratorweighting = %d',numeratorweighting));
+            end
+        end
+    else
+        while 1,
+            check = input('Continue (2), go back (1), end (0) (switch num weighting: 99): ');
+            if check == 2 || check == 1 || check == 0,
+                break;
+            elseif check == 99,
+                numeratorweighting = ~numeratorweighting;
+                disp(sprintf('numeratorweighting = %d',numeratorweighting));
+            end
+        end
+    end
+    if check == 1,
+        % go a step back
+        indexkeep = indexkeep_backup{end};
+        indexkeep_backup = indexkeep_backup(1:end-1);
+    elseif check == 0,
+        % end reduction
+        break;
+    else
+        % continue
+        indexkeep_backup{end+1} = indexkeep;
+        % Select what to reduce
+        Anumscaled = output2.reductioninfo.Anumscaled(:,indexkeep);
+        AnumC = output2.reductioninfo.AnumC(:,indexkeep);
+        [U,S,V] = svd(Anumscaled);
+        SAns = diag(S)';
+        VAns = V(:,end);
+        [U,S,V] = svd(AnumC);
+        SAnc = diag(S)';
+        VAnc = V(:,end);
+        V1 = abs(VAns);
+        V2 = abs(VAnc);
+        % do numeratorweighting (if on then set numerator elements to 0),
+        % avoidng the deletion of numerators
+        if numeratorweighting == 1,
+            isnomterm = output2.reductioninfo.isnomterm(indexkeep);
+            numbernom = sum(isnomterm);
+            numberden = length(isnomterm)-numbernom;
+            factor = [ones(numberden,1); 0*ones(numbernom,1)];
+            V1 = V1.*factor;
+            V2 = V2.*factor;
+        end
+        V1 = max(V1-mean(V1),0);
+        V2 = max(V2-mean(V2),0);
+        if SAns(end) < tol,
+            disp('##########################################');
+            disp('# Reduction:  Based on linear dependency #');
+            disp('##########################################');
+            V = V1+0.01*V2;
+identFlag = 1;
+        else
+            disp('####################################');
+            disp('# Reduction based on approximation #');
+            disp('####################################');
+            V = V2;
+identFlag = 0;
+        end
+
+if identFlag == 0,
+    [dummy,indexdeleteNEXT] = max(V);
+else
+% determine the k that minimizes the relative changes
+    c = output4.reaction_red.parametervalues;
+    testValues = zeros(1,length(c));
+    for k4=1:length(c),
+        ssum = 0;
+        if V(k4) ~= 0,
+            for i4=1:length(V),
+                if k4~=i4,
+                    ssum = ssum + (abs(c(k4)*V(i4)/V(k4)/c(i4)));
+                end
+            end
+            testValues(k4) = ssum;
+        else
+            testValues(k4) = inf;
+        end
+    end
+    [dummy, indexdeleteNEXT] = min(testValues);
+end
+       
+        indexkeep(indexdeleteNEXT) = [];   % delete element
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Update the model with the reduced reaction
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modelred= redupdateSB(output4);
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/modelreduction/auxiliary/reduceoptimSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/modelreduction/auxiliary/reduceoptimSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..066a774e53f9c44ee8495a320c557c04b6190d02
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/modelreduction/auxiliary/reduceoptimSB.m
@@ -0,0 +1,68 @@
+function [output] = reduceoptimSB(output)
+% reduceoptimSB: optimizes reduced parameter values
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Optimize new parameters with estimates as starting guess
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
+global opt_ref opt_formula opt_param opt_var opt_varvalues reac
+opt_ref = output.reaction_orig.reactionvalues;           % reaction value from unreduced reaction
+opt_formula = output.reaction_red.formula;               % reduced formula
+opt_param = output.reaction_red.parameters;              % parameternames in reduced formula
+opt_paramvalues = output.reaction_red.parametervalues;   % parametervalues in reduced formula
+opt_var = output.reaction_red.variables;                 % variable names
+opt_varvalues = output.reaction_red.variablevalues;      % variable values
+options.maxiter = 100;
+options.lowbounds = -1e10*ones(1,length(opt_param));
+options.highbounds = 1e10*ones(1,length(opt_param));
+options.silent = 1;
+old = inf;
+FVAL = -inf;
+while abs(old-FVAL) > 1e-4
+    old = FVAL;
+    [opt_paramvalues, FVAL] = simplexSB(@costfunction,opt_paramvalues,options);
+end
+output.reaction_opt.parametervalues = opt_paramvalues;
+output.reaction_opt.reactionvalues = reac;
+output.reaction_opt.cost = FVAL;
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
+function [cost] = costfunction(X)
+global opt_ref opt_formula opt_param opt_var opt_varvalues reac
+% assign parameter values
+for k = 1:length(X),
+    eval(sprintf('%s = %f;',opt_param{k},X(k)));
+end
+% assign variable values
+for k = 1:length(opt_var),
+    eval(sprintf('%s = opt_varvalues(:,k);',opt_var{k}));
+end
+% evaluate reaction equation
+reac = eval(formula2vecSB(opt_formula));
+% determine cost
+cost = sqrt(sum((reac-opt_ref).^2));
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/modelreduction/auxiliary/reducereacSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/modelreduction/auxiliary/reducereacSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..5d7f390c737a759c256d95d882fab861be200c7b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/modelreduction/auxiliary/reducereacSB.m
@@ -0,0 +1,160 @@
+function [output] = reducereacSB(output,indexkeep,varargin)
+% reducereacSB: reduces the equation by keeping only the defined terms of
+% the A vector. Subsequently the values of the new parameters are defined.
+%
+% [output] = reducereacSB(output,indexkeep)
+% [output] = reducereacSB(output,indexkeep,keeporigparameters)
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% check if symbolic toolbox is present
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~symbolicpresentSB,
+    error('The model reduction feature requires the presence of the symbolic toolbox.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+keeporigparameters = 0;
+if nargin == 3,
+    keeporigparameters = varargin{1};
+end
+
+output.keeporigparameters = keeporigparameters;
+output.reaction_red = [];
+output.reaction_red.formula = [];
+output.reaction_red.formulaop = [];
+output.reaction_red.parameters = [];
+output.reaction_red.parametervalues = [];
+output.reaction_red.variables = [];
+output.reaction_red.variablevalues = [];
+output.reaction_red.reactionvalues = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Build new reduced reaction expression ... use new or original parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% First check if new or original parameters (output.keeporigparameters = 0
+% does not keep them =1 keeps them eventually, =2 keeps them always).
+% copy flag to extra variable to keep it on the initial value in the output
+% structure. =1: Original parameters are kept if it means that this leads to
+% fewer parameters. 
+keeporigparameters = output.keeporigparameters;
+if keeporigparameters == 1,
+    testparam = {};
+    for k = 1:length(indexkeep),
+        % determine parameters
+        testparam = getNewParameters(testparam,output.reaction_trans.c{indexkeep(k)},output.reaction_orig.parameters);
+    end
+    if length(testparam) > length(indexkeep),
+        % Keeping original parameters would lead to more parameters => skip it
+        keeporigparameters = 0;
+    end
+end
+
+expression = sym(0);
+newparam = {};
+if keeporigparameters == 0,
+    % Use new parameters (eventually more degrees of freedom and a better fit
+    newbaseparamname = ['K_' output.reaction '_'];
+    for k = 1:length(indexkeep),
+        newparam{end+1} = sprintf('%s%d',newbaseparamname,k);
+        expression = expression + sym(output.reaction_trans.A{indexkeep(k)})*sym(newparam{end});
+    end
+else
+    % Use original parameters (eventually fewer degrees of freedom and a worse fit)
+    for k = 1:length(indexkeep),
+        % determine parameters
+        newparam = getNewParameters(newparam,output.reaction_trans.c{indexkeep(k)},output.reaction_orig.parameters);
+        % build new expression
+        expression = expression + sym(output.reaction_trans.A{indexkeep(k)})*sym(output.reaction_trans.c{indexkeep(k)});
+    end
+end
+expression = [output.reaction_trans.b{1} '=' char(expression)];
+reacredRHS = solve(expression,output.reaction);
+% add info to structure
+output.reaction_red.formula = char(reacredRHS);
+output.reaction_red.parameters = newparam;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if all numerators have been deleted (leads to an error)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if output.reaction_red.formula == '0',
+    error('All numerator terms have been deleted from the reaction expression.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine the parameter values (starting guesses for eventual optimization)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    
+if keeporigparameters == 0,
+    % New parameters: Use nonlinear regression to estimate the new parameter values
+    %Ared = output.reaction_trans.Anum(:,indexkeep);
+    %bred = output.reaction_trans.bnum;
+    %output.reaction_red.parametervalues = (pinv(Ared)*bred)';
+    % Get new parameters from the old ones (as starting guess)
+    output.reaction_red.parametervalues = output.reaction_trans.cnum(indexkeep);
+else
+    % Old parameters: just use the original values
+    output.reaction_red.parametervalues = SBparameters(output.model,output.reaction_red.parameters)';
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine the variables that are present and also get their numeric values
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
+output.reaction_red.variables = setdiff(explodePCSB(findsym(sym(output.reaction_red.formula))),output.reaction_red.parameters);
+variablevalues = [];
+for k = 1:length(output.reaction_red.variables),
+    index = strmatchSB(output.reaction_red.variables{k}, output.reaction_orig.variables, 'exact');
+    variablevalues(:,end+1) = output.reaction_orig.variablevalues(:,index);
+end
+output.reaction_red.variablevalues = variablevalues;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine the reaction rate for defined experiments 
+% for reduced expression
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    
+% Define all the variables in the workspace
+for k = 1:length(output.reaction_red.variables),
+    eval(sprintf('%s = output.reaction_red.variablevalues(:,k);',output.reaction_red.variables{k}));
+end
+% Define the new parameters in the workspace
+for k = 1:length(output.reaction_red.parameters),
+    eval(sprintf('%s = output.reaction_red.parametervalues(k);',output.reaction_red.parameters{k}));
+end
+% Evaluate the reduced reaction formula
+reaceval = formula2vecSB(output.reaction_red.formula);
+redreactionvalues = eval(reaceval);
+output.reaction_red.reactionvalues = redreactionvalues;
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine new parameters in expression for parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [newparam] = getNewParameters(newparam, expression, possibleparam)
+addparam = explodePCSB(findsym(sym(expression)));
+newparam = unique({newparam{:}, addparam{:}});
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/modelreduction/auxiliary/reducereactionprepSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/modelreduction/auxiliary/reducereactionprepSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..cf788035594b3fba2688d597c3f5eb11fbcc03c3
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/modelreduction/auxiliary/reducereactionprepSB.m
@@ -0,0 +1,263 @@
+function [output] = reducereactionprepSB(output,reaction)
+% reducereactionprepSB: This function transforms the reaction rate in the
+% following form:
+%                       a' * c = v
+% 
+% determines the numerical values based on the simulation of the specified 
+% experiments and determines information about the reducibility of the
+% reaction expression.
+%
+% USAGE:
+% ======
+% output = SBreducereactionprep(model,reaction)
+%
+% model:            SBmodel to consider
+% reaction:         name of the reaction to determine M and c for
+%
+% Output Arguments:
+% =================
+% The output of this function is a matlab structure containing all
+% necessary information.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% check if symbolic toolbox is present
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~symbolicpresentSB,
+    error('The model reduction feature requires the presence of the symbolic toolbox.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% check if given reaction present in model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(reactionindexSB(output.model,reaction)),
+    error('Given reaction is not part of the model.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define the output structure
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output.reaction = reaction;
+output.reaction_orig = [];
+output.reaction_orig.formula = [];
+output.reaction_orig.parameters = [];
+output.reaction_orig.parametervalues = [];
+output.reaction_orig.variables = [];
+output.reaction_orig.variablevalues = [];
+output.reaction_orig.reactionvalues = [];
+output.reaction_trans = [];
+output.reaction_trans.A = [];
+output.reaction_trans.Anum = [];
+output.reaction_trans.b = [];
+output.reaction_trans.bnum = [];
+output.reaction_trans.c = [];
+output.reaction_trans.cnum = [];
+output.reductioninfo = [];
+output.reductioninfo.isnomterm = [];
+output.reductioninfo.Anumscaled = [];
+output.reductioninfo.AnumC = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% get the reaction formula and add it to the output
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[reacnames,reacformulas] = SBreactions(output.model);
+output.reaction_orig.formula = [reacformulas{reactionindexSB(output.model,reaction)}];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% get symbolic parameters, variables, A, b, and c
+% additionally determine a vector with indices 1 if term corresponds to
+% nominator and 0 if to denominator
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[parameters, variables, A, b, c, isnomterm] = getDataAndTransform(output);
+output.reductioninfo.isnomterm = isnomterm;
+output.reaction_orig.parameters = parameters;
+output.reaction_orig.variables = variables;
+output.reaction_trans.A = A;
+output.reaction_trans.b = b;
+output.reaction_trans.c = c;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% get numeric data for parameters, variables, A, b, and c and the reaction
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[reactionn, parametersn, variablesn, An, bn, cn] = getNumericData(output);
+output.reaction_orig.reactionvalues = reactionn;
+output.reaction_orig.parametervalues = parametersn;
+output.reaction_orig.variablevalues = variablesn;
+output.reaction_trans.Anum = An;
+output.reaction_trans.bnum = bn;
+output.reaction_trans.cnum = cn;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% determine reduction information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[Anscaled, AnC] = getReductionInfo(output);
+output.reductioninfo.Anumscaled = Anscaled;
+output.reductioninfo.AnumC = AnC;
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine reduction information
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [Anscaled, AnC] = getReductionInfo(output)
+%%%%%%%%%%%%%%%%%%%%%%%
+% Scale the matrix A such that the element with the largest magnitude
+% in each column and experiment has a magnitude of 1
+%%%%%%%%%%%%%%%%%%%%%%%
+Anscaled = zeros(size(output.reaction_trans.Anum));
+for k = 1:length(output.reference.experiments),
+    Anexp = output.reaction_trans.Anum((k-1)*length(output.timevectors{k})+1:k*length(output.timevectors{k}),:);
+    Anexpscaled = Anexp*diag(1./max(abs(Anexp)));
+    Anscaled((k-1)*length(output.timevectors{k})+1:k*length(output.timevectors{k}),:) = Anexpscaled;
+end
+%%%%%%%%%%%%%%%%%%%%%%%
+% Determine the product of A and c in diagonal matrix (weighting each 
+% term in A with its corresponding coefficient
+%%%%%%%%%%%%%%%%%%%%%%%
+AnC = output.reaction_trans.Anum*diag(output.reaction_trans.cnum);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get numeric data for parameters, variables, A, b, and c
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [reactionn, parametersn, variablesn, An, bn, cn] = getNumericData(output)
+% get variable values 
+variablesn = [];
+for k = 1:length(output.reaction_orig.variables),
+    var = output.reaction_orig.variables{k};
+    % get values from reference data
+    indexdata = strmatchSB(var,output.reference.data,'exact');
+    if ~isempty(indexdata),
+        variablesn(:,k) = output.reference.datavalues(:,indexdata);
+    end
+end
+% get reaction values
+indexdata = strmatchSB(output.reaction,output.reference.data,'exact');
+reactionn = output.reference.datavalues(:,indexdata);
+% Get parameter values (It is assumed that these parameters are constant
+% ... and not chaged during the experiments)
+parametersn = SBparameters(output.model,output.reaction_orig.parameters)';
+%%%%%%%%%%%%%%%%%%%%%%%
+% Determine An
+%%%%%%%%%%%%%%%%%%%%%%%
+% Define all the variables in the workspace
+for kloopx = 1:length(output.reaction_orig.variables),
+    eval(sprintf('%s = variablesn(:,kloopx);',output.reaction_orig.variables{kloopx}));
+end
+% Define the reaction in the workspace
+eval(sprintf('%s = reactionn;',output.reaction));
+% Then determine An
+An = zeros(size(variablesn,1),length(output.reaction_trans.A));
+for k = 1:length(output.reaction_trans.A),
+    Aevalk = formula2vecSB(output.reaction_trans.A{k});
+    An(:,k) = eval(Aevalk);
+end
+%%%%%%%%%%%%%%%%%%%%%%%
+% Determine bn
+%%%%%%%%%%%%%%%%%%%%%%%
+% bn is just the negative of the reaction values
+bn = -reactionn;
+%%%%%%%%%%%%%%%%%%%%%%%
+% Determine cn
+%%%%%%%%%%%%%%%%%%%%%%%
+% Define all reaction parameters
+for kloopx = 1:length(output.reaction_orig.parameters),
+    eval(sprintf('%s = %g;',output.reaction_orig.parameters{kloopx},parametersn(kloopx)));
+end
+cn = [];
+for kloopx = 1:length(output.reaction_trans.c),
+    cn(end+1) = eval(sprintf('%s',output.reaction_trans.c{kloopx}));
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Transform the reaction expression and determine parameters, variables, A,
+% b, and c
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Instead of determining A, b, c directly we go via M * p = 0
+function [parameters, variables, A, b, c, isnomterm] = getDataAndTransform(output)
+%%%%%%%%%%%%%%%%%%%%%%%
+% Obtain M and p
+%%%%%%%%%%%%%%%%%%%%%%%
+% Convert the formula to a symbolic expression and determine numerator and denominator
+% determine numerator and denominator of reaction equation
+formulasym = sym(output.reaction_orig.formula);
+[numFsym, denFsym] = numden(formulasym);
+% Get a symbolic expression with all the variable names (not being coefficients)
+statenames = SBstates(output.model);
+allnames = {statenames{:} output.extravariables{:}};
+variablessym = maplearraySB(allnames);
+% Determine the coefficients in the num and den
+[numCoeffssym,numVarssym] = coeffs(expand(numFsym), variablessym);
+[denCoeffssym,denVarssym] = coeffs(expand(denFsym), variablessym);
+Msym = [denVarssym*output.reaction -numVarssym];
+psym = [denCoeffssym numCoeffssym];
+M = {}; p = {};
+for k = 1:length(Msym),
+    M{k} = char(Msym(k));
+    p{k} = char(psym(k));
+end
+%%%%%%%%%%%%%%%%%%%%%%%
+% Obtain parameters and variables
+%%%%%%%%%%%%%%%%%%%%%%%
+parameters = explodePCSB(findsym(psym));
+variables = setdiff(explodePCSB(findsym(Msym)),output.reaction); % delete reaction name from list of variables
+% Clear not needed symbolic variables
+clear formulasym numFsym denFsym variablessym 
+clear numCoeffssym numVarssym denCoeffssym denVarssym
+clear Msym psym
+%%%%%%%%%%%%%%%%%%%%%%%
+% Get A, b, and c
+%%%%%%%%%%%%%%%%%%%%%%%
+% search the elements of M to determine which one corresponds to the reaction rate 
+for k = 1:length(M),
+    if strcmp(M{k},output.reaction),
+        break;
+    end
+end
+indexelement = k;
+% Determine A from M
+A = M(setdiff(1:length(M),indexelement));
+% Determine b from M (sign is important and should be negative!)
+b = {char(-sym(M{:,indexelement}))};
+% Determine c from p
+c = p(setdiff(1:length(M),indexelement));
+c_divisor = p{indexelement};
+for k = 1:length(c),
+    num = sym(c{k});
+    den = sym(c_divisor);
+    c{k} = char(num/den);
+end
+%%%%%%%%%%%%%%%%%%%%%%%
+% Get isnomterm
+%%%%%%%%%%%%%%%%%%%%%%%
+% Check output.reaction_trans.A: all elements that do not contain the 
+% reaction name correspond to a nominator term
+isnomterm = zeros(1,length(A));
+for k = 1:length(A),
+    if isempty(strfind(A{k},output.reaction)),
+        isnomterm(k) = 1;
+    end
+end
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/modelreduction/auxiliary/redupdateSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/modelreduction/auxiliary/redupdateSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..cfedf0e86572ac34595ba37ce27f9390b2817693
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/modelreduction/auxiliary/redupdateSB.m
@@ -0,0 +1,63 @@
+function [model] = redupdateSB(output)
+% redupdateSB: Returns an SBmodel in which the reaction is exchanged 
+% against the reduced reaction 
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+model = output.model;
+sbs = struct(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Exchange reaction to reduced reaction
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+index = reactionindexSB(model,output.reaction);
+sbs.reactions(index).formula = output.reaction_red.formula;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add/Update new parameters (if parameters already exist only their values
+% need to be changed).
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modelparameters = SBparameters(model);
+for k=1:length(output.reaction_opt.parametervalues),
+    % check if current parameter exists already
+    index = strmatchSB(output.reaction_red.parameters{k},modelparameters,'exact');
+    if ~isempty(index),
+        % parameter exists already => update it
+        sbs.parameters(index).value = output.reaction_opt.parametervalues(k);
+    else
+        % parameter does not exist => add it
+        sbs.parameters(end+1).name = output.reaction_red.parameters{k};
+        sbs.parameters(end).value = output.reaction_opt.parametervalues(k);
+        sbs.parameters(end).type = '';
+        sbs.parameters(end).compartment = '';
+        sbs.parameters(end).unittype = '';
+        sbs.parameters(end).notes = '';
+    end
+end
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Clean the model and return
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+model = SBmodel(sbs);
+model = cleanmodelSB(model,1);
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/simulation/SBstochsim.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/simulation/SBstochsim.m
new file mode 100644
index 0000000000000000000000000000000000000000..1f32d155886593b97678f0d015e2af0a31f55f17
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/simulation/SBstochsim.m
@@ -0,0 +1,206 @@
+function [varargout] = SBstochsim(model,time,V,varargin)
+% SBstochsim: Stochastic simulation of SBmodels that only contain mass
+% action kinetics. The simulator is based on the paper:
+% Ullah, M., Schmidt, H., Cho, K.-H., Wolkenhauer, O. (2006) Deterministic
+% Modelling and Stochastic Simulation of Pathways using MATLAB, 
+% IEE Proceedings - Systems Biology, 153(2), 53-60
+%
+% The SBmodel needs to have a certain format, explained below.
+%
+% USAGE:
+% ======
+% [output] = SBstochsim(model,time,V)         
+% [output] = SBstochsim(model,time,V,units)         
+% [output] = SBstochsim(model,time,V,units,runs)         
+% [output] = SBstochsim(model,time,V,units,runs,Nsample)         
+%
+% model:   SBmodel 
+%          There are certain limitations on an SBmodel used for stochastic
+%          simulation. Please read further below.
+% time:    End time for simulation 
+% V:       Volume/NumbersFlag: If a number is given then this number is in
+%          interpreted as the volume of the reaction space (given in Liter).
+%          This is necessary in order to do stochastic simulations if the
+%          species in the model are in concentration units.
+%          If the species in the model are given in molecule numbers, the 
+%          volume is not important and this is indicated by setting V to
+%          [].
+% units:   This value is only used in the case that the species are defined
+%          in concentration units. Per default nM (units=1e-9) are assumed
+%          for all species. If the model uses uM the units argument needs
+%          to be set to 1e-6, etc. (default: 1e-9 used only if V has a
+%          numeric value) 
+% runs:    number of realizations(simulation runs) (default: 1)
+% Nsample: Each Nsample-th point will be used for output (to save memory) 
+%          (default: 100)
+%
+% Output Arguments:
+% =================
+% If no output arguments are given, the result of the simulation is
+% plotted (if runs>1 only the mean is plotted). Otherwise the output
+% argument has the following structure:
+%
+% output.time:            cell-array with time vectors for the single runs 
+% output.speciesdata:     cell-array with simulation data for the single runs
+% output.runs:            number of runs
+% output.timemean:        ensemble of all time instants in the single runs
+% output.speciesdatamean: matrix containing the means of the simulation data
+% output.species:         cell-array containing the names of the species
+%
+% FORMAT OF THE SBmodel:
+% ======================
+% SBmodels that can be used for stochastic simulation need to follow some
+% rules:
+% 1) All reaction kinetics need to be of mass action type and be defined in
+%    the following syntax:     'ReactionName' = 'kineticParameter' * ...
+% 2) All reactions have to be irreversible. You can use the 
+%    function SBmakeirreversible to convert your model
+% 3) The reactions can at maximum have 2 substrates and 2 products.
+% 4) The right hand side of the ODEs needs only to consist of reaction rate
+%    terms and eventually stoichiometric coefficients. This is necessary in
+%    order to be able to determine the stoichiometric matrix.
+%    More information about the required syntax can be found in the help
+%    text of the function SBstoichiometry
+% 5) No variables, functions, events, functionsMATLAB are allowed to be
+%    present.
+% 6) Initial conditions of species are assumed to be given in numbers of
+%    molecules
+
+% Information:
+% ============
+% Systems Biology Toolbox for MATLAB
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+% 
+% This program is free software; you can redistribute it and/or
+% modify it under the terms of the GNU General Public License
+% as published by the Free Software Foundation; either version 2
+% of the License, or (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,
+% USA.
+
+academicWarningSB
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+runs = 1;
+Nsample = 100;
+shownr = 0;
+units = 1e-9;
+if nargin == 3,
+elseif nargin == 4,
+    units = varargin{1};
+elseif nargin == 5,
+    units = varargin{1};
+    runs = varargin{2};
+elseif nargin == 6,
+    units = varargin{1};
+    runs = varargin{2};
+    Nsample = varargin{3};
+elseif nargin == 7,
+    units = varargin{1};
+    runs = varargin{2};
+    Nsample = varargin{3};
+    shownr  = varargin{4};
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Process the model - ALSO TAKES CARE OF NON-NUMERIC ICs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Convert model to MA structure
+MA = SBconvert2MA(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Obtain necessary data for simulation
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% initial numbers of molecules (or concentration)
+n0 = MA.initialConditions;
+% stoichiometric matrix
+D = MA.N;
+% kinetic parameters
+k = MA.kineticParameters';
+% Stoich coeffs of the reactants (obtained via SBconvert2MA)
+L = MA.L;
+
+if ~isempty(V),
+    % Models species given in concentrations ... determine stochastic rate
+    % and number of initial molecules
+    % Avogadro's number times volume
+    NAV = V*units*6.02214199e23;
+    % convert concentration to numbers
+    n0 = n0*NAV;
+    % molecularity
+    K = sum(L);
+    % 'particle' rate constant
+    kp = k./NAV.^(K-1);
+    % normalise for correct units
+    kp = kp./units.^(K-1);     
+    % stochastic rate constant
+    c = kp.*prod(factorial(L));
+else
+    % Models species given in numbers ... use the kinetic constants as
+    % stochastic rate constants.
+    c = k;
+end
+
+if shownr == 2,
+    disp('kinetic constant / stochastic rate constant');
+    [k(:) c(:)]
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Stochastic simulation
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[Ts,Ns,TT,NBAR] = stochSB(n0,c,D,L,time,runs,Nsample,shownr);
+if nargout == 0,
+    % Display mean data
+    datanames = MA.species;
+    SBplot(TT,NBAR,datanames);
+else
+    % return results in structure
+    output = [];
+    output.time = Ts;
+    output.speciesdata = Ns;
+    output.runs = runs;
+    output.timemean = TT;
+    output.speciesdatamean = NBAR;
+    output.species = MA.species;
+    varargout{1} = output;
+    datanames = MA.species;
+end
+return
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/simulation/auxiliary/stochSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/simulation/auxiliary/stochSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..9784f86eaf7f4a2a22204baf6069398a6f2d7c5f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tasks/simulation/auxiliary/stochSB.m
@@ -0,0 +1,129 @@
+function [Ts,Ns,TT,NBAR] = stochSB(n0,c,d,l,tf,runs,Nsample,shownr)
+% stochSB: performs stochastic simulation of biochemical networks
+%   elementary reactions, using the Gillespie algorithm. The input and 
+%   output arguments have the following meaning:
+%   
+%   n0: Column Vector of initial populations of all the species involved 
+%   c: Row vector of stochastic rate constants of all elementary reactions
+%   d: Stoichiometry matrix with rows correspoding to species and columns
+%      corresponding to reaction channels
+%   l: Stoichiometry matrix for reactants only such that L = -D.*(D < 0); 
+%   tf: Final time of simulation    
+%   runs: Number of simulation runs to perform
+%   Nsample: output frequency
+%
+%   Ts: Cell-array of vectors of time points of reaction events
+%   Ns: Cell-array of matrices of output concentrations with a row for 
+%       each time point.
+%   TT: Vector of the ensemble of time points over all runs
+%   NBAR: Matrix with mean simulation results
+%   
+%   [Ts,Ns] = stochSB(n0,c,d,l,tf,runs)
+%   [Ts,Ns,TT,NBAR] = stochSB(n0,c,d,l,tf,runs)
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% preliminary operations:
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+oneszk = ones(size(c));
+i1 = l==1;                              % reactions of type: A->B, A+B->AB
+i2 = l==2;                              % reactions of type: A+A->AA
+stop = tf - eps(tf);                    % simulation stop time
+nOut = nargout;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% stochastic part:
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+TT = [];
+NBAR = [];
+if runs < 2      
+    % single run
+    [Ts,Ns] = gillespie;                       
+    TT = Ts;
+    NBAR = Ns;
+else
+    % multiple runs
+    Ts = {};
+    Ns = {};
+    for i = 1:runs, 
+        if shownr ~= 0,
+            disp(sprintf('SBstochsim simulation run: #%d',i));
+            drawnow;
+        end
+        [Tsi,Nsi] = gillespie;                 
+        Ts{i} = Tsi;
+        Ns{i} = Nsi;
+        % calculate the mean value of the realizations
+        if i==1,
+            TT = Tsi; % use this time vector for interpolation
+            NBAR = zeros(length(n0),length(TT));
+        end
+        for k=1:length(n0),
+            NBAR(k,:) = NBAR(k,:) + interp1(Tsi,Nsi(k,:),TT,'nearest')/runs;
+        end
+    end 
+end
+% transpose the results
+TT = TT';
+NBAR = NBAR';
+if runs > 1,
+    for k=1:runs,
+        Ts{k} = Ts{k}';
+        Ns{k} = Ns{k}';
+    end
+else
+    Ts = {Ts'};
+    Ns = {Ns'};
+end
+% finished
+
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    %   gillespie algorithm (direct method):
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    function [tt,nn] = gillespie
+        t = 0;                                  % initial time
+        n = n0;                                 % initial population
+        % allocate a bit "to much" memory ... delete afterwards what is not needed
+        % (defined by trailing zeros in the time vector)
+        tt = zeros(1,2*length(TT));
+        nn = zeros(length(n0),2*length(TT));
+        k = 1;                                  % set counter
+        nsamplek = 0;                           % set sampling counter
+        while t <= stop,
+            nsamplek = nsamplek + 1;
+            if nsamplek == 1,
+                tt(k) = t;                      % record time (only Nsample-th)
+                nn(:,k) = n;                    % record population (only Nsample-th)
+                k = k + 1;                      % increment counter
+            end
+            if nsamplek >= Nsample,
+                nsamplek = 0;
+            end
+            m = n(:,oneszk);                % replicate n : size(m,2) = size(k)
+            b = double(~l);
+            b(i1) = m(i1);                  % reactions of type: A->B, A+B->AB
+            b(i2) = m(i2).*(m(i2)-1)/2;     % reactions of type: A+A->AA
+            a = c.*prod(b);                 % propensity
+            astr = sum(a);
+            if ~astr, break, end            % substrate utilised
+            tau = -1/astr*log(rand);        % time to next reaction
+            u = find(cumsum(a)>=astr*rand,1);% index of next reaction
+            n = n + d(:,u);                 % update population
+            t = t + tau;                    % update time
+        end
+        % add last result to nn and tt (only if t smaller than the max time)
+        if t < stop && tt(k-1)~=t,
+            nn(:,k) = n;
+            tt(k) = t;
+        end
+        % find trailing zero elements in tt and delete the corresponding
+        % elements from tt and nn
+        index = find(tt==0);
+        if length(index) > 1,
+            tt(index(2:end)) = [];
+            nn(:,index(2:end)) = [];
+        end
+        % add final time point (it is very certainly not present otherwise)
+        tt = [tt tf];
+        nn = [nn nn(:,end)];        
+    end
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/OutputSBML.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/OutputSBML.m
new file mode 100644
index 0000000000000000000000000000000000000000..08bc9cce2a970a63b89fd023a52922b28ed44752
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/OutputSBML.m
@@ -0,0 +1,55 @@
+% OutputSBML(model, filename(optional)) outputs an xml file
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+% NOTE: This version enables support for SBML L3 FBC package.
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+% The function OutputSBML is the converse of TranslateSBML: 
+% it writes an MATLAB_SBML structure to an XML file. It accepts two arguments:
+%
+%   * model: This argument must be a MATLAB_SBML structure representing the 
+%            model to be written out to a file. Note that the structure will 
+%            not be validated to check if it is fully correct SBML; OutputSBML 
+%            will only verify the basic integrity of the structure (i.e., to 
+%            make sure it has the form expected of a MATLAB_SBML structure), 
+%            but nothing more.
+%
+%   * filename: The name of the file where the SBML content should be written.
+%
+%      NOTE: This argument is optional where a graphical user interface is
+%            available, in which case a missing argument will open a browse window.
+%
+
+%  Filename    : OutputSBML.m
+%  Description : MATLAB help file for OutputSBML
+%  Author(s)   : SBML Development Group <sbml-team@caltech.edu>
+%
+%
+%<!---------------------------------------------------------------------------
+% This file is part of SBMLToolbox.  Please visit http://sbml.org for more
+% information about SBML, and the latest version of SBMLToolbox.
+%
+% Copyright (C) 2013-2014 jointly by the following organizations:
+%     1. California Institute of Technology, Pasadena, CA, USA
+%     2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
+%     3. University of Heidelberg, Heidelberg, Germany
+%
+% Copyright (C) 2009-2013 jointly by the following organizations: 
+%     1. California Institute of Technology, Pasadena, CA, USA
+%     2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
+%  
+% Copyright (C) 2006-2008 by the California Institute of Technology,
+%     Pasadena, CA, USA 
+%  
+% Copyright (C) 2002-2005 jointly by the following organizations: 
+%     1. California Institute of Technology, Pasadena, CA, USA
+%     2. Japan Science and Technology Agency, Japan
+% 
+% This library is free software; you can redistribute it and/or modify it
+% under the terms of the GNU Lesser General Public License as published by
+% the Free Software Foundation.  A copy of the license agreement is provided
+% in the file named "LICENSE.txt" included with this software distribution.
+% and also available online as http://sbml.org/software/sbmltoolbox/license.html
+%----------------------------------------------------------------------- -->
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/README.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/README.txt
new file mode 100644
index 0000000000000000000000000000000000000000..1f557c94f08dbaadf7953318b1eb2b6f04ed840e
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/README.txt
@@ -0,0 +1,5 @@
+This is the compiled version of the SBML Toolbox and libSBML that is necessary to handle SBML import and export by the 
+Systems Biology Toolbox 2 for MATLAB. WINDOWS ONLY with MATLAB 32bit.
+
+All unnecessary files have been deleted in order to reduce the size.
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/TranslateSBML.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/TranslateSBML.m
new file mode 100644
index 0000000000000000000000000000000000000000..87f7759810b80d9e360cd81392ab685fd4c63935
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/TranslateSBML.m
@@ -0,0 +1,77 @@
+% TranslateSBML('filename' (optional), validateFlag (optional), verboseFlag (optional))
+% reads an SBML document and converts it to a MATLAB_SBML structure.
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+% NOTE: This version enables support for SBML L3 FBC package.
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+% It accepts three optional arguments:
+%
+%   * filename: This is the name of the file to be imported. 
+%               If the file is not in the current directory, then the 
+%               argument must be a full pathname (either absolute or 
+%               relative to the current working directory). 
+%
+%        NOTE: In Octave the filename is a required argument.
+%
+%   * validateFlag: This flag tells libSBML whether to perform full 
+%                   validation of the SBML file being read. The default 
+%                   value is 0, which signifies not to perform validation. 
+%                   (Note libSBML will still check for and report basic 
+%                   XML parsing errors regardless of the value of this flag.)
+%
+%   * verboseFlag: A value of 1 (the default) indicates that TranslateSBML 
+%                  should perform the validation process interactively, 
+%                  displaying errors and prompting the user for feedback 
+%                  if the model is invalid. A value of 0 will suppress user 
+%                  interaction, and is useful when calling TranslateSBML 
+%                  from within another function/script.
+%
+
+
+% Filename    : TranslateSBML.m
+% Description : MATLAB help file for TranslateSBML
+% Author(s)   : SBML Team <sbml-team@caltech.edu>
+% Organization: University of Hertfordshire STRC
+% Created     : 2003-09-15
+%
+% This file is part of libSBML.  Please visit http://sbml.org for more
+% information about SBML, and the latest version of libSBML.
+%
+% Copyright (C) 2013-2014 jointly by the following organizations:
+%     1. California Institute of Technology, Pasadena, CA, USA
+%     2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
+%     3. University of Heidelberg, Heidelberg, Germany
+%
+% Copyright (C) 2009-2013 jointly by the following organizations: 
+%     1. California Institute of Technology, Pasadena, CA, USA
+%     2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
+%  
+% Copyright (C) 2006-2008 by the California Institute of Technology,
+%     Pasadena, CA, USA 
+%  
+% Copyright (C) 2002-2005 jointly by the following organizations: 
+%     1. California Institute of Technology, Pasadena, CA, USA
+%     2. Japan Science and Technology Agency, Japan
+% 
+% This library is free software; you can redistribute it and/or modify it
+% under the terms of the GNU Lesser General Public License as published by
+% the Free Software Foundation.  A copy of the license agreement is provided
+% in the file named "LICENSE.txt" included with this software distribution
+% and also available online as http://sbml.org/software/libsbml/license.html
+%
+% The original code contained here was initially developed by:
+%
+%      Sarah Keating
+%      Science and Technology Research Centre
+%      University of Hertfordshire
+%      Hatfield, AL10 9AB
+%      United Kingdom
+%
+%      http://www.sbml.org
+%      mailto:sbml-team@caltech.edu
+%
+% Contributor(s):
+%
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/auxiliary/CheckAndConvert.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/auxiliary/CheckAndConvert.m
new file mode 100644
index 0000000000000000000000000000000000000000..ee87730fae16d5221e66923c5c42d817019cd592
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/auxiliary/CheckAndConvert.m
@@ -0,0 +1,471 @@
+function Formula = CheckAndConvert(Input)
+% converts from MathML in-fix to MATLAB functions
+
+% Filename    : CheckAndConvert.m
+% Description : converts from MathML in-fix to MATLAB functions
+% Author(s)   : SBML Team <sbml-team@caltech.edu>
+% Organization: University of Hertfordshire STRC
+% Created     : 2004-12-13
+%
+% This file is part of libSBML.  Please visit http://sbml.org for more
+% information about SBML, and the latest version of libSBML.
+%
+% Copyright (C) 2013-2014 jointly by the following organizations:
+%     1. California Institute of Technology, Pasadena, CA, USA
+%     2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
+%     3. University of Heidelberg, Heidelberg, Germany
+%
+% Copyright (C) 2009-2013 jointly by the following organizations: 
+%     1. California Institute of Technology, Pasadena, CA, USA
+%     2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
+%  
+% Copyright (C) 2006-2008 by the California Institute of Technology,
+%     Pasadena, CA, USA 
+%  
+% Copyright (C) 2002-2005 jointly by the following organizations: 
+%     1. California Institute of Technology, Pasadena, CA, USA
+%     2. Japan Science and Technology Agency, Japan
+% 
+% This library is free software; you can redistribute it and/or modify it
+% under the terms of the GNU Lesser General Public License as published by
+% the Free Software Foundation.  A copy of the license agreement is provided
+% in the file named "LICENSE.txt" included with this software distribution
+% and also available online as http://sbml.org/software/libsbml/license.html
+%
+% The original code contained here was initially developed by:
+%
+%      Sarah Keating
+%      Science and Technology Research Centre
+%      University of Hertfordshire
+%      Hatfield, AL10 9AB
+%      United Kingdom
+%
+%      http://www.sbml.org
+%      mailto:sbml-team@caltech.edu
+%
+% Contributor(s):
+
+Formula = strrep(Input, 'arccosh', 'acosh');
+
+Formula = strrep(Formula, 'arccot', 'acot');
+
+Formula = strrep(Formula, 'arccoth', 'acoth');
+
+Formula = strrep(Formula, 'arccsc', 'acsc');
+
+Formula = strrep(Formula, 'arccsch', 'acsch');
+
+Formula = strrep(Formula, 'arcsec', 'asec');
+
+Formula = strrep(Formula, 'arcsech', 'asech');
+
+Formula = strrep(Formula, 'arcsinh', 'asinh');
+
+Formula = strrep(Formula, 'arctanh', 'atanh');
+
+Formula = strrep(Formula, 'exponentiale', 'exp(1)');
+
+Formula = strrep(Formula, 'geq', 'ge');
+
+Formula = strrep(Formula, 'leq', 'le');
+
+Formula = strrep(Formula, 'neq', 'ne');
+
+Formula = strrep(Formula, 'pow', 'power');
+
+% any logical expressions can only have two arguments
+Formula = SortLogicals(Formula);
+
+% log(2,x) must become log2(x)
+Formula = strrep(Formula, 'log(2,', 'log2(');
+
+
+% root(n,x) must become nthroot(x,n)
+Index = strfind(Formula, 'root(');
+
+for i = 1:length(Index)
+
+    % create a subformula root(n,x)
+    SubFormula = '';
+    j = 1;
+    nFunctions=0;   %number of functions in expression
+    closedFunctions=0; %number of closed functions
+    while(nFunctions==0 || nFunctions~=closedFunctions)
+        SubFormula(j) = Formula(Index(i)+j-1);
+        if(strcmp(SubFormula(j),')'))
+            closedFunctions=closedFunctions+1;
+        end;
+        if(strcmp(SubFormula(j),'('))
+            nFunctions=nFunctions+1;
+        end;  
+        j = j+1;
+    end;
+    
+    j = 6;
+     n = '';
+    while(~strcmp(SubFormula(j), ','))
+        n = strcat(n, SubFormula(j));
+        j = j+1;
+    end;
+    
+    j = j+1;
+    x = SubFormula(j:length(SubFormula)-1);
+
+    ReplaceFormula = strcat('nthroot(', x, ',', n, ')');
+
+    Formula = strrep(Formula, SubFormula, ReplaceFormula);
+    Index = strfind(Formula, 'root(');
+
+
+end;
+
+% log(n,x) must become (log(x)/log(n))
+% but log(x) must be left alone
+
+LogTypes = IsItLogBase(Formula);
+Index = strfind(Formula, 'log(');
+
+for i = 1:length(Index)
+
+    if (LogTypes(i) == 1)
+    % create a subformula log(n,x)
+    SubFormula = '';
+    j = 1;
+    while(~strcmp(Formula(Index(i)+j-1), ')'))
+        SubFormula(j) = Formula(Index(i)+j-1);
+        j = j+1;
+    end;
+    SubFormula = strcat(SubFormula, ')');
+    
+    j = 5;
+     n = '';
+    while(~strcmp(SubFormula(j), ','))
+        n = strcat(n, SubFormula(j));
+        j = j+1;
+    end;
+    
+    j = j+1;
+    x = '';
+    while(~strcmp(SubFormula(j), ')'))
+        x = strcat(x, SubFormula(j));
+        j = j+1;
+    end;
+    
+    ReplaceFormula = sprintf('(log(%s)/log(%s))', x, n);
+    
+    Formula = strrep(Formula, SubFormula, ReplaceFormula);
+    Index = Index + 7;
+    end;
+
+end;
+
+
+function y = IsItLogBase(Formula)
+
+% returns an array of 0/1 indicating whether each occurence of log is
+% a log(n,x) or a log(x)
+% e.g. Formula = 'log(2,3) + log(6)'
+%      IsItLogBase returns y = [1,0]
+
+
+y = 0;
+
+% find log
+
+LogIndex = strfind(Formula, 'log(');
+
+if (isempty(LogIndex))
+    return;
+else
+    OpenBracket = strfind(Formula, '(');
+    Comma = strfind(Formula, ',');
+    CloseBracket = strfind(Formula, ')');
+
+    for i = 1:length(LogIndex)
+        if (isempty(Comma))
+            % no commas so no logbase formulas
+            y(i) = 0;
+        else
+
+            % find the opening bracket
+            Open = find(ismember(OpenBracket, LogIndex(i)+3) == 1);
+
+            % find closing bracket
+            Close = find(CloseBracket > LogIndex(i)+3, 1);
+
+            % is there a comma between
+            Greater = find(Comma > OpenBracket(Open));
+            Less = find(Comma < CloseBracket(Close));
+
+            if (isempty(Greater) || isempty(Less))
+                y(i) = 0;
+            else
+                Equal = find(Greater == Less);
+                if (isempty(Equal))
+                    y(i) = 0;
+                else
+                    y(i) = 1;
+                end;
+            end;
+
+        end;
+    end;
+end;
+
+function Formula = CorrectFormula(OriginalFormula, LogicalExpression)
+% CorrectFormula takes an OriginalFormula (as a char array)
+%                 and  a Logical Expression (as a char array with following '(')
+% and returns the formula written so that the logical expression only takes 2 arguments
+% 
+% *************************************************************************************
+% 
+% EXAMPLE:    y = CorrectFormula('and(A,B,C)', 'and(')
+% 
+%             y = 'and(and(A,B), C)'
+%             
+
+% find all opening brackets, closing brackets and commas contained
+% within the original formula
+OpeningBracketIndex = find((ismember(OriginalFormula, '(')) == 1);
+
+ClosingBracketIndex = find((ismember(OriginalFormula, ')')) == 1);
+
+CommaIndex = find((ismember(OriginalFormula, ',')) == 1);
+
+% check that tha number of brackets matches 
+if (length(OpeningBracketIndex) ~= length(ClosingBracketIndex))
+    error('Bracket mismatch');
+end;
+
+% find the commas that are between the arguments of the logical expression
+% not those that may be part of the argument
+% in the OpeningBracketIndex the first element refers to the opening
+% bracket of the expression and the last element of ClosingBracketIndex
+% refers to the the closing bracket of the expression
+% commas between other pairs of brackets do not need to be considered
+% e.g.  'and(gt(d,e),lt(2,e),gt(f,d))'
+%                   |       |       
+%                  relevant commas
+
+for i = 1:length(CommaIndex)
+    for j = 2:length(OpeningBracketIndex)
+        if ((CommaIndex(i) > OpeningBracketIndex(j)) && (CommaIndex(i) < ClosingBracketIndex(j-1)))
+            CommaIndex(i) = 0;
+        end;
+    end;
+end;
+
+NonZeros = find(CommaIndex ~= 0);
+
+% if there is only one relevant comma
+% implies only two arguments
+% MATLAB can deal with the OriginalFormula
+
+if (length(NonZeros) == 1)
+     Formula = OriginalFormula;
+     return;
+end;
+
+% get elements that represent the arguments of the logical expression
+% as an array of character arrays
+% e.g. first element is between opening barcket and first relevant comma
+%      next elements are between relevant commas
+%      last element is between last relevant comma and closing bracket
+
+j = OpeningBracketIndex(1);
+ElementNumber = 1;
+
+for i = 1:length(NonZeros)
+    element = '';
+    j = j+1;
+    while (j <= CommaIndex(NonZeros(i)) - 1)
+        element = strcat(element, OriginalFormula(j));
+        j = j + 1;
+    end;
+
+    Elements{ElementNumber} = element;
+    ElementNumber = ElementNumber + 1;
+
+end;
+
+
+element = '';
+j = j+1;
+while (j < ClosingBracketIndex(length(ClosingBracketIndex)) - 1)
+    element = strcat(element, OriginalFormula(j));
+    j = j + 1;
+end;
+
+Elements{ElementNumber} = element;
+
+% iteratively replace the first two arguments with the logical expression applied to
+% the first two arguments
+% e.g. OriginalFormula = 'and(a,b,c,d)'
+% becomes                'and(and(a,b),c,d)'
+% which becomes          'and(and(and(a,b),c),d)'
+Formula = OriginalFormula;
+
+if (length(Elements) > 2)
+    for i = 2:length(Elements)-1
+        Find = strcat(Elements{i-1}, ',', Elements{i});
+        Replace = strcat(LogicalExpression, Find, ')');
+
+        Formula = strrep(Formula, Find, Replace);
+        Elements{i} = Replace;
+    end;
+end;
+
+
+function Arguments = CheckLogical(Formula, LogicalExpression)
+% CheckLogical takes a Formula (as a character array) 
+%               and  a LogicalExpression (as a char array)
+% and returns an array of character strings 
+% representing the application of the logical expression within the formula
+% 
+% NOTE the logical expression is followed by an '(' to prevent confusion 
+% with other character strings within the formula 
+% 
+% ******************************************************************
+%  EXAMPLE:       y = CheckLogical('piecewise(and(A,B,C), 0.2, 1)' , 'and(')
+%  
+%                 y = 'and(A,B,C)'
+%
+%  EXAMPLE:       y = CheckLogical('or(and(A,B), and(A,B,C))', 'and(')
+%
+%                 y = 'and(A,B)'    'and(A,B,C)'
+
+% find the starting indices of all occurences of the logical expression
+Start = strfind(Formula, LogicalExpression);
+
+% if not found; no arguments - return
+if (isempty(Start))
+    Arguments = {};
+    return;
+end;
+
+
+for j = 1:length(Start) % each occurence of the logical expression
+
+    Stop = 0;
+    flag = 0;
+    i = Start(j);
+    output = '';
+
+    for i = Start(j):Start(j)+length(LogicalExpression)
+        output = strcat(output, Formula(i));
+    end;
+    i = i + 1;
+
+    while ((Stop == 0) && (i <= length(Formula)))
+        c = Formula(i);
+
+        if (strcmp(c, '('))
+            flag = flag + 1;
+            output = strcat(output, c);
+        elseif (strcmp(c, ')'))
+            if (flag > 0)
+                output = strcat(output, c);
+                flag = flag - 1;
+            else
+                output = strcat(output, c);
+                Stop = 1;
+            end;
+
+        else
+            output = strcat(output, c);
+        end;
+
+        i = i + 1;
+
+    end;
+
+
+    Arguments{j} = output;
+
+end;
+
+function y = SortLogicals(Formula)
+% SortLogicals takes a formula as a char array
+% and returns the formula with and logical expressions applied to only two arguments
+
+Formula = LoseWhiteSpace(Formula);
+
+Find = CheckLogical(Formula, 'and(');
+
+for i = 1:length(Find)
+    Replace = CorrectFormula(Find{i}, 'and(');
+
+    Formula = strrep(Formula, Find{i}, Replace);
+
+end;
+
+Find = CheckLogical(Formula, 'xor(');
+
+for i = 1:length(Find)
+    Replace = CorrectFormula(Find{i}, 'xor(');
+
+    Formula = strrep(Formula, Find{i}, Replace);
+
+end;
+
+Find = CheckLogical(Formula, 'or(');
+
+for i = 1:length(Find)
+    Replace = CorrectFormula(Find{i}, 'or(');
+
+    Formula = strrep(Formula, Find{i}, Replace);
+
+end;
+y = Formula;
+
+%**********************************************************************
+% LoseWhiteSpace(charArray) takes an array of characters
+% and returns the array with any white space removed
+%
+%**********************************************************************
+
+function y = LoseWhiteSpace(charArray)
+% LoseWhiteSpace(charArray) takes an array of characters
+% and returns the array with any white space removed
+%
+%----------------------------------------------------------------
+% EXAMPLE:
+%           y = LoseWhiteSpace('     exa  mp le')
+%           y = 'example'
+%
+
+%------------------------------------------------------------
+% check input is an array of characters
+if (~ischar(charArray))
+    error('LoseWhiteSpace(input)\n%s', 'input must be an array of characters');
+end;
+
+%-------------------------------------------------------------
+% get the length of the array
+NoChars = length(charArray);
+
+%-------------------------------------------------------------
+% create an array that indicates whether the elements of charArray are
+% spaces
+% e.g. WSpace = isspace('  v b') = [1, 1, 0, 1, 0]
+% and determine how many
+
+WSpace = isspace(charArray);
+NoSpaces = sum(WSpace);
+
+%-----------------------------------------------------------
+% rewrite the array to leaving out any spaces
+% remove any numbers from the array of symbols
+if (NoSpaces > 0)
+    NewArrayCount = 1;
+    for i = 1:NoChars
+        if (~isspace(charArray(i)))
+            y(NewArrayCount) = charArray(i);
+            NewArrayCount = NewArrayCount + 1;
+        end;
+    end;    
+else
+    y = charArray;
+end;
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/auxiliary/Contents.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/auxiliary/Contents.m
new file mode 100644
index 0000000000000000000000000000000000000000..f31b08292f97f6ae9ff0af80b5fd9f6b133e49fa
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/auxiliary/Contents.m
@@ -0,0 +1,93 @@
+%
+% These are the functions to import and export an SBML model into a 
+% MATLAB_SBML structure and back to an SBML file.
+%
+% FUNCTIONS include:
+%
+% TranslateSBML(varargin)
+%
+% - translates a sbml file into a matlab structure
+%    NOTE: this executable must be built in most environments
+%    (see README.txt)
+%
+% OutputSBML(varargin)
+%
+% - translates a appropriate matlab structure back into sbml and writes
+%   out the file
+%    NOTE: this executable must be built in most environments
+%    (see README.txt)
+%
+% CheckAndConvert.m
+%
+% - a script used by TranslateSBML to change some mathematical function names
+%   to those used by MATLAB
+%
+% ConvertFormulaToMathML.m
+%
+% - a script used by OutputSBML to change some mathematical function names
+%   to those used by MathML
+%
+% isSBML_Model.m
+%
+% - a script used by OutputSBML to check that a structure is an appropriate
+%   MATLAB_SBML structure for conversion to SBML
+%
+% isoctave.m
+%
+% - a script to determine if octave or matlab is being used
+%
+% buildSBML 
+%
+% - builds the TranslateSBML/OutputSBML executables from source
+%
+% installSBML
+%
+% - installs the libSBML MATLAB interface
+%
+
+% Description : This is the binding to translate 
+%				 sbml models into a MATLAB structure 
+% Author(s)   : SBML Team <sbml-team@caltech.edu>
+% Organization: University of Hertfordshire STRC
+% Created     : 2003-09-15
+%
+% This file is part of libSBML.  Please visit http://sbml.org for more
+% information about SBML, and the latest version of libSBML.
+%
+% Copyright (C) 2013-2014 jointly by the following organizations:
+%     1. California Institute of Technology, Pasadena, CA, USA
+%     2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
+%     3. University of Heidelberg, Heidelberg, Germany
+%
+% Copyright (C) 2009-2013 jointly by the following organizations: 
+%     1. California Institute of Technology, Pasadena, CA, USA
+%     2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
+%  
+% Copyright (C) 2006-2008 by the California Institute of Technology,
+%     Pasadena, CA, USA 
+%  
+% Copyright (C) 2002-2005 jointly by the following organizations: 
+%     1. California Institute of Technology, Pasadena, CA, USA
+%     2. Japan Science and Technology Agency, Japan
+% 
+% This library is free software; you can redistribute it and/or modify it
+% under the terms of the GNU Lesser General Public License as published by
+% the Free Software Foundation.  A copy of the license agreement is provided
+% in the file named "LICENSE.txt" included with this software distribution
+% and also available online as http://sbml.org/software/libsbml/license.html
+%
+% The original code contained here was initially developed by:
+%
+%      Sarah Keating
+%      Science and Technology Research Centre
+%      University of Hertfordshire
+%      Hatfield, AL10 9AB
+%      United Kingdom
+%
+%      http://www.sbml.org
+%      mailto:sbml-team@caltech.edu
+%
+% Contributor(s):
+%
+%
+%
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/auxiliary/ConvertFormulaToMathML.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/auxiliary/ConvertFormulaToMathML.m
new file mode 100644
index 0000000000000000000000000000000000000000..7b9e59502222ed67177ed15c7f0e9b10fab44f52
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/auxiliary/ConvertFormulaToMathML.m
@@ -0,0 +1,344 @@
+function Formula = ConvertFormulaToMathML(Input)
+% converts from MATLAB to MathML in-fix functions
+
+% Filename    : ConvertFormulaToMathML.m
+% 
+% This file is part of libSBML.  Please visit http://sbml.org for more
+% information about SBML, and the latest version of libSBML.
+%
+% Copyright (C) 2013-2014 jointly by the following organizations:
+%     1. California Institute of Technology, Pasadena, CA, USA
+%     2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
+%     3. University of Heidelberg, Heidelberg, Germany
+%
+% Copyright (C) 2009-2013 jointly by the following organizations: 
+%     1. California Institute of Technology, Pasadena, CA, USA
+%     2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
+%  
+% Copyright (C) 2006-2008 by the California Institute of Technology,
+%     Pasadena, CA, USA 
+%  
+% Copyright (C) 2002-2005 jointly by the following organizations: 
+%     1. California Institute of Technology, Pasadena, CA, USA
+%     2. Japan Science and Technology Agency, Japan
+% 
+% This library is free software; you can redistribute it and/or modify it
+% under the terms of the GNU Lesser General Public License as published by
+% the Free Software Foundation.  A copy of the license agreement is provided
+% in the file named "LICENSE.txt" included with this software distribution
+% and also available online as http://sbml.org/software/libsbml/license.html
+%
+% The original code contained here was initially developed by:
+%
+%      Sarah Keating
+%      Science and Technology Research Centre
+%      University of Hertfordshire
+%      Hatfield, AL10 9AB
+%      United Kingdom
+%
+%      http://www.sbml.org
+%      mailto:sbml-team@caltech.edu
+%
+% Contributor(s):
+
+Input = LoseWhiteSpace(Input);
+
+Formula = strrep(Input, 'acosh(', 'arccosh(');
+
+Formula = strrep(Formula, 'acot(', 'arccot(');
+
+Formula = strrep(Formula, 'acoth(', 'arccoth(');
+
+Formula = strrep(Formula, 'acsc(', 'arccsc(');
+
+Formula = strrep(Formula, 'acsch(', 'arccsch(');
+
+Formula = strrep(Formula, 'asec(', 'arcsec(');
+
+Formula = strrep(Formula, 'asech(', 'arcsech(');
+
+Formula = strrep(Formula, 'asinh(', 'arcsinh(');
+
+Formula = strrep(Formula, 'atanh(', 'arctanh(');
+
+Formula = strrep(Formula, 'exp(1)', 'exponentiale');
+
+Formula = strrep(Formula, 'ge(', 'geq(');
+
+Formula = strrep(Formula, 'le(', 'leq(');
+
+Formula = strrep(Formula, 'ne(', 'neq(');
+
+Formula = strrep(Formula, 'power(', 'pow(');
+
+% log2(x) must become log(2, x)
+Formula = strrep(Formula, 'log2(', 'log(2, ');
+% 
+% 
+% nthroot(x,n) must become root(n,x)
+Index = strfind(Formula, 'nthroot(');
+
+for i = 1:length(Index)
+
+    % create a subformula nthroot(x,n)
+    SubFunction = '';
+    j = 1;
+    nFunctions=0;   %number of functions in expression
+    closedFunctions=0; %number of closed functions
+    while(nFunctions==0 || nFunctions~=closedFunctions)
+        SubFormula(j) = Formula(Index(i)+j-1);
+        if(strcmp(SubFormula(j),')'))
+            closedFunctions=closedFunctions+1;
+        end;
+        if(strcmp(SubFormula(j),'('))
+            nFunctions=nFunctions+1;
+        end;  
+        j = j+1;
+    end;
+    
+    j = 9;
+     n = '';
+    while(~strcmp(SubFormula(j), ','))
+        n = strcat(n, SubFormula(j));
+        j = j+1;
+    end;
+    
+    j = j+1;
+    x = SubFormula(j:length(SubFormula)-1);
+
+    if (exist('OCTAVE_VERSION'))
+      ReplaceFormula = myRegexprep(SubFormula, n, x, 'once');
+      ReplaceFormula = myRegexprep(ReplaceFormula,regexptranslate('escape',x),n,2);
+      ReplaceFormula = myRegexprep(ReplaceFormula, 'nthroot', 'root', 'once');
+   else
+      ReplaceFormula = regexprep(SubFormula, n, x, 'once');
+      ReplaceFormula = regexprep(ReplaceFormula,regexptranslate('escape',x),n,2);
+      ReplaceFormula = regexprep(ReplaceFormula, 'nthroot', 'root', 'once');
+    end;
+    
+    Formula = strrep(Formula, SubFormula, ReplaceFormula);
+    Index = strfind(Formula, 'nthroot(');
+
+
+end;
+
+% (log(x)/log(n)) must become log(n,x)
+% but log(x) must be left alone
+Formula = convertLog(Formula);
+
+% 
+function y = convertLog(Formula)
+y = Formula;
+LogTypes = IsItLogBase(Formula);
+num = sum(LogTypes);
+Index = strfind(Formula, '(log(');
+
+subIndex = 1;
+for i = 1:length(Index)
+
+    if (LogTypes(i) == 1)
+      % get x and n from (log(x)/log(n))
+      pairs = PairBrackets(Formula);
+      for j=1:length(pairs)
+        if (pairs(j,1) == Index(i))
+          break;
+        end;
+      end;
+      subFormula{subIndex} = Formula(Index(i):pairs(j,2));
+      ff = subFormula{subIndex};
+      subPairs = PairBrackets(ff);
+      x = ff(subPairs(2,1)+1:subPairs(2,2)-1);
+      n = ff(subPairs(3,1)+1:subPairs(3,2)-1);
+      newFormula{subIndex} = sprintf('log(%s,%s)', n, x);
+      subIndex = subIndex+1;
+    end;
+
+end;
+if (subIndex-1 > num)
+  error('Problem');
+end;
+for i=1:num
+  y = strrep(y, subFormula{i}, newFormula{i});
+end;
+function y = IsItLogBase(Formula)
+
+% returns an array of 0/1 indicating whether each occurence of log is
+% a (log(n)/log(x)) or a log(x)
+% e.g. Formula = '(log(2)/log(3)) + log(6)'
+%      IsItLogBase returns y = [1,0]
+
+
+y = 0;
+LogIndex = strfind(Formula, '(log(');
+
+if (isempty(LogIndex))
+    return;
+else
+    Divide = strfind(Formula, ')/log(');
+    pairs = PairBrackets(Formula);
+    
+    if (isempty(Divide))
+      return;
+    else
+      % check that the divide occurs between logs
+      for i=1:length(LogIndex)
+        match = 0;
+        for j=1:length(pairs)
+          if (pairs(j, 1) == LogIndex(i))
+            break;
+          end;
+        end;
+        for k = 1:length(Divide)
+          if (pairs(j+1,2) == Divide(k))
+            match = 1;
+            break;
+          end;
+        end;
+      
+        y(i) = match;       
+      end;
+    end;
+end;
+
+%**********************************************************************
+% LoseWhiteSpace(charArray) takes an array of characters
+% and returns the array with any white space removed
+%
+%**********************************************************************
+
+function y = LoseWhiteSpace(charArray)
+% LoseWhiteSpace(charArray) takes an array of characters
+% and returns the array with any white space removed
+%
+%----------------------------------------------------------------
+% EXAMPLE:
+%           y = LoseWhiteSpace('     exa  mp le')
+%           y = 'example'
+%
+
+%------------------------------------------------------------
+% check input is an array of characters
+if (~ischar(charArray))
+    error('LoseWhiteSpace(input)\n%s', 'input must be an array of characters');
+end;
+
+%-------------------------------------------------------------
+% get the length of the array
+NoChars = length(charArray);
+
+%-------------------------------------------------------------
+% create an array that indicates whether the elements of charArray are
+% spaces
+% e.g. WSpace = isspace('  v b') = [1, 1, 0, 1, 0]
+% and determine how many
+
+WSpace = isspace(charArray);
+NoSpaces = sum(WSpace);
+
+%-----------------------------------------------------------
+% rewrite the array to leaving out any spaces
+% remove any numbers from the array of symbols
+if (NoSpaces > 0)
+    NewArrayCount = 1;
+    for i = 1:NoChars
+        if (~isspace(charArray(i)))
+            y(NewArrayCount) = charArray(i);
+            NewArrayCount = NewArrayCount + 1;
+        end;
+    end;    
+else
+    y = charArray;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function pairs = PairBrackets(formula)
+% PairBrackets takes a string 
+%       and returns 
+%           an array of indices of each pair of brackets
+%               ordered from the opening bracket index
+%
+
+if (~ischar(formula))
+    error(sprintf('%s\n%s', 'PairBrackets(formula)', 'first argument must be a string'));
+end;
+
+OpeningBracketIndex = strfind(formula, '(');
+ClosingBracketIndex = strfind(formula, ')');
+
+% check that the number of brackets matches 
+if (length(OpeningBracketIndex) ~= length(ClosingBracketIndex))
+    error('Bracket mismatch');
+end;
+
+if (isempty(OpeningBracketIndex))
+    pairs = 0;
+    return;
+end;
+
+for i = 1:length(OpeningBracketIndex)
+    j = length(OpeningBracketIndex);
+    while(j > 0)
+        if (OpeningBracketIndex(j) < ClosingBracketIndex(i))
+            pairs(i,1) = OpeningBracketIndex(j);
+            pairs(i,2) = ClosingBracketIndex(i);
+            OpeningBracketIndex(j) = max(ClosingBracketIndex);
+            j = 0;
+        else
+            j = j - 1;
+        end;
+    end;
+end;
+
+% order the pairs so that the opening bracket index is in ascending order
+
+OriginalPairs = pairs;
+
+% function 'sort' changes in version 7.0.1
+
+v = version;
+v_num = str2num(v(1));
+
+if (v_num < 7)
+    TempPairs = sort(pairs, 1);
+else
+    TempPairs = sort(pairs, 1, 'ascend');
+end;
+
+for i = 1:length(OpeningBracketIndex)
+    pairs(i, 1) = TempPairs(i, 1);
+    j = find(OriginalPairs == pairs(i, 1));
+    pairs(i, 2) = OriginalPairs(j, 2);
+end;
+
+
+
+function string = myRegexprep(string, repre, repstr, number)
+
+  %% Parse input arguements
+
+  n = -1;
+  if isnumeric(number)
+    n = number;
+  elseif strcmpi(number, 'once')
+    n = 1;
+  else
+    error('Invalid argument to myRegexprep');
+  end;
+
+  [st, en] = regexp(string, repre);
+
+
+  if (n > 0)
+    if (length(st) >= n)
+      st = st(n);
+	  en = en(n);
+    else
+      error('Invalid number of matches in myRegexprep');
+	  st = [];
+    end;
+  end;
+
+  for i = length(st):-1:1
+    string = [string(1:st(i)-1) repstr string(en(i)+1:length(string))];
+  end;
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/auxiliary/buildSBML.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/auxiliary/buildSBML.m
new file mode 100644
index 0000000000000000000000000000000000000000..cbbac684cfea0410e6c825b49337a12f74888749
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/auxiliary/buildSBML.m
@@ -0,0 +1,940 @@
+function buildSBML(varargin)
+% Builds the MATLAB language interface for libSBML.
+%
+% This script is meant to be invoked from libSBML's MATLAB bindings
+% source directory.  LibSBML must already have been compiled and
+% installed on your system.  This script makes the following
+% assumptions:
+%
+% * Linux and Mac systems: the compiled libSBML library must be on the
+%   appropriate library search paths, and/or the appropriate environment
+%   variables must have been set so that programs such as MATLAB can
+%   load the library dynamically.
+%
+% * Windows systems: the libSBML binaries (.dll and .lib files) and its
+%   dependencies (such as the XML parser library being used) must be
+%   located together in the same directory.  This script also assumes
+%   that libSBML was configured to use the libxml2 XML parser library.
+%   (This assumption is under Windows only.)
+%
+% After this script is executed successfully, a second step is necessary
+% to install the results.  This second step is performed by the
+% "installSBML" script found in the same location as this script.
+%
+% (File $Revision: 13171 $ of $Date:: 2011-03-04 10:30:24 +0000#$
+
+% Filename    : buildSBML.m
+% Description : Build MATLAB binding.
+% Author(s)   : SBML Team <sbml-team@caltech.edu>
+% Organization: EMBL-EBI, Caltech
+% Created     : 2011-02-08
+%
+% This file is part of libSBML.  Please visit http://sbml.org for more
+% information about SBML, and the latest version of libSBML.
+%
+% Copyright (C) 2013-2014 jointly by the following organizations:
+%     1. California Institute of Technology, Pasadena, CA, USA
+%     2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
+%     3. University of Heidelberg, Heidelberg, Germany
+%
+% Copyright (C) 2009-2013 jointly by the following organizations:
+%     1. California Institute of Technology, Pasadena, CA, USA
+%     2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
+%
+% Copyright (C) 2006-2008 by the California Institute of Technology,
+%     Pasadena, CA, USA
+%
+% Copyright (C) 2002-2005 jointly by the following organizations:
+%     1. California Institute of Technology, Pasadena, CA, USA
+%     2. Japan Science and Technology Agency, Japan
+%
+% This library is free software; you can redistribute it and/or modify
+% it under the terms of the GNU Lesser General Public License as
+% published by the Free Software Foundation.  A copy of the license
+% agreement is provided in the file named "LICENSE.txt" included with
+% this software distribution and also available online as
+% http://sbml.org/software/libsbml/license.html
+
+
+% =========================================================================
+% Main loop.
+% =========================================================================
+
+
+  [matlab_octave, bit64]  = check_system();
+
+  disp(sprintf('\nConstructing the libSBML %s interface.\n', matlab_octave));
+
+  [location, writeAccess, in_installer] = check_location(matlab_octave);
+
+  if isWindows()
+    build_win(matlab_octave, location, writeAccess, bit64, in_installer);
+  elseif ismac() || isunix()
+
+    % here we allow input arguments of include and library directories
+    % but we only use these if we are in the source tree
+
+    if (nargin > 0 && strcmp(location, 'source'))
+
+      % we need two arguments
+      % one must be the full path to the include directory
+      % two must be the full path to the library directory
+
+      correctArguments = 0;
+      if (nargin == 2)
+        include_dir_supplied = varargin{1};
+        lib_dir_supplied = varargin{2};
+        if checkSuppliedArguments(include_dir_supplied, lib_dir_supplied)
+          correctArguments = 1;
+        end;
+      end;
+      if correctArguments == 0
+        message = sprintf('\n%s\n%s\n%s\n', ...
+          'If arguments are passed to the buildSBML script we expect 2 arguments:', ...
+          '1) the full path to the include directory', ...
+          '2) the full path to the directory containing the libSBML library');
+        error(message);
+      else
+        % arguments are fine - go ahead and build
+        build_unix(matlab_octave, location, writeAccess, bit64, ...
+                   include_dir_supplied, lib_dir_supplied);
+      end;
+    else
+      build_unix(matlab_octave, location, writeAccess, bit64);
+    end;
+  else
+    message = sprintf('\n%s\n%s\n', ...
+      'Unable to determine the type of operating system in use.', ...
+      'Please contact libsbml-team@caltech.edu to help resolve this problem.');
+      error(message);
+  end;
+
+  disp(sprintf('\n%s%s\n', 'Successfully finished. ', ...
+               'If appropriate, please run "installSBML" next.'));
+
+
+% =========================================================================
+% Support functions.
+% =========================================================================
+
+%
+%
+% Is this windows
+% Mac OS X 10.7 Lion returns true for a call to ispc()
+% since we were using that to distinguish between windows and macs we need
+% to catch this
+% ------------------------------------------------------------------------
+function y = isWindows()
+
+  y = 1;
+
+  if isunix()
+    y = 0;
+    return;
+  end;
+
+  if ismac()
+    y = 0;
+    return;
+  end;
+
+  if ~ispc()
+    message = sprintf('\n%s\n%s\n', ...
+      'Unable to determine the type of operating system in use.', ...
+      'Please contact libsbml-team@caltech.edu to help resolve this problem.');
+    error(message);
+  end;
+
+%
+% Assess our computing environment.
+% -------------------------------------------------------------------------
+function [matlab_octave, bit64] = check_system()
+  disp('* Doing preliminary checks of runtime environment ...');
+
+  if (strcmp(isoctave(), '0'))
+    matlab_octave = 'MATLAB';
+    disp('  - This appears to be MATLAB and not Octave.');
+  else
+    matlab_octave = 'Octave';
+    disp('  - This appears to be Octave and not MATLAB.');
+  end;
+
+  bit64 = 32;
+  if isWindows()
+    if strcmp(computer(), 'PCWIN64') == 1
+      bit64 = 64;
+      disp(sprintf('  - %s reports the OS is Windows 64-bit.', matlab_octave));
+    else
+      disp(sprintf('  - %s reports the OS is Windows 32-bit.', matlab_octave));
+    end;
+  elseif ismac()
+    if strcmp(computer(), 'MACI64') == 1
+      bit64 = 64;
+      disp(sprintf('  - %s reports the OS is 64-bit MacOS.', matlab_octave));
+    else
+      % Reading http://www.mathworks.com/help/techdoc/ref/computer.html
+      % it is still not clear to me what a non-64-bit MacOS will report.
+      % Let's not assume the only other alternative is 32-bit, since we
+      % actually don't care here.  Let's just say "macos".
+      %
+      disp(sprintf('  - %s reports the OS is MacOS.', matlab_octave));
+    end;
+  elseif isunix()
+    if strcmp(computer(), 'GLNXA64') == 1
+      bit64 = 64;
+      disp(sprintf('  - %s reports the OS is 64-bit Linux.', matlab_octave));
+    else
+      disp(sprintf('  - %s reports the OS is 32-bit Linux.', matlab_octave));
+    end;
+  end;
+
+
+%
+% Assess our location in the file system.
+% -------------------------------------------------------------------------
+% Possible values returned:
+%   LOCATION:
+%     'installed'  -> installation directory
+%     'source'    -> libsbml source tree
+%
+%  WRITEACCESS:
+%     1 -> we can write in this directory
+%     0 -> we can't write in this directory
+%
+function [location, writeAccess, in_installer] = check_location(matlab_octave)
+  disp('* Trying to establish our location ...');
+
+  % This is where things get iffy.  There are a lot of possibilities, and
+  % we have to resort to heuristics.
+  %
+  % Linux and Mac: we look for 2 possibilities
+  % - installation dir ends in "libsbml/bindings/matlab"
+  %   Detect it by looking for ../../VERSION.txt.
+  %   Assume we're in .../share/libsbml/bindings/matlab and that our
+  %   library is in   .../lib/
+  %
+  % - source dir ends in "libsbml/src/bindings/matlab"
+  %   Detect it by looking for ../../../VERSION.txt.
+  %   Assume our library is in ../../
+  %
+
+  [remain, first] = fileparts(pwd);
+  if strcmpi(matlab_octave, 'matlab')
+    if ~strcmp(first, 'matlab')
+      error_incorrect_dir('matlab');
+    else
+      disp('  - We are in the libSBML subdirectory for Matlab.');
+    end;
+  else
+    if ~strcmp(first, 'octave')
+      error_incorrect_dir('octave');
+    else
+      disp('  - We are in the libSBML subdirectory for Octave.');
+    end;
+  end;
+
+  in_installer = 0;
+  [above_bindings, bindings] = fileparts(remain);
+  if exist(fullfile(above_bindings, 'VERSION.txt'))
+    disp('  - We appear to be in the installation target directory.');
+    in_installer = 1;
+    if isWindows()
+      location = above_bindings;
+    else
+      location = 'installed';
+    end;
+  else
+    [libsbml_root, src] = fileparts(above_bindings);
+    if exist(fullfile(libsbml_root, 'VERSION.txt'))
+      disp('  - We appear to be in the libSBML source tree.');
+      if isWindows()
+        location = libsbml_root;
+      else
+        location = 'source';
+      end;
+    else
+      % We don't know where we are.
+      if strcmpi(matlab_octave, 'MATLAB')
+        error_incorrect_dir('matlab');
+      else
+        error_incorrect_dir('octave');
+      end;
+    end;
+  end;
+
+  % Test that it looks like we have the expected pieces in this directory.
+  % We don't want to assume particular paths, because we might be
+  % getting run from the libSBML source tree or the installed copy of
+  % the matlab bindings sources.  So, we test for just a couple of
+  % things: the tail of the name of the directory in which this file is
+  % located (should be either "matlab" or "octave") and the presence of
+  % another file, "OutputSBML.c", which became part of libsbml at the
+  % same time this new build scheme was introduced.
+
+  our_name   = sprintf('%s.m', mfilename);
+  other_name = 'OutputSBML.c';
+  if ~exist(fullfile(pwd, our_name), 'file') ...
+        || ~exist(fullfile(pwd, other_name), 'file')
+    error_incorrect_dir('matlab');
+  end;
+
+  % Check whether we have write access to this directory.
+
+  fid = fopen('temp.txt', 'w');
+  writeAccess = 1;
+  if fid == -1
+    disp('  - We do not have write access here -- will write elsewhere.');
+    writeAccess = 0;
+  else
+    disp('  - We have write access here!  That makes us happy.');
+    fclose(fid);
+    delete('temp.txt');
+  end;
+
+
+%
+% Find include and library dirs (Linux & Mac case).
+% -------------------------------------------------------------------------
+% Return values:
+%   INCLUDE -> the full path to the include directory
+%   LIB     -> the full path to the libsbml library directory
+%
+function [include, lib] = find_unix_dirs(location, bit64)
+  disp('* Locating libSBML library and include files ...');
+
+  % The 'location' argument guides us:
+  % 'installed'  -> installation directory
+  %    look for libsbml.so or libsbml.dylib in ../../../lib{64}/
+  % 'source'    -> libsbml source tree
+  %    look for libsbml.so or libsbml.dylib in ../../.libs/
+
+  if ismac()
+    libname = 'libsbml.dylib';
+  else
+    libname = 'libsbml.so';
+  end;
+
+  if strcmpi(location, 'source')
+    [parent, here] = fileparts(pwd);     % ..
+    [parent, here] = fileparts(parent);  % ..
+    lib = fullfile(parent, '.libs');
+    libfile = fullfile(lib, libname);
+    if exist(libfile)
+      disp(sprintf('  - Found %s', libfile));
+    else
+      lib = 'unfound';
+    end;
+
+    include = parent;
+    if exist(include)
+      disp(sprintf('  - Root of includes is %s', include));
+    else
+      error_incorrect_dir('matlab');
+    end;
+  else
+    % location is 'installed'
+    [parent, here] = fileparts(pwd);     % ..
+    [parent, here] = fileparts(parent);  % ..
+    [parent, here] = fileparts(parent);  % ..
+    lib = fullfile(parent, 'lib');
+    libfile = fullfile(lib, libname);
+    if exist(libfile)
+      disp(sprintf('  - Found %s', libfile));
+    else
+      if bit64 == 64
+        % Try one more common alternative.
+        lib = fullfile(parent, 'lib64');
+        libfile = fullfile(lib, libname);
+        if exist(libfile)
+          disp(sprintf('  - Found %s', libfile));
+        else
+          lib = 'unfound';
+        end;
+      end;
+    end;
+
+    % In the installed target directory, include will be something
+    % like /usr/local/include
+    %
+    include = fullfile(parent, 'include');
+    if exist(include)
+      disp(sprintf('  - Root of includes is %s', include));
+    else
+      error_incorrect_dir('matlab');
+    end;
+  end;
+
+
+%
+% we on occasion allow the user to supply arguments for the directories
+% Check include and library dirs (Linux & Mac case) supplied exist
+% -------------------------------------------------------------------------
+function y = checkSuppliedArguments(include_supplied, lib_supplied)
+  disp('* Checking for libSBML library and include files ...');
+
+  % assume we find them
+  y = 1;
+
+  % check the include directory supplied exists
+  if exist(include_supplied)
+    disp(sprintf('  - Root of includes found at %s', include_supplied));
+  else
+    disp(sprintf('  - Root of includes NOT found at %s', include_supplied));
+    y = 0;
+  end;
+
+  % check that the correct library is found
+  if ismac()
+    libname = 'libsbml.dylib';
+  else
+    libname = 'libsbml.so';
+  end;
+
+  libfile = fullfile(lib_supplied, libname);
+  if exist(libfile)
+    disp(sprintf('  - Found %s', libfile));
+  else
+    disp(sprintf('  - NOT found %s', libfile));
+    y = 0;
+  end;
+
+
+%
+% Drive the build process (Windows version).
+% -------------------------------------------------------------------------
+function build_win(matlab_octave, root, writeAccess, bit64, in_installer)
+
+  disp('Phase 2: tests for libraries and other dependencies ...');
+  [include_dir, lib] = find_win_dirs(root, bit64, in_installer);
+
+  % check that the libraries can all be found
+  found = 1;
+  for i = 1:length(lib)
+    if (exist(lib{i}) ~= 0)
+      disp(sprintf('%s found', lib{i}));
+    else
+      disp(sprintf('%s not found', lib{i}));
+      found = 0;
+    end;
+  end;
+
+  if (found == 0)
+    error (sprintf('Not all dependencies could be found\n%s%s', ...
+    'expected the dependencies to be in ', fileparts(lib{1})));
+  else
+    disp('  - All dependencies found.  Good.');
+  end;
+
+
+  % if we do not have write access need to find somewhere else to build
+  if (writeAccess == 0)% must be 0; 1 is for testing
+    % create a new dir in the users path
+    this_dir = pwd;
+    if (matlab_octave == 'MATLAB')
+      user_dir = userpath;
+      user_dir = user_dir(1:length(user_dir)-1);
+    else
+      % This is Octave.  Octave doesn't have 'userpath'.
+      user_dir = tempdir;
+    end;
+    disp(sprintf('  - Copying library files to %s ...', user_dir));
+    if (copyLibraries(this_dir, user_dir, lib) == 1)
+      disp('  - Copying of library files successful.');
+    else
+      error('Cannot copy library files on this system');
+    end;
+    disp(sprintf('  - Copying MATLAB binding files to %s ...', user_dir));
+    if (copyMatlabDir(this_dir, user_dir) == 1)
+      disp('- Copying of MATLAB binding files successful');
+    else
+      error('Cannot copy matlab binding files on this system');
+    end;
+  else
+    this_dir = pwd;
+    user_dir = pwd;
+    % copy the library files to here
+    disp(sprintf('  - Copying library files to %s ...', user_dir));
+    if (copyLibraries(this_dir, user_dir, lib) == 1)
+      disp('  - Copying of library files successful');
+    else
+      error('Cannot copy library files on this system');
+    end;
+  end;
+
+  % build the files
+  compile_mex(include_dir, lib{1}, matlab_octave);
+
+%
+% Find include and library dirs (windows case).
+% -------------------------------------------------------------------------
+% Return values:
+%   INCLUDE -> the full path to the include directory
+%   LIB     -> an array of the libsbml dependency libraries
+%
+function [include, lib] = find_win_dirs(root, bit64, in_installer)
+  disp('* Locating libSBML library and include files ...');
+
+  % in the src tree we expect all lib dlls to be in root/win/bin
+  %                 and the include dir to be root/src
+  % in the installer the lib will be in root/win32/lib
+  %                  the dll will be in root/win32/bin
+  %                 and the include dir to be root/win32/include
+  % and for 64 bits the win32 will be win64
+  if (in_installer == 0)
+    bin_dir = [root, filesep, 'win', filesep, 'bin'];
+    lib_dir = [root, filesep, 'win', filesep, 'bin'];
+    include = [root, filesep, 'src'];
+  else
+    if (bit64 == 32)
+      bin_dir = [root, filesep, 'win32', filesep, 'bin'];
+      lib_dir = [root, filesep, 'win32', filesep, 'lib'];
+      include = [root, filesep, 'win32', filesep, 'include'];
+    else
+      bin_dir = [root, filesep, 'win64', filesep, 'bin'];
+      lib_dir = [root, filesep, 'win64', filesep, 'lib'];
+      include = [root, filesep, 'win64', filesep, 'include'];
+    end;
+  end;
+
+  disp(sprintf('  - Checking for the existence of the %s directory ...\n', bin_dir));
+  % and are the libraries in this directory
+  if ((exist(bin_dir, 'dir') ~= 7) || (exist([bin_dir, filesep, 'libsbml.dll']) == 0))
+      disp(sprintf('%s directory could not be found\n\n%s\n%s %s', bin_dir, ...
+          'The build process assumes that the libsbml binaries', ...
+          'exist at', bin_dir));
+      message = sprintf('\n%s\n%s', ...
+          'if they are in another directory please enter the ', ...
+          'full path to reach the directory from this directory: ');
+      new_bin_dir = input(message, 's');
+
+      if (exist(new_bin_dir, 'dir') == 0)
+          error('libraries could not be found');
+      else
+        bin_dir = new_bin_dir;
+        if (in_installer == 0)
+          lib_dir = bin_dir;
+        end;
+      end;
+  end;
+
+  if (~strcmp(bin_dir, lib_dir))
+    disp(sprintf('  - Checking for the existence of the %s directory ...\n', lib_dir));
+    if (exist(lib_dir, 'dir') ~= 7)
+        disp(sprintf('%s directory could not be found\n\n%s\n%s %s', lib_dir, ...
+            'The build process assumes that the libsbml binaries', ...
+            'exist at', lib_dir));
+        message = sprintf('\n%s\n%s', ...
+            'if they are in another directory please enter the ', ...
+            'full path to reach the directory from this directory: ');
+        new_lib_dir = input(message, 's');
+
+        if (exist(new_lib_dir, 'dir') == 0)
+            error('libraries could not be found');
+        else
+          lib_dir = new_lib_dir;
+        end;
+    end;
+  end;
+
+
+% check that the include directory exists
+  disp(sprintf('  - Checking for the existence of the %s directory ...\n', include));
+  if (exist(include, 'dir') ~= 7)
+      disp(sprintf('%s directory could not be found\n\n%s\n%s %s', include, ...
+          'The build process assumes that the libsbml include files', ...
+          'exist at', include));
+      message = sprintf('\n%s\n%s', ...
+          'if they are in another directory please enter the ', ...
+          'full path to reach the directory from this directory: ');
+      new_inc_dir = input(message, 's');
+
+      if (exist(new_inc_dir, 'dir') == 0)
+          error('include files could not be found');
+      else
+        include = new_inc_dir;
+      end;
+  end;
+
+  % create the array of library files
+  if (bit64 == 32)
+    if (in_installer == 0)
+      lib{1} = [bin_dir, filesep, 'libsbml.lib'];
+      lib{2} = [bin_dir, filesep, 'libsbml.dll'];
+      lib{3} = [bin_dir, filesep, 'libxml2.lib'];
+      lib{4} = [bin_dir, filesep, 'libxml2.dll'];
+      lib{5} = [bin_dir, filesep, 'iconv.lib'];
+      lib{6} = [bin_dir, filesep, 'iconv.dll'];
+      lib{7} = [bin_dir, filesep, 'bzip2.lib'];
+      lib{8} = [bin_dir, filesep, 'bzip2.dll'];
+      lib{9} = [bin_dir, filesep, 'zdll.lib'];
+      lib{10} = [bin_dir, filesep, 'zlib1.dll'];
+    else
+      lib{1} = [lib_dir, filesep, 'libsbml.lib'];
+      lib{2} = [bin_dir, filesep, 'libsbml.dll'];
+      lib{3} = [lib_dir, filesep, 'libxml2.lib'];
+      lib{4} = [bin_dir, filesep, 'libxml2.dll'];
+      lib{5} = [lib_dir, filesep, 'iconv.lib'];
+      lib{6} = [bin_dir, filesep, 'iconv.dll'];
+      lib{7} = [lib_dir, filesep, 'bzip2.lib'];
+      lib{8} = [bin_dir, filesep, 'bzip2.dll'];
+      lib{9} = [lib_dir, filesep, 'zdll.lib'];
+      lib{10} = [bin_dir, filesep, 'zlib1.dll'];
+    end;
+  else
+    if (in_installer == 0)
+      lib{1} = [bin_dir, filesep, 'libsbml.lib'];
+      lib{2} = [bin_dir, filesep, 'libsbml.dll'];
+      lib{3} = [bin_dir, filesep, 'libxml2.lib'];
+      lib{4} = [bin_dir, filesep, 'libxml2.dll'];
+      lib{5} = [bin_dir, filesep, 'libiconv.lib'];
+      lib{6} = [bin_dir, filesep, 'libiconv.dll'];
+      lib{7} = [bin_dir, filesep, 'bzip2.lib'];
+      lib{8} = [bin_dir, filesep, 'libbz2.dll'];
+      lib{9} = [bin_dir, filesep, 'zdll.lib'];
+      lib{10} = [bin_dir, filesep, 'zlib1.dll'];
+    else
+      lib{1} = [lib_dir, filesep, 'libsbml.lib'];
+      lib{2} = [bin_dir, filesep, 'libsbml.dll'];
+      lib{3} = [lib_dir, filesep, 'libxml2.lib'];
+      lib{4} = [bin_dir, filesep, 'libxml2.dll'];
+      lib{5} = [lib_dir, filesep, 'libiconv.lib'];
+      lib{6} = [bin_dir, filesep, 'libiconv.dll'];
+      lib{7} = [lib_dir, filesep, 'bzip2.lib'];
+      lib{8} = [bin_dir, filesep, 'libbz2.dll'];
+      lib{9} = [lib_dir, filesep, 'zdll.lib'];
+      lib{10} = [bin_dir, filesep, 'zlib1.dll'];
+    end;
+  end;
+
+
+%
+% Drive the build process (Mac and Linux version).
+% -------------------------------------------------------------------------
+function build_unix(varargin)
+
+  matlab_octave = varargin{1};
+  location = varargin{2};
+  writeAccess = varargin{3};
+  bit64 = varargin{4};
+
+  if (nargin == 4)
+    [include, lib] = find_unix_dirs(location, bit64);
+  else
+    include = varargin{5};
+    lib = varargin{6};
+  end;
+
+  if writeAccess == 1
+    % We can write to the current directory.  Our job is easy-peasy.
+    %
+    compile_mex(include, lib, matlab_octave);
+  else
+    % We don't have write access to this directory.  Copy the files
+    % somewhere else, relocate to there, and then try building.
+    %
+    working_dir = find_working_dir(matlab_octave);
+    current_dir = pwd;
+    copy_matlab_dir(current_dir, working_dir);
+    cd(working_dir);
+    compile_mex(include, lib, matlab_octave);
+    cd(current_dir);
+  end;
+
+
+%
+% Run mex/mkoctfile.
+% -------------------------------------------------------------------------
+function compile_mex(include_dir, library_dir, matlab_octave)
+  disp(sprintf('* Creating mex files in %s', pwd));
+
+  % list the possible opts files to be tried
+  optsfiles = {'', './mexopts-osx109.sh', './mexopts-osx108.sh', './mexopts-lion.sh', './mexopts-xcode43.sh', './mexopts-xcode45.sh', './mexopts-R2009-R2010.sh', './mexopts-R2008.sh', './mexopts-R2007.sh'};
+
+  success = 0;
+  n = 1;
+
+  if strcmpi(matlab_octave, 'matlab')
+    while(~success && n < length(optsfiles))
+        try
+          if ~isempty(optsfiles{n})
+              disp(sprintf('* Trying to compile with mexopts file: %s', optsfiles{n}));
+          end;
+          success = do_compile_mex(include_dir, library_dir, matlab_octave, optsfiles{n});
+        catch err
+          disp(' ==> The last attempt to build the Matlab bindings failed. We will try again with a different mexopts file');
+        end;
+      n = n + 1;
+    end;
+  else
+    success = do_compile_mex(include_dir, library_dir, matlab_octave, optsfiles{n});
+  end;
+
+  if ~success
+    error('Build failed');
+  end;
+
+function success = do_compile_mex(include_dir, library_dir, matlab_octave, altoptions)
+
+   inc_arg    = ['-I', include_dir];
+   inc_arg2   = ['-I', library_dir];
+  lib_arg    = ['-L', library_dir];
+  added_args = [' '];
+
+  if ismac() || isunix()
+    added_args = ['-lsbml'];
+  end;
+
+  % The messy file handle stuff is because this seems to be the best way to
+  % be able to pass arguments to the feval function.
+
+  if strcmpi(matlab_octave, 'matlab')
+    % on windows the command needs to be different
+    if isWindows()
+      fhandle = @mex;
+      disp('  - Building TranslateSBML ...');
+      feval(fhandle, 'TranslateSBML.c', inc_arg, inc_arg2, library_dir, '-DWIN32');
+      disp('  - Building OutputSBML ...');
+      feval(fhandle, 'OutputSBML.c', inc_arg, inc_arg2, library_dir, '-DWIN32');
+    else
+      fhandle = @mex;
+      disp('  - Building TranslateSBML ...');
+      if ~isempty(altoptions)
+        feval(fhandle, 'TranslateSBML.c', '-f', altoptions, inc_arg, inc_arg2, lib_arg, added_args);
+      else
+        feval(fhandle, 'TranslateSBML.c', inc_arg, inc_arg2, lib_arg, added_args);
+      end;
+      disp('  - Building OutputSBML ...');
+      if ~isempty(altoptions)
+        feval(fhandle, 'OutputSBML.c', '-f', altoptions, inc_arg, inc_arg2, lib_arg, added_args);
+      else
+        feval(fhandle, 'OutputSBML.c', inc_arg, inc_arg2, lib_arg, added_args);
+      end;
+    end;
+  else
+    if isWindows()
+      fhandle = @mkoctfile;
+      disp('  - Building TranslateSBML ...');
+      feval(fhandle, '--mex', 'TranslateSBML.c', '-DUSE_OCTAVE', inc_arg, inc_arg2, ...
+            '-lbz2', '-lz', library_dir);
+      disp('  - Building OutputSBML ...');
+      feval(fhandle, '--mex', 'OutputSBML.c', '-DUSE_OCTAVE', inc_arg, inc_arg2, ...
+            '-lbz2', '-lz', library_dir);
+    else
+      fhandle = @mkoctfile;
+      disp('  - Building TranslateSBML ...');
+      feval(fhandle, '--mex', 'TranslateSBML.c', '-DUSE_OCTAVE', inc_arg, inc_arg2, ...
+            '-lbz2', '-lz', lib_arg, added_args);
+      disp('  - Building OutputSBML ...');
+      feval(fhandle, '--mex', 'OutputSBML.c', '-DUSE_OCTAVE', inc_arg, inc_arg2, ...
+            '-lbz2', '-lz', lib_arg, added_args);
+    end;
+%   mkoctfile --mex TranslateSBML.c -DUSE_OCTAVE inc_arg inc_arg2 -lbz2 -lz lib_arg;
+  end;
+
+  transFile = strcat('TranslateSBML.', mexext());
+  outFile = strcat('OutputSBML.', mexext());
+  if ~exist(transFile) || ~exist(outFile)
+    success = 0;
+  else
+    success = 1;
+  end;
+
+
+
+%
+% Find a directory where we can copy our files (Linux & Mac version).
+%
+% -------------------------------------------------------------------------
+function working_dir = find_working_dir(matlab_octave)
+  if strcmpi(matlab_octave, 'matlab')
+    user_dir = userpath;
+    user_dir = user_dir(1:length(user_dir)-1);
+  else
+    % This is Octave.  Octave doesn't have 'userpath'.
+    user_dir = tempdir;
+  end;
+
+  working_dir = fullfile(user_dir, 'libsbml');
+
+  if ~exist(working_dir, 'dir')
+    [success, msg, msgid] = mkdir(working_dir);
+    if ~success
+      error(sprintf('\n%s\n%s\n', msg, 'Build failed.'));
+    end;
+  end;
+
+
+%
+% Copy the matlab binding directory, with tests.
+%
+% This also creates the necessary directories and subdirectories.
+% -------------------------------------------------------------------------
+function copy_matlab_dir(orig_dir, working_dir)
+  disp(sprintf('  - Copying files to %s', working_dir));
+
+  % Copy files from src/bindings/matlab.
+
+  [success, msg, msgid] = copyfile('TranslateSBML.c', working_dir);
+  if ~success
+    error(sprintf('\n%s\n%s\n', msg, 'Build failed.'));
+  end;
+
+  [success, msg, msgid] = copyfile('OutputSBML.c', working_dir);
+  if ~success
+    error(sprintf('\n%s\n%s\n', msg, 'Build failed.'));
+  end;
+
+  [success, msg, msgid] = copyfile('*.m', working_dir);
+  if ~success
+    error(sprintf('\n%s\n%s\n', msg, 'Build failed.'));
+  end;
+
+  [success, msg, msgid] = copyfile('*.xml', working_dir);
+  if ~success
+    error(sprintf('\n%s\n%s\n', msg, 'Build failed.'));
+  end;
+
+  % Copy files from src/bindings/matlab/test.
+
+  test_subdir = fullfile(working_dir, 'test');
+
+  if ~exist(test_subdir, 'dir')
+    [success, msg, msgid] = mkdir(test_subdir);
+    if ~success
+      error(sprintf('\n%s\n%s\n', msg, 'Build failed.'));
+    end;
+  end;
+
+  cd 'test';
+
+  [success, msg, msgid] = copyfile('*.m', test_subdir);
+  if ~success
+    error(sprintf('\n%s\n%s\n', msg, 'Build failed.'));
+  end;
+
+  % Copy files from src/bindings/matlab/test/test-data/.
+
+  test_data_subdir = fullfile(test_subdir, 'test-data');
+
+  if ~exist(test_data_subdir, 'dir')
+    [success, msg, msgid] = mkdir(test_data_subdir);
+    if ~success
+      error(sprintf('\n%s\n%s\n', msg, 'Build failed.'));
+    end;
+  end;
+
+  cd 'test-data';
+
+  [success, msg, msgid] = copyfile('*.xml', test_data_subdir);
+  if ~success
+    error(sprintf('\n%s\n%s\n', msg, 'Build failed.'));
+  end;
+
+
+%
+% Print error about being in the wrong location.
+% -------------------------------------------------------------------------
+function error_incorrect_dir(expected)
+  message = sprintf('\n%s\n%s%s%s\n%s\n%s%s%s\n%s\n', ...
+      'This script needs to be invoked from the libSBML subdirectory ', ...
+      'ending in "', expected, '". However, it is being invoked', ...
+      'from the directory', '   "', pwd, '"', ...
+      'instead.  Please change your working directory and re-run this script.');
+  error(message);
+
+
+
+%
+% Copy library files to the given directory on windows
+% -------------------------------------------------------------------------
+function copied = copyLibraries(orig_dir, target_dir, lib)
+
+  copied = 0;
+  cd (target_dir);
+
+  % if we moving to another location create a libsbml directory
+  % if we are staying in src/matlab/bindings copy here
+  if (~strcmp(orig_dir, target_dir))
+    if (exist('libsbml', 'dir') == 0)
+      mkdir('libsbml');
+    end;
+    cd libsbml;
+  end;
+  new_dir = pwd;
+  % copy the necessary files
+  for i = 1:length(lib)
+    copyfile(lib{i}, new_dir);
+  end;
+  cd(orig_dir);
+
+  copied = 1;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+  % creates a copy of the matlab binding directory with tests
+  function copied = copyMatlabDir(orig_dir, target_dir)
+
+    copied = 0;
+    cd (target_dir);
+    % create libsbml dir
+    if (exist('libsbml', 'dir') == 0)
+      mkdir('libsbml');
+    end;
+    cd libsbml;
+    new_dir = pwd;
+
+    %copy files to libsbml
+    cd(orig_dir);
+    copyfile('TranslateSBML.c', new_dir);
+    copyfile('OutputSBML.c', new_dir);
+    copyfile('*.m', new_dir);
+    copyfile('*.xml', new_dir);
+    cd(new_dir);
+%     delete ('buildLibSBML.m');
+
+    % create test dir
+    testdir = fullfile(pwd, 'test');
+    if (exist(testdir, 'dir') == 0)
+      mkdir('test');
+    end;
+    cd('test');
+    new_dir = pwd;
+
+    %copy test files
+    cd(orig_dir);
+    cd('test');
+    copyfile('*.m', new_dir);
+
+    % create test-data dir
+    cd(new_dir);
+    testdir = fullfile(pwd, 'test-data');
+    if (exist(testdir, 'dir') == 0)
+      mkdir('test-data');
+    end;
+    cd('test-data');
+    new_dir = pwd;
+
+    %copy test-data files
+    cd(orig_dir);
+    cd ('test');
+    cd ('test-data');
+    copyfile('*.xml', new_dir);
+
+    %navigate to new libsbml directory
+    cd(new_dir);
+    cd ..;
+    cd ..;
+
+    % put in some tests here
+    copied = 1;
+
+
+% =========================================================================
+% The end.
+%
+% Please leave the following for [X]Emacs users:
+% Local Variables:
+% matlab-indent-level: 2
+% fill-column: 72
+% End:
+% =========================================================================
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/auxiliary/installSBML.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/auxiliary/installSBML.m
new file mode 100644
index 0000000000000000000000000000000000000000..6d3a2355d14437285dd9010f4c8d7742fcc26690
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/auxiliary/installSBML.m
@@ -0,0 +1,430 @@
+function installSBML(varargin)
+% Installs the MATLAB language interface for libSBML.
+%
+% This script assumes that the libsbml matlab binding executables files already
+% exist; either because the user has built them using buildSBML (only
+% in the src release) or the binding is being installed from an installer.
+%
+% Currently prebuilt executables are only available in the windows installers
+% of libSBML.
+%
+% For Linux or Mac users this means that you need to build libsbml and then
+% run the buildSBML script.
+
+
+% Filename    : installSBML.m
+% Description : install matlab binding
+% Author(s)   : SBML Team <sbml-team@caltech.edu>
+% Organization: EMBL-EBI
+% 
+% This file is part of libSBML.  Please visit http://sbml.org for more
+% information about SBML, and the latest version of libSBML.
+%
+% Copyright (C) 2013-2014 jointly by the following organizations:
+%     1. California Institute of Technology, Pasadena, CA, USA
+%     2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
+%     3. University of Heidelberg, Heidelberg, Germany
+%
+% Copyright (C) 2009-2013 jointly by the following organizations: 
+%     1. California Institute of Technology, Pasadena, CA, USA
+%     2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
+%  
+% Copyright (C) 2006-2008 by the California Institute of Technology,
+%     Pasadena, CA, USA 
+%  
+% Copyright (C) 2002-2005 jointly by the following organizations: 
+%     1. California Institute of Technology, Pasadena, CA, USA
+%     2. Japan Science and Technology Agency, Japan
+% 
+% This library is free software; you can redistribute it and/or modify it
+% under the terms of the GNU Lesser General Public License as published by
+% the Free Software Foundation.  A copy of the license agreement is provided
+% in the file named "LICENSE.txt" included with this software distribution
+% and also available online as http://sbml.org/software/libsbml/license.html
+%
+
+% =========================================================================
+% Main loop.
+% =========================================================================
+
+% look at input arguments
+
+  [verbose, directory] = checkInputArguments(varargin);
+      
+  myDisp({'Installing the libSBML interface.'},  verbose);
+
+ [matlab_octave]  = check_system(verbose);
+ 
+ [functioning, located] = checkForExecutables(matlab_octave, directory, verbose);
+ 
+ if (functioning == 0)
+   if (located == 0)
+     % we didnt find executables where we first looked
+     % try again with a different directory
+     if (isWindows() == 0)
+       if (strcmp(directory, '/usr/local/lib') == 0)
+         directory = '/usr/local/lib';
+         functioning = checkForExecutables(matlab_octave, directory, verbose);
+       end;
+     else
+       if (strcmp(directory, pwd) == 0)
+         directory = pwd;
+         functioning = checkForExecutables(matlab_octave, directory, verbose);
+       end;
+     end;
+   else
+     % we found executables but they did not work
+     error('%s%s%s\n%s%s', ...
+       'Executables were located at ', directory, ' but failed to execute', ...
+       'Please contact the libSBML team libsbml-team@caltech.edu ', ...
+       'for further assistance');
+   end;
+ end;
+
+ if (functioning == 1)
+   myDisp({'Installation successful'}, verbose);
+ end;
+end
+  
+  
+  
+% =========================================================================
+% Helper functions
+% =========================================================================
+
+% check any input arguments
+%--------------------------------------------------------------------------
+function [verbose, directory] = checkInputArguments(input)
+
+  numArgs = length(input);
+  
+  if (numArgs > 2)
+    reportInputArgumentError('Too many arguments to installSBML');
+  end;
+  
+  if (numArgs == 0)
+    verbose = 1;
+    if (isWindows() == 1)
+      directory = pwd;
+    else
+      directory = '/usr/local/lib';
+    end;
+  elseif (numArgs == 1)
+    directory = input{1};
+    verbose = 1;
+  else
+    directory = input{1};
+    verbose = input{2};
+  end;
+ 
+  if (verbose ~= 0 && verbose ~= 1)
+    reportInputArgumentError('Incorrect value for verbose flag');
+  end;
+  
+  if (ischar(directory) ~= 1)
+    reportInputArgumentError('Directory value should be a string');
+  elseif(exist(directory, 'dir') ~= 7)
+    reportInputArgumentError('Directory value should be a directory');
+  end;
+
+end
+% display error message relating to input arguments
+%---------------------------------------------------
+function reportInputArgumentError(message)
+
+    error('%s\n%s\n\t%s%s\n\t%s%s\n\t\t%s', message, ...
+      'Arguments are optional but if present:', ...
+      'the first should be a string representing the directory containing ', ...
+      'the executables', 'the second should be a flag (0 or 1) indicating ', ...
+      'whether messages should be displayed ', ...
+      '0 - no messages; 1 - display messages');
+end
+      
+
+
+% display error messages iff verbose = 1
+%-----------------------------------------
+function myDisp(message, verbose)
+
+  outputStr = '';
+
+  if (verbose == 1)
+    for i=1:length(message)
+      outputStr = sprintf('%s\n%s', outputStr, message{i});
+    end;
+  end;
+ 
+  disp(outputStr);
+end
+
+%
+%
+% Is this windows
+% Mac OS X 10.7 Lion returns true for a call to ispc()
+% since we were using that to distinguish between windows and macs we need
+% to catch this
+% ------------------------------------------------------------------------
+function y = isWindows()
+
+  y = 1;
+  
+  if isunix()
+    y = 0;
+    return;
+  end;
+  
+  if ismac()
+    y = 0;
+    return;
+  end;
+  
+  if ~ispc()
+    error('\n%s\n%s\n', ...
+      'Unable to determine the type of operating system in use.', ...
+      'Please contact libsbml-team@caltech.edu to help resolve this problem.');
+  end;
+end   
+
+% 
+% Assess our computing environment.
+% -------------------------------------------------------------------------
+function [matlab_octave] = check_system(verbose)
+ message{1} = '* Doing preliminary checks of runtime environment ...';
+
+  if (strcmp(isoctave(), '0'))
+    matlab_octave = 'MATLAB';
+    message{2} = '  - This appears to be MATLAB and not Octave.';
+  else
+    matlab_octave = 'Octave';
+    message{2} = '  - This appears to be Octave and not MATLAB.';
+  end;
+  
+  myDisp(message, verbose);
+end
+
+%
+% check for executables and that they are right ones
+% -------------------------------------------------------------------------
+function [success, located] = checkForExecutables(matlab_octave, directory, verbose)  
+  message{1} = 'Checking for executables in ';
+  message{2} = sprintf('\t%s', directory);
+  
+  transFile = strcat('TranslateSBML.', mexext());
+  outFile = strcat('OutputSBML.', mexext());
+  
+  thisDirTFile = fullfile(pwd(), transFile);
+  thisDirOFile = fullfile(pwd(), outFile);
+
+  success = 0;
+  located = 0;
+  
+  if strcmpi(matlab_octave, 'matlab')
+    if (~(exist([directory, filesep, transFile], 'file') ~= 0 ...
+        && exist([directory, filesep, outFile], 'file') ~= 0))
+      located = 0;
+    else 
+      located = 1;
+    end;
+  else
+    % octave is much more picky about whether the files exist
+  	% it wants to find the libraries at the same time
+  	% exist throws an exception if it cannot find them
+    if (~(myExist(directory, transFile) ~= 0 ...
+        && myExist(directory, outFile) ~= 0))
+      located = 0;
+    else 
+      located = 1;
+    end;
+  end;
+
+  if (located == 1)
+    % we have found the executables where the user says but 
+    % need to check that there are not other files on the path
+    t = which(transFile);
+    o = which(outFile);
+      
+    % exclude the current dir
+    currentT = strcmp(t, thisDirTFile);
+    currentO = strcmp(t, thisDirOFile);
+    found = 0;
+    if (currentT == 1 && currentO == 1)
+      t_found = 0;
+      if (isempty(t) == 0 && strcmp(t, [directory, filesep, transFile]) == 0)
+        found = 1;
+        t_found = 1;
+      elseif (isempty(o) == 0 && strcmp(o, [directory, filesep, outFile]) == 0)
+        found = 1;
+      end;
+    end;
+    if (found == 1)  
+      if (t_found == 1)
+        pathDir = t;
+      else
+        pathDir = o;
+      end;
+      error('%s\n%s\n%s', 'Other libsbml executables found on the path at:', ... 
+        pathDir, ...
+      'Please uninstall these before attempting to install again');
+    end;
+  end;
+
+
+  if (located == 1)
+    message{3} = 'Executables found';
+  else
+    message{3} = 'Executables not found';
+  end;
+
+  
+  myDisp(message, verbose);
+  
+  if (located == 1)
+    % we have found the executables
+    % add the directory to the matlab path
+    added = addDir(directory, verbose);
+    
+    % if addDir returns 0 this may be that the user does not have
+    % permission to add to the path
+    if (added == 0)
+      error('%s%s%s%s\n%s%s', ...
+        'The directory containing the executables could not ', ...
+        'be added to the ', matlab_octave, ' path', ... 
+        'You may need to run in administrator mode or contact your ', ...
+        'network manager if running from a network');
+    elseif (added == 1)
+      % to test the actual files we need to be in the directory
+      % if we happen to be in the src tree where the .m helps files
+      % exist these will get picked up first by the function calls
+      % according to mathworks the only way to avoid this is to cd to the 
+      % right dir 
+      currentDir = pwd();
+      cd(directory);
+      success = doesItRun(matlab_octave, verbose, currentDir);
+      cd (currentDir);
+    end;
+    
+    % at this point if success = 0 it means there was an error running
+    % the files - take the directory out of the path
+    if (success == 0 && added == 1)
+      removeDir(directory, verbose);
+    end;
+  end;
+end
+
+% test the installation
+% -------------------------------------------------------------------------
+function success = doesItRun(matlab_octave, verbose, dirForTest)
+    
+  success = 1;
+  
+  message{1} = 'Attempting to execute functions';
+  myDisp(message, verbose);
+    
+  testFile = fullfile(dirForTest, 'test.xml');
+  
+  if strcmpi(matlab_octave, 'matlab')
+    try
+      M = TranslateSBML(testFile);
+      message{1} = 'TranslateSBML successful';
+    catch ME
+      success = 0;
+      message{1} = sprintf('%s\n%s', 'TranslateSBML failed', ME.message);
+    end;
+  else
+    try
+      M = TranslateSBML(testFile);
+      message{1} = 'TranslateSBML successful';
+    catch
+      success = 0;
+      message{1} = 'TranslateSBML failed';
+    end;
+  end;
+
+  if strcmpi(matlab_octave, 'matlab')
+    outFile = [tempdir, filesep, 'test-out.xml'];
+  else
+    if isWindows()
+      outFile = [tempdir, 'temp', filesep, 'test-out.xml'];
+    else
+      outFile = [tempdir, 'test-out.xml'];
+    end;
+  end;
+      
+  if (success == 1)
+    if strcmpi(matlab_octave, 'matlab')
+      try
+        if (verbose == 1)
+          OutputSBML(M, outFile);
+        else
+          OutputSBML(M, outFile, verbose, verbose);
+        end;
+        message{2} = 'OutputSBML successful';
+      catch ME
+        success = 0;
+        message{2} = sprintf('%s\n%s', 'OutputSBML failed', ME.message);
+      end;
+    else
+      try
+        if (verbose == 1)
+          OutputSBML(M, outFile);
+        else
+          OutputSBML(M, outFile, verbose, verbose);
+        end;
+        message{2} = 'OutputSBML successful';
+      catch
+        success = 0;
+        message{2} = 'OutputSBML failed';
+      end;
+    end;
+  end;
+  
+  myDisp(message, verbose);
+end
+ 
+% add directory to the matlab path
+% -------------------------------------------------------------------------
+function added = addDir(name, verbose)
+
+  added = 0;
+  addpath(name);
+  if (savepath ~= 0)
+    message{1} = sprintf('Adding %s to path ...\nFailed', name);
+  else
+    message{1} = sprintf('Adding %s to path ...\nSuccess', name);
+    added = 1;
+  end;
+  
+  myDisp(message, verbose);
+end
+  
+% remove directory to the matlab path
+% -------------------------------------------------------------------------
+function added = removeDir(name, verbose)
+
+  added = 0;
+  rmpath(name);
+  if (savepath ~= 0)
+    message{1} = sprintf('Removing %s from path ...\nFailed', name);
+  else
+    message{1} = sprintf('Removing %s from path ...\nSuccess', name);
+    added = 1;
+  end;
+  
+  myDisp(message, verbose);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function found = myExist(directory, filename)
+
+
+found = 0;
+dirnames = dir(directory);
+i = 1;
+while (found == 0 && i <= length(dirnames))
+  if (dirnames(i).isdir == 0)
+	  found = strcmp(dirnames(i).name, filename);
+	end;
+	i = i+1;
+end;
+  
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/auxiliary/isFbcEnabled.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/auxiliary/isFbcEnabled.m
new file mode 100644
index 0000000000000000000000000000000000000000..578f8a1efc86f5fcac6f20bec56fd6a173054631
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/auxiliary/isFbcEnabled.m
@@ -0,0 +1,76 @@
+function fbcEnabled = isFbcEnabled()
+% Checks whether the version of libSBML has been built with 
+% the FBC package extension enabled
+
+% Filename    : isFbcEnabled.m
+% Description : check fbc status
+% Author(s)   : SBML Team <sbml-team@caltech.edu>
+% Organization: EMBL-EBI, Caltech
+% Created     : 2011-02-08
+%
+% This file is part of libSBML.  Please visit http://sbml.org for more
+% information about SBML, and the latest version of libSBML.
+%
+% Copyright (C) 2013-2014 jointly by the following organizations:
+%     1. California Institute of Technology, Pasadena, CA, USA
+%     2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
+%     3. University of Heidelberg, Heidelberg, Germany
+%
+% Copyright (C) 2009-2011 jointly by the following organizations: 
+%     1. California Institute of Technology, Pasadena, CA, USA
+%     2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
+%  
+% Copyright (C) 2006-2008 by the California Institute of Technology,
+%     Pasadena, CA, USA 
+%  
+% Copyright (C) 2002-2005 jointly by the following organizations: 
+%     1. California Institute of Technology, Pasadena, CA, USA
+%     2. Japan Science and Technology Agency, Japan
+% 
+% This library is free software; you can redistribute it and/or modify
+% it under the terms of the GNU Lesser General Public License as
+% published by the Free Software Foundation.  A copy of the license
+% agreement is provided in the file named "LICENSE.txt" included with
+% this software distribution and also available online as
+% http://sbml.org/software/libsbml/license.html
+
+% assume not enabled
+fbcEnabled = 0;
+
+if (isoctave() == '0')
+  filename = fullfile(tempdir, 'fbc.xml');
+else
+  filename = fullfile(pwd, 'fbc.xml');
+end;
+writeTempFile(filename);
+
+try
+  [m, e] = TranslateSBML(filename, 1, 0);
+
+  if (length(e) == 0 && isfield(m, 'fbc_version') == 1 )
+    fbcEnabled = 1;
+  end;
+  
+  delete(filename);
+  
+catch
+  
+  delete(filename);
+  
+  return
+end;
+
+
+
+
+function writeTempFile(filename)
+
+fout = fopen(filename, 'w');
+
+fprintf(fout, '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n');
+fprintf(fout, '<sbml xmlns=\"http://www.sbml.org/sbml/level3/version1/core\" ');
+fprintf(fout, 'xmlns:fbc=\"http://www.sbml.org/sbml/level3/version1/fbc/version1\" ');
+fprintf(fout, 'level=\"3\" version=\"1\" fbc:required=\"false\">\n');
+fprintf(fout, '  <model/>\n</sbml>\n');
+
+fclose(fout);
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/auxiliary/isSBML_Model.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/auxiliary/isSBML_Model.m
new file mode 100644
index 0000000000000000000000000000000000000000..757342bec6e82d7b07f2df92170e9edc1c23c578
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/auxiliary/isSBML_Model.m
@@ -0,0 +1,3709 @@
+function [valid, message] = isSBML_Model(varargin)
+% [valid, message] = isSBML_Model(SBMLModel)
+%
+% Takes
+%
+% 1. SBMLModel, an SBML Model structure
+% 2. extensions_allowed (optional) =
+%   - 0, structures should contain ONLY required fields
+%   - 1, structures may contain additional fields (default)
+%
+% Returns
+%
+% 1. valid = 
+%   - 1, if the structure represents
+%        a MATLAB_SBML Model structure of the appropriate
+%        level and version
+%   - 0, otherwise
+% 2. a message explaining any failure
+%
+
+%<!---------------------------------------------------------------------------
+% This file is part of libSBML.  Please visit http://sbml.org for more
+% information about SBML, and the latest version of libSBML.
+%
+% Copyright (C) 2013-2014 jointly by the following organizations:
+%     1. California Institute of Technology, Pasadena, CA, USA
+%     2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
+%     3. University of Heidelberg, Heidelberg, Germany
+%
+% Copyright (C) 2009-2013 jointly by the following organizations: 
+%     1. California Institute of Technology, Pasadena, CA, USA
+%     2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
+%  
+% Copyright (C) 2006-2008 by the California Institute of Technology,
+%     Pasadena, CA, USA 
+%  
+% Copyright (C) 2002-2005 jointly by the following organizations: 
+%     1. California Institute of Technology, Pasadena, CA, USA
+%     2. Japan Science and Technology Agency, Japan
+% 
+% This library is free software; you can redistribute it and/or modify
+% it under the terms of the GNU Lesser General Public License as
+% published by the Free Software Foundation.  A copy of the license
+% agreement is provided in the file named "LICENSE.txt" included with
+% this software distribution and also available online as
+% http://sbml.org/software/libsbml/license.html
+%----------------------------------------------------------------------- -->
+
+
+%check the input arguments are appropriate
+if (nargin < 1)
+  error('isSBML_Model needs at least one argument');
+elseif (nargin == 1)
+  SBMLStructure = varargin{1};
+  extensions_allowed = 1;
+elseif (nargin == 2)
+  SBMLStructure = varargin{1};
+  extensions_allowed = varargin{2};
+else
+  error('too many arguments to isSBML_Model');
+end;
+     
+if (isfield(SBMLStructure, 'fbc_version') && isFbcEnabled() == 1)
+  if isfield(SBMLStructure, 'SBML_level') && isfield(SBMLStructure, 'SBML_version')
+    [valid, message] = isSBML_FBC_Model(SBMLStructure, SBMLStructure.SBML_level, ...
+      SBMLStructure.SBML_version, SBMLStructure.fbc_version, extensions_allowed);
+  else
+    [valid, message] = isValidSBML_Model(SBMLStructure, extensions_allowed, 0);
+  end;
+else
+  [valid, message] = isValidSBML_Model(SBMLStructure, extensions_allowed, 0);
+end;  
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [valid, message] = isValidSBML_Model(SBMLStructure, ...
+                                        extensions_allowed, in_fbc)
+
+
+%check the input arguments are appropriate
+
+if (length(SBMLStructure) > 1)
+  valid = 0;
+  message = 'cannot deal with arrays of structures';
+  return;
+end;
+
+if ~isempty(SBMLStructure)
+  if isfield(SBMLStructure, 'SBML_level')
+    level = SBMLStructure.SBML_level;
+  else
+    level = 3;
+  end;
+  if isfield(SBMLStructure, 'SBML_version')
+    version = SBMLStructure.SBML_version;
+  else
+    version = 1;
+  end;
+else
+  level = 3;
+  version = 1;
+end;
+
+isValidLevelVersionCombination(level, version);
+
+message = '';
+
+% check that argument is a structure
+valid = isstruct(SBMLStructure);
+
+% check the typecode
+typecode = 'SBML_MODEL';
+if (valid == 1 && ~isempty(SBMLStructure))
+  if isfield(SBMLStructure, 'typecode')
+    if (strcmp(typecode, SBMLStructure.typecode) ~= 1)
+      valid = 0;
+      message = 'typecode mismatch';
+      return;
+    end;
+  else
+    valid = 0;
+    message = 'missing typecode field';
+    return;
+  end;
+end;
+
+
+% check that structure contains all the necessary fields
+[SBMLfieldnames, numFields] = getFieldnames('SBML_MODEL', level, version);
+
+if (numFields ==0)
+	valid = 0;
+	message = 'invalid level/version';
+end;
+
+index = 1;
+while (valid == 1 && index <= numFields)
+	valid = isfield(SBMLStructure, char(SBMLfieldnames(index)));
+	if (valid == 0);
+		message = sprintf('%s field missing', char(SBMLfieldnames(index)));
+	end;
+	index = index + 1;
+end;
+
+%check that any nested structures are appropriate
+
+% functionDefinitions
+if (valid == 1 && level > 1)
+  index = 1;
+  while (valid == 1 && index <= length(SBMLStructure.functionDefinition))
+    [valid, message] = isSBML_Struct('SBML_FUNCTION_DEFINITION', ...
+                                  SBMLStructure.functionDefinition(index), ...
+                                  level, version, extensions_allowed);
+    index = index + 1;
+  end;
+end;
+
+% unitDefinitions
+if (valid == 1)
+  index = 1;
+  while (valid == 1 && index <= length(SBMLStructure.unitDefinition))
+    [valid, message] = isSBML_Struct('SBML_UNIT_DEFINITION', ...
+                                  SBMLStructure.unitDefinition(index), ...
+                                  level, version, extensions_allowed);
+    index = index + 1;
+  end;
+end;
+
+% compartments
+if (valid == 1)
+  index = 1;
+  while (valid == 1 && index <= length(SBMLStructure.compartment))
+    [valid, message] = isSBML_Struct('SBML_COMPARTMENT', ...
+                                  SBMLStructure.compartment(index), ...
+                                  level, version, extensions_allowed);
+    index = index + 1;
+  end;
+end;
+
+% species
+if (valid == 1 && in_fbc == 0)
+  index = 1;
+  while (valid == 1 && index <= length(SBMLStructure.species))
+    [valid, message] = isSBML_Struct('SBML_SPECIES', ...
+                                  SBMLStructure.species(index), ...
+                                  level, version, extensions_allowed);
+    index = index + 1;
+  end;
+end;
+
+% compartmentTypes
+if (valid == 1 && level == 2 && version > 1)
+  index = 1;
+  while (valid == 1 && index <= length(SBMLStructure.compartmentType))
+    [valid, message] = isSBML_Struct('SBML_COMPARTMENT_TYPE', ...
+                                  SBMLStructure.compartmentType(index), ...
+                                  level, version, extensions_allowed);
+    index = index + 1;
+  end;
+end;
+
+% speciesTypes
+if (valid == 1 && level == 2 && version > 1)
+  index = 1;
+  while (valid == 1 && index <= length(SBMLStructure.speciesType))
+    [valid, message] = isSBML_Struct('SBML_SPECIES_TYPE', ...
+                                  SBMLStructure.speciesType(index), ...
+                                  level, version, extensions_allowed);
+    index = index + 1;
+  end;
+end;
+
+% parameter
+if (valid == 1)
+  index = 1;
+  while (valid == 1 && index <= length(SBMLStructure.parameter))
+    [valid, message] = isSBML_Struct('SBML_PARAMETER', ...
+                                  SBMLStructure.parameter(index), ...
+                                  level, version, extensions_allowed);
+    index = index + 1;
+  end;
+end;
+
+% initialAssignment
+if (valid == 1 && (level > 2 || (level == 2 && version > 1)))
+  index = 1;
+  while (valid == 1 && index <= length(SBMLStructure.initialAssignment))
+    [valid, message] = isSBML_Struct('SBML_INITIAL_ASSIGNMENT', ...
+                                  SBMLStructure.initialAssignment(index), ...
+                                  level, version, extensions_allowed);
+    index = index + 1;
+  end;
+end;
+
+% rule
+if (valid == 1)
+  index = 1;
+  while (valid == 1 && index <= length(SBMLStructure.rule))
+    [valid, message] = isSBML_Rule(SBMLStructure.rule(index), ...
+                                  level, version, extensions_allowed);
+    index = index + 1;
+  end;
+end;
+
+% constraints
+if (valid == 1 && (level > 2 || (level == 2 && version > 1)))
+  index = 1;
+  while (valid == 1 && index <= length(SBMLStructure.constraint))
+    [valid, message] = isSBML_Struct('SBML_CONSTRAINT', ...
+                                  SBMLStructure.constraint(index), ...
+                                  level, version, extensions_allowed);
+    index = index + 1;
+  end;
+end;
+
+% reaction
+if (valid == 1)
+  index = 1;
+  while (valid == 1 && index <= length(SBMLStructure.reaction))
+    [valid, message] = isSBML_Struct('SBML_REACTION', ...
+                                  SBMLStructure.reaction(index), ...
+                                  level, version, extensions_allowed);
+    index = index + 1;
+  end;
+end;
+
+% event
+if (valid == 1 && level > 1)
+  index = 1;
+  while (valid == 1 && index <= length(SBMLStructure.event))
+    [valid, message] = isSBML_Struct('SBML_EVENT', ...
+                                  SBMLStructure.event(index), ...
+                                  level, version, extensions_allowed);
+    index = index + 1;
+  end;
+end;
+
+
+% report failure
+if (valid == 0)
+	message = sprintf('Invalid Model structure\n%s\n', message);
+end;
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [valid, message] = isSBML_Struct(typecode, SBMLStructure, level, version, extensions_allowed)
+
+
+
+
+if (length(SBMLStructure) > 1)
+  valid = 0;
+  message = 'cannot deal with arrays of structures';
+  return;
+end;
+
+isValidLevelVersionCombination(level, version);
+
+message = '';
+
+% check that argument is a structure
+valid = isstruct(SBMLStructure);
+
+% check the typecode
+if (valid == 1 && ~isempty(SBMLStructure))
+  if isfield(SBMLStructure, 'typecode')
+    if (strcmp(typecode, SBMLStructure.typecode) ~= 1)
+      valid = 0;
+      message = 'typecode mismatch';
+      return;
+    end;
+  else
+    valid = 0;
+    message = 'missing typecode field';
+    return;
+  end;
+end;
+
+% if the level and version fields exist they must match
+if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure))
+	if ~isequal(level, SBMLStructure.level)
+		valid = 0;
+		message = 'level mismatch';
+	end;
+end;
+if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure))
+	if ~isequal(version, SBMLStructure.version)
+		valid = 0;
+		message = 'version mismatch';
+	end;
+end;
+
+% check that structure contains all the necessary fields
+[SBMLfieldnames, numFields] = getFieldnames(typecode, level, version);
+
+if (numFields ==0)
+	valid = 0;
+	message = 'invalid level/version';
+end;
+
+index = 1;
+while (valid == 1 && index <= numFields)
+	valid = isfield(SBMLStructure, char(SBMLfieldnames(index)));
+	if (valid == 0);
+		message = sprintf('%s field missing', char(SBMLfieldnames(index)));
+	end;
+	index = index + 1;
+end;
+
+if (extensions_allowed == 0)
+  % check that the structure contains ONLY the expected fields
+  if (valid == 1)
+    if (numFields ~= length(fieldnames(SBMLStructure))-2)
+      valid = 0;
+      message = sprintf('Unexpected field detected');
+    end;
+  end;
+end;
+
+% some structures have child structures
+switch (typecode)
+  case 'SBML_EVENT'
+    % eventAssignments
+    if (valid == 1)
+      index = 1;
+      while (valid == 1 && index <= length(SBMLStructure.eventAssignment))
+        [valid, message] = isSBML_Struct('SBML_EVENT_ASSIGNMENT', ...
+                                      SBMLStructure.eventAssignment(index), ...
+                                      level, version, extensions_allowed);
+        index = index + 1;
+      end;
+    end;
+
+    % trigger/delay/priority
+    % these are level and version dependent
+    if (valid == 1)
+      if (level == 2 && version > 2)
+        if (length(SBMLStructure.trigger) > 1)
+          valid = 0;
+          message = 'multiple trigger elements encountered';
+        elseif (length(SBMLStructure.delay) > 1)
+          valid = 0;
+          message = 'multiple delay elements encountered';
+        end;
+        if (valid == 1 && length(SBMLStructure.trigger) == 1)
+          [valid, message] = isSBML_Struct('SBML_TRIGGER', ...
+                                            SBMLStructure.trigger, ...
+                                            level, version, extensions_allowed);
+        end;
+        if (valid == 1 && length(SBMLStructure.delay) == 1)
+          [valid, message] = isSBML_Struct('SBML_DELAY', ...
+                                            SBMLStructure.delay, ...
+                                            level, version, extensions_allowed);
+       end;
+      elseif (level > 2)
+        if (length(SBMLStructure.trigger) > 1)
+          valid = 0;
+          message = 'multiple trigger elements encountered';
+        elseif (length(SBMLStructure.delay) > 1)
+          valid = 0;
+          message = 'multiple delay elements encountered';
+        elseif (length(SBMLStructure.priority) > 1)
+          valid = 0;
+          message = 'multiple priority elements encountered';
+        end;
+        if (valid == 1 && length(SBMLStructure.trigger) == 1)
+          [valid, message] = isSBML_Struct('SBML_TRIGGER', ...
+                                            SBMLStructure.trigger, ...
+                                            level, version, extensions_allowed);
+        end;
+        if (valid == 1 && length(SBMLStructure.delay) == 1)
+          [valid, message] = isSBML_Struct('SBML_DELAY', ...
+                                            SBMLStructure.delay, ...
+                                            level, version, extensions_allowed);
+        end;
+        if (valid == 1 && length(SBMLStructure.priority) == 1)
+          [valid, message] = isSBML_Struct('SBML_PRIORITY', ...
+                                            SBMLStructure.priority, ...
+                                            level, version, extensions_allowed);
+        end;
+      end;
+    end;
+
+  case 'SBML_KINETIC_LAW'
+    % parameters
+    if (valid == 1 && level < 3)
+      index = 1;
+      while (valid == 1 && index <= length(SBMLStructure.parameter))
+        [valid, message] = isSBML_Struct('SBML_PARAMETER', ...
+                                      SBMLStructure.parameter(index), ...
+                                      level, version, extensions_allowed);
+        index = index + 1;
+      end;
+    end;
+
+    %check that any nested structures are appropriate
+
+    % localParameters
+    if (valid == 1 && level > 2)
+      index = 1;
+      while (valid == 1 && index <= length(SBMLStructure.localParameter))
+        [valid, message] = isSBML_Struct('SBML_LOCAL_PARAMETER', ...
+                                      SBMLStructure.localParameter(index), ...
+                                      level, version, extensions_allowed);
+        index = index + 1;
+      end;
+    end;
+
+  case 'SBML_REACTION'
+    % reactants
+    if (valid == 1)
+      index = 1;
+      while (valid == 1 && index <= length(SBMLStructure.reactant))
+        [valid, message] = isSBML_Struct('SBML_SPECIES_REFERENCE', ...
+                                      SBMLStructure.reactant(index), ...
+                                      level, version, extensions_allowed);
+        index = index + 1;
+      end;
+    end;
+
+    % products
+    if (valid == 1)
+      index = 1;
+      while (valid == 1 && index <= length(SBMLStructure.product))
+        [valid, message] = isSBML_Struct('SBML_SPECIES_REFERENCE', ...
+                                      SBMLStructure.product(index), ...
+                                      level, version, extensions_allowed);
+        index = index + 1;
+      end;
+    end;
+
+    % modifiers
+    if (valid == 1 && level > 1)
+      index = 1;
+      while (valid == 1 && index <= length(SBMLStructure.modifier))
+        [valid, message] = isSBML_Struct('SBML_MODIFIER_SPECIES_REFERENCE', ...
+                                      SBMLStructure.modifier(index), ...
+                                      level, version, extensions_allowed);
+        index = index + 1;
+      end;
+    end;
+
+    % kineticLaw
+    if (valid == 1 && length(SBMLStructure.kineticLaw) == 1)
+      [valid, message] = isSBML_Struct('SBML_KINETIC_LAW', ...
+                                    SBMLStructure.kineticLaw, level, version, extensions_allowed);
+    end;
+
+  case 'SBML_UNIT_DEFINITION'
+    % unit
+    if (valid == 1)
+      index = 1;
+      while (valid == 1 && index <= length(SBMLStructure.unit))
+        [valid, message] = isSBML_Struct('SBML_UNIT', ...
+                                      SBMLStructure.unit(index), ...
+                                      level, version, extensions_allowed);
+        index = index + 1;
+      end;
+    end;
+
+  case 'SBML_SPECIES_REFERENCE'
+    % stoichiometryMath
+    if (level == 2 && version > 2)
+      if (valid == 1 && length(SBMLStructure.stoichiometryMath) == 1)
+        [valid, message] = isSBML_Struct('SBML_STOICHIOMETRY_MATH', ...
+                                      SBMLStructure.stoichiometryMath, ...
+                                      level, version, extensions_allowed);
+      end;
+    end;
+      
+end;
+
+% report failure
+if (valid == 0)
+	message = sprintf('Invalid %s\n%s\n', typecode, message);
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [valid, message] = isSBML_Rule(SBMLStructure, ...
+                                  level, version, extensions_allowed)
+
+
+
+
+if (length(SBMLStructure) > 1)
+  valid = 0;
+  message = 'cannot deal with arrays of structures';
+  return;
+end;
+
+isValidLevelVersionCombination(level, version);
+
+message = '';
+
+if ~isempty(SBMLStructure)
+  if isfield(SBMLStructure, 'typecode')
+    typecode = SBMLStructure.typecode;
+  else
+    valid = 0;
+    message = 'missing typecode';
+    return;
+  end;
+else
+  typecode = 'SBML_ASSIGNMENT_RULE';
+end;
+
+switch (typecode)
+  case {'SBML_ALGEBRAIC_RULE', 'SBML_ASSIGNMENT_RULE', ...
+      'SBML_COMPARTMENT_VOLUME_RULE', 'SBML_PARAMETER_RULE', ...
+      'SBML_RATE_RULE', 'SBML_SPECIES_CONCENTRATION_RULE'}
+    [valid, message] = isSBML_Struct(typecode, SBMLStructure, level, version, extensions_allowed);
+  case 'SBML_RULE'
+    [valid, message] = checkRule(SBMLStructure, level, version, extensions_allowed);
+  otherwise
+    valid = 0;
+    message = 'Incorrect rule typecode';
+ end;
+ 
+
+function [valid, message] = checkRule(SBMLStructure, level, version, extensions_allowed)
+
+
+message = '';
+
+% check that argument is a structure
+valid = isstruct(SBMLStructure);
+
+% check the typecode
+typecode = 'SBML_RULE';
+if (valid == 1 && ~isempty(SBMLStructure))
+  if (strcmp(typecode, SBMLStructure.typecode) ~= 1)
+    valid = 0;
+    message = 'typecode mismatch';
+  end;
+end;
+
+% if the level and version fields exist they must match
+if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure))
+	if ~isequal(level, SBMLStructure.level)
+		valid = 0;
+		message = 'level mismatch';
+	end;
+end;
+if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure))
+	if ~isequal(version, SBMLStructure.version)
+		valid = 0;
+		message = 'version mismatch';
+	end;
+end;
+
+% check that structure contains all the necessary fields
+[SBMLfieldnames, numFields] = getAlgebraicRuleFieldnames(level, version);
+
+if (numFields ==0)
+	valid = 0;
+	message = 'invalid level/version';
+end;
+
+index = 1;
+while (valid == 1 && index <= numFields)
+	valid = isfield(SBMLStructure, char(SBMLfieldnames(index)));
+	if (valid == 0);
+		message = sprintf('%s field missing', char(SBMLfieldnames(index)));
+	end;
+	index = index + 1;
+end;
+
+if (extensions_allowed == 0)
+  % check that the structure contains ONLY the expected fields
+  if (valid == 1)
+    if (numFields ~= length(fieldnames(SBMLStructure))-2)
+      valid = 0;
+      message = sprintf('Unexpected field detected');
+    end;
+  end;
+end;
+
+% report failure
+if (valid == 0)
+	message = sprintf('Invalid Rule\n%s\n', message);
+end;
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [valid, message] = isSBML_FBCStruct(typecode, SBMLStructure, level, ...
+  version, pkgVersion, extensions_allowed)
+
+
+
+
+if (length(SBMLStructure) > 1)
+  valid = 0;
+  message = 'cannot deal with arrays of structures';
+  return;
+end;
+
+isValidLevelVersionCombination(level, version);
+
+message = '';
+
+% check that argument is a structure
+valid = isstruct(SBMLStructure);
+
+% check the typecode
+if (valid == 1 && ~isempty(SBMLStructure))
+  if isfield(SBMLStructure, 'typecode')
+    if (strcmp(typecode, SBMLStructure.typecode) ~= 1)
+      valid = 0;
+      message = 'typecode mismatch';
+      return;
+    end;
+  else
+    valid = 0;
+    message = 'missing typecode field';
+    return;
+  end;
+end;
+
+% if the level and version fields exist they must match
+if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure))
+	if ~isequal(level, SBMLStructure.level)
+		valid = 0;
+		message = 'level mismatch';
+	end;
+end;
+if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure))
+	if ~isequal(version, SBMLStructure.version)
+		valid = 0;
+		message = 'version mismatch';
+	end;
+end;
+
+if (valid == 1 && isfield(SBMLStructure, 'fbc_version') && ~isempty(SBMLStructure))
+	if ~isequal(pkgVersion, SBMLStructure.fbc_version)
+		valid = 0;
+		message = 'fbc version mismatch';
+	end;
+end;
+
+
+% check that structure contains all the necessary fields
+[SBMLfieldnames, numFields] = getFieldnames(typecode, level, version, pkgVersion);
+
+if (numFields ==0)
+	valid = 0;
+	message = 'invalid level/version';
+end;
+
+index = 1;
+while (valid == 1 && index <= numFields)
+	valid = isfield(SBMLStructure, char(SBMLfieldnames(index)));
+	if (valid == 0);
+		message = sprintf('%s field missing', char(SBMLfieldnames(index)));
+	end;
+	index = index + 1;
+end;
+
+if (extensions_allowed == 0)
+  % check that the structure contains ONLY the expected fields
+  if (valid == 1)
+    if (numFields ~= length(fieldnames(SBMLStructure)))
+      valid = 0;
+      message = sprintf('Unexpected field detected');
+    end;
+  end;
+end;
+
+% some structures have child structures
+switch (typecode)
+  case 'SBML_FBC_OBJECTIVE'
+    % eventAssignments
+    if (valid == 1)
+      index = 1;
+      while (valid == 1 && index <= length(SBMLStructure.fbc_fluxObjective))
+        [valid, message] = isSBML_FBCStruct('SBML_FBC_FLUXOBJECTIVE', ...
+                                      SBMLStructure.fbc_fluxObjective(index), ...
+                                      level, version, pkgVersion, extensions_allowed);
+        index = index + 1;
+      end;
+    end;
+end;
+
+% report failure
+if (valid == 0)
+	message = sprintf('Invalid %s\n%s\n', typecode, message);
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+
+function [valid, message] = isSBML_FBC_Model(SBMLStructure, level, version, ...
+             pkgVersion, extensions_allowed)
+% [valid, message] = isSBML_FBC_Model(SBMLFBCModel, level, version, pkgVersion)
+
+
+if (length(SBMLStructure) > 1)
+	message = 'cannot deal with arrays of structures';
+  valid = 0;
+  return;
+end;
+
+isValidLevelVersionCombination(level, version);
+
+message = '';
+
+% check that argument is a structure
+valid = isstruct(SBMLStructure);
+
+% check the typecode
+typecode = 'SBML_MODEL';
+if (valid == 1 && ~isempty(SBMLStructure))
+  if isfield(SBMLStructure, 'typecode')
+    if (strcmp(typecode, SBMLStructure.typecode) ~= 1)
+      valid = 0;
+      message = 'typecode mismatch';
+      return;
+    end;
+  else
+    valid = 0;
+    message = 'typecode field missing';
+    return;
+  end;
+end;
+
+% if the level and version fields exist they must match
+if (valid == 1 && isfield(SBMLStructure, 'SBML_level') && ~isempty(SBMLStructure))
+	if ~isequal(level, SBMLStructure.SBML_level)
+		valid = 0;
+		message = 'level mismatch';
+	end;
+end;
+if (valid == 1 && isfield(SBMLStructure, 'SBML_version') && ~isempty(SBMLStructure))
+	if ~isequal(version, SBMLStructure.SBML_version)
+		valid = 0;
+		message = 'version mismatch';
+	end;
+end;
+if (valid == 1 && isfield(SBMLStructure, 'fbc_version') && ~isempty(SBMLStructure))
+	if ~isequal(pkgVersion, SBMLStructure.fbc_version)
+		valid = 0;
+		message = 'FBC version mismatch';
+	end;
+end;
+
+if (valid == 1)
+  % do not worry about extra fields at this point
+  % we know we are in an fbc model
+  [valid, message] = isValidSBML_Model(SBMLStructure, extensions_allowed, 1);
+end;
+
+% check that structure contains all the fbc fields
+if (valid == 1)
+  [SBMLfieldnames, numFields] = getFieldnames('SBML_FBC_MODEL', level, ...
+                                                version, pkgVersion);
+
+  if (numFields ==0)
+    valid = 0;
+    message = 'invalid level/version';
+  end;
+
+  index = 1;
+  while (valid == 1 && index <= numFields)
+    valid = isfield(SBMLStructure, char(SBMLfieldnames(index)));
+    if (valid == 0);
+      message = sprintf('%s field missing', char(SBMLfieldnames(index)));
+    end;
+    index = index + 1;
+  end;
+
+  %check that any nested structures are appropriate
+
+
+  % fluxBound
+  if (valid == 1)
+    index = 1;
+    while (valid == 1 && index <= length(SBMLStructure.fbc_fluxBound))
+      [valid, message] = isSBML_FBCStruct('SBML_FBC_FLUXBOUND', ...
+                                    SBMLStructure.fbc_fluxBound(index), ...
+                                    level, version, pkgVersion, extensions_allowed);
+      index = index + 1;
+    end;
+  end;
+
+  % objective
+  if (valid == 1)
+    index = 1;
+    while (valid == 1 && index <= length(SBMLStructure.fbc_objective))
+      [valid, message] = isSBML_FBCStruct('SBML_FBC_OBJECTIVE', ...
+                                    SBMLStructure.fbc_objective(index), ...
+                                    level, version, pkgVersion, extensions_allowed);
+      index = index + 1;
+    end;
+  end;
+  
+  %species
+  if (valid == 1)
+    index = 1;
+    while (valid == 1 && index <= length(SBMLStructure.species))
+      [valid, message] = isSBML_FBC_Species('SBML_FBC_SPECIES', ...
+                                    SBMLStructure.species(index), ...
+                                    level, version, pkgVersion, extensions_allowed);
+      index = index + 1;
+    end;
+  end;
+  
+
+end;
+
+% report failure
+if (valid == 0)
+	message = sprintf('Invalid FBC Model\n%s\n', message);
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [valid, message] = isSBML_FBC_Species(typecode, SBMLStructure, ...
+                                    level, version, pkgVersion, extensions_allowed)
+
+if (length(SBMLStructure) > 1)
+	message = 'cannot deal with arrays of structures';
+  valid = 0;
+  return;
+end;
+
+isValidLevelVersionCombination(level, version);
+
+message = '';
+
+% check that argument is a structure
+valid = isstruct(SBMLStructure);
+
+% check the typecode
+typecode = 'SBML_SPECIES';
+if (valid == 1 && ~isempty(SBMLStructure))
+  if isfield(SBMLStructure, 'typecode')
+    if (strcmp(typecode, SBMLStructure.typecode) ~= 1)
+      valid = 0;
+      message = 'typecode mismatch';
+      return;
+    end;
+  else
+    valid = 0;
+    message = 'typecode field missing';
+    return;
+  end;
+end;
+
+% if the level and version fields exist they must match
+if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure))
+	if ~isequal(level, SBMLStructure.level)
+		valid = 0;
+		message = 'level mismatch';
+	end;
+end;
+if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure))
+	if ~isequal(version, SBMLStructure.version)
+		valid = 0;
+		message = 'version mismatch';
+	end;
+end;
+if (valid == 1 && isfield(SBMLStructure, 'fbc_version') && ~isempty(SBMLStructure))
+	if ~isequal(pkgVersion, SBMLStructure.fbc_version)
+		valid = 0;
+		message = 'FBC version mismatch';
+	end;
+end;
+
+if (valid == 1)
+  [valid, message] = isSBML_Struct('SBML_SPECIES', SBMLStructure, level, ...
+                                             version, 1);
+end;
+
+% check that structure contains all the fbc fields
+if (valid == 1)
+  [SBMLfieldnames, numFields] = getFieldnames('SBML_FBC_SPECIES', level, ...
+                                                version);
+
+  if (numFields ==0)
+    valid = 0;
+    message = 'invalid level/version';
+  end;
+
+  index = 1;
+  while (valid == 1 && index <= numFields)
+    valid = isfield(SBMLStructure, char(SBMLfieldnames(index)));
+    if (valid == 0);
+      message = sprintf('%s field missing', char(SBMLfieldnames(index)));
+    end;
+    index = index + 1;
+  end;
+
+  if (extensions_allowed == 0)
+    % check that the structure contains ONLY the expected fields
+    if (valid == 1)
+      if (numFields ~= length(fieldnames(SBMLStructure))-19)
+        valid = 0;
+        message = sprintf('Unexpected field detected');
+      end;
+    end;
+  end;
+
+
+end;
+
+% report failure
+if (valid == 0)
+	message = sprintf('Invalid FBC Species\n%s\n', message);
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function valid = isValidLevelVersionCombination(level, version)
+
+
+
+
+
+
+
+
+
+
+valid = 1;
+
+if ~isIntegralNumber(level)
+	error('level must be an integer');
+elseif ~isIntegralNumber(version)
+	error('version must be an integer');
+end;
+
+if (level < 1 || level > 3)
+	error('current SBML levels are 1, 2 or 3');
+end;
+
+if (level == 1)
+	if (version < 1 || version > 2)
+		error('SBMLToolbox supports versions 1-2 of SBML Level 1');
+	end;
+
+elseif (level == 2)
+	if (version < 1 || version > 4)
+		error('SBMLToolbox supports versions 1-4 of SBML Level 2');
+	end;
+
+elseif (level == 3)
+	if (version ~= 1)
+		error('SBMLToolbox supports only version 1 of SBML Level 3');
+	end;
+
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function value = isIntegralNumber(number)
+
+
+value = 0;
+
+integerClasses = {'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'};
+
+% since the function isinteger does not exist in MATLAB Rel 13
+% this is not used
+%if (isinteger(number))
+if (ismember(class(number), integerClasses))
+    value = 1;
+elseif (isnumeric(number))
+    % if it is an integer 
+    if (number == fix(number))
+        value = 1;
+    end;
+end;
+
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getAlgebraicRuleFieldnames(level, ...
+                                                             version)
+
+
+
+
+
+
+
+
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+if (level == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'type', ...
+		                   'formula', ...
+		                   'variable', ...
+		                   'species', ...
+		                   'compartment', ...
+		                   'name', ...
+		                   'units', ...
+		                 };
+		nNumberFields = 10;
+elseif (level == 2)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'formula', ...
+		                   'variable', ...
+		                   'species', ...
+		                   'compartment', ...
+		                   'name', ...
+		                   'units', ...
+		                 };
+		nNumberFields = 10;
+	elseif (version == 2)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'formula', ...
+		                   'variable', ...
+		                   'species', ...
+		                   'compartment', ...
+		                   'name', ...
+		                   'units', ...
+		                 };
+		nNumberFields = 11;
+	elseif (version == 3)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'formula', ...
+		                   'variable', ...
+		                   'species', ...
+		                   'compartment', ...
+		                   'name', ...
+		                   'units', ...
+		                 };
+		nNumberFields = 11;
+	elseif (version == 4)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'formula', ...
+		                   'variable', ...
+		                   'species', ...
+		                   'compartment', ...
+		                   'name', ...
+		                   'units', ...
+		                 };
+		nNumberFields = 11;
+	end;
+elseif (level == 3)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'formula', ...
+		                   'variable', ...
+		                   'species', ...
+		                   'compartment', ...
+		                   'name', ...
+		                   'units', ...
+		                 };
+		nNumberFields = 11;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getAssignmentRuleFieldnames(level, ...
+                                                             version)
+
+
+
+
+
+
+
+
+
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+if (level == 1)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+elseif (level == 2)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'formula', ...
+		                   'variable', ...
+		                   'species', ...
+		                   'compartment', ...
+		                   'name', ...
+		                   'units', ...
+		                 };
+		nNumberFields = 10;
+	elseif (version == 2)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'formula', ...
+		                   'variable', ...
+		                   'species', ...
+		                   'compartment', ...
+		                   'name', ...
+		                   'units', ...
+		                 };
+		nNumberFields = 11;
+	elseif (version == 3)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'formula', ...
+		                   'variable', ...
+		                   'species', ...
+		                   'compartment', ...
+		                   'name', ...
+		                   'units', ...
+		                 };
+		nNumberFields = 11;
+	elseif (version == 4)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'formula', ...
+		                   'variable', ...
+		                   'species', ...
+		                   'compartment', ...
+		                   'name', ...
+		                   'units', ...
+		                 };
+		nNumberFields = 11;
+	end;
+elseif (level == 3)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'formula', ...
+		                   'variable', ...
+		                   'species', ...
+		                   'compartment', ...
+		                   'name', ...
+		                   'units', ...
+		                 };
+		nNumberFields = 11;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getCompartmentFieldnames(level, ...
+                                                                    version)
+
+
+
+
+
+
+
+
+
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+if (level == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'name', ...
+		                   'volume', ...
+		                   'units', ...
+		                   'outside', ...
+		                   'isSetVolume', ...
+		                 };
+		nNumberFields = 8;
+elseif (level == 2)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'name', ...
+		                   'id', ...
+		                   'spatialDimensions', ...
+		                   'size', ...
+		                   'units', ...
+		                   'outside', ...
+		                   'constant', ...
+		                   'isSetSize', ...
+		                   'isSetVolume', ...
+		                 };
+		nNumberFields = 13;
+	elseif (version == 2)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'name', ...
+		                   'id', ...
+		                   'compartmentType', ...
+		                   'spatialDimensions', ...
+		                   'size', ...
+		                   'units', ...
+		                   'outside', ...
+		                   'constant', ...
+		                   'isSetSize', ...
+		                   'isSetVolume', ...
+		                 };
+		nNumberFields = 14;
+	elseif (version == 3)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'name', ...
+		                   'id', ...
+		                   'compartmentType', ...
+		                   'spatialDimensions', ...
+		                   'size', ...
+		                   'units', ...
+		                   'outside', ...
+		                   'constant', ...
+		                   'isSetSize', ...
+		                   'isSetVolume', ...
+		                 };
+		nNumberFields = 15;
+	elseif (version == 4)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'name', ...
+		                   'id', ...
+		                   'compartmentType', ...
+		                   'spatialDimensions', ...
+		                   'size', ...
+		                   'units', ...
+		                   'outside', ...
+		                   'constant', ...
+		                   'isSetSize', ...
+		                   'isSetVolume', ...
+		                 };
+		nNumberFields = 15;
+	end;
+elseif (level == 3)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'name', ...
+		                   'id', ...
+		                   'spatialDimensions', ...
+		                   'size', ...
+		                   'units', ...
+		                   'constant', ...
+		                   'isSetSize', ...
+		                   'isSetSpatialDimensions', ...
+		                 };
+		nNumberFields = 13;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getCompartmentTypeFieldnames(level, ...
+                                                                        version)
+
+
+
+
+
+
+
+
+
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+if (level == 1)
+	SBMLfieldnames = [];
+	nNumberFields = 0;
+elseif (level == 2)
+	if (version == 1)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+	elseif (version == 2)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'name', ...
+		                   'id', ...
+		                 };
+		nNumberFields = 6;
+	elseif (version == 3)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'name', ...
+		                   'id', ...
+		                 };
+		nNumberFields = 7;
+	elseif (version == 4)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'name', ...
+		                   'id', ...
+		                 };
+		nNumberFields = 7;
+	end;
+elseif (level == 3)
+	if (version == 1)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getCompartmentVolumeRuleFieldnames(level, ...
+                                                             version)
+
+
+
+
+
+
+
+
+
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+if (level == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'type', ...
+		                   'formula', ...
+		                   'variable', ...
+		                   'species', ...
+		                   'compartment', ...
+		                   'name', ...
+		                   'units', ...
+		                 };
+		nNumberFields = 10;
+elseif (level == 2)
+	if (version == 1)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+	elseif (version == 2)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+	elseif (version == 3)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+	elseif (version == 4)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+	end;
+elseif (level == 3)
+	if (version == 1)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getConstraintFieldnames(level, ...
+                                                                   version)
+
+
+
+
+
+
+
+
+
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+if (level == 1)
+	SBMLfieldnames = [];
+	nNumberFields = 0;
+elseif (level == 2)
+	if (version == 1)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+	elseif (version == 2)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'math', ...
+		                   'message', ...
+		                 };
+		nNumberFields = 7;
+	elseif (version == 3)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'math', ...
+		                   'message', ...
+		                 };
+		nNumberFields = 7;
+	elseif (version == 4)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'math', ...
+		                   'message', ...
+		                 };
+		nNumberFields = 7;
+	end;
+elseif (level == 3)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'math', ...
+		                   'message', ...
+		                 };
+		nNumberFields = 7;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getDelayFieldnames(level, ...
+                                                              version)
+
+
+
+
+
+
+
+
+
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+if (level == 1)
+	SBMLfieldnames = [];
+	nNumberFields = 0;
+elseif (level == 2)
+	if (version == 1)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+	elseif (version == 2)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+	elseif (version == 3)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'math', ...
+		                 };
+		nNumberFields = 6;
+	elseif (version == 4)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'math', ...
+		                 };
+		nNumberFields = 6;
+	end;
+elseif (level == 3)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'math', ...
+		                 };
+		nNumberFields = 6;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getEventAssignmentFieldnames(level, ...
+                                                                        version)
+
+
+
+
+
+
+
+
+
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+if (level == 1)
+	SBMLfieldnames = [];
+	nNumberFields = 0;
+elseif (level == 2)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'variable', ...
+		                   'math', ...
+		                 };
+		nNumberFields = 6;
+	elseif (version == 2)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'variable', ...
+		                   'sboTerm', ...
+		                   'math', ...
+		                 };
+		nNumberFields = 7;
+	elseif (version == 3)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'variable', ...
+		                   'math', ...
+		                 };
+		nNumberFields = 7;
+	elseif (version == 4)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'variable', ...
+		                   'math', ...
+		                 };
+		nNumberFields = 7;
+	end;
+elseif (level == 3)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'variable', ...
+		                   'math', ...
+		                 };
+		nNumberFields = 7;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getEventFieldnames(level, ...
+                                                              version)
+
+
+
+
+
+
+
+
+
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+if (level == 1)
+	SBMLfieldnames = [];
+	nNumberFields = 0;
+elseif (level == 2)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'name', ...
+		                   'id', ...
+		                   'trigger', ...
+		                   'delay', ...
+		                   'timeUnits', ...
+		                   'eventAssignment', ...
+		                 };
+		nNumberFields = 10;
+	elseif (version == 2)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'name', ...
+		                   'id', ...
+		                   'trigger', ...
+		                   'delay', ...
+		                   'timeUnits', ...
+		                   'sboTerm', ...
+		                   'eventAssignment', ...
+		                 };
+		nNumberFields = 11;
+	elseif (version == 3)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'name', ...
+		                   'id', ...
+		                   'trigger', ...
+		                   'delay', ...
+		                   'eventAssignment', ...
+		                 };
+		nNumberFields = 10;
+	elseif (version == 4)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'name', ...
+		                   'id', ...
+		                   'useValuesFromTriggerTime', ...
+		                   'trigger', ...
+		                   'delay', ...
+		                   'eventAssignment', ...
+		                 };
+		nNumberFields = 11;
+	end;
+elseif (level == 3)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'name', ...
+		                   'id', ...
+		                   'useValuesFromTriggerTime', ...
+		                   'trigger', ...
+		                   'delay', ...
+		                   'priority', ...
+		                   'eventAssignment', ...
+		                 };
+		nNumberFields = 12;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getFieldnames(varargin)
+
+if (nargin < 3)
+  error('getFieldnames requires 3 arguments');
+end;
+
+typecode = varargin{1};
+level = varargin{2};
+version = varargin{3};
+if nargin == 4
+  pkgVersion = varargin{4};
+else
+  pkgVersion = 1;
+end;
+
+done = 1;
+
+
+switch (typecode)
+  case {'SBML_ALGEBRAIC_RULE', 'AlgebraicRule', 'algebraicRule'}
+    [SBMLfieldnames, nNumberFields] = getAlgebraicRuleFieldnames(level, version);
+  case {'SBML_ASSIGNMENT_RULE', 'AssignmentRule', 'assignmentRule'}
+    [SBMLfieldnames, nNumberFields] = getAssignmentRuleFieldnames(level, version);
+  case {'SBML_COMPARTMENT', 'Compartment', 'compartment'}
+    [SBMLfieldnames, nNumberFields] = getCompartmentFieldnames(level, version);
+  case {'SBML_COMPARTMENT_TYPE', 'CompartmentType', 'compartmentType'}
+    [SBMLfieldnames, nNumberFields] = getCompartmentTypeFieldnames(level, version);
+  case {'SBML_COMPARTMENT_VOLUME_RULE', 'CompartmentVolumeRule', 'compartmentVolumeRule'}
+    [SBMLfieldnames, nNumberFields] = getCompartmentVolumeRuleFieldnames(level, version);
+  case {'SBML_CONSTRAINT', 'Constraint', 'constraint'}
+    [SBMLfieldnames, nNumberFields] = getConstraintFieldnames(level, version);
+  case {'SBML_DELAY', 'Delay', 'delay'}
+    [SBMLfieldnames, nNumberFields] = getDelayFieldnames(level, version);
+  case {'SBML_EVENT', 'Event', 'event'}
+    [SBMLfieldnames, nNumberFields] = getEventFieldnames(level, version);
+  case {'SBML_EVENT_ASSIGNMENT', 'EventAssignment', 'eventAssignment'}
+    [SBMLfieldnames, nNumberFields] = getEventAssignmentFieldnames(level, version);
+  case {'SBML_FUNCTION_DEFINITION', 'FunctionDefinition', 'functionDefinition'}
+    [SBMLfieldnames, nNumberFields] = getFunctionDefinitionFieldnames(level, version);
+  case {'SBML_INITIAL_ASSIGNMENT', 'InitialAssignment', 'initialAssignment'}
+    [SBMLfieldnames, nNumberFields] = getInitialAssignmentFieldnames(level, version);
+  case {'SBML_KINETIC_LAW', 'KineticLaw', 'kineticLaw'}
+    [SBMLfieldnames, nNumberFields] = getKineticLawFieldnames(level, version);
+  case {'SBML_LOCAL_PARAMETER', 'LocalParameter', 'localParameter'}
+    [SBMLfieldnames, nNumberFields] = getLocalParameterFieldnames(level, version);
+  case {'SBML_MODEL', 'Model', 'model'}
+    [SBMLfieldnames, nNumberFields] = getModelFieldnames(level, version);
+  case {'SBML_MODIFIER_SPECIES_REFERENCE', 'ModifierSpeciesReference', 'modifierSpeciesReference'}
+    [SBMLfieldnames, nNumberFields] = getModifierSpeciesReferenceFieldnames(level, version);
+  case {'SBML_PARAMETER', 'Parameter', 'parameter'}
+    [SBMLfieldnames, nNumberFields] = getParameterFieldnames(level, version);
+  case {'SBML_PARAMETER_RULE', 'ParameterRule', 'parameterRule'}
+    [SBMLfieldnames, nNumberFields] = getParameterRuleFieldnames(level, version);
+  case {'SBML_PRIORITY', 'Priority', 'priority'}
+    [SBMLfieldnames, nNumberFields] = getPriorityFieldnames(level, version);
+  case {'SBML_RATE_RULE', 'RateRule', 'ruleRule'}
+    [SBMLfieldnames, nNumberFields] = getRateRuleFieldnames(level, version);
+  case {'SBML_REACTION', 'Reaction', 'reaction'}
+    [SBMLfieldnames, nNumberFields] = getReactionFieldnames(level, version);
+  case {'SBML_SPECIES', 'Species', 'species'}
+    [SBMLfieldnames, nNumberFields] = getSpeciesFieldnames(level, version);
+  case {'SBML_SPECIES_CONCENTRATION_RULE', 'SpeciesConcentrationRule', 'speciesConcentrationRule'}
+    [SBMLfieldnames, nNumberFields] = getSpeciesConcentrationRuleFieldnames(level, version);
+  case {'SBML_SPECIES_REFERENCE', 'SpeciesReference', 'speciesReference'}
+    [SBMLfieldnames, nNumberFields] = getSpeciesReferenceFieldnames(level, version);
+  case {'SBML_SPECIES_TYPE', 'SpeciesType', 'speciesType'}
+    [SBMLfieldnames, nNumberFields] = getSpeciesTypeFieldnames(level, version);
+  case {'SBML_STOICHIOMETRY_MATH', 'StoichiometryMath', 'stoichiometryMath'}
+    [SBMLfieldnames, nNumberFields] = getStoichiometryMathFieldnames(level, version);
+  case {'SBML_TRIGGER', 'Trigger', 'trigger'}
+    [SBMLfieldnames, nNumberFields] = getTriggerFieldnames(level, version);
+  case {'SBML_UNIT', 'Unit', 'unit'}
+    [SBMLfieldnames, nNumberFields] = getUnitFieldnames(level, version);
+  case {'SBML_UNIT_DEFINITION', 'UnitDefinition', 'unitDefinition'}
+    [SBMLfieldnames, nNumberFields] = getUnitDefinitionFieldnames(level, version);
+  otherwise
+    done = 0;  
+end;
+
+if done == 0
+  switch (typecode)
+    case {'SBML_FBC_FLUXBOUND', 'FluxBound', 'fluxBound'}
+     [SBMLfieldnames, nNumberFields] = getFluxBoundFieldnames(level, version, pkgVersion);
+    case {'SBML_FBC_FLUXOBJECTIVE', 'FluxObjective', 'fluxObjective'}
+     [SBMLfieldnames, nNumberFields] = getFluxObjectiveFieldnames(level, version, pkgVersion);
+    case {'SBML_FBC_OBJECTIVE', 'Objective', 'objective'}
+     [SBMLfieldnames, nNumberFields] = getObjectiveFieldnames(level, version, pkgVersion);
+    case {'SBML_FBC_MODEL', 'FBCModel'}
+     [SBMLfieldnames, nNumberFields] = getFBCModelFieldnames(level, version, pkgVersion);
+    case {'SBML_FBC_SPECIES', 'FBCSpecies'}
+     [SBMLfieldnames, nNumberFields] = getFBCSpeciesFieldnames(level, version, pkgVersion);
+    otherwise
+      error('%s\n%s', ...
+        'getFieldnames(typecode, level, version', ...
+        'typecode not recognised');    
+  end;
+end;
+ 
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getFunctionDefinitionFieldnames(level, ...
+                                                                           version)
+
+
+
+
+
+
+
+
+
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+if (level == 1)
+	SBMLfieldnames = [];
+	nNumberFields = 0;
+elseif (level == 2)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'name', ...
+		                   'id', ...
+		                   'math', ...
+		                 };
+		nNumberFields = 7;
+	elseif (version == 2)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'name', ...
+		                   'id', ...
+		                   'math', ...
+		                 };
+		nNumberFields = 8;
+	elseif (version == 3)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'name', ...
+		                   'id', ...
+		                   'math', ...
+		                 };
+		nNumberFields = 8;
+	elseif (version == 4)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'name', ...
+		                   'id', ...
+		                   'math', ...
+		                 };
+		nNumberFields = 8;
+	end;
+elseif (level == 3)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'name', ...
+		                   'id', ...
+		                   'math', ...
+		                 };
+		nNumberFields = 8;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getInitialAssignmentFieldnames(level, ...
+                                                                          version)
+
+
+
+
+
+
+
+
+
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+if (level == 1)
+	SBMLfieldnames = [];
+	nNumberFields = 0;
+elseif (level == 2)
+	if (version == 1)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+	elseif (version == 2)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'symbol', ...
+		                   'math', ...
+		                 };
+		nNumberFields = 7;
+	elseif (version == 3)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'symbol', ...
+		                   'math', ...
+		                 };
+		nNumberFields = 7;
+	elseif (version == 4)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'symbol', ...
+		                   'math', ...
+		                 };
+		nNumberFields = 7;
+	end;
+elseif (level == 3)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'symbol', ...
+		                   'math', ...
+		                 };
+		nNumberFields = 7;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getKineticLawFieldnames(level, ...
+                                                                   version)
+
+
+
+
+
+
+
+
+
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+if (level == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'formula', ...
+		                   'parameter', ...
+		                   'timeUnits', ...
+		                   'substanceUnits', ...
+		                 };
+		nNumberFields = 7;
+elseif (level == 2)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'formula', ...
+		                   'math', ...
+		                   'parameter', ...
+		                   'timeUnits', ...
+		                   'substanceUnits', ...
+		                 };
+		nNumberFields = 9;
+	elseif (version == 2)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'formula', ...
+		                   'math', ...
+		                   'parameter', ...
+		                   'sboTerm', ...
+		                 };
+		nNumberFields = 8;
+	elseif (version == 3)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'formula', ...
+		                   'math', ...
+		                   'parameter', ...
+		                 };
+		nNumberFields = 8;
+	elseif (version == 4)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'formula', ...
+		                   'math', ...
+		                   'parameter', ...
+		                 };
+		nNumberFields = 8;
+	end;
+elseif (level == 3)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'math', ...
+		                   'localParameter', ...
+		                 };
+		nNumberFields = 7;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getLocalParameterFieldnames(level, ...
+                                                                       version)
+
+
+
+
+
+
+
+
+
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+if (level == 1)
+	SBMLfieldnames = [];
+	nNumberFields = 0;
+elseif (level == 2)
+	SBMLfieldnames = [];
+	nNumberFields = 0;
+elseif (level == 3)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'name', ...
+		                   'id', ...
+		                   'value', ...
+		                   'units', ...
+		                   'isSetValue', ...
+		                 };
+		nNumberFields = 10;
+  end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getModelFieldnames(level, ...
+                                                              version)
+
+
+
+
+
+
+
+
+
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+if (level == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'SBML_level', ...
+		                   'SBML_version', ...
+		                   'name', ...
+		                   'unitDefinition', ...
+		                   'compartment', ...
+		                   'species', ...
+		                   'parameter', ...
+		                   'rule', ...
+		                   'reaction', ...
+		                 };
+		nNumberFields = 12;
+elseif (level == 2)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'SBML_level', ...
+		                   'SBML_version', ...
+		                   'name', ...
+		                   'id', ...
+		                   'functionDefinition', ...
+		                   'unitDefinition', ...
+		                   'compartment', ...
+		                   'species', ...
+		                   'parameter', ...
+		                   'rule', ...
+		                   'reaction', ...
+		                   'event', ...
+		                 };
+		nNumberFields = 16;
+	elseif (version == 2)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'SBML_level', ...
+		                   'SBML_version', ...
+		                   'name', ...
+		                   'id', ...
+		                   'sboTerm', ...
+		                   'functionDefinition', ...
+		                   'unitDefinition', ...
+		                   'compartmentType', ...
+		                   'speciesType', ...
+		                   'compartment', ...
+		                   'species', ...
+		                   'parameter', ...
+		                   'initialAssignment', ...
+		                   'rule', ...
+		                   'constraint', ...
+		                   'reaction', ...
+		                   'event', ...
+		                 };
+		nNumberFields = 21;
+	elseif (version == 3)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'SBML_level', ...
+		                   'SBML_version', ...
+		                   'name', ...
+		                   'id', ...
+		                   'sboTerm', ...
+		                   'functionDefinition', ...
+		                   'unitDefinition', ...
+		                   'compartmentType', ...
+		                   'speciesType', ...
+		                   'compartment', ...
+		                   'species', ...
+		                   'parameter', ...
+		                   'initialAssignment', ...
+		                   'rule', ...
+		                   'constraint', ...
+		                   'reaction', ...
+		                   'event', ...
+		                 };
+		nNumberFields = 21;
+	elseif (version == 4)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'SBML_level', ...
+		                   'SBML_version', ...
+		                   'name', ...
+		                   'id', ...
+		                   'sboTerm', ...
+		                   'functionDefinition', ...
+		                   'unitDefinition', ...
+		                   'compartmentType', ...
+		                   'speciesType', ...
+		                   'compartment', ...
+		                   'species', ...
+		                   'parameter', ...
+		                   'initialAssignment', ...
+		                   'rule', ...
+		                   'constraint', ...
+		                   'reaction', ...
+		                   'event', ...
+		                 };
+		nNumberFields = 21;
+	end;
+elseif (level == 3)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'SBML_level', ...
+		                   'SBML_version', ...
+		                   'name', ...
+		                   'id', ...
+		                   'sboTerm', ...
+		                   'functionDefinition', ...
+		                   'unitDefinition', ...
+		                   'compartment', ...
+		                   'species', ...
+		                   'parameter', ...
+		                   'initialAssignment', ...
+		                   'rule', ...
+		                   'constraint', ...
+		                   'reaction', ...
+		                   'event', ...
+		                   'substanceUnits', ...
+		                   'timeUnits', ...
+		                   'lengthUnits', ...
+		                   'areaUnits', ...
+		                   'volumeUnits', ...
+		                   'extentUnits', ...
+		                   'conversionFactor', ...
+		                 };
+		nNumberFields = 26;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getModifierSpeciesReferenceFieldnames(level, ...
+                                                                                 version)
+
+
+
+
+
+
+
+
+
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+if (level == 1)
+	SBMLfieldnames = [];
+	nNumberFields = 0;
+elseif (level == 2)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'species', ...
+		                 };
+		nNumberFields = 5;
+	elseif (version == 2)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'species', ...
+		                   'id', ...
+		                   'name', ...
+		                   'sboTerm', ...
+		                 };
+		nNumberFields = 8;
+	elseif (version == 3)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'species', ...
+		                   'id', ...
+		                   'name', ...
+		                 };
+		nNumberFields = 8;
+	elseif (version == 4)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'species', ...
+		                   'id', ...
+		                   'name', ...
+		                 };
+		nNumberFields = 8;
+	end;
+elseif (level == 3)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'species', ...
+		                   'id', ...
+		                   'name', ...
+		                 };
+		nNumberFields = 8;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getParameterFieldnames(level, ...
+                                                                  version)
+
+
+
+
+
+
+
+
+
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+if (level == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'name', ...
+		                   'value', ...
+		                   'units', ...
+		                   'isSetValue', ...
+		                 };
+		nNumberFields = 7;
+elseif (level == 2)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'name', ...
+		                   'id', ...
+		                   'value', ...
+		                   'units', ...
+		                   'constant', ...
+		                   'isSetValue', ...
+		                 };
+		nNumberFields = 10;
+	elseif (version == 2)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'name', ...
+		                   'id', ...
+		                   'value', ...
+		                   'units', ...
+		                   'constant', ...
+		                   'sboTerm', ...
+		                   'isSetValue', ...
+		                 };
+		nNumberFields = 11;
+	elseif (version == 3)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'name', ...
+		                   'id', ...
+		                   'value', ...
+		                   'units', ...
+		                   'constant', ...
+		                   'isSetValue', ...
+		                 };
+		nNumberFields = 11;
+	elseif (version == 4)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'name', ...
+		                   'id', ...
+		                   'value', ...
+		                   'units', ...
+		                   'constant', ...
+		                   'isSetValue', ...
+		                 };
+		nNumberFields = 11;
+	end;
+elseif (level == 3)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'name', ...
+		                   'id', ...
+		                   'value', ...
+		                   'units', ...
+		                   'constant', ...
+		                   'isSetValue', ...
+		                 };
+		nNumberFields = 11;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getParameterRuleFieldnames(level, ...
+                                                             version)
+
+
+
+
+
+
+
+
+
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+if (level == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'type', ...
+		                   'formula', ...
+		                   'variable', ...
+		                   'species', ...
+		                   'compartment', ...
+		                   'name', ...
+		                   'units', ...
+		                 };
+		nNumberFields = 10;
+elseif (level == 2)
+	if (version == 1)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+	elseif (version == 2)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+	elseif (version == 3)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+	elseif (version == 4)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+	end;
+elseif (level == 3)
+	if (version == 1)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getPriorityFieldnames(level, ...
+                                                                 version)
+
+
+
+
+
+
+
+
+
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+if (level == 1)
+	SBMLfieldnames = [];
+	nNumberFields = 0;
+elseif (level == 2)
+	SBMLfieldnames = [];
+	nNumberFields = 0;
+elseif (level == 3)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'math', ...
+		                 };
+		nNumberFields = 6;
+  end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getRateRuleFieldnames(level, ...
+                                                             version)
+
+
+
+
+
+
+
+
+
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+if (level == 1)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+elseif (level == 2)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'formula', ...
+		                   'variable', ...
+		                   'species', ...
+		                   'compartment', ...
+		                   'name', ...
+		                   'units', ...
+		                 };
+		nNumberFields = 10;
+	elseif (version == 2)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'formula', ...
+		                   'variable', ...
+		                   'species', ...
+		                   'compartment', ...
+		                   'name', ...
+		                   'units', ...
+		                 };
+		nNumberFields = 11;
+	elseif (version == 3)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'formula', ...
+		                   'variable', ...
+		                   'species', ...
+		                   'compartment', ...
+		                   'name', ...
+		                   'units', ...
+		                 };
+		nNumberFields = 11;
+	elseif (version == 4)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'formula', ...
+		                   'variable', ...
+		                   'species', ...
+		                   'compartment', ...
+		                   'name', ...
+		                   'units', ...
+		                 };
+		nNumberFields = 11;
+	end;
+elseif (level == 3)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'formula', ...
+		                   'variable', ...
+		                   'species', ...
+		                   'compartment', ...
+		                   'name', ...
+		                   'units', ...
+		                 };
+		nNumberFields = 11;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getReactionFieldnames(level, ...
+                                                                 version)
+
+
+
+
+
+
+
+
+
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+if (level == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'name', ...
+		                   'reactant', ...
+		                   'product', ...
+		                   'kineticLaw', ...
+		                   'reversible', ...
+		                   'fast', ...
+		                 };
+		nNumberFields = 9;
+elseif (level == 2)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'name', ...
+		                   'id', ...
+		                   'reactant', ...
+		                   'product', ...
+		                   'modifier', ...
+		                   'kineticLaw', ...
+		                   'reversible', ...
+		                   'fast', ...
+		                   'isSetFast', ...
+		                 };
+		nNumberFields = 13;
+	elseif (version == 2)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'name', ...
+		                   'id', ...
+		                   'reactant', ...
+		                   'product', ...
+		                   'modifier', ...
+		                   'kineticLaw', ...
+		                   'reversible', ...
+		                   'fast', ...
+		                   'sboTerm', ...
+		                   'isSetFast', ...
+		                 };
+		nNumberFields = 14;
+	elseif (version == 3)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'name', ...
+		                   'id', ...
+		                   'reactant', ...
+		                   'product', ...
+		                   'modifier', ...
+		                   'kineticLaw', ...
+		                   'reversible', ...
+		                   'fast', ...
+		                   'isSetFast', ...
+		                 };
+		nNumberFields = 14;
+	elseif (version == 4)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'name', ...
+		                   'id', ...
+		                   'reactant', ...
+		                   'product', ...
+		                   'modifier', ...
+		                   'kineticLaw', ...
+		                   'reversible', ...
+		                   'fast', ...
+		                   'isSetFast', ...
+		                 };
+		nNumberFields = 14;
+	end;
+elseif (level == 3)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'name', ...
+		                   'id', ...
+		                   'reactant', ...
+		                   'product', ...
+		                   'modifier', ...
+		                   'kineticLaw', ...
+		                   'reversible', ...
+		                   'fast', ...
+		                   'isSetFast', ...
+		                   'compartment', ...
+		                 };
+		nNumberFields = 15;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getRuleFieldnames(level, ...
+                                                             version)
+
+
+
+
+
+
+
+
+
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+if (level == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'type', ...
+		                   'formula', ...
+		                   'variable', ...
+		                   'species', ...
+		                   'compartment', ...
+		                   'name', ...
+		                   'units', ...
+		                 };
+		nNumberFields = 10;
+elseif (level == 2)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'formula', ...
+		                   'variable', ...
+		                   'species', ...
+		                   'compartment', ...
+		                   'name', ...
+		                   'units', ...
+		                 };
+		nNumberFields = 10;
+	elseif (version == 2)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'formula', ...
+		                   'variable', ...
+		                   'species', ...
+		                   'compartment', ...
+		                   'name', ...
+		                   'units', ...
+		                 };
+		nNumberFields = 11;
+	elseif (version == 3)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'formula', ...
+		                   'variable', ...
+		                   'species', ...
+		                   'compartment', ...
+		                   'name', ...
+		                   'units', ...
+		                 };
+		nNumberFields = 11;
+	elseif (version == 4)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'formula', ...
+		                   'variable', ...
+		                   'species', ...
+		                   'compartment', ...
+		                   'name', ...
+		                   'units', ...
+		                 };
+		nNumberFields = 11;
+	end;
+elseif (level == 3)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'formula', ...
+		                   'variable', ...
+		                   'species', ...
+		                   'compartment', ...
+		                   'name', ...
+		                   'units', ...
+		                 };
+		nNumberFields = 11;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getSpeciesConcentrationRuleFieldnames(level, ...
+                                                             version)
+
+
+
+
+
+
+
+
+
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+if (level == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'type', ...
+		                   'formula', ...
+		                   'variable', ...
+		                   'species', ...
+		                   'compartment', ...
+		                   'name', ...
+		                   'units', ...
+		                 };
+		nNumberFields = 10;
+elseif (level == 2)
+	if (version == 1)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+	elseif (version == 2)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+	elseif (version == 3)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+	elseif (version == 4)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+	end;
+elseif (level == 3)
+	if (version == 1)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getSpeciesFieldnames(level, ...
+                                                                version)
+
+
+
+
+
+
+
+
+
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+if (level == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'name', ...
+		                   'compartment', ...
+		                   'initialAmount', ...
+		                   'units', ...
+		                   'boundaryCondition', ...
+		                   'charge', ...
+		                   'isSetInitialAmount', ...
+		                   'isSetCharge', ...
+		                 };
+		nNumberFields = 11;
+elseif (level == 2)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'name', ...
+		                   'id', ...
+		                   'compartment', ...
+		                   'initialAmount', ...
+		                   'initialConcentration', ...
+		                   'substanceUnits', ...
+		                   'spatialSizeUnits', ...
+		                   'hasOnlySubstanceUnits', ...
+		                   'boundaryCondition', ...
+		                   'charge', ...
+		                   'constant', ...
+		                   'isSetInitialAmount', ...
+		                   'isSetInitialConcentration', ...
+		                   'isSetCharge', ...
+		                 };
+		nNumberFields = 18;
+	elseif (version == 2)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'name', ...
+		                   'id', ...
+		                   'speciesType', ...
+		                   'compartment', ...
+		                   'initialAmount', ...
+		                   'initialConcentration', ...
+		                   'substanceUnits', ...
+		                   'spatialSizeUnits', ...
+		                   'hasOnlySubstanceUnits', ...
+		                   'boundaryCondition', ...
+		                   'charge', ...
+		                   'constant', ...
+		                   'isSetInitialAmount', ...
+		                   'isSetInitialConcentration', ...
+		                   'isSetCharge', ...
+		                 };
+		nNumberFields = 19;
+	elseif (version == 3)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'name', ...
+		                   'id', ...
+		                   'speciesType', ...
+		                   'compartment', ...
+		                   'initialAmount', ...
+		                   'initialConcentration', ...
+		                   'substanceUnits', ...
+		                   'hasOnlySubstanceUnits', ...
+		                   'boundaryCondition', ...
+		                   'charge', ...
+		                   'constant', ...
+		                   'isSetInitialAmount', ...
+		                   'isSetInitialConcentration', ...
+		                   'isSetCharge', ...
+		                 };
+		nNumberFields = 19;
+	elseif (version == 4)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'name', ...
+		                   'id', ...
+		                   'speciesType', ...
+		                   'compartment', ...
+		                   'initialAmount', ...
+		                   'initialConcentration', ...
+		                   'substanceUnits', ...
+		                   'hasOnlySubstanceUnits', ...
+		                   'boundaryCondition', ...
+		                   'charge', ...
+		                   'constant', ...
+		                   'isSetInitialAmount', ...
+		                   'isSetInitialConcentration', ...
+		                   'isSetCharge', ...
+		                 };
+		nNumberFields = 19;
+	end;
+elseif (level == 3)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'name', ...
+		                   'id', ...
+		                   'compartment', ...
+		                   'initialAmount', ...
+		                   'initialConcentration', ...
+		                   'substanceUnits', ...
+		                   'hasOnlySubstanceUnits', ...
+		                   'boundaryCondition', ...
+		                   'constant', ...
+		                   'isSetInitialAmount', ...
+		                   'isSetInitialConcentration', ...
+		                   'conversionFactor', ...
+		                 };
+		nNumberFields = 17;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getSpeciesReferenceFieldnames(level, ...
+                                                                         version)
+
+
+
+
+
+
+
+
+
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+if (level == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'species', ...
+		                   'stoichiometry', ...
+		                   'denominator', ...
+		                 };
+		nNumberFields = 6;
+elseif (level == 2)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'species', ...
+		                   'stoichiometry', ...
+		                   'denominator', ...
+		                   'stoichiometryMath', ...
+		                 };
+		nNumberFields = 8;
+	elseif (version == 2)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'species', ...
+		                   'id', ...
+		                   'name', ...
+		                   'sboTerm', ...
+		                   'stoichiometry', ...
+		                   'stoichiometryMath', ...
+		                 };
+		nNumberFields = 10;
+	elseif (version == 3)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'species', ...
+		                   'id', ...
+		                   'name', ...
+		                   'stoichiometry', ...
+		                   'stoichiometryMath', ...
+		                 };
+		nNumberFields = 10;
+	elseif (version == 4)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'species', ...
+		                   'id', ...
+		                   'name', ...
+		                   'stoichiometry', ...
+		                   'stoichiometryMath', ...
+		                 };
+		nNumberFields = 10;
+	end;
+elseif (level == 3)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'species', ...
+		                   'id', ...
+		                   'name', ...
+		                   'stoichiometry', ...
+		                   'constant', ...
+		                   'isSetStoichiometry', ...
+		                 };
+		nNumberFields = 11;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getSpeciesTypeFieldnames(level, ...
+                                                                    version)
+
+
+
+
+
+
+
+
+
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+if (level == 1)
+	SBMLfieldnames = [];
+	nNumberFields = 0;
+elseif (level == 2)
+	if (version == 1)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+	elseif (version == 2)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'name', ...
+		                   'id', ...
+		                 };
+		nNumberFields = 6;
+	elseif (version == 3)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'name', ...
+		                   'id', ...
+		                 };
+		nNumberFields = 7;
+	elseif (version == 4)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'name', ...
+		                   'id', ...
+		                 };
+		nNumberFields = 7;
+	end;
+elseif (level == 3)
+	if (version == 1)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getStoichiometryMathFieldnames(level, ...
+                                                                          version)
+
+
+
+
+
+
+
+
+
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+if (level == 1)
+	SBMLfieldnames = [];
+	nNumberFields = 0;
+elseif (level == 2)
+	if (version == 1)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+	elseif (version == 2)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+	elseif (version == 3)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'math', ...
+		                 };
+		nNumberFields = 6;
+	elseif (version == 4)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'math', ...
+		                 };
+		nNumberFields = 6;
+	end;
+elseif (level == 3)
+	if (version == 1)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getTriggerFieldnames(level, ...
+                                                                version)
+
+
+
+
+
+
+
+
+
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+if (level == 1)
+	SBMLfieldnames = [];
+	nNumberFields = 0;
+elseif (level == 2)
+	if (version == 1)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+	elseif (version == 2)
+		SBMLfieldnames = [];
+		nNumberFields = 0;
+	elseif (version == 3)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'math', ...
+		                 };
+		nNumberFields = 6;
+	elseif (version == 4)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'math', ...
+		                 };
+		nNumberFields = 6;
+	end;
+elseif (level == 3)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'persistent', ...
+		                   'initialValue', ...
+		                   'math', ...
+		                 };
+		nNumberFields = 8;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getUnitDefinitionFieldnames(level, ...
+                                                                       version)
+
+
+
+
+
+
+
+
+
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+if (level == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'name', ...
+		                   'unit', ...
+		                 };
+		nNumberFields = 5;
+elseif (level == 2)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'name', ...
+		                   'id', ...
+		                   'unit', ...
+		                 };
+		nNumberFields = 7;
+	elseif (version == 2)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'name', ...
+		                   'id', ...
+		                   'unit', ...
+		                 };
+		nNumberFields = 7;
+	elseif (version == 3)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'name', ...
+		                   'id', ...
+		                   'unit', ...
+		                 };
+		nNumberFields = 8;
+	elseif (version == 4)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'name', ...
+		                   'id', ...
+		                   'unit', ...
+		                 };
+		nNumberFields = 8;
+	end;
+elseif (level == 3)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'name', ...
+		                   'id', ...
+		                   'unit', ...
+		                 };
+		nNumberFields = 8;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getUnitFieldnames(level, ...
+                                                             version)
+
+
+
+
+
+
+
+
+
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+if (level == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'kind', ...
+		                   'exponent', ...
+		                   'scale', ...
+		                 };
+		nNumberFields = 6;
+elseif (level == 2)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'kind', ...
+		                   'exponent', ...
+		                   'scale', ...
+		                   'multiplier', ...
+		                   'offset', ...
+		                 };
+		nNumberFields = 9;
+	elseif (version == 2)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'kind', ...
+		                   'exponent', ...
+		                   'scale', ...
+		                   'multiplier', ...
+		                 };
+		nNumberFields = 8;
+	elseif (version == 3)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'kind', ...
+		                   'exponent', ...
+		                   'scale', ...
+		                   'multiplier', ...
+		                 };
+		nNumberFields = 9;
+	elseif (version == 4)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'kind', ...
+		                   'exponent', ...
+		                   'scale', ...
+		                   'multiplier', ...
+		                 };
+		nNumberFields = 9;
+	end;
+elseif (level == 3)
+	if (version == 1)
+		SBMLfieldnames = { 'typecode', ...
+		                   'metaid', ...
+		                   'notes', ...
+		                   'annotation', ...
+		                   'sboTerm', ...
+		                   'kind', ...
+		                   'exponent', ...
+		                   'scale', ...
+		                   'multiplier', ...
+		                 };
+		nNumberFields = 9;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getFBCModelFieldnames(level, ...
+                                                         version, pkgVersion)
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+% need a check on package version
+
+if (level == 1)
+	SBMLfieldnames = [];
+	nNumberFields = 0;
+elseif (level == 2)
+	SBMLfieldnames = [];
+	nNumberFields = 0;
+elseif (level == 3)
+	if (version == 1)
+    if (pkgVersion == 1)
+      SBMLfieldnames = { 'fbc_version', ...
+                         'fbc_fluxBound', ...
+                         'fbc_objective', ...
+                         'fbc_activeObjective', ...
+                       };
+      nNumberFields = 4;
+    end;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getFBCSpeciesFieldnames(level, ...
+                                                         version, pkgVersion)
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+% need a check on package version
+
+if (level == 1)
+	SBMLfieldnames = [];
+	nNumberFields = 0;
+elseif (level == 2)
+	SBMLfieldnames = [];
+	nNumberFields = 0;
+elseif (level == 3)
+	if (version == 1)
+    if (pkgVersion == 1)
+      SBMLfieldnames = { 'fbc_charge', ...
+                         'isSetfbc_charge', ...
+                         'fbc_chemicalFormula', ...
+                         'fbc_version', ...
+                       };
+      nNumberFields = 4;
+    end;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getFluxBoundFieldnames(level, ...
+                                                         version, pkgVersion)
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+% need a check on package version
+
+if (level == 1)
+	SBMLfieldnames = [];
+	nNumberFields = 0;
+elseif (level == 2)
+	SBMLfieldnames = [];
+	nNumberFields = 0;
+elseif (level == 3)
+	if (version == 1)
+    if (pkgVersion == 1)
+      SBMLfieldnames = { 'typecode', ...
+                         'metaid', ...
+                         'notes', ...
+                         'annotation', ...
+                         'sboTerm', ...
+                         'fbc_id', ...
+                         'fbc_reaction', ...
+                         'fbc_operation', ...
+                         'fbc_value', ...
+                         'isSetfbc_value', ...
+                         'level', ...
+                         'version', ...
+                         'fbc_version', ...
+                       };
+      nNumberFields = 13;
+    end;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getFluxObjectiveFieldnames(level, ...
+                                                         version, pkgVersion)
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+% need a check on package version
+
+if (level == 1)
+	SBMLfieldnames = [];
+	nNumberFields = 0;
+elseif (level == 2)
+	SBMLfieldnames = [];
+	nNumberFields = 0;
+elseif (level == 3)
+	if (version == 1)
+    if (pkgVersion == 1)
+      SBMLfieldnames = { 'typecode', ...
+                         'metaid', ...
+                         'notes', ...
+                         'annotation', ...
+                         'sboTerm', ...
+                         'fbc_reaction', ...
+                         'fbc_coefficient', ...
+                         'isSetfbc_coefficient', ...
+                         'level', ...
+                         'version', ...
+                         'fbc_version', ...
+                       };
+      nNumberFields = 11;
+    end;
+	end;
+end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function [SBMLfieldnames, nNumberFields] = getObjectiveFieldnames(level, ...
+                                                         version, pkgVersion)
+
+if (~isValidLevelVersionCombination(level, version))
+  error ('invalid level/version combination');
+end;
+
+% need a check on package version
+
+if (level == 1)
+	SBMLfieldnames = [];
+	nNumberFields = 0;
+elseif (level == 2)
+	SBMLfieldnames = [];
+	nNumberFields = 0;
+elseif (level == 3)
+	if (version == 1)
+    if (pkgVersion == 1)
+      SBMLfieldnames = { 'typecode', ...
+                         'metaid', ...
+                         'notes', ...
+                         'annotation', ...
+                         'sboTerm', ...
+                         'fbc_id', ...
+                         'fbc_type', ...
+                         'fbc_fluxObjective', ...
+                         'level', ...
+                         'version', ...
+                         'fbc_version', ...
+                       };
+      nNumberFields = 11;
+    end;
+	end;
+end;
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/auxiliary/isoctave.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/auxiliary/isoctave.m
new file mode 100644
index 0000000000000000000000000000000000000000..fadef931834e2e09e433078c1e61e2e5d7fa1ae0
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/THIRD_PARTY_SOFTWARE/SBMLimportExport/auxiliary/isoctave.m
@@ -0,0 +1,27 @@
+function t=isoctave()
+%ISOCTAVE  True if the operating environment is octave.
+%   Usage: t=isoctave();
+%
+%   Returns 1 if the operating environment is octave, otherwise
+%   0 (Matlab)
+
+% @file    isoctave.m
+% @brief   Returns true if using octave
+% @author  Sarah Keating
+% 
+%
+% ISOCTAVE.M
+%
+% COPYRIGHT : (c) NUHAG, Dept.Math., University of Vienna, AUSTRIA
+%             http://nuhag.eu/
+%             Permission is granted to modify and re-distribute this
+%             code in any manner as long as this notice is preserved.
+%             All standard disclaimers apply.
+%
+
+if exist('OCTAVE_VERSION')
+  % Only Octave has this variable.
+  t='1';
+else
+  t='0';
+end;
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/optimization/SSmSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/optimization/SSmSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..da4095941adc042b0b189507c86842d9bb66ddcd
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/optimization/SSmSB.m
@@ -0,0 +1,359 @@
+function [X,FVAL,result] = SSmSB(varargin)
+% SSmSB: Interface function to a Global optimization algorithm for 
+% MINLP's based on Scatter Search. 
+%
+% Note that the optimization method itself is not included in 
+% the toolbox but that it can be downloaded from
+% http://www.iim.csic.es/~gingproc/software.html
+%
+%   SSm attempts to solve problems of the form:
+%       min F(x)  subject to:  ceq(x) = 0 (equality constraints)
+%        x                     c_L <= c(x) <= c_U (inequality constraints)
+%                              x_L <= x <= x_U (bounds on the decision variables)            
+%
+% If you use SSm and publish the results, please cite the following papers:
+%
+% Egea, J.A., M. Rodriguez-Fernandez, J. R. Banga and R. Mart� (2007) Scatter 
+% Search for chemical and bioprocess optimization. Journal of Global Optimization 
+% 37(3):481-503.
+%
+% Rodriguez-Fernandez, M., J. A. Egea and J. R. Banga (2006) Novel Metaheuristic for Parameter 
+% Estimation in Nonlinear Dynamic Biological Systems. BMC Bioinformatics 7:483.
+%
+% This interface function addresses the SSm package:
+%   Function   : SSm beta 3.3.1
+%   Written by : Process Engineering Group IIM-CSIC (jegea@iim.csic.es)
+%   Created on : 15/06/2005
+%   Last Update: 12/03/2008
+%   Email      : gingproc@iim.csic.es
+%   (c) CSIC, Spanish Council for Scientific Research
+%
+% USAGE:
+% ======
+% [info] = SSmSB()
+% [X,FVAL,result] = SSmSB(FUN,X,OPTIONS)
+%
+% FUN: Function to optimize
+% X: Starting Guess (Not strictly required but kept for the sake of
+%    compatible optimization function calls)
+% OPTIONS: structure containing options for the algorithm:
+%        OPTIONS.vtr: cost function value to reach
+%        OPTIONS.highbounds: vector containing upper bounds for parameters
+%           Instead of a vector highbounds can also be a scalar > 1. In the
+%           latter case the highbounds are determined by multiplying this
+%           scalar to the initial parameter guess X. This latter case works
+%           only for positive X(i) ... if negative present then the user
+%           needs to specify a whole highbounds vector. 
+%        OPTIONS.lowbounds: vector containing lower bounds for parameters.
+%           Instead of a vector lowbounds can also be a scalar < 1. In the
+%           latter case the lowbounds are determined by multiplying this
+%           scalar to the initial parameter guess X. This latter case works
+%           only for positive X(i) ... if negative present then the user
+%           needs to specify a whole lowbounds vector. 
+% User options
+%        OPTIONS.maxfunevals: Maximum number of function evaluations
+%        OPTIONS.maxtime: Maximum time (in minutes) for optimization
+%        OPTIONS.silent: =0: output of info, =1: no output
+%        OPTIONS.plot. Plots convergence curves: 
+%               0-Deactivated,
+%               1-Plot curves on line,
+%               2-Plot final results
+%        OPTIONS.weight: Weight that multiplies the penalty term added
+%           to the objective function in constrained problems
+%        OPTIONS.tolc: Maximum absolute violation of the constraints.
+%        OPTIONS.log_var: Indexes of the variables which will be used
+%           to generate diverse solutions in different orders of magnitude
+% Global options
+%        OPTIONS.dim_refset: Number of elements in Refset
+%        OPTIONS.ndiverse: Number of solutions generated by the
+%           diversificator 
+%        OPTIONS.initiate: Type of Refset initialization
+%               0: Take bounds, middle point and fill by euclidean distance
+%               1: Evaluate all the diverse solutions,take the dim_refset/2 best
+%                  solutions and fill by euclidean distance
+%        OPTIONS.combination: Type of combination of Refset elements
+%               1: hyper-rectangles
+%               2: linear combinations
+%        OPTIONS.regenerate: Type of Refset regeneration 
+%               1: Regeneration by distance diversity
+%               2: Regeneration by direction diversity
+%               3: Randomly alternates 1 and 2
+%        OPTIONS.delete: Maximum number of Refset elements
+%           deleted when regenerating Refset
+%               'standard': Maximum deleted elements=dim_refset/2 
+%                           (half of the elements)
+%               'aggressive': Delete dim_refset-1 (all of them except the 
+%                           best solution found)
+%        OPTIONS.intens: Iteration interval between intensifications
+%        OPTIONS.tolfun: Function tolerance for joining the Refset
+%        OPTIONS.diverse_criteria: Criterion for diversification in the Refset
+%               1: euclidean distance
+%               2: tolerances
+%        OPTIONS.tolx: Variable tolerance for joining the Refset when 
+%           the euclidean distance is deactivated        
+% Local options
+%        OPTIONS.local.solver: Choose local solver:
+%               0: local search off, 'constrnew','fminsearch','nomad','solnp',
+%               'n2fb','dn2fb','dhc','fsqp','ipopt', 'misqp','lsqnonlin'
+%        OPTIONS.local.n1: Number of function evaluations before applying
+%           local search for the 1st time
+%        OPTIONS.local.n2: Minimum number of function evaluations in the 
+%           global phase between 2 local calls
+%        OPTIONS.local.finish: Local solver (see above) to be used in the
+%           final refinement.
+%        OPTIONS.local.bestx: (=1): This option ignores all the local search
+%           filters and perform a local search only when the best function
+%           value has been improved. This is useful for those problems in
+%           which local searches are not providing satisfactory solutions
+%           but still it can help a bit more than pure global search.
+%           (=0): option deactivated.
+%
+% Output Arguments:
+% =================
+% info:     calling the function w/o input argument returns information about
+%           the options and a flag indicating if the algorithm can handle
+%           constraints or not
+% X:        Found solution
+% FVAL:     Value of the function FUN at X
+% result:   Structure containing results
+%
+%       result.fbest                   = Best objective function value
+%                                         found after the optimization
+%       result.xbest                   = Vector providing the best
+%                                         function value
+%       result.cpu_time                = Time in seconds consumed in the
+%                                         optimization
+%       result.f                       = Vector containing the best
+%                                         objective function value after each
+%                                         iteration
+%       result.x                       = Matrix containing the best vector
+%                                         after each iteration
+%       result.time                    = Vector containing the cpu time
+%                                         consumed after each iteration
+%       result.neval                   = Vector containing the number of
+%                                         function evaluations after each
+%                                         iteration
+%       result.numeval                 = Number of function evaluations
+%       result.local_solutions         = Local solutions found by the
+%                                         local solver (in rows)
+%       result.local_solutions_values  = Function values of the local
+%                                         solutions
+%       result.end_crit                = Criterion to finish the
+%                                         optimization
+%                                         1: Maximal number of function
+%                                         evaluations achieved
+%                                         2: Maximum allowed CPU Time
+%                                         achieved
+%                                         3: Value to reach achieved
+%
+% DEFAULT VALUES:
+% ===============
+% OPTIONS.lowbounds:        0.1  => lowbounds = 0.1*X 
+% OPTIONS.highbounds:       10  => highbounds = 10*X 
+% OPTIONS.maxfunevals:      400*ndim
+% OPTIONS.maxtime:          120 (minutes)        
+% OPTIONS.silent:           0          
+% OPTIONS.plot              0
+% OPTIONS.weight:           1e6
+% OPTIONS.tolc:             1e-5
+% OPTIONS.log_var:          [1:ndim] (all variables)
+%
+% OPTIONS.dim_refset:       'auto'
+% OPTIONS.ndiverse:         10*ndim
+% OPTIONS.initiate:         1
+% OPTIONS.combination:      1
+% OPTIONS.regenerate:       3
+% OPTIONS.delete:           'standard'
+% OPTIONS.intens:           10
+% OPTIONS.tolfun:           1e-4
+% OPTIONS.diverse_criteria: 1
+% OPTIONS.tolx:             1e-3      
+%
+% OPTIONS.local.solver:     'dn2fb'
+% OPTIONS.local.n1:         100*ndim
+% OPTIONS.local.n2:         200*ndim
+% OPTIONS.local.finish:     'dn2fb'
+% OPTIONS.local.bestx:      0
+
+% Information:
+% ============
+% This license information is valid only for this interface function.
+%
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+academicWarningSB
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF SSm IS PRESENT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(which('ssm_kernel')),
+    error(sprintf('SSm is not installed on your system! SSmSB is only the interface function.\nYou can download SSm from: http://www.iim.csic.es/~gingproc/software.html.\nAfter installation you can use the SSmSB interface function included in the SBTOOLBOX2.'));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ASSIGNING DEFAULT OUTPUT VALUES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+X = [];
+FVAL = [];
+result = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 0,
+    X.name = 'SSmSB';
+    X.constrained = 1;
+    X.description = 'Scatter Search based optimization (global)';
+    X.defaultOptions.names = {'maxfunevals', 'maxtime'};
+    X.defaultOptions.values = {'20000','500'};
+    X.defaultOptions.description = {'Maximum number of function evaluations', 'Maximum time in minutes'};
+    return
+elseif nargin == 2,
+    FUN = varargin{1};
+    X = varargin{2};
+    OPTIONS = [];
+elseif nargin == 3,
+    FUN = varargin{1};
+    X = varargin{2};
+    OPTIONS = varargin{3};
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Set default values
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ndim = length(X);
+lowbounds = 0.1*X;
+highbounds = 10*X;
+
+%%%%%%%%%%%%%%
+% SSm options
+%%%%%%%%%%%%%%
+opts = [];
+% user options
+opts.maxeval = 400*ndim;    % Maximum number of function evaluations 
+opts.maxtime = 120*60;      % Maximum CPU time in seconds
+opts.iterprint = 1;         % Print each iteration on screen
+opts.plot      = 0;         % Plots convergence curves: 0-Deactivated,
+                            % 1-Plot curves on line, 2-Plot final results
+opts.weight    = 1e6;       % Weight that multiplies the penalty term added
+                            % to the objective function in constrained
+                            % problems
+opts.tolc      = 1e-5;                            
+opts.log_var   = [];        % Indexes of the variables which will be used
+                            % to generate diverse solutions in different
+                            % orders of magnitude global options
+% global options
+opts.dim_refset = 'auto';
+opts.ndiverse = 10*ndim;
+opts.initiate = 1;
+opts.combination = 1;
+opts.regenerate = 3;
+opts.delete = 'standard';
+opts.intens = 10;
+opts.tolf = 1e-4;           % Function tolerance for joining the Refset
+opts.diverse_criteria = 1;  % Criterion for diversification in the Refset
+                            %    1: euclidean distance
+                            %    2: tolerances
+opts.tolx = 1e-3;           % Variable tolerance for joining the Refset when 
+                            % the euclidean distance is deactivated        
+% local options
+opts.local.solver = 'dn2fb';      % Choose local solver:
+                                  % 0: local search off, 'constrnew',
+                                  % 'fminsearch','nomad','solnp',
+                                  % 'n2fb','dn2fb','dhc','fsqp','ipopt',
+                                  % 'misqp','lsqnonlin'
+opts.local.n1 = 100*ndim;   % Number of function evaluations before applying
+                            % local search for the 1st time
+opts.local.n2 = 200*ndim;   % Minimum number of function evaluations in the 
+                            % global phase between 2 local calls         
+opts.local.finish = 'dn2fb'; % Local solver for final refinement                            
+opts.local.bestx = 0; 
+                           
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% options - Structure containing optional settings
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% user options
+try opts.maxeval            = OPTIONS.maxfunevals; catch, end; 
+try opts.maxtime            = 60*OPTIONS.maxtime; catch, end; % SSm expects seconds
+try opts.iterprint          = ~OPTIONS.silent; catch, end;
+try opts.plot           	= OPTIONS.plot; catch, end;
+try opts.weight             = OPTIONS.weight; catch, end;
+try opts.log_var            = OPTIONS.log_var; catch, end;
+% global options
+try opts.dim_refset         = OPTIONS.dim_refset; catch, end; 
+try opts.ndiverse           = OPTIONS.ndiverse; catch, end; 
+try opts.initiate           = OPTIONS.initiate; catch, end; 
+try opts.combination        = OPTIONS.combination; catch, end; 
+try opts.regenerate         = OPTIONS.regenerate; catch, end; 
+try opts.delete             = OPTIONS.delete; catch, end; 
+try opts.intens             = OPTIONS.intens; catch, end; 
+try opts.tolf               = OPTIONS.tolfun; catch, end; 
+try opts.diverse_criteria   = OPTIONS.diverse_criteria; catch, end;
+try opts.tolx               = OPTIONS.tolx; catch, end;
+% local options
+try opts.local.solver       = OPTIONS.local.solver ; catch, end;
+try opts.local.n1           = OPTIONS.local.n1; catch, end;
+try opts.local.n2           = OPTIONS.local.n2; catch, end;
+try opts.local.finish       = OPTIONS.local.finish; catch, end;
+try opts.local.bestx        = OPTIONS.local.bestx; catch, end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% problem - Structure containing problem settings
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[lowbounds, highbounds] = handleLowHighBoundsSB(OPTIONS,X,lowbounds,highbounds);
+if ~ischar(FUN),
+    FUN = func2str(FUN);    % convert function handle to string
+end
+problem = [];
+problem.f = FUN;            % Name of the file containing the objective function
+problem.x_L = lowbounds;    % Lower bounds of decision variables
+problem.x_U = highbounds;   % Upper bounds of decision variables
+problem.x_0 = X;            % Initial point(s) (optional)
+try problem.vtr = OPTIONS.vtr; catch, end; % value to reach
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% call SSm 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+disp('If you use SSm and publish the results, please cite the following papers:');
+disp(' ');
+disp('Egea, J.A., M. Rodriguez-Fernandez, J. R. Banga and R. Mart� (2007) Scatter');
+disp('Search for chemical and bioprocess optimization. Journal of Global Optimization');
+disp('37(3):481-503.');
+disp(' ');
+disp('Rodriguez-Fernandez, M., J. A. Egea and J. R. Banga (2006) Novel Metaheuristic');
+disp('for Parameter Estimation in Nonlinear Dynamic Biological Systems.');
+disp('BMC Bioinformatics 7:483.');
+useFAST = 0;
+if isfield(OPTIONS,'fast'),
+    if OPTIONS.fast == 1,
+        useFAST = 1;
+    end
+end
+if useFAST,
+    result = fssm_kernel(problem,opts);
+else
+    result = ssm_kernel(problem,opts);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% handle output
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+X = result.xbest;
+FVAL = result.fbest;
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/optimization/fSSmSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/optimization/fSSmSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..c02535ea0565360cd40ca9b7f098e6c42e46dbe4
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/optimization/fSSmSB.m
@@ -0,0 +1,362 @@
+function [X,FVAL,result] = fSSmSB(varargin)
+% fSSmSB: Interface function to a Global optimization algorithm for 
+% MINLP's based on Scatter Search ("fast" version). 
+%
+% Note that the optimization method itself is not included in 
+% the toolbox but that it can be downloaded from
+% http://www.iim.csic.es/~gingproc/software.html
+%
+%   fSSm attempts to solve problems of the form:
+%       min F(x)  subject to:  ceq(x) = 0 (equality constraints)
+%        x                     c_L <= c(x) <= c_U (inequality constraints)
+%                              x_L <= x <= x_U (bounds on the decision variables)            
+%
+% If you use fSSm and publish the results, please cite the following papers:
+%
+% Egea, J.A., M. Rodriguez-Fernandez, J. R. Banga and R. Mart� (2007) Scatter 
+% Search for chemical and bioprocess optimization. Journal of Global Optimization 
+% 37(3):481-503.
+%
+% Rodriguez-Fernandez, M., J. A. Egea and J. R. Banga (2006) Novel Metaheuristic for Parameter 
+% Estimation in Nonlinear Dynamic Biological Systems. BMC Bioinformatics 7:483.
+%
+% This interface function addresses the (f)SSm package:
+%   Function   : SSm beta 3.3.1
+%   Written by : Process Engineering Group IIM-CSIC (jegea@iim.csic.es)
+%   Created on : 15/06/2005
+%   Last Update: 12/03/2008
+%   Email      : gingproc@iim.csic.es
+%   (c) CSIC, Spanish Council for Scientific Research
+%
+% USAGE:
+% ======
+% [info] = fSSmSB()
+% [X,FVAL,result] = fSSmSB(FUN,X,OPTIONS)
+%
+% FUN: Function to optimize
+% X: Starting Guess (Not strictly required but kept for the sake of
+%    compatible optimization function calls)
+% OPTIONS: structure containing options for the algorithm:
+%        OPTIONS.vtr: cost function value to reach
+%        OPTIONS.highbounds: vector containing upper bounds for parameters
+%           Instead of a vector highbounds can also be a scalar > 1. In the
+%           latter case the highbounds are determined by multiplying this
+%           scalar to the initial parameter guess X. This latter case works
+%           only for positive X(i) ... if negative present then the user
+%           needs to specify a whole highbounds vector. 
+%        OPTIONS.lowbounds: vector containing lower bounds for parameters.
+%           Instead of a vector lowbounds can also be a scalar < 1. In the
+%           latter case the lowbounds are determined by multiplying this
+%           scalar to the initial parameter guess X. This latter case works
+%           only for positive X(i) ... if negative present then the user
+%           needs to specify a whole lowbounds vector. 
+% User options
+%        OPTIONS.maxfunevals: Maximum number of function evaluations
+%        OPTIONS.maxtime: Maximum time (in minutes) for optimization
+%        OPTIONS.silent: =0: output of info, =1: no output
+%        OPTIONS.plot. Plots convergence curves: 
+%               0-Deactivated,
+%               1-Plot curves on line,
+%               2-Plot final results
+%        OPTIONS.weight: Weight that multiplies the penalty term added
+%           to the objective function in constrained problems
+%        OPTIONS.tolc: Maximum absolute violation of the constraints.
+%        OPTIONS.log_var: Indexes of the variables which will be used
+%           to generate diverse solutions in different orders of magnitude
+% Global options
+%        OPTIONS.dim_refset: Number of elements in Refset
+%        OPTIONS.ndiverse: Number of solutions generated by the
+%           diversificator 
+%        OPTIONS.initiate: Type of Refset initialization
+%               0: Take bounds, middle point and fill by euclidean distance
+%               1: Evaluate all the diverse solutions,take the dim_refset/2 best
+%                  solutions and fill by euclidean distance
+%        OPTIONS.combination: Type of combination of Refset elements
+%               1: hyper-rectangles
+%               2: linear combinations
+%        OPTIONS.regenerate: Type of Refset regeneration 
+%               1: Regeneration by distance diversity
+%               2: Regeneration by direction diversity
+%               3: Randomly alternates 1 and 2
+%        OPTIONS.delete: Maximum number of Refset elements
+%           deleted when regenerating Refset
+%               'standard': Maximum deleted elements=dim_refset/2 
+%                           (half of the elements)
+%               'aggressive': Delete dim_refset-1 (all of them except the 
+%                           best solution found)
+%        OPTIONS.intens: Iteration interval between intensifications
+%        OPTIONS.tolfun: Function tolerance for joining the Refset
+%        OPTIONS.diverse_criteria: Criterion for diversification in the Refset
+%               1: euclidean distance
+%               2: tolerances
+%        OPTIONS.tolx: Variable tolerance for joining the Refset when 
+%           the euclidean distance is deactivated        
+% Local options
+%        OPTIONS.local.solver: Choose local solver:
+%               0: local search off, 'constrnew','fminsearch','nomad','solnp',
+%               'n2fb','dn2fb','dhc','fsqp','ipopt', 'misqp','lsqnonlin'
+%        OPTIONS.local.n1: Number of function evaluations before applying
+%           local search for the 1st time
+%        OPTIONS.local.n2: Minimum number of function evaluations in the 
+%           global phase between 2 local calls
+%        OPTIONS.local.finish: Local solver to be used in the final
+%           refinement.
+%        OPTIONS.local.bestx: (=1): This option ignores all the local search
+%           filters and perform a local search only when the best function
+%           value has been improved. This is useful for those problems in
+%           which local searches are not providing satisfactory solutions
+%           but still it can help a bit more than pure global search.
+%           (=0): option deactivated.
+%
+% Output Arguments:
+% =================
+% info:     calling the function w/o input argument returns information about
+%           the options and a flag indicating if the algorithm can handle
+%           constraints or not
+% X:        Found solution
+% FVAL:     Value of the function FUN at X
+% result:   Structure containing results
+%
+%       result.fbest                   = Best objective function value
+%                                         found after the optimization
+%       result.xbest                   = Vector providing the best
+%                                         function value
+%       result.cpu_time                = Time in seconds consumed in the
+%                                         optimization
+%       result.f                       = Vector containing the best
+%                                         objective function value after each
+%                                         iteration
+%       result.x                       = Matrix containing the best vector
+%                                         after each iteration
+%       result.time                    = Vector containing the cpu time
+%                                         consumed after each iteration
+%       result.neval                   = Vector containing the number of
+%                                         function evaluations after each
+%                                         iteration
+%       result.numeval                 = Number of function evaluations
+%       result.local_solutions         = Local solutions found by the
+%                                         local solver (in rows)
+%       result.local_solutions_values  = Function values of the local
+%                                         solutions
+%       result.end_crit                = Criterion to finish the
+%                                         optimization
+%                                         1: Maximal number of function
+%                                         evaluations achieved
+%                                         2: Maximum allowed CPU Time
+%                                         achieved
+%                                         3: Value to reach achieved
+%
+% DEFAULT VALUES:
+% ===============
+% OPTIONS.lowbounds:        0.1  => lowbounds = 0.1*X 
+% OPTIONS.highbounds:       10  => highbounds = 10*X 
+% OPTIONS.maxfunevals:      400*ndim
+% OPTIONS.maxtime:          120 (minutes)        
+% OPTIONS.silent:           0          
+% OPTIONS.plot              0
+% OPTIONS.weight:           1e6
+% OPTIONS.tolc:             1e-5
+% OPTIONS.log_var:          [1:ndim] (all variables)
+%
+% OPTIONS.dim_refset:       'auto'
+% OPTIONS.ndiverse:         10*ndim
+% OPTIONS.initiate:         1
+% OPTIONS.combination:      1
+% OPTIONS.regenerate:       3
+% OPTIONS.delete:           'standard'
+% OPTIONS.intens:           10
+% OPTIONS.tolfun:           1e-4
+% OPTIONS.diverse_criteria: 1
+% OPTIONS.tolx:             1e-3      
+%
+% OPTIONS.local.solver:     'dn2fb'
+% OPTIONS.local.n1:         100*ndim
+% OPTIONS.local.n2:         200*ndim
+% OPTIONS.local.finish:     'dn2fb'
+% OPTIONS.local.bestx:      0
+
+% Information:
+% ============
+% This license information is valid only for this interface function.
+%
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+academicWarningSB
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF SSm IS PRESENT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(which('ssm_kernel')),
+    error(sprintf('SSm is not installed on your system! SSmSB is only the interface function.\nYou can download SSm from: http://www.iim.csic.es/~gingproc/software.html.\nAfter installation you can use the SSmSB interface function included in the SBTOOLBOX2.'));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ASSIGNING DEFAULT OUTPUT VALUES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+X = [];
+FVAL = [];
+result = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 0,
+    X.name = 'fSSmSB';
+    X.constrained = 1;
+    X.description = '(fast) Scatter Search based optimization (global)';
+    X.defaultOptions.names = {'maxfunevals', 'maxtime'};
+    X.defaultOptions.values = {'20000','500'};
+    X.defaultOptions.description = {'Maximum number of function evaluations', 'Maximum time in minutes'};
+    return
+elseif nargin == 2,
+    FUN = varargin{1};
+    X = varargin{2};
+    OPTIONS = [];
+elseif nargin == 3,
+    FUN = varargin{1};
+    X = varargin{2};
+    OPTIONS = varargin{3};
+else
+    error('Incorrect number of input arguments.');
+end
+% always use the fast version 
+OPTIONS.fast = 1;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Set default values
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ndim = length(X);
+lowbounds = 0.1*X;
+highbounds = 10*X;
+
+%%%%%%%%%%%%%%
+% SSm options
+%%%%%%%%%%%%%%
+opts = [];
+% user options
+opts.maxeval = 400*ndim;    % Maximum number of function evaluations 
+opts.maxtime = 120*60;      % Maximum CPU time in seconds
+opts.iterprint = 1;         % Print each iteration on screen
+opts.plot      = 0;         % Plots convergence curves: 0-Deactivated,
+                            % 1-Plot curves on line, 2-Plot final results
+opts.weight    = 1e6;       % Weight that multiplies the penalty term added
+                            % to the objective function in constrained
+                            % problems
+opts.tolc      = 1e-5;                            
+opts.log_var   = [];        % Indexes of the variables which will be used
+                            % to generate diverse solutions in different
+                            % orders of magnitude global options
+% global options
+opts.dim_refset = 'auto';
+opts.ndiverse = 10*ndim;
+opts.initiate = 1;
+opts.combination = 1;
+opts.regenerate = 3;
+opts.delete = 'standard';
+opts.intens = 10;
+opts.tolf = 1e-4;           % Function tolerance for joining the Refset
+opts.diverse_criteria = 1;  % Criterion for diversification in the Refset
+                            %    1: euclidean distance
+                            %    2: tolerances
+opts.tolx = 1e-3;           % Variable tolerance for joining the Refset when 
+                            % the euclidean distance is deactivated        
+% local options
+opts.local.solver = 'dn2fb';      % Choose local solver:
+                                  % 0: local search off, 'constrnew',
+                                  % 'fminsearch','nomad','solnp',
+                                  % 'n2fb','dn2fb','dhc','fsqp','ipopt',
+                                  % 'misqp','lsqnonlin'
+opts.local.n1 = 100*ndim;   % Number of function evaluations before applying
+                            % local search for the 1st time
+opts.local.n2 = 200*ndim;   % Minimum number of function evaluations in the 
+                            % global phase between 2 local calls         
+opts.local.finish = 'dn2fb'; % Local solver for final refinement                            
+opts.local.bestx = 0; 
+                            
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% options - Structure containing optional settings
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% user options
+try opts.maxeval            = OPTIONS.maxfunevals; catch, end; 
+try opts.maxtime            = 60*OPTIONS.maxtime; catch, end; % SSm expects seconds
+try opts.iterprint          = ~OPTIONS.silent; catch, end;
+try opts.plot           	= OPTIONS.plot; catch, end;
+try opts.weight             = OPTIONS.weight; catch, end;
+try opts.tolc               = OPTIONS.tolc; catch, end;
+try opts.log_var            = OPTIONS.log_var; catch, end;
+% global options
+try opts.dim_refset         = OPTIONS.dim_refset; catch, end; 
+try opts.ndiverse           = OPTIONS.ndiverse; catch, end; 
+try opts.initiate           = OPTIONS.initiate; catch, end; 
+try opts.combination        = OPTIONS.combination; catch, end; 
+try opts.regenerate         = OPTIONS.regenerate; catch, end; 
+try opts.delete             = OPTIONS.delete; catch, end; 
+try opts.intens             = OPTIONS.intens; catch, end; 
+try opts.tolf               = OPTIONS.tolfun; catch, end; 
+try opts.diverse_criteria   = OPTIONS.diverse_criteria; catch, end;
+try opts.tolx               = OPTIONS.tolx; catch, end;
+% local options
+try opts.local.solver       = OPTIONS.local.solver ; catch, end;
+try opts.local.n1           = OPTIONS.local.n1; catch, end;
+try opts.local.n2           = OPTIONS.local.n2; catch, end;
+try opts.local.finish       = OPTIONS.local.finish; catch, end;
+try opts.local.bestx        = OPTIONS.local.bestx; catch, end;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% problem - Structure containing problem settings
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[lowbounds, highbounds] = handleLowHighBoundsSB(OPTIONS,X,lowbounds,highbounds);
+if ~ischar(FUN),
+    FUN = func2str(FUN);    % convert function handle to string
+end
+problem = [];
+problem.f = FUN;            % Name of the file containing the objective function
+problem.x_L = lowbounds;    % Lower bounds of decision variables
+problem.x_U = highbounds;   % Upper bounds of decision variables
+problem.x_0 = X;            % Initial point(s) (optional)
+try problem.vtr = OPTIONS.vtr; catch, end; % value to reach
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% call SSm 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%disp('If you use SSm and publish the results, please cite the following papers:');
+%disp(' ');
+%disp('Egea, J.A., M. Rodriguez-Fernandez, J. R. Banga and R. Mart� (2007) Scatter');
+%disp('Search for chemical and bioprocess optimization. Journal of Global Optimization');
+%disp('37(3):481-503.');
+%disp(' ');
+%disp('Rodriguez-Fernandez, M., J. A. Egea and J. R. Banga (2006) Novel Metaheuristic');
+%disp('for Parameter Estimation in Nonlinear Dynamic Biological Systems.');
+%disp('BMC Bioinformatics 7:483.');
+useFAST = 0;
+if isfield(OPTIONS,'fast'),
+    if OPTIONS.fast == 1,
+        useFAST = 1;
+    end
+end
+if useFAST,
+    result = fssm_kernel(problem,opts);
+else
+    result = ssm_kernel(problem,opts);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% handle output
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+X = result.xbest;
+FVAL = result.fbest;
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/signal/centeredfftSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/signal/centeredfftSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..f96217f5c2df5cc869a794333aef6fe941671f4d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/signal/centeredfftSB.m
@@ -0,0 +1,44 @@
+function [X,freq]=centeredfftSB(x,Fs)
+% centeredfftSB: Uses the fft function of MATLAB to determine a two sided
+% spectrum of x, where te data in x have been sampled with the frequency 
+% Fs. 
+%
+% [X,freq] = centeredfftSB(x,Fs)
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+% Get the length of the data vector x 
+N=length(x);
+
+% Determine the frequency axis
+if mod(N,2)==0
+    k = -N/2:N/2-1; % N even
+else
+    k = -(N-1)/2:(N-1)/2; % N odd
+end
+T = N/Fs;
+freq = k/T;  % Frequency axis
+
+% Determine the fft and normalize the result
+X = fft(x)/N; 
+% Shift the data in order to center it
+X = fftshift(X); 
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/signal/positivefftSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/signal/positivefftSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..3bf2172b6e643455e0d0737d5303b862fe938e59
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/signal/positivefftSB.m
@@ -0,0 +1,45 @@
+function [X,freq] = positivefftSB(x,Fs)
+% positivefftSB: Uses the fft function of MATLAB to determine a one sided
+% spectrum of x, where te data in x have been sampled with the frequency 
+% Fs. 
+%
+% [X,freq] = positivefftSB(x,Fs)
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+% Get the length of the data vector x 
+N=length(x);
+
+% Create the frequency axis
+k=0:N-1;     
+T=N/Fs;      
+freq=k/T;    
+
+% Determine the fft and normalize it
+X=fft(x)/N; 
+ 
+% Remove the negative frequency part and double the result (one sided)
+cutOff = ceil(N/2); 
+X = 2*X(1:cutOff);
+freq = freq(1:cutOff);
+return
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/signal/postpadSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/signal/postpadSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..858710560438938235074d15261e45610b1867fb
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/signal/postpadSB.m
@@ -0,0 +1,82 @@
+function y = postpadSB(x, l, c, dim)
+% y = postpadSB(x, l)
+% y = postpadSB(x, l, c)
+% y = postpadSB(x, l, c, dim)
+% postpadSB: Appends value c (default: 0) until to extend vector x to a
+% length of l. Same with matrices x, where the dimension to extend is given
+% by dim (default: 1). 
+
+% Information:
+% ============
+% Author: Tony Richardson <arichard@stark.cc.oh.us>
+% Created: June 1994
+% Adapted for the SBTOOLBOX2 by Henning Schmidt
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+if (nargin < 2 || nargin > 4)
+    error('Incorrect number of input arguments.');
+end
+
+if (nargin < 3 || isempty (c))
+    c = 0;
+else
+    if (~isscalar (c))
+        error ('postpadSB: third argument must be empty or a scalar');
+    end
+end
+
+nd = ndims (x);
+sz = size (x);
+if (nargin < 4)
+    % Find the first non-singleton dimension
+    dim  = 1;
+    while (dim < nd + 1 && sz (dim) == 1),
+        dim = dim + 1;
+    end
+    if (dim > nd)
+        dim = 1;
+    end
+else
+    if (~(isscalar (dim) && dim == round (dim)) && dim > 0 && dim < (nd + 1))
+        error ('postpadSB: dim must be an integer and valid dimension');
+    end
+end
+
+if (~ isscalar (l) || l < 0)
+    error ('postpadSB: second argument must be a positive scaler');
+end
+
+if (dim > nd)
+    sz(nd+1:dim) = 1;
+end
+
+d = sz (dim);
+
+if (d >= l)
+    idx = cell ();
+    for i = 1:nd
+        idx{i} = 1:sz(i);
+    end
+    idx{dim} = 1:l;
+    y = x(idx{:});
+else
+    sz (dim) = l - d;
+    y = cat (dim, x, c * ones (sz));
+end
+
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/signal/prepadSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/signal/prepadSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..a36ac459299187276f4e87f98a26d4376cad3145
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/signal/prepadSB.m
@@ -0,0 +1,81 @@
+function y = prepadSB(x, l, c, dim)
+% y = prepadSB(x, l)
+% y = prepadSB(x, l, c)
+% y = prepadSB(x, l, c, dim)
+% prepadSB: prepends value c (default: 0) until to extend vector x to a
+% length of l. Same with matrices x, where the dimension to extend is given
+% by dim (default: 1). 
+
+% Information:
+% ============
+% Author: Tony Richardson <arichard@stark.cc.oh.us>
+% Created: June 1994
+% Adapted for the SBTOOLBOX2 by Henning Schmidt
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+%
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
+% USA.
+academicWarningSB
+
+if (nargin < 2 || nargin > 4)
+    print_usage ();
+end
+
+if (nargin < 3 || isempty (c))
+    c = 0;
+else
+    if (~isscalar (c))
+        error ('prepadSB: third argument must be empty or a scalar');
+    end
+end
+
+nd = ndims (x);
+sz = size (x);
+if (nargin < 4),
+    %% Find the first non-singleton dimension
+    dim  = 1;
+    while (dim < nd + 1 && sz (dim) == 1)
+        dim = dim + 1;
+    end
+    if (dim > nd)
+        dim = 1;
+    end
+else
+    if (~(isscalar (dim) && dim == round (dim)) && dim > 0 && dim < (nd + 1))
+        error ('prepadSB: dim must be an integer and valid dimension');
+    end
+end
+
+if (~ isscalar (l) || l < 0)
+    error ('prepadSB: second argument must be a positive scaler');
+end
+
+if (dim > nd)
+    sz(nd+1:dim) = 1;
+end
+
+d = sz (dim);
+
+if (d >= l)
+    idx = cell ();
+    for i = 1:nd
+        idx{i} = 1:sz(i);
+    end
+    idx{dim} = d-l+1:d;
+    y = x(idx{:});
+else
+    sz (dim) = l - d;
+    y = cat (dim, c * ones (sz), x);
+end
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/signal/resampleSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/signal/resampleSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..e63c0285529b8901ebe6068577ae331a51239b0d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/signal/resampleSB.m
@@ -0,0 +1,74 @@
+function [x2,t2] = resampleSB(t1,x1,t2,method)
+% resampleSB: resamples time series x1, which is sampled at the time
+% instances t1 to time series x2 using a sampling defined by t2.
+%
+% t2: scalar representing sampling interval or vector of sampling instances
+% method: 'zoh', 'linear', 'cubic'. The use of 'method' is optional.
+%         (default: 'linear')
+%
+% The output t2 is the vector that has been used for the resampling.
+%
+% [x2,t2] = resampleSB(t1,x1,t2,method)
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+if nargin < 3 || nargin > 4,
+    error('Incorrect number of input arguments.');
+end
+
+if nargin == 3,
+    method = 'linear';
+end
+
+if length(t2) == 1,
+    t2 = [0:t2:t1(end)];
+end
+
+% Handle NaN data values
+t1end = t1(end);
+indnan = find(isnan(x1));
+x1(indnan) = [];
+t1(indnan) = [];
+% Handle the case when the last value is NaN
+if t1(end) ~= t1end,
+    t1(end) = t1end;
+end
+
+% Do the resampling
+x2 = zeros(1,length(t2));
+if strcmp(method,'linear'),
+    for k=1:length(t2),
+        x2(k) = interp1SB(t1,x1,t2(k));
+    end
+elseif strcmp(method,'zoh'),
+    for k=1:length(t2),
+        x2(k) = interp0SB(t1,x1,t2(k));
+    end    
+elseif strcmp(method,'cubic'),
+    for k=1:length(t2),
+        x2(k) = interpcsSB(t1,x1,t2(k));
+    end    
+else
+    error('Wrong definition for ''method'' input argument.');
+end
+
+return
+    
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/signal/xcorrSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/signal/xcorrSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..7101b367bbc215fe6b12dc43401bc04b878aada6
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/signal/xcorrSB.m
@@ -0,0 +1,173 @@
+function [R, lags] = xcorrSB(X, varargin)
+% Compute correlation R_xy of X and Y for various lags k:  
+%
+%    R_xy(k) = sum_{i=1}^{N-k}{x_i y_{i-k}}/(N-k),  for k >= 0
+%    R_xy(k) = R_yx(-k),  for k <= 0
+%
+% usage: [R, lag] = xcorrSB(X)
+% usage: [R, lag] = xcorrSB(X, Y)
+% usage: [R, lag] = xcorrSB(X, Y, maxlag)
+% usage: [R, lag] = xcorrSB(X, Y, maxlag, scale)
+%
+% Returns R(k+maxlag+1)=Rxy(k) for lag k=[-maxlag:maxlag].
+% Scale is one of:
+%    'biased'   for correlation=raw/N, 
+%    'unbiased' for correlation=raw/(N-|lag|), 
+%    'coeff'    for correlation=raw/(correlation at lag 0),
+%    'none'     for correlation=raw
+% If Y is omitted, compute autocorrelation.  
+% If maxlag is omitted, use N-1 where N=max(length(X),length(Y)).
+% If scale is omitted, use 'none'.
+%
+% If X is a matrix, computes the cross correlation of each column
+% against every other column for every lag.  The resulting matrix has
+% 2*maxlag+1 rows and P^2 columns where P is columns(X). That is,
+%    R(k+maxlag+1,P*(i-1)+j) == Rij(k) for lag k=[-maxlag:maxlag],
+% so
+%    R(:,P*(i-1)+j) == xcorr(X(:,i),X(:,j))
+% and
+%    reshape(R(k,:),P,P) is the cross-correlation matrix for X(k,:).
+%
+% xcorr computes the cross correlation using an FFT, so the cost is
+% dependent on the length N of the vectors and independent of the
+% number of lags k that you need.  If you only need lags 0:k-1 for 
+% vectors x and y, then the direct sum may be faster:
+%
+% unbiased:
+%  ( hankel(x(1:k),[x(k:N); zeros(k-1,1)]) * y ) ./ [N:-1:N-k+1](:)
+% biased:
+%  ( hankel(x(1:k),[x(k:N); zeros(k-1,1)]) * y ) ./ N
+%
+% If length(x) == length(y) + k, then you can use the simpler
+%    ( hankel(x(1:k),x(k:N-k)) * y ) ./ N
+%
+% Ref: Stearns, SD and David, RA (1988). Signal Processing Algorithms.
+%      New Jersey: Prentice-Hall.
+
+% Information:
+% ============
+% Function taken from the Octave distribution
+% Adapted for the SBTOOLBOX2 by Henning Schmidt
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+%
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
+% USA.
+academicWarningSB
+
+if (nargin < 1 || nargin > 4)
+    error('Incorrect number of input arguments.');
+end
+
+% assign arguments from list
+Y = [];
+maxlag = [];
+scale = 'none';
+N = length(X);
+if nargin==2
+    Y = varargin{1};
+    N = max(length(X),length(Y));
+elseif nargin==3
+    Y = varargin{1};
+    maxlag = varargin{2};
+elseif nargin == 4,
+    Y = varargin{1};
+    maxlag = varargin{2};
+    scale = varargin{3};
+end
+if isempty(maxlag),
+    maxlag = N-1;
+end
+
+% check argument values
+if isscalar(X) || ischar(X) || isempty(X),
+    error('xcorrSB: X must be a vector or matrix');
+end
+if isscalar(Y) || ischar(Y) || (~isempty(Y) && ~isvector(Y)),
+    error('xcorrSB: Y must be a vector');
+end
+if ~isvector(X) && ~isempty(Y),
+    error('xcorrSB: X must be a vector if Y is specified');
+end
+if ~isscalar(maxlag) && ~isempty(maxlag)
+    error('xcorrSB: maxlag must be a scalar');
+end
+if maxlag>N-1,
+    error('xcorrSB: maxlag must be less than length(X)');
+end
+if isvector(X) && isvector(Y) && length(X) ~= length(Y) && ~strcmp(scale,'none')
+    error('xcorrSB: scale must be ''none'' if length(X) ~= length(Y)')
+end
+
+P = size(X,2);
+M = 2^nextpow2(N + maxlag);
+if ~isvector(X)
+    % For matrix X, compute cross-correlation of all columns
+    R = zeros(2*maxlag+1,P^2);
+
+    % Precompute the padded and transformed `X' vectors
+    pre = fft (postpadSB (prepadSB (X, N+maxlag), M) );
+    post = conj (fft (postpadSB (X, M)));
+
+    % For diagonal (i==j)
+    cor = ifft (post .* pre);
+    R(:, 1:P+1:P^2) = conj (cor (1:2*maxlag+1,:));
+
+    % For remaining i,j generate xcorr(i,j) and by symmetry xcorr(j,i).
+    for i=1:P-1
+        j = i+1:P;
+        cor = ifft (pre(:,i*ones(length(j),1)) .* post(:,j));
+        R(:,(i-1)*P+j) = conj (cor (1:2*maxlag+1, :));
+        R(:,(j-1)*P+i) = flipud (cor (1:2*maxlag+1, :));
+    end
+elseif isempty(Y)
+    % compute autocorrelation of a single vector
+    post = fft (postpadSB(X,M));
+    cor = ifft (conj(post(:)) .* post(:));
+    R = [ conj(cor(maxlag+1:-1:2)) ; cor(1:maxlag+1) ];
+else
+    % compute cross-correlation of X and Y
+    post = fft (postpadSB(Y,M));
+    pre = fft (postpadSB(prepadSB(X,N+maxlag),M));
+    cor = conj (ifft (conj(post(:)) .* pre(:)));
+    R = cor(1:2*maxlag+1);
+end
+
+% if inputs are real, outputs should be real, so ignore the
+% insignificant complex portion left over from the FFT
+if isreal(X) && (isempty(Y) || isreal(Y))
+    R=real(R);
+end
+
+% correct for bias
+if strcmp(scale, 'biased')
+    R = R ./ N;
+elseif strcmp(scale, 'unbiased')
+    R = R ./ ( [ N-maxlag:N-1, N, N-1:-1:N-maxlag ]' * ones(1,columns(R)) );
+elseif strcmp(scale, 'coeff')
+    R = R ./ ( ones(size(R,1),1) * R(maxlag+1, :) );
+elseif ~strcmp(scale, 'none')
+    error('xcorr: scale must be ''biased'', ''unbiased'', ''coeff'' or ''none''');
+end
+
+% correct the shape so that it is the same as the input vector
+if isvector(X) && P > 1
+    R = R';
+end
+
+% return the lag indices if desired
+if nargout == 2
+    lags = [-maxlag:maxlag];
+end
+
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/auxiliary/common_size.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/auxiliary/common_size.m
new file mode 100644
index 0000000000000000000000000000000000000000..f48da03fc487094a7322e1e96d4fad1d9efc2c04
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/auxiliary/common_size.m
@@ -0,0 +1,75 @@
+function [errorcode, varargout] = common_size (varargin)
+% common_size: Determine if all input arguments are either scalar or of common
+% size.  If so, the output variable 'errorcode' is zero, and 'b' is a matrix 
+% of the common size with all entries equal to 'x' if this is a scalar or
+% x otherwise.  If the inputs cannot be brought to a common size,
+% errorcode is 1, and 'b' is 'x'.  For example,
+%
+% [errorcode, a, b] = common_size ([1 2; 3 4], 5)
+% 
+% results in:
+%               errorcode = 0
+%               a = [ 1, 2; 3, 4 ]
+%               b = [ 5, 5; 5, 5 ]
+%
+% USAGE:
+% ======
+% [errorcode, a, b] = common_size (x, y)
+
+% Information:
+% ============
+% Original author: KH <Kurt.Hornik@wu-wien.ac.at>
+% This function has been taken from Octave and adapted for the SBTOOLBOX2
+% by Henning Schmidt
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+  if (nargin < 2)
+    error ('common_size: only makes sense if nargin >= 2');
+  end
+
+  len = 2;
+  for i = 1 : nargin
+    sz =  size (varargin{i});
+    if (length (sz) < len)
+      s(i,:) = [sz, ones(1,len - length(sz))];
+    else
+      if (length (sz) > len)
+	if (i > 1)
+	  s = [s, ones(size(s,1), length(sz) - len)];
+	end
+	len = length (sz);
+      end
+      s(i,:) = sz;
+    end
+  end
+
+  m = max (s);
+  if (any (any ((s ~= 1)') & any ((s ~= ones (nargin, 1) * m)')))
+    errorcode = 1;
+    varargout = varargin;
+  else
+    errorcode = 0;
+    for i = 1 : nargin
+      varargout{i} = varargin{i};
+      if (prod (s(i,:)) == 1)
+           varargout{i} = varargout{i}*ones (m);
+      end
+    end
+  end
+
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/auxiliary/ismatrixSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/auxiliary/ismatrixSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..0e72072549ab2935e5c81174e769f610f2e31fa7
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/auxiliary/ismatrixSB.m
@@ -0,0 +1,38 @@
+function [ out ] = ismatrixSB( in )
+% ismatrixSB: Checks if the given argument is a matrix. out=1 if yes and 0
+% if not.
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+out = 1;
+if ~isnumeric(in),
+    out = 0;
+    return
+end
+
+dimvector = size(in);
+if min(dimvector) == 1,
+   out = 0;
+   return
+end
+
+return
+    
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/auxiliary/plot_dendrogram.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/auxiliary/plot_dendrogram.m
new file mode 100644
index 0000000000000000000000000000000000000000..71c42158ef217eeaa13cc60d7dc8f1c8bdb85663
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/auxiliary/plot_dendrogram.m
@@ -0,0 +1,123 @@
+function plot_dendrogram(topology,labels,fontsize)
+% DENDPLOT: Plots a dendrogram given a topology matrix.
+%
+%     Usage: dendplot(topology,{labels},{fontsize})
+%
+%         topology = [(n-1) x 4] matrix summarizing dendrogram topology:
+%                       col 1 = 1st OTU/cluster being grouped at current step
+%                       col 2 = 2nd OTU/cluster
+%                       col 3 = ID of cluster being produced
+%                       col 4 = distance at node
+%         labels =   optional cell-array with label names
+%         fontsize = optional font size for labels [default = 10].
+%
+
+% RE Strauss, 5/27/98
+%   8/20/99 - miscellaneous changes for Matlab v5.
+academicWarningSB
+
+
+if (nargin<2)
+    labels = {};
+end;
+if (nargin < 3)
+    fontsize = [];
+end;
+
+if (isempty(fontsize))              % Default font size for labels
+    fontsize = 10;
+end;
+
+r = size(topology,1);
+n = r+1;                            % Number of taxa
+
+links = dendhier([],topology,n-1);  % Find dendrogram links (branches)
+otu_indx = find(links(:,1)<=n);     % Get sequence of OTUs
+otus = links(otu_indx,1);
+y = zeros(2*n-1,1);                 % Y-coords for plot
+y(otus) = 0.5:(n-0.5);
+for i = 1:(n-1)
+    y(topology(i,3)) = mean([y(topology(i,1)),y(topology(i,2))]);
+end;
+
+%  clf;                                % Begin plot
+hold on;
+
+for i = 1:(2*n-2)                   % Horizontal lines
+    desc = links(i,1);
+    anc =  links(i,2);
+    X = [links(i,3) links(i,4)];
+    Y = [y(desc) y(desc)];
+    plot(X,Y,'k');
+end;
+
+for i = (n+1):(2*n-1)               % Vertical lines
+    indx = find(links(:,2)==i);
+    X = [links(indx,4)];
+    Y = [y(links(indx(1),1)) y(links(indx(2),1))];
+    plot(X,Y,'k');
+end;
+
+maxdist = max(links(:,4));
+for i = 1:n                         % OTU labels
+    if (~isempty(labels))
+        h = text(-.02*maxdist,y(i),labels{i},'Interpreter','none');   % For OTUs on right
+        set(h,'fontsize',fontsize);
+    else
+        h = text(-.02*maxdist,y(i),num2str(i));  % For OTUs on right
+        set(h,'fontsize',fontsize);
+        %     text(-.06*maxdist,y(i),num2str(i)); % For UTOs on left
+    end;
+end;
+
+axis([0-abs(0.3*maxdist) maxdist+0.03*maxdist 0 n]); % Axes
+%axis('square');
+set(gca,'Ytick',[]);                % Suppress y-axis labels and tick marks
+set(gca,'Ycolor','w');              % Make y-axes invisible
+set(gca,'Xdir','reverse');          % For OTUs on right
+
+hold off;
+return;
+
+
+% DENDHIER: Recursive algorithm to find links and distance coordinates on a
+%             dendrogram, given the topology matrix.
+%
+%     Usage: [links,topology,node] = dendhier(links,topology,node)
+%
+%         links =     4-col matrix of descendants, ancestors, descendant
+%                       distances, and ancestor distances; pass to
+%                       function as null vector []
+%         topology =  dendrogram topology matrix
+%         node =      current node; pass as N-1
+%
+
+% RE Strauss, 7/13/95
+
+function [links,topology,node] = dendhier(links,topology,node)
+n = size(topology,1)+1;             % Number of OTUs
+
+c1 =   topology(node,1);
+c2 =   topology(node,2);
+clst = topology(node,3);
+dist = topology(node,4);
+
+if (c1 <= n)
+    links = [links; c1 clst 0 dist];
+else
+    prevnode = find(topology(:,3)==c1);
+    prevdist = topology(prevnode,4);
+    links = [links; c1 clst prevdist dist];
+    [links,topology,node] = dendhier(links,topology,prevnode);
+end;
+
+if (c2 <= n)
+    links = [links; c2 clst 0 dist];
+else
+    prevnode = find(topology(:,3)==c2);
+    prevdist = topology(prevnode,4);
+    links = [links; c2 clst prevdist dist];
+    [links,topology,node] = dendhier(links,topology,prevnode);
+end;
+
+return;
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/boxplotSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/boxplotSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..9f74b9488d0db88e6bdfb86fe13960f72888737a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/boxplotSB.m
@@ -0,0 +1,207 @@
+function boxplotSB(data,varargin)
+% boxplotSB: plots a box-and-whisker diagram for the given data. The two sides 
+% (green color) of the box define the lower and upper quartile. The red
+% line corresponds to the median. The whiskers are the blue lines. Outliers
+% are depicted as black dots.
+%
+% USAGE:
+% ======
+% boxplotSB(data)        
+% boxplotSB(OPTIONS)        
+%
+% data:  column vector of matrix where each sample corresponds to one column
+% OPTIONS: structure containing options for the function
+%       OPTIONS.samplenames: Cell-array with names or other information of the samples
+%       OPTIONS.boxWidth: Width of the boxes to be drawn
+%       OPTIONS.whiskerLength: Whisker length relative to the length of the box
+%       OPTIONS.verticalFlag: Flag determining if the boxes are oriented
+%                             vertically (=1) or horizontally (=0)
+%
+% DEFAULT VALUES:
+% ===============
+% OPTIONS.samplenames:    {'Sample 1','Sample 2', ...}
+% OPTIONS.boxWidth:       0.5
+% OPTIONS.whiskerLength:  1.5 (standard)
+% OPTIONS.verticalFlag:   0 (plot horizontally)
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GLOBAL VARIABLES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+global verticalFlag boxWidth whiskerLength
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VECTOR OR MATRIX
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isvector(data)
+    data = data(:);
+end
+nrsamples = size(data,2);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 1,
+    OPTIONS = [];
+elseif nargin == 2,
+    OPTIONS = varargin{1};
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Set default values
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+samplenames = {}; for k=1:nrsamples, samplenames{k} = sprintf('Sample %d',k); end
+boxWidth = 0.5;
+whiskerLength = 1.5;
+verticalFlag = 0;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET OPTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% samplenames
+if isfield(OPTIONS,'samplenames'),
+    if ~isempty(OPTIONS.samplenames),
+        samplenames = OPTIONS.samplenames;
+    end
+end
+% boxWidth
+if isfield(OPTIONS,'boxWidth'),
+    if ~isempty(OPTIONS.boxWidth),
+        boxWidth = OPTIONS.boxWidth;
+    end
+end
+% whiskerLength
+if isfield(OPTIONS,'whiskerLength'),
+    if ~isempty(OPTIONS.whiskerLength),
+        whiskerLength = OPTIONS.whiskerLength;
+    end
+end
+% verticalFlag
+if isfield(OPTIONS,'verticalFlag'),
+    if ~isempty(OPTIONS.verticalFlag),
+        verticalFlag = OPTIONS.verticalFlag;
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SIMPLE OPTION CHECK
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(samplenames)
+    if length(samplenames) ~= nrsamples,
+        error('Number of samplenames does not fit the number of samples.');
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CYCLE THROUGH THE COLUMNS AND DO THE PLOTTING
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+figure % new figure
+hold on
+for k= 1:nrsamples
+    doplot(data(:,k),k);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% RESCALE THE PLOT AND DISPLAY SAMPLENAMES IF DEFINED
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+Ymin = min(min(data)); Ymax = max(max(data));
+DeltaY = 0.025*(Ymax-Ymin); % just a little bit of space on limits
+if verticalFlag
+    axis([[1-boxWidth, nrsamples+boxWidth] [(Ymin-DeltaY) (Ymax+DeltaY)]]);
+    set(gca,'XTick',[1:nrsamples]);
+    if ~isempty(samplenames), xticklabel_rotate([1:nrsamples],90,samplenames); end        
+else
+    axis([[(Ymin-DeltaY) (Ymax+DeltaY)] [1-boxWidth, nrsamples+boxWidth]]);
+    set(gca,'YTick',[1:nrsamples]);
+    if ~isempty(samplenames), set(gca, 'YTickLabel',samplenames); end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% THATS ALL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PLOT FUNCTION FOR PLOTTING A SINGLE BOX WITH WHISKERS AND OUTLIERS
+% THE FUNCTION ALSO NEEDS TO DETERMINE THE PERCENTILES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [] = doplot(sampledata,k)
+global verticalFlag boxWidth whiskerLength
+% Determine the percentiles
+prctiles = prctileSB(sampledata,[25 50 75]);
+p25 = prctiles(1,:); p50 = prctiles(2,:); p75 = prctiles(3,:);
+% Determine the upper whisker position (needs to be on a sampledata point)
+index = find(sampledata <= p75+whiskerLength*(p75-p25));
+if isempty(index),
+    upperWhisker = p75; % if no larger data points then use the 75 percentile
+else
+    upperWhisker = max(sampledata(index)); % get the max sampledata point smaller than the 75% percentile
+end
+% Determine the upper whisker position (needs to be on a sampledata point)
+index = find(sampledata >= p25-whiskerLength*(p75-p25));
+if isempty(index),
+    lowerWhisker = p25; % if no smaller data points then use the 25 percentile
+else
+    lowerWhisker = min(sampledata(index)); % get the min sampledata point larger than the 25% percentile
+end
+% Determine the outliers
+% Outliers are all the data points that lie outside the whiskers
+outlier = sampledata([find(sampledata<lowerWhisker); find(sampledata > upperWhisker)]);
+% Determine the right and the left (in a vertical sense) values
+% for the box
+rightValue = k+0.5*boxWidth;
+leftValue = k-0.5*boxWidth;
+% All things are determined so now the messy plot :)
+if verticalFlag
+    % plot the whiskers
+    plot([k-0.25*boxWidth k+0.25*boxWidth],[upperWhisker upperWhisker],'b'); % plot end half as wide as the box
+    plot([k-0.25*boxWidth k+0.25*boxWidth],[lowerWhisker lowerWhisker],'b'); % plot end half as wide as the box
+    plot([k k],[lowerWhisker p25],'b--'); 
+    plot([k k],[p75 upperWhisker],'b--');
+    % plot the median
+    plot([leftValue rightValue],[p50 p50],'r');
+    % plot the outliers
+    plot(k*ones(1,length(outlier)),outlier,'k.');
+    % plot the 4 sides of the box
+    plot([leftValue rightValue],[p75 p75],'g');
+    plot([rightValue rightValue],[p75 p25],'k');
+    plot([rightValue leftValue],[p25 p25],'g');
+    plot([leftValue leftValue],[p25 p75],'k');
+else
+    % plot the whiskers
+    plot([upperWhisker upperWhisker],[k-0.25*boxWidth k+0.25*boxWidth],'b'); % plot end half as wide as the box
+    plot([lowerWhisker lowerWhisker],[k-0.25*boxWidth k+0.25*boxWidth],'b'); % plot end half as wide as the box
+    plot([lowerWhisker p25],[k k],'b--'); 
+    plot([p75 upperWhisker],[k k],'b--'); 
+    % plot the median
+    plot([p50 p50],[leftValue rightValue],'r');
+    % plot the outliers
+    plot(outlier,k*ones(1,length(outlier)),'k.');
+    % plot the 4 sides of the box
+    plot([p75 p75],[leftValue rightValue],'g');
+    plot([p75 p25],[rightValue rightValue],'k');
+    plot([p25 p25],[rightValue leftValue],'g');
+    plot([p25 p75],[leftValue leftValue],'k');
+end
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/clusteringSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/clusteringSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..b9548c96615a93d0322e100d62f45943b30b6ce8
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/clusteringSB.m
@@ -0,0 +1,116 @@
+function [varargout] = clusteringSB(dist,varargin)
+% clusteringSB: Performs UPGMA on distance matrix and produces a
+% denddrogram plot.
+% 
+% Initially, each object is in its own cluster. At each step, the nearest 2
+% clusters are combined into a higher-level cluster. The distance between 
+% any 2 clusters A and B is taken to be the average of all distances
+% between pairs of objects "a" in A and "b" in B. 
+%
+% USAGE:
+% ======
+% [] = clusteringSB(dist,labels,fontsize)       
+% [topology] = clusteringSB(dist,labels,fontsize)
+%
+% dist:     [n x n] symmetric distance matrix
+% labels:   optional cell-array with label names
+% fontsize: optional font size for labels [default = 10]
+
+% Output Arguments:
+% =================
+% If no output argument is specified the dendrogram is plotted.
+%
+%    topology   - [(n-1) x 4] matrix summarizing dendrogram topology:
+%                 col 1 = 1st OTU/cluster being grouped at current step
+%                 col 2 = 2nd OTU/cluster
+%                 col 3 = ID of cluster being produced
+%                 col 4 = distance at node
+
+% RE Strauss, 5/27/96
+%   9/7/99 - miscellaneous changes for Matlab v5.
+%   9/24/01 - check diagonal elements against eps rather than zero.
+%
+% Adapted for the Systems Biology Toolbox 2 for MATLAB by
+% Henning Schmidt, henning@sbtoolbox2.org, 01. January 2008
+academicWarningSB
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+labels = [];
+fontsize = [];
+if nargin < 1 || nargin > 3,
+    error('Incorrect number of input arguments.');
+elseif nargin == 2,
+    labels = varargin{1};
+elseif nargin == 3,
+    labels = varargin{1};
+    fontsize = varargin{2};
+end
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Some checks
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[n,p] = size(dist);
+if n~=p || any(diag(dist)>eps),
+    error('Input matrix is not a distance matrix - consider function "pdistSB" to calculate it.');
+end
+if ~isempty(labels),
+    if size(labels,1) ~= n,
+        error('Numbers of taxa and taxon labels do not match');
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Do the clustering
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+clstsize = ones(1,n);               % Number of elements in clusters/otus
+id = 1:n;                           % Cluster IDs
+topology = zeros(n-1,4);            % Output dendrogram-topology matrix
+
+plug = 10e6;
+dist = dist + eye(n)*plug;          % Replace diagonal with plugs
+
+for step = 1:(n-1),                 % Clustering steps
+    min_dist = min(dist(:));            % Find minimum pairwise distance
+    [ii,jj] = find(dist==min_dist);     % Find location of minimum
+    k = 1;                              % Use first identified minimum
+    while (ii(k)>jj(k)),                 %   for which i<j
+        k = k+1;
+    end
+    i = ii(k);
+    j = jj(k);
+    if (id(i)<id(j)),
+        topology(step,:) = [id(i) id(j) n+step min_dist];
+    else
+        topology(step,:) = [id(j) id(i) n+step min_dist];
+    end
+    id(i) = n+step;
+    dist(i,j) = plug;
+    dist(j,i) = plug;
+
+    new_clstsize = clstsize(i) + clstsize(j);
+    alpha_i = clstsize(i) / new_clstsize;
+    alpha_j = clstsize(j) / new_clstsize;
+    clstsize(i) = new_clstsize;
+
+    for k = 1:n,                         % For all other clusters/OTUs,
+        if (k~=i && k~=j),                %   adjust distances to new cluster
+            dist(k,i) = alpha_i * dist(k,i) + alpha_j * dist(k,j);
+            dist(i,k) = alpha_i * dist(i,k) + alpha_j * dist(j,k);
+            dist(k,j) = plug;
+            dist(j,k) = plug;
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle output
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargout == 1,
+    varargout{1} = topology;
+else
+    figure; clf;
+    plot_dendrogram(topology,labels,fontsize);
+end    
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/betacdfSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/betacdfSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..1d299223c36103a37da98c0cc1f21d6737b24a4a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/betacdfSB.m
@@ -0,0 +1,67 @@
+function cdf = betacdfSB(x, a, b)
+% Cumulative density function of the Beta distribution
+%
+% USAGE:
+% ======
+% cdf = betacdfSB(x, a, b)
+%
+% For each element of 'x', returns the CDF at 'x' of the beta
+% distribution with parameters 'a' and 'b', i.e.,
+% PROB (beta ('a', 'b') <= 'x').
+
+% Information:
+% ============
+% Original author: KH <Kurt.Hornik@wu-wien.ac.at>
+% This function has been taken from Octave and adapted for the SBTOOLBOX2
+% by Henning Schmidt
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+  if (nargin ~= 3)
+    error('Incorrect number of input arguments'); 
+  end
+
+  if (~isscalar (a) || ~isscalar(b))
+    [retval, x, a, b] = common_size (x, a, b);
+    if (retval > 0)
+      error ('x, a and b must be of common size or scalar');
+    end
+  end
+
+  sz = size(x);
+  cdf = zeros (sz);
+
+  k = find (~(a > 0) | ~(b > 0) | isnan (x));
+  if (any (k))
+    cdf (k) = NaN;
+  end
+
+  k = find ((x >= 1) & (a > 0) & (b > 0));
+  if (any (k))
+    cdf (k) = 1;
+  end
+
+  k = find ((x > 0) & (x < 1) & (a > 0) & (b > 0));
+  if (any (k))
+    if (isscalar (a) && isscalar(b))
+      cdf (k) = betainc(x(k), a, b);
+    else
+      cdf (k) = betainc(x(k), a(k), b(k));
+    end
+  end
+
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/betainvSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/betainvSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..721b478a5c32e0413d78868e707e3ac05daebc6a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/betainvSB.m
@@ -0,0 +1,99 @@
+function inv = betainvSB(x, a, b)
+% Quantile function of the Beta distribution
+%
+% USAGE:
+% ======
+% inv = betainvSB(x, a, b)
+%
+% For each component of 'x', compute the quantile (the inverse of
+% the CDF) at 'x' of the Beta distribution with parameters 'a'
+% and 'b'.
+
+% Information:
+% ============
+% Original author: KH <Kurt.Hornik@wu-wien.ac.at>
+% This function has been taken from Octave and adapted for the SBTOOLBOX2
+% by Henning Schmidt
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+  if (nargin ~= 3)
+    error('Incorrect number of input arguments'); 
+  end
+
+  if (~isscalar (a) || ~isscalar(b))
+    [retval, x, a, b] = common_size (x, a, b);
+    if (retval > 0)
+      error ('x, a and b must be of common size or scalars');
+    end
+  end
+  
+  sz = size (x);
+  inv = zeros (sz);
+
+  k = find ((x < 0) | (x > 1) | ~(a > 0) | ~(b > 0) | isnan (x));
+  if (any (k))
+    inv (k) = NaN;
+  end
+
+  k = find ((x == 1) & (a > 0) & (b > 0));
+  if (any (k))
+    inv (k) = 1;
+  end
+
+  k = find ((x > 0) & (x < 1) & (a > 0) & (b > 0));
+  if (any (k))
+    if (~isscalar(a) || ~isscalar(b))
+      a = a (k);
+      b = b (k);
+      y = a ./ (a + b);
+    else
+      y = a / (a + b) * ones (size (k));
+    end
+    x = x (k);
+    l = find (y < eps);
+    if (any (l))
+      y(l) = sqrt (eps) * ones (length (l), 1);
+    end
+    l = find (y > 1 - eps);
+    if (any (l))
+      y(l) = 1 - sqrt (eps) * ones (length (l), 1);
+    end
+
+    y_old = y;
+    for i = 1 : 10000
+      h     = (betacdfSB(y_old, a, b) - x) ./ betapdfSB(y_old, a, b);
+      y_new = y_old - h;
+      ind   = find (y_new <= eps);
+      if (any (ind))
+        y_new (ind) = y_old (ind) / 10;
+      end
+      ind = find (y_new >= 1 - eps);
+      if (any (ind))
+        y_new (ind) = 1 - (1 - y_old (ind)) / 10;
+      end
+      h = y_old - y_new;
+      if (max (abs (h)) < sqrt (eps))
+        break;
+      end
+      y_old = y_new;
+    end
+
+    inv (k) = y_new;
+  end
+
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/betapdfSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/betapdfSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..729df6d409c82644f62e4db021444a0fc251ce9e
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/betapdfSB.m
@@ -0,0 +1,61 @@
+function pdf = betapdfSB(x, a, b)
+% Probability density function of the Beta distribution
+%
+% USAGE:
+% ======
+% pdf = betapdfSB(x, a, b)
+%
+% For each element of 'x', returns the PDF at 'x' of the beta
+% distribution with parameters 'a' and 'b'.
+
+% Information:
+% ============
+% Original author: KH <Kurt.Hornik@wu-wien.ac.at>
+% This function has been taken from Octave and adapted for the SBTOOLBOX2
+% by Henning Schmidt
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+  if (nargin ~= 3)
+    error('Incorrect number of input arguments'); 
+  end
+  
+  if (~isscalar (a) || ~isscalar(b))
+    [retval, x, a, b] = common_size (x, a, b);
+    if (retval > 0)
+      error ('x, a and b must be of common size or scalar');
+    end
+  end
+
+  sz = size (x);
+  pdf = zeros (sz);
+
+  k = find (~(a > 0) | ~(b > 0) | isnan (x));
+  if (any (k))
+    pdf (k) = NaN;
+  end
+
+  k = find ((x > 0) & (x < 1) & (a > 0) & (b > 0));
+  if (any (k))
+    if (isscalar(a) && isscalar(b))
+      pdf(k) = exp ((a - 1) .* log (x(k)) + (b - 1) .* log (1 - x(k))) ./ beta(a, b);
+    else
+      pdf(k) = exp ((a(k) - 1) .* log (x(k)) + (b(k) - 1) .* log (1 - x(k))) ./ beta(a(k), b(k));
+    end
+  end
+
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/chi2cdfSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/chi2cdfSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..569dd9dc7f6e2d86171bd0d70391eb4742d70f5d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/chi2cdfSB.m
@@ -0,0 +1,47 @@
+function cdf = chi2cdfSB(x, n)
+% Cumulative density function of the chi-square distribution
+%
+% USAGE:
+% ======
+% cdf = chi2cdfSB(x, n)
+%
+% For each element of 'x', compute the cumulative distribution
+% function (CDF) at 'x' of the chisquare distribution with 'n'
+% degrees of freedom.
+
+% Information:
+% ============
+% Original author: TT <Teresa.Twaroch@ci.tuwien.ac.at>
+% This function has been taken from Octave and adapted for the SBTOOLBOX2
+% by Henning Schmidt
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+  if (nargin ~= 2)
+    error('Incorrect number of input arguments');
+  end
+
+  if (~isscalar (n) || ~isscalr)
+    [retval, x, n] = common_size (x, n);
+    if (retval > 0)
+      error ('x and n must be of common size or scalar');
+    end
+  end
+
+  cdf = gamcdfSB(x, n / 2, 2);
+
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/chi2invSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/chi2invSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..648b0673530e308d1b98455cf3609533fa3ab40f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/chi2invSB.m
@@ -0,0 +1,47 @@
+function inv = chi2invSB(x, n)
+% Quantile function of the chi-square distribution
+%
+% USAGE:
+% ======
+% inv = chi2invSB(x, n)
+%
+% For each element of 'x', compute the quantile (the inverse of the
+% CDF) at 'x' of the chisquare distribution with 'n' degrees of
+% freedom.
+
+% Information:
+% ============
+% Original author: TT <Teresa.Twaroch@ci.tuwien.ac.at>
+% This function has been taken from Octave and adapted for the SBTOOLBOX2
+% by Henning Schmidt
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+  if (nargin ~= 2)
+    error('Incorrect number of input arguments'); 
+  end
+
+  if (~isscalar (n))
+    [retval, x, n] = common_size (x, n);
+    if (retval > 0)
+      error ('x and n must be of common size or scalar');
+    end
+  end
+
+  inv = gaminvSB(x, n / 2, 2);
+
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/chi2pdfSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/chi2pdfSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..3dce1b67d2a8bb53a8d1a8b48a1ce2ba89147c88
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/chi2pdfSB.m
@@ -0,0 +1,47 @@
+function pdf = chi2pdfSB(x, n)
+% Probability density function of the chi-square distribution
+%
+% USAGE:
+% ======
+% pdf = chi2pdfSB(x, n)
+%
+% For each element of 'x', compute the probability density function
+% (PDF) at 'x' of the chisquare distribution with 'n' degrees
+% of freedom.
+
+% Information:
+% ============
+% Original author: TT <Teresa.Twaroch@ci.tuwien.ac.at>
+% This function has been taken from Octave and adapted for the SBTOOLBOX2
+% by Henning Schmidt
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+  if (nargin ~= 2)
+    error('Incorrect number of input arguments'); 
+  end
+
+  if (~isscalar (n))
+    [retval, x, n] = common_size (x, n);
+    if (retval > 0)
+      error ('x and n must be of common size or scalar');
+    end
+  end
+
+  pdf = gampdfSB(x, n / 2, 2);
+
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/gamcdfSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/gamcdfSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..0157645e22045402ce37d8d47849192b1d8acae4
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/gamcdfSB.m
@@ -0,0 +1,62 @@
+function cdf = gamcdfSB(x, a, b)
+% Cumulative density function of the Gamma distribution
+%
+% USAGE:
+% ======
+% cdf = gamcdfSB(x, a, b)
+%
+% For each element of 'x', compute the cumulative distribution
+% function (CDF) at 'x' of the Gamma distribution with parameters
+% 'a' and 'b'.
+
+% Information:
+% ============
+% Original author: TT <Teresa.Twaroch@ci.tuwien.ac.at>
+% This function has been taken from Octave and adapted for the SBTOOLBOX2
+% by Henning Schmidt
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+  if (nargin ~= 3)
+    error('Incorrect number of input arguments'); 
+  end
+
+  if (~isscalar (a) || ~isscalar(b))
+    [retval, x, a, b] = common_size (x, a, b);
+    if (retval > 0)
+      error ('x, a and b must be of common size or scalars');
+    end
+  end
+
+  sz = size (x);
+  cdf = zeros (sz);
+
+  k = find (~(a > 0) | ~(b > 0) | isnan (x));
+  if (any (k))
+    cdf (k) = NaN;
+  end
+
+  k = find ((x > 0) & (a > 0) & (b > 0));
+  if (any (k))
+    if (isscalar (a) && isscalar(b))
+      cdf (k) = gammainc(x(k) ./ b, a);
+    else
+      cdf (k) = gammainc(x(k) ./ b(k), a(k));
+    end
+  end
+
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/gaminvSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/gaminvSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..c69db4e59ac7e5864b28812a926f5bad46e6bce8
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/gaminvSB.m
@@ -0,0 +1,91 @@
+function inv = gaminvSB(x, a, b)
+% Quantile function of the Gamma distribution
+%
+% USAGE:
+% ======
+% inv = gaminvSB(x, a, b)
+%
+% For each component of 'x', compute the quantile (the inverse of
+% the CDF) at 'x' of the Gamma distribution with parameters 'a'
+% and 'b'.
+
+% Information:
+% ============
+% Original author: KH <Kurt.Hornik@wu-wien.ac.at>
+% This function has been taken from Octave and adapted for the SBTOOLBOX2
+% by Henning Schmidt
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+  if (nargin ~= 3)
+    error('Incorrect number of input arguments'); 
+  end
+
+  if (~isscalar (a) || ~isscalar(b))
+    [retval, x, a, b] = common_size (x, a, b);
+    if (retval > 0)
+      error ('x, a and b must be of common size or scalars');
+    end
+  end
+
+  sz = size (x);
+  inv = zeros (sz);
+
+  k = find ((x < 0) | (x > 1) | isnan (x) | ~(a > 0) | ~(b > 0));
+  if (any (k))
+    inv (k) = NaN;
+  end
+
+  k = find ((x == 1) & (a > 0) & (b > 0));
+  if (any (k))
+    inv (k) = Inf;
+  end
+
+  k = find ((x > 0) & (x < 1) & (a > 0) & (b > 0));
+  if (any (k))
+    if (~isscalar(a) || ~isscalar(b))
+      a = a (k);
+      b = b (k);
+      y = a .* b;
+    else
+      y = a * b * ones (size (k));
+    end
+    x = x (k);
+    l = find (x < eps);
+    if (any (l))
+      y(l) = sqrt (eps) * ones (length (l), 1);
+    end
+
+    y_old = y;
+    for i = 1 : 100
+      h     = (gamcdfSB(y_old, a, b) - x) ./ gampdfSB(y_old, a, b);
+      y_new = y_old - h;
+      ind   = find (y_new <= eps);
+      if (any (ind))
+        y_new (ind) = y_old (ind) / 10;
+        h = y_old - y_new;
+      end
+      if (max (abs (h)) < sqrt (eps))
+        break;
+      end
+      y_old = y_new;
+    end
+
+    inv (k) = y_new;
+  end
+
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/gampdfSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/gampdfSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..e22205b55ddbd29cc9a8eac66008d824ef6486df
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/gampdfSB.m
@@ -0,0 +1,71 @@
+function pdf = gampdfSB(x, a, b)
+% Probability density function of the Gamma distribution
+%
+% USAGE:
+% ======
+% pdf = gampdfSB(x, a, b)
+%
+% For each element of 'x', return the probability density function
+% (PDF) at 'x' of the Gamma distribution with parameters 'a'
+% and 'b'.
+
+% Information:
+% ============
+% Original author: TT <Teresa.Twaroch@ci.tuwien.ac.at>
+% This function has been taken from Octave and adapted for the SBTOOLBOX2
+% by Henning Schmidt
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+  if (nargin ~= 3)
+    error('Incorrect number of input arguments'); 
+  end
+
+  if (~isscalar (a) || ~isscalar(b))
+    [retval, x, a, b] = common_size (x, a, b);
+    if (retval > 0)
+      error ('x, a and b must be of common size or scalars');
+    end
+  end
+
+  sz = size(x);
+  pdf = zeros (sz);
+
+  k = find (~(a > 0) | ~(b > 0) | isnan (x));
+  if (any (k))
+    pdf (k) = NaN;
+  end
+
+  k = find ((x > 0) & (a > 0) & (a <= 1) & (b > 0));
+  if (any (k))
+    if (isscalar(a) && isscalar(b))
+      pdf(k) = (x(k) .^ (a - 1)) .* exp(- x(k) ./ b) ./ gamma(a) ./ (b .^ a);
+    else
+      pdf(k) = (x(k) .^ (a(k) - 1)) .* exp(- x(k) ./ b(k)) ./ gamma(a(k)) ./ (b(k) .^ a(k));
+    end
+  end
+
+  k = find ((x > 0) & (a > 1) & (b > 0));
+  if (any (k))
+    if (isscalar(a) && isscalar(b))
+      pdf(k) = exp (- a .* log (b) + (a-1) .* log (x(k)) - x(k) ./ b - gammaln(a));
+    else
+      pdf(k) = exp (- a(k) .* log (b(k)) + (a(k)-1) .* log (x(k)) - x(k) ./ b(k) - gammaln(a(k)));
+    end
+  end
+
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/normcdfSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/normcdfSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..40043cbe497ebeb098e3230d45e7c0dbc936fbc6
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/normcdfSB.m
@@ -0,0 +1,75 @@
+function cdf = normcdfSB(x, m, s)
+% Cumulative densitiy function of the normal distribution
+%
+% USAGE:
+% ======
+% cdf = normcdfSB(x, m, s)
+%
+% For each element of 'x', compute the cumulative distribution
+% function (CDF) at 'x' of the normal distribution with mean
+% 'm' and standard deviation 's'.
+%
+% Default values are 'm' = 0, 's' = 1.
+
+% Information:
+% ============
+% Original author: TT <Teresa.Twaroch@ci.tuwien.ac.at>
+% This function has been taken from Octave and adapted for the SBTOOLBOX2
+% by Henning Schmidt
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+  if (~ ((nargin == 1) || (nargin == 3)))
+    error('Incorrect number of input arguments'); 
+  end
+
+  if (nargin == 1)
+    m = 0;
+    s = 1;
+  end
+
+  if (~isscalar (m) || ~isscalar (s))
+    [retval, x, m, s] = common_size(x, m, s);
+    if (retval > 0)
+      error ('x, m and s must be of common size or scalar');
+    end
+  end
+
+  sz = size (x);
+  cdf = zeros (sz);
+
+  if (isscalar (m) && isscalar(s))
+    if (find (isinf (m) | isnan (m) | ~(s >= 0) | ~(s < Inf)))
+      cdf = NaN * ones (sz);
+    else
+      cdf =  stdnormalcdfSB((x - m) ./ s);
+    end
+  else
+    k = find (isinf (m) | isnan (m) | ~(s >= 0) | ~(s < Inf));
+    if (any (k))
+      cdf(k) = NaN;
+    end
+
+    k = find (~isinf (m) & ~isnan (m) & (s >= 0) & (s < Inf));
+    if (any (k))
+      cdf(k) = stdnormalcdfSB((x(k) - m(k)) ./ s(k));
+    end
+  end
+
+  cdf((s == 0) & (x == m)) = 0.5;
+
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/norminvSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/norminvSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..26d665409aa3709f47fc1470a5f68bd952a4fc38
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/norminvSB.m
@@ -0,0 +1,81 @@
+function inv = norminvSB(x, m, s)
+% Quantile function of the normal distribution
+%
+% USAGE:
+% ======
+% pdf = norminvSB(x, m, s)
+%
+% For each element of 'x', compute the quantile (the inverse of the
+% CDF) at 'x' of the normal distribution with mean 'm' and
+% standard deviation 's'.
+%
+% Default values are 'm' = 0, 's' = 1.
+
+% Information:
+% ============
+% Original author: KH <Kurt.Hornik@wu-wien.ac.at>
+% This function has been taken from Octave and adapted for the SBTOOLBOX2
+% by Henning Schmidt
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+  if (nargin ~= 1 && nargin ~= 3)
+    error('Incorrect number of input arguments'); 
+  end
+
+  if (nargin == 1)
+    m = 0;
+    s = 1;
+  end
+
+  if (~isscalar (m) || ~isscalar (s))
+    [retval, x, m, s] = common_size (x, m, s);
+    if (retval > 0)
+      error ('x, m and s must be of common size or scalars');
+    end
+  end
+
+  sz = size (x);
+  inv = zeros (sz);
+
+  if (isscalar (m) && isscalar (s))
+    if (find (isinf (m) | isnan (m) | ~(s > 0) | ~(s < Inf)))
+      inv = NaN * ones (sz);
+    else
+      inv =  m + s .* stdnormalinvSB(x);
+    end
+  else
+    k = find (isinf (m) | isnan (m) | ~(s > 0) | ~(s < Inf));
+    if (any (k))
+      inv(k) = NaN;
+    end
+
+    k = find (~isinf (m) & ~isnan (m) & (s > 0) & (s < Inf));
+    if (any (k))
+      inv(k) = m(k) + s(k) .* stdnormalinvSB (x(k));
+    end
+  end
+
+  k = find ((s == 0) & (x > 0) & (x < 1));
+  if (any (k))
+    inv(k) = m(k);
+  end
+
+  inv((s == 0) & (x == 0)) = -Inf;
+  inv((s == 0) & (x == 1)) = Inf;
+
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/normpdfSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/normpdfSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..3664c1b5a16d4b11d686073841865c69389f8054
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/normpdfSB.m
@@ -0,0 +1,76 @@
+function pdf = normpdfSB(x, m, s)
+% Probability density function of the normal distribution
+%
+% USAGE:
+% ======
+% pdf = normpdfSB(x, m, s)
+%
+% For each element of 'x', compute the probability density function
+% (PDF) at 'x' of the normal distribution with mean 'm' and
+% standard deviation 's'.
+%
+% Default values are 'm' = 0, 's' = 1.
+
+% Information:
+% ============
+% Original author: TT <Teresa.Twaroch@ci.tuwien.ac.at>
+% This function has been taken from Octave and adapted for the SBTOOLBOX2
+% by Henning Schmidt
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+  if (nargin ~= 1 && nargin ~= 3)
+    error('Incorrect number of input arguments'); 
+  end
+
+  if (nargin == 1)
+    m = 0;
+    s = 1;
+  end
+
+  if (~isscalar (m) || ~isscalar (s))
+    [retval, x, m, s] = common_size (x, m, s);
+    if (retval > 0)
+      error ('x, m and s must be of common size or scalars');
+    end
+  end
+
+  sz = size (x);
+  pdf = zeros (sz);
+
+  if (isscalar (m) && isscalar (s))
+    if (find (isinf (m) | isnan (m) | ~(s >= 0) | ~(s < Inf)))
+      pdf = NaN * ones (sz);
+    else
+      pdf = stdnormalpdfSB((x - m) ./ s) ./ s;
+    end
+  else
+    k = find (isinf (m) | isnan (m) | ~(s >= 0) | ~(s < Inf));
+    if (any (k))
+      pdf(k) = NaN;
+    end
+
+    k = find (~isinf (m) & ~isnan (m) & (s >= 0) & (s < Inf));
+    if (any (k))
+      pdf(k) = stdnormalpdfSB((x(k) - m(k)) ./ s(k)) ./ s(k);
+    end
+  end
+
+  pdf((s == 0) & (x == m)) = Inf;
+  pdf((s == 0) & ((x < m) | (x > m))) = 0;
+
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/stdnormalcdfSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/stdnormalcdfSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..ea224afe2b76e0631f976d3293e5ca5abd903989
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/stdnormalcdfSB.m
@@ -0,0 +1,48 @@
+function cdf = stdnormalcdfSB (x)
+% Cumulative density function of the standard normal distribution
+%
+% USAGE:
+% ======
+% cdf = stdnormalcdfSB (x)
+%
+% For each component of 'x', compute the CDF of the standard normal
+% distribution at 'x'.
+
+% Information:
+% ============
+% Original author: KH <Kurt.Hornik@wu-wien.ac.at>
+% This function has been taken from Octave and adapted for the SBTOOLBOX2
+% by Henning Schmidt
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+  if (nargin ~= 1)
+    error('Incorrect number of input arguments'); 
+  end
+
+  sz = size (x);
+  if (numel(x) == 0)
+    error ('x must not be empty');
+  end
+
+  cdf = (ones (sz) + erf (x / sqrt (2))) / 2;
+
+return
+
+
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/stdnormalinvSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/stdnormalinvSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..541e3637b704f27f4aec3204aab63cf514998843
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/stdnormalinvSB.m
@@ -0,0 +1,39 @@
+function inv = stdnormalinvSB(x)
+% Quantile function of the standard normal distribution
+%
+% USAGE:
+% ======
+% inv = stdnormalinvSB(x)
+%
+% For each component of 'x', compute compute the quantile (the
+% inverse of the CDF) at 'x' of the standard normal distribution.
+
+% Information:
+% ============
+% Original author: KH <Kurt.Hornik@wu-wien.ac.at>
+% This function has been taken from Octave and adapted for the SBTOOLBOX2
+% by Henning Schmidt
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+  if (nargin ~= 1)
+    error('Incorrect number of input arguments'); 
+  end
+
+  inv = sqrt (2) * erfinv(2 * x - 1);
+
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/stdnormalpdfSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/stdnormalpdfSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..25a2f081a4b14ca03d98651d7dfa0b5bf93a1d14
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/stdnormalpdfSB.m
@@ -0,0 +1,50 @@
+function pdf = stdnormalpdfSB(x)
+% Probability density function of the standard normal distribution
+%
+% USAGE:
+% ======
+% pdf = stdnormalpdfSB(x)
+%
+% For each element of 'x', compute the probability density function
+% (PDF) of the standard normal distribution at 'x'.
+
+% Information:
+% ============
+% Original author: TT <Teresa.Twaroch@ci.tuwien.ac.at>
+% This function has been taken from Octave and adapted for the SBTOOLBOX2
+% by Henning Schmidt
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+  if (nargin ~= 1)
+    error('Incorrect number of input arguments'); 
+  end
+
+  sz = size(x);
+  pdf = zeros (sz);
+
+  k = find (isnan (x));
+  if (any (k))
+    pdf(k) = NaN;
+  end
+
+  k = find (~isinf (x));
+  if (any (k))
+    pdf (k) = (2 * pi)^(- 1/2) * exp (- x(k) .^ 2 / 2);
+  end
+
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/tcdfSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/tcdfSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..423a0be153f5ba8a2dfdaf5dbbdc08ff84a643da
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/tcdfSB.m
@@ -0,0 +1,70 @@
+function cdf = tcdfSB(x, n)
+% Cumulative density function of the t distribution
+%
+% USAGE:
+% ======
+% cdf = tcdfSB(x, n)
+%
+% For each element of 'x', compute the CDF at 'x' of the
+% t (Student) distribution with 'n' degrees of freedom, i.e.,
+% PROB (t(n) <= x).
+
+% Information:
+% ============
+% Original author: KH <Kurt.Hornik@wu-wien.ac.at>
+% This function has been taken from Octave and adapted for the SBTOOLBOX2
+% by Henning Schmidt
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+  if (nargin ~= 2)
+    error('Incorrect number of input arguments'); 
+  end
+
+  if (~isscalar (n))
+    [retval, x, n] = common_size (x, n);
+    if (retval > 0)
+      error ('x and n must be of common size or scalar');
+    end
+  end
+
+  cdf = zeros (size (x));
+
+  k = find (isnan (x) | ~(n > 0));
+  if (any (k))
+    cdf(k) = NaN;
+  end
+
+  k = find ((x == Inf) & (n > 0));
+  if (any (k))
+    cdf(k) = 1;
+  end
+
+  k = find ((x > -Inf) & (x < Inf) & (n > 0));
+  if (any (k))
+    if (isscalar (n))
+      cdf(k) = betainc(1 ./ (1 + x(k) .^ 2 ./ n), n / 2, 1 / 2) / 2;
+    else
+      cdf(k) = betainc(1 ./ (1 + x(k) .^ 2 ./ n(k)), n(k) / 2, 1 / 2) / 2;
+    end
+    ind = find (x(k) > 0);
+    if (any (ind))
+      cdf(k(ind)) = 1 - cdf(k(ind));
+    end
+  end
+
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/tinvSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/tinvSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..7735a3c0857745d957b9297b8851a0c966081b96
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/tinvSB.m
@@ -0,0 +1,77 @@
+function inv = tinvSB(x, n)
+% Quantile function of the t distribution
+%
+% USAGE:
+% ======
+% inv = tinvSB(x, n)
+%
+% For each component of 'x', compute the quantile (the inverse of
+% the CDF) at 'x' of the t (Student) distribution with parameter
+% 'n'.
+
+% Information:
+% ============
+% Original author: KH <Kurt.Hornik@wu-wien.ac.at>
+% This function has been taken from Octave and adapted for the SBTOOLBOX2
+% by Henning Schmidt
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+  if (nargin ~= 2)
+    error('Incorrect number of input arguments'); 
+  end
+
+  if (~isscalar (n))
+    [retval, x, n] = common_size (x, n);
+    if (retval > 0)
+      error ('x and n must be of common size or scalar');
+    end
+  end
+
+  inv = zeros (size (x));
+
+  k = find ((x < 0) | (x > 1) | isnan (x) | ~(n > 0));
+  if (any (k))
+    inv(k) = NaN;
+  end
+
+  k = find ((x == 0) & (n > 0));
+  if (any (k))
+    inv(k) = -Inf;
+  end
+
+  k = find ((x == 1) & (n > 0));
+  if (any (k))
+    inv(k) = Inf;
+  end
+
+  k = find ((x > 0) & (x < 1) & (n > 0) & (n < 10000));
+  if (any (k))
+    if (isscalar (n))
+      inv(k) = (sign (x(k) - 1/2) .* sqrt (n .* (1 ./ betainvSB(2*min (x(k), 1 - x(k)), n/2, 1/2) - 1)));
+    else
+      inv(k) = (sign (x(k) - 1/2) .* sqrt (n(k) .* (1 ./ betainvSB(2*min (x(k), 1 - x(k)), n(k)/2, 1/2) - 1)));
+    end
+  end
+
+  % For large n, use the quantiles of the standard normal
+  k = find ((x > 0) & (x < 1) & (n >= 10000));
+  if (any (k))
+    inv(k) = stdnormalinvSB(x(k));
+  end
+
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/tpdfSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/tpdfSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..163db1b451664414cd7ae0e5c7eff1773e515b0a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/distributions/tpdfSB.m
@@ -0,0 +1,61 @@
+function pdf = tpdfSB(x, n)
+% Probability density function of the t distribution
+%
+% USAGE:
+% ======
+% pdf = tpdfSB(x, n)
+%
+% For each element of 'x', compute the probability density function
+% (PDF) at 'x' of the t (Student) distribution with 'n'
+% degrees of freedom. 
+
+% Information:
+% ============
+% Original author: KH <Kurt.Hornik@wu-wien.ac.at>
+% This function has been taken from Octave and adapted for the SBTOOLBOX2
+% by Henning Schmidt
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+  if (nargin ~= 2)
+    error('Incorrect number of input arguments'); 
+  end
+
+  if (~isscalar (n))
+    [retval, x, n] = common_size (x, n);
+    if (retval > 0)
+      error ('x and n must be of common size or scalar');
+    end
+  end
+
+  pdf = zeros (size (x));
+
+  k = find (isnan (x) | ~(n > 0) | ~(n < Inf));
+  if (any (k))
+    pdf(k) = NaN;
+  end
+
+  k = find (~isinf (x) & ~isnan (x) & (n > 0) & (n < Inf));
+  if (any (k))
+    if (isscalar (n))
+      pdf(k) = (exp (- (n + 1) .* log (1 + x(k) .^ 2 ./ n)/2) / (sqrt (n) * beta(n/2, 1/2)));
+    else
+      pdf(k) = (exp (- (n(k) + 1) .* log (1 + x(k) .^ 2 ./ n(k))/2) ./ (sqrt (n(k)) .* beta(n(k)/2, 1/2)));
+    end
+  end
+
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/other/centerSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/other/centerSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..51cc1b6b77b1046a04643d716a7f0b39140a34cb
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/other/centerSB.m
@@ -0,0 +1,59 @@
+function [retval] = centerSB(x, varargin)
+% Center by subtracting means
+%
+% USAGE:
+% ======
+% retval = centerSB(x)
+% retval = centerSB(x,dim)
+%
+% If x is a vector, subtract its mean. If x is a matrix, do the above for
+% each column. If the optional argument dim is given, perform the above
+% operation along this dimension 
+
+% Information:
+% ============
+% Original author: KH <Kurt.Hornik@wu-wien.ac.at>
+% This function has been taken from Octave and adapted for the SBTOOLBOX2
+% by Henning Schmidt
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+if (nargin ~= 1 && nargin ~= 2)
+    print_usage ();
+end
+
+if (isvector (x))
+    retval = x - mean (x, varargin{:});
+elseif (ismatrixSB (x))
+    if nargin < 2
+        dim = find (size (x) > 1, 1);
+        if isempty (dim),
+            dim=1;
+        end;
+    else
+        dim = varargin{1};
+    end
+    sz = ones (1, ndims (x));
+    sz (dim) = size (x, dim);
+    retval = x - repmat (mean (x, dim), sz);
+elseif (isempty (x))
+    retval = x;
+else
+    error ('centerSB: x must be a vector or a matrix');
+end
+
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/other/kurtosisSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/other/kurtosisSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..8e1845184e2b2383d435f5f678a491ae6c056963
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/other/kurtosisSB.m
@@ -0,0 +1,70 @@
+function retval = kurtosisSB(x, dim)
+% If 'x' is a vector of length 'N', return the kurtosis
+% of 'x'.  If 'x' is a matrix, return the kurtosis over the
+% first non-singleton dimension. The optional argument 'dim'
+% can be given to force the kurtosis to be given over that 
+% dimension.
+%
+% USAGE:
+% ======
+% retval = kurtosisSB(x, dim)
+
+% Information:
+% ============
+% Original author: KH <Kurt.Hornik@wu-wien.ac.at>
+% Adapted-By: jwe
+% Adapted for the SBTOOLBOX2 by Henning Schmidt
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+  if (nargin ~= 1 && nargin ~= 2)
+    error('Incorrect number of input arguments'); 
+  end
+
+  nd = ndims (x);
+  sz = size (x);
+  if (nargin ~= 2)
+    % Find the first non-singleton dimension.
+    dim  = 1;
+    while (dim < nd + 1 && sz(dim) == 1)
+      dim = dim + 1;
+    end
+    if (dim > nd)
+      dim = 1;
+    end
+  else
+    if (~(isscalar (dim) && dim == round (dim)) && dim > 0	&& dim < (nd + 1))
+      error ('dim must be an integer and valid dimension');
+    end
+  end
+  
+  if (~ismatrixSB(x) && ~isvector(x))
+    error ('x has to be a matrix or a vector');
+  end
+
+  c = sz(dim);
+  sz(dim) = 1;
+  idx = ones (1, nd);
+  idx(dim) = c;
+  x = x - repmat (mean (x, dim), idx);
+  retval = zeros (sz);
+  s = std (x, [], dim);
+  x = sum(x.^4, dim);
+  ind = find (s > 0);
+  retval(ind) = x(ind) / (c*s(ind) .^ 4);
+
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/other/sumsqSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/other/sumsqSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..d0a486856bf6eec09f9a1f102321fe1b725aa705
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/other/sumsqSB.m
@@ -0,0 +1,45 @@
+function [ sumsq ] = sumsqSB( x, varargin )
+% sumsqSB: Sum of squares of elements along dimension dim. 
+%
+% USAGE:
+% ======
+% sumsq = sumsqSB(x)
+% sumsq = sumsqSB(x,dim)
+%
+% If dim is omitted, it defaults to 1 (column-wise sum of squares).
+% As a special case if x is a vector and dim is omitted, return the sum of
+% squares of its elements.
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+if nargin == 1,
+    dim = 1;
+elseif nargin == 2,
+    dim = varargin{1};
+else
+    error('Incorrect number of input arguments.');
+end
+
+if isvector(x),
+    sumsq = sum(x.^2);
+else
+    sumsq = sum(x.^2,dim);
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/other/zscoreSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/other/zscoreSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..2b14d967fd86fd20ccb3288356351667c3c5d038
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/other/zscoreSB.m
@@ -0,0 +1,49 @@
+function A = zscoreSB(X,varargin)
+% zscroeSB: Compute the z-score of each element of X relative to the data
+% in the columns of X. The z-score for a single data point x_i is:
+% (x_i - mean(x))/std(x)
+%
+% USAGE:
+% ======
+% A = zscoreSB(x)
+% A = zscoreSB(x,dim)
+%
+% default dimension: 1
+
+% Information:
+% ============
+% Original author: Paul Kienzle
+% This function has been taken from Octave and adapted for the SBTOOLBOX2
+% by Henning Schmidt
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+if (nargin ~= 1 && nargin ~= 2)
+    error('Incorrect number of input arguments.');
+end
+if (nargin == 2)
+    dim = varargin{1};
+else
+    dim = min(find(size(X)>1));
+    if isempty(dim), 
+        dim=1; 
+    end
+end
+sz = ones(1,length(size(X)));
+sz(dim) = size(X,dim);
+A = (X - repmat(mean(X,varargin{:}),sz)) ./ repmat(std(X,varargin{:}),sz);
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/pdistSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/pdistSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..a2793f648d19f3eea1ec7906ee21643c3d1e6e37
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/pdistSB.m
@@ -0,0 +1,72 @@
+function [D] = pdistSB(datamatrix,varargin)
+% pdistSB: Determines the distance matrix for a set of points whose
+% coordinates are given as row-vectors in the data matrix.
+%
+% USAGE:
+% ======
+% D = pdistSB(datamatrix) 
+% D = pdistSB(datamatrix, method) 
+%
+% datamatrix: datamatrix is an NxP matrix of coordinates for N points in P dimensions
+% method: is an integer between 1 and 3 representing the chosen
+%         method for computing the distance matrix (see note below)
+%
+% DEFAULT VALUES:
+% ===============
+% method: method chosen problem size dependend if not specified
+%
+% Output Arguments:
+% =================
+% D: An NxN matrix, where the value of DMAT(i,j) corresponds to
+%           the distance from datamatrix(i,:) to datamatrix(j,:)
+% Note:
+% =====
+% method=1: Usually fastest for small inputs. Takes advantage of the symmetric
+%           property of distance matrices to perform half as many calculations
+% method=2: Usually fastest for medium inputs. Uses a fully vectorized method
+% method=3: Usually fastest for large inputs. Uses a partially vectorized
+%           method with relatively small memory requirement
+
+% Author: Joseph Kirk
+% Email: jdkirk630 at gmail dot com
+% Release: 1.0
+% Release Date: 5/29/07
+%
+% Adapted for the Systems Biology Toolbox 2 for MATLAB by
+% Henning Schmidt (henning@sbtoolbox2.org), 01. January 2008
+academicWarningSB
+
+% Handle variable input arguments and select the method
+if nargin < 1 || nargin > 2,
+    error('Incorrect number of input arguments.');
+end
+if nargin == 2,
+    method = varargin{1};
+else
+    [n,dims] = size(datamatrix);
+    numels = n*n*dims;
+    method = 2; 
+    if numels > 5e4, 
+        method = 3; 
+    elseif n < 20, 
+        method = 1; 
+    end
+end
+
+% distance matrix calculation options
+switch method
+    case 1 % half as many computations (symmetric upper triangular property)
+        [k,kk] = find(triu(ones(n),1));
+        D = zeros(n);
+        D(k+n*(kk-1)) = sqrt(sum((datamatrix(k,:) - datamatrix(kk,:)).^2,2));
+        D(kk+n*(k-1)) = D(k+n*(kk-1));
+    case 2 % fully vectorized calculation (very fast for medium inputs)
+        a = reshape(datamatrix,1,n,dims);
+        b = reshape(datamatrix,n,1,dims);
+        D = sqrt(sum((a(ones(n,1),:,:) - b(:,ones(n,1),:)).^2,3));
+    case 3 % partially vectorized (smaller memory requirement for large inputs)
+        D = zeros(n,n);
+        for k = 1:n
+            D(k,:) = sqrt(sum((datamatrix(k*ones(n,1),:) - datamatrix).^2,2));
+        end
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/prctileSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/prctileSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..ebde0073b6b59d7cef58b69174077eefc5c4249b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/prctileSB.m
@@ -0,0 +1,74 @@
+function [output] = prctileSB(data,p)
+% prctileSB: This function determines the percentiles of a sample, based on
+% interpolation.
+%
+% USAGE:
+% ======
+% [output] = prctileSB(data,p)        
+%
+% data:  column vector of matrix where each sample corresponds to one column
+% p: vector of percentage values to calculate the percentiles for
+%
+% Output Arguments:
+% =================
+% output: column vector with same length as p, containing the percentiles
+%         for the given percentages in p.
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INITIALIZE THE OUTPUT VARIABLE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output = nan(length(p),1);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% BASIC CHECK OF THE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty([find(p>100) find(p<0)]),
+    error('At least one element in ''p'' is out of bounds. Allowed: [0 100]');
+end
+if isempty(data),
+    error('''data'' is empty');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% BASIC CHECK OF THE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[nrrows,nrcols] = size(data);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE THE PERCENTILES COLUMNWISE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+data = sort(data,1);
+for k = 1:nrcols
+    % build the function to be interpolated to find the quantiles
+%     x = (100*(0:nrrows+1)./(nrrows+1))';
+    x = [0 100*(0.5:(nrrows-0.5))./nrrows 100]';
+    f = [data(1,k)
+         data(:,k)
+         data(nrrows,k)];
+    output(:,k) = interp1SB(x,f,p(:));
+end
+
+
+
+
+           
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/princompSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/princompSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..5a302430705f0b88baa84bac13972bb02395eb5f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/princompSB.m
@@ -0,0 +1,38 @@
+function [pc,z,w,Tsq] = princompSB(X)
+% princompSB: Compute principal components of X
+%
+% USAGE:
+% ======
+% [pc,z,w,Tsq] = princomp(X)
+%
+% pc:  the principal components
+% z:   the transformed data
+% w:   the eigenvalues of the covariance matrix
+% Tsq: Hotelling's T^2 statistic for the transformed data
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+C = cov(X);
+[U,D,pc] = svd(C);
+z = centerSB(X)*pc;
+w = diag(D);
+Tsq = sumsqSB(zscoreSB(z),2);
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/tests/swtestSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/tests/swtestSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..be85ad951ab4524b27647532fecfd2ab14dcd9a1
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/statistic/tests/swtestSB.m
@@ -0,0 +1,246 @@
+function [H, pValue, W] = swtestSB(x, alpha, tail)
+% swtestSB: Shapiro-Wilk parametric hypothesis test of composite normality.
+%
+% USAGE:
+% ======
+% [H, pValue, SWstatistic] = swtestSB(x)
+% [H, pValue, SWstatistic] = swtestSB(x, alpha)
+% [H, pValue, SWstatistic] = swtestSB(x, alpha, tail)
+%
+% This function performs the Shapiro-Wilk test to determine if the null 
+% hypothesis of composite normality is a reasonable assumption regarding 
+% the population distribution of a random sample x. The desired 
+% significance level, alpha, is an optional scalar input (default = 0.05).
+% tail indicates the type of test (default = 1).
+%
+% The Shapiro-Wilk hypotheses are: 
+% Null Hypothesis: x is normal with unspecified mean and variance.
+%    For tail =  0 (2-sided test), alternative: x is not normal.
+%    For tail =  1 (1-sided test), alternative: x is upper the normal.
+%    For tail = -1 (1-sided test), alternative: x is lower the normal.
+%
+% This is an omnibus test, and is generally considered relatively
+% powerful against a variety of alternatives.
+% Shapiro-Wilk test is better than the Shapiro-Francia test for
+% Platykurtic sample. Conversely, Shapiro-Francia test is better than the
+% Shapiro-Wilk test for Leptokurtic samples.
+%
+% When the series 'x' is Leptokurtic, swtestSB performs the Shapiro-Francia
+% test, else (series 'x' is Platykurtic) swtestSB performs the
+% Shapiro-Wilk test.
+% 
+% Inputs:
+%   x - a vector of deviates from an unknown distribution. The observation
+%       number must exceed 3 and be less than 5000.
+%
+% Optional inputs:
+%   alpha - The significance level for the test (default = 0.05).
+%   tail  - The type of the test (default = 1).
+% 
+% Outputs:
+%  SWstatistic - The test statistic (non normalized).
+%
+%  pValue - is the p-value, or the probability of observing the given
+%           result by chance given that the null hypothesis is true. Small
+%           values of pValue cast doubt on the validity of the null hypothesis.
+%
+%     H = 0 => Do not reject the null hypothesis at significance level alpha.
+%     H = 1 => Reject the null hypothesis at significance level alpha.
+%
+% References: Royston P. "Algorithm AS R94", Applied Statistics (1995) Vol. 44, No. 4.
+%   AS R94 -- calculates Shapiro-Wilk normality test and P-value
+%   for sample sizes 3 <= n <= 5000. Handles censored or uncensored data.
+%   Corrects AS 181, which was found to be inaccurate for n > 50.
+
+% Information:
+% ============
+% Original author:  	Ahmed Ben Sa�da 
+% Included into the SBTOOLBOX2 by Henning Schmidt (with permission of the
+% author).
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+%
+% Ensure the sample data is a VECTOR.
+%
+if numel(x) == length(x)
+    x  =  x(:);               % Ensure a column vector.
+else
+    error('Input sample ''x'' must be a vector.');
+end
+
+%
+% Remove missing observations indicated by NaN's and check sample size.
+%
+x  =  x(~isnan(x));
+if length(x) < 3
+   error('Sample vector ''x'' must have at least 3 valid observations.');
+end
+
+if length(x) > 5000
+    warning('Shapiro-Wilk test might be inaccurate due to large sample size ( > 5000).');
+end
+
+%
+% Ensure the significance level, alpha, is a 
+% scalar, and set default if necessary.
+%
+if (nargin >= 2) && ~isempty(alpha)
+   if numel(alpha) > 1
+      error('Significance level ''Alpha'' must be a scalar.');
+   end
+   if (alpha <= 0 || alpha >= 1)
+      error('Significance level ''Alpha'' must be between 0 and 1.'); 
+   end
+else
+   alpha  =  0.05;
+end
+
+%
+% Ensure the type-of-test indicator, tail, is a scalar integer from 
+% the allowable set {-1 , 0 , 1}, and set default if necessary.
+%
+if (nargin >= 3) && ~isempty(tail)
+   if numel(tail) > 1
+      error('Type-of-test indicator ''Tail'' must be a scalar.');
+   end
+   if (tail ~= -1) && (tail ~= 0) && (tail ~= 1)
+      error('Type-of-test indicator ''Tail'' must be -1, 0, or 1.');
+   end
+else
+   tail  =  1;
+end
+
+% First, calculate the a's for weights as a function of the m's
+% See Royston (1995) for details in the approximation.
+x       =   sort(x); % Sort the vector x in ascending order.
+n       =   length(x);
+mtilde  =   norminvSB(((1:n)' - 3/8) / (n + 0.25));
+weights =   zeros(n,1); % Preallocate the weights.
+
+if kurtosisSB(x) > 3
+%     disp('SB: SFSFSF');
+    % The Shapiro-Francia test is better for leptokurtic samples.
+    weights =   1/sqrt(mtilde'*mtilde) * mtilde;
+    %
+    % The Shapiro-Francia statistic W is calculated to avoid excessive rounding
+    % errors for W close to 1 (a potential problem in very large samples).
+    %
+    W   =   (weights' * x) ^2 / ((x - mean(x))' * (x - mean(x)));
+    nu      =   log(n);
+    u1      =   log(nu) - nu;
+    u2      =   log(nu) + 2/nu;
+    mu      =   -1.2725 + (1.0521 * u1);
+    sigma   =   1.0308 - (0.26758 * u2);
+    newSFstatistic  =   log(1 - W);
+    
+    
+    %
+    % Compute the normalized Shapiro-Francia statistic and its p-value.
+    %
+    NormalSFstatistic =   (newSFstatistic - mu) / sigma;
+    % the next p-value is for the tail = 1 test.
+    pValue   =   1 - normcdfSB(NormalSFstatistic, 0, 1);
+else
+% disp('SB: SWSWSW')
+    % The Shapiro-Wilk test is better for platykurtic samples.
+    c    =   1/sqrt(mtilde'*mtilde) * mtilde;
+    u    =   1/sqrt(n);
+    PolyCoef_1   =   [-2.706056 , 4.434685 , -2.071190 , -0.147981 , 0.221157 , c(n)];
+    PolyCoef_2   =   [-3.582633 , 5.682633 , -1.752461 , -0.293762 , 0.042981 , c(n-1)];
+    PolyCoef_3   =   [-0.0006714 , 0.0250540 , -0.39978 , 0.54400];
+    PolyCoef_4   =   [-0.0020322 , 0.0627670 , -0.77857 , 1.38220];
+    PolyCoef_5   =   [0.00389150 , -0.083751 , -0.31082 , -1.5861];
+    PolyCoef_6   =   [0.00303020 , -0.082676 , -0.48030];
+    PolyCoef_7   =   [0.459 , -2.273];
+    weights(n)   =   polyval(PolyCoef_1 , u);
+    weights(1)   =   -weights(n);
+
+    % Special attention when n=3 (this is a special case).
+    if n == 3
+        weights(1)  =   0.707106781;
+        weights(n)  =   -weights(1);
+    end
+    if n >= 6
+        weights(n-1) =   polyval(PolyCoef_2 , u);
+        weights(2)   =   -weights(n-1);
+        count  =   3;
+        phi    =   (mtilde'*mtilde - 2 * mtilde(n)^2 - 2 * mtilde(n-1)^2) / (1 - 2 * weights(n)^2 - 2 * weights(n-1)^2);
+    else
+        count  =   2;
+        phi    =   (mtilde'*mtilde - 2 * mtilde(n)^2) /  (1 - 2 * weights(n)^2);
+    end
+
+    %
+    % The vector 'WEIGHTS' obtained next corresponds to the same coefficients
+    % listed by Shapiro-Wilk in their original test for small samples.
+    %
+    weights(count : n-count+1)  =  mtilde(count : n-count+1) / sqrt(phi);
+
+    %
+    % The Shapiro-Wilk statistic W is calculated to avoid excessive rounding
+    % errors for W close to 1 (a potential problem in very large samples).
+    %
+    W   =   (weights' * x) ^2 / ((x - mean(x))' * (x - mean(x)));
+
+    %
+    % Calculate the significance level for W (exact for n=3).
+    %
+
+    newn    =   log(n);
+    if (n > 3) && (n <= 11)
+        mu      =   polyval(PolyCoef_3 , n);
+        sigma   =   exp(polyval(PolyCoef_4 , n));    
+        gam     =   polyval(PolyCoef_7 , n);
+        newSWstatistic  =   -log(gam-log(1-W));
+    elseif n >= 12
+        mu      =   polyval(PolyCoef_5 , newn);
+        sigma   =   exp(polyval(PolyCoef_6 , newn));
+        newSWstatistic  =   log(1 - W);
+    elseif n == 3
+        mu      =   0;
+        sigma   =   1;
+        newSWstatistic  =   0;
+    end
+
+    %
+    % Compute the normalized Shapiro-Wilk statistic and its p-value.
+    %
+    NormalSWstatistic       =   (newSWstatistic - mu) / sigma;
+    % The next p-value is for the tail = 1 test.
+    pValue       =   1 - normcdfSB(NormalSWstatistic, 0, 1);
+    % Special attention when n=3 (this is a special case).
+    if n == 3
+        pValue  =   1.909859 * (asin(sqrt(W)) - 1.047198);
+        NormalSWstatistic =   norminvSB(pValue, 0, 1);
+    end
+end
+
+% The p-value just found is for the tail = 1 test.
+if tail == 0
+    pValue = 2 * min(pValue, 1-pValue);
+elseif tail == -1
+    pValue = 1 - pValue;
+end
+
+%
+% To maintain consistency with existing Statistics Toolbox hypothesis
+% tests, returning 'H = 0' implies that we 'Do not reject the null 
+% hypothesis at the significance level of alpha' and 'H = 1' implies 
+% that we 'Reject the null hypothesis at significance level of alpha.'
+%
+H  = (alpha >= pValue);
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/symbolic/formula2vecSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/symbolic/formula2vecSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..e8bca9069a4017c12744ee41999b4291c7c1b74a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/symbolic/formula2vecSB.m
@@ -0,0 +1,36 @@
+function [formula] = formula2vecSB(formula)
+% formula2vecSB: Converts a formula given as a string into a formula that
+% can be evaluated with variables given as vectors. (Adding '.' in front of
+% '*', '/', '^'
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+academicWarningSB
+
+
+formula = regexprep(formula,'\*','.*');
+formula = regexprep(formula,'\/','./');
+formula = regexprep(formula,'\^','.^');
+
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/symbolic/maplearraySB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/symbolic/maplearraySB.m
new file mode 100644
index 0000000000000000000000000000000000000000..43bcbe5971808f36325bc2a62ba50dee1043eb97
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/symbolic/maplearraySB.m
@@ -0,0 +1,39 @@
+function [output] = maplearraySB(input)
+% maplearraySB: Creates a symbolic expression of the form: '{a,b,c,d}' 
+% where a, b,c ,d are strings coming from a cellarray input argument.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+academicWarningSB
+
+
+for kindex=1:length(input)
+    if kindex==1
+        output = sprintf('{%s', input{kindex});
+    else
+        output = sprintf('%s,%s', output, input{kindex});
+    end
+end
+output = sym(strcat(output,'}'));
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/symbolic/substitutevarsSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/symbolic/substitutevarsSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..6770311caf80a7ebe88f607005184f1dea6fd4c8
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_ACADEMIC/tools/symbolic/substitutevarsSB.m
@@ -0,0 +1,62 @@
+function [model] = substitutevarsSB(model)
+% substitutevarsSB: For each of the selected reactions substitutes variables
+% into the reaction rate expression, thereby creating a expression
+% consisting solely of parameters and states. 
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+academicWarningSB
+
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% check if symbolic toolbox is present
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~symbolicpresentSB,
+    error('The model reduction feature requires the presence of the symbolic toolbox.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% substitution
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[variablenames, variableformulas] = SBvariables(model);
+sbs = struct(model);
+% For all reactions
+for k = 1:length(sbs.reactions)
+    % reaction rate formula
+    formula = sbs.reactions(k).formula;
+    % determines all variables and parameters in expression
+    match = regexp(formula,'\w+','match');
+    members = find(ismember(variablenames, match)');
+    while ~eq(sum(members), 0)
+        % Substitutes relevant variable expressions into reaction
+        formula = char(subs(formula, variablenames(members), variableformulas(members)));
+        % updates list of variables found in reaction rate expression
+        match = regexp(formula,'\w+','match');
+        members = find(ismember(variablenames, match)', 1);
+    end
+    % sets new reactionformula
+    sbs.reactions(k).formula = formula;
+end
+model = SBmodel(sbs);
+model = cleanmodelSB(model,1);
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/MeasurementExample.csv b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/MeasurementExample.csv
new file mode 100644
index 0000000000000000000000000000000000000000..8b710af330952603500d0e9a3abe8f0937f5fc9a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/MeasurementExample.csv
@@ -0,0 +1,82 @@
+% Example measurement data file in the format required by the SBTOOLBOX2
+% ======================================================================
+%
+% A line starting with the percentage character "%" is interpreted as a
+% comment line and neglected during the import of the measurement data.
+
+[Name]
+% The following line defines the name of the measurement data
+% It makes sense to keep the name relatively short.
+Measurement Example CSV
+
+[Notes]
+Here you can enter information about the experiment and the data. 
+Experimental conditions, when the measurement was performed, everything you
+think will be of use to you later.
+
+[Components]
+% A comma separated list, defininig the names of the measured components.
+% If data are to be used for parameter estimation, names should be chosen 
+% as they appear in the model.
+time,A,A+,A-,B,C
+
+% The 'time' component should always be called 'time'!
+
+% Note the A+ and A-: A component name, followed by + or - defines the error
+% max/min errorbounds for the corresponding component.
+
+[Componentnotes]
+% For each component a note can be defined. The syntax is as follows:
+A: Component A
+B: Component B
+% IMPORTANT: To min/max errorbounds no comment can be added.
+
+[Values]
+% Finally, here are the data defined for the components. In this example the 
+% time-vector is defined in the first column (which is not required but makes 
+% most sense). The time vector consists of all time instants at which 
+% measurements have been made. If a certain component has not been measured 
+% at a certain time instant then this can be indicated by 'NaN' or not 
+% entering a value for this time step. See example below.
+0, 0.0172, 0.01892, 0.01548, 0.0116, 0.0009
+49.0552, 0.0171892, 0.0189081, 0.0154703, 0.0115591, 0.000865671
+98.9524, 0.0170854, 0.0187939, 0.0153769, 0.0114354, 0.000858473
+128.814, 0.0173518, 0.019087, 0.0156166, 0.0118688, 0.000825422
+151.362, 0.0169693, 0.0186663, 0.0152724, 0.0109388, 0.00104578
+160.548, 0.0181534, 0.0199687, 0.0163381, 0.0125635, 0.00104271
+173.206, 0.0170857, 0.0187943, 0.0153772, 0.0119458, 0.000671465
+186.74, 0.0146325, 0.0160957, 0.0131692, 0.00809325, 0.0010277
+189.85, 0.0150251, 0.0165276, 0.0135226, 0.00806028, 0.00138207
+190.64, 0.0151959, 0.0167155, 0.0136763, 0.00811683, 0.00149481
+199.735, 0.0173497, 0.0190847, 0.0156147, 0.00929493, 0.00295474
+207.51, 0.0186011, 0.0204612, 0.016741,  , 0.00337649
+211.924, 0.0190048, 0.0209053, 0.0171043,  , 0.00270628
+217.317, 0.0190811, 0.0209892, 0.017173, NaN, 0.00120062
+226.538, 0.0161404, 0.0177545, 0.0145264, 0.0111411, 0.000550005
+235.681, 0.0135297, 0.0148827, 0.0121768, 0.00717188, 0.000783385
+241.166, 0.0139325, 0.0153258, 0.0125393, 0.00671213, 0.00146087
+241.697, 0.0140435, 0.0154479, 0.0126392, 0.00672502, 0.0015506
+242.971, 0.0143499, 0.0157849, 0.0129149, 0.00679063, 0.00178496
+255.948, 0.017554, 0.0193094, 0.0157986, 0.00790143, 0.00460672
+267.944, 0.0191239, 0.0210363, 0.0172115, 0.00910938, 0.00594728
+273.356, 0.0194106, 0.0213516, 0.0174695, 0.010229, 0.00548378
+277.175, 0.0194979, 0.0214477, 0.0175481, 0.0117932, 0.0042322
+282.952, 0.0190639, 0.0209703, 0.0171575, 0.0145928, 0.00117943
+287.379, 0.0171421, 0.0188563, 0.0154279, 0.0127413, 0.000630849
+297.186, 0.0135157, 0.0148673, 0.0121642, 0.00744541, 0.000596608
+304.409, 0.0138344, 0.0152178, 0.012451, 0.00667011, 0.00140572
+305.229, 0.0139956, 0.0153951, 0.012596, 0.00668163, 0.00154211
+305.791, 0.0141234, 0.0155357, 0.012711, 0.00670328, 0.00164227
+314.823, 0.0164794, 0.0181274, 0.0148315, 0.00744152, 0.00361603
+329.17, 0.0189181, 0.0208099, 0.0170263, 0.0087181, 0.0059432
+335.835, 0.0193632, 0.0212996, 0.0174269, 0.00977667, 0.00580894
+339.933, 0.0194907, 0.0214398, 0.0175416, 0.0111078, 0.00485787
+344.499, 0.0194307, 0.0213738, 0.0174877, 0.0138351, 0.00229322
+350.306, 0.0177736, 0.019551, 0.0159963, 0.0135014, 0.000718082
+358.196, 0.0140837, 0.0154921, 0.0126754, 0.00847553, 0.000474314
+366.873, 0.0136128, 0.0149741, 0.0122515, 0.00671776, 0.00116925
+369.168, 0.0139677, 0.0153644, 0.0125709, 0.00667759, 0.00152
+369.614, 0.0140658, 0.0154724, 0.0126592, 0.00669205, 0.00159802
+374.926, 0.0154593, 0.0170052, 0.0139134, 0.00709309, 0.00270825
+389.946, 0.0185564, 0.020412, 0.0167007, 0.00838632, 0.00564731
+398.345, 0.0192878, 0.0212166, 0.017359, 0.00944865, 0.00595697
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/MeasurementExample.xls b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/MeasurementExample.xls
new file mode 100644
index 0000000000000000000000000000000000000000..63a6c044e7443633cf899128b0cf478cc2a8f6fb
Binary files /dev/null and b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/MeasurementExample.xls differ
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/NovakTysonModel.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/NovakTysonModel.txt
new file mode 100644
index 0000000000000000000000000000000000000000..87e739da0434a7d2547db930941b2e7da4610a93
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/NovakTysonModel.txt
@@ -0,0 +1,92 @@
+********** MODEL NAME
+Novak-Tyson Model
+
+********** MODEL NOTES
+Novak-Tyson cell cycle model, described in J. theor. Biol. (1998) 195, 69-85
+
+********** MODEL STATES
+d/dt(Cyclin) = R1-R2-R3 %state
+d/dt(YT) = R4-R5-R6-R7+R8+R3 %state
+d/dt(PYT) = R5-R8-R9-R10+R11 %state
+d/dt(PYTP) = R12-R11-R13-R14+R9 %state
+d/dt(MPF) = R6-R4-R12-R15+R13 %state
+d/dt(Cdc25P) = R16 %state
+d/dt(Wee1P) = R17 %state
+d/dt(IEP) = R18 %state
+d/dt(APCstar) = R19 %state
+
+Cyclin(0) = 0.017200
+YT(0) = 0.011600
+PYT(0) = 0.000900
+PYTP(0) = 0.019800
+MPF(0) = 0.073000
+Cdc25P(0) = 0.949900
+Wee1P(0) = 0.949900
+IEP(0) = 0.242000
+APCstar(0) = 0.313200
+
+********** MODEL PARAMETERS
+Ka = 0.1 %parameter
+Kb = 1 %parameter
+Kc = 0.01 %parameter
+Kd = 1 %parameter
+Ke = 0.1 %parameter
+Kf = 1 %parameter
+Kg = 0.01 %parameter
+Kh = 0.01 %parameter
+k1 = 0.01 %parameter
+k3 = 0.5 %parameter
+V2p = 0.005 %parameter
+V2pp = 0.25 %parameter
+V25p = 0.017 %parameter
+V25pp = 0.17 %parameter
+Vweep = 0.01 %parameter
+Vweepp = 1 %parameter
+kcak = 0.64 %parameter
+kpp = 0.004 %parameter
+kas = 2 %parameter
+kbs = 0.1 %parameter
+kcs = 0.13 %parameter
+kds = 0.13 %parameter
+kes = 2 %parameter
+kfs = 0.1 %parameter
+kgs = 2 %parameter
+khs = 0.15 %parameter
+
+
+********** MODEL VARIABLES
+k2 = V2p+APCstar*(V2pp-V2p) %variable
+kwee = Vweepp+Wee1P*(Vweep-Vweepp) %variable
+k25 = V25p+Cdc25P*(V25pp-V25p) %variable
+
+
+********** MODEL REACTIONS
+R1 = k1 %reaction
+R2 = k2*Cyclin %reaction
+R3 = k3*Cyclin %reaction
+R4 = kpp*MPF %reaction
+R5 = kwee*YT %reaction
+R6 = kcak*YT %reaction
+R7 = k2*YT %reaction
+R8 = k25*PYT %reaction
+R9 = kcak*PYT %reaction
+R10 = k2*PYT %reaction
+R11 = kpp*PYTP %reaction
+R12 = kwee*MPF %reaction
+R13 = k25*PYTP %reaction
+R14 = k2*PYTP %reaction
+R15 = k2*MPF %reaction
+R16 = kas*MPF*(1-Cdc25P)/(1+Ka-Cdc25P)-kbs*Cdc25P/(Kb+Cdc25P) {reversible} %reaction
+R17 = kes*MPF*(1-Wee1P)/(1+Ke-Wee1P)-kfs*Wee1P/(Kf+Wee1P) {reversible} %reaction
+R18 = kgs*MPF*(1-IEP)/(1+Kg-IEP)-khs*IEP/(Kh+IEP) {reversible} %reaction
+R19 = kcs*IEP*(1-APCstar)/(1+Kc-APCstar)-kds*APCstar/(Kd+APCstar) {reversible} %reaction
+
+
+********** MODEL FUNCTIONS
+
+
+********** MODEL EVENTS
+
+
+********** MODEL MATLAB FUNCTIONS
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/SBMLexampleLevel1.xml b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/SBMLexampleLevel1.xml
new file mode 100644
index 0000000000000000000000000000000000000000..7feec327d1facf2f82434c23a66206e13289a2d8
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/SBMLexampleLevel1.xml
@@ -0,0 +1,71 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<sbml level = "1" version = "1" xmlns = "http://www.sbml.org/sbml/level1">
+   <model name = "hill">
+      <listOfCompartments>
+         <compartment name = "compart" volume = "1"/>
+      </listOfCompartments>
+      <listOfSpecies>
+         <specie boundaryCondition = "false" compartment = "compart" initialAmount = "0" name = "S1"/>
+         <specie boundaryCondition = "false" compartment = "compart" initialAmount = "0" name = "S2"/>
+         <specie boundaryCondition = "false" compartment = "compart" initialAmount = "0" name = "S3"/>
+         <specie boundaryCondition = "true" compartment = "compart" initialAmount = "0" name = "S4"/>
+         <specie boundaryCondition = "true" compartment = "compart" initialAmount = "5" name = "S0"/>
+      </listOfSpecies>
+      <listOfReactions>
+         <reaction name = "J1" reversible = "false">
+            <listOfReactants>
+               <specieReference specie = "S1" stoichiometry = "1"/>
+            </listOfReactants>
+            <listOfProducts>
+               <specieReference specie = "S2" stoichiometry = "1"/>
+            </listOfProducts>
+            <kineticLaw formula = "Vmax*S1^n/(K^n + S1^n)">
+               <listOfParameters>
+                  <parameter name = "Vmax" value = "5.5"/>
+                  <parameter name = "n" value = "4"/>
+                  <parameter name = "K" value = "0.5"/>
+               </listOfParameters>
+            </kineticLaw>
+         </reaction>
+         <reaction name = "J2" reversible = "false">
+            <listOfReactants>
+               <specieReference specie = "S2" stoichiometry = "1"/>
+            </listOfReactants>
+            <listOfProducts>
+               <specieReference specie = "S3" stoichiometry = "1"/>
+            </listOfProducts>
+            <kineticLaw formula = "J2_k*S2">
+               <listOfParameters>
+                  <parameter name = "J2_k" value = "0.1"/>
+               </listOfParameters>
+            </kineticLaw>
+         </reaction>
+         <reaction name = "J3" reversible = "false">
+            <listOfReactants>
+               <specieReference specie = "S3" stoichiometry = "1"/>
+            </listOfReactants>
+            <listOfProducts>
+               <specieReference specie = "S4" stoichiometry = "1"/>
+            </listOfProducts>
+            <kineticLaw formula = "J3_k*S3">
+               <listOfParameters>
+                  <parameter name = "J3_k" value = "0.1"/>
+               </listOfParameters>
+            </kineticLaw>
+         </reaction>
+         <reaction name = "J0" reversible = "false">
+            <listOfReactants>
+               <specieReference specie = "S0" stoichiometry = "1"/>
+            </listOfReactants>
+            <listOfProducts>
+               <specieReference specie = "S1" stoichiometry = "1"/>
+            </listOfProducts>
+            <kineticLaw formula = "J0_k*S0">
+               <listOfParameters>
+                  <parameter name = "J0_k" value = "0.01"/>
+               </listOfParameters>
+            </kineticLaw>
+         </reaction>
+      </listOfReactions>
+   </model>
+</sbml>
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/SBMLexampleLevel2.xml b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/SBMLexampleLevel2.xml
new file mode 100644
index 0000000000000000000000000000000000000000..196015afd33dd325ac87574e9bbea93dca285621
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/SBMLexampleLevel2.xml
@@ -0,0 +1,145 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<sbml level = "2" version = "1" xmlns = "http://www.sbml.org/sbml/level2">
+   <model id = "hill">
+      <listOfCompartments>
+         <compartment id = "compart" size = "1"/>
+      </listOfCompartments>
+      <listOfSpecies>
+         <species boundaryCondition = "false" compartment = "compart" id = "S1" initialConcentration = "0"/>
+         <species boundaryCondition = "false" compartment = "compart" id = "S2" initialConcentration = "0"/>
+         <species boundaryCondition = "false" compartment = "compart" id = "S3" initialConcentration = "0"/>
+         <species boundaryCondition = "true" compartment = "compart" id = "S4" initialConcentration = "0"/>
+         <species boundaryCondition = "true" compartment = "compart" id = "S0" initialConcentration = "5"/>
+      </listOfSpecies>
+      <listOfReactions>
+         <reaction id = "J1" reversible = "false">
+            <listOfReactants>
+               <speciesReference species = "S1" stoichiometry = "1"/>
+            </listOfReactants>
+            <listOfProducts>
+               <speciesReference species = "S2" stoichiometry = "1"/>
+            </listOfProducts>
+            <kineticLaw>
+               <math xmlns = "http://www.w3.org/1998/Math/MathML">
+                  <apply>
+                     <divide/>
+                     <apply>
+                        <times/>
+                        <ci>
+                               Vmax 
+                        </ci>
+                        <apply>
+                           <power/>
+                           <ci>
+                                  S1 
+                           </ci>
+                           <ci>
+                                  n 
+                           </ci>
+                        </apply>
+                     </apply>
+                     <apply>
+                        <plus/>
+                        <apply>
+                           <power/>
+                           <ci>
+                                  K 
+                           </ci>
+                           <ci>
+                                  n 
+                           </ci>
+                        </apply>
+                        <apply>
+                           <power/>
+                           <ci>
+                                  S1 
+                           </ci>
+                           <ci>
+                                  n 
+                           </ci>
+                        </apply>
+                     </apply>
+                  </apply>
+               </math>
+               <listOfParameters>
+                  <parameter id = "Vmax" value = "5.5"/>
+                  <parameter id = "n" value = "4"/>
+                  <parameter id = "K" value = "0.5"/>
+               </listOfParameters>
+            </kineticLaw>
+         </reaction>
+         <reaction id = "J2" reversible = "false">
+            <listOfReactants>
+               <speciesReference species = "S2" stoichiometry = "1"/>
+            </listOfReactants>
+            <listOfProducts>
+               <speciesReference species = "S3" stoichiometry = "1"/>
+            </listOfProducts>
+            <kineticLaw>
+               <math xmlns = "http://www.w3.org/1998/Math/MathML">
+                  <apply>
+                     <times/>
+                     <ci>
+                            J2_k 
+                     </ci>
+                     <ci>
+                            S2 
+                     </ci>
+                  </apply>
+               </math>
+               <listOfParameters>
+                  <parameter id = "J2_k" value = "0.1"/>
+               </listOfParameters>
+            </kineticLaw>
+         </reaction>
+         <reaction id = "J3" reversible = "false">
+            <listOfReactants>
+               <speciesReference species = "S3" stoichiometry = "1"/>
+            </listOfReactants>
+            <listOfProducts>
+               <speciesReference species = "S4" stoichiometry = "1"/>
+            </listOfProducts>
+            <kineticLaw>
+               <math xmlns = "http://www.w3.org/1998/Math/MathML">
+                  <apply>
+                     <times/>
+                     <ci>
+                            J3_k 
+                     </ci>
+                     <ci>
+                            S3 
+                     </ci>
+                  </apply>
+               </math>
+               <listOfParameters>
+                  <parameter id = "J3_k" value = "0.1"/>
+               </listOfParameters>
+            </kineticLaw>
+         </reaction>
+         <reaction id = "J0" reversible = "false">
+            <listOfReactants>
+               <speciesReference species = "S0" stoichiometry = "1"/>
+            </listOfReactants>
+            <listOfProducts>
+               <speciesReference species = "S1" stoichiometry = "1"/>
+            </listOfProducts>
+            <kineticLaw>
+               <math xmlns = "http://www.w3.org/1998/Math/MathML">
+                  <apply>
+                     <times/>
+                     <ci>
+                            J0_k 
+                     </ci>
+                     <ci>
+                            S0 
+                     </ci>
+                  </apply>
+               </math>
+               <listOfParameters>
+                  <parameter id = "J0_k" value = "0.01"/>
+               </listOfParameters>
+            </kineticLaw>
+         </reaction>
+      </listOfReactions>
+   </model>
+</sbml>
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/bcmodel.txtbc b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/bcmodel.txtbc
new file mode 100644
index 0000000000000000000000000000000000000000..7ed2c5e98724c4ae232be0cd6734e5f774b3c367
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/bcmodel.txtbc
@@ -0,0 +1,37 @@
+********** MODEL NAME
+test
+
+********** MODEL NOTES
+
+
+********** MODEL STATE INFORMATION
+A(0) = 0
+A2(0) = 0
+B(0) = 1
+C(0) = 0
+
+
+********** MODEL PARAMETERS
+k1 = 3.1
+
+********** MODEL VARIABLES
+
+
+********** MODEL REACTIONS
+A + B => 2*C : R1
+	vf = k1*A*B
+
+B => 3*A : R2
+	vf = 5.1*B
+
+2*A => A2 : R3
+    vf = 2.7*A^2
+
+********** MODEL FUNCTIONS
+
+
+********** MODEL EVENTS
+
+
+********** MODEL MATLAB FUNCTIONS
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/bifurcationdata.dat b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/bifurcationdata.dat
new file mode 100644
index 0000000000000000000000000000000000000000..0091f4c1f0f6c71255235455e702b117811e7942
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/bifurcationdata.dat
@@ -0,0 +1,5968 @@
+0.01 0.0729734 0.0729734 2 1 
+0.0100063 0.0729747 0.0729747 2 1 
+0.0100126 0.0729761 0.0729761 2 1 
+0.0100252 0.0729788 0.0729788 2 1 
+0.0100505 0.0729841 0.0729841 2 1 
+0.0100821 0.0729908 0.0729908 2 1 
+0.0101138 0.0729974 0.0729974 2 1 
+0.0101455 0.073004 0.073004 2 1 
+0.0101772 0.0730106 0.0730106 2 1 
+0.010209 0.0730172 0.0730172 2 1 
+0.0102409 0.0730237 0.0730237 2 1 
+0.0102727 0.0730302 0.0730302 2 1 
+0.0103046 0.0730367 0.0730367 2 1 
+0.0103366 0.0730431 0.0730431 2 1 
+0.0103686 0.0730495 0.0730495 2 1 
+0.0104006 0.0730559 0.0730559 2 1 
+0.0104326 0.0730623 0.0730623 2 1 
+0.0104648 0.0730686 0.0730686 2 1 
+0.0104969 0.0730749 0.0730749 2 1 
+0.0105291 0.0730812 0.0730812 2 1 
+0.0105613 0.0730875 0.0730875 2 1 
+0.0105936 0.0730937 0.0730937 2 1 
+0.0106259 0.0730999 0.0730999 2 1 
+0.0106582 0.0731061 0.0731061 2 1 
+0.0106906 0.0731122 0.0731122 2 1 
+0.0107231 0.0731183 0.0731183 2 1 
+0.0107555 0.0731244 0.0731244 2 1 
+0.0107881 0.0731305 0.0731305 2 1 
+0.0108206 0.0731366 0.0731366 2 1 
+0.0108532 0.0731426 0.0731426 2 1 
+0.0108858 0.0731486 0.0731486 2 1 
+0.0109185 0.0731546 0.0731546 2 1 
+0.0109512 0.0731605 0.0731605 2 1 
+0.010984 0.0731664 0.0731664 2 1 
+0.0110168 0.0731723 0.0731723 2 1 
+0.0110496 0.0731782 0.0731782 2 1 
+0.0110825 0.0731841 0.0731841 2 1 
+0.0111154 0.0731899 0.0731899 2 1 
+0.0111484 0.0731957 0.0731957 2 1 
+0.0111814 0.0732015 0.0732015 2 1 
+0.0112144 0.0732073 0.0732073 2 1 
+0.0112475 0.073213 0.073213 2 1 
+0.0112807 0.0732187 0.0732187 2 1 
+0.0113138 0.0732244 0.0732244 2 1 
+0.011347 0.0732301 0.0732301 2 1 
+0.0113803 0.0732357 0.0732357 2 1 
+0.0114136 0.0732413 0.0732413 2 1 
+0.0114469 0.073247 0.073247 2 1 
+0.0114803 0.0732525 0.0732525 2 1 
+0.0115137 0.0732581 0.0732581 2 1 
+0.0115472 0.0732636 0.0732636 2 1 
+0.0115806 0.0732692 0.0732692 2 1 
+0.0116142 0.0732747 0.0732747 2 1 
+0.0116478 0.0732801 0.0732801 2 1 
+0.0116814 0.0732856 0.0732856 2 1 
+0.0117151 0.073291 0.073291 2 1 
+0.0117488 0.0732964 0.0732964 2 1 
+0.0117825 0.0733018 0.0733018 2 1 
+0.0118163 0.0733072 0.0733072 2 1 
+0.0118501 0.0733126 0.0733126 2 1 
+0.011884 0.0733179 0.0733179 2 1 
+0.0119179 0.0733232 0.0733232 2 1 
+0.0119519 0.0733285 0.0733285 2 1 
+0.0119859 0.0733338 0.0733338 2 1 
+0.0120199 0.073339 0.073339 2 1 
+0.012054 0.0733443 0.0733443 2 1 
+0.0120881 0.0733495 0.0733495 2 1 
+0.0121223 0.0733547 0.0733547 2 1 
+0.0121565 0.0733598 0.0733598 2 1 
+0.0121907 0.073365 0.073365 2 1 
+0.012225 0.0733701 0.0733701 2 1 
+0.0122593 0.0733753 0.0733753 2 1 
+0.0122937 0.0733804 0.0733804 2 1 
+0.0123281 0.0733854 0.0733854 2 1 
+0.0123626 0.0733905 0.0733905 2 1 
+0.0123971 0.0733956 0.0733956 2 1 
+0.0124316 0.0734006 0.0734006 2 1 
+0.0124662 0.0734056 0.0734056 2 1 
+0.0125008 0.0734106 0.0734106 2 1 
+0.0125355 0.0734156 0.0734156 2 1 
+0.0125702 0.0734205 0.0734205 2 1 
+0.0126049 0.0734255 0.0734255 2 1 
+0.0126397 0.0734304 0.0734304 2 1 
+0.0126745 0.0734353 0.0734353 2 1 
+0.0127094 0.0734402 0.0734402 2 1 
+0.0127443 0.073445 0.073445 2 1 
+0.0127793 0.0734499 0.0734499 2 1 
+0.0128143 0.0734547 0.0734547 2 1 
+0.0128493 0.0734595 0.0734595 2 1 
+0.0128844 0.0734643 0.0734643 2 1 
+0.0129195 0.0734691 0.0734691 2 1 
+0.0129547 0.0734739 0.0734739 2 1 
+0.0129899 0.0734787 0.0734787 2 1 
+0.0130252 0.0734834 0.0734834 2 1 
+0.0130605 0.0734881 0.0734881 2 1 
+0.0130958 0.0734928 0.0734928 2 1 
+0.0131312 0.0734975 0.0734975 2 1 
+0.0131666 0.0735022 0.0735022 2 1 
+0.0132021 0.0735068 0.0735068 2 1 
+0.0132376 0.0735115 0.0735115 2 1 
+0.0132731 0.0735161 0.0735161 2 1 
+0.0133087 0.0735207 0.0735207 2 1 
+0.0133444 0.0735253 0.0735253 2 1 
+0.01338 0.0735299 0.0735299 2 1 
+0.0134157 0.0735345 0.0735345 2 1 
+0.0134515 0.073539 0.073539 2 1 
+0.0134873 0.0735435 0.0735435 2 1 
+0.0135232 0.0735481 0.0735481 2 1 
+0.0135591 0.0735526 0.0735526 2 1 
+0.013595 0.073557 0.073557 2 1 
+0.013631 0.0735615 0.0735615 2 1 
+0.013667 0.073566 0.073566 2 1 
+0.013703 0.0735704 0.0735704 2 1 
+0.0137391 0.0735749 0.0735749 2 1 
+0.0137753 0.0735793 0.0735793 2 1 
+0.0138115 0.0735837 0.0735837 2 1 
+0.0138477 0.0735881 0.0735881 2 1 
+0.013884 0.0735924 0.0735924 2 1 
+0.0139203 0.0735968 0.0735968 2 1 
+0.0139567 0.0736011 0.0736011 2 1 
+0.0139931 0.0736055 0.0736055 2 1 
+0.0140295 0.0736098 0.0736098 2 1 
+0.014066 0.0736141 0.0736141 2 1 
+0.0141025 0.0736184 0.0736184 2 1 
+0.0141391 0.0736227 0.0736227 2 1 
+0.0141757 0.0736269 0.0736269 2 1 
+0.0142124 0.0736312 0.0736312 2 1 
+0.0142491 0.0736354 0.0736354 2 1 
+0.0142858 0.0736397 0.0736397 2 1 
+0.0143226 0.0736439 0.0736439 2 1 
+0.0143594 0.0736481 0.0736481 2 1 
+0.0143963 0.0736522 0.0736522 2 1 
+0.0144332 0.0736564 0.0736564 2 1 
+0.0144702 0.0736606 0.0736606 2 1 
+0.0145072 0.0736647 0.0736647 2 1 
+0.0145443 0.0736689 0.0736689 2 1 
+0.0145813 0.073673 0.073673 2 1 
+0.0146185 0.0736771 0.0736771 2 1 
+0.0146557 0.0736812 0.0736812 2 1 
+0.0146929 0.0736853 0.0736853 2 1 
+0.0147301 0.0736893 0.0736893 2 1 
+0.0147674 0.0736934 0.0736934 2 1 
+0.0148048 0.0736975 0.0736975 2 1 
+0.0148422 0.0737015 0.0737015 2 1 
+0.0148796 0.0737055 0.0737055 2 1 
+0.0149171 0.0737095 0.0737095 2 1 
+0.0149546 0.0737135 0.0737135 2 1 
+0.0149922 0.0737175 0.0737175 2 1 
+0.0150298 0.0737215 0.0737215 2 1 
+0.0150675 0.0737255 0.0737255 2 1 
+0.0151052 0.0737294 0.0737294 2 1 
+0.0151429 0.0737334 0.0737334 2 1 
+0.0151807 0.0737373 0.0737373 2 1 
+0.0152185 0.0737412 0.0737412 2 1 
+0.0152564 0.0737451 0.0737451 2 1 
+0.0152943 0.073749 0.073749 2 1 
+0.0153322 0.0737529 0.0737529 2 1 
+0.0153702 0.0737568 0.0737568 2 1 
+0.0154083 0.0737606 0.0737606 2 1 
+0.0154464 0.0737645 0.0737645 2 1 
+0.0154845 0.0737683 0.0737683 2 1 
+0.0155227 0.0737722 0.0737722 2 1 
+0.0155609 0.073776 0.073776 2 1 
+0.0155992 0.0737798 0.0737798 2 1 
+0.0156375 0.0737836 0.0737836 2 1 
+0.0156758 0.0737874 0.0737874 2 1 
+0.0157142 0.0737911 0.0737911 2 1 
+0.0157527 0.0737949 0.0737949 2 1 
+0.0157911 0.0737987 0.0737987 2 1 
+0.0158297 0.0738024 0.0738024 2 1 
+0.0158682 0.0738061 0.0738061 2 1 
+0.0159069 0.0738099 0.0738099 2 1 
+0.0159455 0.0738136 0.0738136 2 1 
+0.0159842 0.0738173 0.0738173 2 1 
+0.016023 0.073821 0.073821 2 1 
+0.0160617 0.0738247 0.0738247 2 1 
+0.0161006 0.0738283 0.0738283 2 1 
+0.0161395 0.073832 0.073832 2 1 
+0.0161784 0.0738356 0.0738356 2 1 
+0.0162173 0.0738393 0.0738393 2 1 
+0.0162563 0.0738429 0.0738429 2 1 
+0.0162954 0.0738466 0.0738466 2 1 
+0.0163345 0.0738502 0.0738502 2 1 
+0.0163736 0.0738538 0.0738538 2 1 
+0.0164128 0.0738574 0.0738574 2 1 
+0.0164521 0.0738609 0.0738609 2 1 
+0.0164913 0.0738645 0.0738645 2 1 
+0.0165306 0.0738681 0.0738681 2 1 
+0.01657 0.0738717 0.0738717 2 1 
+0.0166094 0.0738752 0.0738752 2 1 
+0.0166489 0.0738787 0.0738787 2 1 
+0.0166884 0.0738823 0.0738823 2 1 
+0.0167279 0.0738858 0.0738858 2 1 
+0.0167675 0.0738893 0.0738893 2 1 
+0.0168071 0.0738928 0.0738928 2 1 
+0.0168468 0.0738963 0.0738963 2 1 
+0.0168865 0.0738998 0.0738998 2 1 
+0.0169262 0.0739033 0.0739033 2 1 
+0.016966 0.0739067 0.0739067 2 1 
+0.0170059 0.0739102 0.0739102 2 1 
+0.0170458 0.0739136 0.0739136 2 1 
+0.0170857 0.0739171 0.0739171 2 1 
+0.0171257 0.0739205 0.0739205 2 1 
+0.0171657 0.0739239 0.0739239 2 1 
+0.0172058 0.0739273 0.0739273 2 1 
+0.0172459 0.0739307 0.0739307 2 1 
+0.0172861 0.0739341 0.0739341 2 1 
+0.0173263 0.0739375 0.0739375 2 1 
+0.0173665 0.0739409 0.0739409 2 1 
+0.0174068 0.0739443 0.0739443 2 1 
+0.0174471 0.0739476 0.0739476 2 1 
+0.0174875 0.073951 0.073951 2 1 
+0.017528 0.0739543 0.0739543 2 1 
+0.0175684 0.0739577 0.0739577 2 1 
+0.0176089 0.073961 0.073961 2 1 
+0.0176495 0.0739643 0.0739643 2 1 
+0.0176901 0.0739676 0.0739676 2 1 
+0.0177308 0.073971 0.073971 2 1 
+0.0177714 0.0739742 0.0739742 2 1 
+0.0178122 0.0739775 0.0739775 2 1 
+0.017853 0.0739808 0.0739808 2 1 
+0.0178938 0.0739841 0.0739841 2 1 
+0.0179347 0.0739874 0.0739874 2 1 
+0.0179756 0.0739906 0.0739906 2 1 
+0.0180165 0.0739939 0.0739939 2 1 
+0.0180575 0.0739971 0.0739971 2 1 
+0.0180986 0.0740004 0.0740004 2 1 
+0.0181397 0.0740036 0.0740036 2 1 
+0.0181808 0.0740068 0.0740068 2 1 
+0.018222 0.07401 0.07401 2 1 
+0.0182632 0.0740132 0.0740132 2 1 
+0.0183045 0.0740164 0.0740164 2 1 
+0.0183458 0.0740196 0.0740196 2 1 
+0.0183872 0.0740228 0.0740228 2 1 
+0.0184286 0.074026 0.074026 2 1 
+0.0184701 0.0740291 0.0740291 2 1 
+0.0185116 0.0740323 0.0740323 2 1 
+0.0185531 0.0740355 0.0740355 2 1 
+0.0185947 0.0740386 0.0740386 2 1 
+0.0186363 0.0740417 0.0740417 2 1 
+0.018678 0.0740449 0.0740449 2 1 
+0.0187197 0.074048 0.074048 2 1 
+0.0187615 0.0740511 0.0740511 2 1 
+0.0188033 0.0740542 0.0740542 2 1 
+0.0188452 0.0740573 0.0740573 2 1 
+0.0188871 0.0740604 0.0740604 2 1 
+0.018929 0.0740635 0.0740635 2 1 
+0.018971 0.0740666 0.0740666 2 1 
+0.0190131 0.0740697 0.0740697 2 1 
+0.0190552 0.0740728 0.0740728 2 1 
+0.0190973 0.0740758 0.0740758 2 1 
+0.0191395 0.0740789 0.0740789 2 1 
+0.0191817 0.0740819 0.0740819 2 1 
+0.0192239 0.074085 0.074085 2 1 
+0.0192663 0.074088 0.074088 2 1 
+0.0193086 0.0740911 0.0740911 2 1 
+0.019351 0.0740941 0.0740941 2 1 
+0.0193935 0.0740971 0.0740971 2 1 
+0.0194359 0.0741001 0.0741001 2 1 
+0.0194785 0.0741031 0.0741031 2 1 
+0.0195211 0.0741061 0.0741061 2 1 
+0.0195637 0.0741091 0.0741091 2 1 
+0.0196064 0.0741121 0.0741121 2 1 
+0.0196491 0.0741151 0.0741151 2 1 
+0.0196918 0.074118 0.074118 2 1 
+0.0197346 0.074121 0.074121 2 1 
+0.0197775 0.074124 0.074124 2 1 
+0.0198204 0.0741269 0.0741269 2 1 
+0.0198633 0.0741299 0.0741299 2 1 
+0.0199063 0.0741328 0.0741328 2 1 
+0.0199494 0.0741358 0.0741358 2 1 
+0.0199924 0.0741387 0.0741387 2 1 
+0.0200356 0.0741416 0.0741416 2 1 
+0.0200787 0.0741445 0.0741445 2 1 
+0.0201219 0.0741475 0.0741475 2 1 
+0.0201652 0.0741504 0.0741504 2 1 
+0.0202085 0.0741533 0.0741533 2 1 
+0.0202519 0.0741562 0.0741562 2 1 
+0.0202953 0.0741591 0.0741591 2 1 
+0.0203387 0.0741619 0.0741619 2 1 
+0.0203822 0.0741648 0.0741648 2 1 
+0.0204257 0.0741677 0.0741677 2 1 
+0.0204693 0.0741706 0.0741706 2 1 
+0.0205129 0.0741734 0.0741734 2 1 
+0.0205566 0.0741763 0.0741763 2 1 
+0.0206003 0.0741791 0.0741791 2 1 
+0.0206441 0.074182 0.074182 2 1 
+0.0206879 0.0741848 0.0741848 2 1 
+0.0207317 0.0741876 0.0741876 2 1 
+0.0207756 0.0741905 0.0741905 2 1 
+0.0208196 0.0741933 0.0741933 2 1 
+0.0208636 0.0741961 0.0741961 2 1 
+0.0209076 0.0741989 0.0741989 2 1 
+0.0209517 0.0742017 0.0742017 2 1 
+0.0209958 0.0742045 0.0742045 2 1 
+0.02104 0.0742073 0.0742073 2 1 
+0.0210842 0.0742101 0.0742101 2 1 
+0.0211285 0.0742129 0.0742129 2 1 
+0.0211728 0.0742157 0.0742157 2 1 
+0.0212171 0.0742185 0.0742185 2 1 
+0.0212615 0.0742213 0.0742213 2 1 
+0.021306 0.074224 0.074224 2 1 
+0.0213505 0.0742268 0.0742268 2 1 
+0.021395 0.0742295 0.0742295 2 1 
+0.0214396 0.0742323 0.0742323 2 1 
+0.0214842 0.074235 0.074235 2 1 
+0.0215289 0.0742378 0.0742378 2 1 
+0.0215736 0.0742405 0.0742405 2 1 
+0.0216184 0.0742432 0.0742432 2 1 
+0.0216632 0.074246 0.074246 2 1 
+0.021708 0.0742487 0.0742487 2 1 
+0.0217529 0.0742514 0.0742514 2 1 
+0.0217979 0.0742541 0.0742541 2 1 
+0.0218429 0.0742568 0.0742568 2 1 
+0.0218879 0.0742595 0.0742595 2 1 
+0.021933 0.0742622 0.0742622 2 1 
+0.0219781 0.0742649 0.0742649 2 1 
+0.0220233 0.0742676 0.0742676 2 1 
+0.0220685 0.0742703 0.0742703 2 1 
+0.0221138 0.074273 0.074273 2 1 
+0.0221591 0.0742757 0.0742757 2 1 
+0.0222045 0.0742783 0.0742783 2 1 
+0.0222499 0.074281 0.074281 2 1 
+0.0222953 0.0742837 0.0742837 2 1 
+0.0223408 0.0742863 0.0742863 2 1 
+0.0223864 0.074289 0.074289 2 1 
+0.0224319 0.0742916 0.0742916 2 1 
+0.0224776 0.0742943 0.0742943 2 1 
+0.0225233 0.0742969 0.0742969 2 1 
+0.022569 0.0742995 0.0742995 2 1 
+0.0226148 0.0743022 0.0743022 2 1 
+0.0226606 0.0743048 0.0743048 2 1 
+0.0227064 0.0743074 0.0743074 2 1 
+0.0227523 0.07431 0.07431 2 1 
+0.0227983 0.0743126 0.0743126 2 1 
+0.0228443 0.0743153 0.0743153 2 1 
+0.0228903 0.0743179 0.0743179 2 1 
+0.0229364 0.0743205 0.0743205 2 1 
+0.0229826 0.0743231 0.0743231 2 1 
+0.0230288 0.0743257 0.0743257 2 1 
+0.023075 0.0743282 0.0743282 2 1 
+0.0231213 0.0743308 0.0743308 2 1 
+0.0231676 0.0743334 0.0743334 2 1 
+0.023214 0.074336 0.074336 2 1 
+0.0232604 0.0743386 0.0743386 2 1 
+0.0233068 0.0743411 0.0743411 2 1 
+0.0233533 0.0743437 0.0743437 2 1 
+0.0233999 0.0743463 0.0743463 2 1 
+0.0234465 0.0743488 0.0743488 2 1 
+0.0234931 0.0743514 0.0743514 2 1 
+0.0235398 0.0743539 0.0743539 2 1 
+0.0235865 0.0743565 0.0743565 2 1 
+0.0236333 0.074359 0.074359 2 1 
+0.0236802 0.0743616 0.0743616 2 1 
+0.023727 0.0743641 0.0743641 2 1 
+0.0237739 0.0743666 0.0743666 2 1 
+0.0238209 0.0743692 0.0743692 2 1 
+0.0238679 0.0743717 0.0743717 2 1 
+0.023915 0.0743742 0.0743742 2 1 
+0.0239621 0.0743767 0.0743767 2 1 
+0.0240092 0.0743792 0.0743792 2 1 
+0.0240564 0.0743818 0.0743818 2 1 
+0.0241037 0.0743843 0.0743843 2 1 
+0.0241509 0.0743868 0.0743868 2 1 
+0.0241983 0.0743893 0.0743893 2 1 
+0.0242456 0.0743918 0.0743918 2 1 
+0.0242931 0.0743943 0.0743943 2 1 
+0.0243405 0.0743968 0.0743968 2 1 
+0.024388 0.0743992 0.0743992 2 1 
+0.0244356 0.0744017 0.0744017 2 1 
+0.0244832 0.0744042 0.0744042 2 1 
+0.0245309 0.0744067 0.0744067 2 1 
+0.0245786 0.0744092 0.0744092 2 1 
+0.0246263 0.0744116 0.0744116 2 1 
+0.0246741 0.0744141 0.0744141 2 1 
+0.0247219 0.0744166 0.0744166 2 1 
+0.0247698 0.074419 0.074419 2 1 
+0.0248177 0.0744215 0.0744215 2 1 
+0.0248657 0.074424 0.074424 2 1 
+0.0249137 0.0744264 0.0744264 2 1 
+0.0249618 0.0744289 0.0744289 2 1 
+0.0250099 0.0744313 0.0744313 2 1 
+0.025058 0.0744337 0.0744337 2 1 
+0.0251062 0.0744362 0.0744362 2 1 
+0.0251545 0.0744386 0.0744386 2 1 
+0.0252028 0.0744411 0.0744411 2 1 
+0.0252511 0.0744435 0.0744435 2 1 
+0.0252995 0.0744459 0.0744459 2 1 
+0.0253479 0.0744483 0.0744483 2 1 
+0.0253964 0.0744508 0.0744508 2 1 
+0.0254449 0.0744532 0.0744532 2 1 
+0.0254935 0.0744556 0.0744556 2 1 
+0.0255421 0.074458 0.074458 2 1 
+0.0255907 0.0744604 0.0744604 2 1 
+0.0256394 0.0744629 0.0744629 2 1 
+0.0256882 0.0744653 0.0744653 2 1 
+0.025737 0.0744677 0.0744677 2 1 
+0.0257858 0.0744701 0.0744701 2 1 
+0.0258347 0.0744725 0.0744725 2 1 
+0.0258836 0.0744749 0.0744749 2 1 
+0.0259326 0.0744773 0.0744773 2 1 
+0.0259816 0.0744797 0.0744797 2 1 
+0.0260307 0.074482 0.074482 2 1 
+0.0260798 0.0744844 0.0744844 2 1 
+0.0261289 0.0744868 0.0744868 2 1 
+0.0261781 0.0744892 0.0744892 2 1 
+0.0262274 0.0744916 0.0744916 2 1 
+0.0262767 0.074494 0.074494 2 1 
+0.026326 0.0744963 0.0744963 2 1 
+0.0263754 0.0744987 0.0744987 2 1 
+0.0264248 0.0745011 0.0745011 2 1 
+0.0264743 0.0745034 0.0745034 2 1 
+0.0265238 0.0745058 0.0745058 2 1 
+0.0265734 0.0745082 0.0745082 2 1 
+0.026623 0.0745105 0.0745105 2 1 
+0.0266726 0.0745129 0.0745129 2 1 
+0.0267223 0.0745153 0.0745153 2 1 
+0.0267721 0.0745176 0.0745176 2 1 
+0.0268219 0.07452 0.07452 2 1 
+0.0268717 0.0745223 0.0745223 2 1 
+0.0269216 0.0745247 0.0745247 2 1 
+0.0269715 0.074527 0.074527 2 1 
+0.0270215 0.0745294 0.0745294 2 1 
+0.0270715 0.0745317 0.0745317 2 1 
+0.0271215 0.0745341 0.0745341 2 1 
+0.0271716 0.0745364 0.0745364 2 1 
+0.0272218 0.0745387 0.0745387 2 1 
+0.027272 0.0745411 0.0745411 2 1 
+0.0273222 0.0745434 0.0745434 2 1 
+0.0273725 0.0745457 0.0745457 2 1 
+0.0274228 0.0745481 0.0745481 2 1 
+0.0274732 0.0745504 0.0745504 2 1 
+0.0275236 0.0745527 0.0745527 2 1 
+0.0275741 0.0745551 0.0745551 2 1 
+0.0276246 0.0745574 0.0745574 2 1 
+0.0276751 0.0745597 0.0745597 2 1 
+0.0277257 0.074562 0.074562 2 1 
+0.0277764 0.0745643 0.0745643 2 1 
+0.027827 0.0745667 0.0745667 2 1 
+0.0278778 0.074569 0.074569 2 1 
+0.0279285 0.0745713 0.0745713 2 1 
+0.0279794 0.0745736 0.0745736 2 1 
+0.0280302 0.0745759 0.0745759 2 1 
+0.0280811 0.0745782 0.0745782 2 1 
+0.0281321 0.0745805 0.0745805 2 1 
+0.0281831 0.0745829 0.0745829 2 1 
+0.0282341 0.0745852 0.0745852 2 1 
+0.0282852 0.0745875 0.0745875 2 1 
+0.0283363 0.0745898 0.0745898 2 1 
+0.0283875 0.0745921 0.0745921 2 1 
+0.0284387 0.0745944 0.0745944 2 1 
+0.0284899 0.0745967 0.0745967 2 1 
+0.0285412 0.074599 0.074599 2 1 
+0.0285926 0.0746013 0.0746013 2 1 
+0.028644 0.0746036 0.0746036 2 1 
+0.0286954 0.0746059 0.0746059 2 1 
+0.0287469 0.0746082 0.0746082 2 1 
+0.0287984 0.0746105 0.0746105 2 1 
+0.0288499 0.0746128 0.0746128 2 1 
+0.0289015 0.0746151 0.0746151 2 1 
+0.0289532 0.0746174 0.0746174 2 1 
+0.0290049 0.0746196 0.0746196 2 1 
+0.0290566 0.0746219 0.0746219 2 1 
+0.0291084 0.0746242 0.0746242 2 1 
+0.0291602 0.0746265 0.0746265 2 1 
+0.0292121 0.0746288 0.0746288 2 1 
+0.029264 0.0746311 0.0746311 2 1 
+0.0293159 0.0746334 0.0746334 2 1 
+0.0293679 0.0746357 0.0746357 2 1 
+0.0294199 0.074638 0.074638 2 1 
+0.029472 0.0746402 0.0746402 2 1 
+0.0295241 0.0746425 0.0746425 2 1 
+0.0295763 0.0746448 0.0746448 2 1 
+0.0296285 0.0746471 0.0746471 2 1 
+0.0296807 0.0746494 0.0746494 2 1 
+0.029733 0.0746517 0.0746517 2 1 
+0.0297853 0.0746539 0.0746539 2 1 
+0.0298377 0.0746562 0.0746562 2 1 
+0.0298901 0.0746585 0.0746585 2 1 
+0.0299426 0.0746608 0.0746608 2 1 
+0.0299951 0.0746631 0.0746631 2 1 
+0.0300476 0.0746654 0.0746654 2 1 
+0.0301002 0.0746676 0.0746676 2 1 
+0.0301528 0.0746699 0.0746699 2 1 
+0.0302055 0.0746722 0.0746722 2 1 
+0.0302582 0.0746745 0.0746745 2 1 
+0.0303109 0.0746768 0.0746768 2 1 
+0.0303637 0.0746791 0.0746791 2 1 
+0.0304165 0.0746813 0.0746813 2 1 
+0.0304694 0.0746836 0.0746836 2 1 
+0.0305223 0.0746859 0.0746859 2 1 
+0.0305752 0.0746882 0.0746882 2 1 
+0.0306282 0.0746905 0.0746905 2 1 
+0.0306813 0.0746928 0.0746928 2 1 
+0.0307343 0.074695 0.074695 2 1 
+0.0307874 0.0746973 0.0746973 2 1 
+0.0308406 0.0746996 0.0746996 2 1 
+0.0308938 0.0747019 0.0747019 2 1 
+0.030947 0.0747042 0.0747042 2 1 
+0.0310003 0.0747065 0.0747065 2 1 
+0.0310536 0.0747088 0.0747088 2 1 
+0.0311069 0.0747111 0.0747111 2 1 
+0.0311603 0.0747133 0.0747133 2 1 
+0.0312137 0.0747156 0.0747156 2 1 
+0.0312672 0.0747179 0.0747179 2 1 
+0.0313207 0.0747202 0.0747202 2 1 
+0.0313742 0.0747225 0.0747225 2 1 
+0.0314278 0.0747248 0.0747248 2 1 
+0.0314814 0.0747271 0.0747271 2 1 
+0.0315351 0.0747294 0.0747294 2 1 
+0.0315888 0.0747317 0.0747317 2 1 
+0.0316425 0.074734 0.074734 2 1 
+0.0316963 0.0747363 0.0747363 2 1 
+0.0317501 0.0747386 0.0747386 2 1 
+0.0318039 0.0747409 0.0747409 2 1 
+0.0318578 0.0747432 0.0747432 2 1 
+0.0319117 0.0747455 0.0747455 2 1 
+0.0319657 0.0747478 0.0747478 2 1 
+0.0320197 0.0747501 0.0747501 2 1 
+0.0320737 0.0747524 0.0747524 2 1 
+0.0321278 0.0747547 0.0747547 2 1 
+0.0321819 0.0747571 0.0747571 2 1 
+0.032236 0.0747594 0.0747594 2 1 
+0.0322902 0.0747617 0.0747617 2 1 
+0.0323444 0.074764 0.074764 2 1 
+0.0323986 0.0747663 0.0747663 2 1 
+0.0324529 0.0747687 0.0747687 2 1 
+0.0325072 0.074771 0.074771 2 1 
+0.0325615 0.0747733 0.0747733 2 1 
+0.0326159 0.0747756 0.0747756 2 1 
+0.0326703 0.074778 0.074778 2 1 
+0.0327248 0.0747803 0.0747803 2 1 
+0.0327793 0.0747826 0.0747826 2 1 
+0.0328338 0.074785 0.074785 2 1 
+0.0328883 0.0747873 0.0747873 2 1 
+0.0329429 0.0747897 0.0747897 2 1 
+0.0329975 0.074792 0.074792 2 1 
+0.0330521 0.0747944 0.0747944 2 1 
+0.0331068 0.0747967 0.0747967 2 1 
+0.0331615 0.0747991 0.0747991 2 1 
+0.0332163 0.0748014 0.0748014 2 1 
+0.033271 0.0748038 0.0748038 2 1 
+0.0333258 0.0748062 0.0748062 2 1 
+0.0333807 0.0748085 0.0748085 2 1 
+0.0334355 0.0748109 0.0748109 2 1 
+0.0334904 0.0748133 0.0748133 2 1 
+0.0335453 0.0748157 0.0748157 2 1 
+0.0336003 0.074818 0.074818 2 1 
+0.0336552 0.0748204 0.0748204 2 1 
+0.0337102 0.0748228 0.0748228 2 1 
+0.0337653 0.0748252 0.0748252 2 1 
+0.0338203 0.0748276 0.0748276 2 1 
+0.0338754 0.07483 0.07483 2 1 
+0.0339305 0.0748324 0.0748324 2 1 
+0.0339856 0.0748348 0.0748348 2 1 
+0.0340408 0.0748372 0.0748372 2 1 
+0.034096 0.0748396 0.0748396 2 1 
+0.0341512 0.0748421 0.0748421 2 1 
+0.0342064 0.0748445 0.0748445 2 1 
+0.0342617 0.0748469 0.0748469 2 1 
+0.034317 0.0748494 0.0748494 2 1 
+0.0343723 0.0748518 0.0748518 2 1 
+0.0344276 0.0748542 0.0748542 2 1 
+0.034483 0.0748567 0.0748567 2 1 
+0.0345384 0.0748591 0.0748591 2 1 
+0.0345937 0.0748616 0.0748616 2 1 
+0.0346492 0.0748641 0.0748641 2 1 
+0.0347046 0.0748665 0.0748665 2 1 
+0.0347601 0.074869 0.074869 2 1 
+0.0348155 0.0748715 0.0748715 2 1 
+0.034871 0.074874 0.074874 2 1 
+0.0349265 0.0748765 0.0748765 2 1 
+0.0349821 0.074879 0.074879 2 1 
+0.0350376 0.0748815 0.0748815 2 1 
+0.0350932 0.074884 0.074884 2 1 
+0.0351487 0.0748865 0.0748865 2 1 
+0.0352043 0.074889 0.074889 2 1 
+0.0352599 0.0748916 0.0748916 2 1 
+0.0353155 0.0748941 0.0748941 2 1 
+0.0353712 0.0748966 0.0748966 2 1 
+0.0354268 0.0748992 0.0748992 2 1 
+0.0354825 0.0749018 0.0749018 2 1 
+0.0355381 0.0749043 0.0749043 2 1 
+0.0355938 0.0749069 0.0749069 2 1 
+0.0356495 0.0749095 0.0749095 2 1 
+0.0357052 0.0749121 0.0749121 2 1 
+0.0357609 0.0749146 0.0749146 2 1 
+0.0358166 0.0749173 0.0749173 2 1 
+0.0358723 0.0749199 0.0749199 2 1 
+0.035928 0.0749225 0.0749225 2 1 
+0.0359837 0.0749251 0.0749251 2 1 
+0.0360394 0.0749277 0.0749277 2 1 
+0.0360952 0.0749304 0.0749304 2 1 
+0.0361509 0.074933 0.074933 2 1 
+0.0362066 0.0749357 0.0749357 2 1 
+0.0362623 0.0749384 0.0749384 2 1 
+0.036318 0.0749411 0.0749411 2 1 
+0.0363737 0.0749437 0.0749437 2 1 
+0.0364295 0.0749464 0.0749464 2 1 
+0.0364852 0.0749492 0.0749492 2 1 
+0.0365409 0.0749519 0.0749519 2 1 
+0.0365965 0.0749546 0.0749546 2 1 
+0.0366522 0.0749573 0.0749573 2 1 
+0.0367079 0.0749601 0.0749601 2 1 
+0.0367635 0.0749629 0.0749629 2 1 
+0.0368192 0.0749656 0.0749656 2 1 
+0.0368748 0.0749684 0.0749684 2 1 
+0.0369304 0.0749712 0.0749712 2 1 
+0.036986 0.074974 0.074974 2 1 
+0.0370416 0.0749768 0.0749768 2 1 
+0.0370972 0.0749796 0.0749796 2 1 
+0.0371527 0.0749825 0.0749825 2 1 
+0.0372082 0.0749853 0.0749853 2 1 
+0.0372637 0.0749882 0.0749882 2 1 
+0.0373192 0.0749911 0.0749911 2 1 
+0.0373746 0.074994 0.074994 2 1 
+0.03743 0.0749969 0.0749969 2 1 
+0.0374854 0.0749998 0.0749998 2 1 
+0.0375407 0.0750027 0.0750027 2 1 
+0.0375961 0.0750057 0.0750057 2 1 
+0.0376513 0.0750086 0.0750086 2 1 
+0.0377066 0.0750116 0.0750116 2 1 
+0.0377617 0.0750146 0.0750146 2 1 
+0.0378169 0.0750176 0.0750176 2 1 
+0.037872 0.0750206 0.0750206 2 1 
+0.0379271 0.0750236 0.0750236 2 1 
+0.0379821 0.0750267 0.0750267 2 1 
+0.038037 0.0750297 0.0750297 2 1 
+0.0380919 0.0750328 0.0750328 2 1 
+0.0381468 0.0750359 0.0750359 2 1 
+0.0382016 0.075039 0.075039 2 1 
+0.0382563 0.0750421 0.0750421 2 1 
+0.038311 0.0750453 0.0750453 2 1 
+0.0383656 0.0750485 0.0750485 2 1 
+0.0384201 0.0750516 0.0750516 2 1 
+0.0384746 0.0750548 0.0750548 2 1 
+0.038529 0.075058 0.075058 2 1 
+0.0385833 0.0750613 0.0750613 2 1 
+0.0386375 0.0750645 0.0750645 2 1 
+0.0386917 0.0750678 0.0750678 2 1 
+0.0387458 0.0750711 0.0750711 2 1 
+0.0387998 0.0750744 0.0750744 2 1 
+0.0388537 0.0750777 0.0750777 2 1 
+0.0389075 0.0750811 0.0750811 2 1 
+0.0389612 0.0750844 0.0750844 2 1 
+0.0390148 0.0750878 0.0750878 2 1 
+0.0390683 0.0750912 0.0750912 2 1 
+0.0391217 0.0750946 0.0750946 2 1 
+0.039175 0.0750981 0.0750981 2 1 
+0.0392282 0.0751016 0.0751016 2 1 
+0.0392812 0.0751051 0.0751051 2 1 
+0.0393342 0.0751086 0.0751086 2 1 
+0.039387 0.0751121 0.0751121 2 1 
+0.0394397 0.0751157 0.0751157 2 1 
+0.0394923 0.0751193 0.0751193 2 1 
+0.0395447 0.0751229 0.0751229 2 1 
+0.039597 0.0751265 0.0751265 2 1 
+0.0396491 0.0751301 0.0751301 2 1 
+0.0397011 0.0751338 0.0751338 2 1 
+0.039753 0.0751375 0.0751375 2 1 
+0.0398047 0.0751412 0.0751412 2 1 
+0.0398562 0.075145 0.075145 2 1 
+0.0399076 0.0751488 0.0751488 2 1 
+0.0399588 0.0751526 0.0751526 2 1 
+0.0400099 0.0751564 0.0751564 2 1 
+0.0400608 0.0751603 0.0751603 2 1 
+0.0401114 0.0751641 0.0751641 2 1 
+0.040162 0.075168 0.075168 2 1 
+0.0402123 0.075172 0.075172 2 1 
+0.0402624 0.0751759 0.0751759 2 1 
+0.0403124 0.0751799 0.0751799 2 1 
+0.0403621 0.0751839 0.0751839 2 1 
+0.0404116 0.075188 0.075188 2 1 
+0.0404609 0.075192 0.075192 2 1 
+0.0405101 0.0751961 0.0751961 2 1 
+0.0405589 0.0752002 0.0752002 2 1 
+0.0406076 0.0752044 0.0752044 2 1 
+0.0406561 0.0752086 0.0752086 1 1 
+0.0407043 0.0752128 0.0752128 1 1 
+0.0407523 0.075217 0.075217 1 1 
+0.0408 0.0752213 0.0752213 1 1 
+0.0408475 0.0752256 0.0752256 1 1 
+0.0408947 0.0752299 0.0752299 1 1 
+0.0409417 0.0752342 0.0752342 1 1 
+0.0409885 0.0752386 0.0752386 1 1 
+0.041035 0.075243 0.075243 1 1 
+0.0410812 0.0752474 0.0752474 1 1 
+0.0411271 0.0752519 0.0752519 1 1 
+0.0411728 0.0752564 0.0752564 1 1 
+0.0412182 0.0752609 0.0752609 1 1 
+0.0412633 0.0752655 0.0752655 1 1 
+0.0413082 0.0752701 0.0752701 1 1 
+0.0413527 0.0752747 0.0752747 1 1 
+0.041397 0.0752793 0.0752793 1 1 
+0.041441 0.075284 0.075284 1 1 
+0.0414846 0.0752887 0.0752887 1 1 
+0.041528 0.0752934 0.0752934 1 1 
+0.0415711 0.0752982 0.0752982 1 1 
+0.0416139 0.075303 0.075303 1 1 
+0.0416563 0.0753078 0.0753078 1 1 
+0.0416985 0.0753127 0.0753127 1 1 
+0.0417403 0.0753176 0.0753176 1 1 
+0.0417818 0.0753225 0.0753225 1 1 
+0.0418231 0.0753274 0.0753274 1 1 
+0.0418639 0.0753324 0.0753324 1 1 
+0.0419045 0.0753374 0.0753374 1 1 
+0.0419448 0.0753424 0.0753424 1 1 
+0.0419847 0.0753475 0.0753475 1 1 
+0.0420243 0.0753526 0.0753526 1 1 
+0.0420635 0.0753577 0.0753577 1 1 
+0.0421025 0.0753628 0.0753628 1 1 
+0.0421411 0.075368 0.075368 1 1 
+0.0421794 0.0753732 0.0753732 1 1 
+0.0422174 0.0753784 0.0753784 1 1 
+0.042255 0.0753837 0.0753837 1 1 
+0.0422923 0.075389 0.075389 1 1 
+0.0423292 0.0753943 0.0753943 1 1 
+0.0423659 0.0753996 0.0753996 1 1 
+0.0424022 0.075405 0.075405 1 1 
+0.0424382 0.0754104 0.0754104 1 1 
+0.0424738 0.0754158 0.0754158 1 1 
+0.0425091 0.0754213 0.0754213 1 1 
+0.0425441 0.0754267 0.0754267 1 1 
+0.0425788 0.0754322 0.0754322 1 1 
+0.0426131 0.0754378 0.0754378 1 1 
+0.0426471 0.0754433 0.0754433 1 1 
+0.0426808 0.0754489 0.0754489 1 1 
+0.0427142 0.0754545 0.0754545 1 1 
+0.0427472 0.0754602 0.0754602 1 1 
+0.0427799 0.0754658 0.0754658 1 1 
+0.0428123 0.0754715 0.0754715 1 1 
+0.0428444 0.0754772 0.0754772 1 1 
+0.0428762 0.075483 0.075483 1 1 
+0.0429077 0.0754888 0.0754888 1 1 
+0.0429388 0.0754945 0.0754945 1 1 
+0.0429697 0.0755004 0.0755004 1 1 
+0.0430002 0.0755062 0.0755062 1 1 
+0.0430305 0.0755121 0.0755121 1 1 
+0.0430604 0.075518 0.075518 1 1 
+0.0430901 0.0755239 0.0755239 1 1 
+0.0431194 0.0755298 0.0755298 1 1 
+0.0431485 0.0755358 0.0755358 1 1 
+0.0431773 0.0755418 0.0755418 1 1 
+0.0432057 0.0755478 0.0755478 1 1 
+0.0432339 0.0755539 0.0755539 1 1 
+0.0432618 0.0755599 0.0755599 1 1 
+0.0432895 0.075566 0.075566 1 1 
+0.0433168 0.0755721 0.0755721 1 1 
+0.0433439 0.0755783 0.0755783 1 1 
+0.0433708 0.0755844 0.0755844 1 1 
+0.0433973 0.0755906 0.0755906 1 1 
+0.0434236 0.0755969 0.0755969 1 1 
+0.0434496 0.0756031 0.0756031 1 1 
+0.0434754 0.0756094 0.0756094 1 1 
+0.0435009 0.0756156 0.0756156 1 1 
+0.0435262 0.075622 0.075622 1 1 
+0.0435512 0.0756283 0.0756283 1 1 
+0.043576 0.0756346 0.0756346 1 1 
+0.0436005 0.075641 0.075641 1 1 
+0.0436248 0.0756474 0.0756474 1 1 
+0.0436488 0.0756539 0.0756539 1 1 
+0.0436727 0.0756603 0.0756603 1 1 
+0.0436963 0.0756668 0.0756668 1 1 
+0.0437196 0.0756733 0.0756733 1 1 
+0.0437428 0.0756798 0.0756798 1 1 
+0.0437657 0.0756864 0.0756864 1 1 
+0.0437884 0.075693 0.075693 1 1 
+0.0438109 0.0756996 0.0756996 1 1 
+0.0438332 0.0757062 0.0757062 1 1 
+0.0438552 0.0757129 0.0757129 1 1 
+0.0438771 0.0757195 0.0757195 1 1 
+0.0438987 0.0757262 0.0757262 1 1 
+0.0439202 0.075733 0.075733 1 1 
+0.0439415 0.0757397 0.0757397 1 1 
+0.0439625 0.0757465 0.0757465 1 1 
+0.0439834 0.0757533 0.0757533 1 1 
+0.0440041 0.0757601 0.0757601 1 1 
+0.0440246 0.075767 0.075767 1 1 
+0.0440449 0.0757738 0.0757738 1 1 
+0.0440651 0.0757808 0.0757808 1 1 
+0.044085 0.0757877 0.0757877 1 1 
+0.0441048 0.0757946 0.0757946 1 1 
+0.0441244 0.0758016 0.0758016 1 1 
+0.0441439 0.0758086 0.0758086 1 1 
+0.0441632 0.0758157 0.0758157 1 1 
+0.0441823 0.0758227 0.0758227 1 1 
+0.0442012 0.0758298 0.0758298 1 1 
+0.04422 0.0758369 0.0758369 1 1 
+0.0442387 0.0758441 0.0758441 1 1 
+0.0442572 0.0758512 0.0758512 1 1 
+0.0442755 0.0758584 0.0758584 1 1 
+0.0442937 0.0758657 0.0758657 1 1 
+0.0443117 0.0758729 0.0758729 1 1 
+0.0443296 0.0758802 0.0758802 1 1 
+0.0443474 0.0758875 0.0758875 1 1 
+0.044365 0.0758948 0.0758948 1 1 
+0.0443824 0.0759022 0.0759022 1 1 
+0.0443998 0.0759096 0.0759096 1 1 
+0.044417 0.075917 0.075917 1 1 
+0.0444341 0.0759245 0.0759245 1 1 
+0.044451 0.075932 0.075932 1 1 
+0.0444678 0.0759395 0.0759395 1 1 
+0.0444845 0.075947 0.075947 1 1 
+0.0445011 0.0759546 0.0759546 1 1 
+0.0445175 0.0759622 0.0759622 1 1 
+0.0445339 0.0759698 0.0759698 1 1 
+0.0445501 0.0759775 0.0759775 1 1 
+0.0445662 0.0759852 0.0759852 1 1 
+0.0445822 0.0759929 0.0759929 1 1 
+0.044598 0.0760007 0.0760007 1 1 
+0.0446138 0.0760085 0.0760085 1 1 
+0.0446295 0.0760163 0.0760163 1 1 
+0.044645 0.0760242 0.0760242 1 1 
+0.0446605 0.0760321 0.0760321 1 1 
+0.0446758 0.07604 0.07604 1 1 
+0.0446911 0.0760479 0.0760479 1 1 
+0.0447062 0.0760559 0.0760559 1 1 
+0.0447213 0.076064 0.076064 1 1 
+0.0447363 0.076072 0.076072 1 1 
+0.0447511 0.0760801 0.0760801 1 1 
+0.0447659 0.0760882 0.0760882 1 1 
+0.0447806 0.0760964 0.0760964 1 1 
+0.0447952 0.0761046 0.0761046 1 1 
+0.0448097 0.0761129 0.0761129 1 1 
+0.0448241 0.0761211 0.0761211 1 1 
+0.0448385 0.0761294 0.0761294 1 1 
+0.0448528 0.0761378 0.0761378 1 1 
+0.0448669 0.0761462 0.0761462 1 1 
+0.0448811 0.0761546 0.0761546 1 1 
+0.0448951 0.0761631 0.0761631 1 1 
+0.044909 0.0761716 0.0761716 1 1 
+0.0449229 0.0761801 0.0761801 1 1 
+0.0449367 0.0761887 0.0761887 1 1 
+0.0449505 0.0761973 0.0761973 1 1 
+0.0449641 0.076206 0.076206 1 1 
+0.0449777 0.0762147 0.0762147 1 1 
+0.0449913 0.0762234 0.0762234 1 1 
+0.0450047 0.0762322 0.0762322 1 1 
+0.0450181 0.076241 0.076241 1 1 
+0.0450315 0.0762499 0.0762499 1 1 
+0.0450448 0.0762588 0.0762588 1 1 
+0.045058 0.0762678 0.0762678 1 1 
+0.0450711 0.0762768 0.0762768 1 1 
+0.0450842 0.0762858 0.0762858 1 1 
+0.0450973 0.0762949 0.0762949 1 1 
+0.0451103 0.076304 0.076304 1 1 
+0.0451232 0.0763132 0.0763132 1 1 
+0.0451361 0.0763224 0.0763224 1 1 
+0.0451489 0.0763317 0.0763317 1 1 
+0.0451617 0.076341 0.076341 1 1 
+0.0451744 0.0763504 0.0763504 1 1 
+0.0451871 0.0763598 0.0763598 1 1 
+0.0451997 0.0763692 0.0763692 1 1 
+0.0452123 0.0763787 0.0763787 1 1 
+0.0452249 0.0763883 0.0763883 1 1 
+0.0452374 0.0763979 0.0763979 1 1 
+0.0452498 0.0764076 0.0764076 1 1 
+0.0452622 0.0764173 0.0764173 1 1 
+0.0452746 0.0764271 0.0764271 1 1 
+0.0452869 0.0764369 0.0764369 1 1 
+0.0452992 0.0764467 0.0764467 1 1 
+0.0453115 0.0764567 0.0764567 1 1 
+0.0453237 0.0764666 0.0764666 1 1 
+0.0453359 0.0764767 0.0764767 1 1 
+0.0453481 0.0764867 0.0764867 1 1 
+0.0453602 0.0764969 0.0764969 1 1 
+0.0453723 0.0765071 0.0765071 1 1 
+0.0453843 0.0765173 0.0765173 1 1 
+0.0453964 0.0765277 0.0765277 1 1 
+0.0454084 0.076538 0.076538 1 1 
+0.0454204 0.0765484 0.0765484 1 1 
+0.0454323 0.0765589 0.0765589 1 1 
+0.0454442 0.0765695 0.0765695 1 1 
+0.0454561 0.0765801 0.0765801 1 1 
+0.045468 0.0765908 0.0765908 1 1 
+0.0454798 0.0766015 0.0766015 1 1 
+0.0454917 0.0766123 0.0766123 1 1 
+0.0455035 0.0766232 0.0766232 1 1 
+0.0455153 0.0766341 0.0766341 1 1 
+0.045527 0.0766451 0.0766451 1 1 
+0.0455388 0.0766561 0.0766561 1 1 
+0.0455505 0.0766673 0.0766673 1 1 
+0.0455623 0.0766784 0.0766784 1 1 
+0.045574 0.0766897 0.0766897 1 1 
+0.0455857 0.076701 0.076701 1 1 
+0.0455973 0.0767124 0.0767124 1 1 
+0.045609 0.0767239 0.0767239 1 1 
+0.0456207 0.0767354 0.0767354 1 1 
+0.0456323 0.0767471 0.0767471 1 1 
+0.0456439 0.0767587 0.0767587 1 1 
+0.0456556 0.0767705 0.0767705 1 1 
+0.0456672 0.0767823 0.0767823 1 1 
+0.0456788 0.0767942 0.0767942 1 1 
+0.0456904 0.0768062 0.0768062 1 1 
+0.045702 0.0768183 0.0768183 1 1 
+0.0457136 0.0768304 0.0768304 1 1 
+0.0457252 0.0768427 0.0768427 1 1 
+0.0457368 0.076855 0.076855 1 1 
+0.0457484 0.0768674 0.0768674 1 1 
+0.04576 0.0768798 0.0768798 1 1 
+0.0457716 0.0768924 0.0768924 1 1 
+0.0457832 0.076905 0.076905 1 1 
+0.0457948 0.0769177 0.0769177 1 1 
+0.0458064 0.0769306 0.0769306 1 1 
+0.045818 0.0769435 0.0769435 1 1 
+0.0458297 0.0769564 0.0769564 1 1 
+0.0458413 0.0769695 0.0769695 1 1 
+0.0458529 0.0769827 0.0769827 1 1 
+0.0458646 0.0769959 0.0769959 1 1 
+0.0458762 0.0770093 0.0770093 1 1 
+0.0458879 0.0770228 0.0770228 1 1 
+0.0458996 0.0770363 0.0770363 1 1 
+0.0459112 0.0770499 0.0770499 1 1 
+0.0459229 0.0770637 0.0770637 1 1 
+0.0459347 0.0770775 0.0770775 1 1 
+0.0459464 0.0770915 0.0770915 1 1 
+0.0459582 0.0771055 0.0771055 1 1 
+0.0459699 0.0771196 0.0771196 1 1 
+0.0459817 0.0771339 0.0771339 1 1 
+0.0459935 0.0771483 0.0771483 1 1 
+0.0460053 0.0771627 0.0771627 1 1 
+0.0460172 0.0771773 0.0771773 1 1 
+0.0460291 0.077192 0.077192 1 1 
+0.046041 0.0772068 0.0772068 1 1 
+0.0460529 0.0772217 0.0772217 1 1 
+0.0460648 0.0772367 0.0772367 1 1 
+0.0460768 0.0772518 0.0772518 1 1 
+0.0460888 0.0772671 0.0772671 1 1 
+0.0461009 0.0772825 0.0772825 1 1 
+0.0461129 0.077298 0.077298 1 1 
+0.046125 0.0773136 0.0773136 1 1 
+0.0461371 0.0773293 0.0773293 1 1 
+0.0461493 0.0773452 0.0773452 1 1 
+0.0461615 0.0773612 0.0773612 1 1 
+0.0461737 0.0773774 0.0773774 1 1 
+0.046186 0.0773936 0.0773936 1 1 
+0.0461983 0.07741 0.07741 1 1 
+0.0462107 0.0774265 0.0774265 1 1 
+0.0462231 0.0774432 0.0774432 1 1 
+0.0462355 0.07746 0.07746 1 1 
+0.046248 0.077477 0.077477 1 1 
+0.0462605 0.0774941 0.0774941 1 1 
+0.0462731 0.0775113 0.0775113 1 1 
+0.0462857 0.0775287 0.0775287 1 1 
+0.0462984 0.0775462 0.0775462 1 1 
+0.0463111 0.0775639 0.0775639 1 1 
+0.0463239 0.0775817 0.0775817 1 1 
+0.0463367 0.0775997 0.0775997 1 1 
+0.0463496 0.0776179 0.0776179 1 1 
+0.0463625 0.0776362 0.0776362 1 1 
+0.0463755 0.0776547 0.0776547 1 1 
+0.0463885 0.0776733 0.0776733 1 1 
+0.0464016 0.0776921 0.0776921 1 1 
+0.0464148 0.0777111 0.0777111 1 1 
+0.0464281 0.0777303 0.0777303 1 1 
+0.0464413 0.0777496 0.0777496 1 1 
+0.0464547 0.0777691 0.0777691 1 1 
+0.0464681 0.0777888 0.0777888 1 1 
+0.0464816 0.0778087 0.0778087 1 1 
+0.0464952 0.0778287 0.0778287 1 1 
+0.0465089 0.077849 0.077849 1 1 
+0.0465226 0.0778694 0.0778694 1 1 
+0.0465364 0.07789 0.07789 1 1 
+0.0465502 0.0779109 0.0779109 1 1 
+0.0465642 0.0779319 0.0779319 1 1 
+0.0465782 0.0779531 0.0779531 1 1 
+0.0465923 0.0779746 0.0779746 1 1 
+0.0466065 0.0779963 0.0779963 1 1 
+0.0466208 0.0780181 0.0780181 1 1 
+0.0466352 0.0780402 0.0780402 1 1 
+0.0466497 0.0780625 0.0780625 1 1 
+0.0466642 0.0780851 0.0780851 1 1 
+0.0466789 0.0781078 0.0781078 1 1 
+0.0466936 0.0781308 0.0781308 1 1 
+0.0467085 0.0781541 0.0781541 1 1 
+0.0467234 0.0781776 0.0781776 1 1 
+0.0467385 0.0782013 0.0782013 1 1 
+0.0467537 0.0782253 0.0782253 1 1 
+0.0467689 0.0782495 0.0782495 1 1 
+0.0467843 0.078274 0.078274 1 1 
+0.0467998 0.0782987 0.0782987 1 1 
+0.0468154 0.0783237 0.0783237 1 1 
+0.0468311 0.078349 0.078349 1 1 
+0.046847 0.0783746 0.0783746 1 1 
+0.0468629 0.0784004 0.0784004 1 1 
+0.046879 0.0784265 0.0784265 1 1 
+0.0468953 0.0784529 0.0784529 1 1 
+0.0469116 0.0784796 0.0784796 1 1 
+0.0469281 0.0785066 0.0785066 1 1 
+0.0469447 0.078534 0.078534 1 1 
+0.0469615 0.0785616 0.0785616 1 1 
+0.0469784 0.0785895 0.0785895 1 1 
+0.0469954 0.0786178 0.0786178 1 1 
+0.0470126 0.0786464 0.0786464 1 1 
+0.04703 0.0786753 0.0786753 1 1 
+0.0470475 0.0787046 0.0787046 1 1 
+0.0470651 0.0787342 0.0787342 1 1 
+0.0470829 0.0787642 0.0787642 1 1 
+0.0471009 0.0787945 0.0787945 1 1 
+0.0471191 0.0788252 0.0788252 1 1 
+0.0471374 0.0788563 0.0788563 1 1 
+0.0471559 0.0788878 0.0788878 1 1 
+0.0471746 0.0789196 0.0789196 1 1 
+0.0471935 0.0789519 0.0789519 1 1 
+0.0472125 0.0789845 0.0789845 1 1 
+0.0472318 0.0790176 0.0790176 1 1 
+0.0472512 0.0790511 0.0790511 1 1 
+0.0472708 0.079085 0.079085 1 1 
+0.0472907 0.0791193 0.0791193 1 1 
+0.0473108 0.0791541 0.0791541 1 1 
+0.047331 0.0791894 0.0791894 1 1 
+0.0473515 0.0792251 0.0792251 1 1 
+0.0473722 0.0792613 0.0792613 1 1 
+0.0473932 0.079298 0.079298 1 1 
+0.0474144 0.0793351 0.0793351 1 1 
+0.0474358 0.0793728 0.0793728 1 1 
+0.0474575 0.079411 0.079411 1 1 
+0.0474794 0.0794497 0.0794497 1 1 
+0.0475016 0.079489 0.079489 1 1 
+0.047524 0.0795288 0.0795288 1 1 
+0.0475467 0.0795692 0.0795692 1 1 
+0.0475697 0.0796101 0.0796101 1 1 
+0.0475929 0.0796517 0.0796517 1 1 
+0.0476165 0.0796938 0.0796938 1 1 
+0.0476404 0.0797365 0.0797365 1 1 
+0.0476645 0.0797799 0.0797799 1 1 
+0.047689 0.0798239 0.0798239 1 1 
+0.0477137 0.0798686 0.0798686 1 1 
+0.0477388 0.0799139 0.0799139 1 1 
+0.0477643 0.07996 0.07996 1 1 
+0.0477901 0.0800067 0.0800067 1 1 
+0.0478162 0.0800541 0.0800541 1 1 
+0.0478427 0.0801023 0.0801023 1 1 
+0.0478695 0.0801513 0.0801513 1 1 
+0.0478968 0.080201 0.080201 1 1 
+0.0479244 0.0802515 0.0802515 1 1 
+0.0479524 0.0803028 0.0803028 1 1 
+0.0479808 0.0803549 0.0803549 1 1 
+0.0480096 0.0804079 0.0804079 1 1 
+0.0480389 0.0804617 0.0804617 1 1 
+0.0480686 0.0805165 0.0805165 1 1 
+0.0480987 0.0805722 0.0805722 1 1 
+0.0481294 0.0806288 0.0806288 1 1 
+0.0481604 0.0806863 0.0806863 1 1 
+0.048192 0.0807449 0.0807449 1 1 
+0.0482241 0.0808045 0.0808045 1 1 
+0.0482567 0.0808651 0.0808651 1 1 
+0.0482898 0.0809267 0.0809267 1 1 
+0.0483235 0.0809895 0.0809895 1 1 
+0.0483577 0.0810534 0.0810534 1 1 
+0.0483925 0.0811185 0.0811185 1 1 
+0.0484278 0.0811847 0.0811847 1 1 
+0.0484638 0.0812522 0.0812522 1 1 
+0.0485004 0.0813209 0.0813209 1 1 
+0.0485377 0.0813909 0.0813909 1 1 
+0.0485756 0.0814622 0.0814622 1 1 
+0.0486142 0.0815349 0.0815349 1 1 
+0.0486534 0.081609 0.081609 1 1 
+0.0486934 0.0816846 0.0816846 1 1 
+0.0487342 0.0817616 0.0817616 1 1 
+0.0487757 0.0818401 0.0818401 1 1 
+0.048818 0.0819203 0.0819203 1 1 
+0.0488611 0.082002 0.082002 1 1 
+0.048905 0.0820854 0.0820854 1 1 
+0.0489498 0.0821706 0.0821706 1 1 
+0.0489955 0.0822575 0.0822575 1 1 
+0.0490421 0.0823463 0.0823463 1 1 
+0.0490897 0.0824369 0.0824369 1 1 
+0.0491382 0.0825295 0.0825295 1 1 
+0.0491878 0.0826241 0.0826241 1 1 
+0.0492383 0.0827207 0.0827207 1 1 
+0.04929 0.0828195 0.0828195 1 1 
+0.0493428 0.0829205 0.0829205 1 1 
+0.0493967 0.0830238 0.0830238 1 1 
+0.0494518 0.0831295 0.0831295 1 1 
+0.0495081 0.0832375 0.0832375 1 1 
+0.0495657 0.0833481 0.0833481 1 1 
+0.0496246 0.0834613 0.0834613 1 1 
+0.0496848 0.0835772 0.0835772 1 1 
+0.0497465 0.0836958 0.0836958 1 1 
+0.0498096 0.0838173 0.0838173 1 1 
+0.0498742 0.0839418 0.0839418 1 1 
+0.0499403 0.0840694 0.0840694 1 1 
+0.0500081 0.0842002 0.0842002 1 1 
+0.0500775 0.0843342 0.0843342 1 1 
+0.0501487 0.0844717 0.0844717 1 1 
+0.0502217 0.0846127 0.0846127 1 1 
+0.0502965 0.0847574 0.0847574 1 1 
+0.0503732 0.0849058 0.0849058 1 1 
+0.0504519 0.0850582 0.0850582 1 1 
+0.0505327 0.0852147 0.0852147 1 1 
+0.0506157 0.0853754 0.0853754 1 1 
+0.0507008 0.0855405 0.0855405 1 1 
+0.0507883 0.0857101 0.0857101 1 1 
+0.0508782 0.0858844 0.0858844 1 1 
+0.0509705 0.0860636 0.0860636 1 1 
+0.0510655 0.0862478 0.0862478 1 1 
+0.051163 0.0864373 0.0864373 1 1 
+0.0512634 0.0866323 0.0866323 1 1 
+0.0513666 0.0868328 0.0868328 1 1 
+0.0514728 0.0870392 0.0870392 1 1 
+0.0515821 0.0872517 0.0872517 1 1 
+0.0516946 0.0874704 0.0874704 1 1 
+0.0518104 0.0876955 0.0876955 1 1 
+0.0519296 0.0879274 0.0879274 1 1 
+0.0520523 0.0881662 0.0881662 1 1 
+0.0521788 0.0884122 0.0884122 1 1 
+0.052309 0.0886656 0.0886656 1 1 
+0.0524431 0.0889267 0.0889267 1 1 
+0.0525813 0.0891956 0.0891956 1 1 
+0.0527236 0.0894727 0.0894727 1 1 
+0.0528703 0.0897581 0.0897581 1 1 
+0.0530213 0.0900521 0.0900521 1 1 
+0.0531769 0.090355 0.090355 1 1 
+0.0533371 0.090667 0.090667 1 1 
+0.0535022 0.0909882 0.0909882 1 1 
+0.0536721 0.0913189 0.0913189 1 1 
+0.0538469 0.0916593 0.0916593 1 1 
+0.0540269 0.0920095 0.0920095 1 1 
+0.054212 0.0923698 0.0923698 1 1 
+0.0544024 0.0927403 0.0927403 1 1 
+0.0545981 0.093121 0.093121 1 1 
+0.0547992 0.0935122 0.0935122 1 1 
+0.0550057 0.0939138 0.0939138 1 1 
+0.0552176 0.0943259 0.0943259 1 1 
+0.055435 0.0947486 0.0947486 1 1 
+0.0556579 0.0951817 0.0951817 1 1 
+0.0558861 0.0956253 0.0956253 1 1 
+0.0561198 0.0960794 0.0960794 1 1 
+0.0563588 0.0965437 0.0965437 1 1 
+0.0566032 0.0970182 0.0970182 1 1 
+0.0568527 0.0975026 0.0975026 1 1 
+0.0571074 0.0979969 0.0979969 1 1 
+0.057367 0.0985008 0.0985008 1 1 
+0.0576316 0.099014 0.099014 1 1 
+0.057901 0.0995364 0.0995364 1 1 
+0.058175 0.100068 0.100068 1 1 
+0.0584535 0.100607 0.100607 1 1 
+0.0587363 0.101155 0.101155 1 1 
+0.0590234 0.101711 0.101711 1 1 
+0.0593145 0.102275 0.102275 1 1 
+0.0596094 0.102846 0.102846 1 1 
+0.0599081 0.103424 0.103424 1 1 
+0.0602104 0.104009 0.104009 1 1 
+0.0605161 0.1046 0.1046 1 1 
+0.060825 0.105197 0.105197 1 1 
+0.0611371 0.1058 0.1058 1 1 
+0.0614521 0.106409 0.106409 1 1 
+0.0617699 0.107022 0.107022 1 1 
+0.0620904 0.107641 0.107641 1 1 
+0.0624135 0.108265 0.108265 1 1 
+0.062739 0.108893 0.108893 1 1 
+0.0630668 0.109525 0.109525 1 1 
+0.0633968 0.110161 0.110161 1 1 
+0.0637288 0.110801 0.110801 1 1 
+0.0640629 0.111445 0.111445 1 1 
+0.0643988 0.112092 0.112092 1 1 
+0.0647365 0.112742 0.112742 1 1 
+0.0650758 0.113396 0.113396 1 1 
+0.0654168 0.114052 0.114052 1 1 
+0.0657593 0.114711 0.114711 1 1 
+0.0661032 0.115373 0.115373 1 1 
+0.0664485 0.116037 0.116037 1 1 
+0.0667952 0.116703 0.116703 1 1 
+0.067143 0.117372 0.117372 1 1 
+0.0674921 0.118042 0.118042 1 1 
+0.0678422 0.118715 0.118715 1 1 
+0.0681934 0.11939 0.11939 1 1 
+0.0685457 0.120066 0.120066 1 1 
+0.0688989 0.120744 0.120744 1 1 
+0.069253 0.121423 0.121423 1 1 
+0.0696081 0.122105 0.122105 1 1 
+0.0699639 0.122787 0.122787 1 1 
+0.0703206 0.123471 0.123471 1 1 
+0.070678 0.124156 0.124156 1 1 
+0.0710362 0.124843 0.124843 1 1 
+0.0713951 0.125531 0.125531 1 1 
+0.0717546 0.126219 0.126219 1 1 
+0.0721148 0.126909 0.126909 1 1 
+0.0724756 0.1276 0.1276 1 1 
+0.072837 0.128292 0.128292 1 1 
+0.0731989 0.128985 0.128985 1 1 
+0.0735614 0.129679 0.129679 1 1 
+0.0739244 0.130373 0.130373 1 1 
+0.0742879 0.131069 0.131069 1 1 
+0.0746519 0.131765 0.131765 1 1 
+0.0750164 0.132462 0.132462 1 1 
+0.0753813 0.13316 0.13316 1 1 
+0.0757466 0.133858 0.133858 1 1 
+0.0761123 0.134557 0.134557 1 1 
+0.0764784 0.135257 0.135257 1 1 
+0.0768449 0.135957 0.135957 1 1 
+0.0772117 0.136658 0.136658 1 1 
+0.0775789 0.137359 0.137359 1 1 
+0.0779465 0.138061 0.138061 1 1 
+0.0783144 0.138763 0.138763 1 1 
+0.0786825 0.139466 0.139466 1 1 
+0.079051 0.140169 0.140169 1 1 
+0.0794198 0.140873 0.140873 1 1 
+0.0797889 0.141577 0.141577 1 1 
+0.0801582 0.142282 0.142282 1 1 
+0.0805278 0.142987 0.142987 1 1 
+0.0808977 0.143692 0.143692 1 1 
+0.0812678 0.144398 0.144398 1 1 
+0.0816381 0.145104 0.145104 1 1 
+0.0820087 0.145811 0.145811 1 1 
+0.0823795 0.146518 0.146518 1 1 
+0.0827505 0.147225 0.147225 1 1 
+0.0831217 0.147932 0.147932 1 1 
+0.0834931 0.14864 0.14864 1 1 
+0.0838647 0.149348 0.149348 1 1 
+0.0842365 0.150056 0.150056 1 1 
+0.0846085 0.150765 0.150765 1 1 
+0.0849807 0.151474 0.151474 1 1 
+0.085353 0.152183 0.152183 1 1 
+0.0857256 0.152892 0.152892 1 1 
+0.0860982 0.153601 0.153601 1 1 
+0.0864711 0.154311 0.154311 1 1 
+0.0868441 0.155021 0.155021 1 1 
+0.0872172 0.155731 0.155731 1 1 
+0.0875905 0.156441 0.156441 1 1 
+0.0879639 0.157152 0.157152 1 1 
+0.0883375 0.157863 0.157863 1 1 
+0.0887112 0.158574 0.158574 1 1 
+0.089085 0.159285 0.159285 1 1 
+0.089459 0.159996 0.159996 1 1 
+0.0898331 0.160707 0.160707 1 1 
+0.0902073 0.161419 0.161419 1 1 
+0.0905816 0.162131 0.162131 1 1 
+0.090956 0.162843 0.162843 1 1 
+0.0913305 0.163555 0.163555 1 1 
+0.0917052 0.164267 0.164267 1 1 
+0.0920799 0.164979 0.164979 1 1 
+0.0924548 0.165691 0.165691 1 1 
+0.0928298 0.166404 0.166404 1 1 
+0.0932048 0.167117 0.167117 1 1 
+0.09358 0.167829 0.167829 1 1 
+0.0939552 0.168542 0.168542 1 1 
+0.0943305 0.169255 0.169255 1 1 
+0.0947059 0.169968 0.169968 1 1 
+0.0950814 0.170682 0.170682 1 1 
+0.095457 0.171395 0.171395 1 1 
+0.0958327 0.172108 0.172108 1 1 
+0.0962084 0.172822 0.172822 1 1 
+0.0965843 0.173535 0.173535 1 1 
+0.0969602 0.174249 0.174249 1 1 
+0.0973361 0.174963 0.174963 1 1 
+0.0977122 0.175677 0.175677 1 1 
+0.0980883 0.176391 0.176391 1 1 
+0.0984645 0.177105 0.177105 1 1 
+0.0988407 0.177819 0.177819 1 1 
+0.0992171 0.178533 0.178533 1 1 
+0.0995934 0.179247 0.179247 1 1 
+0.0999699 0.179962 0.179962 1 1 
+0.100346 0.180676 0.180676 1 1 
+0.0406561 0.0752086 0.0752086 4 2 
+0.0406539 0.0752172 0.0751995 3 2 
+0.0406545 0.0752379 0.075179 4 2 
+0.0406538 0.0752737 0.0751432 3 2 
+0.0405726 0.0773735 0.0731442 3 2 
+0.0405785 0.0772903 0.0732199 3 2 
+0.0405849 0.0771982 0.073304 3 2 
+0.0405909 0.0771061 0.0733885 3 2 
+0.0405967 0.0770141 0.0734732 3 2 
+0.0406023 0.0769222 0.0735584 3 2 
+0.0406075 0.0768305 0.0736436 3 2 
+0.0406125 0.0767389 0.0737289 3 2 
+0.0406172 0.0766475 0.0738144 3 2 
+0.0406216 0.0765562 0.0739002 3 2 
+0.0406258 0.0764651 0.0739862 3 2 
+0.0406296 0.0763742 0.0740724 3 2 
+0.0406332 0.0762833 0.0741589 3 2 
+0.0406365 0.0761926 0.0742455 3 2 
+0.0406395 0.0761021 0.0743323 3 2 
+0.0406422 0.0760117 0.0744193 3 2 
+0.0406447 0.0759215 0.0745065 3 2 
+0.0406468 0.0758314 0.0745939 3 2 
+0.0406487 0.0757415 0.0746815 3 2 
+0.0406503 0.0756518 0.0747693 3 2 
+0.0406516 0.0755622 0.0748573 3 2 
+0.0406526 0.0754728 0.0749455 3 2 
+0.0406533 0.0753836 0.0750338 3 2 
+0.0406537 0.0752946 0.0751223 3 2 
+0.0406537 0.0752894 0.0751274 3 2 
+0.0406539 0.0752162 0.0752006 3 2 
+0.0406537 0.0753051 0.0751119 3 2 
+0.0406532 0.0753941 0.0750234 3 2 
+0.0406525 0.0754834 0.074935 3 2 
+0.0406515 0.0755728 0.0748469 3 2 
+0.0406501 0.0756624 0.074759 3 2 
+0.0406485 0.0757522 0.0746712 3 2 
+0.0406466 0.075842 0.0745836 3 2 
+0.0406444 0.0759321 0.0744962 3 2 
+0.0406419 0.0760224 0.074409 3 2 
+0.0406392 0.0761127 0.074322 3 2 
+0.0406361 0.0762032 0.0742352 3 2 
+0.0406328 0.0762939 0.0741487 3 2 
+0.0406292 0.0763848 0.0740622 3 2 
+0.0406253 0.0764758 0.073976 3 2 
+0.0406211 0.0765669 0.07389 3 2 
+0.0406167 0.0766584 0.0738044 3 2 
+0.0406119 0.0767498 0.0737188 3 2 
+0.0406069 0.0768414 0.0736335 3 2 
+0.0406016 0.0769331 0.0735482 3 2 
+0.0405961 0.077025 0.0734632 3 2 
+0.0405902 0.077117 0.0733786 3 2 
+0.0405841 0.077209 0.0732944 3 2 
+0.0405777 0.0773013 0.0732101 3 2 
+0.0405711 0.0773937 0.073126 3 2 
+0.0405642 0.0774862 0.073042 3 2 
+0.040557 0.0775789 0.0729585 3 2 
+0.0405496 0.0776717 0.0728751 3 2 
+0.0405419 0.0777647 0.0727922 3 2 
+0.040534 0.0778577 0.0727093 3 2 
+0.0405258 0.0779509 0.0726268 3 2 
+0.0405173 0.0780442 0.0725442 3 2 
+0.0405086 0.0781376 0.0724621 3 2 
+0.0404996 0.0782311 0.0723802 3 2 
+0.0404904 0.0783246 0.0722983 3 2 
+0.040481 0.0784183 0.0722168 3 2 
+0.0404713 0.0785121 0.0721356 3 2 
+0.0404614 0.078606 0.072055 3 2 
+0.0404512 0.0787002 0.0719743 3 2 
+0.0404409 0.0787945 0.0718939 3 2 
+0.0404302 0.0788887 0.0718133 3 2 
+0.0404194 0.0789832 0.0717334 3 2 
+0.0404083 0.0790778 0.0716537 3 2 
+0.040397 0.0791727 0.0715744 3 2 
+0.0403855 0.0792675 0.0714951 3 2 
+0.0403738 0.0793624 0.0714161 3 2 
+0.0403618 0.0794571 0.0713374 3 2 
+0.0403497 0.0795522 0.071259 3 2 
+0.0403373 0.0796473 0.0711808 3 2 
+0.0403247 0.0797425 0.0711028 3 2 
+0.040312 0.0798378 0.0710252 3 2 
+0.040299 0.0799332 0.0709477 3 2 
+0.0402858 0.080029 0.0708711 3 2 
+0.0402725 0.0801247 0.0707942 3 2 
+0.0402589 0.0802204 0.0707175 3 2 
+0.0402452 0.080317 0.0706407 3 2 
+0.0402313 0.0804131 0.0705646 3 2 
+0.0402172 0.0805093 0.0704888 3 2 
+0.0402029 0.0806055 0.0704132 3 2 
+0.0401884 0.0807019 0.0703379 3 2 
+0.0401738 0.0807984 0.0702628 3 2 
+0.040159 0.080895 0.0701883 3 2 
+0.0401441 0.0809917 0.0701137 3 2 
+0.0401289 0.0810885 0.0700393 3 2 
+0.0401137 0.0811853 0.0699653 3 2 
+0.0400982 0.0812822 0.0698916 3 2 
+0.0400826 0.0813793 0.0698182 3 2 
+0.0400669 0.0814762 0.0697445 3 2 
+0.040051 0.0815736 0.0696715 3 2 
+0.040035 0.0816711 0.0695987 3 2 
+0.0400188 0.0817687 0.0695264 3 2 
+0.0400025 0.0818664 0.0694541 3 2 
+0.039986 0.0819642 0.0693821 3 2 
+0.0399694 0.0820623 0.0693107 3 2 
+0.0399527 0.0821603 0.0692392 3 2 
+0.0399359 0.0822584 0.0691679 3 2 
+0.0399189 0.0823565 0.0690968 3 2 
+0.0399018 0.0824548 0.0690261 3 2 
+0.0398846 0.0825531 0.0689557 3 2 
+0.0398673 0.0826509 0.0688853 3 2 
+0.0398498 0.0827494 0.0688153 3 2 
+0.0398323 0.082848 0.0687456 3 2 
+0.0398146 0.0829474 0.0686764 3 2 
+0.0397968 0.0830465 0.0686072 3 2 
+0.039779 0.0831456 0.0685381 3 2 
+0.039761 0.0832448 0.0684697 3 2 
+0.0397429 0.0833442 0.0684012 3 2 
+0.0397248 0.0834437 0.068333 3 2 
+0.0397065 0.0835434 0.0682645 3 2 
+0.0396882 0.0836431 0.0681967 3 2 
+0.0396698 0.0837429 0.0681292 3 2 
+0.0396512 0.0838426 0.0680618 3 2 
+0.0396326 0.0839425 0.0679947 3 2 
+0.039614 0.0840426 0.0679279 3 2 
+0.0395952 0.0841429 0.0678613 3 2 
+0.0395764 0.0842432 0.0677949 3 2 
+0.0395575 0.0843436 0.0677288 3 2 
+0.0395385 0.0844428 0.0676628 3 2 
+0.0395194 0.0845434 0.0675971 3 2 
+0.0395003 0.0846443 0.0675316 3 2 
+0.0394811 0.0847469 0.0674664 3 2 
+0.0394619 0.084848 0.0674013 3 2 
+0.0394426 0.0849492 0.0673365 3 2 
+0.0394232 0.0850505 0.0672716 3 2 
+0.0394038 0.0851519 0.0672072 3 2 
+0.0393843 0.0852534 0.067143 3 2 
+0.0393648 0.0853548 0.0670789 3 2 
+0.0393452 0.0854565 0.0670151 3 2 
+0.0393255 0.0855583 0.0669515 3 2 
+0.0393059 0.0856602 0.0668885 3 2 
+0.0392861 0.0857623 0.0668253 3 2 
+0.0392663 0.0858645 0.0667622 3 2 
+0.0392465 0.0859673 0.0666997 3 2 
+0.0392266 0.0860698 0.066637 3 2 
+0.0392067 0.0861724 0.0665746 3 2 
+0.0391868 0.0862744 0.0665123 3 2 
+0.0391668 0.0863772 0.0664503 3 2 
+0.0391468 0.0864801 0.0663884 3 2 
+0.0391267 0.0865845 0.0663266 3 2 
+0.0391066 0.0866879 0.0662651 3 2 
+0.0390865 0.0867914 0.0662037 3 2 
+0.0390663 0.0868948 0.0661424 3 2 
+0.0390461 0.0869985 0.0660814 3 2 
+0.0390259 0.0871024 0.0660206 3 2 
+0.0390056 0.0872066 0.0659595 3 2 
+0.0389854 0.0873107 0.0658991 3 2 
+0.0389651 0.0874149 0.0658388 3 2 
+0.0389447 0.0875194 0.0657787 3 2 
+0.0389244 0.0876239 0.0657188 3 2 
+0.038904 0.0877285 0.0656589 3 2 
+0.0388836 0.0878333 0.0655995 3 2 
+0.0388632 0.0879381 0.06554 3 2 
+0.0388427 0.0880431 0.0654806 3 2 
+0.0388222 0.0881474 0.0654219 3 2 
+0.0388018 0.0882526 0.0653629 3 2 
+0.0387812 0.0883579 0.0653039 3 2 
+0.0387607 0.0884646 0.0652449 3 2 
+0.0387402 0.0885703 0.0651863 3 2 
+0.0387196 0.0886762 0.0651278 3 2 
+0.038699 0.0887818 0.0650693 3 2 
+0.0386784 0.0888879 0.0650111 3 2 
+0.0386578 0.0889942 0.064953 3 2 
+0.0386372 0.0891003 0.064895 3 2 
+0.0386166 0.0892069 0.0648372 3 2 
+0.0385959 0.0893136 0.0647795 3 2 
+0.0385752 0.0894195 0.0647225 3 2 
+0.0385546 0.0895265 0.0646651 3 2 
+0.0385339 0.0896337 0.0646078 3 2 
+0.0385132 0.0897398 0.0645507 3 2 
+0.0384924 0.089847 0.0644936 3 2 
+0.0384717 0.0899544 0.0644367 3 2 
+0.038451 0.0900638 0.0643804 3 2 
+0.0384302 0.0901715 0.0643237 3 2 
+0.0384095 0.0902794 0.0642671 3 2 
+0.0383887 0.0903876 0.0642103 3 2 
+0.0383679 0.0904958 0.064154 3 2 
+0.0383471 0.0906041 0.0640978 3 2 
+0.0383263 0.0907134 0.0640417 3 2 
+0.0383055 0.0908221 0.0639857 3 2 
+0.0382847 0.0909309 0.0639298 3 2 
+0.0382638 0.09104 0.0638749 3 2 
+0.038243 0.0911491 0.0638192 3 2 
+0.0382221 0.0912584 0.0637636 3 2 
+0.0382013 0.0913678 0.0637078 3 2 
+0.0381804 0.0914774 0.0636524 3 2 
+0.0381595 0.0915871 0.0635971 3 2 
+0.0381386 0.0916969 0.0635417 3 2 
+0.0381177 0.0918069 0.0634866 3 2 
+0.0380968 0.0919171 0.0634316 3 2 
+0.0380759 0.0920275 0.0633768 3 2 
+0.038055 0.092138 0.063322 3 2 
+0.038034 0.0922486 0.0632673 3 2 
+0.0380131 0.0923594 0.0632128 3 2 
+0.0379921 0.0924704 0.0631583 3 2 
+0.0379712 0.0925815 0.0631039 3 2 
+0.0379502 0.0926927 0.0630496 3 2 
+0.0379292 0.0928042 0.0629954 3 2 
+0.0379082 0.0929158 0.0629412 3 2 
+0.0378872 0.0930271 0.0628871 3 2 
+0.0378662 0.0931391 0.0628332 3 2 
+0.0378452 0.0932513 0.0627793 3 2 
+0.0378242 0.0933598 0.0627255 3 2 
+0.0378031 0.0934722 0.0626717 3 2 
+0.0377821 0.093585 0.062618 3 2 
+0.037761 0.0937005 0.0625646 3 2 
+0.0377399 0.0938133 0.0625111 3 2 
+0.0377189 0.0939264 0.0624576 3 2 
+0.0376978 0.0940409 0.0624049 3 2 
+0.0376767 0.0941544 0.0623515 3 2 
+0.0376556 0.094268 0.0622982 3 2 
+0.0376344 0.0943824 0.0622455 3 2 
+0.0376133 0.0944964 0.0621925 3 2 
+0.0375921 0.0946107 0.0621396 3 2 
+0.037571 0.0947246 0.0620855 3 2 
+0.0375498 0.0948393 0.0620326 3 2 
+0.0375286 0.0949541 0.0619798 3 2 
+0.0375074 0.095068 0.0619271 3 2 
+0.0374862 0.0951832 0.0618744 3 2 
+0.0374649 0.0952987 0.0618217 3 2 
+0.0374437 0.0954131 0.0617692 3 2 
+0.0374224 0.0955289 0.0617167 3 2 
+0.0374012 0.095645 0.0616642 3 2 
+0.0373799 0.0957609 0.0616124 3 2 
+0.0373586 0.0958771 0.06156 3 2 
+0.0373372 0.0959935 0.0615076 3 2 
+0.0373159 0.0961128 0.0614561 3 2 
+0.0372945 0.0962298 0.061404 3 2 
+0.0372732 0.0963469 0.0613518 3 2 
+0.0372518 0.0964645 0.0612987 3 2 
+0.0372304 0.0965821 0.0612466 3 2 
+0.0372089 0.0967 0.0611946 3 2 
+0.0371875 0.0968171 0.0611427 3 2 
+0.037166 0.0969355 0.0610907 3 2 
+0.0371445 0.097054 0.0610388 3 2 
+0.037123 0.0971711 0.0609876 3 2 
+0.0371015 0.0972902 0.0609357 3 2 
+0.0370799 0.0974095 0.0608839 3 2 
+0.0370584 0.0975269 0.0608329 3 2 
+0.0370368 0.0976467 0.0607811 3 2 
+0.0370151 0.0977668 0.0607294 3 2 
+0.0369935 0.0978856 0.060678 3 2 
+0.0369718 0.0980058 0.0606266 3 2 
+0.0369501 0.0981263 0.0605752 3 2 
+0.0369284 0.0982504 0.0605226 3 2 
+0.0369067 0.0983714 0.0604712 3 2 
+0.0368849 0.0984926 0.0604199 3 2 
+0.0368631 0.0986155 0.0603682 3 2 
+0.0368413 0.0987373 0.0603169 3 2 
+0.0368194 0.0988594 0.0602656 3 2 
+0.0367975 0.098983 0.0602145 3 2 
+0.0367756 0.0991056 0.0601631 3 2 
+0.0367536 0.0992286 0.0601118 3 2 
+0.0367317 0.0993514 0.0600609 3 2 
+0.0367096 0.099475 0.0600096 3 2 
+0.0366876 0.0995989 0.0599584 3 2 
+0.0366655 0.0997212 0.0599076 3 2 
+0.0366434 0.0998458 0.0598563 3 2 
+0.0366213 0.0999706 0.0598051 3 2 
+0.0365991 0.100094 0.059754 3 2 
+0.0365768 0.100219 0.0597028 3 2 
+0.0365546 0.100345 0.0596517 3 2 
+0.0365323 0.100469 0.0596009 3 2 
+0.0365099 0.100595 0.0595497 3 2 
+0.0364875 0.100722 0.0594986 3 2 
+0.0364651 0.100848 0.0594473 3 2 
+0.0364427 0.100974 0.0593963 3 2 
+0.0364201 0.101102 0.0593453 3 2 
+0.0363976 0.101234 0.0592946 3 2 
+0.036375 0.101362 0.0592435 3 2 
+0.0363523 0.10149 0.0591925 3 2 
+0.0363296 0.101621 0.0591416 3 2 
+0.0363069 0.10175 0.0590905 3 2 
+0.0362841 0.10188 0.0590395 3 2 
+0.0362613 0.102011 0.0589886 3 2 
+0.0362384 0.102141 0.0589375 3 2 
+0.0362154 0.102272 0.0588865 3 2 
+0.0361924 0.102403 0.0588356 3 2 
+0.0361694 0.102534 0.0587845 3 2 
+0.0361463 0.102666 0.0587335 3 2 
+0.0361231 0.102798 0.0586826 3 2 
+0.0360999 0.102931 0.0586315 3 2 
+0.0360766 0.103064 0.0585804 3 2 
+0.0360533 0.103197 0.0585294 3 2 
+0.0360299 0.103331 0.0584783 3 2 
+0.0360064 0.103465 0.0584272 3 2 
+0.0359829 0.103598 0.0583762 3 2 
+0.0359593 0.103733 0.0583251 3 2 
+0.0359356 0.103869 0.0582739 3 2 
+0.0359119 0.104001 0.0582236 3 2 
+0.0358881 0.104138 0.0581723 3 2 
+0.0358643 0.104275 0.058121 3 2 
+0.0358404 0.104409 0.058071 3 2 
+0.0358164 0.104546 0.0580195 3 2 
+0.0357923 0.104684 0.0579681 3 2 
+0.0357682 0.104827 0.0579168 3 2 
+0.0357439 0.104966 0.0578657 3 2 
+0.0357197 0.105105 0.0578147 3 2 
+0.0356953 0.105246 0.0577624 3 2 
+0.0356709 0.105386 0.0577112 3 2 
+0.0356463 0.105526 0.05766 3 2 
+0.0356217 0.105669 0.0576082 3 2 
+0.0355971 0.105811 0.0575569 3 2 
+0.0355723 0.105952 0.0575056 3 2 
+0.0355475 0.106098 0.0574536 3 2 
+0.0355226 0.106241 0.0574022 3 2 
+0.0354976 0.106385 0.0573508 3 2 
+0.0354725 0.10653 0.0572986 3 2 
+0.0354473 0.106674 0.0572471 3 2 
+0.0354221 0.10682 0.0571955 3 2 
+0.0353967 0.106964 0.0571436 3 2 
+0.0353713 0.10711 0.0570919 3 2 
+0.0353458 0.107257 0.0570401 3 2 
+0.0353202 0.107402 0.0569887 3 2 
+0.0352945 0.10755 0.0569367 3 2 
+0.0352688 0.107699 0.0568848 3 2 
+0.0352429 0.107845 0.0568336 3 2 
+0.035217 0.107994 0.0567815 3 2 
+0.0351909 0.108145 0.0567293 3 2 
+0.0351648 0.108292 0.0566775 3 2 
+0.0351386 0.108443 0.0566253 3 2 
+0.0351123 0.108595 0.0565731 3 2 
+0.0350859 0.108749 0.0565218 3 2 
+0.0350595 0.1089 0.0564699 3 2 
+0.0350329 0.109052 0.056418 3 2 
+0.0350063 0.109208 0.0563651 3 2 
+0.0349795 0.109361 0.0563126 3 2 
+0.0349527 0.109514 0.0562601 3 2 
+0.0349258 0.109671 0.0562073 3 2 
+0.0348988 0.109826 0.056155 3 2 
+0.0348718 0.109981 0.0561028 3 2 
+0.0348446 0.110137 0.0560502 3 2 
+0.0348174 0.110293 0.0559979 3 2 
+0.03479 0.110449 0.0559455 3 2 
+0.0347626 0.110606 0.0558932 3 2 
+0.0347351 0.110764 0.0558403 3 2 
+0.0347076 0.110921 0.0557875 3 2 
+0.0346799 0.11108 0.0557358 3 2 
+0.0346522 0.111239 0.0556827 3 2 
+0.0346244 0.111398 0.0556297 3 2 
+0.0345965 0.111554 0.0555765 3 2 
+0.0345685 0.111713 0.0555234 3 2 
+0.0345405 0.111873 0.0554703 3 2 
+0.0345124 0.112034 0.055417 3 2 
+0.0344842 0.112195 0.055364 3 2 
+0.0344559 0.112357 0.0553109 3 2 
+0.0344276 0.112512 0.0552577 3 2 
+0.0343992 0.112675 0.0552046 3 2 
+0.0343707 0.112838 0.0551515 3 2 
+0.0343422 0.113001 0.0550983 3 2 
+0.0343136 0.113165 0.0550451 3 2 
+0.0342849 0.113329 0.0549919 3 2 
+0.0342561 0.113491 0.0549381 3 2 
+0.0342273 0.113656 0.0548847 3 2 
+0.0341985 0.113821 0.0548313 3 2 
+0.0341695 0.113986 0.054778 3 2 
+0.0341405 0.114151 0.0547245 3 2 
+0.0341114 0.114317 0.054671 3 2 
+0.0340823 0.114487 0.0546172 3 2 
+0.0340531 0.114653 0.0545636 3 2 
+0.0340238 0.11482 0.05451 3 2 
+0.0339945 0.114987 0.0544561 3 2 
+0.0339651 0.115153 0.0544023 3 2 
+0.0339356 0.11532 0.0543486 3 2 
+0.0339061 0.115485 0.054293 3 2 
+0.0338765 0.115653 0.054239 3 2 
+0.0338469 0.11582 0.0541849 3 2 
+0.0338172 0.115986 0.0541302 3 2 
+0.0337874 0.116154 0.0540757 3 2 
+0.0337576 0.116321 0.0540211 3 2 
+0.0337277 0.116493 0.0539685 3 2 
+0.0336978 0.116661 0.0539135 3 2 
+0.0336678 0.11683 0.0538585 3 2 
+0.0336377 0.11699 0.0538023 3 2 
+0.0336076 0.11716 0.0537475 3 2 
+0.0335774 0.11733 0.0536926 3 2 
+0.0335472 0.117506 0.0536383 3 2 
+0.0335169 0.117675 0.053583 3 2 
+0.0334865 0.117845 0.0535275 3 2 
+0.0334561 0.118008 0.0534727 3 2 
+0.0334256 0.118179 0.0534175 3 2 
+0.033395 0.118349 0.0533623 3 2 
+0.0333644 0.118523 0.0533051 3 2 
+0.0333337 0.118692 0.0532494 3 2 
+0.033303 0.118862 0.0531937 3 2 
+0.0332722 0.119032 0.053138 3 2 
+0.0332413 0.119203 0.0530819 3 2 
+0.0332104 0.119374 0.0530257 3 2 
+0.0331794 0.119544 0.0529695 3 2 
+0.0331483 0.119715 0.0529131 3 2 
+0.0331172 0.119886 0.0528567 3 2 
+0.033086 0.120053 0.0528001 3 2 
+0.0330548 0.120223 0.0527435 3 2 
+0.0330234 0.120393 0.0526868 3 2 
+0.032992 0.120565 0.0526301 3 2 
+0.0329606 0.120735 0.0525733 3 2 
+0.032929 0.120905 0.0525163 3 2 
+0.0328974 0.121082 0.0524586 3 2 
+0.0328657 0.121252 0.0524013 3 2 
+0.032834 0.121423 0.0523439 3 2 
+0.0328021 0.121587 0.0522876 3 2 
+0.0327702 0.121758 0.0522297 3 2 
+0.0327382 0.121929 0.0521716 3 2 
+0.0327062 0.122098 0.0521143 3 2 
+0.032674 0.122267 0.0520559 3 2 
+0.0326418 0.122436 0.0519974 3 2 
+0.0326095 0.122607 0.0519396 3 2 
+0.0325771 0.122776 0.0518809 3 2 
+0.0325446 0.122947 0.051822 3 2 
+0.0325121 0.123117 0.0517638 3 2 
+0.0324794 0.123286 0.0517046 3 2 
+0.0324467 0.123455 0.0516452 3 2 
+0.0324139 0.123626 0.051587 3 2 
+0.032381 0.123794 0.0515273 3 2 
+0.032348 0.123962 0.0514674 3 2 
+0.0323149 0.124137 0.0514071 3 2 
+0.0322817 0.124304 0.0513475 3 2 
+0.0322484 0.124472 0.0512877 3 2 
+0.032215 0.124637 0.0512271 3 2 
+0.0321815 0.124803 0.051167 3 2 
+0.032148 0.124969 0.0511067 3 2 
+0.0321143 0.125143 0.0510444 3 2 
+0.0320805 0.125309 0.0509834 3 2 
+0.0320466 0.125476 0.0509223 3 2 
+0.0320125 0.125633 0.0508626 3 2 
+0.0319784 0.125798 0.0508008 3 2 
+0.0319442 0.125963 0.0507389 3 2 
+0.0319098 0.126127 0.0506785 3 2 
+0.0318754 0.126292 0.0506164 3 2 
+0.0318408 0.126456 0.0505538 3 2 
+0.0318061 0.126618 0.0504916 3 2 
+0.0317712 0.126781 0.050429 3 2 
+0.0317363 0.126943 0.0503657 3 2 
+0.0317012 0.127102 0.0503022 3 2 
+0.031666 0.127263 0.0502392 3 2 
+0.0316306 0.127424 0.0501759 3 2 
+0.0315951 0.127581 0.0501095 3 2 
+0.0315595 0.127738 0.0500455 3 2 
+0.0315237 0.127896 0.0499813 3 2 
+0.0314878 0.128053 0.0499167 3 2 
+0.0314518 0.128209 0.0498521 3 2 
+0.0314156 0.128365 0.0497871 3 2 
+0.0313793 0.12852 0.0497212 3 2 
+0.0313428 0.128675 0.0496556 3 2 
+0.0313061 0.128828 0.0495897 3 2 
+0.0312693 0.128982 0.0495237 3 2 
+0.0312323 0.129133 0.0494572 3 2 
+0.0311952 0.129283 0.0493904 3 2 
+0.0311579 0.129434 0.0493235 3 2 
+0.0311205 0.129582 0.0492562 3 2 
+0.0310828 0.129728 0.0491886 3 2 
+0.031045 0.129874 0.0491214 3 2 
+0.0310071 0.130018 0.0490531 3 2 
+0.0309689 0.130161 0.0489845 3 2 
+0.0309306 0.130303 0.0489159 3 2 
+0.0308921 0.130443 0.0488467 3 2 
+0.0308534 0.130582 0.0487771 3 2 
+0.0308145 0.130714 0.0487081 3 2 
+0.0307755 0.13085 0.0486379 3 2 
+0.0307363 0.130984 0.0485673 3 2 
+0.0306968 0.131118 0.0484991 3 2 
+0.0306572 0.131249 0.0484279 3 2 
+0.0306174 0.13138 0.0483562 3 2 
+0.0305774 0.131515 0.0482852 3 2 
+0.0305372 0.131643 0.0482128 3 2 
+0.0304969 0.131769 0.0481402 3 2 
+0.0304563 0.131893 0.0480674 3 2 
+0.0304155 0.132016 0.0479947 3 2 
+0.0303746 0.132137 0.0479218 3 2 
+0.0303334 0.132257 0.0478474 3 2 
+0.0302921 0.132375 0.0477731 3 2 
+0.0302506 0.13249 0.0476985 3 2 
+0.0302088 0.132603 0.0476237 3 2 
+0.0301669 0.132715 0.0475485 3 2 
+0.0301249 0.132825 0.047473 3 2 
+0.0300826 0.132929 0.0473992 3 2 
+0.0300401 0.133034 0.0473237 3 2 
+0.0299975 0.133138 0.0472474 3 2 
+0.0299547 0.133243 0.0471684 3 2 
+0.0299117 0.133344 0.0470917 3 2 
+0.0298685 0.133443 0.0470148 3 2 
+0.0298252 0.133542 0.0469365 3 2 
+0.0297817 0.133637 0.0468589 3 2 
+0.0297381 0.13373 0.0467811 3 2 
+0.0296942 0.133821 0.0467027 3 2 
+0.0296503 0.13391 0.0466243 3 2 
+0.0296062 0.133997 0.0465457 3 2 
+0.0295619 0.134079 0.0464665 3 2 
+0.0295176 0.134161 0.0463873 3 2 
+0.0294731 0.134242 0.0463079 3 2 
+0.0294284 0.134325 0.0462295 3 2 
+0.0293837 0.134404 0.0461495 3 2 
+0.0293388 0.134481 0.0460693 3 2 
+0.0292938 0.134556 0.0459894 3 2 
+0.0292487 0.134628 0.0459088 3 2 
+0.0292035 0.134699 0.0458281 3 2 
+0.0291582 0.134764 0.0457493 3 2 
+0.0291128 0.134831 0.0456682 3 2 
+0.0290674 0.134898 0.045587 3 2 
+0.0290218 0.134966 0.0455064 3 2 
+0.0289762 0.13503 0.0454255 3 2 
+0.0289305 0.135093 0.0453445 3 2 
+0.0288847 0.135157 0.0452625 3 2 
+0.0288389 0.135217 0.0451807 3 2 
+0.028793 0.135275 0.0450988 3 2 
+0.0287471 0.135326 0.045015 3 2 
+0.0287011 0.135381 0.0449332 3 2 
+0.0286551 0.135435 0.0448515 3 2 
+0.028609 0.135493 0.0447701 3 2 
+0.0285629 0.135546 0.0446882 3 2 
+0.0285168 0.135598 0.0446064 3 2 
+0.0284706 0.13565 0.0445239 3 2 
+0.0284244 0.135699 0.0444419 3 2 
+0.0283782 0.135748 0.04436 3 2 
+0.028332 0.135796 0.0442781 3 2 
+0.0282857 0.135843 0.0441961 3 2 
+0.0282395 0.135888 0.0441142 3 2 
+0.0281932 0.135933 0.0440307 3 2 
+0.0281469 0.135976 0.0439486 3 2 
+0.0281006 0.13602 0.0438664 3 2 
+0.0280543 0.136059 0.0437855 3 2 
+0.028008 0.1361 0.0437032 3 2 
+0.0279617 0.136142 0.0436209 3 2 
+0.0279154 0.136187 0.0435416 3 2 
+0.027869 0.136228 0.0434597 3 2 
+0.0278227 0.136268 0.0433774 3 2 
+0.0277764 0.136309 0.0432926 3 2 
+0.0277301 0.136348 0.0432108 3 2 
+0.0276839 0.136386 0.0431289 3 2 
+0.0276376 0.136424 0.0430459 3 2 
+0.0275913 0.136461 0.042964 3 2 
+0.0275451 0.136498 0.0428822 3 2 
+0.0274988 0.136532 0.0428001 3 2 
+0.0274526 0.136567 0.0427183 3 2 
+0.0274064 0.136602 0.0426364 3 2 
+0.0273602 0.136636 0.0425548 3 2 
+0.0273141 0.13667 0.0424731 3 2 
+0.0272679 0.136704 0.0423914 3 2 
+0.0272218 0.136738 0.0423099 3 2 
+0.0271757 0.136773 0.0422284 3 2 
+0.0271296 0.136808 0.0421469 3 2 
+0.0270835 0.136843 0.0420654 3 2 
+0.0270375 0.136877 0.041984 3 2 
+0.0269914 0.13691 0.0419027 3 2 
+0.0269454 0.136944 0.0418217 3 2 
+0.0268995 0.136977 0.0417404 3 2 
+0.0268535 0.137009 0.0416592 3 2 
+0.0268076 0.13704 0.0415792 3 2 
+0.0267617 0.137071 0.0414981 3 2 
+0.0267159 0.137101 0.0414171 3 2 
+0.02667 0.137125 0.0413372 3 2 
+0.0266242 0.137157 0.0412565 3 2 
+0.0265785 0.137189 0.0411759 3 2 
+0.0265327 0.137219 0.0410931 3 2 
+0.026487 0.137248 0.0410125 3 2 
+0.0264414 0.137277 0.040932 3 2 
+0.0263957 0.137311 0.0408518 3 2 
+0.0263501 0.137342 0.0407714 3 2 
+0.0263045 0.137372 0.0406912 3 2 
+0.026259 0.137403 0.0406106 3 2 
+0.0262135 0.137432 0.0405304 3 2 
+0.026168 0.13746 0.0404503 3 2 
+0.0261226 0.137491 0.0403706 3 2 
+0.0260772 0.137519 0.0402906 3 2 
+0.0260318 0.137547 0.0402107 3 2 
+0.0259865 0.137574 0.0401313 3 2 
+0.0259412 0.137601 0.0400516 3 2 
+0.025896 0.137628 0.0399719 3 2 
+0.0258508 0.137658 0.0398932 3 2 
+0.0258056 0.137685 0.0398137 3 2 
+0.0257605 0.137712 0.0397343 3 2 
+0.0257154 0.137739 0.0396547 3 2 
+0.0256703 0.137765 0.0395755 3 2 
+0.0256253 0.137791 0.0394964 3 2 
+0.0255804 0.13782 0.0394167 3 2 
+0.0255355 0.137846 0.0393378 3 2 
+0.0254906 0.137872 0.039259 3 2 
+0.0254458 0.137897 0.0391806 3 2 
+0.025401 0.137925 0.0391019 3 2 
+0.0253562 0.137953 0.0390234 3 2 
+0.0253115 0.137985 0.038945 3 2 
+0.0252669 0.138012 0.0388666 3 2 
+0.0252223 0.138039 0.0387884 3 2 
+0.0251777 0.138067 0.0387102 3 2 
+0.0251332 0.138094 0.0386321 3 2 
+0.0250887 0.138121 0.0385542 3 2 
+0.0250443 0.138147 0.0384763 3 2 
+0.0249999 0.138174 0.0383986 3 2 
+0.0249556 0.1382 0.038321 3 2 
+0.0249113 0.138225 0.0382434 3 2 
+0.0248671 0.138251 0.038166 3 2 
+0.0248229 0.138276 0.0380887 3 2 
+0.0247788 0.1383 0.0380115 3 2 
+0.0247347 0.138325 0.0379344 3 2 
+0.0246907 0.13835 0.0378574 3 2 
+0.0246468 0.138379 0.0377803 3 2 
+0.0246028 0.138405 0.0377035 3 2 
+0.024559 0.138432 0.0376268 3 2 
+0.0245152 0.138457 0.0375518 3 2 
+0.0244714 0.138482 0.0374753 3 2 
+0.0244277 0.138507 0.037399 3 2 
+0.024384 0.138536 0.0373235 3 2 
+0.0243404 0.138562 0.0372474 3 2 
+0.0242969 0.138587 0.0371714 3 2 
+0.0242534 0.138613 0.0370954 3 2 
+0.02421 0.138638 0.0370196 3 2 
+0.0241666 0.138663 0.0369439 3 2 
+0.0241232 0.138689 0.0368678 3 2 
+0.02408 0.138715 0.0367924 3 2 
+0.0240368 0.13874 0.0367171 3 2 
+0.0239936 0.138766 0.0366426 3 2 
+0.0239505 0.138791 0.0365675 3 2 
+0.0239075 0.138816 0.0364925 3 2 
+0.0238645 0.138842 0.0364163 3 2 
+0.0238216 0.138867 0.0363416 3 2 
+0.0237787 0.138893 0.0362669 3 2 
+0.0237359 0.138919 0.0361916 3 2 
+0.0236932 0.138944 0.0361172 3 2 
+0.0236505 0.138969 0.0360429 3 2 
+0.0236079 0.138995 0.0359684 3 2 
+0.0235653 0.13902 0.0358944 3 2 
+0.0235228 0.139045 0.0358205 3 2 
+0.0234804 0.139066 0.0357487 3 2 
+0.023438 0.139091 0.0356751 3 2 
+0.0233957 0.139115 0.0356016 3 2 
+0.0233534 0.139141 0.0355282 3 2 
+0.0233112 0.139166 0.0354549 3 2 
+0.0232691 0.139191 0.0353818 3 2 
+0.0232271 0.139218 0.0353086 3 2 
+0.0231851 0.139245 0.0352357 3 2 
+0.0231431 0.139272 0.0351629 3 2 
+0.0231012 0.139298 0.0350904 3 2 
+0.0230594 0.139325 0.035018 3 2 
+0.0230177 0.139351 0.0349456 3 2 
+0.022976 0.139377 0.0348722 3 2 
+0.0229344 0.139403 0.0348001 3 2 
+0.0228929 0.13943 0.0347282 3 2 
+0.0228514 0.139456 0.0346567 3 2 
+0.02281 0.139483 0.034585 3 2 
+0.0227686 0.139509 0.0345135 3 2 
+0.0227274 0.139535 0.0344408 3 2 
+0.0226862 0.139562 0.0343695 3 2 
+0.022645 0.139588 0.0342983 3 2 
+0.0226039 0.139614 0.0342272 3 2 
+0.0225629 0.139641 0.0341563 3 2 
+0.022522 0.139667 0.0340856 3 2 
+0.0224811 0.139694 0.0340148 3 2 
+0.0224403 0.13972 0.0339443 3 2 
+0.0223996 0.139747 0.0338739 3 2 
+0.0223589 0.139773 0.0338038 3 2 
+0.0223183 0.1398 0.0337337 3 2 
+0.0222778 0.139826 0.0336638 3 2 
+0.0222374 0.139852 0.0335939 3 2 
+0.022197 0.139878 0.0335242 3 2 
+0.0221567 0.139904 0.0334547 3 2 
+0.0221165 0.139924 0.0333871 3 2 
+0.0220763 0.139952 0.0333179 3 2 
+0.0220362 0.13998 0.0332488 3 2 
+0.0219962 0.140006 0.0331786 3 2 
+0.0219562 0.140034 0.0331097 3 2 
+0.0219163 0.140063 0.033041 3 2 
+0.0218765 0.140089 0.0329724 3 2 
+0.0218368 0.140118 0.032904 3 2 
+0.0217971 0.140146 0.0328357 3 2 
+0.0217576 0.140174 0.0327673 3 2 
+0.021718 0.140203 0.0326994 3 2 
+0.0216786 0.140231 0.0326316 3 2 
+0.0216392 0.140257 0.0325639 3 2 
+0.0216 0.140285 0.0324964 3 2 
+0.0215607 0.140314 0.032429 3 2 
+0.0215216 0.140344 0.032362 3 2 
+0.0214825 0.140372 0.032295 3 2 
+0.0214435 0.1404 0.0322281 3 2 
+0.0214046 0.140429 0.0321613 3 2 
+0.0213658 0.140457 0.0320947 3 2 
+0.021327 0.140485 0.0320281 3 2 
+0.0212883 0.140513 0.0319624 3 2 
+0.0212497 0.140541 0.0318961 3 2 
+0.0212112 0.140569 0.03183 3 2 
+0.0211727 0.140598 0.0317646 3 2 
+0.0211343 0.140626 0.0316988 3 2 
+0.021096 0.140654 0.0316331 3 2 
+0.0210578 0.140681 0.0315673 3 2 
+0.0210196 0.140709 0.0315021 3 2 
+0.0209815 0.140737 0.031437 3 2 
+0.0209435 0.140763 0.0313714 3 2 
+0.0209056 0.140794 0.0313066 3 2 
+0.0208678 0.140824 0.0312419 3 2 
+0.02083 0.140856 0.0311772 3 2 
+0.0207923 0.140886 0.0311128 3 2 
+0.0207547 0.140917 0.0310486 3 2 
+0.0207171 0.140943 0.0309843 3 2 
+0.0206797 0.140974 0.0309204 3 2 
+0.0206423 0.141005 0.0308566 3 2 
+0.020605 0.141031 0.030793 3 2 
+0.0205678 0.141062 0.0307295 3 2 
+0.0205306 0.141093 0.0306661 3 2 
+0.0204936 0.141121 0.0306032 3 2 
+0.0204566 0.141153 0.0305401 3 2 
+0.0204197 0.141184 0.0304772 3 2 
+0.0203829 0.141212 0.0304149 3 2 
+0.0203461 0.141244 0.0303523 3 2 
+0.0203094 0.141276 0.0302898 3 2 
+0.0202729 0.141306 0.0302277 3 2 
+0.0202363 0.141338 0.0301655 3 2 
+0.0201999 0.14137 0.0301035 3 2 
+0.0201636 0.141402 0.0300419 3 2 
+0.0201273 0.141434 0.0299802 3 2 
+0.0200911 0.141466 0.0299186 3 2 
+0.020055 0.141497 0.0298571 3 2 
+0.020019 0.14153 0.029796 3 2 
+0.019983 0.141562 0.0297351 3 2 
+0.0199471 0.141593 0.0296737 3 2 
+0.0199114 0.141626 0.029613 3 2 
+0.0198756 0.141658 0.0295524 3 2 
+0.01984 0.141691 0.0294919 3 2 
+0.0198045 0.141723 0.0294316 3 2 
+0.019769 0.141756 0.0293715 3 2 
+0.0197336 0.141788 0.0293116 3 2 
+0.0196983 0.141821 0.0292517 3 2 
+0.0196631 0.141854 0.0291921 3 2 
+0.0196279 0.141887 0.0291327 3 2 
+0.0195929 0.14192 0.0290733 3 2 
+0.0195579 0.141953 0.0290141 3 2 
+0.019523 0.141986 0.028955 3 2 
+0.0194882 0.142019 0.0288961 3 2 
+0.0194534 0.142052 0.0288374 3 2 
+0.0194188 0.142085 0.0287789 3 2 
+0.0193842 0.142118 0.0287205 3 2 
+0.0193497 0.142151 0.0286623 3 2 
+0.0193153 0.142182 0.0286042 3 2 
+0.019281 0.142214 0.0285463 3 2 
+0.0192467 0.142247 0.0284885 3 2 
+0.0192125 0.142284 0.0284307 3 2 
+0.0191784 0.142319 0.0283732 3 2 
+0.0191444 0.142354 0.0283158 3 2 
+0.0191105 0.142392 0.0282588 3 2 
+0.0190766 0.142427 0.0282017 3 2 
+0.0190429 0.142461 0.0281447 3 2 
+0.0190092 0.142487 0.0280879 3 2 
+0.0189756 0.142521 0.0280313 3 2 
+0.0189421 0.142557 0.0279749 3 2 
+0.0189086 0.142601 0.0279187 3 2 
+0.0188753 0.142636 0.0278625 3 2 
+0.018842 0.142671 0.0278066 3 2 
+0.0188088 0.142701 0.0277509 3 2 
+0.0187757 0.142736 0.0276952 3 2 
+0.0187426 0.14277 0.0276397 3 2 
+0.0187097 0.142812 0.0275844 3 2 
+0.0186768 0.142847 0.0275292 3 2 
+0.018644 0.142882 0.0274742 3 2 
+0.0186113 0.142915 0.027419 3 2 
+0.0185787 0.142953 0.0273643 3 2 
+0.0185461 0.14299 0.0273097 3 2 
+0.0185137 0.143023 0.0272554 3 2 
+0.0184813 0.143059 0.0272011 3 2 
+0.018449 0.143095 0.027147 3 2 
+0.0184167 0.143136 0.0270929 3 2 
+0.0183846 0.143172 0.027039 3 2 
+0.0183525 0.143208 0.0269853 3 2 
+0.0183205 0.143245 0.0269321 3 2 
+0.0182886 0.143281 0.0268786 3 2 
+0.0182568 0.143318 0.0268253 3 2 
+0.018225 0.143356 0.0267723 3 2 
+0.0181934 0.143395 0.0267193 3 2 
+0.0181618 0.143434 0.0266664 3 2 
+0.0181303 0.143472 0.0266135 3 2 
+0.0180989 0.143511 0.026561 3 2 
+0.0180675 0.14355 0.0265087 3 2 
+0.0180363 0.143589 0.0264565 3 2 
+0.0180051 0.143628 0.0264044 3 2 
+0.017974 0.143667 0.0263525 3 2 
+0.0179429 0.143706 0.0263009 3 2 
+0.017912 0.143745 0.0262493 3 2 
+0.0178811 0.143785 0.0261977 3 2 
+0.0178503 0.143824 0.0261466 3 2 
+0.0178196 0.143863 0.0260954 3 2 
+0.017789 0.143902 0.0260442 3 2 
+0.0177584 0.143941 0.0259935 3 2 
+0.017728 0.143981 0.0259429 3 2 
+0.0176976 0.14402 0.0258923 3 2 
+0.0176673 0.144059 0.0258418 3 2 
+0.017637 0.144099 0.0257914 3 2 
+0.0176069 0.144139 0.0257411 3 2 
+0.0175768 0.144179 0.0256912 3 2 
+0.0175468 0.144218 0.0256412 3 2 
+0.0175169 0.144258 0.0255914 3 2 
+0.017487 0.144297 0.0255416 3 2 
+0.0174573 0.144337 0.0254921 3 2 
+0.0174276 0.144377 0.0254428 3 2 
+0.017398 0.144411 0.0253936 3 2 
+0.0173684 0.144451 0.0253446 3 2 
+0.017339 0.144491 0.0252957 3 2 
+0.0173096 0.144533 0.0252472 3 2 
+0.0172803 0.144575 0.0251987 3 2 
+0.0172511 0.144617 0.0251503 3 2 
+0.0172219 0.144662 0.0251018 3 2 
+0.0171928 0.144704 0.0250536 3 2 
+0.0171639 0.144746 0.0250054 3 2 
+0.0171349 0.144783 0.024958 3 2 
+0.0171061 0.144826 0.0249103 3 2 
+0.0170773 0.144869 0.0248625 3 2 
+0.0170486 0.144911 0.0248149 3 2 
+0.01702 0.144954 0.0247676 3 2 
+0.0169915 0.144996 0.0247205 3 2 
+0.016963 0.14504 0.0246726 3 2 
+0.0169346 0.145083 0.0246256 3 2 
+0.0169063 0.145125 0.0245788 3 2 
+0.0168781 0.145166 0.0245322 3 2 
+0.0168499 0.145209 0.0244856 3 2 
+0.0168218 0.145252 0.0244392 3 2 
+0.0167938 0.145294 0.0243932 3 2 
+0.0167659 0.145338 0.024347 3 2 
+0.016738 0.145381 0.0243009 3 2 
+0.0167102 0.145423 0.0242553 3 2 
+0.0166825 0.145467 0.0242095 3 2 
+0.0166549 0.145511 0.0241638 3 2 
+0.0166273 0.145553 0.024118 3 2 
+0.0165998 0.145597 0.0240727 3 2 
+0.0165724 0.145641 0.0240275 3 2 
+0.0165451 0.145684 0.0239824 3 2 
+0.0165178 0.145728 0.0239375 3 2 
+0.0164906 0.145772 0.0238927 3 2 
+0.0164635 0.145816 0.0238475 3 2 
+0.0164364 0.14586 0.0238029 3 2 
+0.0164094 0.145904 0.0237584 3 2 
+0.0163825 0.145949 0.0237142 3 2 
+0.0163557 0.145993 0.0236699 3 2 
+0.0163289 0.146037 0.0236258 3 2 
+0.0163022 0.146082 0.0235823 3 2 
+0.0162756 0.146126 0.0235383 3 2 
+0.0162491 0.14617 0.0234945 3 2 
+0.0162226 0.146215 0.0234514 3 2 
+0.0161962 0.14626 0.0234078 3 2 
+0.0161698 0.146304 0.0233644 3 2 
+0.0161436 0.146349 0.0233215 3 2 
+0.0161174 0.146393 0.0232783 3 2 
+0.0160912 0.146437 0.0232352 3 2 
+0.0160652 0.146478 0.0231928 3 2 
+0.0160392 0.146522 0.0231499 3 2 
+0.0160133 0.146566 0.0231072 3 2 
+0.0159874 0.14662 0.023065 3 2 
+0.0159617 0.146665 0.0230225 3 2 
+0.015936 0.146709 0.0229802 3 2 
+0.0159103 0.146753 0.0229381 3 2 
+0.0158848 0.146797 0.0228959 3 2 
+0.0158593 0.146842 0.0228539 3 2 
+0.0158338 0.146892 0.022812 3 2 
+0.0158085 0.146937 0.0227702 3 2 
+0.0157832 0.146982 0.0227286 3 2 
+0.0157579 0.147029 0.0226875 3 2 
+0.0157328 0.147074 0.0226461 3 2 
+0.0157077 0.147119 0.0226049 3 2 
+0.0156827 0.147165 0.0225634 3 2 
+0.0156577 0.147211 0.0225225 3 2 
+0.0156328 0.147257 0.0224817 3 2 
+0.015608 0.147311 0.0224414 3 2 
+0.0155832 0.147357 0.0224009 3 2 
+0.0155585 0.147402 0.0223606 3 2 
+0.0155339 0.147447 0.02232 3 2 
+0.0155094 0.147492 0.0222796 3 2 
+0.0154849 0.147539 0.0222394 3 2 
+0.0154604 0.147588 0.0221993 3 2 
+0.0154361 0.147634 0.0221594 3 2 
+0.0154118 0.147683 0.0221195 3 2 
+0.0153875 0.147737 0.0220797 3 2 
+0.0153634 0.147783 0.0220402 3 2 
+0.0153393 0.14783 0.0220008 3 2 
+0.0153152 0.147876 0.021962 3 2 
+0.0152913 0.147925 0.0219228 3 2 
+0.0152674 0.147974 0.0218838 3 2 
+0.0152435 0.148025 0.0218439 3 2 
+0.0152197 0.148073 0.021805 3 2 
+0.015196 0.148122 0.0217662 3 2 
+0.0151724 0.14817 0.0217275 3 2 
+0.0151488 0.148219 0.021689 3 2 
+0.0151252 0.148268 0.0216505 3 2 
+0.0151018 0.148316 0.021612 3 2 
+0.0150784 0.148365 0.0215738 3 2 
+0.015055 0.148414 0.0215356 3 2 
+0.0150318 0.148463 0.0214976 3 2 
+0.0150085 0.148512 0.0214596 3 2 
+0.0149854 0.14856 0.0214218 3 2 
+0.0149623 0.148609 0.0213841 3 2 
+0.0149393 0.148658 0.0213465 3 2 
+0.0149163 0.148706 0.0213089 3 2 
+0.0148934 0.148755 0.0212717 3 2 
+0.0148705 0.148803 0.0212343 3 2 
+0.0148477 0.148852 0.021197 3 2 
+0.014825 0.148901 0.02116 3 2 
+0.0148023 0.148949 0.021123 3 2 
+0.0147797 0.148998 0.021086 3 2 
+0.0147572 0.149047 0.0210491 3 2 
+0.0147347 0.149096 0.0210125 3 2 
+0.0147123 0.149144 0.0209759 3 2 
+0.0146899 0.149193 0.0209394 3 2 
+0.0146676 0.149242 0.020903 3 2 
+0.0146453 0.14929 0.0208667 3 2 
+0.0146231 0.14934 0.020831 3 2 
+0.014601 0.14939 0.0207948 3 2 
+0.0145789 0.149441 0.0207588 3 2 
+0.0145569 0.149491 0.0207229 3 2 
+0.0145349 0.149542 0.0206871 3 2 
+0.014513 0.149593 0.0206513 3 2 
+0.0144912 0.149645 0.0206155 3 2 
+0.0144694 0.149695 0.02058 3 2 
+0.0144477 0.149746 0.0205445 3 2 
+0.014426 0.149797 0.0205095 3 2 
+0.0144044 0.149848 0.0204744 3 2 
+0.0143828 0.149898 0.0204393 3 2 
+0.0143613 0.149949 0.020404 3 2 
+0.0143399 0.15 0.0203691 3 2 
+0.0143185 0.15005 0.0203344 3 2 
+0.0142971 0.1501 0.0202995 3 2 
+0.0142758 0.150151 0.0202649 3 2 
+0.0142546 0.150201 0.0202304 3 2 
+0.0142334 0.150251 0.0201958 3 2 
+0.0142123 0.150301 0.0201615 3 2 
+0.0141913 0.150351 0.0201273 3 2 
+0.0141703 0.150402 0.0200928 3 2 
+0.0141493 0.150452 0.0200588 3 2 
+0.0141284 0.150502 0.0200248 3 2 
+0.0141076 0.150551 0.0199912 3 2 
+0.0140868 0.150601 0.0199574 3 2 
+0.014066 0.15065 0.0199238 3 2 
+0.0140453 0.150709 0.0198896 3 2 
+0.0140247 0.150761 0.019856 3 2 
+0.0140041 0.150812 0.0198225 3 2 
+0.0139836 0.150855 0.0197901 3 2 
+0.0139631 0.150908 0.0197567 3 2 
+0.0139427 0.15096 0.0197234 3 2 
+0.0139223 0.151007 0.0196906 3 2 
+0.013902 0.15106 0.0196575 3 2 
+0.0138817 0.151113 0.0196244 3 2 
+0.0138615 0.151161 0.0195912 3 2 
+0.0138414 0.151214 0.0195584 3 2 
+0.0138213 0.151267 0.0195256 3 2 
+0.0138012 0.151316 0.0194927 3 2 
+0.0137812 0.151369 0.0194602 3 2 
+0.0137612 0.151422 0.0194278 3 2 
+0.0137413 0.151473 0.0193956 3 2 
+0.0137215 0.151526 0.0193633 3 2 
+0.0137016 0.151579 0.0193311 3 2 
+0.0136819 0.15163 0.0192991 3 2 
+0.0136622 0.151683 0.0192671 3 2 
+0.0136425 0.151736 0.0192351 3 2 
+0.0136229 0.151787 0.0192033 3 2 
+0.0136034 0.15184 0.0191715 3 2 
+0.0135838 0.151892 0.0191399 3 2 
+0.0135644 0.151942 0.0191083 3 2 
+0.013545 0.151995 0.0190769 3 2 
+0.0135256 0.152048 0.0190455 3 2 
+0.0135063 0.152098 0.0190145 3 2 
+0.013487 0.152151 0.0189834 3 2 
+0.0134678 0.152204 0.0189523 3 2 
+0.0134486 0.152255 0.0189218 3 2 
+0.0134295 0.152308 0.0188909 3 2 
+0.0134104 0.152361 0.0188601 3 2 
+0.0133914 0.152412 0.0188296 3 2 
+0.0133724 0.152465 0.018799 3 2 
+0.0133535 0.152518 0.0187685 3 2 
+0.0133346 0.152569 0.0187386 3 2 
+0.0133157 0.152622 0.0187082 3 2 
+0.0132969 0.152675 0.0186779 3 2 
+0.0132782 0.152727 0.0186486 3 2 
+0.0132595 0.15278 0.0186185 3 2 
+0.0132408 0.152833 0.0185883 3 2 
+0.0132222 0.152884 0.0185564 3 2 
+0.0132036 0.152937 0.0185261 3 2 
+0.0131851 0.15299 0.0184959 3 2 
+0.0131667 0.153042 0.0184642 3 2 
+0.0131482 0.153095 0.0184342 3 2 
+0.0131298 0.153147 0.0184044 3 2 
+0.0131115 0.153199 0.0183753 3 2 
+0.0130932 0.153252 0.0183458 3 2 
+0.0130749 0.153305 0.0183163 3 2 
+0.0130567 0.153357 0.0182894 3 2 
+0.0130386 0.15341 0.0182602 3 2 
+0.0130204 0.153463 0.0182311 3 2 
+0.0130024 0.153515 0.0181984 3 2 
+0.0129843 0.153568 0.0181693 3 2 
+0.0129663 0.15362 0.0181403 3 2 
+0.0129484 0.153673 0.0181112 3 2 
+0.0129305 0.153725 0.0180822 3 2 
+0.0129126 0.153778 0.0180532 3 2 
+0.0128948 0.153831 0.0180267 3 2 
+0.012877 0.153883 0.0179982 3 2 
+0.0128593 0.153936 0.0179697 3 2 
+0.0128416 0.153987 0.0179386 3 2 
+0.012824 0.154039 0.0179099 3 2 
+0.0128063 0.154091 0.0178814 3 2 
+0.0127888 0.154145 0.0178536 3 2 
+0.0127713 0.154197 0.0178254 3 2 
+0.0127538 0.154249 0.0177972 3 2 
+0.0127363 0.154299 0.017769 3 2 
+0.0127189 0.15435 0.0177407 3 2 
+0.0127016 0.154402 0.0177126 3 2 
+0.0126842 0.154454 0.0176844 3 2 
+0.012667 0.154505 0.0176566 3 2 
+0.0126497 0.15456 0.0176289 3 2 
+0.0126325 0.154615 0.0176006 3 2 
+0.0126154 0.154669 0.0175728 3 2 
+0.0125983 0.154723 0.0175451 3 2 
+0.0125812 0.154777 0.0175176 3 2 
+0.0125641 0.154831 0.01749 3 2 
+0.0125471 0.154884 0.0174625 3 2 
+0.0125302 0.154936 0.0174361 3 2 
+0.0125133 0.15499 0.0174087 3 2 
+0.0124964 0.155043 0.0173813 3 2 
+0.0124795 0.155095 0.017354 3 2 
+0.0124627 0.155148 0.0173268 3 2 
+0.012446 0.155202 0.0172997 3 2 
+0.0124292 0.155255 0.0172729 3 2 
+0.0124126 0.155308 0.0172459 3 2 
+0.0123959 0.155361 0.0172189 3 2 
+0.0123793 0.155414 0.0171929 3 2 
+0.0123627 0.155467 0.017166 3 2 
+0.0123462 0.15552 0.0171392 3 2 
+0.0123297 0.155572 0.0171124 3 2 
+0.0123132 0.155625 0.0170858 3 2 
+0.0122968 0.155678 0.0170592 3 2 
+0.0122804 0.155731 0.0170333 3 2 
+0.0122641 0.155783 0.0170068 3 2 
+0.0122477 0.155836 0.0169804 3 2 
+0.0122315 0.155889 0.0169544 3 2 
+0.0122152 0.155941 0.0169281 3 2 
+0.012199 0.155994 0.0169019 3 2 
+0.0121829 0.156047 0.0168762 3 2 
+0.0121667 0.156099 0.0168501 3 2 
+0.0121506 0.156151 0.016824 3 2 
+0.0121346 0.156205 0.0167987 3 2 
+0.0121186 0.156257 0.0167728 3 2 
+0.0121026 0.156309 0.0167469 3 2 
+0.0120866 0.156362 0.0167219 3 2 
+0.0120707 0.156414 0.0166961 3 2 
+0.0120548 0.156466 0.0166704 3 2 
+0.012039 0.156519 0.0166443 3 2 
+0.0120232 0.15657 0.0166187 3 2 
+0.0120074 0.156622 0.0165932 3 2 
+0.0119916 0.156674 0.0165675 3 2 
+0.0119759 0.156726 0.0165422 3 2 
+0.0119603 0.156777 0.0165169 3 2 
+0.0119446 0.15683 0.0164915 3 2 
+0.011929 0.156881 0.0164663 3 2 
+0.0119134 0.156932 0.0164413 3 2 
+0.0118979 0.156985 0.0164165 3 2 
+0.0118824 0.157036 0.0163916 3 2 
+0.0118669 0.15709 0.0163668 3 2 
+0.0118515 0.157143 0.0163419 3 2 
+0.0118361 0.157197 0.0163172 3 2 
+0.0118207 0.157251 0.0162926 3 2 
+0.0118054 0.157302 0.0162681 3 2 
+0.0117901 0.157356 0.0162436 3 2 
+0.0117748 0.15741 0.0162192 3 2 
+0.0117596 0.157462 0.0161944 3 2 
+0.0117444 0.157516 0.01617 3 2 
+0.0117292 0.157569 0.0161457 3 2 
+0.0117141 0.157621 0.0161217 3 2 
+0.0116989 0.157675 0.0160975 3 2 
+0.0116839 0.157728 0.0160734 3 2 
+0.0116688 0.15778 0.016049 3 2 
+0.0116538 0.157833 0.016025 3 2 
+0.0116388 0.157886 0.016001 3 2 
+0.0116239 0.157939 0.015977 3 2 
+0.011609 0.157991 0.0159531 3 2 
+0.0115941 0.158044 0.0159294 3 2 
+0.0115792 0.158096 0.0159051 3 2 
+0.0115644 0.158149 0.0158814 3 2 
+0.0115496 0.158201 0.0158578 3 2 
+0.0115348 0.158253 0.0158344 3 2 
+0.0115201 0.158305 0.0158109 3 2 
+0.0115054 0.158358 0.0157875 3 2 
+0.0114907 0.15841 0.0157654 3 2 
+0.0114761 0.158462 0.0157421 3 2 
+0.0114615 0.158514 0.0157189 3 2 
+0.0114469 0.158566 0.0156961 3 2 
+0.0114323 0.158618 0.0156726 3 2 
+0.0114178 0.15867 0.0156491 3 2 
+0.0114033 0.158722 0.0156264 3 2 
+0.0113889 0.158773 0.015603 3 2 
+0.0113744 0.158825 0.0155796 3 2 
+0.01136 0.158877 0.0155575 3 2 
+0.0113457 0.158928 0.0155343 3 2 
+0.0113313 0.15898 0.015511 3 2 
+0.011317 0.159032 0.0154884 3 2 
+0.0113027 0.159083 0.0154653 3 2 
+0.0112885 0.159134 0.0154422 3 2 
+0.0112742 0.159186 0.0154193 3 2 
+0.01126 0.159237 0.0153963 3 2 
+0.0112459 0.159288 0.0153734 3 2 
+0.0112317 0.15934 0.0153498 3 2 
+0.0112176 0.159391 0.0153271 3 2 
+0.0112035 0.159441 0.0153044 3 2 
+0.0111895 0.159494 0.0152804 3 2 
+0.0111754 0.159544 0.0152579 3 2 
+0.0111614 0.159594 0.0152354 3 2 
+0.0111475 0.159646 0.0152129 3 2 
+0.0111335 0.159696 0.0151906 3 2 
+0.0111196 0.159748 0.0151683 3 2 
+0.0111057 0.159799 0.0151461 3 2 
+0.0110918 0.159851 0.0151239 3 2 
+0.011078 0.159904 0.0151018 3 2 
+0.0110642 0.159953 0.0150829 3 2 
+0.0110504 0.160005 0.0150611 3 2 
+0.0110367 0.160057 0.0150393 3 2 
+0.0110229 0.160106 0.0150138 3 2 
+0.0110092 0.160159 0.0149919 3 2 
+0.0109955 0.160211 0.01497 3 2 
+0.0109819 0.160261 0.0149482 3 2 
+0.0109683 0.160314 0.0149265 3 2 
+0.0109547 0.160366 0.0149048 3 2 
+0.0109411 0.160417 0.0148841 3 2 
+0.0109276 0.160469 0.0148624 3 2 
+0.010914 0.160521 0.0148407 3 2 
+0.0109006 0.160571 0.0148203 3 2 
+0.0108871 0.160623 0.0147987 3 2 
+0.0108736 0.160674 0.0147771 3 2 
+0.0108602 0.160725 0.0147548 3 2 
+0.0108468 0.160776 0.0147334 3 2 
+0.0108335 0.160827 0.0147119 3 2 
+0.0108201 0.160878 0.0146938 3 2 
+0.0108068 0.160929 0.0146723 3 2 
+0.0107935 0.160979 0.0146509 3 2 
+0.0107803 0.16103 0.0146281 3 2 
+0.010767 0.16108 0.0146068 3 2 
+0.0107538 0.16113 0.0145856 3 2 
+0.0107406 0.161181 0.0145678 3 2 
+0.0107275 0.161231 0.014547 3 2 
+0.0107143 0.161281 0.0145263 3 2 
+0.0107012 0.161332 0.0145027 3 2 
+0.0106881 0.161382 0.0144817 3 2 
+0.010675 0.161433 0.0144607 3 2 
+0.010662 0.161483 0.014441 3 2 
+0.010649 0.161533 0.0144205 3 2 
+0.010636 0.161583 0.0144 3 2 
+0.010623 0.161633 0.0143789 3 2 
+0.0106101 0.161683 0.0143581 3 2 
+0.0105971 0.161732 0.0143373 3 2 
+0.0105842 0.161782 0.0143176 3 2 
+0.0105714 0.161831 0.0142973 3 2 
+0.0105585 0.16188 0.0142771 3 2 
+0.0105457 0.16193 0.0142578 3 2 
+0.0105329 0.161979 0.0142376 3 2 
+0.0105201 0.162028 0.014217 3 2 
+0.0105073 0.162078 0.0141959 3 2 
+0.0104946 0.162127 0.0141759 3 2 
+0.0104819 0.162175 0.0141559 3 2 
+0.0104692 0.162225 0.0141351 3 2 
+0.0104565 0.162273 0.0141152 3 2 
+0.0104439 0.162322 0.0140953 3 2 
+0.0104313 0.162372 0.0140754 3 2 
+0.0104187 0.16242 0.0140556 3 2 
+0.0104061 0.162469 0.0140358 3 2 
+0.0103935 0.162519 0.0140148 3 2 
+0.010381 0.162567 0.0139947 3 2 
+0.0103685 0.162618 0.0139746 3 2 
+0.010356 0.162666 0.0139565 3 2 
+0.0103435 0.162716 0.0139365 3 2 
+0.0103311 0.162766 0.0139164 3 2 
+0.0103186 0.162814 0.0138951 3 2 
+0.0103062 0.162864 0.0138753 3 2 
+0.0102939 0.162914 0.0138554 3 2 
+0.0102815 0.162963 0.013834 3 2 
+0.0102692 0.163013 0.0138145 3 2 
+0.0102568 0.163063 0.0137951 3 2 
+0.0102446 0.16311 0.0137754 3 2 
+0.0102323 0.16316 0.0137558 3 2 
+0.01022 0.163209 0.0137363 3 2 
+0.0102078 0.163257 0.0137177 3 2 
+0.0101956 0.163306 0.0136985 3 2 
+0.0101834 0.163355 0.0136793 3 2 
+0.0101712 0.163403 0.0136601 3 2 
+0.0101591 0.163452 0.0136407 3 2 
+0.0101469 0.1635 0.0136213 3 2 
+0.0101348 0.163549 0.013601 3 2 
+0.0101227 0.163597 0.0135819 3 2 
+0.0101107 0.163645 0.0135629 3 2 
+0.0100986 0.163693 0.0135432 3 2 
+0.0100866 0.163741 0.0135242 3 2 
+0.0100746 0.163789 0.0135052 3 2 
+0.0100626 0.163836 0.0134893 3 2 
+0.0100507 0.163884 0.0134705 3 2 
+0.0100387 0.163931 0.0134518 3 2 
+0.0100268 0.163977 0.0134348 3 2 
+0.0100149 0.164024 0.0134157 3 2 
+0.010003 0.16407 0.0133966 3 2 
+0.00999112 0.164115 0.0133779 3 2 
+0.00997927 0.164161 0.0133594 3 2 
+0.00996745 0.164209 0.0133407 3 2 
+0.00995564 0.164257 0.0133214 3 2 
+0.00994385 0.164306 0.013303 3 2 
+0.00993208 0.164354 0.0132846 3 2 
+0.00992033 0.164398 0.0132659 3 2 
+0.0099086 0.164446 0.0132471 3 2 
+0.00989688 0.164495 0.0132284 3 2 
+0.00988519 0.16454 0.0132107 3 2 
+0.00987352 0.164589 0.013192 3 2 
+0.00986186 0.164637 0.0131734 3 2 
+0.00985022 0.164682 0.0131544 3 2 
+0.00983861 0.16473 0.0131358 3 2 
+0.00982701 0.164778 0.0131173 3 2 
+0.00981543 0.164824 0.0130984 3 2 
+0.00980386 0.164872 0.01308 3 2 
+0.00979232 0.164919 0.0130616 3 2 
+0.00978079 0.164965 0.0130436 3 2 
+0.00976929 0.165012 0.0130252 3 2 
+0.0097578 0.165059 0.0130069 3 2 
+0.00974633 0.165105 0.0129893 3 2 
+0.00973487 0.165152 0.0129711 3 2 
+0.00972344 0.165199 0.0129529 3 2 
+0.00971202 0.165244 0.0129355 3 2 
+0.00970062 0.165291 0.0129173 3 2 
+0.00968924 0.165337 0.0128992 3 2 
+0.00967788 0.165383 0.0128809 3 2 
+0.00966653 0.165429 0.0128629 3 2 
+0.0096552 0.165475 0.0128449 3 2 
+0.00964389 0.165521 0.012827 3 2 
+0.0096326 0.165567 0.0128091 3 2 
+0.00962132 0.165612 0.0127912 3 2 
+0.00961006 0.165658 0.0127734 3 2 
+0.00959882 0.165703 0.0127556 3 2 
+0.0095876 0.165748 0.0127378 3 2 
+0.00957639 0.165794 0.0127202 3 2 
+0.0095652 0.165839 0.0127025 3 2 
+0.00955403 0.165884 0.0126848 3 2 
+0.00954287 0.165929 0.0126672 3 2 
+0.00953173 0.165974 0.0126496 3 2 
+0.00952061 0.166018 0.012632 3 2 
+0.0095095 0.166064 0.0126152 3 2 
+0.00949841 0.166108 0.0125976 3 2 
+0.00948734 0.166152 0.0125801 3 2 
+0.00947628 0.166197 0.0125627 3 2 
+0.00946524 0.166241 0.0125452 3 2 
+0.00945422 0.166285 0.0125278 3 2 
+0.00944321 0.16633 0.0125105 3 2 
+0.00943222 0.166373 0.0124932 3 2 
+0.00942125 0.166416 0.0124758 3 2 
+0.00941029 0.166462 0.0124584 3 2 
+0.00939935 0.166505 0.0124411 3 2 
+0.00938842 0.166548 0.0124239 3 2 
+0.00937751 0.166593 0.012407 3 2 
+0.00936662 0.166635 0.0123898 3 2 
+0.00935574 0.166678 0.0123727 3 2 
+0.00934488 0.166723 0.0123559 3 2 
+0.00933403 0.166765 0.0123388 3 2 
+0.0093232 0.166807 0.0123217 3 2 
+0.00931239 0.166852 0.0123061 3 2 
+0.00930159 0.166895 0.0122891 3 2 
+0.0092908 0.16694 0.012272 3 2 
+0.00928003 0.166982 0.0122552 3 2 
+0.00926928 0.167027 0.0122382 3 2 
+0.00925854 0.167072 0.0122213 3 2 
+0.00924782 0.167114 0.0122053 3 2 
+0.00923711 0.167159 0.0121883 3 2 
+0.00922642 0.167203 0.0121714 3 2 
+0.00921574 0.167245 0.0121555 3 2 
+0.00920508 0.16729 0.0121386 3 2 
+0.00919443 0.167334 0.0121218 3 2 
+0.0091838 0.167376 0.012106 3 2 
+0.00917318 0.16742 0.0120892 3 2 
+0.00916258 0.167463 0.0120725 3 2 
+0.00915199 0.167505 0.0120572 3 2 
+0.00914142 0.167548 0.0120405 3 2 
+0.00913086 0.167591 0.0120237 3 2 
+0.00912032 0.167633 0.0120076 3 2 
+0.00910979 0.167676 0.011991 3 2 
+0.00909927 0.167719 0.0119743 3 2 
+0.00908877 0.167761 0.0119591 3 2 
+0.00907829 0.167803 0.0119424 3 2 
+0.00906782 0.167846 0.0119258 3 2 
+0.00905736 0.167887 0.011909 3 2 
+0.00904691 0.16793 0.0118929 3 2 
+0.00903648 0.167972 0.0118768 3 2 
+0.00902607 0.168013 0.0118607 3 2 
+0.00901567 0.168055 0.0118443 3 2 
+0.00900528 0.168096 0.0118278 3 2 
+0.00899491 0.168138 0.011812 3 2 
+0.00898455 0.168179 0.011796 3 2 
+0.0089742 0.16822 0.0117801 3 2 
+0.00896387 0.168261 0.0117625 3 2 
+0.00895355 0.168302 0.0117465 3 2 
+0.00894325 0.168343 0.0117307 3 2 
+0.00893296 0.168384 0.0117131 3 2 
+0.00892268 0.168424 0.0116972 3 2 
+0.00891242 0.168465 0.0116814 3 2 
+0.00890217 0.168506 0.0116649 3 2 
+0.00889193 0.168546 0.0116491 3 2 
+0.00888171 0.168586 0.0116333 3 2 
+0.0088715 0.168627 0.0116163 3 2 
+0.0088613 0.168666 0.0116006 3 2 
+0.00885112 0.168706 0.0115848 3 2 
+0.00884095 0.168746 0.0115697 3 2 
+0.00883079 0.168785 0.0115541 3 2 
+0.00882064 0.168824 0.0115384 3 2 
+0.00881051 0.168864 0.0115233 3 2 
+0.00880039 0.168902 0.0115078 3 2 
+0.00879029 0.168943 0.0114922 3 2 
+0.00878019 0.168983 0.0114774 3 2 
+0.00877011 0.169024 0.0114619 3 2 
+0.00876005 0.169065 0.0114464 3 2 
+0.00874999 0.169105 0.0114293 3 2 
+0.00873995 0.169145 0.0114138 3 2 
+0.00872992 0.169185 0.0113984 3 2 
+0.0087199 0.169225 0.0113816 3 2 
+0.0087099 0.169264 0.0113662 3 2 
+0.00869991 0.169304 0.0113509 3 2 
+0.00868993 0.169343 0.0113345 3 2 
+0.00867996 0.169382 0.0113192 3 2 
+0.00867001 0.16942 0.0113039 3 2 
+0.00866006 0.169459 0.0112895 3 2 
+0.00865013 0.169497 0.0112743 3 2 
+0.00864022 0.169535 0.0112591 3 2 
+0.00863031 0.169573 0.0112421 3 2 
+0.00862042 0.16961 0.0112269 3 2 
+0.00861053 0.169648 0.0112117 3 2 
+0.00860066 0.169685 0.0111957 3 2 
+0.00859081 0.169722 0.0111806 3 2 
+0.00858096 0.169758 0.0111654 3 2 
+0.00857113 0.169794 0.0111517 3 2 
+0.0085613 0.169832 0.0111367 3 2 
+0.00855149 0.169871 0.0111216 3 2 
+0.00854169 0.169912 0.0111057 3 2 
+0.00853191 0.16995 0.0110907 3 2 
+0.00852213 0.169989 0.0110757 3 2 
+0.00851237 0.170028 0.0110587 3 2 
+0.00850261 0.170065 0.0110437 3 2 
+0.00849287 0.170103 0.0110287 3 2 
+0.00848314 0.17014 0.0110135 3 2 
+0.00847342 0.170176 0.0109986 3 2 
+0.00846372 0.170213 0.0109837 3 2 
+0.00845402 0.170251 0.0109718 3 2 
+0.00844433 0.170287 0.0109566 3 2 
+0.00843466 0.170324 0.0109414 3 2 
+0.008425 0.17036 0.0109268 3 2 
+0.00841535 0.170397 0.010912 3 2 
+0.00840571 0.170433 0.0108971 3 2 
+0.00839608 0.170469 0.0108814 3 2 
+0.00838646 0.170505 0.0108668 3 2 
+0.00837685 0.170541 0.0108521 3 2 
+0.00836726 0.170576 0.0108376 3 2 
+0.00835767 0.170611 0.010823 3 2 
+0.0083481 0.170646 0.010808 3 2 
+0.00833853 0.170681 0.0107935 3 2 
+0.00832898 0.170715 0.0107786 3 2 
+0.00831944 0.170749 0.0107636 3 2 
+0.0083099 0.170783 0.010749 3 2 
+0.00830038 0.170819 0.0107341 3 2 
+0.00829087 0.170856 0.0107193 3 2 
+0.00828137 0.170896 0.0107049 3 2 
+0.00827188 0.170931 0.01069 3 2 
+0.0082624 0.170966 0.0106752 3 2 
+0.00825293 0.171 0.0106582 3 2 
+0.00824348 0.171035 0.0106437 3 2 
+0.00823403 0.17107 0.0106293 3 2 
+0.00822459 0.171096 0.0106139 3 2 
+0.00821516 0.171132 0.0105995 3 2 
+0.00820574 0.171168 0.0105851 3 2 
+0.00819634 0.171204 0.0105713 3 2 
+0.00818694 0.171237 0.0105569 3 2 
+0.00817755 0.17127 0.0105426 3 2 
+0.00816817 0.171303 0.01053 3 2 
+0.00815881 0.171335 0.0105158 3 2 
+0.00814945 0.171368 0.0105016 3 2 
+0.0081401 0.171411 0.0104853 3 2 
+0.00813076 0.171444 0.0104709 3 2 
+0.00812144 0.171477 0.0104564 3 2 
+0.00811212 0.171503 0.0104416 3 2 
+0.00810281 0.171534 0.0104272 3 2 
+0.00809351 0.171568 0.0104129 3 2 
+0.00808422 0.171609 0.0103984 3 2 
+0.00807494 0.171642 0.0103842 3 2 
+0.00806567 0.171675 0.0103701 3 2 
+0.00805641 0.171707 0.0103551 3 2 
+0.00804716 0.17174 0.0103409 3 2 
+0.00803792 0.171773 0.0103268 3 2 
+0.00802869 0.171803 0.0103154 3 2 
+0.00801947 0.171836 0.0103011 3 2 
+0.00801025 0.171869 0.0102868 3 2 
+0.00800105 0.171893 0.0102705 3 2 
+0.00799186 0.171926 0.0102564 3 2 
+0.00798267 0.171959 0.0102423 3 2 
+0.00797349 0.171996 0.0102285 3 2 
+0.00796433 0.172028 0.0102145 3 2 
+0.00795517 0.17206 0.0102005 3 2 
+0.00794602 0.172084 0.0101868 3 2 
+0.00793688 0.172117 0.0101728 3 2 
+0.00792775 0.172149 0.0101587 3 2 
+0.00791863 0.172184 0.0101455 3 2 
+0.00790951 0.172215 0.0101314 3 2 
+0.00790041 0.172246 0.0101174 3 2 
+0.00789131 0.172275 0.0101036 3 2 
+0.00788223 0.172305 0.0100896 3 2 
+0.00787315 0.172335 0.0100757 3 2 
+0.00786408 0.172363 0.0100625 3 2 
+0.00785502 0.172392 0.0100485 3 2 
+0.00784597 0.172421 0.0100346 3 2 
+0.00783693 0.172458 0.0100194 3 2 
+0.00782789 0.172488 0.0100056 3 2 
+0.00781886 0.172517 0.00999183 3 2 
+0.00780985 0.17254 0.00997938 3 2 
+0.00780084 0.172571 0.00996554 3 2 
+0.00779184 0.172602 0.00995171 3 2 
+0.00778285 0.172636 0.00993757 3 2 
+0.00777386 0.172665 0.0099238 3 2 
+0.00776489 0.172694 0.00991005 3 2 
+0.00775592 0.172716 0.00989711 3 2 
+0.00774696 0.172747 0.00988336 3 2 
+0.00773801 0.172777 0.00986962 3 2 
+0.00772907 0.172809 0.00985592 3 2 
+0.00772014 0.172837 0.00984223 3 2 
+0.00771121 0.172865 0.00982856 3 2 
+0.00770229 0.172886 0.00981493 3 2 
+0.00769338 0.172916 0.0098013 3 2 
+0.00768448 0.172945 0.00978769 3 2 
+0.00767559 0.172977 0.00977415 3 2 
+0.0076667 0.173004 0.00976057 3 2 
+0.00765782 0.173031 0.00974701 3 2 
+0.00764895 0.173055 0.00973344 3 2 
+0.00764009 0.173081 0.00971993 3 2 
+0.00763124 0.173108 0.00970643 3 2 
+0.00762239 0.173142 0.0096931 3 2 
+0.00761355 0.173168 0.00967963 3 2 
+0.00760472 0.173194 0.00966617 3 2 
+0.0075959 0.17322 0.00965285 3 2 
+0.00758708 0.173245 0.00963942 3 2 
+0.00757827 0.17327 0.00962601 3 2 
+0.00756947 0.173302 0.00961243 3 2 
+0.00756068 0.173328 0.00959911 3 2 
+0.00755189 0.173353 0.0095858 3 2 
+0.00754312 0.173377 0.00957248 3 2 
+0.00753435 0.173401 0.0095592 3 2 
+0.00752558 0.173427 0.00954594 3 2 
+0.00751683 0.173459 0.0095331 3 2 
+0.00750808 0.173483 0.00951992 3 2 
+0.00749934 0.173508 0.00950675 3 2 
+0.00749061 0.173529 0.00949591 3 2 
+0.00748188 0.173556 0.00948271 3 2 
+0.00747316 0.173582 0.00946936 3 2 
+0.00746445 0.173608 0.00945338 3 2 
+0.00745574 0.173631 0.00944022 3 2 
+0.00744705 0.173654 0.00942708 3 2 
+0.00743836 0.173679 0.00941439 3 2 
+0.00742967 0.173703 0.00940121 3 2 
+0.007421 0.173729 0.00938804 3 2 
+0.00741233 0.173754 0.00937564 3 2 
+0.00740366 0.173776 0.00936265 3 2 
+0.00739501 0.173799 0.00934967 3 2 
+0.00738636 0.173824 0.00933663 3 2 
+0.00737772 0.173849 0.00932349 3 2 
+0.00736908 0.173874 0.00931036 3 2 
+0.00736046 0.173894 0.00929632 3 2 
+0.00735184 0.173918 0.00928331 3 2 
+0.00734322 0.173943 0.00927031 3 2 
+0.00733461 0.173964 0.00925801 3 2 
+0.00732601 0.173988 0.00924497 3 2 
+0.00731742 0.174013 0.00923195 3 2 
+0.00730883 0.174033 0.00921957 3 2 
+0.00730025 0.174057 0.00920655 3 2 
+0.00729168 0.174081 0.00919355 3 2 
+0.00728311 0.174101 0.0091799 3 2 
+0.00727455 0.174124 0.00916705 3 2 
+0.00726599 0.174148 0.00915422 3 2 
+0.00725744 0.174168 0.00914282 3 2 
+0.0072489 0.174191 0.00912986 3 2 
+0.00724037 0.174214 0.00911691 3 2 
+0.00723184 0.174231 0.00910279 3 2 
+0.00722331 0.174254 0.00909002 3 2 
+0.0072148 0.174277 0.00907726 3 2 
+0.00720629 0.174297 0.00906504 3 2 
+0.00719778 0.174319 0.00905219 3 2 
+0.00718928 0.174341 0.00903935 3 2 
+0.00718079 0.174359 0.00902612 3 2 
+0.00717231 0.174381 0.00901335 3 2 
+0.00716383 0.174402 0.00900059 3 2 
+0.00715536 0.174421 0.00898806 3 2 
+0.00714689 0.174442 0.00897531 3 2 
+0.00713843 0.174463 0.00896258 3 2 
+0.00712997 0.174481 0.00894994 3 2 
+0.00712152 0.174502 0.00893724 3 2 
+0.00711308 0.174523 0.00892455 3 2 
+0.00710464 0.174541 0.00891209 3 2 
+0.00709621 0.174561 0.00889941 3 2 
+0.00708779 0.174581 0.00888675 3 2 
+0.00707937 0.174599 0.00887438 3 2 
+0.00707095 0.174618 0.00886173 3 2 
+0.00706254 0.174638 0.00884909 3 2 
+0.00705414 0.174656 0.00883679 3 2 
+0.00704575 0.174675 0.00882416 3 2 
+0.00703736 0.174694 0.00881155 3 2 
+0.00702897 0.17471 0.00879935 3 2 
+0.00702059 0.174729 0.00878675 3 2 
+0.00701222 0.174747 0.00877416 3 2 
+0.00700385 0.174764 0.00876181 3 2 
+0.00699549 0.174782 0.00874924 3 2 
+0.00698713 0.1748 0.00873669 3 2 
+0.00697878 0.174816 0.00872474 3 2 
+0.00697043 0.174834 0.00871218 3 2 
+0.00696209 0.174852 0.00869965 3 2 
+0.00695376 0.174868 0.00868754 3 2 
+0.00694543 0.174885 0.00867501 3 2 
+0.0069371 0.174902 0.00866251 3 2 
+0.00692878 0.174917 0.00865029 3 2 
+0.00692047 0.174934 0.0086378 3 2 
+0.00691216 0.17495 0.00862533 3 2 
+0.00690386 0.174966 0.00861263 3 2 
+0.00689556 0.174982 0.0086002 3 2 
+0.00688727 0.174998 0.00858778 3 2 
+0.00687898 0.175013 0.00857585 3 2 
+0.0068707 0.175028 0.00856344 3 2 
+0.00686242 0.175044 0.00855104 3 2 
+0.00685415 0.175059 0.00853815 3 2 
+0.00684588 0.175073 0.00852581 3 2 
+0.00683762 0.175088 0.00851349 3 2 
+0.00682937 0.175103 0.0085011 3 2 
+0.00682112 0.175117 0.00848887 3 2 
+0.00681287 0.175131 0.00847665 3 2 
+0.00680463 0.175145 0.00846424 3 2 
+0.00679639 0.175158 0.00845202 3 2 
+0.00678816 0.175172 0.00843981 3 2 
+0.00677993 0.175186 0.0084276 3 2 
+0.00677171 0.175199 0.00841541 3 2 
+0.00676349 0.175211 0.00840324 3 2 
+0.00675528 0.175225 0.00839114 3 2 
+0.00674708 0.175237 0.008379 3 2 
+0.00673887 0.175249 0.00836687 3 2 
+0.00673068 0.175262 0.00835508 3 2 
+0.00672248 0.175274 0.008343 3 2 
+0.00671429 0.175285 0.00833093 3 2 
+0.00670611 0.175298 0.00831977 3 2 
+0.00669793 0.175308 0.00830776 3 2 
+0.00668976 0.175319 0.00829577 3 2 
+0.00668159 0.175331 0.008283 3 2 
+0.00667342 0.175342 0.00827101 3 2 
+0.00666526 0.175355 0.00825903 3 2 
+0.00665711 0.175366 0.00824757 3 2 
+0.00664896 0.175378 0.00823563 3 2 
+0.00664081 0.17539 0.0082237 3 2 
+0.00663267 0.175401 0.00821053 3 2 
+0.00662453 0.175412 0.00819859 3 2 
+0.0066164 0.175424 0.00818666 3 2 
+0.00660827 0.175434 0.00817385 3 2 
+0.00660014 0.175445 0.0081619 3 2 
+0.00659202 0.175455 0.00814997 3 2 
+0.00658391 0.17546 0.00813761 3 2 
+0.0065758 0.175468 0.00812566 3 2 
+0.00656769 0.175476 0.00811372 3 2 
+0.00655959 0.175492 0.00810188 3 2 
+0.00655149 0.1755 0.00808998 3 2 
+0.00654339 0.175508 0.00807809 3 2 
+0.0065353 0.175518 0.00806634 3 2 
+0.00652722 0.175526 0.00805439 3 2 
+0.00651913 0.175533 0.00804245 3 2 
+0.00651106 0.175543 0.00803054 3 2 
+0.00650298 0.175551 0.00801863 3 2 
+0.00649491 0.175558 0.00800672 3 2 
+0.00648685 0.175567 0.00799613 3 2 
+0.00647879 0.175574 0.00798418 3 2 
+0.00647073 0.17558 0.00797225 3 2 
+0.00646268 0.175589 0.0079609 3 2 
+0.00645463 0.175595 0.00794897 3 2 
+0.00644658 0.175601 0.00793705 3 2 
+0.00643854 0.175609 0.0079246 3 2 
+0.0064305 0.175614 0.00791288 3 2 
+0.00642247 0.17562 0.00790117 3 2 
+0.00641444 0.175627 0.00788906 3 2 
+0.00640641 0.175632 0.00787736 3 2 
+0.00639839 0.175636 0.00786567 3 2 
+0.00639037 0.175644 0.00785519 3 2 
+0.00638236 0.175648 0.00784333 3 2 
+0.00637435 0.175652 0.00783148 3 2 
+0.00636634 0.175659 0.0078193 3 2 
+0.00635834 0.175663 0.00780748 3 2 
+0.00635034 0.175666 0.00779568 3 2 
+0.00634234 0.175671 0.00778351 3 2 
+0.00633435 0.175674 0.00777189 3 2 
+0.00632636 0.175676 0.00776028 3 2 
+0.00631838 0.175682 0.00774888 3 2 
+0.0063104 0.175687 0.0077373 3 2 
+0.00630242 0.175692 0.00772573 3 2 
+0.00629445 0.175692 0.00771394 3 2 
+0.00628648 0.175697 0.00770238 3 2 
+0.00627851 0.175702 0.00769083 3 2 
+0.00627055 0.175703 0.00767859 3 2 
+0.00626259 0.175707 0.00766691 3 2 
+0.00625463 0.175711 0.00765524 3 2 
+0.00624668 0.175711 0.00764393 3 2 
+0.00623873 0.175715 0.00763227 3 2 
+0.00623079 0.175718 0.00762062 3 2 
+0.00622284 0.175719 0.00760837 3 2 
+0.0062149 0.175722 0.00759679 3 2 
+0.00620697 0.175724 0.00758521 3 2 
+0.00619904 0.175724 0.00757363 3 2 
+0.00619111 0.175726 0.00756209 3 2 
+0.00618318 0.175727 0.00755055 3 2 
+0.00617526 0.175728 0.00753908 3 2 
+0.00616734 0.175729 0.00752754 3 2 
+0.00615943 0.17573 0.00751602 3 2 
+0.00615152 0.17573 0.00750582 3 2 
+0.00614361 0.17573 0.00749424 3 2 
+0.0061357 0.175729 0.00748267 3 2 
+0.0061278 0.175729 0.00747191 3 2 
+0.0061199 0.175728 0.00746034 3 2 
+0.006112 0.175726 0.00744877 3 2 
+0.00610411 0.175726 0.00743788 3 2 
+0.00609622 0.175724 0.00742632 3 2 
+0.00608833 0.175722 0.00741477 3 2 
+0.00608045 0.175721 0.00740247 3 2 
+0.00607257 0.175718 0.00739113 3 2 
+0.00606469 0.175715 0.0073798 3 2 
+0.00605682 0.175713 0.00736781 3 2 
+0.00604895 0.17571 0.00735635 3 2 
+0.00604108 0.175706 0.0073449 3 2 
+0.00603322 0.175703 0.00733395 3 2 
+0.00602535 0.175698 0.0073225 3 2 
+0.00601749 0.175693 0.00731107 3 2 
+0.00600964 0.175689 0.00729973 3 2 
+0.00600179 0.175685 0.00728831 3 2 
+0.00599394 0.175683 0.0072769 3 2 
+0.00598609 0.17568 0.00726567 3 2 
+0.00597824 0.175678 0.00725427 3 2 
+0.0059704 0.175675 0.00724289 3 2 
+0.00596256 0.175671 0.00723163 3 2 
+0.00595473 0.175667 0.00722026 3 2 
+0.0059469 0.175663 0.0072089 3 2 
+0.00593907 0.17566 0.00719785 3 2 
+0.00593124 0.175654 0.00718663 3 2 
+0.00592342 0.175649 0.00717543 3 2 
+0.0059156 0.175643 0.00716427 3 2 
+0.00590778 0.175637 0.00715293 3 2 
+0.00589996 0.175631 0.0071416 3 2 
+0.00589215 0.175624 0.00713001 3 2 
+0.00588434 0.175618 0.00711872 3 2 
+0.00587653 0.17561 0.00710743 3 2 
+0.00586873 0.175602 0.00709734 3 2 
+0.00586092 0.175594 0.00708621 3 2 
+0.00585312 0.175585 0.00707509 3 2 
+0.00584533 0.175571 0.00706291 3 2 
+0.00583753 0.175564 0.00705178 3 2 
+0.00582974 0.175558 0.00704065 3 2 
+0.00582196 0.175558 0.00702875 3 2 
+0.00581417 0.175549 0.00701762 3 2 
+0.00580639 0.175541 0.00700649 3 2 
+0.00579861 0.175521 0.00699506 3 2 
+0.00579083 0.175509 0.00698389 3 2 
+0.00578305 0.175502 0.00697274 3 2 
+0.00577528 0.175503 0.00696351 3 2 
+0.00576751 0.175494 0.00695228 3 2 
+0.00575975 0.175485 0.00694106 3 2 
+0.00575198 0.175471 0.00692822 3 2 
+0.00574422 0.175462 0.00691712 3 2 
+0.00573646 0.175452 0.00690603 3 2 
+0.0057287 0.175434 0.00689558 3 2 
+0.00572095 0.175422 0.00688455 3 2 
+0.0057132 0.175413 0.00687352 3 2 
+0.00570545 0.175407 0.00686172 3 2 
+0.0056977 0.175397 0.00685067 3 2 
+0.00568995 0.175386 0.00683963 3 2 
+0.00568221 0.175374 0.00682848 3 2 
+0.00567447 0.175362 0.00681744 3 2 
+0.00566673 0.17535 0.0068064 3 2 
+0.005659 0.175336 0.00679537 3 2 
+0.00565127 0.175324 0.00678435 3 2 
+0.00564354 0.175311 0.00677334 3 2 
+0.00563581 0.175295 0.00676349 3 2 
+0.00562808 0.175282 0.00675255 3 2 
+0.00562036 0.175269 0.00674163 3 2 
+0.00561264 0.175255 0.00672967 3 2 
+0.00560492 0.175241 0.00671872 3 2 
+0.0055972 0.175228 0.00670779 3 2 
+0.00558949 0.175211 0.00669738 3 2 
+0.00558178 0.175197 0.00668648 3 2 
+0.00557407 0.175183 0.00667559 3 2 
+0.00556637 0.175168 0.00666412 3 2 
+0.00555866 0.175153 0.00665312 3 2 
+0.00555096 0.175137 0.00664214 3 2 
+0.00554326 0.175121 0.00663114 3 2 
+0.00553556 0.175105 0.00662018 3 2 
+0.00552787 0.175088 0.00660922 3 2 
+0.00552018 0.17507 0.00659845 3 2 
+0.00551249 0.175052 0.00658759 3 2 
+0.0055048 0.175034 0.00657675 3 2 
+0.00549711 0.175015 0.00656552 3 2 
+0.00548943 0.174999 0.00655461 3 2 
+0.00548175 0.174983 0.0065437 3 2 
+0.00547407 0.174967 0.00653286 3 2 
+0.0054664 0.174948 0.00652197 3 2 
+0.00545872 0.174928 0.0065111 3 2 
+0.00545105 0.174911 0.00650221 3 2 
+0.00544338 0.174891 0.00649145 3 2 
+0.00543571 0.174871 0.00648065 3 2 
+0.00542805 0.174852 0.00646762 3 2 
+0.00542039 0.174831 0.0064568 3 2 
+0.00541273 0.174809 0.00644599 3 2 
+0.00540507 0.174794 0.00643532 3 2 
+0.00539741 0.174772 0.00642455 3 2 
+0.00538976 0.17475 0.00641378 3 2 
+0.00538211 0.17473 0.00640287 3 2 
+0.00537446 0.174708 0.0063921 3 2 
+0.00536681 0.174685 0.00638135 3 2 
+0.00535916 0.174664 0.00637109 3 2 
+0.00535152 0.174644 0.00636037 3 2 
+0.00534388 0.174624 0.00634967 3 2 
+0.00533624 0.174605 0.00633848 3 2 
+0.00532861 0.174584 0.00632771 3 2 
+0.00532097 0.174562 0.00631695 3 2 
+0.00531334 0.174539 0.00630706 3 2 
+0.00530571 0.174516 0.00629628 3 2 
+0.00529808 0.174492 0.0062855 3 2 
+0.00529046 0.174462 0.00627393 3 2 
+0.00528284 0.174437 0.00626322 3 2 
+0.00527522 0.174411 0.00625252 3 2 
+0.0052676 0.174387 0.00624256 3 2 
+0.00525998 0.174365 0.00623182 3 2 
+0.00525237 0.174342 0.0062211 3 2 
+0.00524475 0.174318 0.00621163 3 2 
+0.00523714 0.174295 0.00620099 3 2 
+0.00522954 0.174271 0.00619025 3 2 
+0.00522193 0.174248 0.00617827 3 2 
+0.00521433 0.174223 0.00616767 3 2 
+0.00520673 0.174197 0.00615707 3 2 
+0.00519913 0.174168 0.00614596 3 2 
+0.00519153 0.174141 0.00613535 3 2 
+0.00518393 0.174112 0.00612474 3 2 
+0.00517634 0.174085 0.00611518 3 2 
+0.00516875 0.174056 0.00610464 3 2 
+0.00516116 0.174027 0.00609411 3 2 
+0.00515358 0.174009 0.00608235 3 2 
+0.00514599 0.173981 0.00607177 3 2 
+0.00513841 0.173953 0.0060612 3 2 
+0.00513083 0.173925 0.00605064 3 2 
+0.00512326 0.173896 0.00604008 3 2 
+0.00511568 0.173868 0.00602954 3 2 
+0.00510811 0.173838 0.00601899 3 2 
+0.00510054 0.173809 0.00600846 3 2 
+0.00509298 0.173778 0.00599794 3 2 
+0.00508541 0.17375 0.00598763 3 2 
+0.00507785 0.173719 0.00597708 3 2 
+0.00507028 0.173688 0.00596655 3 2 
+0.00506272 0.173659 0.00595589 3 2 
+0.00505516 0.173629 0.0059454 3 2 
+0.00504761 0.173598 0.00593492 3 2 
+0.00504006 0.17356 0.00592606 3 2 
+0.0050325 0.173531 0.00591566 3 2 
+0.00502495 0.173501 0.00590526 3 2 
+0.00501741 0.17347 0.00589347 3 2 
+0.00500986 0.173439 0.00588297 3 2 
+0.00500232 0.173407 0.00587249 3 2 
+0.00499479 0.173375 0.00586171 3 2 
+0.00498725 0.173342 0.00585129 3 2 
+0.00497971 0.173308 0.00584088 3 2 
+0.00497218 0.173273 0.00583088 3 2 
+0.00496465 0.173238 0.00582043 3 2 
+0.00495712 0.173202 0.00580998 3 2 
+0.0049496 0.173167 0.00580007 3 2 
+0.00494208 0.173135 0.00578962 3 2 
+0.00493456 0.173102 0.00577918 3 2 
+0.00492704 0.17307 0.00576909 3 2 
+0.00491952 0.173035 0.00575877 3 2 
+0.00491201 0.172999 0.00574846 3 2 
+0.0049045 0.172965 0.00573742 3 2 
+0.00489699 0.172929 0.00572711 3 2 
+0.00488948 0.172892 0.00571681 3 2 
+0.00488198 0.172853 0.00570596 3 2 
+0.00487448 0.172814 0.00569564 3 2 
+0.00486698 0.172776 0.00568534 3 2 
+0.00485948 0.17274 0.00567497 3 2 
+0.00485199 0.172705 0.00566468 3 2 
+0.00484449 0.172669 0.00565439 3 2 
+0.004837 0.172635 0.00564484 3 2 
+0.00482952 0.172597 0.0056345 3 2 
+0.00482203 0.172558 0.00562417 3 2 
+0.00481455 0.172521 0.00561359 3 2 
+0.00480707 0.172481 0.00560336 3 2 
+0.00479959 0.172442 0.00559314 3 2 
+0.00479212 0.172404 0.00558252 3 2 
+0.00478464 0.172363 0.00557229 3 2 
+0.00477717 0.172323 0.00556208 3 2 
+0.0047697 0.172283 0.00555218 3 2 
+0.00476224 0.172241 0.00554199 3 2 
+0.00475477 0.172199 0.00553181 3 2 
+0.00474732 0.172157 0.0055212 3 2 
+0.00473986 0.172114 0.00551102 3 2 
+0.0047324 0.17207 0.00550085 3 2 
+0.00472495 0.172031 0.00549082 3 2 
+0.0047175 0.171992 0.00548061 3 2 
+0.00471005 0.171952 0.00547041 3 2 
+0.00470261 0.171912 0.00546008 3 2 
+0.00469517 0.171871 0.00544991 3 2 
+0.00468773 0.17183 0.00543975 3 2 
+0.00468029 0.171788 0.00542965 3 2 
+0.00467285 0.171745 0.0054195 3 2 
+0.00466542 0.171702 0.00540936 3 2 
+0.00465799 0.171659 0.0053999 3 2 
+0.00465057 0.171614 0.00538983 3 2 
+0.00464314 0.17157 0.00537977 3 2 
+0.00463573 0.171524 0.00536949 3 2 
+0.00462831 0.171478 0.00535937 3 2 
+0.00462089 0.171432 0.00534925 3 2 
+0.00461348 0.171384 0.0053389 3 2 
+0.00460607 0.171336 0.00532886 3 2 
+0.00459867 0.171289 0.00531883 3 2 
+0.00459127 0.171247 0.00530851 3 2 
+0.00458386 0.171203 0.00529848 3 2 
+0.00457647 0.171159 0.00528845 3 2 
+0.00456907 0.171114 0.00527844 3 2 
+0.00456167 0.171069 0.00526844 3 2 
+0.00455429 0.171023 0.00525844 3 2 
+0.0045469 0.170977 0.00524843 3 2 
+0.00453952 0.17093 0.00523843 3 2 
+0.00453213 0.170883 0.00522843 3 2 
+0.00452476 0.170835 0.00521858 3 2 
+0.00451738 0.170787 0.0052086 3 2 
+0.00451001 0.170738 0.00519862 3 2 
+0.00450264 0.170688 0.00519015 3 2 
+0.00449527 0.170638 0.00518022 3 2 
+0.00448791 0.170587 0.00517022 3 2 
+0.00448055 0.170536 0.00515967 3 2 
+0.00447319 0.170484 0.0051498 3 2 
+0.00446584 0.170433 0.00513993 3 2 
+0.00445849 0.170384 0.00512914 3 2 
+0.00445114 0.170336 0.00511926 3 2 
+0.00444379 0.170288 0.0051094 3 2 
+0.00443645 0.170237 0.00510009 3 2 
+0.00442911 0.170188 0.00509017 3 2 
+0.00442178 0.170138 0.00508027 3 2 
+0.00441445 0.170088 0.00507105 3 2 
+0.00440712 0.170037 0.00506114 3 2 
+0.00439979 0.169985 0.00505125 3 2 
+0.00439247 0.169933 0.0050409 3 2 
+0.00438515 0.169881 0.00503112 3 2 
+0.00437784 0.169828 0.00502134 3 2 
+0.00437053 0.169773 0.00501138 3 2 
+0.00436322 0.169719 0.00500162 3 2 
+0.00435591 0.169664 0.00499186 3 2 
+0.00434861 0.169609 0.00498271 3 2 
+0.00434131 0.169553 0.00497299 3 2 
+0.00433402 0.169497 0.00496328 3 2 
+0.00432673 0.169443 0.00495235 3 2 
+0.00431944 0.169391 0.00494263 3 2 
+0.00431215 0.169338 0.00493291 3 2 
+0.00430487 0.169285 0.00492394 3 2 
+0.00429759 0.169232 0.00491426 3 2 
+0.00429032 0.169177 0.0049046 3 2 
+0.00428305 0.169122 0.00489504 3 2 
+0.00427578 0.169067 0.0048854 3 2 
+0.00426852 0.169011 0.00487568 3 2 
+0.00426126 0.168955 0.00486584 3 2 
+0.00425401 0.168898 0.00485622 3 2 
+0.00424675 0.16884 0.0048466 3 2 
+0.00423951 0.168782 0.0048359 3 2 
+0.00423226 0.168724 0.00482626 3 2 
+0.00422502 0.168664 0.00481663 3 2 
+0.00421779 0.168606 0.00480705 3 2 
+0.00421055 0.168545 0.00479743 3 2 
+0.00420332 0.168484 0.00478783 3 2 
+0.0041961 0.168425 0.00477877 3 2 
+0.00418888 0.168369 0.00476915 3 2 
+0.00418166 0.168312 0.00475955 3 2 
+0.00417445 0.168253 0.00475026 3 2 
+0.00416724 0.168196 0.00474067 3 2 
+0.00416003 0.168138 0.00473109 3 2 
+0.00415283 0.168078 0.00472127 3 2 
+0.00414563 0.16802 0.00471171 3 2 
+0.00413844 0.167961 0.00470217 3 2 
+0.00413125 0.167899 0.00469251 3 2 
+0.00412407 0.16784 0.00468303 3 2 
+0.00411689 0.16778 0.00467356 3 2 
+0.00410971 0.167719 0.00466395 3 2 
+0.00410254 0.167658 0.00465447 3 2 
+0.00409537 0.167596 0.00464501 3 2 
+0.00408821 0.167534 0.00463612 3 2 
+0.00408105 0.167472 0.00462672 3 2 
+0.00407389 0.167409 0.00461732 3 2 
+0.00406674 0.167346 0.00460748 3 2 
+0.00405959 0.167282 0.0045981 3 2 
+0.00405245 0.167217 0.00458872 3 2 
+0.00404531 0.167153 0.00457921 3 2 
+0.00403818 0.167087 0.00456985 3 2 
+0.00403105 0.167021 0.0045605 3 2 
+0.00402393 0.166958 0.004551 3 2 
+0.0040168 0.166891 0.00454164 3 2 
+0.00400969 0.166823 0.0045323 3 2 
+0.00400258 0.166758 0.00452305 3 2 
+0.00399547 0.166696 0.00451374 3 2 
+0.00398837 0.166635 0.00450445 3 2 
+0.00398127 0.166568 0.00449513 3 2 
+0.00397418 0.166505 0.00448583 3 2 
+0.00396709 0.166442 0.00447655 3 2 
+0.00396001 0.16638 0.00446732 3 2 
+0.00395293 0.166316 0.00445805 3 2 
+0.00394585 0.166251 0.00444879 3 2 
+0.00393878 0.166182 0.00443993 3 2 
+0.00393171 0.166117 0.00443067 3 2 
+0.00392465 0.166052 0.00442143 3 2 
+0.0039176 0.165986 0.00441194 3 2 
+0.00391055 0.165918 0.00440273 3 2 
+0.00390351 0.16585 0.00439353 3 2 
+0.00389646 0.165784 0.00438434 3 2 
+0.00388943 0.165716 0.00437518 3 2 
+0.0038824 0.165647 0.00436605 3 2 
+0.00387538 0.16558 0.00435685 3 2 
+0.00386835 0.16551 0.00434773 3 2 
+0.00386134 0.165441 0.00433862 3 2 
+0.00385433 0.16537 0.00432977 3 2 
+0.00384732 0.165299 0.00432069 3 2 
+0.00384032 0.165227 0.00431163 3 2 
+0.00383333 0.165157 0.00430237 3 2 
+0.00382634 0.165085 0.00429329 3 2 
+0.00381936 0.165013 0.00428422 3 2 
+0.00381238 0.164945 0.00427535 3 2 
+0.0038054 0.164878 0.00426629 3 2 
+0.00379843 0.16481 0.00425725 3 2 
+0.00379147 0.164738 0.0042487 3 2 
+0.00378452 0.164669 0.00423967 3 2 
+0.00377756 0.1646 0.00423065 3 2 
+0.00377062 0.164529 0.00422116 3 2 
+0.00376367 0.164459 0.00421221 3 2 
+0.00375674 0.164389 0.00420327 3 2 
+0.00374981 0.164317 0.0041943 3 2 
+0.00374288 0.164246 0.00418536 3 2 
+0.00373596 0.164174 0.00417643 3 2 
+0.00372905 0.164102 0.00416774 3 2 
+0.00372215 0.164029 0.00415886 3 2 
+0.00371524 0.163955 0.00414999 3 2 
+0.00370835 0.163882 0.00414075 3 2 
+0.00370145 0.163807 0.00413189 3 2 
+0.00369457 0.163732 0.00412304 3 2 
+0.00368769 0.163659 0.0041143 3 2 
+0.00368082 0.163584 0.00410548 3 2 
+0.00367395 0.163507 0.00409668 3 2 
+0.00366709 0.163433 0.00408839 3 2 
+0.00366023 0.163355 0.00407962 3 2 
+0.00365338 0.163278 0.00407087 3 2 
+0.00364654 0.163205 0.00406151 3 2 
+0.0036397 0.163127 0.00405276 3 2 
+0.00363287 0.163053 0.00404403 3 2 
+0.00362604 0.162982 0.00403536 3 2 
+0.00361922 0.16291 0.00402662 3 2 
+0.0036124 0.162836 0.0040179 3 2 
+0.0036056 0.162759 0.00400915 3 2 
+0.0035988 0.162686 0.00400048 3 2 
+0.003592 0.162611 0.00399181 3 2 
+0.00358521 0.162535 0.00398309 3 2 
+0.00357843 0.16246 0.00397445 3 2 
+0.00357165 0.162385 0.00396582 3 2 
+0.00356488 0.162309 0.00395735 3 2 
+0.00355811 0.162232 0.00394875 3 2 
+0.00355136 0.162155 0.00394016 3 2 
+0.00354461 0.162078 0.0039316 3 2 
+0.00353786 0.162 0.00392303 3 2 
+0.00353112 0.161922 0.00391449 3 2 
+0.00352439 0.161841 0.00390643 3 2 
+0.00351766 0.161761 0.00389792 3 2 
+0.00351094 0.16168 0.00388942 3 2 
+0.00350423 0.1616 0.00388034 3 2 
+0.00349752 0.161518 0.00387183 3 2 
+0.00349082 0.161436 0.00386332 3 2 
+0.00348413 0.161366 0.00385467 3 2 
+0.00347744 0.161284 0.0038462 3 2 
+0.00347076 0.161201 0.00383775 3 2 
+0.00346408 0.161121 0.00382939 3 2 
+0.00345742 0.161037 0.00382095 3 2 
+0.00345076 0.160959 0.00381253 3 2 
+0.0034441 0.160882 0.00380419 3 2 
+0.00343745 0.160806 0.00379581 3 2 
+0.00343081 0.160729 0.00378745 3 2 
+0.00342418 0.160651 0.00377955 3 2 
+0.00341755 0.160573 0.00377118 3 2 
+0.00341093 0.160495 0.00376281 3 2 
+0.00340432 0.160415 0.00375399 3 2 
+0.00339772 0.160335 0.00374569 3 2 
+0.00339112 0.160255 0.0037374 3 2 
+0.00338452 0.160174 0.00372942 3 2 
+0.00337794 0.160093 0.00372116 3 2 
+0.00337136 0.160012 0.00371292 3 2 
+0.00336479 0.15993 0.00370445 3 2 
+0.00335822 0.159849 0.0036962 3 2 
+0.00335167 0.159767 0.00368797 3 2 
+0.00334512 0.159684 0.00367971 3 2 
+0.00333858 0.1596 0.00367153 3 2 
+0.00333204 0.159516 0.00366336 3 2 
+0.00332551 0.159434 0.00365549 3 2 
+0.00331899 0.159349 0.00364735 3 2 
+0.00331248 0.159264 0.00363923 3 2 
+0.00330597 0.159176 0.00363114 3 2 
+0.00329948 0.159089 0.00362305 3 2 
+0.00329298 0.159002 0.00361497 3 2 
+0.0032865 0.158928 0.00360638 3 2 
+0.00328002 0.15884 0.0035983 3 2 
+0.00327355 0.158753 0.00359023 3 2 
+0.00326709 0.158665 0.00358253 3 2 
+0.00326064 0.158585 0.00357451 3 2 
+0.01 0.0729734 0.0729734 2 1 
+0.00999369 0.072972 0.072972 2 1 
+0.00998739 0.0729707 0.0729707 2 1 
+0.00997478 0.072968 0.072968 2 1 
+0.00994959 0.0729626 0.0729626 2 1 
+0.00991814 0.0729558 0.0729558 2 1 
+0.00988672 0.0729489 0.0729489 2 1 
+0.00985535 0.0729421 0.0729421 2 1 
+0.00982401 0.0729352 0.0729352 2 1 
+0.00979272 0.0729283 0.0729283 2 1 
+0.00976147 0.0729213 0.0729213 2 1 
+0.00973025 0.0729143 0.0729143 2 1 
+0.00969908 0.0729073 0.0729073 2 1 
+0.00966794 0.0729003 0.0729003 2 1 
+0.00963685 0.0728932 0.0728932 2 1 
+0.0096058 0.0728861 0.0728861 2 1 
+0.00957478 0.0728789 0.0728789 2 1 
+0.00954381 0.0728718 0.0728718 2 1 
+0.00951287 0.0728646 0.0728646 2 1 
+0.00948198 0.0728573 0.0728573 2 1 
+0.00945112 0.07285 0.07285 2 1 
+0.00942031 0.0728427 0.0728427 2 1 
+0.00938953 0.0728354 0.0728354 2 1 
+0.00935879 0.072828 0.072828 2 1 
+0.0093281 0.0728206 0.0728206 2 1 
+0.00929744 0.0728131 0.0728131 2 1 
+0.00926682 0.0728056 0.0728056 2 1 
+0.00923624 0.0727981 0.0727981 2 1 
+0.0092057 0.0727906 0.0727906 2 1 
+0.00917521 0.072783 0.072783 2 1 
+0.00914475 0.0727753 0.0727753 2 1 
+0.00911433 0.0727677 0.0727677 2 1 
+0.00908394 0.07276 0.07276 2 1 
+0.0090536 0.0727522 0.0727522 2 1 
+0.0090233 0.0727444 0.0727444 2 1 
+0.00899304 0.0727366 0.0727366 2 1 
+0.00896282 0.0727288 0.0727288 2 1 
+0.00893263 0.0727209 0.0727209 2 1 
+0.00890249 0.0727129 0.0727129 2 1 
+0.00887238 0.0727049 0.0727049 2 1 
+0.00884231 0.0726969 0.0726969 2 1 
+0.00881229 0.0726889 0.0726889 2 1 
+0.0087823 0.0726808 0.0726808 2 1 
+0.00875235 0.0726727 0.0726727 2 1 
+0.00872244 0.0726645 0.0726645 2 1 
+0.00869257 0.0726563 0.0726563 2 1 
+0.00866274 0.072648 0.072648 2 1 
+0.00863294 0.0726397 0.0726397 2 1 
+0.00860319 0.0726314 0.0726314 2 1 
+0.00857348 0.072623 0.072623 2 1 
+0.0085438 0.0726145 0.0726145 2 1 
+0.00851416 0.0726061 0.0726061 2 1 
+0.00848457 0.0725976 0.0725976 2 1 
+0.00845501 0.072589 0.072589 2 1 
+0.00842549 0.0725804 0.0725804 2 1 
+0.008396 0.0725717 0.0725717 2 1 
+0.00836656 0.072563 0.072563 2 1 
+0.00833716 0.0725543 0.0725543 2 1 
+0.00830779 0.0725455 0.0725455 2 1 
+0.00827846 0.0725367 0.0725367 2 1 
+0.00824918 0.0725278 0.0725278 2 1 
+0.00821993 0.0725189 0.0725189 2 1 
+0.00819072 0.0725099 0.0725099 2 1 
+0.00816154 0.0725009 0.0725009 2 1 
+0.00813241 0.0724918 0.0724918 2 1 
+0.00810332 0.0724827 0.0724827 2 1 
+0.00807426 0.0724735 0.0724735 2 1 
+0.00804524 0.0724643 0.0724643 2 1 
+0.00801626 0.072455 0.072455 2 1 
+0.00798732 0.0724457 0.0724457 2 1 
+0.00795842 0.0724363 0.0724363 2 1 
+0.00792955 0.0724269 0.0724269 2 1 
+0.00790073 0.0724174 0.0724174 2 1 
+0.00787194 0.0724079 0.0724079 2 1 
+0.00784319 0.0723983 0.0723983 2 1 
+0.00781448 0.0723887 0.0723887 2 1 
+0.0077858 0.072379 0.072379 2 1 
+0.00775717 0.0723693 0.0723693 2 1 
+0.00772857 0.0723595 0.0723595 2 1 
+0.00770001 0.0723496 0.0723496 2 1 
+0.00767149 0.0723397 0.0723397 2 1 
+0.00764301 0.0723298 0.0723298 2 1 
+0.00761457 0.0723197 0.0723197 2 1 
+0.00758616 0.0723097 0.0723097 2 1 
+0.00755779 0.0722995 0.0722995 2 1 
+0.00752946 0.0722893 0.0722893 2 1 
+0.00750117 0.0722791 0.0722791 2 1 
+0.00747291 0.0722688 0.0722688 2 1 
+0.0074447 0.0722584 0.0722584 2 1 
+0.00741652 0.072248 0.072248 2 1 
+0.00738838 0.0722375 0.0722375 2 1 
+0.00736027 0.0722269 0.0722269 2 1 
+0.00733221 0.0722163 0.0722163 2 1 
+0.00730418 0.0722056 0.0722056 2 1 
+0.00727619 0.0721949 0.0721949 2 1 
+0.00724824 0.0721841 0.0721841 2 1 
+0.00722032 0.0721732 0.0721732 2 1 
+0.00719245 0.0721623 0.0721623 2 1 
+0.00716461 0.0721513 0.0721513 2 1 
+0.00713681 0.0721402 0.0721402 2 1 
+0.00710904 0.0721291 0.0721291 2 1 
+0.00708131 0.0721179 0.0721179 2 1 
+0.00705362 0.0721066 0.0721066 2 1 
+0.00702597 0.0720952 0.0720952 2 1 
+0.00699836 0.0720838 0.0720838 2 1 
+0.00697078 0.0720723 0.0720723 2 1 
+0.00694324 0.0720608 0.0720608 2 1 
+0.00691574 0.0720492 0.0720492 2 1 
+0.00688827 0.0720375 0.0720375 2 1 
+0.00686085 0.0720257 0.0720257 2 1 
+0.00683346 0.0720139 0.0720139 2 1 
+0.0068061 0.0720019 0.0720019 2 1 
+0.00677879 0.0719899 0.0719899 2 1 
+0.00675151 0.0719779 0.0719779 2 1 
+0.00672427 0.0719657 0.0719657 2 1 
+0.00669706 0.0719535 0.0719535 2 1 
+0.00666989 0.0719412 0.0719412 2 1 
+0.00664276 0.0719288 0.0719288 2 1 
+0.00661567 0.0719163 0.0719163 2 1 
+0.00658861 0.0719038 0.0719038 2 1 
+0.00656159 0.0718912 0.0718912 2 1 
+0.00653461 0.0718784 0.0718784 2 1 
+0.00650767 0.0718657 0.0718657 2 1 
+0.00648076 0.0718528 0.0718528 2 1 
+0.00645388 0.0718398 0.0718398 2 1 
+0.00642705 0.0718268 0.0718268 2 1 
+0.00640025 0.0718136 0.0718136 2 1 
+0.00637349 0.0718004 0.0718004 2 1 
+0.00634676 0.0717871 0.0717871 2 1 
+0.00632008 0.0717737 0.0717737 2 1 
+0.00629342 0.0717602 0.0717602 2 1 
+0.00626681 0.0717466 0.0717466 2 1 
+0.00624023 0.0717329 0.0717329 2 1 
+0.00621369 0.0717191 0.0717191 2 1 
+0.00618718 0.0717053 0.0717053 2 1 
+0.00616072 0.0716913 0.0716913 2 1 
+0.00613428 0.0716772 0.0716772 2 1 
+0.00610789 0.0716631 0.0716631 2 1 
+0.00608153 0.0716488 0.0716488 2 1 
+0.00605521 0.0716345 0.0716345 2 1 
+0.00602892 0.07162 0.07162 2 1 
+0.00600267 0.0716054 0.0716054 2 1 
+0.00597645 0.0715908 0.0715908 2 1 
+0.00595028 0.071576 0.071576 2 1 
+0.00592414 0.0715611 0.0715611 2 1 
+0.00589803 0.0715462 0.0715462 2 1 
+0.00587196 0.0715311 0.0715311 2 1 
+0.00584593 0.0715159 0.0715159 2 1 
+0.00581993 0.0715006 0.0715006 2 1 
+0.00579397 0.0714851 0.0714851 2 1 
+0.00576805 0.0714696 0.0714696 2 1 
+0.00574216 0.071454 0.071454 2 1 
+0.00571631 0.0714382 0.0714382 2 1 
+0.00569049 0.0714223 0.0714223 2 1 
+0.00566471 0.0714063 0.0714063 2 1 
+0.00563896 0.0713902 0.0713902 2 1 
+0.00561326 0.071374 0.071374 2 1 
+0.00558758 0.0713576 0.0713576 2 1 
+0.00556195 0.0713411 0.0713411 2 1 
+0.00553634 0.0713245 0.0713245 2 1 
+0.00551078 0.0713078 0.0713078 2 1 
+0.00548525 0.0712909 0.0712909 2 1 
+0.00545976 0.0712739 0.0712739 2 1 
+0.0054343 0.0712568 0.0712568 2 1 
+0.00540887 0.0712395 0.0712395 2 1 
+0.00538349 0.0712221 0.0712221 2 1 
+0.00535814 0.0712046 0.0712046 2 1 
+0.00533282 0.0711869 0.0711869 2 1 
+0.00530754 0.0711691 0.0711691 2 1 
+0.00528229 0.0711511 0.0711511 2 1 
+0.00525709 0.071133 0.071133 2 1 
+0.00523191 0.0711148 0.0711148 2 1 
+0.00520677 0.0710964 0.0710964 2 1 
+0.00518167 0.0710779 0.0710779 2 1 
+0.0051566 0.0710592 0.0710592 2 1 
+0.00513157 0.0710404 0.0710404 2 1 
+0.00510657 0.0710214 0.0710214 2 1 
+0.00508161 0.0710022 0.0710022 2 1 
+0.00505668 0.0709829 0.0709829 2 1 
+0.00503179 0.0709634 0.0709634 2 1 
+0.00500694 0.0709438 0.0709438 2 1 
+0.00498211 0.070924 0.070924 2 1 
+0.00495733 0.0709041 0.0709041 2 1 
+0.00493258 0.0708839 0.0708839 2 1 
+0.00490786 0.0708636 0.0708636 2 1 
+0.00488318 0.0708432 0.0708432 2 1 
+0.00485853 0.0708225 0.0708225 2 1 
+0.00483392 0.0708017 0.0708017 2 1 
+0.00480935 0.0707807 0.0707807 2 1 
+0.00478481 0.0707595 0.0707595 2 1 
+0.0047603 0.0707381 0.0707381 2 1 
+0.00473583 0.0707166 0.0707166 2 1 
+0.00471139 0.0706948 0.0706948 2 1 
+0.00468699 0.0706729 0.0706729 2 1 
+0.00466262 0.0706508 0.0706508 2 1 
+0.00463829 0.0706284 0.0706284 2 1 
+0.00461399 0.0706059 0.0706059 2 1 
+0.00458973 0.0705832 0.0705832 2 1 
+0.0045655 0.0705602 0.0705602 2 1 
+0.00454131 0.0705371 0.0705371 2 1 
+0.00451715 0.0705137 0.0705137 2 1 
+0.00449303 0.0704902 0.0704902 2 1 
+0.00446894 0.0704664 0.0704664 2 1 
+0.00444488 0.0704424 0.0704424 2 1 
+0.00442086 0.0704181 0.0704181 2 1 
+0.00439687 0.0703937 0.0703937 2 1 
+0.00437292 0.070369 0.070369 2 1 
+0.00434901 0.070344 0.070344 2 1 
+0.00432512 0.0703189 0.0703189 2 1 
+0.00430127 0.0702935 0.0702935 2 1 
+0.00427746 0.0702678 0.0702678 2 1 
+0.00425368 0.0702419 0.0702419 2 1 
+0.00422993 0.0702158 0.0702158 2 1 
+0.00420622 0.0701894 0.0701894 2 1 
+0.00418254 0.0701627 0.0701627 2 1 
+0.0041589 0.0701358 0.0701358 2 1 
+0.00413529 0.0701086 0.0701086 2 1 
+0.00411172 0.0700812 0.0700812 2 1 
+0.00408818 0.0700534 0.0700534 2 1 
+0.00406467 0.0700254 0.0700254 2 1 
+0.0040412 0.0699971 0.0699971 2 1 
+0.00401776 0.0699685 0.0699685 2 1 
+0.00399436 0.0699397 0.0699397 2 1 
+0.00397099 0.0699105 0.0699105 2 1 
+0.00394765 0.069881 0.069881 2 1 
+0.00392435 0.0698512 0.0698512 2 1 
+0.00390108 0.0698211 0.0698211 2 1 
+0.00387784 0.0697907 0.0697907 2 1 
+0.00385464 0.06976 0.06976 2 1 
+0.00383148 0.069729 0.069729 2 1 
+0.00380834 0.0696976 0.0696976 2 1 
+0.00378525 0.0696659 0.0696659 2 1 
+0.00376218 0.0696338 0.0696338 2 1 
+0.00373915 0.0696014 0.0696014 2 1 
+0.00371615 0.0695687 0.0695687 2 1 
+0.00369319 0.0695355 0.0695355 2 1 
+0.00367026 0.0695021 0.0695021 2 1 
+0.00364736 0.0694682 0.0694682 2 1 
+0.0036245 0.069434 0.069434 2 1 
+0.00360167 0.0693994 0.0693994 2 1 
+0.00357888 0.0693644 0.0693644 2 1 
+0.00355612 0.069329 0.069329 2 1 
+0.00353339 0.0692932 0.0692932 2 1 
+0.0035107 0.0692569 0.0692569 2 1 
+0.00348804 0.0692203 0.0692203 2 1 
+0.00346541 0.0691832 0.0691832 2 1 
+0.00344282 0.0691458 0.0691458 2 1 
+0.00342026 0.0691078 0.0691078 2 1 
+0.00339774 0.0690694 0.0690694 2 1 
+0.00337524 0.0690306 0.0690306 2 1 
+0.00335279 0.0689913 0.0689913 2 1 
+0.00333036 0.0689515 0.0689515 2 1 
+0.00330797 0.0689113 0.0689113 2 1 
+0.00328562 0.0688706 0.0688706 2 1 
+0.0032633 0.0688293 0.0688293 2 1 
+0.00324101 0.0687876 0.0687876 2 1 
+0.00321875 0.0687453 0.0687453 2 1 
+0.00319653 0.0687025 0.0687025 2 1 
+0.00317434 0.0686592 0.0686592 2 1 
+0.00315219 0.0686153 0.0686153 2 1 
+0.00313007 0.0685709 0.0685709 2 1 
+0.00310798 0.0685259 0.0685259 2 1 
+0.00308593 0.0684803 0.0684803 2 1 
+0.00306392 0.0684341 0.0684341 2 1 
+0.00304193 0.0683874 0.0683874 2 1 
+0.00301998 0.06834 0.06834 2 1 
+0.00299807 0.068292 0.068292 2 1 
+0.00297618 0.0682433 0.0682433 2 1 
+0.00295434 0.068194 0.068194 2 1 
+0.00293252 0.0681441 0.0681441 2 1 
+0.00291074 0.0680935 0.0680935 2 1 
+0.002889 0.0680421 0.0680421 2 1 
+0.00286729 0.0679901 0.0679901 2 1 
+0.00284561 0.0679374 0.0679374 2 1 
+0.00282397 0.0678839 0.0678839 2 1 
+0.00280236 0.0678296 0.0678296 2 1 
+0.00278079 0.0677747 0.0677747 2 1 
+0.00275925 0.0677189 0.0677189 2 1 
+0.00273775 0.0676623 0.0676623 2 1 
+0.00271628 0.0676049 0.0676049 2 1 
+0.00269485 0.0675467 0.0675467 2 1 
+0.00267345 0.0674877 0.0674877 2 1 
+0.00265209 0.0674278 0.0674278 2 1 
+0.00263077 0.0673669 0.0673669 2 1 
+0.00260948 0.0673052 0.0673052 2 1 
+0.00258822 0.0672426 0.0672426 2 1 
+0.00258646 0.0672374 0.0672374 2 1 
+0.00256524 0.0671737 0.0671737 1 1 
+0.00254406 0.0671091 0.0671091 1 1 
+0.00252292 0.0670435 0.0670435 1 1 
+0.00250181 0.0669768 0.0669768 1 1 
+0.00248074 0.0669092 0.0669092 1 1 
+0.00245971 0.0668405 0.0668405 1 1 
+0.00243872 0.0667707 0.0667707 1 1 
+0.00241776 0.0666998 0.0666998 1 1 
+0.00239684 0.0666278 0.0666278 1 1 
+0.00237596 0.0665546 0.0665546 1 1 
+0.00235511 0.0664802 0.0664802 1 1 
+0.00233431 0.0664046 0.0664046 1 1 
+0.00231354 0.0663278 0.0663278 1 1 
+0.00229282 0.0662498 0.0662498 1 1 
+0.00227213 0.0661704 0.0661704 1 1 
+0.00225149 0.0660897 0.0660897 1 1 
+0.00223088 0.0660076 0.0660076 1 1 
+0.00221032 0.0659242 0.0659242 1 1 
+0.0021898 0.0658393 0.0658393 1 1 
+0.00216932 0.065753 0.065753 1 1 
+0.00214889 0.0656652 0.0656652 1 1 
+0.00212849 0.0655758 0.0655758 1 1 
+0.00210815 0.0654849 0.0654849 1 1 
+0.00208784 0.0653924 0.0653924 1 1 
+0.00206759 0.0652982 0.0652982 1 1 
+0.00204738 0.0652024 0.0652024 1 1 
+0.00202722 0.0651048 0.0651048 1 1 
+0.0020071 0.0650055 0.0650055 1 1 
+0.00198704 0.0649044 0.0649044 1 1 
+0.00196703 0.0648014 0.0648014 1 1 
+0.00194706 0.0646966 0.0646966 1 1 
+0.00192716 0.0645898 0.0645898 1 1 
+0.0019073 0.064481 0.064481 1 1 
+0.0018875 0.0643702 0.0643702 1 1 
+0.00186776 0.0642573 0.0642573 1 1 
+0.00184808 0.0641423 0.0641423 1 1 
+0.00182845 0.0640251 0.0640251 1 1 
+0.00180889 0.0639056 0.0639056 1 1 
+0.00178939 0.0637839 0.0637839 1 1 
+0.00176996 0.0636599 0.0636599 1 1 
+0.0017506 0.0635335 0.0635335 1 1 
+0.0017313 0.0634047 0.0634047 1 1 
+0.00171208 0.0632734 0.0632734 1 1 
+0.00169294 0.0631395 0.0631395 1 1 
+0.00167387 0.0630031 0.0630031 1 1 
+0.00165488 0.0628641 0.0628641 1 1 
+0.00163598 0.0627223 0.0627223 1 1 
+0.00161716 0.0625778 0.0625778 1 1 
+0.00159843 0.0624306 0.0624306 1 1 
+0.0015798 0.0622805 0.0622805 1 1 
+0.00156127 0.0621275 0.0621275 1 1 
+0.00154283 0.0619716 0.0619716 1 1 
+0.00152451 0.0618128 0.0618128 1 1 
+0.00150629 0.061651 0.061651 1 1 
+0.00148819 0.0614861 0.0614861 1 1 
+0.00147021 0.0613182 0.0613182 1 1 
+0.00145236 0.0611472 0.0611472 1 1 
+0.00143464 0.0609731 0.0609731 1 1 
+0.00141705 0.060796 0.060796 1 1 
+0.00139961 0.0606157 0.0606157 1 1 
+0.00138232 0.0604323 0.0604323 1 1 
+0.00136518 0.0602458 0.0602458 1 1 
+0.00134821 0.0600562 0.0600562 1 1 
+0.0013314 0.0598635 0.0598635 1 1 
+0.00131477 0.0596678 0.0596678 1 1 
+0.00129832 0.0594692 0.0594692 1 1 
+0.00128206 0.0592676 0.0592676 1 1 
+0.001266 0.0590632 0.0590632 1 1 
+0.00125014 0.0588559 0.0588559 1 1 
+0.0012345 0.058646 0.058646 1 1 
+0.00121907 0.0584335 0.0584335 1 1 
+0.00120386 0.0582185 0.0582185 1 1 
+0.00118889 0.0580012 0.0580012 1 1 
+0.00117415 0.0577816 0.0577816 1 1 
+0.00115966 0.0575599 0.0575599 1 1 
+0.00114541 0.0573363 0.0573363 1 1 
+0.00113142 0.0571108 0.0571108 1 1 
+0.00111769 0.0568838 0.0568838 1 1 
+0.00110422 0.0566553 0.0566553 1 1 
+0.00109102 0.0564255 0.0564255 1 1 
+0.00107809 0.0561946 0.0561946 1 1 
+0.00106542 0.0559628 0.0559628 1 1 
+0.00105304 0.0557302 0.0557302 1 1 
+0.00104093 0.0554971 0.0554971 1 1 
+0.00102909 0.0552636 0.0552636 1 1 
+0.00101753 0.0550299 0.0550299 1 1 
+0.00100624 0.0547962 0.0547962 1 1 
+0.000995228 0.0545626 0.0545626 1 1 
+0.000984487 0.0543292 0.0543292 1 1 
+0.000974014 0.0540964 0.0540964 1 1 
+0.000963808 0.0538641 0.0538641 1 1 
+0.000953864 0.0536326 0.0536326 1 1 
+0.00094418 0.053402 0.053402 1 1 
+0.000934751 0.0531723 0.0531723 1 1 
+0.000925573 0.0529438 0.0529438 1 1 
+0.00091664 0.0527165 0.0527165 1 1 
+0.000907949 0.0524905 0.0524905 1 1 
+0.000899494 0.052266 0.052266 1 1 
+0.000891269 0.0520429 0.0520429 1 1 
+0.00088327 0.0518214 0.0518214 1 1 
+0.000875491 0.0516016 0.0516016 1 1 
+0.000867926 0.0513835 0.0513835 1 1 
+0.000860569 0.0511671 0.0511671 1 1 
+0.000853416 0.0509526 0.0509526 1 1 
+0.00084646 0.0507399 0.0507399 1 1 
+0.000839696 0.0505291 0.0505291 1 1 
+0.000833119 0.0503202 0.0503202 1 1 
+0.000826723 0.0501133 0.0501133 1 1 
+0.000820502 0.0499083 0.0499083 1 1 
+0.000814453 0.0497053 0.0497053 1 1 
+0.000808569 0.0495043 0.0495043 1 1 
+0.000802845 0.0493053 0.0493053 1 1 
+0.000797277 0.0491083 0.0491083 1 1 
+0.00079186 0.0489134 0.0489134 1 1 
+0.000786589 0.0487204 0.0487204 1 1 
+0.000781459 0.0485294 0.0485294 1 1 
+0.000776468 0.0483404 0.0483404 1 1 
+0.000771609 0.0481535 0.0481535 1 1 
+0.000766879 0.0479685 0.0479685 1 1 
+0.000762274 0.0477854 0.0477854 1 1 
+0.00075779 0.0476043 0.0476043 1 1 
+0.000753423 0.0474252 0.0474252 1 1 
+0.00074917 0.047248 0.047248 1 1 
+0.000745027 0.0470727 0.0470727 1 1 
+0.000740991 0.0468993 0.0468993 1 1 
+0.000737058 0.0467277 0.0467277 1 1 
+0.000733226 0.0465581 0.0465581 1 1 
+0.000729491 0.0463902 0.0463902 1 1 
+0.000725851 0.0462242 0.0462242 1 1 
+0.000722302 0.0460599 0.0460599 1 1 
+0.000718842 0.0458974 0.0458974 1 1 
+0.000715468 0.0457367 0.0457367 1 1 
+0.000712177 0.0455777 0.0455777 1 1 
+0.000708968 0.0454204 0.0454204 1 1 
+0.000705837 0.0452648 0.0452648 1 1 
+0.000702783 0.0451108 0.0451108 1 1 
+0.000699803 0.0449585 0.0449585 1 1 
+0.000696895 0.0448078 0.0448078 1 1 
+0.000694057 0.0446587 0.0446587 1 1 
+0.000691287 0.0445111 0.0445111 1 1 
+0.000688583 0.0443651 0.0443651 1 1 
+0.000685944 0.0442207 0.0442207 1 1 
+0.000683367 0.0440777 0.0440777 1 1 
+0.00068085 0.0439363 0.0439363 1 1 
+0.000678393 0.0437963 0.0437963 1 1 
+0.000675993 0.0436577 0.0436577 1 1 
+0.000673649 0.0435206 0.0435206 1 1 
+0.00067136 0.0433849 0.0433849 1 1 
+0.000669123 0.0432505 0.0432505 1 1 
+0.000666938 0.0431175 0.0431175 1 1 
+0.000664803 0.0429859 0.0429859 1 1 
+0.000662717 0.0428556 0.0428556 1 1 
+0.000660679 0.0427265 0.0427265 1 1 
+0.000658687 0.0425988 0.0425988 1 1 
+0.00065674 0.0424723 0.0424723 1 1 
+0.000654837 0.0423471 0.0423471 1 1 
+0.000652977 0.0422231 0.0422231 1 1 
+0.000651159 0.0421003 0.0421003 1 1 
+0.000649382 0.0419787 0.0419787 1 1 
+0.000647645 0.0418583 0.0418583 1 1 
+0.000645946 0.041739 0.041739 1 1 
+0.000644286 0.0416209 0.0416209 1 1 
+0.000642662 0.0415039 0.0415039 1 1 
+0.000641075 0.041388 0.041388 1 1 
+0.000639522 0.0412732 0.0412732 1 1 
+0.000638005 0.0411595 0.0411595 1 1 
+0.00063652 0.0410468 0.0410468 1 1 
+0.000635069 0.0409352 0.0409352 1 1 
+0.000633649 0.0408245 0.0408245 1 1 
+0.000632261 0.040715 0.040715 1 1 
+0.000630904 0.0406064 0.0406064 1 1 
+0.000629577 0.0404988 0.0404988 1 1 
+0.000628278 0.0403921 0.0403921 1 1 
+0.000627009 0.0402864 0.0402864 1 1 
+0.000625767 0.0401817 0.0401817 1 1 
+0.000624553 0.0400779 0.0400779 1 1 
+0.000623365 0.039975 0.039975 1 1 
+0.000622204 0.039873 0.039873 1 1 
+0.000621068 0.0397719 0.0397719 1 1 
+0.000619957 0.0396717 0.0396717 1 1 
+0.000618871 0.0395723 0.0395723 1 1 
+0.000617809 0.0394738 0.0394738 1 1 
+0.00061677 0.0393761 0.0393761 1 1 
+0.000615755 0.0392793 0.0392793 1 1 
+0.000615593 0.0392636 0.0392636 2 1 
+0.000614602 0.0391677 0.0391677 2 1 
+0.000613635 0.0390726 0.0390726 2 1 
+0.000612689 0.0389783 0.0389783 2 1 
+0.000611764 0.0388848 0.0388848 2 1 
+0.00061086 0.038792 0.038792 2 1 
+0.000609977 0.0387 0.0387 2 1 
+0.000609113 0.0386088 0.0386088 2 1 
+0.000608268 0.0385183 0.0385183 2 1 
+0.000607443 0.0384285 0.0384285 2 1 
+0.000606637 0.0383395 0.0383395 2 1 
+0.000605849 0.0382511 0.0382511 2 1 
+0.000605079 0.0381635 0.0381635 2 1 
+0.000604326 0.0380766 0.0380766 2 1 
+0.000603591 0.0379903 0.0379903 2 1 
+0.000602874 0.0379047 0.0379047 2 1 
+0.000602172 0.0378198 0.0378198 2 1 
+0.000601488 0.0377355 0.0377355 2 1 
+0.000600819 0.0376519 0.0376519 2 1 
+0.000600166 0.0375689 0.0375689 2 1 
+0.000599528 0.0374865 0.0374865 2 1 
+0.000598906 0.0374048 0.0374048 2 1 
+0.000598299 0.0373236 0.0373236 2 1 
+0.000597707 0.0372431 0.0372431 2 1 
+0.000597128 0.0371632 0.0371632 2 1 
+0.000596565 0.0370838 0.0370838 2 1 
+0.000596015 0.0370051 0.0370051 2 1 
+0.000595478 0.0369269 0.0369269 2 1 
+0.000594955 0.0368493 0.0368493 2 1 
+0.000594446 0.0367722 0.0367722 2 1 
+0.000593949 0.0366957 0.0366957 2 1 
+0.000593465 0.0366198 0.0366198 2 1 
+0.000592994 0.0365443 0.0365443 2 1 
+0.000592535 0.0364694 0.0364694 2 1 
+0.000592088 0.0363951 0.0363951 2 1 
+0.000591653 0.0363212 0.0363212 2 1 
+0.00059123 0.0362479 0.0362479 2 1 
+0.000590818 0.0361751 0.0361751 2 1 
+0.000590417 0.0361027 0.0361027 2 1 
+0.000590028 0.0360309 0.0360309 2 1 
+0.00058965 0.0359596 0.0359596 2 1 
+0.000589283 0.0358887 0.0358887 2 1 
+0.000588926 0.0358183 0.0358183 2 1 
+0.00058858 0.0357484 0.0357484 2 1 
+0.000588243 0.0356789 0.0356789 2 1 
+0.000587918 0.0356099 0.0356099 2 1 
+0.000587602 0.0355414 0.0355414 2 1 
+0.000587296 0.0354733 0.0354733 2 1 
+0.000586999 0.0354056 0.0354056 2 1 
+0.000586712 0.0353384 0.0353384 2 1 
+0.000586435 0.0352716 0.0352716 2 1 
+0.000586166 0.0352053 0.0352053 2 1 
+0.000585907 0.0351393 0.0351393 2 1 
+0.000585657 0.0350738 0.0350738 2 1 
+0.000585415 0.0350087 0.0350087 2 1 
+0.000585183 0.034944 0.034944 2 1 
+0.000584958 0.0348797 0.0348797 2 1 
+0.000584743 0.0348158 0.0348158 2 1 
+0.000584535 0.0347523 0.0347523 2 1 
+0.000584336 0.0346892 0.0346892 2 1 
+0.000584144 0.0346264 0.0346264 2 1 
+0.000583961 0.0345641 0.0345641 2 1 
+0.000583786 0.0345021 0.0345021 2 1 
+0.000583618 0.0344405 0.0344405 2 1 
+0.000583458 0.0343792 0.0343792 2 1 
+0.000583305 0.0343184 0.0343184 2 1 
+0.00058316 0.0342578 0.0342578 2 1 
+0.000583022 0.0341977 0.0341977 2 1 
+0.000582891 0.0341378 0.0341378 2 1 
+0.000582768 0.0340784 0.0340784 2 1 
+0.000582651 0.0340192 0.0340192 2 1 
+0.000582541 0.0339605 0.0339605 2 1 
+0.000582438 0.033902 0.033902 2 1 
+0.000582342 0.0338439 0.0338439 2 1 
+0.000582252 0.0337861 0.0337861 2 1 
+0.000582169 0.0337286 0.0337286 2 1 
+0.000582093 0.0336715 0.0336715 2 1 
+0.000582022 0.0336146 0.0336146 2 1 
+0.000581958 0.0335581 0.0335581 2 1 
+0.0005819 0.0335019 0.0335019 2 1 
+0.000581849 0.033446 0.033446 2 1 
+0.000581803 0.0333904 0.0333904 2 1 
+0.000581763 0.0333351 0.0333351 2 1 
+0.000581729 0.0332801 0.0332801 2 1 
+0.000581701 0.0332254 0.0332254 2 1 
+0.000581679 0.033171 0.033171 2 1 
+0.000581662 0.0331168 0.0331168 2 1 
+0.000581651 0.033063 0.033063 2 1 
+0.000581645 0.0330094 0.0330094 2 1 
+0.000581644 0.0329804 0.0329804 2 1 
+0.000581647 0.0329272 0.0329272 2 1 
+0.000581655 0.0328744 0.0328744 2 1 
+0.000581668 0.0328218 0.0328218 2 1 
+0.000581687 0.0327695 0.0327695 2 1 
+0.000581711 0.0327174 0.0327174 2 1 
+0.000581739 0.0326656 0.0326656 2 1 
+0.000581773 0.0326141 0.0326141 2 1 
+0.000581812 0.0325628 0.0325628 2 1 
+0.000581855 0.0325118 0.0325118 2 1 
+0.000581903 0.032461 0.032461 2 1 
+0.000581956 0.0324105 0.0324105 2 1 
+0.000582014 0.0323603 0.0323603 2 1 
+0.000582077 0.0323102 0.0323102 2 1 
+0.000582144 0.0322605 0.0322605 2 1 
+0.000582215 0.0322109 0.0322109 2 1 
+0.000582291 0.0321616 0.0321616 2 1 
+0.000582372 0.0321125 0.0321125 2 1 
+0.000582457 0.0320637 0.0320637 2 1 
+0.000582546 0.0320151 0.0320151 2 1 
+0.00058264 0.0319667 0.0319667 2 1 
+0.000582737 0.0319186 0.0319186 2 1 
+0.000582839 0.0318706 0.0318706 2 1 
+0.000582945 0.0318229 0.0318229 2 1 
+0.000583056 0.0317754 0.0317754 2 1 
+0.00058317 0.0317282 0.0317282 2 1 
+0.000583288 0.0316811 0.0316811 2 1 
+0.00058341 0.0316343 0.0316343 2 1 
+0.000583536 0.0315876 0.0315876 2 1 
+0.000583666 0.0315412 0.0315412 2 1 
+0.0005838 0.031495 0.031495 2 1 
+0.000583937 0.031449 0.031449 2 1 
+0.000584078 0.0314031 0.0314031 2 1 
+0.000584223 0.0313575 0.0313575 2 1 
+0.000584372 0.0313121 0.0313121 2 1 
+0.000584524 0.0312669 0.0312669 2 1 
+0.00058468 0.0312219 0.0312219 2 1 
+0.000584839 0.031177 0.031177 2 1 
+0.000585002 0.0311324 0.0311324 2 1 
+0.000585168 0.031088 0.031088 2 1 
+0.000585338 0.0310437 0.0310437 2 1 
+0.000585511 0.0309996 0.0309996 2 1 
+0.000585687 0.0309557 0.0309557 2 1 
+0.000585867 0.030912 0.030912 2 1 
+0.00058605 0.0308685 0.0308685 2 1 
+0.000586236 0.0308251 0.0308251 2 1 
+0.000586426 0.030782 0.030782 2 1 
+0.000586618 0.030739 0.030739 2 1 
+0.000586814 0.0306961 0.0306961 2 1 
+0.000587013 0.0306535 0.0306535 2 1 
+0.000587215 0.030611 0.030611 2 1 
+0.00058742 0.0305687 0.0305687 2 1 
+0.000587628 0.0305266 0.0305266 2 1 
+0.000587839 0.0304846 0.0304846 2 1 
+0.000588053 0.0304428 0.0304428 2 1 
+0.00058827 0.0304011 0.0304011 2 1 
+0.000588489 0.0303596 0.0303596 2 1 
+0.000588712 0.0303183 0.0303183 2 1 
+0.000588937 0.0302771 0.0302771 2 1 
+0.000589166 0.0302361 0.0302361 2 1 
+0.000589397 0.0301953 0.0301953 2 1 
+0.000589631 0.0301545 0.0301545 2 1 
+0.000589867 0.030114 0.030114 2 1 
+0.000590106 0.0300736 0.0300736 2 1 
+0.000590348 0.0300333 0.0300333 2 1 
+0.000590593 0.0299932 0.0299932 2 1 
+0.00059084 0.0299533 0.0299533 2 1 
+0.000591089 0.0299135 0.0299135 2 1 
+0.000591342 0.0298738 0.0298738 2 1 
+0.000591597 0.0298343 0.0298343 2 1 
+0.000591854 0.0297949 0.0297949 2 1 
+0.000592114 0.0297557 0.0297557 2 1 
+0.000592376 0.0297166 0.0297166 2 1 
+0.000592641 0.0296776 0.0296776 2 1 
+0.000592908 0.0296388 0.0296388 2 1 
+0.000593177 0.0296001 0.0296001 2 1 
+0.000593449 0.0295616 0.0295616 2 1 
+0.000593724 0.0295232 0.0295232 2 1 
+0.000594 0.0294849 0.0294849 2 1 
+0.000594279 0.0294467 0.0294467 2 1 
+0.00059456 0.0294087 0.0294087 2 1 
+0.000594844 0.0293708 0.0293708 2 1 
+0.00059513 0.029333 0.029333 2 1 
+0.000595418 0.0292954 0.0292954 2 1 
+0.000595708 0.0292579 0.0292579 2 1 
+0.000596 0.0292205 0.0292205 2 1 
+0.000596295 0.0291832 0.0291832 2 1 
+0.000596591 0.0291461 0.0291461 2 1 
+0.00059689 0.0291091 0.0291091 2 1 
+0.000597191 0.0290722 0.0290722 2 1 
+0.000597494 0.0290354 0.0290354 2 1 
+0.000597799 0.0289987 0.0289987 2 1 
+0.000598106 0.0289622 0.0289622 2 1 
+0.000598415 0.0289257 0.0289257 2 1 
+0.000598726 0.0288894 0.0288894 2 1 
+0.000599039 0.0288532 0.0288532 2 1 
+0.000599354 0.0288171 0.0288171 2 1 
+0.000599671 0.0287812 0.0287812 2 1 
+0.00059999 0.0287453 0.0287453 2 1 
+0.000600311 0.0287095 0.0287095 2 1 
+0.000600634 0.0286739 0.0286739 2 1 
+0.000600958 0.0286384 0.0286384 2 1 
+0.000601285 0.0286029 0.0286029 2 1 
+0.000601613 0.0285676 0.0285676 2 1 
+0.000601944 0.0285324 0.0285324 2 1 
+0.000602276 0.0284973 0.0284973 2 1 
+0.00060261 0.0284623 0.0284623 2 1 
+0.000602945 0.0284274 0.0284274 2 1 
+0.000603283 0.0283926 0.0283926 2 1 
+0.000603622 0.0283579 0.0283579 2 1 
+0.000603963 0.0283233 0.0283233 2 1 
+0.000604305 0.0282888 0.0282888 2 1 
+0.00060465 0.0282544 0.0282544 2 1 
+0.000604996 0.0282201 0.0282201 2 1 
+0.000605344 0.0281859 0.0281859 2 1 
+0.000605693 0.0281518 0.0281518 2 1 
+0.000606044 0.0281178 0.0281178 2 1 
+0.000606397 0.0280838 0.0280838 2 1 
+0.000606751 0.02805 0.02805 2 1 
+0.000607107 0.0280163 0.0280163 2 1 
+0.000607465 0.0279827 0.0279827 2 1 
+0.000607824 0.0279491 0.0279491 2 1 
+0.000608184 0.0279157 0.0279157 2 1 
+0.000608547 0.0278823 0.0278823 2 1 
+0.000608911 0.027849 0.027849 2 1 
+0.000609276 0.0278158 0.0278158 2 1 
+0.000609643 0.0277828 0.0277828 2 1 
+0.000610011 0.0277497 0.0277497 2 1 
+0.000610381 0.0277168 0.0277168 2 1 
+0.000610752 0.027684 0.027684 2 1 
+0.000611125 0.0276512 0.0276512 2 1 
+0.0006115 0.0276186 0.0276186 2 1 
+0.000611875 0.027586 0.027586 2 1 
+0.000612253 0.0275535 0.0275535 2 1 
+0.000612631 0.0275211 0.0275211 2 1 
+0.000613011 0.0274888 0.0274888 2 1 
+0.000613393 0.0274565 0.0274565 2 1 
+0.000613775 0.0274243 0.0274243 2 1 
+0.00061416 0.0273922 0.0273922 2 1 
+0.000614545 0.0273602 0.0273602 2 1 
+0.000614932 0.0273283 0.0273283 2 1 
+0.00061532 0.0272964 0.0272964 2 1 
+0.00061571 0.0272647 0.0272647 2 1 
+0.000616101 0.027233 0.027233 2 1 
+0.000616493 0.0272013 0.0272013 2 1 
+0.000616886 0.0271698 0.0271698 2 1 
+0.000617281 0.0271383 0.0271383 2 1 
+0.000617677 0.0271069 0.0271069 2 1 
+0.000618075 0.0270756 0.0270756 2 1 
+0.000618473 0.0270444 0.0270444 2 1 
+0.000618873 0.0270132 0.0270132 2 1 
+0.000619274 0.0269821 0.0269821 2 1 
+0.000619677 0.026951 0.026951 2 1 
+0.00062008 0.0269201 0.0269201 2 1 
+0.000620485 0.0268892 0.0268892 2 1 
+0.000620891 0.0268584 0.0268584 2 1 
+0.000621298 0.0268276 0.0268276 2 1 
+0.000621706 0.0267969 0.0267969 2 1 
+0.000622116 0.0267663 0.0267663 2 1 
+0.000622527 0.0267358 0.0267358 2 1 
+0.000622938 0.0267053 0.0267053 2 1 
+0.000623351 0.0266749 0.0266749 2 1 
+0.000623765 0.0266445 0.0266445 2 1 
+0.000624181 0.0266142 0.0266142 2 1 
+0.000624597 0.026584 0.026584 2 1 
+0.000625015 0.0265539 0.0265539 2 1 
+0.000625433 0.0265238 0.0265238 2 1 
+0.000625853 0.0264937 0.0264937 2 1 
+0.000626273 0.0264638 0.0264638 2 1 
+0.000626695 0.0264339 0.0264339 2 1 
+0.000627118 0.026404 0.026404 2 1 
+0.000627542 0.0263743 0.0263743 2 1 
+0.000627967 0.0263445 0.0263445 2 1 
+0.000628393 0.0263149 0.0263149 2 1 
+0.00062882 0.0262853 0.0262853 2 1 
+0.000629248 0.0262558 0.0262558 2 1 
+0.000629677 0.0262263 0.0262263 2 1 
+0.000630107 0.0261969 0.0261969 2 1 
+0.000630538 0.0261675 0.0261675 2 1 
+0.000630971 0.0261382 0.0261382 2 1 
+0.000631404 0.026109 0.026109 2 1 
+0.000631838 0.0260798 0.0260798 2 1 
+0.000632273 0.0260506 0.0260506 2 1 
+0.000632709 0.0260216 0.0260216 2 1 
+0.000633146 0.0259926 0.0259926 2 1 
+0.000633583 0.0259636 0.0259636 2 1 
+0.000634022 0.0259347 0.0259347 2 1 
+0.000634462 0.0259058 0.0259058 2 1 
+0.000634903 0.025877 0.025877 2 1 
+0.000635344 0.0258483 0.0258483 2 1 
+0.000635787 0.0258196 0.0258196 2 1 
+0.00063623 0.0257909 0.0257909 2 1 
+0.000636675 0.0257624 0.0257624 2 1 
+0.00063712 0.0257338 0.0257338 2 1 
+0.000637566 0.0257053 0.0257053 2 1 
+0.000638013 0.0256769 0.0256769 2 1 
+0.000638461 0.0256485 0.0256485 2 1 
+0.000638909 0.0256202 0.0256202 2 1 
+0.000639359 0.0255919 0.0255919 2 1 
+0.000639809 0.0255637 0.0255637 2 1 
+0.00064026 0.0255355 0.0255355 2 1 
+0.000640713 0.0255073 0.0255073 2 1 
+0.000641165 0.0254792 0.0254792 2 1 
+0.000641619 0.0254512 0.0254512 2 1 
+0.000642074 0.0254232 0.0254232 2 1 
+0.000642529 0.0253953 0.0253953 2 1 
+0.000642985 0.0253674 0.0253674 2 1 
+0.000643442 0.0253395 0.0253395 2 1 
+0.0006439 0.0253117 0.0253117 2 1 
+0.000644358 0.0252839 0.0252839 2 1 
+0.000644818 0.0252562 0.0252562 2 1 
+0.000645278 0.0252286 0.0252286 2 1 
+0.000645739 0.0252009 0.0252009 2 1 
+0.0006462 0.0251734 0.0251734 2 1 
+0.000646663 0.0251458 0.0251458 2 1 
+0.000647126 0.0251183 0.0251183 2 1 
+0.000647589 0.0250909 0.0250909 2 1 
+0.000648054 0.0250635 0.0250635 2 1 
+0.000648519 0.0250361 0.0250361 2 1 
+0.000648985 0.0250088 0.0250088 2 1 
+0.000649452 0.0249815 0.0249815 2 1 
+0.00064992 0.0249543 0.0249543 2 1 
+0.000650388 0.0249271 0.0249271 2 1 
+0.000650857 0.0248999 0.0248999 2 1 
+0.000651326 0.0248728 0.0248728 2 1 
+0.000651796 0.0248457 0.0248457 2 1 
+0.000652267 0.0248187 0.0248187 2 1 
+0.000652739 0.0247917 0.0247917 2 1 
+0.000653211 0.0247647 0.0247647 2 1 
+0.000653684 0.0247378 0.0247378 2 1 
+0.000654158 0.0247109 0.0247109 2 1 
+0.000654632 0.0246841 0.0246841 2 1 
+0.000655107 0.0246573 0.0246573 2 1 
+0.000655583 0.0246305 0.0246305 2 1 
+0.000656059 0.0246038 0.0246038 2 1 
+0.000656536 0.0245771 0.0245771 2 1 
+0.000657013 0.0245505 0.0245505 2 1 
+0.000657491 0.0245238 0.0245238 2 1 
+0.00065797 0.0244973 0.0244973 2 1 
+0.000658449 0.0244707 0.0244707 2 1 
+0.000658929 0.0244442 0.0244442 2 1 
+0.00065941 0.0244177 0.0244177 2 1 
+0.000659891 0.0243913 0.0243913 2 1 
+0.000660373 0.0243649 0.0243649 2 1 
+0.000660855 0.0243385 0.0243385 2 1 
+0.000661338 0.0243122 0.0243122 2 1 
+0.000661821 0.0242859 0.0242859 2 1 
+0.000662306 0.0242596 0.0242596 2 1 
+0.00066279 0.0242334 0.0242334 2 1 
+0.000663275 0.0242072 0.0242072 2 1 
+0.000663761 0.0241811 0.0241811 2 1 
+0.000664247 0.0241549 0.0241549 2 1 
+0.000664734 0.0241288 0.0241288 2 1 
+0.000665222 0.0241028 0.0241028 2 1 
+0.00066571 0.0240767 0.0240767 2 1 
+0.000666198 0.0240507 0.0240507 2 1 
+0.000666687 0.0240248 0.0240248 2 1 
+0.000667177 0.0239988 0.0239988 2 1 
+0.000667667 0.0239729 0.0239729 2 1 
+0.000668158 0.023947 0.023947 2 1 
+0.000668649 0.0239212 0.0239212 2 1 
+0.00066914 0.0238954 0.0238954 2 1 
+0.000669632 0.0238696 0.0238696 2 1 
+0.000670125 0.0238438 0.0238438 2 1 
+0.000670618 0.0238181 0.0238181 2 1 
+0.000671112 0.0237924 0.0237924 2 1 
+0.000671606 0.0237667 0.0237667 2 1 
+0.0006721 0.0237411 0.0237411 2 1 
+0.000672595 0.0237155 0.0237155 2 1 
+0.000673091 0.0236899 0.0236899 2 1 
+0.000673587 0.0236643 0.0236643 2 1 
+0.000674083 0.0236388 0.0236388 2 1 
+0.00067458 0.0236133 0.0236133 2 1 
+0.000675078 0.0235878 0.0235878 2 1 
+0.000675575 0.0235624 0.0235624 2 1 
+0.000676074 0.023537 0.023537 2 1 
+0.000676572 0.0235116 0.0235116 2 1 
+0.000677072 0.0234862 0.0234862 2 1 
+0.000677571 0.0234609 0.0234609 2 1 
+0.000678071 0.0234356 0.0234356 2 1 
+0.000678571 0.0234103 0.0234103 2 1 
+0.000679072 0.023385 0.023385 2 1 
+0.000679574 0.0233598 0.0233598 2 1 
+0.000680075 0.0233346 0.0233346 2 1 
+0.000680577 0.0233094 0.0233094 2 1 
+0.00068108 0.0232842 0.0232842 2 1 
+0.000681583 0.0232591 0.0232591 2 1 
+0.000682086 0.023234 0.023234 2 1 
+0.00068259 0.0232089 0.0232089 2 1 
+0.000683094 0.0231838 0.0231838 2 1 
+0.000683598 0.0231588 0.0231588 2 1 
+0.000684103 0.0231338 0.0231338 2 1 
+0.000684608 0.0231088 0.0231088 2 1 
+0.000685114 0.0230838 0.0230838 2 1 
+0.00068562 0.0230588 0.0230588 2 1 
+0.000686126 0.0230339 0.0230339 2 1 
+0.000686633 0.023009 0.023009 2 1 
+0.00068714 0.0229841 0.0229841 2 1 
+0.000687647 0.0229593 0.0229593 2 1 
+0.000688155 0.0229344 0.0229344 2 1 
+0.000688663 0.0229096 0.0229096 2 1 
+0.000689171 0.0228848 0.0228848 2 1 
+0.00068968 0.0228601 0.0228601 2 1 
+0.000690189 0.0228353 0.0228353 2 1 
+0.000690698 0.0228106 0.0228106 2 1 
+0.000691208 0.0227859 0.0227859 2 1 
+0.000691718 0.0227612 0.0227612 2 1 
+0.000692228 0.0227365 0.0227365 2 1 
+0.000692739 0.0227119 0.0227119 2 1 
+0.00069325 0.0226873 0.0226873 2 1 
+0.000693761 0.0226627 0.0226627 2 1 
+0.000694273 0.0226381 0.0226381 2 1 
+0.000694784 0.0226135 0.0226135 2 1 
+0.000695296 0.0225889 0.0225889 2 1 
+0.000695809 0.0225644 0.0225644 2 1 
+0.000696322 0.0225399 0.0225399 2 1 
+0.000696835 0.0225154 0.0225154 2 1 
+0.000697348 0.0224909 0.0224909 2 1 
+0.000697861 0.0224665 0.0224665 2 1 
+0.000698375 0.0224421 0.0224421 2 1 
+0.000698889 0.0224176 0.0224176 2 1 
+0.000699404 0.0223932 0.0223932 2 1 
+0.000699918 0.0223689 0.0223689 2 1 
+0.000700433 0.0223445 0.0223445 2 1 
+0.000700948 0.0223201 0.0223201 2 1 
+0.000701463 0.0222958 0.0222958 2 1 
+0.000701979 0.0222715 0.0222715 2 1 
+0.000702495 0.0222472 0.0222472 2 1 
+0.000703011 0.0222229 0.0222229 2 1 
+0.000703527 0.0221987 0.0221987 2 1 
+0.000704044 0.0221744 0.0221744 2 1 
+0.00070456 0.0221502 0.0221502 2 1 
+0.000705077 0.022126 0.022126 2 1 
+0.000705594 0.0221018 0.0221018 2 1 
+0.000706112 0.0220776 0.0220776 2 1 
+0.000706629 0.0220534 0.0220534 2 1 
+0.000707147 0.0220293 0.0220293 2 1 
+0.000707665 0.0220051 0.0220051 2 1 
+0.000708183 0.021981 0.021981 2 1 
+0.000708702 0.0219569 0.0219569 2 1 
+0.00070922 0.0219328 0.0219328 2 1 
+0.000709739 0.0219087 0.0219087 2 1 
+0.000710258 0.0218847 0.0218847 2 1 
+0.000710777 0.0218606 0.0218606 2 1 
+0.000711297 0.0218366 0.0218366 2 1 
+0.000711816 0.0218126 0.0218126 2 1 
+0.000712336 0.0217886 0.0217886 2 1 
+0.000712856 0.0217646 0.0217646 2 1 
+0.000713375 0.0217406 0.0217406 2 1 
+0.000713896 0.0217166 0.0217166 2 1 
+0.000714416 0.0216927 0.0216927 2 1 
+0.000714936 0.0216688 0.0216688 2 1 
+0.000715457 0.0216448 0.0216448 2 1 
+0.000715978 0.0216209 0.0216209 2 1 
+0.000716498 0.021597 0.021597 2 1 
+0.000717019 0.0215731 0.0215731 2 1 
+0.000717541 0.0215493 0.0215493 2 1 
+0.000718062 0.0215254 0.0215254 2 1 
+0.000718583 0.0215016 0.0215016 2 1 
+0.000719105 0.0214777 0.0214777 2 1 
+0.000719626 0.0214539 0.0214539 2 1 
+0.000720148 0.0214301 0.0214301 2 1 
+0.00072067 0.0214063 0.0214063 2 1 
+0.000721192 0.0213825 0.0213825 2 1 
+0.000721714 0.0213587 0.0213587 2 1 
+0.000722236 0.0213349 0.0213349 2 1 
+0.000722758 0.0213112 0.0213112 2 1 
+0.000723281 0.0212874 0.0212874 2 1 
+0.000723803 0.0212637 0.0212637 2 1 
+0.000724326 0.02124 0.02124 2 1 
+0.000724848 0.0212163 0.0212163 2 1 
+0.000725371 0.0211926 0.0211926 2 1 
+0.000725894 0.0211689 0.0211689 2 1 
+0.000726416 0.0211452 0.0211452 2 1 
+0.000726939 0.0211215 0.0211215 2 1 
+0.000727462 0.0210979 0.0210979 2 1 
+0.000727985 0.0210742 0.0210742 2 1 
+0.000728508 0.0210506 0.0210506 2 1 
+0.000729031 0.0210269 0.0210269 2 1 
+0.000729555 0.0210033 0.0210033 2 1 
+0.000730078 0.0209797 0.0209797 2 1 
+0.000730601 0.0209561 0.0209561 2 1 
+0.000731124 0.0209325 0.0209325 2 1 
+0.000731648 0.0209089 0.0209089 2 1 
+0.000732171 0.0208853 0.0208853 2 1 
+0.000732694 0.0208617 0.0208617 2 1 
+0.000733218 0.0208382 0.0208382 2 1 
+0.000733741 0.0208146 0.0208146 2 1 
+0.000734265 0.0207911 0.0207911 2 1 
+0.000734788 0.0207675 0.0207675 2 1 
+0.000735312 0.020744 0.020744 2 1 
+0.000735835 0.0207205 0.0207205 2 1 
+0.000736359 0.020697 0.020697 2 1 
+0.000736882 0.0206735 0.0206735 2 1 
+0.000737405 0.02065 0.02065 2 1 
+0.000737929 0.0206265 0.0206265 2 1 
+0.000738452 0.020603 0.020603 2 1 
+0.000738976 0.0205795 0.0205795 2 1 
+0.000739499 0.0205561 0.0205561 2 1 
+0.000740022 0.0205326 0.0205326 2 1 
+0.000740546 0.0205091 0.0205091 2 1 
+0.000741069 0.0204857 0.0204857 2 1 
+0.000741592 0.0204623 0.0204623 2 1 
+0.000742116 0.0204388 0.0204388 2 1 
+0.000742639 0.0204154 0.0204154 2 1 
+0.000743162 0.020392 0.020392 2 1 
+0.000743685 0.0203686 0.0203686 2 1 
+0.000744208 0.0203451 0.0203451 2 1 
+0.000744731 0.0203217 0.0203217 2 1 
+0.000745254 0.0202983 0.0202983 2 1 
+0.000745777 0.0202749 0.0202749 2 1 
+0.000746299 0.0202516 0.0202516 2 1 
+0.000746822 0.0202282 0.0202282 2 1 
+0.000747345 0.0202048 0.0202048 2 1 
+0.000747867 0.0201814 0.0201814 2 1 
+0.00074839 0.0201581 0.0201581 2 1 
+0.000748912 0.0201347 0.0201347 2 1 
+0.000749434 0.0201113 0.0201113 2 1 
+0.000749957 0.020088 0.020088 2 1 
+0.000750479 0.0200647 0.0200647 2 1 
+0.000751001 0.0200413 0.0200413 2 1 
+0.000751522 0.020018 0.020018 2 1 
+0.000752044 0.0199946 0.0199946 2 1 
+0.000752566 0.0199713 0.0199713 2 1 
+0.000753087 0.019948 0.019948 2 1 
+0.000753609 0.0199247 0.0199247 2 1 
+0.00075413 0.0199014 0.0199014 2 1 
+0.000754651 0.019878 0.019878 2 1 
+0.000755172 0.0198547 0.0198547 2 1 
+0.000755693 0.0198314 0.0198314 2 1 
+0.000756214 0.0198081 0.0198081 2 1 
+0.000756734 0.0197848 0.0197848 2 1 
+0.000757255 0.0197615 0.0197615 2 1 
+0.000757775 0.0197382 0.0197382 2 1 
+0.000758295 0.019715 0.019715 2 1 
+0.000758815 0.0196917 0.0196917 2 1 
+0.000759335 0.0196684 0.0196684 2 1 
+0.000759854 0.0196451 0.0196451 2 1 
+0.000760374 0.0196218 0.0196218 2 1 
+0.000760893 0.0195986 0.0195986 2 1 
+0.000761412 0.0195753 0.0195753 2 1 
+0.000761931 0.019552 0.019552 2 1 
+0.00076245 0.0195288 0.0195288 2 1 
+0.000762968 0.0195055 0.0195055 2 1 
+0.000763486 0.0194822 0.0194822 2 1 
+0.000764004 0.019459 0.019459 2 1 
+0.000764522 0.0194357 0.0194357 2 1 
+0.00076504 0.0194125 0.0194125 2 1 
+0.000765557 0.0193892 0.0193892 2 1 
+0.000766075 0.019366 0.019366 2 1 
+0.000766592 0.0193427 0.0193427 2 1 
+0.000767108 0.0193195 0.0193195 2 1 
+0.000767625 0.0192962 0.0192962 2 1 
+0.000768141 0.019273 0.019273 2 1 
+0.000768657 0.0192497 0.0192497 2 1 
+0.000769173 0.0192265 0.0192265 2 1 
+0.000769689 0.0192033 0.0192033 2 1 
+0.000770204 0.01918 0.01918 2 1 
+0.000770719 0.0191568 0.0191568 2 1 
+0.000771234 0.0191335 0.0191335 2 1 
+0.000771748 0.0191103 0.0191103 2 1 
+0.000772263 0.0190871 0.0190871 2 1 
+0.000772776 0.0190638 0.0190638 2 1 
+0.00077329 0.0190406 0.0190406 2 1 
+0.000773804 0.0190173 0.0190173 2 1 
+0.000774317 0.0189941 0.0189941 2 1 
+0.00077483 0.0189709 0.0189709 2 1 
+0.000775342 0.0189476 0.0189476 2 1 
+0.000775854 0.0189244 0.0189244 2 1 
+0.000776366 0.0189012 0.0189012 2 1 
+0.000776878 0.0188779 0.0188779 2 1 
+0.000777389 0.0188547 0.0188547 2 1 
+0.0007779 0.0188315 0.0188315 2 1 
+0.000778411 0.0188082 0.0188082 2 1 
+0.000778921 0.018785 0.018785 2 1 
+0.000779431 0.0187617 0.0187617 2 1 
+0.000779941 0.0187385 0.0187385 2 1 
+0.00078045 0.0187153 0.0187153 2 1 
+0.000780959 0.018692 0.018692 2 1 
+0.000781468 0.0186688 0.0186688 2 1 
+0.000781976 0.0186455 0.0186455 2 1 
+0.000782484 0.0186223 0.0186223 2 1 
+0.000782991 0.018599 0.018599 2 1 
+0.000783499 0.0185758 0.0185758 2 1 
+0.000784005 0.0185526 0.0185526 2 1 
+0.000784512 0.0185293 0.0185293 2 1 
+0.000785018 0.0185061 0.0185061 2 1 
+0.000785524 0.0184828 0.0184828 2 1 
+0.000786029 0.0184595 0.0184595 2 1 
+0.000786534 0.0184363 0.0184363 2 1 
+0.000787038 0.018413 0.018413 2 1 
+0.000787542 0.0183898 0.0183898 2 1 
+0.000788046 0.0183665 0.0183665 2 1 
+0.000788549 0.0183432 0.0183432 2 1 
+0.000789052 0.01832 0.01832 2 1 
+0.000789554 0.0182967 0.0182967 2 1 
+0.000790056 0.0182734 0.0182734 2 1 
+0.000790558 0.0182502 0.0182502 2 1 
+0.000791059 0.0182269 0.0182269 2 1 
+0.000791559 0.0182036 0.0182036 2 1 
+0.00079206 0.0181803 0.0181803 2 1 
+0.000792559 0.018157 0.018157 2 1 
+0.000793059 0.0181337 0.0181337 2 1 
+0.000793557 0.0181105 0.0181105 2 1 
+0.000794056 0.0180872 0.0180872 2 1 
+0.000794554 0.0180639 0.0180639 2 1 
+0.000795051 0.0180406 0.0180406 2 1 
+0.000795548 0.0180173 0.0180173 2 1 
+0.000796044 0.017994 0.017994 2 1 
+0.00079654 0.0179706 0.0179706 2 1 
+0.000797035 0.0179473 0.0179473 2 1 
+0.00079753 0.017924 0.017924 2 1 
+0.000798025 0.0179007 0.0179007 2 1 
+0.000798519 0.0178774 0.0178774 2 1 
+0.000799012 0.017854 0.017854 2 1 
+0.000799505 0.0178307 0.0178307 2 1 
+0.000799997 0.0178074 0.0178074 2 1 
+0.000800489 0.017784 0.017784 2 1 
+0.00080098 0.0177607 0.0177607 2 1 
+0.000801471 0.0177373 0.0177373 2 1 
+0.000801961 0.017714 0.017714 2 1 
+0.00080245 0.0176906 0.0176906 2 1 
+0.000802939 0.0176673 0.0176673 2 1 
+0.000803427 0.0176439 0.0176439 2 1 
+0.000803915 0.0176205 0.0176205 2 1 
+0.000804402 0.0175971 0.0175971 2 1 
+0.000804889 0.0175738 0.0175738 2 1 
+0.000805375 0.0175504 0.0175504 2 1 
+0.000805861 0.017527 0.017527 2 1 
+0.000806345 0.0175036 0.0175036 2 1 
+0.00080683 0.0174802 0.0174802 2 1 
+0.000807313 0.0174568 0.0174568 2 1 
+0.000807796 0.0174334 0.0174334 2 1 
+0.000808279 0.0174099 0.0174099 2 1 
+0.00080876 0.0173865 0.0173865 2 1 
+0.000809242 0.0173631 0.0173631 2 1 
+0.000809722 0.0173397 0.0173397 2 1 
+0.000810202 0.0173162 0.0173162 2 1 
+0.000810681 0.0172928 0.0172928 2 1 
+0.000811159 0.0172693 0.0172693 2 1 
+0.000811637 0.0172459 0.0172459 2 1 
+0.000812114 0.0172224 0.0172224 2 1 
+0.000812591 0.0171989 0.0171989 2 1 
+0.000813067 0.0171755 0.0171755 2 1 
+0.000813542 0.017152 0.017152 2 1 
+0.000814016 0.0171285 0.0171285 2 1 
+0.00081449 0.017105 0.017105 2 1 
+0.000814963 0.0170815 0.0170815 2 1 
+0.000815435 0.017058 0.017058 2 1 
+0.000815906 0.0170345 0.0170345 2 1 
+0.000816377 0.0170109 0.0170109 2 1 
+0.000816847 0.0169874 0.0169874 2 1 
+0.000817317 0.0169639 0.0169639 2 1 
+0.000817785 0.0169403 0.0169403 2 1 
+0.000818253 0.0169168 0.0169168 2 1 
+0.00081872 0.0168932 0.0168932 2 1 
+0.000819186 0.0168697 0.0168697 2 1 
+0.000819652 0.0168461 0.0168461 2 1 
+0.000820117 0.0168225 0.0168225 2 1 
+0.000820581 0.016799 0.016799 2 1 
+0.000821044 0.0167754 0.0167754 2 1 
+0.000821506 0.0167518 0.0167518 2 1 
+0.000821968 0.0167282 0.0167282 2 1 
+0.000822428 0.0167046 0.0167046 2 1 
+0.000822888 0.0166809 0.0166809 2 1 
+0.000823347 0.0166573 0.0166573 2 1 
+0.000823806 0.0166337 0.0166337 2 1 
+0.000824263 0.01661 0.01661 2 1 
+0.000824719 0.0165864 0.0165864 2 1 
+0.000825175 0.0165627 0.0165627 2 1 
+0.00082563 0.016539 0.016539 2 1 
+0.000826084 0.0165154 0.0165154 2 1 
+0.000826537 0.0164917 0.0164917 2 1 
+0.000826989 0.016468 0.016468 2 1 
+0.000827441 0.0164443 0.0164443 2 1 
+0.000827891 0.0164206 0.0164206 2 1 
+0.000828341 0.0163969 0.0163969 2 1 
+0.000828789 0.0163731 0.0163731 2 1 
+0.000829237 0.0163494 0.0163494 2 1 
+0.000829684 0.0163257 0.0163257 2 1 
+0.000830129 0.0163019 0.0163019 2 1 
+0.000830574 0.0162782 0.0162782 2 1 
+0.000831018 0.0162544 0.0162544 2 1 
+0.000831461 0.0162306 0.0162306 2 1 
+0.000831903 0.0162068 0.0162068 2 1 
+0.000832344 0.016183 0.016183 2 1 
+0.000832784 0.0161592 0.0161592 2 1 
+0.000833224 0.0161354 0.0161354 2 1 
+0.000833662 0.0161116 0.0161116 2 1 
+0.000834099 0.0160877 0.0160877 2 1 
+0.000834535 0.0160639 0.0160639 2 1 
+0.00083497 0.01604 0.01604 2 1 
+0.000835404 0.0160162 0.0160162 2 1 
+0.000835837 0.0159923 0.0159923 2 1 
+0.000836269 0.0159684 0.0159684 2 1 
+0.0008367 0.0159445 0.0159445 2 1 
+0.00083713 0.0159206 0.0159206 2 1 
+0.000837559 0.0158967 0.0158967 2 1 
+0.000837986 0.0158728 0.0158728 2 1 
+0.000838413 0.0158489 0.0158489 2 1 
+0.000838838 0.0158249 0.0158249 2 1 
+0.000839263 0.015801 0.015801 2 1 
+0.000839686 0.015777 0.015777 2 1 
+0.000840109 0.015753 0.015753 2 1 
+0.00084053 0.0157291 0.0157291 2 1 
+0.00084095 0.0157051 0.0157051 2 1 
+0.000841369 0.0156811 0.0156811 2 1 
+0.000841786 0.015657 0.015657 2 1 
+0.000842203 0.015633 0.015633 2 1 
+0.000842618 0.015609 0.015609 2 1 
+0.000843032 0.0155849 0.0155849 2 1 
+0.000843445 0.0155609 0.0155609 2 1 
+0.000843857 0.0155368 0.0155368 2 1 
+0.000844268 0.0155127 0.0155127 2 1 
+0.000844677 0.0154886 0.0154886 2 1 
+0.000845086 0.0154645 0.0154645 2 1 
+0.000845493 0.0154404 0.0154404 2 1 
+0.000845898 0.0154163 0.0154163 2 1 
+0.000846303 0.0153922 0.0153922 2 1 
+0.000846706 0.015368 0.015368 2 1 
+0.000847108 0.0153439 0.0153439 2 1 
+0.000847509 0.0153197 0.0153197 2 1 
+0.000847908 0.0152955 0.0152955 2 1 
+0.000848306 0.0152713 0.0152713 2 1 
+0.000848703 0.0152471 0.0152471 2 1 
+0.000849099 0.0152229 0.0152229 2 1 
+0.000849493 0.0151987 0.0151987 2 1 
+0.000849886 0.0151744 0.0151744 2 1 
+0.000850277 0.0151502 0.0151502 2 1 
+0.000850667 0.0151259 0.0151259 2 1 
+0.000851056 0.0151016 0.0151016 2 1 
+0.000851444 0.0150773 0.0150773 2 1 
+0.00085183 0.015053 0.015053 2 1 
+0.000852215 0.0150287 0.0150287 2 1 
+0.000852598 0.0150044 0.0150044 2 1 
+0.00085298 0.01498 0.01498 2 1 
+0.00085336 0.0149557 0.0149557 2 1 
+0.000853739 0.0149313 0.0149313 2 1 
+0.000854117 0.014907 0.014907 2 1 
+0.000854493 0.0148826 0.0148826 2 1 
+0.000854868 0.0148582 0.0148582 2 1 
+0.000855241 0.0148337 0.0148337 2 1 
+0.000855613 0.0148093 0.0148093 2 1 
+0.000855983 0.0147849 0.0147849 2 1 
+0.000856352 0.0147604 0.0147604 2 1 
+0.000856719 0.0147359 0.0147359 2 1 
+0.000857084 0.0147115 0.0147115 2 1 
+0.000857449 0.014687 0.014687 2 1 
+0.000857811 0.0146625 0.0146625 2 1 
+0.000858172 0.0146379 0.0146379 2 1 
+0.000858532 0.0146134 0.0146134 2 1 
+0.00085889 0.0145889 0.0145889 2 1 
+0.000859246 0.0145643 0.0145643 2 1 
+0.000859601 0.0145397 0.0145397 2 1 
+0.000859954 0.0145151 0.0145151 2 1 
+0.000860305 0.0144905 0.0144905 2 1 
+0.000860655 0.0144659 0.0144659 2 1 
+0.000861003 0.0144413 0.0144413 2 1 
+0.00086135 0.0144166 0.0144166 2 1 
+0.000861695 0.014392 0.014392 2 1 
+0.000862038 0.0143673 0.0143673 2 1 
+0.000862379 0.0143426 0.0143426 2 1 
+0.000862719 0.0143179 0.0143179 2 1 
+0.000863057 0.0142932 0.0142932 2 1 
+0.000863393 0.0142684 0.0142684 2 1 
+0.000863728 0.0142437 0.0142437 2 1 
+0.000864061 0.0142189 0.0142189 2 1 
+0.000864392 0.0141942 0.0141942 2 1 
+0.000864721 0.0141694 0.0141694 2 1 
+0.000865048 0.0141446 0.0141446 2 1 
+0.000865374 0.0141197 0.0141197 2 1 
+0.000865698 0.0140949 0.0140949 2 1 
+0.00086602 0.0140701 0.0140701 2 1 
+0.00086634 0.0140452 0.0140452 2 1 
+0.000866658 0.0140203 0.0140203 2 1 
+0.000866975 0.0139954 0.0139954 2 1 
+0.000867289 0.0139705 0.0139705 2 1 
+0.000867602 0.0139456 0.0139456 2 1 
+0.000867912 0.0139206 0.0139206 2 1 
+0.000868221 0.0138957 0.0138957 2 1 
+0.000868528 0.0138707 0.0138707 2 1 
+0.000868833 0.0138457 0.0138457 2 1 
+0.000869136 0.0138207 0.0138207 2 1 
+0.000869437 0.0137957 0.0137957 2 1 
+0.000869736 0.0137707 0.0137707 2 1 
+0.000870033 0.0137456 0.0137456 2 1 
+0.000870328 0.0137206 0.0137206 2 1 
+0.00087062 0.0136955 0.0136955 2 1 
+0.000870911 0.0136704 0.0136704 2 1 
+0.0008712 0.0136453 0.0136453 2 1 
+0.000871487 0.0136201 0.0136201 2 1 
+0.000871771 0.013595 0.013595 2 1 
+0.000872054 0.0135698 0.0135698 2 1 
+0.000872334 0.0135446 0.0135446 2 1 
+0.000872612 0.0135194 0.0135194 2 1 
+0.000872888 0.0134942 0.0134942 2 1 
+0.000873162 0.013469 0.013469 2 1 
+0.000873434 0.0134437 0.0134437 2 1 
+0.000873703 0.0134185 0.0134185 2 1 
+0.00087397 0.0133932 0.0133932 2 1 
+0.000874235 0.0133679 0.0133679 2 1 
+0.000874498 0.0133426 0.0133426 2 1 
+0.000874759 0.0133173 0.0133173 2 1 
+0.000875017 0.0132919 0.0132919 2 1 
+0.000875273 0.0132666 0.0132666 2 1 
+0.000875526 0.0132412 0.0132412 2 1 
+0.000875778 0.0132158 0.0132158 2 1 
+0.000876027 0.0131904 0.0131904 2 1 
+0.000876273 0.0131649 0.0131649 2 1 
+0.000876517 0.0131395 0.0131395 2 1 
+0.000876759 0.013114 0.013114 2 1 
+0.000876999 0.0130885 0.0130885 2 1 
+0.000877235 0.013063 0.013063 2 1 
+0.00087747 0.0130375 0.0130375 2 1 
+0.000877702 0.0130119 0.0130119 2 1 
+0.000877932 0.0129864 0.0129864 2 1 
+0.000878159 0.0129608 0.0129608 2 1 
+0.000878383 0.0129352 0.0129352 2 1 
+0.000878605 0.0129096 0.0129096 2 1 
+0.000878825 0.012884 0.012884 2 1 
+0.000879042 0.0128583 0.0128583 2 1 
+0.000879256 0.0128327 0.0128327 2 1 
+0.000879467 0.012807 0.012807 2 1 
+0.000879677 0.0127813 0.0127813 2 1 
+0.000879883 0.0127556 0.0127556 2 1 
+0.000880087 0.0127298 0.0127298 2 1 
+0.000880288 0.0127041 0.0127041 2 1 
+0.000880486 0.0126783 0.0126783 2 1 
+0.000880682 0.0126525 0.0126525 2 1 
+0.000880875 0.0126267 0.0126267 2 1 
+0.000881065 0.0126008 0.0126008 2 1 
+0.000881252 0.012575 0.012575 2 1 
+0.000881437 0.0125491 0.0125491 2 1 
+0.000881619 0.0125232 0.0125232 2 1 
+0.000881797 0.0124973 0.0124973 2 1 
+0.000881974 0.0124714 0.0124714 2 1 
+0.000882147 0.0124454 0.0124454 2 1 
+0.000882317 0.0124195 0.0124195 2 1 
+0.000882484 0.0123935 0.0123935 2 1 
+0.000882649 0.0123675 0.0123675 2 1 
+0.00088281 0.0123415 0.0123415 2 1 
+0.000882969 0.0123154 0.0123154 2 1 
+0.000883124 0.0122893 0.0122893 2 1 
+0.000883277 0.0122633 0.0122633 2 1 
+0.000883426 0.0122372 0.0122372 2 1 
+0.000883572 0.012211 0.012211 2 1 
+0.000883716 0.0121849 0.0121849 2 1 
+0.000883856 0.0121587 0.0121587 2 1 
+0.000883993 0.0121325 0.0121325 2 1 
+0.000884127 0.0121063 0.0121063 2 1 
+0.000884257 0.0120801 0.0120801 2 1 
+0.000884385 0.0120539 0.0120539 2 1 
+0.000884509 0.0120276 0.0120276 2 1 
+0.00088463 0.0120013 0.0120013 2 1 
+0.000884748 0.011975 0.011975 2 1 
+0.000884862 0.0119487 0.0119487 2 1 
+0.000884973 0.0119223 0.0119223 2 1 
+0.000885081 0.011896 0.011896 2 1 
+0.000885185 0.0118696 0.0118696 2 1 
+0.000885286 0.0118432 0.0118432 2 1 
+0.000885384 0.0118167 0.0118167 2 1 
+0.000885478 0.0117903 0.0117903 2 1 
+0.000885569 0.0117638 0.0117638 2 1 
+0.000885656 0.0117373 0.0117373 2 1 
+0.00088574 0.0117108 0.0117108 2 1 
+0.00088582 0.0116843 0.0116843 2 1 
+0.000885896 0.0116577 0.0116577 2 1 
+0.000885969 0.0116312 0.0116312 2 1 
+0.000886039 0.0116046 0.0116046 2 1 
+0.000886104 0.0115779 0.0115779 2 1 
+0.000886166 0.0115513 0.0115513 2 1 
+0.000886225 0.0115246 0.0115246 2 1 
+0.000886279 0.0114979 0.0114979 2 1 
+0.00088633 0.0114712 0.0114712 2 1 
+0.000886377 0.0114445 0.0114445 2 1 
+0.000886421 0.0114178 0.0114178 2 1 
+0.00088646 0.011391 0.011391 2 1 
+0.000886496 0.0113642 0.0113642 2 1 
+0.000886528 0.0113374 0.0113374 2 1 
+0.000886555 0.0113105 0.0113105 2 1 
+0.000886579 0.0112837 0.0112837 2 1 
+0.000886599 0.0112568 0.0112568 2 1 
+0.000886615 0.0112299 0.0112299 2 1 
+0.000886627 0.011203 0.011203 2 1 
+0.000886635 0.011176 0.011176 2 1 
+0.000886638 0.0111491 0.0111491 2 1 
+0.000886639 0.0111383 0.0111383 2 1 
+0.000886637 0.0111113 0.0111113 1 1 
+0.00088663 0.0110843 0.0110843 1 1 
+0.00088662 0.0110573 0.0110573 1 1 
+0.000886605 0.0110302 0.0110302 1 1 
+0.000886586 0.0110031 0.0110031 1 1 
+0.000886563 0.010976 0.010976 1 1 
+0.000886536 0.0109488 0.0109488 1 1 
+0.000886504 0.0109217 0.0109217 1 1 
+0.000886468 0.0108945 0.0108945 1 1 
+0.000886427 0.0108673 0.0108673 1 1 
+0.000886382 0.0108401 0.0108401 1 1 
+0.000886332 0.0108128 0.0108128 1 1 
+0.000886278 0.0107855 0.0107855 1 1 
+0.00088622 0.0107582 0.0107582 1 1 
+0.000886156 0.0107309 0.0107309 1 1 
+0.000886088 0.0107036 0.0107036 1 1 
+0.000886016 0.0106762 0.0106762 1 1 
+0.000885939 0.0106488 0.0106488 1 1 
+0.000885857 0.0106214 0.0106214 1 1 
+0.00088577 0.0105939 0.0105939 1 1 
+0.000885679 0.0105665 0.0105665 1 1 
+0.000885583 0.010539 0.010539 1 1 
+0.000885482 0.0105115 0.0105115 1 1 
+0.000885376 0.0104839 0.0104839 1 1 
+0.000885265 0.0104564 0.0104564 1 1 
+0.000885149 0.0104288 0.0104288 1 1 
+0.000885028 0.0104012 0.0104012 1 1 
+0.000884902 0.0103736 0.0103736 1 1 
+0.000884771 0.0103459 0.0103459 1 1 
+0.000884635 0.0103182 0.0103182 1 1 
+0.000884494 0.0102905 0.0102905 1 1 
+0.000884347 0.0102628 0.0102628 1 1 
+0.000884195 0.010235 0.010235 1 1 
+0.000884039 0.0102073 0.0102073 1 1 
+0.000883876 0.0101795 0.0101795 1 1 
+0.000883709 0.0101516 0.0101516 1 1 
+0.000883536 0.0101238 0.0101238 1 1 
+0.000883357 0.0100959 0.0100959 1 1 
+0.000883173 0.010068 0.010068 1 1 
+0.000882984 0.0100401 0.0100401 1 1 
+0.000882789 0.0100121 0.0100121 1 1 
+0.000882588 0.00998416 0.00998416 1 1 
+0.000882382 0.00995616 0.00995616 1 1 
+0.00088217 0.00992814 0.00992814 1 1 
+0.000881952 0.00990009 0.00990009 1 1 
+0.000881729 0.00987202 0.00987202 1 1 
+0.0008815 0.00984392 0.00984392 1 1 
+0.000881265 0.0098158 0.0098158 1 1 
+0.000881024 0.00978765 0.00978765 1 1 
+0.000880777 0.00975947 0.00975947 1 1 
+0.000880524 0.00973128 0.00973128 1 1 
+0.000880265 0.00970305 0.00970305 1 1 
+0.00088 0.0096748 0.0096748 1 1 
+0.000879729 0.00964653 0.00964653 1 1 
+0.000879451 0.00961823 0.00961823 1 1 
+0.000879168 0.00958991 0.00958991 1 1 
+0.000878878 0.00956156 0.00956156 1 1 
+0.000878582 0.00953318 0.00953318 1 1 
+0.000878279 0.00950478 0.00950478 1 1 
+0.000877971 0.00947636 0.00947636 1 1 
+0.000877655 0.0094479 0.0094479 1 1 
+0.000877333 0.00941943 0.00941943 1 1 
+0.000877005 0.00939092 0.00939092 1 1 
+0.00087667 0.0093624 0.0093624 1 1 
+0.000876328 0.00933384 0.00933384 1 1 
+0.00087598 0.00930526 0.00930526 1 1 
+0.000875625 0.00927666 0.00927666 1 1 
+0.000875263 0.00924803 0.00924803 1 1 
+0.000874894 0.00921937 0.00921937 1 1 
+0.000874518 0.00919069 0.00919069 1 1 
+0.000874135 0.00916198 0.00916198 1 1 
+0.000873746 0.00913325 0.00913325 1 1 
+0.000873349 0.00910449 0.00910449 1 1 
+0.000872945 0.0090757 0.0090757 1 1 
+0.000872534 0.00904689 0.00904689 1 1 
+0.000872115 0.00901806 0.00901806 1 1 
+0.000871689 0.00898919 0.00898919 1 1 
+0.000871256 0.00896031 0.00896031 1 1 
+0.000870816 0.00893139 0.00893139 1 1 
+0.000870368 0.00890245 0.00890245 1 1 
+0.000869913 0.00887349 0.00887349 1 1 
+0.000869449 0.00884449 0.00884449 1 1 
+0.000868979 0.00881548 0.00881548 1 1 
+0.0008685 0.00878643 0.00878643 1 1 
+0.000868014 0.00875736 0.00875736 1 1 
+0.00086752 0.00872827 0.00872827 1 1 
+0.000867018 0.00869915 0.00869915 1 1 
+0.000866509 0.00867 0.00867 1 1 
+0.000865991 0.00864083 0.00864083 1 1 
+0.000865465 0.00861163 0.00861163 1 1 
+0.000864931 0.0085824 0.0085824 1 1 
+0.000864389 0.00855315 0.00855315 1 1 
+0.000863838 0.00852388 0.00852388 1 1 
+0.00086328 0.00849458 0.00849458 1 1 
+0.000862713 0.00846525 0.00846525 1 1 
+0.000862137 0.00843589 0.00843589 1 1 
+0.000861553 0.00840652 0.00840652 1 1 
+0.00086096 0.00837711 0.00837711 1 1 
+0.000860359 0.00834768 0.00834768 1 1 
+0.000859749 0.00831822 0.00831822 1 1 
+0.00085913 0.00828874 0.00828874 1 1 
+0.000858503 0.00825923 0.00825923 1 1 
+0.000857866 0.0082297 0.0082297 1 1 
+0.000857221 0.00820014 0.00820014 1 1 
+0.000856566 0.00817056 0.00817056 1 1 
+0.000855903 0.00814095 0.00814095 1 1 
+0.00085523 0.00811132 0.00811132 1 1 
+0.000854548 0.00808166 0.00808166 1 1 
+0.000853856 0.00805197 0.00805197 1 1 
+0.000853156 0.00802226 0.00802226 1 1 
+0.000852445 0.00799253 0.00799253 1 1 
+0.000851726 0.00796277 0.00796277 1 1 
+0.000850996 0.00793298 0.00793298 1 1 
+0.000850257 0.00790317 0.00790317 1 1 
+0.000849508 0.00787333 0.00787333 1 1 
+0.00084875 0.00784347 0.00784347 1 1 
+0.000847981 0.00781359 0.00781359 1 1 
+0.000847202 0.00778368 0.00778368 1 1 
+0.000846414 0.00775375 0.00775375 1 1 
+0.000845615 0.00772379 0.00772379 1 1 
+0.000844806 0.00769381 0.00769381 1 1 
+0.000843986 0.0076638 0.0076638 1 1 
+0.000843157 0.00763377 0.00763377 1 1 
+0.000842317 0.00760371 0.00760371 1 1 
+0.000841466 0.00757363 0.00757363 1 1 
+0.000840605 0.00754353 0.00754353 1 1 
+0.000839733 0.0075134 0.0075134 1 1 
+0.00083885 0.00748325 0.00748325 1 1 
+0.000837956 0.00745308 0.00745308 1 1 
+0.000837052 0.00742288 0.00742288 1 1 
+0.000836136 0.00739266 0.00739266 1 1 
+0.000835209 0.00736242 0.00736242 1 1 
+0.000834272 0.00733215 0.00733215 1 1 
+0.000833323 0.00730186 0.00730186 1 1 
+0.000832362 0.00727155 0.00727155 1 1 
+0.00083139 0.00724122 0.00724122 1 1 
+0.000830407 0.00721086 0.00721086 1 1 
+0.000829412 0.00718048 0.00718048 1 1 
+0.000828405 0.00715008 0.00715008 1 1 
+0.000827387 0.00711966 0.00711966 1 1 
+0.000826356 0.00708922 0.00708922 1 1 
+0.000825314 0.00705875 0.00705875 1 1 
+0.00082426 0.00702826 0.00702826 1 1 
+0.000823193 0.00699775 0.00699775 1 1 
+0.000822115 0.00696723 0.00696723 1 1 
+0.000821024 0.00693668 0.00693668 1 1 
+0.00081992 0.00690611 0.00690611 1 1 
+0.000818804 0.00687552 0.00687552 1 1 
+0.000817676 0.00684491 0.00684491 1 1 
+0.000816535 0.00681428 0.00681428 1 1 
+0.000815381 0.00678363 0.00678363 1 1 
+0.000814215 0.00675296 0.00675296 1 1 
+0.000813035 0.00672227 0.00672227 1 1 
+0.000811842 0.00669157 0.00669157 1 1 
+0.000810637 0.00666084 0.00666084 1 1 
+0.000809418 0.0066301 0.0066301 1 1 
+0.000808186 0.00659934 0.00659934 1 1 
+0.00080694 0.00656856 0.00656856 1 1 
+0.000805681 0.00653776 0.00653776 1 1 
+0.000804408 0.00650695 0.00650695 1 1 
+0.000803122 0.00647612 0.00647612 1 1 
+0.000801822 0.00644527 0.00644527 1 1 
+0.000800508 0.00641441 0.00641441 1 1 
+0.00079918 0.00638353 0.00638353 1 1 
+0.000797838 0.00635264 0.00635264 1 1 
+0.000796482 0.00632173 0.00632173 1 1 
+0.000795112 0.0062908 0.0062908 1 1 
+0.000793727 0.00625987 0.00625987 1 1 
+0.000792328 0.00622891 0.00622891 1 1 
+0.000790914 0.00619795 0.00619795 1 1 
+0.000789486 0.00616697 0.00616697 1 1 
+0.000788043 0.00613598 0.00613598 1 1 
+0.000786586 0.00610497 0.00610497 1 1 
+0.000785113 0.00607395 0.00607395 1 1 
+0.000783626 0.00604293 0.00604293 1 1 
+0.000782123 0.00601189 0.00601189 1 1 
+0.000780605 0.00598084 0.00598084 1 1 
+0.000779072 0.00594977 0.00594977 1 1 
+0.000777524 0.0059187 0.0059187 1 1 
+0.00077596 0.00588762 0.00588762 1 1 
+0.000774381 0.00585653 0.00585653 1 1 
+0.000772786 0.00582544 0.00582544 1 1 
+0.000771175 0.00579433 0.00579433 1 1 
+0.000769548 0.00576322 0.00576322 1 1 
+0.000767906 0.0057321 0.0057321 1 1 
+0.000766247 0.00570097 0.00570097 1 1 
+0.000764572 0.00566984 0.00566984 1 1 
+0.000762882 0.0056387 0.0056387 1 1 
+0.000761175 0.00560755 0.00560755 1 1 
+0.000759451 0.0055764 0.0055764 1 1 
+0.000757711 0.00554525 0.00554525 1 1 
+0.000755955 0.0055141 0.0055141 1 1 
+0.000754182 0.00548294 0.00548294 1 1 
+0.000752392 0.00545178 0.00545178 1 1 
+0.000750585 0.00542062 0.00542062 1 1 
+0.000748762 0.00538946 0.00538946 1 1 
+0.000746921 0.00535829 0.00535829 1 1 
+0.000745064 0.00532713 0.00532713 1 1 
+0.000743189 0.00529597 0.00529597 1 1 
+0.000741297 0.00526481 0.00526481 1 1 
+0.000739388 0.00523366 0.00523366 1 1 
+0.000737461 0.0052025 0.0052025 1 1 
+0.000735517 0.00517135 0.00517135 1 1 
+0.000733555 0.00514021 0.00514021 1 1 
+0.000731576 0.00510907 0.00510907 1 1 
+0.000729579 0.00507793 0.00507793 1 1 
+0.000727564 0.0050468 0.0050468 1 1 
+0.000725531 0.00501568 0.00501568 1 1 
+0.000723481 0.00498457 0.00498457 1 1 
+0.000721412 0.00495347 0.00495347 1 1 
+0.000719326 0.00492237 0.00492237 1 1 
+0.000717221 0.00489129 0.00489129 1 1 
+0.000715098 0.00486021 0.00486021 1 1 
+0.000712957 0.00482915 0.00482915 1 1 
+0.000710797 0.0047981 0.0047981 1 1 
+0.000708619 0.00476707 0.00476707 1 1 
+0.000706422 0.00473605 0.00473605 1 1 
+0.000704207 0.00470504 0.00470504 1 1 
+0.000701974 0.00467405 0.00467405 1 1 
+0.000699722 0.00464308 0.00464308 1 1 
+0.000697451 0.00461213 0.00461213 1 1 
+0.000695161 0.00458119 0.00458119 1 1 
+0.000692853 0.00455027 0.00455027 1 1 
+0.000690525 0.00451937 0.00451937 1 1 
+0.000688179 0.0044885 0.0044885 1 1 
+0.000685814 0.00445764 0.00445764 1 1 
+0.00068343 0.00442681 0.00442681 1 1 
+0.000681027 0.00439601 0.00439601 1 1 
+0.000678604 0.00436522 0.00436522 1 1 
+0.000676163 0.00433447 0.00433447 1 1 
+0.000673703 0.00430374 0.00430374 1 1 
+0.000671223 0.00427304 0.00427304 1 1 
+0.000668724 0.00424236 0.00424236 1 1 
+0.000666206 0.00421172 0.00421172 1 1 
+0.000663669 0.0041811 0.0041811 1 1 
+0.000661113 0.00415052 0.00415052 1 1 
+0.000658537 0.00411997 0.00411997 1 1 
+0.000655942 0.00408945 0.00408945 1 1 
+0.000653327 0.00405897 0.00405897 1 1 
+0.000650693 0.00402852 0.00402852 1 1 
+0.00064804 0.00399811 0.00399811 1 1 
+0.000645368 0.00396774 0.00396774 1 1 
+0.000642676 0.0039374 0.0039374 1 1 
+0.000639965 0.0039071 0.0039071 1 1 
+0.000637234 0.00387685 0.00387685 1 1 
+0.000634484 0.00384663 0.00384663 1 1 
+0.000631715 0.00381646 0.00381646 1 1 
+0.000628926 0.00378633 0.00378633 1 1 
+0.000626118 0.00375624 0.00375624 1 1 
+0.00062329 0.0037262 0.0037262 1 1 
+0.000620444 0.00369621 0.00369621 1 1 
+0.000617578 0.00366626 0.00366626 1 1 
+0.000614692 0.00363636 0.00363636 1 1 
+0.000611788 0.00360651 0.00360651 1 1 
+0.000608864 0.00357671 0.00357671 1 1 
+0.000605921 0.00354696 0.00354696 1 1 
+0.000602959 0.00351726 0.00351726 1 1 
+0.000599978 0.00348762 0.00348762 1 1 
+0.000596977 0.00345803 0.00345803 1 1 
+0.000593958 0.00342849 0.00342849 1 1 
+0.000590919 0.00339901 0.00339901 1 1 
+0.000587862 0.00336959 0.00336959 1 1 
+0.000584785 0.00334023 0.00334023 1 1 
+0.00058169 0.00331092 0.00331092 1 1 
+0.000578576 0.00328168 0.00328168 1 1 
+0.000575443 0.00325249 0.00325249 1 1 
+0.000572292 0.00322337 0.00322337 1 1 
+0.000569121 0.00319431 0.00319431 1 1 
+0.000565933 0.00316531 0.00316531 1 1 
+0.000562725 0.00313638 0.00313638 1 1 
+0.000559499 0.00310751 0.00310751 1 1 
+0.000556255 0.00307871 0.00307871 1 1 
+0.000552993 0.00304998 0.00304998 1 1 
+0.000549712 0.00302132 0.00302132 1 1 
+0.000546413 0.00299272 0.00299272 1 1 
+0.000543096 0.0029642 0.0029642 1 1 
+0.000539762 0.00293574 0.00293574 1 1 
+0.000536409 0.00290736 0.00290736 1 1 
+0.000533038 0.00287905 0.00287905 1 1 
+0.00052965 0.00285081 0.00285081 1 1 
+0.000526244 0.00282264 0.00282264 1 1 
+0.00052282 0.00279456 0.00279456 1 1 
+0.000519379 0.00276654 0.00276654 1 1 
+0.000515921 0.00273861 0.00273861 1 1 
+0.000512445 0.00271075 0.00271075 1 1 
+0.000508953 0.00268296 0.00268296 1 1 
+0.000505443 0.00265526 0.00265526 1 1 
+0.000501916 0.00262764 0.00262764 1 1 
+0.000498372 0.00260009 0.00260009 1 1 
+0.000494812 0.00257263 0.00257263 1 1 
+0.000491235 0.00254525 0.00254525 1 1 
+0.000487642 0.00251795 0.00251795 1 1 
+0.000484032 0.00249074 0.00249074 1 1 
+0.000480406 0.0024636 0.0024636 1 1 
+0.000476764 0.00243655 0.00243655 1 1 
+0.000473106 0.00240959 0.00240959 1 1 
+0.000469432 0.00238271 0.00238271 1 1 
+0.000465742 0.00235592 0.00235592 1 1 
+0.000462036 0.00232921 0.00232921 1 1 
+0.000458315 0.00230259 0.00230259 1 1 
+0.000454578 0.00227606 0.00227606 1 1 
+0.000450826 0.00224961 0.00224961 1 1 
+0.000447059 0.00222326 0.00222326 1 1 
+0.000443277 0.00219699 0.00219699 1 1 
+0.00043948 0.00217081 0.00217081 1 1 
+0.000435668 0.00214472 0.00214472 1 1 
+0.000431842 0.00211873 0.00211873 1 1 
+0.000428001 0.00209282 0.00209282 1 1 
+0.000424145 0.002067 0.002067 1 1 
+0.000420275 0.00204128 0.00204128 1 1 
+0.000416391 0.00201565 0.00201565 1 1 
+0.000412494 0.00199011 0.00199011 1 1 
+0.000408582 0.00196466 0.00196466 1 1 
+0.000404656 0.0019393 0.0019393 1 1 
+0.000400717 0.00191404 0.00191404 1 1 
+0.000396764 0.00188887 0.00188887 1 1 
+0.000392798 0.0018638 0.0018638 1 1 
+0.000388819 0.00183881 0.00183881 1 1 
+0.000384827 0.00181393 0.00181393 1 1 
+0.000380822 0.00178913 0.00178913 1 1 
+0.000376804 0.00176444 0.00176444 1 1 
+0.000372773 0.00173983 0.00173983 1 1 
+0.00036873 0.00171532 0.00171532 1 1 
+0.000364674 0.00169091 0.00169091 1 1 
+0.000360606 0.00166659 0.00166659 1 1 
+0.000356526 0.00164237 0.00164237 1 1 
+0.000352434 0.00161824 0.00161824 1 1 
+0.00034833 0.00159421 0.00159421 1 1 
+0.000344214 0.00157027 0.00157027 1 1 
+0.000340087 0.00154643 0.00154643 1 1 
+0.000335948 0.00152269 0.00152269 1 1 
+0.000331798 0.00149904 0.00149904 1 1 
+0.000327637 0.00147549 0.00147549 1 1 
+0.000323464 0.00145203 0.00145203 1 1 
+0.000319281 0.00142867 0.00142867 1 1 
+0.000315087 0.00140541 0.00140541 1 1 
+0.000310882 0.00138224 0.00138224 1 1 
+0.000306666 0.00135916 0.00135916 1 1 
+0.00030244 0.00133619 0.00133619 1 1 
+0.000298204 0.00131331 0.00131331 1 1 
+0.000293957 0.00129052 0.00129052 1 1 
+0.0002897 0.00126783 0.00126783 1 1 
+0.000285434 0.00124524 0.00124524 1 1 
+0.000281157 0.00122274 0.00122274 1 1 
+0.000276871 0.00120033 0.00120033 1 1 
+0.000272576 0.00117803 0.00117803 1 1 
+0.00026827 0.00115581 0.00115581 1 1 
+0.000263956 0.00113369 0.00113369 1 1 
+0.000259632 0.00111167 0.00111167 1 1 
+0.000255299 0.00108974 0.00108974 1 1 
+0.000250957 0.00106791 0.00106791 1 1 
+0.000246607 0.00104617 0.00104617 1 1 
+0.000242247 0.00102452 0.00102452 1 1 
+0.000237879 0.00100297 0.00100297 1 1 
+0.000233502 0.000981511 0.000981511 1 1 
+0.000229117 0.000960147 0.000960147 1 1 
+0.000224724 0.000938875 0.000938875 1 1 
+0.000220322 0.000917697 0.000917697 1 1 
+0.000215912 0.000896611 0.000896611 1 1 
+0.000211494 0.000875619 0.000875619 1 1 
+0.000207069 0.000854718 0.000854718 1 1 
+0.000202635 0.000833909 0.000833909 1 1 
+0.000198194 0.000813193 0.000813193 1 1 
+0.000193746 0.000792567 0.000792567 1 1 
+0.00018929 0.000772034 0.000772034 1 1 
+0.000184826 0.000751591 0.000751591 1 1 
+0.000180355 0.000731238 0.000731238 1 1 
+0.000175877 0.000710976 0.000710976 1 1 
+0.000171393 0.000690805 0.000690805 1 1 
+0.000166901 0.000670723 0.000670723 1 1 
+0.000162402 0.00065073 0.00065073 1 1 
+0.000157896 0.000630827 0.000630827 1 1 
+0.000153384 0.000611012 0.000611012 1 1 
+0.000148865 0.000591286 0.000591286 1 1 
+0.00014434 0.000571648 0.000571648 1 1 
+0.000139808 0.000552098 0.000552098 1 1 
+0.00013527 0.000532636 0.000532636 1 1 
+0.000130726 0.000513261 0.000513261 1 1 
+0.000126175 0.000493972 0.000493972 1 1 
+0.000121619 0.00047477 0.00047477 1 1 
+0.000117056 0.000455654 0.000455654 1 1 
+0.000112488 0.000436624 0.000436624 1 1 
+0.000107914 0.000417679 0.000417679 1 1 
+0.000103334 0.00039882 0.00039882 1 1 
+9.87483e-05 0.000380045 0.000380045 1 1 
+9.41572e-05 0.000361354 0.000361354 1 1 
+8.95607e-05 0.000342747 0.000342747 1 1 
+8.49587e-05 0.000324224 0.000324224 1 1 
+8.03515e-05 0.000305784 0.000305784 1 1 
+7.5739e-05 0.000287427 0.000287427 1 1 
+7.11213e-05 0.000269152 0.000269152 1 1 
+6.64985e-05 0.00025096 0.00025096 1 1 
+6.18707e-05 0.000232849 0.000232849 1 1 
+5.7238e-05 0.000214819 0.000214819 1 1 
+5.26003e-05 0.000196871 0.000196871 1 1 
+4.79579e-05 0.000179002 0.000179002 1 1 
+4.33107e-05 0.000161214 0.000161214 1 1 
+3.86589e-05 0.000143506 0.000143506 1 1 
+3.40025e-05 0.000125877 0.000125877 1 1 
+2.93415e-05 0.000108327 0.000108327 1 1 
+2.46761e-05 9.08561e-05 9.08561e-05 1 1 
+2.00062e-05 7.34631e-05 7.34631e-05 1 1 
+1.53321e-05 5.61478e-05 5.61478e-05 1 1 
+1.06536e-05 3.89099e-05 3.89099e-05 1 1 
+5.97094e-06 2.17491e-05 2.17491e-05 1 1 
+1.28413e-06 4.66493e-06 4.66493e-06 1 1 
+0.00258646 0.0672374 0.0672374 4 7 
+0.00258645 0.0672506 0.067224 4 7 
+0.00258645 0.0672571 0.0672175 3 7 
+0.00258648 0.0673102 0.0671642 3 7 
+0.00258661 0.067416 0.0670572 3 7 
+0.00258692 0.0675476 0.0669228 3 7 
+0.00258741 0.0676785 0.0667875 3 7 
+0.00258806 0.0678085 0.0666515 3 7 
+0.00258888 0.0679378 0.0665147 3 7 
+0.00258987 0.0680663 0.0663771 3 7 
+0.00259103 0.0681941 0.0662388 3 7 
+0.00259235 0.0683211 0.0660997 3 7 
+0.00259383 0.0684472 0.0659598 3 7 
+0.00259546 0.0685726 0.0658191 3 7 
+0.00259726 0.0686974 0.0656776 3 7 
+0.0025992 0.0688214 0.0655355 3 7 
+0.0026013 0.0689447 0.0653924 3 7 
+0.00260354 0.0690673 0.0652486 3 7 
+0.00260593 0.069189 0.0651041 3 7 
+0.00260846 0.0693101 0.0649587 3 7 
+0.00261112 0.0694306 0.0648126 3 7 
+0.00261392 0.0695506 0.0646657 3 7 
+0.00261685 0.0696696 0.064518 3 7 
+0.0026199 0.069788 0.0643696 3 7 
+0.00262307 0.0699056 0.0642204 3 7 
+0.00262636 0.0700227 0.0640704 3 7 
+0.00262976 0.0701391 0.0639197 3 7 
+0.00263327 0.070255 0.0637682 3 7 
+0.00263688 0.0703702 0.063616 3 7 
+0.0026406 0.0704847 0.063463 3 7 
+0.00264441 0.0705986 0.0633091 3 7 
+0.00264832 0.070712 0.0631543 3 7 
+0.00265231 0.0708248 0.0629988 3 7 
+0.00265639 0.0709368 0.0628424 3 7 
+0.00266055 0.0710485 0.0626854 3 7 
+0.00266478 0.0711597 0.0625277 3 7 
+0.00266909 0.0712701 0.0623692 3 7 
+0.00267347 0.0713801 0.0622099 3 7 
+0.00267791 0.0714896 0.0620499 3 7 
+0.00268242 0.0715994 0.0618891 3 7 
+0.00268698 0.0717081 0.0617276 3 7 
+0.0026916 0.0718162 0.0615654 3 7 
+0.00269628 0.0719238 0.0614022 3 7 
+0.002701 0.0720311 0.0612385 3 7 
+0.00270577 0.0721378 0.061074 3 7 
+0.00271058 0.0722438 0.0609087 3 7 
+0.00271544 0.0723498 0.0607426 3 7 
+0.00272033 0.0724554 0.0605758 3 7 
+0.00272526 0.0725608 0.0604083 3 7 
+0.00273022 0.0726654 0.06024 3 7 
+0.00273521 0.0727697 0.0600711 3 7 
+0.00274023 0.0728739 0.0599015 3 7 
+0.00274528 0.0729775 0.0597312 3 7 
+0.00275035 0.0730807 0.0595603 3 7 
+0.00275544 0.0731837 0.0593889 3 7 
+0.00276055 0.0732863 0.0592168 3 7 
+0.00276569 0.0733885 0.059044 3 7 
+0.00277083 0.0734903 0.0588709 3 7 
+0.002776 0.0735918 0.0586967 3 7 
+0.00278118 0.073693 0.0585218 3 7 
+0.00278637 0.0737943 0.0583467 3 7 
+0.00279156 0.0738949 0.0581707 3 7 
+0.00279677 0.0739953 0.0579941 3 7 
+0.00280199 0.0740947 0.057817 3 7 
+0.00280721 0.0741945 0.0576393 3 7 
+0.00281243 0.0742941 0.0574611 3 7 
+0.00281766 0.0743929 0.0572825 3 7 
+0.00282289 0.0744916 0.0571032 3 7 
+0.00282812 0.0745902 0.0569235 3 7 
+0.00283335 0.0746882 0.0567433 3 7 
+0.00283858 0.0747865 0.0565626 3 7 
+0.0028438 0.0748845 0.0563815 3 7 
+0.00284902 0.0749827 0.0561999 3 7 
+0.00285424 0.0750799 0.0560179 3 7 
+0.00285944 0.0751769 0.0558354 3 7 
+0.00286464 0.0752746 0.0556526 3 7 
+0.00286983 0.0753713 0.0554693 3 7 
+0.00287501 0.0754679 0.0552857 3 7 
+0.00288017 0.0755645 0.0551018 3 7 
+0.00288533 0.0756605 0.0549174 3 7 
+0.00289047 0.0757563 0.0547326 3 7 
+0.00289559 0.0758502 0.0545476 3 7 
+0.0029007 0.0759457 0.054362 3 7 
+0.00290579 0.076041 0.054176 3 7 
+0.00291086 0.0761355 0.0539897 3 7 
+0.00291591 0.0762303 0.0538032 3 7 
+0.00292094 0.076325 0.0536163 3 7 
+0.00292594 0.0764206 0.0534291 3 7 
+0.00293092 0.0765147 0.0532418 3 7 
+0.00293588 0.0766086 0.0530541 3 7 
+0.00294081 0.0766994 0.0528662 3 7 
+0.00294571 0.0767925 0.052678 3 7 
+0.00295059 0.0768857 0.0524897 3 7 
+0.00295543 0.0769818 0.0523011 3 7 
+0.00296024 0.0770747 0.0521123 3 7 
+0.00296502 0.0771673 0.0519233 3 7 
+0.00296976 0.0772586 0.0517342 3 7 
+0.00297447 0.077351 0.0515449 3 7 
+0.00297914 0.0774431 0.0513554 3 7 
+0.00298377 0.077533 0.0511658 3 7 
+0.00298836 0.0776243 0.050976 3 7 
+0.00299291 0.0777153 0.0507862 3 7 
+0.00299742 0.0778092 0.0505963 3 7 
+0.00300188 0.0779 0.0504062 3 7 
+0.00300629 0.0779906 0.050216 3 7 
+0.00301066 0.0780818 0.0500259 3 7 
+0.00301497 0.078172 0.0498355 3 7 
+0.00301924 0.078262 0.0496451 3 7 
+0.00302345 0.0783524 0.0494548 3 7 
+0.0030276 0.0784421 0.0492643 3 7 
+0.0030317 0.0785316 0.0490738 3 7 
+0.00303574 0.0786206 0.0488833 3 7 
+0.00303972 0.0787095 0.0486928 3 7 
+0.00304364 0.0787982 0.0485023 3 7 
+0.00304749 0.0788865 0.0483118 3 7 
+0.00305128 0.0789746 0.0481214 3 7 
+0.003055 0.0790625 0.0479311 3 7 
+0.00305865 0.0791506 0.0477408 3 7 
+0.00306223 0.0792379 0.0475506 3 7 
+0.00306574 0.079325 0.0473605 3 7 
+0.00306917 0.0794097 0.0471706 3 7 
+0.00307252 0.079496 0.0469807 3 7 
+0.00307579 0.0795819 0.0467911 3 7 
+0.00307898 0.079672 0.0466016 3 7 
+0.00308208 0.0797578 0.0464123 3 7 
+0.0030851 0.0798433 0.0462231 3 7 
+0.00308803 0.0799248 0.0460342 3 7 
+0.00309086 0.0800101 0.0458456 3 7 
+0.00309361 0.080095 0.0456572 3 7 
+0.00309626 0.0801801 0.0454691 3 7 
+0.00309881 0.0802643 0.0452813 3 7 
+0.00310126 0.0803481 0.0450938 3 7 
+0.00310361 0.0804297 0.0449066 3 7 
+0.00310585 0.0805129 0.0447198 3 7 
+0.00310799 0.0805956 0.0445334 3 7 
+0.00311001 0.0806798 0.0443474 3 7 
+0.00311193 0.0807614 0.0441619 3 7 
+0.00311373 0.0808425 0.0439768 3 7 
+0.00311542 0.0809222 0.0437921 3 7 
+0.00311699 0.0810021 0.043608 3 7 
+0.00311844 0.0810815 0.0434245 3 7 
+0.00311976 0.0811606 0.0432415 3 7 
+0.00312096 0.0812397 0.0430591 3 7 
+0.00312204 0.0813184 0.0428773 3 7 
+0.00312298 0.0813969 0.0426961 3 7 
+0.0031238 0.0814743 0.0425157 3 7 
+0.00312448 0.0815511 0.042336 3 7 
+0.00312503 0.0816272 0.042157 3 7 
+0.00312544 0.0817028 0.0419788 3 7 
+0.00312571 0.0817776 0.0418014 3 7 
+0.00312585 0.0818472 0.0416247 3 7 
+0.00312586 0.0818819 0.0415411 4 7 
+0.00312579 0.0819551 0.0413658 4 7 
+0.00312557 0.0820306 0.0411914 4 7 
+0.00312521 0.082103 0.041018 4 7 
+0.00312471 0.0821748 0.0408456 4 7 
+0.00312406 0.082246 0.0406741 4 7 
+0.00312326 0.0823155 0.0405038 4 7 
+0.00312231 0.0823842 0.0403345 4 7 
+0.00312122 0.0824492 0.0401662 4 7 
+0.00311998 0.0825175 0.0399992 4 7 
+0.00311859 0.0825849 0.0398327 4 7 
+0.00311705 0.0826508 0.0396678 4 7 
+0.00311536 0.0827166 0.0395036 4 7 
+0.00311353 0.0827815 0.0393407 4 7 
+0.00311154 0.0828463 0.0391795 4 7 
+0.00310941 0.0829085 0.0390192 4 7 
+0.00310713 0.0829697 0.0388602 4 7 
+0.00310471 0.0830255 0.0387031 4 7 
+0.00310214 0.083086 0.0385469 4 7 
+0.00309943 0.0831459 0.038392 4 7 
+0.00309658 0.0832025 0.0382391 4 7 
+0.00309358 0.0832605 0.0380871 4 7 
+0.00309044 0.0833176 0.0379366 4 7 
+0.00308717 0.0833741 0.0377883 4 7 
+0.00308376 0.0834292 0.0376407 4 7 
+0.00308022 0.0834832 0.0374946 4 7 
+0.00307655 0.0835338 0.0373508 4 7 
+0.00307274 0.0835842 0.0372077 4 7 
+0.00306881 0.0836335 0.0370661 4 7 
+0.00306475 0.0836841 0.0369255 4 7 
+0.00306057 0.0837315 0.0367872 4 7 
+0.00305627 0.0837783 0.0366503 4 7 
+0.00305185 0.0838313 0.036515 4 7 
+0.00304731 0.0838773 0.0363814 4 7 
+0.00304266 0.0839221 0.0362494 4 7 
+0.00303791 0.0839624 0.036119 4 7 
+0.00303304 0.0840041 0.0359901 4 7 
+0.00302807 0.0840448 0.0358627 4 7 
+0.00302299 0.0840911 0.035737 4 7 
+0.00301782 0.0841313 0.0356128 4 7 
+0.00301255 0.0841704 0.0354901 4 7 
+0.00300718 0.0842084 0.0353689 4 7 
+0.00300173 0.0842453 0.0352493 4 7 
+0.00299618 0.0842811 0.0351312 4 7 
+0.00299055 0.0843147 0.0350145 4 7 
+0.00298484 0.0843482 0.0348994 4 7 
+0.00297904 0.0843807 0.0347857 4 7 
+0.00297316 0.0844116 0.0346732 4 7 
+0.00296721 0.0844439 0.0345615 4 7 
+0.00296119 0.0844761 0.0344513 4 7 
+0.00295509 0.0845054 0.0343424 4 7 
+0.00294893 0.0845333 0.034235 4 7 
+0.0029427 0.0845631 0.034129 4 7 
+0.0029364 0.0845897 0.0340244 4 7 
+0.00293005 0.0846175 0.0339211 4 7 
+0.00292363 0.0846447 0.0338191 4 7 
+0.00291716 0.0846734 0.0337186 4 7 
+0.00291063 0.0846984 0.0336192 4 7 
+0.00290405 0.0847225 0.0335212 4 7 
+0.00289742 0.0847456 0.0334244 4 7 
+0.00289074 0.0847676 0.0333289 4 7 
+0.00288401 0.0847886 0.0332345 4 7 
+0.00287724 0.0848036 0.0331414 4 7 
+0.00287042 0.0848249 0.0330495 4 7 
+0.00286356 0.0848454 0.0329588 4 7 
+0.00285666 0.084867 0.0328692 4 7 
+0.00284972 0.0848854 0.0327808 4 7 
+0.00284275 0.084903 0.0326935 4 7 
+0.00283574 0.0849198 0.0326073 4 7 
+0.0028287 0.0849356 0.0325222 4 7 
+0.00282163 0.0849505 0.0324382 4 7 
+0.00281452 0.0849653 0.0323552 4 7 
+0.00280739 0.0849789 0.0322732 4 7 
+0.00280023 0.0849917 0.0321924 4 7 
+0.00279304 0.0850058 0.0321125 4 7 
+0.00278583 0.0850179 0.0320336 4 7 
+0.00277859 0.0850293 0.0319557 4 7 
+0.00277133 0.0850363 0.0318785 4 7 
+0.00276405 0.0850454 0.0318025 4 7 
+0.00275675 0.0850538 0.0317275 4 7 
+0.00274943 0.0850693 0.031653 4 7 
+0.00274209 0.0850785 0.0315791 4 7 
+0.00273473 0.085087 0.0315058 4 7 
+0.00272736 0.0850917 0.0314337 4 7 
+0.00271998 0.0850977 0.0313622 4 7 
+0.00271257 0.0851031 0.0312915 4 7 
+0.00270516 0.0851142 0.0312223 4 7 
+0.00269773 0.0851193 0.0311532 4 7 
+0.00269029 0.0851238 0.031085 4 7 
+0.00268284 0.0851292 0.0310184 4 7 
+0.00267538 0.0851327 0.0309517 4 7 
+0.00266792 0.0851355 0.0308857 4 7 
+0.00266044 0.0851361 0.0308226 4 7 
+0.00265295 0.0851374 0.030758 4 7 
+0.00264546 0.0851381 0.0306941 4 7 
+0.00263796 0.0851477 0.0306296 4 7 
+0.00263046 0.0851492 0.0305674 4 7 
+0.00262295 0.0851501 0.0305059 4 7 
+0.00261544 0.0851499 0.030445 4 7 
+0.00260792 0.0851493 0.0303849 4 7 
+0.0026004 0.0851482 0.0303255 4 7 
+0.00259287 0.0851456 0.0302668 4 7 
+0.00258535 0.0851432 0.0302087 4 7 
+0.00257782 0.0851401 0.0301513 4 7 
+0.00257029 0.0851432 0.0300946 4 7 
+0.00256276 0.0851415 0.0300384 4 7 
+0.00255523 0.0851392 0.0299829 4 7 
+0.00254771 0.0851362 0.029928 4 7 
+0.00254018 0.0851322 0.0298737 4 7 
+0.00253265 0.0851276 0.02982 4 7 
+0.00252513 0.0851234 0.0297669 4 7 
+0.0025176 0.0851179 0.0297143 4 7 
+0.00251008 0.0851119 0.0296624 4 7 
+0.00250256 0.0851051 0.029611 4 7 
+0.00249505 0.085098 0.0295598 4 7 
+0.00248754 0.0850903 0.0295085 4 7 
+0.00248003 0.0850844 0.0294577 4 7 
+0.00247253 0.0850791 0.0294075 4 7 
+0.00246503 0.0850734 0.0293579 4 7 
+0.00245754 0.0850675 0.0293085 4 7 
+0.00245005 0.0850607 0.0292599 4 7 
+0.00244257 0.0850534 0.0292118 4 7 
+0.00243509 0.0850403 0.0291644 4 7 
+0.00242762 0.0850329 0.0291173 4 7 
+0.00242015 0.085025 0.0290707 4 7 
+0.0024127 0.085019 0.0290246 4 7 
+0.00240525 0.0850095 0.0289789 4 7 
+0.0023978 0.0849994 0.0289337 4 7 
+0.00239037 0.0849892 0.028889 4 7 
+0.00238294 0.0849785 0.0288447 4 7 
+0.00237552 0.0849674 0.0288009 4 7 
+0.0023681 0.0849532 0.0287575 4 7 
+0.0023607 0.0849405 0.0287145 4 7 
+0.0023533 0.0849274 0.028672 4 7 
+0.00234592 0.084916 0.0286298 4 7 
+0.00233854 0.084905 0.0285881 4 7 
+0.00233117 0.0848936 0.0285468 4 7 
+0.00232381 0.0848796 0.0285058 4 7 
+0.00231646 0.0848676 0.0284653 4 7 
+0.00230912 0.0848552 0.0284253 4 7 
+0.00230178 0.0848398 0.0283853 4 7 
+0.00229446 0.0848269 0.028346 4 7 
+0.00228715 0.0848137 0.0283071 4 7 
+0.00227985 0.0847987 0.0282681 4 7 
+0.00227256 0.0847849 0.0282299 4 7 
+0.00226528 0.0847706 0.0281921 4 7 
+0.00225801 0.084755 0.0281541 4 7 
+0.00225075 0.0847402 0.0281161 4 7 
+0.00224351 0.0847249 0.0280784 4 7 
+0.00223627 0.0847092 0.0280409 4 7 
+0.00222905 0.0846931 0.028004 4 7 
+0.00222183 0.0846766 0.0279675 4 7 
+0.00221463 0.08466 0.0279312 4 7 
+0.00220744 0.084643 0.0278954 4 7 
+0.00220026 0.0846256 0.0278599 4 7 
+0.00219309 0.0846075 0.0278248 4 7 
+0.00218594 0.0845892 0.02779 4 7 
+0.0021788 0.0845705 0.0277555 4 7 
+0.00217167 0.084549 0.0277214 4 7 
+0.00216455 0.0845292 0.0276876 4 7 
+0.00215744 0.0845098 0.0276541 4 7 
+0.00215035 0.0844911 0.027621 4 7 
+0.00214327 0.0844738 0.0275881 4 7 
+0.0021362 0.084456 0.0275556 4 7 
+0.00212915 0.0844362 0.0275235 4 7 
+0.0021221 0.084415 0.0274916 4 7 
+0.00211507 0.0843936 0.02746 4 7 
+0.00210806 0.0843809 0.0274286 4 7 
+0.00210105 0.0843613 0.0273976 4 7 
+0.00209406 0.0843413 0.0273664 4 7 
+0.00208709 0.0843201 0.0273353 4 7 
+0.00208012 0.0842986 0.0273042 4 7 
+0.00207317 0.0842767 0.0272733 4 7 
+0.00206623 0.0842562 0.027243 4 7 
+0.00205931 0.0842339 0.0272127 4 7 
+0.0020524 0.0842112 0.0271827 4 7 
+0.0020455 0.0841904 0.0271532 4 7 
+0.00203862 0.0841673 0.0271237 4 7 
+0.00203175 0.0841439 0.0270945 4 7 
+0.0020249 0.084118 0.0270656 4 7 
+0.00201806 0.0840952 0.027037 4 7 
+0.00201123 0.0840738 0.0270087 4 7 
+0.00200442 0.0840492 0.0269807 4 7 
+0.00199762 0.0840275 0.0269529 4 7 
+0.00199083 0.0840055 0.0269254 4 7 
+0.00198406 0.0839825 0.0268982 4 7 
+0.0019773 0.0839574 0.0268712 4 7 
+0.00197056 0.0839319 0.0268444 4 7 
+0.00196383 0.0839077 0.0268179 4 7 
+0.00195712 0.083882 0.0267916 4 7 
+0.00195042 0.083859 0.0267657 4 7 
+0.00194374 0.0838385 0.0267393 4 7 
+0.00193706 0.0838145 0.0267128 4 7 
+0.00193041 0.0837902 0.0266865 4 7 
+0.00192377 0.083766 0.0266606 4 7 
+0.00191714 0.0837401 0.0266348 4 7 
+0.00191053 0.0837138 0.0266092 4 7 
+0.00190393 0.0836852 0.026584 4 7 
+0.00189735 0.083658 0.0265589 4 7 
+0.00189078 0.0836304 0.026534 4 7 
+0.00188423 0.0836029 0.0265094 4 7 
+0.00187769 0.083578 0.026485 4 7 
+0.00187117 0.0835527 0.0264608 4 7 
+0.00186466 0.0835246 0.0264369 4 7 
+0.00185817 0.083499 0.0264132 4 7 
+0.00185169 0.0834731 0.0263897 4 7 
+0.00184522 0.0834486 0.0263663 4 7 
+0.00183878 0.0834217 0.0263432 4 7 
+0.00183234 0.0833946 0.0263204 4 7 
+0.00182592 0.0833671 0.0262975 4 7 
+0.00181952 0.0833392 0.026275 4 7 
+0.00181313 0.083311 0.0262528 4 7 
+0.00180676 0.0832814 0.0262305 4 7 
+0.0018004 0.0832535 0.0262077 4 7 
+0.00179406 0.0832254 0.0261849 4 7 
+0.00178774 0.0831969 0.0261624 4 7 
+0.00178143 0.0831682 0.0261401 4 7 
+0.00177513 0.0831391 0.0261179 4 7 
+0.00176885 0.083108 0.0260963 4 7 
+0.00176258 0.0830793 0.0260745 4 7 
+0.00175634 0.0830503 0.0260529 4 7 
+0.0017501 0.0830211 0.0260316 4 7 
+0.00174388 0.0829914 0.0260104 4 7 
+0.00173768 0.0829615 0.0259894 4 7 
+0.00173149 0.0829244 0.0259686 4 7 
+0.00172532 0.0828954 0.025948 4 7 
+0.00171917 0.0828662 0.0259276 4 7 
+0.00171303 0.0828314 0.0259072 4 7 
+0.0017069 0.0828007 0.0258871 4 7 
+0.00170079 0.0827713 0.0258673 4 7 
+0.0016947 0.0827435 0.0258473 4 7 
+0.00168862 0.0827133 0.0258277 4 7 
+0.00168256 0.0826828 0.0258084 4 7 
+0.00167651 0.0826532 0.0257889 4 7 
+0.00167048 0.0826218 0.0257699 4 7 
+0.00166447 0.08259 0.02575 4 7 
+0.00165847 0.0825579 0.0257303 4 7 
+0.00165249 0.0825255 0.0257106 4 7 
+0.00164652 0.0824928 0.0256911 4 7 
+0.00164057 0.0824578 0.0256719 4 7 
+0.00163464 0.0824243 0.0256528 4 7 
+0.00162872 0.0823905 0.0256338 4 7 
+0.00162282 0.0823561 0.0256151 4 7 
+0.00161693 0.0823245 0.0255964 4 7 
+0.00161106 0.0822927 0.0255779 4 7 
+0.00160521 0.0822578 0.0255595 4 7 
+0.00159937 0.0822231 0.0255413 4 7 
+0.00159355 0.0821884 0.0255233 4 7 
+0.00158774 0.082159 0.0255053 4 7 
+0.00158195 0.0821264 0.0254876 4 7 
+0.00157618 0.0820935 0.0254701 4 7 
+0.00157042 0.0820598 0.0254525 4 7 
+0.00156468 0.0820265 0.0254353 4 7 
+0.00155896 0.0819929 0.0254182 4 7 
+0.00155325 0.0819505 0.025401 4 7 
+0.00154756 0.0819171 0.0253839 4 7 
+0.00154188 0.0818838 0.025366 4 7 
+0.00153623 0.0818486 0.0253487 4 7 
+0.00153058 0.0818149 0.0253311 4 7 
+0.00152496 0.081781 0.0253136 4 7 
+0.00151935 0.0817462 0.0252965 4 7 
+0.00151375 0.0817118 0.0252793 4 7 
+0.00150818 0.0816772 0.0252624 4 7 
+0.00150262 0.0816384 0.0252456 4 7 
+0.00149708 0.0816037 0.025229 4 7 
+0.00149155 0.0815689 0.0252125 4 7 
+0.00148604 0.0815355 0.0251961 4 7 
+0.00148054 0.0814999 0.0251798 4 7 
+0.00147507 0.0814642 0.0251638 4 7 
+0.00146961 0.081426 0.0251475 4 7 
+0.00146416 0.0813887 0.0251316 4 7 
+0.00145874 0.0813513 0.0251159 4 7 
+0.00145333 0.0813127 0.0250998 4 7 
+0.00144793 0.0812747 0.0250844 4 7 
+0.00144256 0.0812364 0.0250691 4 7 
+0.0014372 0.0812048 0.0250537 4 7 
+0.00143186 0.0811684 0.0250375 4 7 
+0.00142653 0.0811317 0.0250213 4 7 
+0.00142122 0.0810898 0.025006 4 7 
+0.00141593 0.0810511 0.02499 4 7 
+0.00141066 0.0810122 0.024974 4 7 
+0.0014054 0.0809794 0.0249588 4 7 
+0.00140016 0.0809406 0.0249431 4 7 
+0.00139493 0.0809017 0.0249275 4 7 
+0.00138973 0.0808678 0.0249124 4 7 
+0.00138454 0.0808299 0.024897 4 7 
+0.00137936 0.0807919 0.0248818 4 7 
+0.00137421 0.0807536 0.0248668 4 7 
+0.00136907 0.0807151 0.0248518 4 7 
+0.00136395 0.0806764 0.0248369 4 7 
+0.00135885 0.0806326 0.0248221 4 7 
+0.00135376 0.0805944 0.0248075 4 7 
+0.00134869 0.0805561 0.024793 4 7 
+0.00134364 0.0805186 0.0247782 4 7 
+0.0013386 0.0804797 0.024764 4 7 
+0.00133359 0.0804407 0.0247499 4 7 
+0.00132859 0.0803995 0.0247354 4 7 
+0.00132361 0.0803603 0.0247216 4 7 
+0.00131864 0.080321 0.0247066 4 7 
+0.00131369 0.080282 0.0246923 4 7 
+0.00130876 0.0802417 0.0246774 4 7 
+0.00130385 0.0802012 0.0246626 4 7 
+0.00129896 0.0801542 0.0246485 4 7 
+0.00129408 0.0801148 0.0246339 4 7 
+0.00128922 0.0800751 0.0246195 4 7 
+0.00128438 0.0800352 0.0246055 4 7 
+0.00127956 0.0799952 0.0245912 4 7 
+0.00127475 0.0799551 0.0245771 4 7 
+0.00126996 0.0799103 0.0245631 4 7 
+0.00126519 0.0798683 0.0245492 4 7 
+0.00126044 0.0798264 0.0245355 4 7 
+0.0012557 0.0797881 0.0245215 4 7 
+0.00125099 0.0797459 0.0245078 4 7 
+0.00124629 0.0797036 0.0244943 4 7 
+0.00124161 0.0796641 0.0244804 4 7 
+0.00123694 0.0796231 0.0244671 4 7 
+0.0012323 0.079582 0.0244539 4 7 
+0.00122767 0.0795421 0.0244401 4 7 
+0.00122306 0.0795007 0.024427 4 7 
+0.00121847 0.0794591 0.0244141 4 7 
+0.0012139 0.0794178 0.0244005 4 7 
+0.00120935 0.0793759 0.0243874 4 7 
+0.00120481 0.0793338 0.0243733 4 7 
+0.00120029 0.0792925 0.0243604 4 7 
+0.00119579 0.0792499 0.0243464 4 7 
+0.00119131 0.079207 0.0243326 4 7 
+0.00118685 0.0791635 0.0243201 4 7 
+0.00118241 0.0791203 0.0243063 4 7 
+0.00117798 0.0790771 0.0242927 4 7 
+0.00117357 0.0790281 0.0242798 4 7 
+0.00116918 0.0789844 0.0242663 4 7 
+0.00116481 0.0789406 0.024253 4 7 
+0.00116046 0.0789049 0.0242403 4 7 
+0.00115613 0.0788613 0.024227 4 7 
+0.00115182 0.0788176 0.0242139 4 7 
+0.00114752 0.0787742 0.0242011 4 7 
+0.00114324 0.0787303 0.0241881 4 7 
+0.00113899 0.0786863 0.0241752 4 7 
+0.00113475 0.0786421 0.0241624 4 7 
+0.00113053 0.0785979 0.0241496 4 7 
+0.00112632 0.0785536 0.0241371 4 7 
+0.00112214 0.0785111 0.0241242 4 7 
+0.00111798 0.0784667 0.0241117 4 7 
+0.00111383 0.0784223 0.0240994 4 7 
+0.00110971 0.0783793 0.0240864 4 7 
+0.0011056 0.0783348 0.0240741 4 7 
+0.00110151 0.0782901 0.0240621 4 7 
+0.00109745 0.0782457 0.024049 4 7 
+0.0010934 0.0782009 0.0240369 4 7 
+0.00108937 0.078156 0.0240251 4 7 
+0.00108536 0.0781088 0.0240119 4 7 
+0.00108137 0.0780637 0.0240001 4 7 
+0.00107739 0.0780186 0.0239884 4 7 
+0.00107344 0.0779706 0.0239756 4 7 
+0.00106951 0.0779253 0.0239641 4 7 
+0.0010656 0.07788 0.0239515 4 7 
+0.0010617 0.0778398 0.0239392 4 7 
+0.00105783 0.0777944 0.0239264 4 7 
+0.00105397 0.0777489 0.0239137 4 7 
+0.00105014 0.0776967 0.0239018 4 7 
+0.00104632 0.0776511 0.0238893 4 7 
+0.00104253 0.0776055 0.023877 4 7 
+0.00103875 0.0775611 0.0238653 4 7 
+0.001035 0.0775149 0.0238531 4 7 
+0.00103126 0.0774686 0.023841 4 7 
+0.00102754 0.0774262 0.0238293 4 7 
+0.00102385 0.0773798 0.0238173 4 7 
+0.00102017 0.0773334 0.0238055 4 7 
+0.00101651 0.0772897 0.023794 4 7 
+0.00101288 0.0772432 0.0237826 4 7 
+0.00100926 0.0771967 0.0237715 4 7 
+0.00100566 0.0771484 0.0237597 4 7 
+0.00100209 0.0771015 0.0237488 4 7 
+0.000998532 0.0770546 0.0237373 4 7 
+0.000994996 0.07701 0.0237253 4 7 
+0.000991481 0.0769631 0.0237131 4 7 
+0.000987986 0.076916 0.0237012 4 7 
+0.000984511 0.0768665 0.0236901 4 7 
+0.000981057 0.0768191 0.0236783 4 7 
+0.000977623 0.0767715 0.0236667 4 7 
+0.00097421 0.0767214 0.0236554 4 7 
+0.000970817 0.0766734 0.023644 4 7 
+0.000967444 0.0766252 0.0236328 4 7 
+0.000964093 0.0765782 0.0236216 4 7 
+0.000960762 0.0765318 0.0236106 4 7 
+0.000957451 0.0764854 0.0235999 4 7 
+0.000954161 0.0764442 0.0235884 4 7 
+0.000950892 0.0763963 0.0235777 4 7 
+0.000947644 0.0763482 0.0235673 4 7 
+0.000944417 0.0763035 0.0235565 4 7 
+0.00094121 0.0762559 0.0235459 4 7 
+0.000938025 0.0762081 0.0235344 4 7 
+0.00093486 0.0761509 0.0235241 4 7 
+0.000931716 0.0761042 0.0235127 4 7 
+0.000928593 0.0760577 0.0235016 4 7 
+0.000925492 0.0760175 0.0234909 4 7 
+0.000922411 0.0759696 0.0234801 4 7 
+0.000919351 0.0759216 0.0234695 4 7 
+0.000916313 0.0758659 0.0234589 4 7 
+0.000913295 0.0758163 0.0234486 4 7 
+0.000910299 0.075769 0.0234385 4 7 
+0.000907324 0.075728 0.023428 4 7 
+0.000904371 0.0756791 0.0234182 4 7 
+0.000901439 0.0756299 0.0234086 4 7 
+0.000898527 0.0755851 0.0233984 4 7 
+0.000895638 0.0755374 0.0233879 4 7 
+0.00089277 0.0754895 0.0233772 4 7 
+0.000889923 0.0754411 0.0233672 4 7 
+0.000887098 0.0753931 0.0233568 4 7 
+0.000884294 0.0753449 0.0233467 4 7 
+0.000881512 0.0752957 0.0233368 4 7 
+0.000878751 0.075248 0.023327 4 7 
+0.000876012 0.0752 0.0233175 4 7 
+0.000873294 0.075151 0.0233076 4 7 
+0.000870598 0.0751032 0.0232983 4 7 
+0.000867924 0.0750551 0.0232893 4 7 
+0.000865272 0.0750041 0.0232801 4 7 
+0.000862641 0.0749569 0.0232705 4 7 
+0.000860032 0.0749093 0.0232605 4 7 
+0.000857445 0.0748596 0.0232509 4 7 
+0.00085488 0.0748122 0.0232414 4 7 
+0.000852337 0.0747645 0.0232322 4 7 
+0.000849815 0.0747071 0.023223 4 7 
+0.000847315 0.0746606 0.0232141 4 7 
+0.000844838 0.0746144 0.0232055 4 7 
+0.000842382 0.0745669 0.0231964 4 7 
+0.000839949 0.0745163 0.023188 4 7 
+0.000837537 0.0744652 0.02318 4 7 
+0.000835147 0.074423 0.0231708 4 7 
+0.00083278 0.0743727 0.0231626 4 7 
+0.000830435 0.0743218 0.0231533 4 7 
+0.000828112 0.0742792 0.0231452 4 7 
+0.000825811 0.0742321 0.0231362 4 7 
+0.000823532 0.0741846 0.0231275 4 7 
+0.000821275 0.0741314 0.0231192 4 7 
+0.000819041 0.0740804 0.0231109 4 7 
+0.000816829 0.074031 0.023103 4 7 
+0.00081464 0.0739877 0.0230949 4 7 
+0.000812472 0.0739369 0.0230871 4 7 
+0.000810327 0.0738857 0.0230797 4 7 
+0.000808205 0.0738425 0.0230718 4 7 
+0.000806105 0.0737914 0.0230647 4 7 
+0.000804027 0.0737437 0.0230569 4 7 
+0.000801972 0.0737025 0.0230493 4 7 
+0.000799939 0.0736527 0.0230415 4 7 
+0.000797929 0.0736022 0.0230339 4 7 
+0.000795941 0.0735577 0.0230267 4 7 
+0.000793976 0.0735073 0.0230196 4 7 
+0.000792034 0.0734562 0.0230129 4 7 
+0.000790114 0.0734091 0.0230058 4 7 
+0.000788217 0.073365 0.0229994 4 7 
+0.000786342 0.0733207 0.0229932 4 7 
+0.00078449 0.0732745 0.0229863 4 7 
+0.00078266 0.0732248 0.0229796 4 7 
+0.000780854 0.0731742 0.0229726 4 7 
+0.00077907 0.0731358 0.0229664 4 7 
+0.000777308 0.0730872 0.0229598 4 7 
+0.000775569 0.0730378 0.0229535 4 7 
+0.000773853 0.0729967 0.0229474 4 7 
+0.00077216 0.0729485 0.0229415 4 7 
+0.000770489 0.0728996 0.0229359 4 7 
+0.000768841 0.0728589 0.02293 4 7 
+0.000767216 0.0728141 0.0229248 4 7 
+0.000765613 0.0727684 0.0229196 4 7 
+0.000764033 0.0727184 0.022914 4 7 
+0.000762475 0.0726696 0.0229085 4 7 
+0.00076094 0.0726254 0.0229028 4 7 
+0.000759428 0.0725846 0.0228979 4 7 
+0.000757938 0.0725367 0.0228924 4 7 
+0.00075647 0.0724903 0.0228873 4 7 
+0.000755025 0.0724546 0.0228825 4 7 
+0.000753603 0.0724088 0.0228776 4 7 
+0.000752202 0.0723622 0.022873 4 7 
+0.000750824 0.0723223 0.0228684 4 7 
+0.000749468 0.0722763 0.0228639 4 7 
+0.000748134 0.0722293 0.0228598 4 7 
+0.000746823 0.072188 0.0228553 4 7 
+0.000745533 0.0721463 0.0228513 4 7 
+0.000744265 0.0721078 0.0228476 4 7 
+0.000743018 0.072069 0.0228434 4 7 
+0.000741794 0.0720288 0.0228399 4 7 
+0.000740591 0.0719878 0.0228361 4 7 
+0.000739409 0.0719454 0.0228322 4 7 
+0.000738249 0.0719065 0.022829 4 7 
+0.00073711 0.0718668 0.022825 4 7 
+0.000735992 0.071819 0.0228216 4 7 
+0.000734895 0.0717834 0.0228187 4 7 
+0.000733819 0.071747 0.022815 4 7 
+0.000732763 0.0717078 0.0228119 4 7 
+0.000731728 0.0716666 0.0228091 4 7 
+0.000730713 0.0716245 0.0228056 4 7 
+0.000729719 0.0715871 0.0228026 4 7 
+0.000728744 0.0715541 0.0228001 4 7 
+0.000727789 0.0715205 0.0227973 4 7 
+0.000726853 0.0714869 0.0227941 4 7 
+0.000725937 0.0714511 0.0227917 4 7 
+0.00072504 0.0714146 0.0227894 4 7 
+0.000724163 0.0713809 0.0227869 4 7 
+0.000723304 0.0713451 0.0227846 4 7 
+0.000722463 0.0713086 0.0227819 4 7 
+0.000721641 0.071279 0.0227797 4 7 
+0.000720837 0.0712454 0.0227772 4 7 
+0.000720051 0.0712111 0.0227749 4 7 
+0.000719283 0.0711777 0.0227728 4 7 
+0.000718531 0.0711481 0.0227707 4 7 
+0.000717798 0.071118 0.0227688 4 7 
+0.000717081 0.0710827 0.0227671 4 7 
+0.000716381 0.0710485 0.0227655 4 7 
+0.000715697 0.0710191 0.0227633 4 7 
+0.00071503 0.0709891 0.0227616 4 7 
+0.000714378 0.0709615 0.02276 4 7 
+0.000713743 0.0709364 0.022758 4 7 
+0.000713122 0.0709033 0.0227565 4 7 
+0.000712517 0.0708782 0.0227547 4 7 
+0.000711927 0.0708544 0.0227529 4 7 
+0.000711352 0.0708253 0.0227515 4 7 
+0.000710791 0.0707957 0.0227498 4 7 
+0.000710245 0.0707741 0.0227483 4 7 
+0.000709712 0.0707494 0.022747 4 7 
+0.000709194 0.0707209 0.0227454 4 7 
+0.000708688 0.0706996 0.022744 4 7 
+0.000708196 0.0706777 0.0227429 4 7 
+0.000707717 0.0706508 0.0227414 4 7 
+0.000707251 0.0706295 0.02274 4 7 
+0.000706797 0.0706131 0.022739 4 7 
+0.000706355 0.0705889 0.0227375 4 7 
+0.000705925 0.0705642 0.0227362 4 7 
+0.000705508 0.0705506 0.0227352 4 7 
+0.000705101 0.0705286 0.0227339 4 7 
+0.000704706 0.0705061 0.0227326 4 7 
+0.000704322 0.0704918 0.0227314 4 7 
+0.000703949 0.0704719 0.0227303 4 7 
+0.000703586 0.0704516 0.0227292 4 7 
+0.000703234 0.0704361 0.0227278 4 7 
+0.000702892 0.0704174 0.0227267 4 7 
+0.00070256 0.0703982 0.0227257 4 7 
+0.000702237 0.0703847 0.0227243 4 7 
+0.000701924 0.0703681 0.0227233 4 7 
+0.000701621 0.0703512 0.0227223 4 7 
+0.000701326 0.070332 0.0227213 4 7 
+0.00070104 0.0703136 0.0227201 4 7 
+0.000700763 0.0702976 0.022719 4 7 
+0.000700494 0.0702926 0.0227179 4 7 
+0.000700234 0.0702779 0.0227168 4 7 
+0.000699982 0.0702629 0.0227157 4 7 
+0.000699737 0.0702508 0.0227147 4 7 
+0.000699501 0.0702388 0.0227137 4 7 
+0.000699271 0.0702265 0.0227128 4 7 
+0.000699049 0.0702144 0.0227117 4 7 
+0.000698835 0.0702024 0.0227108 4 7 
+0.000698627 0.0701901 0.0227099 4 7 
+0.000698426 0.0701801 0.0227087 4 7 
+0.000698231 0.0701689 0.0227078 4 7 
+0.000698044 0.0701574 0.0227069 4 7 
+0.000697862 0.0701488 0.0227058 4 7 
+0.000697686 0.0701389 0.0227049 4 7 
+0.000697517 0.0701285 0.022704 4 7 
+0.000697353 0.07012 0.0227029 4 7 
+0.000697195 0.07011 0.022702 4 7 
+0.000697043 0.0700996 0.0227011 4 7 
+0.000696896 0.0700908 0.0227001 4 7 
+0.000696754 0.0700801 0.0226992 4 7 
+0.000696617 0.0700689 0.0226983 4 7 
+0.000696485 0.0700641 0.0226973 4 7 
+0.000696358 0.0700596 0.0226965 4 7 
+0.000696236 0.0700546 0.0226956 4 7 
+0.000696118 0.0700449 0.0226947 4 7 
+0.000696005 0.0700407 0.0226938 4 7 
+0.000695896 0.0700361 0.022693 4 7 
+0.000695791 0.0700281 0.0226922 4 7 
+0.00069569 0.070024 0.0226913 4 7 
+0.000695594 0.0700195 0.0226905 4 7 
+0.000695501 0.0700144 0.0226897 4 7 
+0.000695411 0.0700095 0.0226889 4 7 
+0.000695326 0.0700042 0.0226881 4 7 
+0.000695244 0.0699994 0.0226874 4 7 
+0.000695165 0.0699937 0.0226866 4 7 
+0.00069509 0.0699876 0.0226858 4 7 
+0.000695017 0.0699795 0.0226852 4 7 
+0.000694948 0.0699781 0.0226845 4 7 
+0.000694882 0.0699763 0.0226837 4 7 
+0.000694819 0.0699748 0.0226829 4 7 
+0.000694758 0.0699704 0.0226823 4 7 
+0.000694701 0.0699655 0.0226816 4 7 
+0.000694645 0.0699647 0.0226809 4 7 
+0.000694593 0.0699611 0.0226802 4 7 
+0.000694543 0.0699569 0.0226796 4 7 
+0.000694495 0.0699549 0.022679 4 7 
+0.000694449 0.0699506 0.0226784 4 7 
+0.000694406 0.0699458 0.0226778 4 7 
+0.000694365 0.0699482 0.0226772 4 7 
+0.000694326 0.0699454 0.0226766 4 7 
+0.000694288 0.0699421 0.0226761 4 7 
+0.000694253 0.069935 0.0226755 4 7 
+0.00069422 0.0699295 0.022675 4 7 
+0.000694188 0.0699267 0.0226745 4 7 
+0.000694158 0.0699235 0.022674 4 7 
+0.000694129 0.0699255 0.0226735 4 7 
+0.000694103 0.0699269 0.0226731 4 7 
+0.000694077 0.0699225 0.0226726 4 7 
+0.000694053 0.0699241 0.0226722 4 7 
+0.000694031 0.0699252 0.0226718 4 7 
+0.000694009 0.0699173 0.0226714 4 7 
+0.000693989 0.0699194 0.022671 4 7 
+0.000693971 0.0699209 0.0226706 4 7 
+0.000693953 0.069919 0.0226702 4 7 
+0.000693936 0.0699203 0.0226699 4 7 
+0.000693921 0.0699209 0.0226696 4 7 
+0.000693906 0.0699161 0.0226692 4 7 
+0.000693892 0.0699176 0.0226689 4 7 
+0.00069388 0.0699184 0.0226686 4 7 
+0.000693868 0.069914 0.0226683 4 7 
+0.000693857 0.0699156 0.0226681 4 7 
+0.000693846 0.0699166 0.0226678 4 7 
+0.000693837 0.069917 0.0226676 4 7 
+0.000693828 0.0699161 0.0226673 4 7 
+0.00069382 0.0699144 0.0226671 4 7 
+0.000693812 0.0699154 0.0226669 4 7 
+0.000693805 0.0699143 0.0226667 4 7 
+0.000693798 0.0699123 0.0226665 4 7 
+0.000693792 0.0699074 0.0226663 4 7 
+0.000693787 0.0699099 0.0226661 4 7 
+0.000693782 0.0699118 0.022666 4 7 
+0.000693777 0.0699121 0.0226658 4 7 
+0.000693772 0.0699129 0.0226657 4 7 
+0.000693769 0.0699129 0.0226655 4 7 
+0.000693765 0.0699117 0.0226654 4 7 
+0.000693762 0.0699097 0.0226653 4 7 
+0.000693759 0.0699068 0.0226652 4 7 
+0.000693756 0.0699033 0.0226651 4 7 
+0.000693753 0.0698987 0.022665 4 7 
+0.000693751 0.0699028 0.0226649 4 7 
+0.000693749 0.0699053 0.0226648 4 7 
+0.000693747 0.069901 0.0226647 4 7 
+0.000693746 0.0698991 0.0226647 4 7 
+0.000693744 0.0699042 0.0226646 4 7 
+0.000693743 0.0699073 0.0226645 4 7 
+0.000693742 0.0699095 0.0226645 4 7 
+0.000693741 0.0699077 0.0226644 4 7 
+0.00069374 0.0699098 0.0226644 4 7 
+0.000693739 0.0699109 0.0226643 4 7 
+0.000693738 0.0699111 0.0226643 4 7 
+0.000693737 0.0699106 0.0226643 4 7 
+0.000693737 0.069909 0.0226642 4 7 
+0.000693736 0.069911 0.0226642 4 7 
+0.000693736 0.0699104 0.0226642 4 7 
+0.000693735 0.0699088 0.0226642 4 7 
+0.000693735 0.0699107 0.0226641 4 7 
+0.000693735 0.0699094 0.0226641 4 7 
+0.000693735 0.0699069 0.0226641 4 7 
+0.000693734 0.0698975 0.0226641 4 7 
+0.000693734 0.0699008 0.0226641 4 7 
+0.000693734 0.0699049 0.0226641 4 7 
+0.000693734 0.0699032 0.0226641 4 7 
+0.000693734 0.0699068 0.022664 4 7 
+0.000693734 0.0699093 0.022664 4 7 
+0.000693733 0.0699105 0.022664 4 7 
+0.000693733 0.069909 0.022664 4 7 
+0.000693733 0.0699062 0.022664 4 7 
+0.000693733 0.0698966 0.022664 4 7 
+0.000693733 0.0699 0.022664 4 7 
+0.000693733 0.0699045 0.022664 4 7 
+0.000693733 0.0699063 0.022664 4 7 
+0.000693733 0.069909 0.022664 4 7 
+0.000693733 0.0699105 0.022664 4 7 
+0.000693733 0.0699075 0.022664 4 7 
+0.000693733 0.0699035 0.022664 4 7 
+0.000693733 0.0698979 0.022664 4 7 
+0.000693733 0.069901 0.022664 4 7 
+0.000693733 0.0698945 0.022664 4 7 
+0.000693733 0.0699005 0.022664 4 7 
+0.000693733 0.0699096 0.022664 4 7 
+0.000693733 0.0699107 0.022664 4 7 
+0.000693733 0.0699103 0.022664 4 7 
+0.000693733 0.0699057 0.022664 4 7 
+0.000693733 0.0699006 0.022664 4 7 
+0.000693733 0.0698964 0.022664 4 7 
+0.000693733 0.0699077 0.022664 4 7 
+0.000693733 0.0699101 0.022664 4 7 
+0.000693733 0.0699108 0.022664 4 7 
+0.000693733 0.0699105 0.022664 4 7 
+0.000693733 0.0699106 0.022664 4 7 
+0.000693733 0.0699089 0.022664 4 7 
+0.000693733 0.0699077 0.022664 4 7 
+0.000693733 0.0699032 0.022664 4 7 
+0.000693733 0.0698964 0.022664 4 7 
+0.000693733 0.0699074 0.022664 4 7 
+0.000693733 0.0699025 0.022664 4 7 
+0.000693733 0.0698952 0.022664 4 7 
+0.000693733 0.0698985 0.022664 4 7 
+0.000693733 0.0698983 0.022664 4 7 
+0.000693733 0.0699043 0.022664 4 7 
+0.000693733 0.0699071 0.022664 4 7 
+0.000693733 0.06991 0.022664 4 7 
+0.000693733 0.0699108 0.022664 4 7 
+0.000693733 0.0699108 0.022664 4 7 
+0.000693733 0.0699092 0.022664 4 7 
+0.000693733 0.0699051 0.022664 4 7 
+0.000693733 0.0699093 0.022664 4 7 
+0.000693733 0.0699108 0.022664 4 7 
+0.000693733 0.0699098 0.022664 4 7 
+0.000693733 0.0699108 0.022664 4 7 
+0.000693733 0.0699099 0.022664 4 7 
+0.000693733 0.0699061 0.022664 4 7 
+0.000693733 0.0699094 0.022664 4 7 
+0.000693733 0.069905 0.022664 4 7 
+0.000693733 0.0698974 0.022664 4 7 
+0.000693733 0.0699072 0.022664 4 7 
+0.000693733 0.0699007 0.022664 4 7 
+0.000693733 0.0698917 0.022664 4 7 
+0.000693733 0.0699071 0.022664 4 7 
+0.000693733 0.0699003 0.022664 4 7 
+0.000693733 0.0698928 0.022664 4 7 
+0.000693733 0.0699108 0.022664 4 7 
+0.000693733 0.0699089 0.022664 4 7 
+0.000693733 0.0699033 0.022664 4 7 
+0.000693733 0.0699089 0.022664 4 7 
+0.000693733 0.0699108 0.022664 4 7 
+0.000693733 0.069909 0.022664 4 7 
+0.000693733 0.0699049 0.022664 4 7 
+0.000693733 0.0699097 0.022664 4 7 
+0.000693733 0.0699107 0.022664 4 7 
+0.000693733 0.0698948 0.022664 4 7 
+0.000693733 0.0699004 0.022664 4 7 
+0.000693733 0.0699076 0.022664 4 7 
+0.000693733 0.0699068 0.022664 4 7 
+0.000693733 0.069898 0.022664 4 7 
+0.000693733 0.0698959 0.022664 4 7 
+0.000693733 0.0699062 0.022664 4 7 
+0.000693733 0.0698963 0.022664 4 7 
+0.000693733 0.0698979 0.022664 4 7 
+0.000693733 0.0699082 0.022664 4 7 
+0.000693733 0.0698997 0.022664 4 7 
+0.000693733 0.0698946 0.022664 4 7 
+0.000693733 0.0699089 0.022664 4 7 
+0.000693733 0.0699107 0.022664 4 7 
+0.000693733 0.0699063 0.022664 4 7 
+0.000693733 0.0699065 0.022664 4 7 
+0.000693733 0.0698951 0.022664 4 7 
+0.000693733 0.0698998 0.022664 4 7 
+0.000693733 0.0699008 0.022664 4 7 
+0.000693733 0.069909 0.022664 4 7 
+0.000693733 0.0699104 0.022664 4 7 
+0.000693733 0.0699094 0.022664 4 7 
+0.000693733 0.0699003 0.022664 4 7 
+0.000693733 0.0698935 0.022664 4 7 
+0.000693733 0.0699096 0.022664 4 7 
+0.000693733 0.0699097 0.022664 4 7 
+0.000693733 0.0699001 0.022664 4 7 
+0.000693733 0.0699066 0.022664 4 7 
+0.000693733 0.0698915 0.022664 4 7 
+0.000693733 0.069903 0.022664 4 7 
+0.000693733 0.0699041 0.022664 4 7 
+0.000693733 0.0698922 0.022664 4 7 
+0.000693733 0.0699068 0.022664 4 7 
+0.000693733 0.0699099 0.0226639 4 7 
+0.000693733 0.0699082 0.022664 4 7 
+0.000693733 0.0698922 0.022664 4 7 
+0.000693733 0.0699035 0.0226639 4 7 
+0.000693733 0.0698951 0.022664 4 7 
+0.000693733 0.0699091 0.022664 4 7 
+0.000693733 0.0699099 0.022664 4 7 
+0.000693733 0.0699069 0.022664 4 7 
+0.000693733 0.0698871 0.022664 4 7 
+0.000693733 0.0698982 0.022664 4 7 
+0.000693733 0.0699014 0.022664 4 7 
+0.000693733 0.0699108 0.022664 4 7 
+0.000693733 0.0698954 0.022664 4 7 
+0.000693733 0.0699052 0.022664 4 7 
+0.000693733 0.0699094 0.022664 4 7 
+0.000693733 0.0698901 0.022664 4 7 
+0.000693733 0.06991 0.022664 4 7 
+0.000693733 0.0699012 0.022664 4 7 
+0.000693733 0.0699107 0.022664 4 7 
+0.000693733 0.0698946 0.022664 4 7 
+0.000693733 0.0699039 0.022664 4 7 
+0.000693733 0.0699049 0.022664 4 7 
+0.000693733 0.0699054 0.022664 4 7 
+0.000693733 0.0698907 0.022664 4 7 
+0.000693733 0.0699107 0.022664 4 7 
+0.000693733 0.0698807 0.022664 4 7 
+0.000693733 0.0699108 0.022664 4 7 
+0.000693733 0.0699107 0.022664 4 7 
+0.000693733 0.0698877 0.022664 4 7 
+0.000693733 0.0699077 0.022664 4 7 
+0.000693733 0.0699108 0.0226639 4 7 
+0.000693733 0.0698926 0.0226639 4 7 
+0.000693733 0.0698954 0.022664 4 7 
+0.000693733 0.0699057 0.0226639 4 7 
+0.000693733 0.0698715 0.022664 4 7 
+0.000693733 0.0698965 0.022664 4 7 
+0.000693733 0.0699074 0.0226639 4 7 
+0.000693734 0.0698981 0.0226639 4 7 
+0.000693735 0.0698507 0.0226639 4 7 
+0.000693733 0.0698914 0.0226639 4 7 
+0.000693733 0.0699105 0.022664 4 7 
+0.000693733 0.0698611 0.022664 4 7 
+0.000693733 0.0699106 0.0226639 4 7 
+0.000693733 0.0698957 0.0226639 4 7 
+0.000693733 0.0698718 0.0226639 4 7 
+0.000693733 0.0698833 0.0226636 4 7 
+0.000693733 0.0699104 0.0226638 4 7 
+0.000693733 0.0698574 0.0226639 4 7 
+0.000693733 0.06991 0.0226636 4 7 
+0.000693733 0.0698535 0.0226638 4 7 
+0.000693733 0.0699104 0.0226639 4 7 
+0.000693733 0.069885 0.0226639 4 7 
+0.000693733 0.069903 0.0226638 4 7 
+0.000693733 0.069903 0.0226638 4 7 
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/constraints/Example_Constraints_States_TEXT.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/constraints/Example_Constraints_States_TEXT.txt
new file mode 100644
index 0000000000000000000000000000000000000000..1d1d05824ae1066036b2399306a6266da3c11d53
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/constraints/Example_Constraints_States_TEXT.txt
@@ -0,0 +1,59 @@
+********** MODEL NAME
+State_Constraint_Example_TEXT
+
+********** MODEL NOTES
+This model exemplifies how to implement upper and lower bounds on state 
+variables in TEXT models. The identifier for state constraints is the 
+following:
+
+    {constraints:["lower bound","upper bound"]}
+    
+This identifier needs to be written as additional information behind the 
+ODE definitions (see example below).
+
+This information is, of course, optional and can be present at the same 
+time as the SBML related additional information is present (see ODE for Y 
+below).
+
+The upper and lower bounds can consist of "+inf","-inf", parameters
+defined in the model and numeric values.
+
+No error checking is done so far that the parameters are really defined, 
+lower is smaller than upper bound, etc.
+
+IMPORTANT: During model import these constraint information are converted 
+to prefactors and piecewiseSB expressions. Thus when exporting the model
+again, the "{constraints:["lower bound","upper bound"]}" information will 
+not be present anymore but replaced by the constraint implementing 
+mathematical constructs.
+
+********** MODEL STATES
+d/dt(X) = -X + U1 %{constraints:[-inf,Xmax]}       
+d/dt(Y) = U2      %{isSpecie:Xmax:concentration} {constraints:[Ymin,1.5]}        
+
+Y(0) = 0.1
+
+********** MODEL PARAMETERS
+% Constraints for state-variable X
+Xmax = 1  % Upper bound on X
+
+% Constraints for state-variable Y
+Ymin = -0.1 % Lower bound on Y
+
+********** MODEL VARIABLES
+
+% Input functions
+U1 = piecewiseSB(0, ge(time, 10), 2)              % Input function on state X
+U2 = -0.5 +  piecewiseSB(0, lt(time, 5), 0, ge(time, 15),1)	% Input function on state Y
+
+********** MODEL REACTIONS
+
+
+********** MODEL FUNCTIONS
+
+
+********** MODEL EVENTS
+
+
+********** MODEL MATLAB FUNCTIONS
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/constraints/Example_Constraints_States_TEXTBC.txtbc b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/constraints/Example_Constraints_States_TEXTBC.txtbc
new file mode 100644
index 0000000000000000000000000000000000000000..0c4bfb3c8f4453f6f7974fc79570be3979c2d920
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/constraints/Example_Constraints_States_TEXTBC.txtbc
@@ -0,0 +1,64 @@
+********** MODEL NAME
+State_Constraint_Example_TEXTBC
+
+********** MODEL NOTES
+This model exemplifies how to implement upper and lower bounds on state 
+variables in TEXTBC models. The identifier for state constraints is the 
+following: 
+
+    {constraints:["lower bound","upper bound"]}
+    
+This identifier needs to be written as additional information behind the 
+initial condition definitions (see example below).
+
+This information is, of course, optional and can be present at the same 
+time as the SBML related additional information is present (see IC for Y 
+below).
+
+The upper and lower bounds can consist of "+inf","-inf", parameters
+defined in the model and numeric values.
+
+No error checking is done so far that the parameters are really defined, 
+lower is smaller than upper bound, etc.
+
+IMPORTANT: During model import these constraint information are converted 
+to prefactors and piecewiseSB expressions. Thus when exporting the model
+again, the "{constraints:["lower bound","upper bound"]}" information will 
+not be present anymore but replaced by the constraint implementing 
+mathematical constructs.
+
+********** MODEL STATE INFORMATION
+X(0) = 0       {constraints:[-inf,Xmax]}  
+Y(0) = 0.1     {isSpecie:Xmax:concentration}  {constraints:[Ymin,1.5]}  
+
+********** MODEL PARAMETERS
+% Constraints for state-variable X
+Xmax = 1  % Upper bound on X
+
+% Constraints for state-variable Y
+Ymin = -0.1 % Lower bound on Y
+
+********** MODEL VARIABLES
+
+% Input functions
+U1 = piecewiseSB(0, ge(time, 10), 2)                         % Input function on state X
+U2 = -0.5 +  piecewiseSB(0, lt(time, 5), 0, ge(time, 15),1)  % Input function on state X
+
+********** MODEL REACTIONS
+X => : R1
+    vf = X
+    
+  => X : R2
+    vf = U1
+    
+  => Y : R3
+    vf = U2
+
+********** MODEL FUNCTIONS
+
+
+********** MODEL EVENTS
+
+
+********** MODEL MATLAB FUNCTIONS
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/eventExample.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/eventExample.txt
new file mode 100644
index 0000000000000000000000000000000000000000..892a80588cfc0372d79c946b933ef1c7844e1a13
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/eventExample.txt
@@ -0,0 +1,30 @@
+********** MODEL NAME
+Event Example
+
+********** MODEL NOTES
+Event example taken from the SBML validation suite: events_one_event_two_assignments
+
+********** MODEL STATES
+d/dt(S1) = -R %species
+d/dt(S2) = +R %species
+
+S1(0) = 1
+S2(0) = 0
+
+********** MODEL PARAMETERS
+
+
+********** MODEL VARIABLES
+
+
+********** MODEL REACTIONS
+R = S1 %reaction kinetics
+
+********** MODEL FUNCTIONS
+
+
+********** MODEL EVENTS
+Event_1 = lt(S1, 0.1),S1,1,S2,0
+
+********** MODEL MATLAB FUNCTIONS
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/eventExample2.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/eventExample2.txt
new file mode 100644
index 0000000000000000000000000000000000000000..4a12deb7df9f6bc84a65bcf014a27c15b6b9168c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/eventExample2.txt
@@ -0,0 +1,32 @@
+********** MODEL NAME
+Event Example
+
+********** MODEL NOTES
+Event example taken from the SBML validation suite: events_one_event_two_assignments
+
+********** MODEL STATES
+d/dt(S1) = -R %species
+d/dt(S2) = +k3*R %species
+
+S1(0) = 1
+S2(0) = 0
+
+********** MODEL PARAMETERS
+k1 = 1
+k2 = 2
+k3 = 3
+
+********** MODEL VARIABLES
+
+
+********** MODEL REACTIONS
+R = k1*S1 + k2 %reaction kinetics
+
+********** MODEL FUNCTIONS
+
+
+********** MODEL EVENTS
+Event_1 = lt(S1,0.1),S1,1,S2,0
+
+********** MODEL MATLAB FUNCTIONS
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/exampleSBMLexport.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/exampleSBMLexport.txt
new file mode 100644
index 0000000000000000000000000000000000000000..ce7fb6bffa2e6fc0da0bf8dd9b006920608e5cfd
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/exampleSBMLexport.txt
@@ -0,0 +1,32 @@
+********** MODEL NAME
+SBML export example
+
+********** MODEL NOTES
+
+********** MODEL STATES
+d/dt(S1) = -R {isSpecie:cytosol:concentration} 
+d/dt(S2) = R {isSpecie:nucleus:concentration} 
+d/dt(X) = -0.5*X + Y {isParameter} 
+
+S1(0) = 1
+S2(0) = 0
+X(0) = 2
+
+********** MODEL PARAMETERS
+k1 = 1 {isParameter}
+k2 = 2 {isParameter}
+cytosol = 10 {isCompartment:}  
+nucleus = 1 {isCompartment:cytosol}
+
+********** MODEL VARIABLES
+Y = 1-S1 {isParameter}
+
+********** MODEL REACTIONS
+R = k1*S1 - k2*S2 {reversible} 
+
+********** MODEL FUNCTIONS
+
+********** MODEL EVENTS
+
+********** MODEL MATLAB FUNCTIONS
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/experiment/experiment.exp b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/experiment/experiment.exp
new file mode 100644
index 0000000000000000000000000000000000000000..5f68e3bb658e7de7e6cd4a39faed9541ce466a39
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/experiment/experiment.exp
@@ -0,0 +1,51 @@
+********** EXPERIMENT NAME
+example experiment
+
+********** EXPERIMENT NOTES
+just an example experiment 
+
+********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS
+% The expression in this limiter will be evaluated when merging the 
+% experiment with the model. Please note that the entries here will be 
+% evaluated sequentially. The initial conditions and the parameters
+% that are defined in the model can be accessed here. Additionally, the 
+% functions, defined in the model under MODEL FUNCTIONS, can be used here.
+
+% Initial conditions can be set (both directly numerical values or 
+% as mathematical expressions)
+A(0) = 1            % comment 1
+
+% Parameter values can be changed by both setting numerical values and 
+% mathematical expressions
+k2 = 1 + k1*A(0)    % k1 as defined in model
+k1 = f(A(0),k2)     % redefine k1 (sequential evaluation of expressions)
+                    % The function f(x,y) is defined in the model! 
+
+% Definition of parameters and initial conditions can appear anywhere.
+B(0) = A(0) + 5*k1  % k1 and A as defined above
+
+********** EXPERIMENT PARAMETER CHANGES
+% In this section parameter changes can be defined that are evaluated during
+% the merged models evaluation
+
+% One possibility is simply to define an algebraic expression for a parameter
+k3 = exp(-0.4*time)
+
+% The second possibility is to use piecewiseSB expressions (type "help piecewiseSB"
+% for more information on the syntax):
+k4 = piecewiseSB(-0.5,ge(time,5),0)
+
+% Another possibility is to use lookup tables, such as:
+k5 = interp0SB([0,1,2,3,4],[12,2,3,44,2],time)    % zero order interpolation
+%k5 = interp1SB([0,1,2,3,4],[12,2,3,44,2],time)   % first order interpolation
+%k5 = interpcsSB([0,1,2,3,4],[12,2,3,44,2],time)  % cubic spline interpolation
+
+% Obviously, in this section the expressions have full access to the functions 
+% defined in the models MODEL FUNCTION section.
+
+********** EXPERIMENT STATE CHANGES
+% State changes in the experiment description can only be done at certain 
+% time points yet. This will probably also change in a coming revision.
+
+time = 10, A = 5, B = 1+A
+time = 15, B = 10*A
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/experiment/model.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/experiment/model.txt
new file mode 100644
index 0000000000000000000000000000000000000000..2c34ae74a8e281bdc3765b7163bf7453b3e9c3ed
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/experiment/model.txt
@@ -0,0 +1,33 @@
+********** MODEL NAME
+experiment example
+
+********** MODEL NOTES
+just a simple model to be used to 
+explain the experiment description
+
+********** MODEL STATES
+d/dt(A) = -R % eoh oh oho hoh 
+d/dt(B) = +R
+
+A(0) = 0
+B(0) = 0
+********** MODEL PARAMETERS
+k1 = 0.1
+k2 = 1
+k3 = 0
+k4 = 0
+k5 = 0
+
+********** MODEL VARIABLES
+
+
+********** MODEL REACTIONS
+R = (k1+k2+k3+k4+k5)*A % oeh fouh oh oho u
+
+********** MODEL FUNCTIONS
+f(x,y) = x+y
+
+********** MODEL EVENTS
+
+
+********** MODEL MATLAB FUNCTIONS
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/experiment/readme.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/experiment/readme.m
new file mode 100644
index 0000000000000000000000000000000000000000..ef6a986287f91c6d5f29e7bedba40428335013f1
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/experiment/readme.m
@@ -0,0 +1,39 @@
+% Example for the experiment description
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+clc; clear all;
+
+%% load the model (have a look at the model.txt file
+model = SBmodel('model.txt')
+
+%% load the experiment
+experiment = SBexperiment('experiment.exp')
+
+%% merge model and experiment
+expmodel = SBmergemodexp(model,experiment)
+
+%% Have a look at the merged model
+SBcreateTEXTfile(expmodel,'mergedModelWithExperiment');
+edit mergedModelWithExperiment.txt
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/functionsExample.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/functionsExample.txt
new file mode 100644
index 0000000000000000000000000000000000000000..1009c2622cf31b2dae5f4c9ae6c2ec46f2c75d3b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/functionsExample.txt
@@ -0,0 +1,46 @@
+********** MODEL NAME
+untitled
+
+********** MODEL NOTES
+
+
+********** MODEL STATES
+d/dt(s1) = -re1 %species
+d/dt(s2) = +re1 %species
+d/dt(s3) = -re2+re4 %species
+d/dt(s4) = +re2-re5 %species
+d/dt(s5) = -re3 %species
+d/dt(s6) = +re3 %species
+
+s1(0) = 1
+s2(0) = 0.5
+s3(0) = 0.2
+s4(0) = 0.1
+s5(0) = 0.8
+s6(0) = 0.2
+
+********** MODEL PARAMETERS
+s7 = 1 %boundary species
+s8 = 1 %boundary species
+default = 1 %compartment size
+
+********** MODEL VARIABLES
+x = f(s1,s2)
+y = g(s5)
+
+********** MODEL REACTIONS
+re1 = x*s1-2*s2 {reversible} %reaction kinetics
+re2 = s3 %reaction kinetics
+re3 = s4*s5-s4*s6 {reversible} %reaction kinetics
+re4 = y %reaction kinetics
+re5 = s4 %reaction kinetics
+
+********** MODEL FUNCTIONS
+f(x,y) = x+y
+g(x) = 2*x
+
+********** MODEL EVENTS
+
+
+********** MODEL MATLAB FUNCTIONS
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/functionsMATLABexample.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/functionsMATLABexample.txt
new file mode 100644
index 0000000000000000000000000000000000000000..abe048b4460a71fa44abb2114924cc76b91a8867
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/functionsMATLABexample.txt
@@ -0,0 +1,51 @@
+********** MODEL NAME
+untitled
+
+********** MODEL NOTES
+
+
+********** MODEL STATES
+d/dt(s1) = -re1 %species
+d/dt(s2) = +re1 %species
+d/dt(s3) = -re2+re4 %species
+d/dt(s4) = +re2-re5 %species
+d/dt(s5) = -re3 %species
+d/dt(s6) = +re3 %species
+
+s1(0) = 1
+s2(0) = 0.5
+s3(0) = 0.2
+s4(0) = 0.1
+s5(0) = 0.8
+s6(0) = 0.2
+
+********** MODEL PARAMETERS
+s7 = 1 %boundary species
+s8 = 1 %boundary species
+default = 1 %compartment size
+
+********** MODEL VARIABLES
+x = 1+unitstep(time,10)
+y = 1+unitstep(time,15)
+
+
+********** MODEL REACTIONS
+re1 = x*s1-2*s2 {reversible} %reaction kinetics
+re2 = s3 %reaction kinetics
+re3 = s4*s5-s4*s6 {reversible} %reaction kinetics
+re4 = y %reaction kinetics
+re5 = s4 %reaction kinetics
+
+********** MODEL FUNCTIONS
+
+
+********** MODEL MATLAB FUNCTIONS
+% MATLAB function realizing a unitstep at a given timeinstant.
+% This function can be called within the rest of the model.
+function [result] = unitstep(time,timeinstant)
+if time <= timeinstant,
+result = 0;
+else
+result = 1;
+end
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/hofmann.txtbc b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/hofmann.txtbc
new file mode 100644
index 0000000000000000000000000000000000000000..767eabc2fb3ba6cd146277b8da1c0e1f19f706fa
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/hofmann.txtbc
@@ -0,0 +1,88 @@
+********** MODEL NAME
+Hofmann
+
+********** MODEL NOTES
+Biophysical Journal Volume 71, 1996, 3051-3063
+Volume: 30e-6 Liter
+
+********** MODEL STATE INFORMATION
+G(0) = 3000 
+Gact(0) = 0 
+GactPDEact(0) = 0 
+Gr(0) = 0 
+PDE(0) = 300 
+R(0) = 500 
+Ract(0) = 1 
+RactG(0) = 0 
+Ri(0) = 0 
+
+********** MODEL PARAMETERS
+k1f = 200
+k1r = 0
+
+k2f = 1
+k2r = 0
+
+k3f = 2000 % 2000 -> 8000
+k3r = 0
+
+k4f = 1
+k4r = 0
+
+k5f = 0.5 % 0.5 -> 3.3
+k5r = 0
+
+k6f = 0.05
+k6r = 0
+
+k7f = 2
+k7r = 0
+
+
+k8r = 0
+k8f = 2
+
+********** MODEL VARIABLES
+
+
+********** MODEL REACTIONS
+R <=> Ract : R1
+    vf = k1f*R
+    vr = k1r*Ract
+
+Ract + G <=> RactG : R2
+    vf = k2f*Ract*G
+    vr = k2r*RactG
+    
+RactG <=> Ract + Gact : R3
+    vf = k3f*RactG
+    vr = k3r*Ract*Gact
+    
+Gact + PDE <=> GactPDEact : R4
+    vf = k4f*Gact*PDE
+    vr = k4r*GactPDEact
+    
+Ract <=> Ri : R5
+    vf = k5f*Ract
+    vr = k5r*Ri
+    
+Gact <=> Gr : R6
+    vf = k6f*Gact
+    vr = k6r*Gr
+    
+GactPDEact <=> PDE + Gr : R7
+    vf = k7f*GactPDEact
+    vr = k7r*PDE*Gr
+    
+Gr <=> G : R8
+    vf = k8f*Gr
+    vr = k8r*G
+    
+    
+********** MODEL FUNCTIONS
+
+
+********** MODEL EVENTS
+
+
+********** MODEL MATLAB FUNCTIONS
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/novak_tyson.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/novak_tyson.m
new file mode 100644
index 0000000000000000000000000000000000000000..067a803d0cb25890ed31cdabf4fc95917345f747
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/novak_tyson.m
@@ -0,0 +1,29 @@
+% Script for the creation of an SBmodel of the Novak-Tyson cell cycle 
+% model, described in J. theor. Biol. (1998) 195, 69-85
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+sbm = SBmodel('NovakTysonModel.txt')
+disp('The variable containing the Novak-Tyson model is: sbm');
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/special/example_algebraic_rule.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/special/example_algebraic_rule.txt
new file mode 100644
index 0000000000000000000000000000000000000000..a23638238532e584d7908b7eb6c791b315c32757
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/special/example_algebraic_rule.txt
@@ -0,0 +1,42 @@
+********** MODEL NAME
+simple AR example
+
+********** MODEL NOTES
+A simple example model using an algebraic rule
+
+********** MODEL STATES
+% Differential equations are defined first
+d/dt(A) = -R2 + R1
+d/dt(B) = -R3 + R2 
+
+% After the ODEs you can define the algebraic rules (ARs) in the following syntax:
+% 0 = "mathematical expression" : "defined algebraic state" {"additional information for the state"} % comment
+0 = C+B-5 : C % Algebraic rule, defining C (here a moiety conservation)
+              % OF COURSE: it would be better to define a variable below as:   C = 5-B
+              % but here I just want to demonstrate how to define ARs
+              
+% Finally you define the initial conditions. The initial conditions for the 
+% algebraic states do not have to be consistent since the solver is able to find a 
+% solution. But it is better and just makes more sense to at least try to find correct
+% initial conditions.
+A(0) = 1
+B(0) = 0  
+C(0) = 5
+
+********** MODEL PARAMETERS
+k2 = 2
+k3 = 0.1
+
+********** MODEL VARIABLES
+
+********** MODEL REACTIONS
+R1 = 0.1
+R2 = k2*A
+R3 = k3*B
+
+********** MODEL FUNCTIONS
+
+********** MODEL EVENTS
+
+********** MODEL MATLAB FUNCTIONS
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/special/example_delay.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/special/example_delay.txt
new file mode 100644
index 0000000000000000000000000000000000000000..5beca8ed688a724290ac432a6a827d642c86fab0
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/special/example_delay.txt
@@ -0,0 +1,40 @@
+********** MODEL NAME
+Simple example model containing a delay
+
+********** MODEL NOTES
+Delays can be added anywhere in the model. The function that 
+realizes a delay is called "delaySB" and has the following syntax:
+
+    output = delaySB(input, tau)
+    
+where "input" a mathematical expression or a single variable etc., that
+should be delayed, "tau" is the delay, and "output" is the delayed thing.
+
+Of course you can have any number of events in a model. Within
+the mathematical expression inside a delay can also appear any number of 
+delays (if that's what you like ... one never knows :))
+
+ONLY Limitation: The delay "tau" has to be constant within a single delay.
+Otherwise delay times can be different for different delays.
+
+The history of a delay is set automatically to the first input value. 
+In the example below the history of delaySB(B,5) will be B(0) = 0.5.
+
+********** MODEL STATES
+d/dt(A) = -2*A + delaySB(B,5)
+d/dt(B) = -1*B + A
+
+A(0) = 1
+B(0) = 0.5
+
+********** MODEL PARAMETERS
+
+********** MODEL VARIABLES
+
+********** MODEL REACTIONS
+
+********** MODEL FUNCTIONS
+
+********** MODEL EVENTS
+
+********** MODEL MATLAB FUNCTIONS
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/special/example_delayed_event.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/special/example_delayed_event.txt
new file mode 100644
index 0000000000000000000000000000000000000000..b7b8e9fcfa07473b5a53fee1d99a7196662796fc
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/special/example_delayed_event.txt
@@ -0,0 +1,48 @@
+********** MODEL NAME
+Simple example model containing a delayed event
+
+********** MODEL NOTES
+Please check first the "example_delay.txt" model to learn about the
+delaySB function.
+
+Delayed events are defined as follows: Given that the trigger function of 
+an event fires at "time=te" and the delay is "tau". Then the event 
+assignments are executed at "time=te+tau" based on the assignment values 
+at "time=te".
+
+A non-delayed event is defined by:
+
+event1 = gt(time,5),A,2*A
+
+This will set "A" to "2*A" as soon as "time" gets larger than "5". 
+Employing the "delaySB" function a delayed version of this event can now 
+easily be written as:
+
+eventdelayed1 = delaySB(gt(time,5),tau),A,delaySB(2*A,tau)
+
+This means that the firing of the event is delayed by "tau" through the 
+delaySB function around the trigger and the assignment value is delayed 
+by the same amount, leading to a correct assignment.
+
+Just have a look at the example below and run it. Do to its simplicity it
+can easily been checked that the result is correct. However, it works 
+equally well in much more complex models.
+
+********** MODEL STATES
+d/dt(A) = -0.2*A
+
+A(0) = 1
+
+********** MODEL PARAMETERS
+tau = 2
+
+********** MODEL VARIABLES
+
+********** MODEL REACTIONS
+
+********** MODEL FUNCTIONS
+
+********** MODEL EVENTS
+event = delaySB(gt(time,5),tau),A,delaySB(2*A,tau)
+
+********** MODEL MATLAB FUNCTIONS
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/special/example_fast_reaction.txtbc b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/special/example_fast_reaction.txtbc
new file mode 100644
index 0000000000000000000000000000000000000000..e725d7748c2d4618858af9490c811b1c30767aaa
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/special/example_fast_reaction.txtbc
@@ -0,0 +1,53 @@
+********** MODEL NAME
+Simple example fast reaction
+
+********** MODEL NOTES
+Just a simple example model to demonstrate how to define a fast reaction
+Please scroll down to the definition of reaction "r2". There is written
+"{fast}", which defines that "r2" is a fast reaction.
+
+Try to simulate the model both with and without the "{fast}" setting
+and compare the differences.
+
+Please note that models with moiety conservation can not directly be simulated
+if they contain fast flags. You first need to take away these moiety conservations
+using the "SBreducemodel" function.
+
+********** MODEL STATE INFORMATION
+s1(0) = 0
+s2(0) = 0 
+s3(0) = 0 
+
+********** MODEL PARAMETERS
+k0 = 1
+k1 = 1
+k2f = 2
+k2r = 1
+k3 = 1
+
+********** MODEL VARIABLES
+
+
+********** MODEL REACTIONS
+   => s1 : re0
+    vf = k0
+    
+s1 => s2 : re1 
+	vf = k1 * s1 
+
+s2 <=> s3 : re2 {fast}
+	vf = k2f * s2 
+    vr = k2r * s3
+
+s3 =>     : re3 
+	vf = k3 * s3 
+
+
+********** MODEL FUNCTIONS
+
+
+********** MODEL EVENTS
+
+
+********** MODEL MATLAB FUNCTIONS
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/special/runExamples.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/special/runExamples.m
new file mode 100644
index 0000000000000000000000000000000000000000..098b75ea0ad2361c92363a523e7df607165a5845
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/special/runExamples.m
@@ -0,0 +1,71 @@
+% This example script runs the example models in this folder to demonstrate
+% the toolbox' capability of simulating algebraic rules, delays, delayed
+% events, and fast reactions.
+
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+% It's GPL 
+
+%% ALGEBRAIC RULES
+clc; clear all;
+disp('ALGEBRAIC RULES EXAMPLE');
+% Please have first a look at the model and read the documentation in it.
+disp('Please have first a look at the model and read the documentation in it.');
+edit example_algebraic_rule.txt
+disp('Press any key to continue'); pause;
+% Load the model
+model = SBmodel('example_algebraic_rule.txt');
+% Simulate the model
+SBsimulate(model)
+% Now you can browse the visualization and check the result
+disp('Now you can browse the visualization and check the result.');
+disp('Press any key to continue'); pause;
+ 
+%% FAST REACTIONS
+clc; clear all;
+disp('FAST REACTIONS EXAMPLE');
+% Please have first a look at the model and read the documentation in it.
+disp('Please have first a look at the model and read the documentation in it.');
+edit example_fast_reaction.txtbc
+disp('Press any key to continue'); pause;
+% Load the model
+model = SBmodel('example_fast_reaction.txtbc');
+% Simulate the model
+SBsimulate(model)
+% Now you can browse the visualization and check the result
+disp('Now you can browse the visualization and check the result.');
+disp('Press any key to continue'); pause;
+
+%% DELAY
+clc; clear all;
+disp('DELAY EXAMPLE');
+% Please have first a look at the model and read the documentation in it.
+disp('Please have first a look at the model and read the documentation in it.');
+edit example_delay.txt
+disp('Press any key to continue'); pause;
+% Load the model
+model = SBmodel('example_delay.txt');
+% Simulate the model
+SBsimulate(model)
+% Now you can browse the visualization and check the result
+disp('Now you can browse the visualization and check the result.');
+disp('Press any key to continue'); pause;
+
+%% DELAYED EVENT
+clc; clear all;
+disp('DELAYED EVENTS EXAMPLE');
+% Please have first a look at the model and read the documentation in it.
+disp('Please have first a look at the model and read the documentation in it.');
+edit example_delayed_event.txt
+disp('Press any key to continue'); pause;
+% Load the model
+model = SBmodel('example_delayed_event.txt');
+% Simulate the model
+SBsimulate(model)
+% Now you can browse the visualization and check the result
+disp('Now you can browse the visualization and check the result.');
+disp('Press any key to continue'); pause;
+
+%% DONE
+clc; clear all;
+disp('DONE');
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/stochexample.txtbc b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/stochexample.txtbc
new file mode 100644
index 0000000000000000000000000000000000000000..85897c454a488904ea603d4445f82fc900d0fdaf
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/stochexample.txtbc
@@ -0,0 +1,69 @@
+********** MODEL NAME
+Example model for stochastic simulation
+********** MODEL NOTES
+The model is based on the model published in: Unified phototransduction 
+model from Hamer et al., Visual Neuroscience 22, 417-436
+
+Simplified considerably to test the rhodopsin shut-off.
+
+% Test simulation using:
+time = 20
+volume = []   % since species in numbers
+units = []    % since species in numbers
+runs = 1      % single run
+Nsample = 1   % each reaction event is reported
+SBstochsim(model,time,volume,units,runs,Nsample)
+
+********** MODEL STATE INFORMATION
+R0(0) = 1           % a single photoactivated rhodopsin (GPCR)
+Arr(0) = 3.13e7     % number of arrestin molecules
+Gt(0) = 3.6e8       % number of transducin molecukes (G protein)
+
+********** MODEL PARAMETERS
+kA1 = 8.45575079872204e-008     
+kA2 = 0.0023		
+ktherm = 0.0238
+kG1 = 2.64564444444444e-005     
+kG2 = 2000      
+kG3 = 2000 
+kG4_GDP = 600
+kG5_GTP = 750     
+kG6 = 2000 
+
+********** MODEL VARIABLES
+
+********** MODEL REACTIONS
+
+% Arr shutoff
+Arr + R0 <=> R0_Arr : v_A2_0
+	vf = kA1 * Arr * R0 
+    vr = kA2 * R0_Arr
+
+% Thermal decay
+R0 => Ops  : v_therm0
+   vf = ktherm * R0
+       
+% Rhodopsin and transducin binding
+Gt + R0 <=> R0_Gt : v_A3a_0
+    vf = kG1 * Gt * R0 
+    vr = kG2 * R0_Gt
+
+% GDP dissociation from Rn_Gt   
+R0_Gt <=> R0_G : v_A3b_0
+    vf = kG3 * R0_Gt
+    vr = kG4_GDP * R0_G
+
+% GTP binding to Rn_G   
+R0_G => R0_G_GTP : v_A3c_0
+	vf = kG5_GTP * R0_G
+
+% Rn_G_GTP dissociation to Rn and G_GTP
+R0_G_GTP => R0 + G_GTP : v_A3d_0
+	vf = kG6 * R0_G_GTP 
+
+********** MODEL FUNCTIONS
+
+********** MODEL EVENTS
+
+********** MODEL MATLAB FUNCTIONS
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/testsingular.xml b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/testsingular.xml
new file mode 100644
index 0000000000000000000000000000000000000000..950c772ecc800359678bfdd22e40052357287c51
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/_EXAMPLES/testsingular.xml
@@ -0,0 +1,329 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- Created by SBML API 2.0(a17.0) -->
+<sbml level="2" version="1" xmlns="http://www.sbml.org/sbml/level2" xmlns:celldesigner="http://www.sbml.org/2001/ns/celldesigner">
+<model id="untitled">
+<annotation>
+<celldesigner:modelVersion>2.3</celldesigner:modelVersion>
+<celldesigner:modelDisplay sizeX="640" sizeY="480"/>
+<celldesigner:listOfCompartmentAliases/>
+<celldesigner:listOfSpeciesAliases>
+<celldesigner:speciesAlias id="a0" species="s1">
+<celldesigner:activity>inactive</celldesigner:activity>
+<celldesigner:bounds h="24.0" w="80.0" x="73.97571502024759" y="293.4864913960946"/>
+<celldesigner:singleLine width="0.0"/>
+<celldesigner:paint color="7fcccccc" scheme="Color"/>
+</celldesigner:speciesAlias>
+<celldesigner:speciesAlias id="a1" species="s2">
+<celldesigner:activity>inactive</celldesigner:activity>
+<celldesigner:bounds h="24.0" w="80.0" x="27.274419092024885" y="167.3448216894213"/>
+<celldesigner:singleLine width="0.0"/>
+<celldesigner:paint color="7fcccccc" scheme="Color"/>
+</celldesigner:speciesAlias>
+<celldesigner:speciesAlias id="a2" species="s3">
+<celldesigner:activity>inactive</celldesigner:activity>
+<celldesigner:bounds h="24.0" w="80.0" x="136.67294588839906" y="57.8963767359279"/>
+<celldesigner:singleLine width="0.0"/>
+<celldesigner:paint color="7fcccccc" scheme="Color"/>
+</celldesigner:speciesAlias>
+<celldesigner:speciesAlias id="a3" species="s4">
+<celldesigner:activity>inactive</celldesigner:activity>
+<celldesigner:bounds h="24.0" w="80.0" x="174.0761660346129" y="186.88968239737645"/>
+<celldesigner:singleLine width="0.0"/>
+<celldesigner:paint color="7fcccccc" scheme="Color"/>
+</celldesigner:speciesAlias>
+<celldesigner:speciesAlias id="a4" species="s5">
+<celldesigner:activity>inactive</celldesigner:activity>
+<celldesigner:bounds h="24.0" w="80.0" x="348.9700463077219" y="134.67331096391314"/>
+<celldesigner:singleLine width="0.0"/>
+<celldesigner:paint color="7fcccccc" scheme="Color"/>
+</celldesigner:speciesAlias>
+<celldesigner:speciesAlias id="a5" species="s6">
+<celldesigner:activity>inactive</celldesigner:activity>
+<celldesigner:bounds h="24.0" w="80.0" x="386.6132632557188" y="249.653363972029"/>
+<celldesigner:singleLine width="0.0"/>
+<celldesigner:paint color="7fcccccc" scheme="Color"/>
+</celldesigner:speciesAlias>
+<celldesigner:speciesAlias id="a6" species="s7">
+<celldesigner:activity>inactive</celldesigner:activity>
+<celldesigner:bounds h="24.0" w="80.0" x="86.7190776653897" y="4.166166507919442"/>
+<celldesigner:singleLine width="0.0"/>
+<celldesigner:paint color="7fcccccc" scheme="Color"/>
+</celldesigner:speciesAlias>
+<celldesigner:speciesAlias id="a7" species="s8">
+<celldesigner:activity>inactive</celldesigner:activity>
+<celldesigner:bounds h="24.0" w="80.0" x="229.55466391098543" y="328.7473969819038"/>
+<celldesigner:singleLine width="0.0"/>
+<celldesigner:paint color="7fcccccc" scheme="Color"/>
+</celldesigner:speciesAlias>
+</celldesigner:listOfSpeciesAliases>
+<celldesigner:listOfGroups/>
+<celldesigner:listOfProteins/>
+<celldesigner:listOfBlockDiagrams/>
+</annotation>
+<listOfCompartments>
+<compartment id="default" size="1.0"/>
+</listOfCompartments>
+<listOfSpecies>
+<species compartment="default" id="s1" initialAmount="1.0" name="s1">
+<annotation>
+<celldesigner:positionToCompartment>inside</celldesigner:positionToCompartment>
+<celldesigner:speciesIdentity>
+<celldesigner:class>UNKNOWN</celldesigner:class>
+<celldesigner:name>s1</celldesigner:name>
+</celldesigner:speciesIdentity>
+</annotation>
+</species>
+<species compartment="default" id="s2" initialAmount="0.5" name="s2">
+<annotation>
+<celldesigner:positionToCompartment>inside</celldesigner:positionToCompartment>
+<celldesigner:speciesIdentity>
+<celldesigner:class>UNKNOWN</celldesigner:class>
+<celldesigner:name>s2</celldesigner:name>
+</celldesigner:speciesIdentity>
+<celldesigner:listOfCatalyzedReactions>
+<celldesigner:catalyzed reaction="re2"/>
+</celldesigner:listOfCatalyzedReactions>
+</annotation>
+</species>
+<species compartment="default" id="s3" initialAmount="0.2" name="s3">
+<annotation>
+<celldesigner:positionToCompartment>inside</celldesigner:positionToCompartment>
+<celldesigner:speciesIdentity>
+<celldesigner:class>UNKNOWN</celldesigner:class>
+<celldesigner:name>s3</celldesigner:name>
+</celldesigner:speciesIdentity>
+</annotation>
+</species>
+<species compartment="default" id="s4" initialAmount="0.1" name="s4">
+<annotation>
+<celldesigner:positionToCompartment>inside</celldesigner:positionToCompartment>
+<celldesigner:speciesIdentity>
+<celldesigner:class>UNKNOWN</celldesigner:class>
+<celldesigner:name>s4</celldesigner:name>
+</celldesigner:speciesIdentity>
+<celldesigner:listOfCatalyzedReactions>
+<celldesigner:catalyzed reaction="re3"/>
+</celldesigner:listOfCatalyzedReactions>
+</annotation>
+</species>
+<species compartment="default" id="s5" initialAmount="0.8" name="s5">
+<annotation>
+<celldesigner:positionToCompartment>inside</celldesigner:positionToCompartment>
+<celldesigner:speciesIdentity>
+<celldesigner:class>UNKNOWN</celldesigner:class>
+<celldesigner:name>s5</celldesigner:name>
+</celldesigner:speciesIdentity>
+</annotation>
+</species>
+<species compartment="default" id="s6" initialAmount="0.2" name="s6">
+<annotation>
+<celldesigner:positionToCompartment>inside</celldesigner:positionToCompartment>
+<celldesigner:speciesIdentity>
+<celldesigner:class>UNKNOWN</celldesigner:class>
+<celldesigner:name>s6</celldesigner:name>
+</celldesigner:speciesIdentity>
+</annotation>
+</species>
+<species boundaryCondition="true" compartment="default" id="s7" initialAmount="1.0" name="s7">
+<annotation>
+<celldesigner:positionToCompartment>inside</celldesigner:positionToCompartment>
+<celldesigner:speciesIdentity>
+<celldesigner:class>UNKNOWN</celldesigner:class>
+<celldesigner:name>s7</celldesigner:name>
+</celldesigner:speciesIdentity>
+</annotation>
+</species>
+<species boundaryCondition="true" compartment="default" id="s8" initialAmount="1.0" name="s8">
+<annotation>
+<celldesigner:positionToCompartment>inside</celldesigner:positionToCompartment>
+<celldesigner:speciesIdentity>
+<celldesigner:class>UNKNOWN</celldesigner:class>
+<celldesigner:name>s8</celldesigner:name>
+</celldesigner:speciesIdentity>
+</annotation>
+</species>
+</listOfSpecies>
+<listOfReactions>
+<reaction id="re1" name="re1">
+<annotation>
+<celldesigner:name>re1</celldesigner:name>
+<celldesigner:reactionType>STATE_TRANSITION</celldesigner:reactionType>
+<celldesigner:baseReactants>s1</celldesigner:baseReactants>
+<celldesigner:baseProducts>s2</celldesigner:baseProducts>
+<celldesigner:editPoints>0.33333333333333304,-1.1102230246251565E-16 0.6666666666666661,-1.1102230246251565E-16</celldesigner:editPoints>
+</annotation>
+<listOfReactants>
+<speciesReference species="s1">
+<annotation>
+<celldesigner:alias>a0</celldesigner:alias>
+</annotation>
+</speciesReference>
+</listOfReactants>
+<listOfProducts>
+<speciesReference species="s2">
+<annotation>
+<celldesigner:alias>a1</celldesigner:alias>
+</annotation>
+</speciesReference>
+</listOfProducts>
+<kineticLaw>
+<math xmlns="http://www.w3.org/1998/Math/MathML">
+<apply>
+<minus/>
+<apply>
+<times/>
+<cn type="integer">3</cn>
+<ci>s1</ci>
+</apply>
+<apply>
+<times/>
+<cn type="integer">2</cn>
+<ci>s2</ci>
+</apply>
+</apply>
+</math>
+</kineticLaw>
+</reaction>
+<reaction id="re2" name="re2" reversible="false">
+<annotation>
+<celldesigner:name>re2</celldesigner:name>
+<celldesigner:reactionType>STATE_TRANSITION</celldesigner:reactionType>
+<celldesigner:baseReactants>s3</celldesigner:baseReactants>
+<celldesigner:baseProducts>s4</celldesigner:baseProducts>
+<celldesigner:editPoints>0.3333333333333333,-4.440892098500626E-16 0.6666666666666667,0.0</celldesigner:editPoints>
+<celldesigner:listOfModification>
+<celldesigner:modification aliases="a1" editPoints="0.33333333333333337,-4.440892098500626E-16 0.6666666666666665,-4.440892098500626E-16" modifiers="s2" targetLineIndex="-1,1" type="CATALYSIS"/>
+</celldesigner:listOfModification>
+</annotation>
+<listOfReactants>
+<speciesReference species="s3">
+<annotation>
+<celldesigner:alias>a2</celldesigner:alias>
+</annotation>
+</speciesReference>
+</listOfReactants>
+<listOfProducts>
+<speciesReference species="s4">
+<annotation>
+<celldesigner:alias>a3</celldesigner:alias>
+</annotation>
+</speciesReference>
+</listOfProducts>
+<listOfModifiers>
+<modifierSpeciesReference species="s2">
+<annotation>
+<celldesigner:alias>a1</celldesigner:alias>
+</annotation>
+</modifierSpeciesReference>
+</listOfModifiers>
+<kineticLaw>
+<math xmlns="http://www.w3.org/1998/Math/MathML">
+<ci>s3</ci>
+</math>
+</kineticLaw>
+</reaction>
+<reaction id="re3" name="re3">
+<annotation>
+<celldesigner:name>re3</celldesigner:name>
+<celldesigner:reactionType>STATE_TRANSITION</celldesigner:reactionType>
+<celldesigner:baseReactants>s5</celldesigner:baseReactants>
+<celldesigner:baseProducts>s6</celldesigner:baseProducts>
+<celldesigner:editPoints>0.33333333333333287,0.0 0.6666666666666665,-8.881784197001252E-16</celldesigner:editPoints>
+<celldesigner:listOfModification>
+<celldesigner:modification aliases="a3" editPoints="0.33333333333333326,-1.1102230246251565E-16 0.6666666666666667,-2.220446049250313E-16" modifiers="s4" targetLineIndex="-1,1" type="CATALYSIS"/>
+</celldesigner:listOfModification>
+</annotation>
+<listOfReactants>
+<speciesReference species="s5">
+<annotation>
+<celldesigner:alias>a4</celldesigner:alias>
+</annotation>
+</speciesReference>
+</listOfReactants>
+<listOfProducts>
+<speciesReference species="s6">
+<annotation>
+<celldesigner:alias>a5</celldesigner:alias>
+</annotation>
+</speciesReference>
+</listOfProducts>
+<listOfModifiers>
+<modifierSpeciesReference species="s4">
+<annotation>
+<celldesigner:alias>a3</celldesigner:alias>
+</annotation>
+</modifierSpeciesReference>
+</listOfModifiers>
+<kineticLaw>
+<math xmlns="http://www.w3.org/1998/Math/MathML">
+<apply>
+<times/>
+<ci>s4</ci>
+<apply>
+<minus/>
+<ci>s5</ci>
+<ci>s6</ci>
+</apply>
+</apply>
+</math>
+</kineticLaw>
+</reaction>
+<reaction id="re4" name="re4" reversible="false">
+<annotation>
+<celldesigner:name>re4</celldesigner:name>
+<celldesigner:reactionType>STATE_TRANSITION</celldesigner:reactionType>
+<celldesigner:baseReactants>s7</celldesigner:baseReactants>
+<celldesigner:baseProducts>s3</celldesigner:baseProducts>
+<celldesigner:editPoints>0.33333333333333304,2.220446049250313E-16 0.666666666666667,2.220446049250313E-16</celldesigner:editPoints>
+</annotation>
+<listOfReactants>
+<speciesReference species="s7">
+<annotation>
+<celldesigner:alias>a6</celldesigner:alias>
+</annotation>
+</speciesReference>
+</listOfReactants>
+<listOfProducts>
+<speciesReference species="s3">
+<annotation>
+<celldesigner:alias>a2</celldesigner:alias>
+</annotation>
+</speciesReference>
+</listOfProducts>
+<kineticLaw>
+<math xmlns="http://www.w3.org/1998/Math/MathML">
+<cn type="integer">1</cn>
+</math>
+</kineticLaw>
+</reaction>
+<reaction id="re5" name="re5" reversible="false">
+<annotation>
+<celldesigner:name>re5</celldesigner:name>
+<celldesigner:reactionType>STATE_TRANSITION</celldesigner:reactionType>
+<celldesigner:baseReactants>s4</celldesigner:baseReactants>
+<celldesigner:baseProducts>s8</celldesigner:baseProducts>
+<celldesigner:editPoints>0.33333333333333326,1.1102230246251565E-16 0.6666666666666672,0.0</celldesigner:editPoints>
+</annotation>
+<listOfReactants>
+<speciesReference species="s4">
+<annotation>
+<celldesigner:alias>a3</celldesigner:alias>
+</annotation>
+</speciesReference>
+</listOfReactants>
+<listOfProducts>
+<speciesReference species="s8">
+<annotation>
+<celldesigner:alias>a7</celldesigner:alias>
+</annotation>
+</speciesReference>
+</listOfProducts>
+<kineticLaw>
+<math xmlns="http://www.w3.org/1998/Math/MathML">
+<ci>s4</ci>
+</math>
+</kineticLaw>
+</reaction>
+</listOfReactions>
+</model>
+</sbml>
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/academicWarningSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/academicWarningSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..a29435d4d94ceb7bf9cd470cf738312930c639e7
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/academicWarningSB.m
@@ -0,0 +1,7 @@
+FLAGacademicWarning = 0;
+
+if FLAGacademicWarning,
+warning(sprintf('Function is located in the "_ACADEMIC" folder of the SBTOOLBOX2.\n\nThis means:\n    - No unit tests have been developed for this function\n    - This function is not subject to validation requirements for use\n      in clinical drug development projects\n    - This function should NOT be used in clinical drug development projects\n      where validated software is required\n    - You can still use this function for academic or exploratory purposes\n\nIf you do not want to get this message everytime you run this function,\nplease set the flag in the "academicWarningSB.m" file from 1 to 0.\n\n'));
+end
+      
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/checkDependenciesSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/checkDependenciesSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..4e3ab4f04d8d611822270c6846230c9ed01be405
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/checkDependenciesSB.m
@@ -0,0 +1,112 @@
+function [] = checkDependenciesSB()
+% checkDependenciesSB: checks if functions / scripts (*.m files) in the 
+% NON _ACADEMIC/_DEPRECATED/_EXPLORATORY folders depend on functions or scripts
+% (*.m files) in the _ACADEMIC/_DEPRECATED/_EXPLORATORY folders.
+% If such non-allowed dependencies are found, the user is warned.
+% ".svn" folders are not considered
+% The following function names are excluded from consideration:
+%       'disp.m','set.m','display.m','SBPOPstruct.m','SBimportSBML.m','SBimportSBMLCD.m'
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+clear all;
+
+global mfiles_ACADEMIC_DEPRECATED_EXPLORATORY dependencies_found
+mfiles_ACADEMIC_DEPRECATED_EXPLORATORY = {};
+dependencies_found = 0;
+
+disp('checkDependenciesSB: The following function names in the _ACADEMIC/_DEPRECATED/_EXPLORATORY folders are excluded from consideration:');
+disp('                     disp.m,set.m,display.m,SBPOPstruct.m,SBimportSBML.m,SBimportSBMLCD.m');
+
+old = pwd;
+SBPOP_FOLDER = fileparts(which(('installSBPOPpackage')));
+cd([SBPOP_FOLDER '/..']);
+% Get folder name of SBPOP PACKAGE
+[xdummyx,SBPOP_FOLDER_NAME] = fileparts(SBPOP_FOLDER);
+recurseFolderGET_ACADEMIC_mfiles(SBPOP_FOLDER_NAME);
+cd(old);
+
+% Remove some entries from the mfiles_ACADEMIC_DEPRECATED_EXPLORATORY list
+mfiles_ACADEMIC_DEPRECATED_EXPLORATORY = unique(mfiles_ACADEMIC_DEPRECATED_EXPLORATORY);
+remove = {'disp.m','set.m','display.m','SBPOPstruct.m','SBimportSBML.m','SBimportSBMLCD.m'};
+for k=1:length(remove),
+    ix = strmatch(remove{k},mfiles_ACADEMIC_DEPRECATED_EXPLORATORY,'exact');
+    if ~isempty(ix),
+        mfiles_ACADEMIC_DEPRECATED_EXPLORATORY{ix} = 'xxxxxxxxxxxxxxxxxxxxxxxxx.xxx';
+    end
+end
+
+old = pwd;
+cd([SBPOP_FOLDER '/..']);
+check_NONACADEMIC_files(SBPOP_FOLDER_NAME);
+cd(old);
+
+if dependencies_found == 0,
+    disp('No dependencies of normal functions on _ACADEMIC or _DEPRECATED or _EXPLORATORY functions found.');
+end
+return
+
+function check_NONACADEMIC_files(folder)
+global mfiles_ACADEMIC_DEPRECATED_EXPLORATORY dependencies_found
+% change folder
+cd(folder);
+% get list of all m files if ACADEMIC or DEPRECATED folders
+if isempty(strfind(pwd,'_ACADEMIC')) && isempty(strfind(pwd,'_DEPRECATED')) && isempty(strfind(pwd,'_EXPLORATORY')),
+    files = dir('*.m');
+    for k=1:length(files),
+        content = fileread(files(k).name);
+        for k2=1:length(mfiles_ACADEMIC_DEPRECATED_EXPLORATORY),
+            ix = regexp(content,['\<' strrep(mfiles_ACADEMIC_DEPRECATED_EXPLORATORY{k2},'.m','') '[\s]*\(']);
+            if ~isempty(ix),
+                fprintf('Call to _ACADEMIC or _DEPRECATED or _EXPLORATORY function "%s" found in function "%s" in path "%s".\n',mfiles_ACADEMIC_DEPRECATED_EXPLORATORY{k2},files(k).name,pwd);
+                dependencies_found = 1;
+            end
+        end
+    end
+end
+% recurse in all subfolders
+allfiles = dir;
+for k = 1:length(allfiles),
+    if ~strcmp(allfiles(k).name,'.svn') && ~strcmp(allfiles(k).name,'..') && ~strcmp(allfiles(k).name,'.') && allfiles(k).isdir == 1,
+        check_NONACADEMIC_files(allfiles(k).name);
+    end
+end
+% up we go
+cd ..
+return
+
+
+function recurseFolderGET_ACADEMIC_mfiles(folder)
+global mfiles_ACADEMIC_DEPRECATED_EXPLORATORY
+% change folder
+cd(folder);
+% get list of all m files if ACADEMIC or DEPRECATED folders
+if ~isempty(strfind(pwd,'_ACADEMIC')) || ~isempty(strfind(pwd,'_DEPRECATED')) || ~isempty(strfind(pwd,'_EXPLORATORY')),
+    files = dir('*.m');
+    mfiles_ACADEMIC_DEPRECATED_EXPLORATORY = {mfiles_ACADEMIC_DEPRECATED_EXPLORATORY{:} files.name};
+end
+% recurse in all subfolders
+allfiles = dir;
+for k = 1:length(allfiles),
+    if ~strcmp(allfiles(k).name,'.svn') && ~strcmp(allfiles(k).name,'..') && ~strcmp(allfiles(k).name,'.') && allfiles(k).isdir == 1,
+        recurseFolderGET_ACADEMIC_mfiles(allfiles(k).name);
+    end
+end
+% up we go
+cd ..
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/compatibility/mat2datasetSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/compatibility/mat2datasetSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..2ee37ac8432feec3eb6749a66571c11a2f1d6432
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/compatibility/mat2datasetSB.m
@@ -0,0 +1,46 @@
+function [output] = mat2datasetSB(x,colNames)
+% mat2datasetSB: converts a double matrix to a dataset
+% Function required to allow SBPOP be compatible with pre R2013 versions of MATLAB
+%
+%   d = mat2datasetSB(x)
+%   d = mat2datasetSB(x,colNames)
+%
+% x:        matlab matrix
+% colNames: cell-array with columnnames
+
+% Information:
+% ============
+% Copyright (C) 2013 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+if nargin == 1,
+    colNames = {};
+    for k=1:size(x,2),
+        colNames{k} = sprintf('x%d',k);
+    end
+end
+
+if length(colNames) ~= size(x,2),
+    error('Incorrect number of column names.');
+end
+
+output = dataset();
+for k=1:size(x,2),
+    output.(colNames{k}) = x(:,k);
+end
+
+    
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/compatibility/strmatchSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/compatibility/strmatchSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..3bd0613be59b7dfd4a5255d903413ee3c4cd53ad
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/compatibility/strmatchSB.m
@@ -0,0 +1,65 @@
+function [I] = strmatchSB(str,strarray,varargin)
+% strmatchSB: emulates the functionality of strmatch. strmatch will be
+% removed from standard matlab soon (currently R2012a).
+%
+% I = strmatchSB(STR, STRARRAY) looks through the rows of the character
+% array or cell array of strings STRARRAY to find strings that begin
+% with the string contained in STR, and returns the matching row indices.
+% Any trailing space characters in STR or STRARRAY are ignored when
+% matching. strmatch is fastest when STRARRAY is a character array.
+% 
+% I = strmatchSB(STR, STRARRAY, 'exact') compares STR with each row of
+% STRARRAY, looking for an exact match of the entire strings. Any
+% trailing space characters in STR or STRARRAY are ignored when matching.
+
+% Information:
+% ============
+% Copyright (C) 2013 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+% if verLessThan('matlab', '7.14'),
+%     % strmatch exists
+%     I = strmatch(str,strarray,varargin{:}); %#ok<*MATCH3>
+% else
+    % In newer versions "strmatch" might not exist - use a workaround instead
+
+    % Check if strarray is a string array and if yes, convert to cell-array
+    if ischar(strarray),
+        strarraynew = {};
+        for k=1:size(strarray,1),
+            strarraynew{k} = strarray(k,:);
+        end
+        strarray = strarraynew;
+    end
+    
+    if nargin==3,
+        if strcmp(varargin{1},'exact'),
+            I = find(strcmp(str,strarray));
+            I = I(:);
+        else
+            error('Third input argument to strmatchSB needs to be "exact" or not specified.');
+        end
+    else
+        I = find(strncmp(str,strarray,length(str)));
+        I = I(:);
+    end
+% end
+        
+if isempty(I),
+    I = [];
+end
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/cell2wraptextSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/cell2wraptextSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..7d4ab44287f6d7238860f12d0f8f3595f6ec49c7
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/cell2wraptextSB.m
@@ -0,0 +1,59 @@
+function [text] = cell2wraptextSB(input,rowmax,varargin)
+% cell2wraptextSB: Takes a cell-array of strings and formats it into a 
+% string. The separator characters can be chosen and the maximum number of
+% elements in a row.
+%
+% USAGE:
+% ======
+% [text] = cell2wraptextSB(input,rowmax)
+% [text] = cell2wraptextSB(input,rowmax,separator)
+%
+% input:  cell-array with string elements
+% rowmax: maximum number of elements per line of text
+% separator: separating characters between the elements
+%
+% DEFAULT VALUES:
+% ===============
+% separator: ', '
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+if nargin == 2,
+    separator = ', ';
+elseif nargin == 3,
+    separator = varargin{1};
+else
+    error('Incorrect number of input arguments.');
+end
+if ~iscell(input),
+    error('Cell-array required.');
+end
+text = '';
+for k=1:length(input),
+    text = sprintf('%s%s%s',text,input{k},separator);
+    if mod(k-1,rowmax) == rowmax-1 && k ~= length(input),
+        text = sprintf('%s\n',text);
+    end
+end
+if ~isempty(text),
+    text = text(1:end-length(separator));
+end
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/deleteTempODEfileSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/deleteTempODEfileSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..73636e2d4f9a24e369d22c50605fba513feb8e93
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/deleteTempODEfileSB.m
@@ -0,0 +1,43 @@
+function [] = deleteTempODEfile(fullpathfilename)
+% This function takes as input argument the full path to an ODE file that
+% is to be deleted. It also tries to delete the datafile_* and the event
+% files that belong to this ODE file. Warnings are switched of not to enoy
+% the user with unecessary warnings when a file is not present.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+% initialize simulation results
+
+[pathstr,filename,ext] = fileparts(fullpathfilename);
+ODEfilename = strcat(pathstr,'/',filename,'.m');
+DATAfilename = strcat(pathstr,'/','datafile_',filename,'.m');
+EVENTfilename = strcat(pathstr,'/','event_',filename,'.m');
+EVENTASSIGNfilename = strcat(pathstr,'/','event_assignment_',filename,'.m');
+warning off;  % toggle warnings off as not all files might exist
+delete(ODEfilename);
+delete(DATAfilename);
+delete(EVENTfilename);
+delete(EVENTASSIGNfilename);
+warning on;  % toggle warnings on again
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/depowerSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/depowerSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..a57613f41c090e0913e22b0c35be102bd45e1280
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/depowerSB.m
@@ -0,0 +1,81 @@
+function [model,changeFlag] = depowerSB(model)
+% depowerSB: simple function that replaces power(x,y) expressions in models
+% to (x)^(y)
+%
+% USAGE:
+% ======
+% model = depowerSB(model)
+%
+% Output Arguments:
+% =================
+% model:        SBmodel with replaced power expressions
+% changeFlag:   =0 => no changes, =1 => changes made
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+global changeFlag
+changeFlag = 0;
+sbstruct = SBstruct(model);
+% states
+for k = 1:length(sbstruct.states),
+    sbstruct.states(k).ODE = exchangepowerexp(sbstruct.states(k).ODE);
+end
+% variables
+for k = 1:length(sbstruct.variables),
+    sbstruct.variables(k).formula = exchangepowerexp(sbstruct.variables(k).formula);
+end
+% reactions
+for k = 1:length(sbstruct.reactions),
+    sbstruct.reactions(k).formula = exchangepowerexp(sbstruct.reactions(k).formula);
+end
+% events
+for k = 1:length(sbstruct.events),
+    sbstruct.events(k).trigger = exchangepowerexp(sbstruct.events(k).trigger);
+    for k2 = 1:length(sbstruct.events(k).assignment),
+        sbstruct.events(k).assignment(k2).formula = exchangepowerexp(sbstruct.events(k).assignment(k2).formula);
+    end        
+end
+% functions
+for k = 1:length(sbstruct.functions),
+    sbstruct.functions(k).formula = exchangepowerexp(sbstruct.functions(k).formula);
+end
+model = SBmodel(sbstruct);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% regexprep command doing the replacement
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [formula] = exchangepowerexp(formula)
+global changeFlag
+oldformula = formula;
+formula = regexprep(['#' formula],'([\W]+)',' $1 ');
+formula = regexprep(formula,'[\s]power[\s]*\(([^,]+),([^,]+)\)','($1)^($2)');
+formula = regexprep(formula,'\s','');
+formula = formula(2:end);
+if ~strcmp(oldformula,formula),
+    changeFlag = 1;
+end
+return
+    
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/diff/diff.exe b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/diff/diff.exe
new file mode 100644
index 0000000000000000000000000000000000000000..2797ffd05d13c0cd59d28ab31b5d562f3e3c7987
Binary files /dev/null and b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/diff/diff.exe differ
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/diff/diffSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/diff/diffSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..7dd2494461c9a4269611c40fbab4e1ef2edb5c44
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/diff/diffSB.m
@@ -0,0 +1,10 @@
+function [status, res] = diffSB(A,B)
+% Comparison of two files using the diff command. 
+% Wrapper to handle Unix and Windows
+
+if isunix(),
+    eval(sprintf('[status, res] = system(''diff %s %s'');', A,B));
+else
+    diffLocation = which('diff.exe');
+    eval(sprintf('[status, res] = system(''"%s" %s %s'');', diffLocation,A,B))
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/getlocalmaxSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/getlocalmaxSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..a0ac3b53071a75b1ebffc876381a22a314f6fc9c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/getlocalmaxSB.m
@@ -0,0 +1,90 @@
+function [values,indices] = getlocalmaxSB(X,varargin)
+% getlocalmaxSB: determines the values and the indices of local maxima in
+% the vector X.  
+%
+% USAGE:
+% ======
+% [values,indices] = getlocalmaxSB(X)         
+% [values,indices] = getlocalmaxSB(X,borderFlag)         
+%
+% X: vector of doubles for which to determine the values and indices of the
+%   local maxima
+% borderFlag: =0: do not consider maxima at borders, =1: do consider maxima
+%   at borders (default: 0 => no maxima at borders)
+%
+% Output Arguments:
+% =================
+% values: vector with max values
+% indices: vector with indices corresponding to these values
+
+% Information:
+% ============
+% SBPOP package 
+% Copyright 2008 Novartis AG
+% Author: Henning Schmidt (henning.schmidt@novartis.com)
+% Created: 2009-01-17
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+borderFlag = 0;
+if nargin == 2,
+    borderFlag = varargin{1};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET MAX INDICES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+delta = X(2:end)-X(1:end-1);
+% get indices of zero elements
+iz = find(delta == 0);
+% remove zero elements
+matrix = [delta(:)'; 1:length(delta)];
+matrix(:,iz) = [];
+negelements = find(matrix(1,2:end).*matrix(1,1:end-1)<0) + 1;
+indices_try = matrix(2, negelements);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK max/min to isolate max (check to the right)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+indices = [];
+for k=1:length(indices_try),
+    if X(indices_try(k)) > X(indices_try(k)+1),
+        indices(end+1) = indices_try(k);
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK multiple instances of same value at same max
+% (always to the left)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(indices),
+    index = indices(k);
+    maxvalue = X(index);
+    offset = 1;
+    while maxvalue == X(index-offset),
+        indices = [indices index-offset];
+        offset = offset + 1;
+        if index-offset < 1,
+            break;
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE BORDER FLAG
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if borderFlag,
+    if X(2) < X(1),
+        indices = [1 indices];
+    end
+    if X(end) > X(end-1),
+        indices = [indices length(X)];
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PREPARE OUTPUT AND RETURN
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+indices = sort(indices);
+values = X(indices);
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/ismatrixSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/ismatrixSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..7aa9925d3a16c20fe016370ed7f6afe5dde5a2ca
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/ismatrixSB.m
@@ -0,0 +1,34 @@
+function [result] = ismatrix(x)
+% Checks if given argument is a matrix. Vectors count as matrices.
+
+% Information:
+% ============
+% Original author: KH <Kurt.Hornik@wu-wien.ac.at>
+% Adapted-By: jwe
+% Adapted for the SBTOOLBOX2 by Henning Schmidt
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+[n,m] = size(x);
+
+if n>1 || m>1,
+    result = 1;
+else
+    result = 0;
+end
+
+return
+    
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/lookforHERE.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/lookforHERE.m
new file mode 100644
index 0000000000000000000000000000000000000000..406a0895afe97872f7c9f10718baf5d701a80a63
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/lookforHERE.m
@@ -0,0 +1,53 @@
+function [] = lookforHERE(text)
+% lookforHERE: searches all m-files in the current folder tree for the 
+% text given as argument. It displays the filenames in which the text
+% appears and additionally opens the files in the editor.
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+old = pwd;
+recurseFolder('.',text);
+cd(old);
+return
+
+
+function recurseFolder(folder,text)
+% change folder
+cd(folder);
+% check all m files in folder for the text
+mfiles = dir('*.m');
+for k = 1:length(mfiles),
+    % read file
+    content = fileread(mfiles(k).name);
+    if strfind(content,text),
+        disp(mfiles(k).name);
+        edit(mfiles(k).name);
+    else
+%        edit(mfiles(k).name);
+    end
+end
+% recurse in all subfolders
+allfiles = dir;
+for k = 1:length(allfiles),
+    if ~strcmp(allfiles(k).name,'.git') && ~strcmp(allfiles(k).name,'..') && ~strcmp(allfiles(k).name,'.') && allfiles(k).isdir == 1,
+        recurseFolder(allfiles(k).name,text);
+    end
+end
+% up we go
+cd ..
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/lookforSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/lookforSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..087f45769939c0c5bd3dbf19475eabafcac27eef
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/lookforSB.m
@@ -0,0 +1,56 @@
+function [] = lookforSB(text)
+% lookforSB: searches all m-files in the SBTOOLBOX2 folder tree for the 
+% text given as argument. It displays the filenames in which the text
+% appears and additionally opens the files in the editor.
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+old = pwd;
+cd([fileparts(which('installSB')) '/..']);
+recurseFolder('SBTOOLBOX2',text);
+cd(old);
+return
+
+
+function recurseFolder(folder,text)
+% change folder
+cd(folder);
+% check all m files in folder for the text
+mfiles = dir('*.m');
+for k = 1:length(mfiles),
+    % read file
+    content = fileread(strcat(mfiles(k).name));
+    if strfind(content,text),
+        disp(mfiles(k).name);
+        edit(mfiles(k).name);
+    else
+%        edit(mfiles(k).name);
+    end
+end
+% recurse in all subfolders
+allfiles = dir;
+for k = 1:length(allfiles),
+    if ~strcmp(allfiles(k).name,'.git') && ~strcmp(allfiles(k).name,'..') && ~strcmp(allfiles(k).name,'.') && allfiles(k).isdir == 1,
+        recurseFolder(allfiles(k).name,text);
+    end
+end
+% up we go
+cd ..
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/parsaveSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/parsaveSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..bb788b9c33a066d15c5c6063480cf00c6742a5e6
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/parsaveSB.m
@@ -0,0 +1,34 @@
+function [] = parsaveSB(filename,variableName,variable)
+% parsaveSB: Allows saving from within a parfor loop
+%
+% USAGE:
+% ======
+% [] = parsaveSB(filename,variableName,variable)
+%
+% Output Arguments:
+% =================
+% filename:         filename for the mat file
+% variableName:     name how the variable is to be saved
+% variable:         variable value
+
+% Information:
+% ============
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+eval(sprintf('%s = variable;',variableName));
+
+save(filename, variableName)
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/postFillCharSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/postFillCharSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..0028d6481d9ba52320ff453d7c1b3f2f458c5ce4
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/postFillCharSB.m
@@ -0,0 +1,9 @@
+function [result] = postFillCharSB(value2prefill,lengthString,fillChar)
+
+if isnumeric(value2prefill),
+    result = [num2str(value2prefill) char(double(fillChar)*ones(1,lengthString-length(num2str(value2prefill))))];
+elseif ischar(value2prefill),
+    result = [value2prefill char(double(fillChar)*ones(1,lengthString-length(value2prefill)))];
+else
+    error('Unknown type to prefill.');
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/preFillCharSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/preFillCharSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..aade16ac7f62b0d5946ec182d9e602a00fe12b33
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/preFillCharSB.m
@@ -0,0 +1,10 @@
+function [result] = preFillCharSB(value2prefill,lengthString,fillChar)
+% [result] = preFillCharSB(value2prefill,lengthString,fillChar)
+
+if isnumeric(value2prefill),
+    result = [char(double(fillChar)*ones(1,lengthString-length(num2str(value2prefill)))) num2str(value2prefill)];
+elseif ischar(value2prefill),
+    result = [char(double(fillChar)*ones(1,lengthString-length(value2prefill))) value2prefill];
+else
+    error('Unknown type to prefill.');
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/symbolicpresentSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/symbolicpresentSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..d8e09b7cb998cbe0732ae661a609ce8a14cf4096
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/other/symbolicpresentSB.m
@@ -0,0 +1,38 @@
+function [flag] = symbolicpresentSB()
+% symbolicpresentSB: checks if the symbolic toolbox is present
+%
+% USAGE:
+% ======
+% [flag] = symbolicpresentSB()
+%
+% Output Arguments:
+% =================
+% flag: 1 if present, 0 if not present
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+flag = ~isempty(ver('symbolic'));
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/plotting/SBbarplotErrors.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/plotting/SBbarplotErrors.m
new file mode 100644
index 0000000000000000000000000000000000000000..050468ff724574f5c2ac3c6812d4097064c51498
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/plotting/SBbarplotErrors.m
@@ -0,0 +1,255 @@
+function [bar_xtick,hb,he]=SBbarplotErrors(bar_input,errorbar_input,varargin)
+%
+% SBbarplotErrors: grouped bar plot with error bars, customizable.
+%
+% SBbarplotErrors(bar_input,errorbar_input) produces a bar plot of matrix
+% bar_input. Each column corresponds to one group and each element in a
+% column to one bar. The bars are
+% grouped together, similar to the plot produced by BAR(Y,'grouped').
+%
+% If a row vector is passed, it is converted to a column vector to avoid
+% grouping => single group then also used.
+%
+% It then overlays an error bar plot of errorbar_input, the size of which
+% must match that of bar_input. Error bars are assumed to be symmetric
+% around the values of the bar plot, similar to the plot produced by
+% ERRORBAR(Y,E). Note that, if all the values of errorbar_input are set to
+% zero, the function skips plotting the error bars.
+%
+% SBbarplotErrors(bar_input,errorbar_lower,errorbar_upper) allows
+% the lower and upper bounds of the error bars to be asymmetric around the
+% values of the bar plot, similar to the plot produced by ERRORBAR(Y,L,U).
+%
+% Note that it is impossible to input the X coordinates of the bars using
+% this function.
+%
+% bar_xtick = SBbarplotErrors(...) returns the X coordinates for the center
+% of each group of bars.
+%
+% [...,hb,he] = SBbarplotErrors(...) returns the handles to the bars
+% (produced by BAR) and the error bars (produced by ERRORBAR).
+%
+% SBbarplotErrors(...,'ParameterName',ParameterValue) allows customizing
+% the display.
+%
+% 'bar_width': scalar determining bar width. Must be between 0 and 1. A
+% bar_width value of 1 causes all the bars to touch each other. This
+% parameter is identical to the optional width parameter of BAR. Default
+% value: 0.9.
+%
+% 'errorbar_width': scalar determining error bar width, expressed as a
+% fraction of the width of the bars themselves. Default value: 0.75.
+%
+% 'bar_colors': N-by-3 matrix determing the RGB values for bar colors. You
+% must provide at least as many colors as there are groups in your plot.
+% Default values: from getcolorsSBPOP()
+%
+% 'errorbar_colors': N-by-3 matrix determining the RGB values for error bar
+% colors. You must provide at least as many colors as there are groups in
+% your plot. Default value: the error bar colors are set to black.
+%
+% 'optional_bar_arguments': cell array containing any 'PropertyName' -
+% 'PropertyValue' input argument pair that you would like to pass on to
+% BAR. Default value: no further input arguments are passed to BAR.
+%
+% 'optional_errorbar_arguments': cell array containing any 'PropertyName' -
+% 'PropertyValue' input argument pair that you would like to pass on to
+% ERRORBAR. Default value: {'LineStyle','none','Marker','none'}
+% (causes ERRORBAR to plot no line between error bars, and no marker at the
+% center of each error bar)
+%
+% 'bar_names': cell string array containing labels to apply to each group
+% of bars. You must provide at least as many labels as there are bars in
+% your plot. Default value: the bars are numbered consecutively, starting
+% from 1.
+%
+% Examples:
+%
+% Basic usage:
+%   bar_input=rand(3,8)/2+0.5;
+%   errorbar_input=rand(3,8)/8;
+%   SBbarplotErrors(bar_input,errorbar_input);
+%
+% Set the lower bound of the error bars to 0, effectively plotting only the
+% upper bound:
+%   bar_input=rand(4,6)/2+0.5;
+%   errorbar_lower=zeros(size(bar_input));
+%   errorbar_upper=rand(4,6)/8;
+%   SBbarplotErrors(bar_input,errorbar_lower,errorbar_upper);
+%
+% When plotting fewer groups and bars, the plot might look better with
+% thinner bars and error bars. This also shows how to input custom names
+% for the groups of bars:
+%   bar_input=rand(2,4)/2+0.5;
+%   errorbar_input=rand(2,4)/8;
+%   SBbarplotErrors(bar_input,errorbar_input, ...
+%       'bar_width',0.75,'errorbar_width',0.5, ...
+%       'bar_names',{'A','B','C','D'});
+%
+% Here is how to pass optional input arguments to BAR and ERRORBAR:
+%   bar_input=rand(2,4)/2+0.5;
+%   errorbar_input=rand(2,4)/8;
+%   SBbarplotErrors(bar_input,errorbar_input, ...
+%       'bar_width',0.75,'errorbar_width',0.5, ...
+%       'optional_bar_arguments',{'LineWidth',1.5}, ...
+%       'optional_errorbar_arguments',{'LineStyle','none','Marker','none','LineWidth',1.5});
+
+% Author of this function: pierre.megevand@gmail.com
+% Changes to work with R2014B and SBPOP: Henning Schmidt
+%
+% change log:
+% 2014/07/16 -- first uploaded to the MATLAB File Exchange. Does not
+% do anything with the 'grp_names' optional input yet.
+% 2014/07/18 -- The x axis is now adjusted to fit the plot.
+% 2014/07/28 -- With David Groppe's help, added optional figure and axes
+% handles.
+% 2014/08/19 -- Simplified how default parameters are defined. Added option
+% to skip plotting the error bars altogether.
+
+% Make column vector if row vectors
+if isvector(bar_input),
+    bar_input = bar_input(:);
+end
+if isvector(errorbar_input),
+    errorbar_input = errorbar_input(:);
+end
+
+% Interface to function by transposing
+bar_input = bar_input';
+errorbar_input = errorbar_input';
+
+% init defaults for parameters
+[N_grps,N_bars]             = size(bar_input);
+bar_width                   = 0.8;
+errorbar_width              = 0.75;
+bar_colors                  = getcolorsSBPOP();
+
+% get some distinguishable colors for the bars!
+errorbar_colors             = zeros(N_grps,3); % default errorbar color is black
+optional_bar_arguments      = {}; % there are no default optional arguments for bar
+optional_errorbar_arguments = {'LineStyle','none','Marker','none'}; % default optional arguments for errorbar
+bar_names                   = strtrim(cellstr(num2str((1:N_bars)')));
+grp_names                   = strtrim(cellstr(num2str((1:N_grps)')));
+
+% deal with the input arguments
+if nargin<2 % the indispensable input arguments are not provided
+    error('You need to provide at least ''bar_input'' and ''errorbar_input''.');
+else
+    errorbar_lower=errorbar_input;
+    errorbar_upper=errorbar_input;
+    if any(size(bar_input)~=size(errorbar_input)) % the indispensable input arguments must have the exact same size
+        error('The size of ''bar_input'' and ''errorbar_input'' must be the same.');
+    else
+        if numel(varargin)>0 % optional input arguments are provided
+            if ~ischar(varargin{1}) % if the first optional input argument is not a character array, then by design it must be the upper bound of the error bars, or an error is thrown
+                errorbar_lower=errorbar_input;
+                errorbar_upper=varargin{1};
+                % Adjust errorbar_upper as the other two input arguments above
+                if isvector(errorbar_upper),
+                    errorbar_upper = errorbar_upper(:);
+                end
+                % Interface to function by transposing
+                errorbar_upper = errorbar_upper';
+                if any(size(errorbar_lower)~=size(errorbar_upper))
+                    error('The size of ''errorbar_input_low'' and ''errorbar_input_high'' must be the same.');
+                end
+                varargin(1)=[]; % the first optional argument has been dealt with -- remove...
+            end
+            while ~isempty(varargin)
+                if numel(varargin)<2
+                    error('You need to provide optional input arguments as ''ParameterName''-''ParameterValue'' pairs.');
+                end
+                switch varargin{1}
+                    case 'bar_width'
+                        bar_width=varargin{2};
+                    case 'errorbar_width'
+                        errorbar_width=varargin{2};
+                    case 'bar_colors'
+                        bar_colors=varargin{2};
+                    case 'errorbar_colors'
+                        errorbar_colors=varargin{2};
+                    case 'optional_bar_arguments'
+                        optional_bar_arguments=varargin{2};
+                    case 'optional_errorbar_arguments'
+                        optional_errorbar_arguments=varargin{2};
+                    case 'bar_names'
+                        bar_names=varargin{2};
+                    case 'grp_names'
+                        grp_names=varargin{2};
+                    otherwise
+                        error('Unexpected ''ParameterName'' input: %s\n',varargin{1});
+                end
+                varargin(1:2)=[]; % this pair of optional input arguments has been dealt with -- remove...
+            end
+        end
+    end
+end
+
+% init group width and bar shift
+shift_span                  = (1-bar_width)*(N_grps-1);
+bar_shift                   = linspace(-shift_span/2,+shift_span/2,N_grps);
+
+% compute position of group x ticks
+bar_xtick                   = N_grps/2+0.5:N_grps:N_bars*N_grps-N_grps/2+0.5;
+
+% init handles vectors
+hb                          = zeros(N_grps,1);
+he                          = zeros(N_grps,1);
+
+% Clear current axes ... or create new figure
+cla
+hold on;
+
+% plot the bars themselves
+for grp=1:N_grps
+    hb(grp)=bar( ...
+        (grp:N_grps:N_bars*N_grps-(N_grps-grp))-bar_shift(grp), ... % this is the x position for each bar
+        bar_input(grp,:),  ... % this is the y position for each bar
+        bar_width/N_grps, ... % this is the width of each bar
+        'FaceColor',bar_colors(grp,:), ... % color parameter
+        optional_bar_arguments{:}); % extra parameters
+end
+
+% plot the error bars
+if ~all(all(errorbar_lower==0))&&~all(all(errorbar_upper==0))
+    
+    for grp=1:N_grps
+        he(grp)=errorbar( ...
+            (grp:N_grps:N_bars*N_grps-(N_grps-grp))-bar_shift(grp), ... % this is the x position for each bar
+            bar_input(grp,:),  ... % this is the y position for each bar
+            errorbar_lower(grp,:), ... % this is the error low value for each bar
+            errorbar_upper(grp,:), ... % this is the error high value for each bar
+            'Color',errorbar_colors(grp,:), ... % color parameter
+            optional_errorbar_arguments{:}); % extra parameters
+    end
+        
+    % Set the errorbar widths    
+    if verLessThan('matlab', '8.4'),
+        % Before R2014B
+        he_c=get(he,'Children');
+        if ~iscell(he_c)
+            temp=he_c;
+            he_c=cell(1,1);
+            he_c{1}=temp;
+            clear temp;
+        end
+        for grp=1:N_grps
+            he_xdata=get(he_c{grp}(2),'XData');
+            he_xdata(4:9:end)=he_xdata(1:9:end)-errorbar_width*bar_width/2;
+            he_xdata(7:9:end)=he_xdata(1:9:end)-errorbar_width*bar_width/2;
+            he_xdata(5:9:end)=he_xdata(1:9:end)+errorbar_width*bar_width/2;
+            he_xdata(8:9:end)=he_xdata(1:9:end)+errorbar_width*bar_width/2;
+            set(he_c{grp}(2),'XData',he_xdata);
+        end
+    else
+        % From R2014B
+        % Keep as is for now ... can not find in the objects
+    end
+end
+
+% set the x tick labels
+set(gca,'XTick',bar_xtick,'XTickLabel',bar_names);
+
+% cosmetic fine-tuning of the figure
+set(gca,'XLim',[0 bar_xtick(end)+bar_xtick(1)]); % adjusts the x axis to the plot
+hold off;
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/plotting/SBplotselected.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/plotting/SBplotselected.m
new file mode 100644
index 0000000000000000000000000000000000000000..513924c72c954c4e5fabdb12dc293c51068319c5
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/plotting/SBplotselected.m
@@ -0,0 +1,117 @@
+function SBplotselected(simdata,plotcomponents,varargin)
+% SBplotselected: Takes a simulation result as input. Additionally, the
+% names of states, variables, and reactions can be defined for which the
+% values should be plotted. 
+%
+% USAGE:
+% ======
+% SBplotselected(simdata,plotcomponents)
+% SBplotselected(simdata,plotcomponents,headers)
+%
+% simdata: Simulation results returned, e.g. from SBsimulate
+% plotcomponents: cell-array with component names to plot (states,
+%   variables and/or reactions). Alternatively, the cell-array can contain 
+%   only cell-arrays of component names. This allows to define
+%   plot-subgroups, which can be selected using the pulldown menu in the
+%   upper left corner of the SBplot window.
+% headers: if plotcomponents contains only cell-arrays, then this input
+%   argument contains the names to be displayed in the pull-down menu.
+%
+% DEFAULT VALUES:
+% ===============
+% headers: {'plot 1', 'plot 2', ...}
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check plotcomponents argument
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~iscell(plotcomponents),
+    error('SBT2:SBplotselected:componentsNotCellArray','Second input argument needs to be a cell-array.');
+end
+charfound = 0;
+cellfound = 0;
+for k=1:length(plotcomponents),
+    if ischar(plotcomponents{k}),
+        charfound = 1;
+    elseif iscell(plotcomponents{k}),
+        cellfound = 1;
+    end
+end
+if charfound == 1 && cellfound == 1,
+    error('SBT2:SBplotselected:charCellMix','Second input argument needs to contain either chars or cells. Not both!');
+end
+% convert char to cell model
+if charfound == 1,
+    plotcomponents = {plotcomponents};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+headers = {};
+for k=1:length(plotcomponents),
+    headers{k} = sprintf('plot %d',k);
+end
+if nargin == 3,
+    headers = varargin{1};
+end
+if length(headers) ~= length(plotcomponents),
+    error('SBT2:SBplotselected:wrongHeadersLength','Wrong number of elements in third input argument.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Prepare the different plot structures
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+plotstructures = {};
+states = simdata.states; sind = 1:length(states);
+variables = simdata.variables; vind = 1:length(variables);
+reactions = simdata.reactions; rind = 1:length(reactions);
+for k=1:length(plotcomponents),
+    comp = plotcomponents{k};
+    simdatak = simdata;
+    sind_keep = [];
+    vind_keep = [];
+    rind_keep = [];
+    for k2=1:length(comp),
+        % reduce simulation results to only contain the components in comp
+        sind_keep = [sind_keep strmatchSB(comp{k2},states,'exact')];
+        vind_keep = [vind_keep strmatchSB(comp{k2},variables,'exact')];
+        rind_keep = [rind_keep strmatchSB(comp{k2},reactions,'exact')];
+    end
+    simdatak.states = simdatak.states(sind_keep);
+    simdatak.statevalues = simdatak.statevalues(:,sind_keep);
+    simdatak.variables = simdatak.variables(vind_keep);
+    simdatak.variablevalues = simdatak.variablevalues(:,vind_keep);
+    simdatak.reactions = simdatak.reactions(rind_keep);
+    simdatak.reactionvalues = simdatak.reactionvalues(:,rind_keep);
+    % convert to plot structure 
+    plotstructures{k} = createdatastruct2SBplotSB(simdatak,headers{k}); 
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Construct SBplot command and plot
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+plotcommand = 'SBplot(';
+for k=1:length(plotstructures),
+    plotcommand = sprintf('%splotstructures{%d},',plotcommand,k);
+end
+plotcommand = [plotcommand(1:end-1) ')'];
+eval(plotcommand)
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/ps/gs/bin/gsdll32.dll b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/ps/gs/bin/gsdll32.dll
new file mode 100644
index 0000000000000000000000000000000000000000..0d900f008bd8f8d7b3037106c51b098540aa60c0
Binary files /dev/null and b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/ps/gs/bin/gsdll32.dll differ
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/ps/gs/bin/gsdll32.lib b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/ps/gs/bin/gsdll32.lib
new file mode 100644
index 0000000000000000000000000000000000000000..f1071482a3daecc7409bc5859b0a7341780a79c9
Binary files /dev/null and b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/ps/gs/bin/gsdll32.lib differ
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/ps/gs/bin/gswin32c.exe b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/ps/gs/bin/gswin32c.exe
new file mode 100644
index 0000000000000000000000000000000000000000..6b7f4e50d0b5ef30c40f921a87ddce3576574a4e
Binary files /dev/null and b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/ps/gs/bin/gswin32c.exe differ
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/ps/ps2pdfSB/license.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/ps/ps2pdfSB/license.txt
new file mode 100644
index 0000000000000000000000000000000000000000..938125d4137ae513ed6bd9830a941d60c84383e9
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/ps/ps2pdfSB/license.txt
@@ -0,0 +1,27 @@
+Copyright (c) 2008-2010, The MathWorks, Inc.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+    * Redistributions of source code must retain the above copyright
+      notice, this list of conditions and the following disclaimer.
+    * Redistributions in binary form must reproduce the above copyright
+      notice, this list of conditions and the following disclaimer in
+      the documentation and/or other materials provided with the distribution
+    * Neither the name of the The MathWorks, Inc. nor the names
+      of its contributors may be used to endorse or promote products derived
+      from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/ps/ps2pdfSB/ps2pdf.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/ps/ps2pdfSB/ps2pdf.m
new file mode 100644
index 0000000000000000000000000000000000000000..7f433e689ba7795bcdefd00d87423eadf3401ecc
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/ps/ps2pdfSB/ps2pdf.m
@@ -0,0 +1,393 @@
+function ps2pdfSB(varargin)
+%ps2pdfSB Function to convert a PostScript file to PDF using Ghostscript
+%
+%  Converts a postscript file into PDF. The resulting PDF file will contain
+%  one page for each page defined in the postscript files, so a multi-page
+%  postscript file, like those generated by using the '-append' option of 
+%  MATLAB's print command, can be used to generate a multi-page PDF file. 
+%
+%   Ghostscript is a third-party application currently supplied with 
+%   MATLAB. The caller may also specify a different version of Ghostscript
+%   to use.
+%
+%   ps2pdfSB expects to be called with a set of parameter-value pairs. The
+%   order of these is unimportant, but required parameters MUST be
+%   specified
+%
+%   In the list below, required parameters are marked with an asterisk *
+%        NOTE: ps2pdfSB can not use MATLAB's version of Ghostscript
+%              in a deployed application; you MUST provide a 
+%              the path to a separate instance of Ghostscript. This 
+%              parameter is marked with a double asterisk **
+%
+%   Parameter:        Value:  
+%   *  psfile         full or relative path to the postscript file to convert
+%
+%   *  pdffile        full or relative path to the pdf file to create
+%
+%   ** gscommand      path to Ghostscript executable to use; this will try
+%                     to default to the version of Ghostscript shipped with 
+%                     MATLAB, if any. If this value is specified you should 
+%                     also specify the gsfontpath and gslibpath values.
+%
+%                     ** See note on deployed applications, above.
+%
+%      gsfontpath     full path to the Ghostscript font files
+%                     If a gscommand is specified then this path should
+%                     also be specified and reference the same Ghostscript
+%                     version
+%
+%      gslibpath      full path to the Ghostscript library (.ps) files. 
+%                     If a gscommand is specified then this path should
+%                     also be specified and reference the same Ghostscript
+%                     version
+%
+%                     If gscommand is NOT specified and we can determine
+%                     the version of Ghostscript, if any, shipped with
+%                     MATLAB, then this value will be overridden to use the
+%                     path that references MATLAB's version of Ghostscript
+%
+%      gspapersize    paper size to use in the created .pdf file. If not 
+%                     specified or the specified value is not recognized 
+%                     it will use whatever default paper size is 
+%                     built into the version of Ghostscript being run
+%
+%                         NOTE: no scaling of the input occurs - it's simply
+%                         placed on a page with the specified paper size. 
+%
+%                         Valid values for gspapersize are: 
+%                              'letter', 'ledger', 'legal', '11x17', 
+%                              'archA', 'archB', 'archC', 'archD', 'archE', 
+%                              'a0', 'a1', 'a2', 'a3','a4', 'a5',
+%                              'a6', 'a7', 'a8', 'a9', 'a10'
+%                         
+%      deletepsfile   0 to keep the input ps file after creating pdf
+%                     non-zero to delete the input ps file after creating pdf
+%                     Default is 0: keep the input ps file (do NOT delete it)
+%                        NOTE: if the pdf creation process fails, the input
+%                        PS file will be kept regardless of this setting
+%
+%      verbose        0 to suppress display of status/progress info; 
+%                     non-zero to allow display of status/progress info
+%                     Default is 0 (no display)
+%
+% Example usage: 
+%    use MATLAB's version of Ghostscript to generate an A4 pdf file
+%      ps2pdfSB('psfile', 'input.ps', 'pdffile', 'output.pdf', 'gspapersize', 'a4')
+%
+%    use a local copy of Ghostcript to generate a file, and display some 
+%    status/progress info while doing so.
+%      ps2pdfSB('psfile', '../reports/input.ps', 'pdffile', 'c:\temp\output3.pdf', ...
+%            'gspapersize', 'a4', 'verbose', 1, ...
+%            'gscommand', 'C:\Program Files\GhostScript\bin\gswin32c.exe', ...
+%            'gsfontpath', 'C:\Program Files\GhostScript\fonts', ...
+%            'gslibpath', 'C:\Program Files\GhostScript\lib')
+%
+%    use MATLAB's version of Ghostscript to generate a pdf file and delete
+%    the input.ps file when done 
+%      ps2pdfSB('psfile', 'input.ps', 'pdffile', 'output.pdf', 'gspapersize', 'a4', 'deletepsfile', 1)
+
+%   Update log: 
+%      Jun 16, 2010: added check for deployed application
+%      May 19, 2010: wrapped filenames sent to Ghostscript in quotes
+%      May 06, 2010: updated how Ghostscript is found, don't rely on MATLAB version #
+%      Aug 15, 2008: fixed bug where embedded space in location of 
+%                    MATLAB's version of Ghostscript caused ps2pdfSB to fail.
+%      Apr 16, 2008: added deletepsfile option
+
+%   Copyright 2008-2010 The MathWorks, Inc.
+
+   if nargin < 1 
+      error('ps2pdfSB:parameters', 'No parameters specified. Type ''help ps2pdfSB'' for details on how to use this function.');
+   end
+
+   % parse input args
+   gsData = LocalParseArgs(varargin{:});
+
+   % setup the file that tells GS what we want it to do
+   gsData = LocalCreateResponseFile(gsData); 
+
+   gsDebug = 0;
+   if gsData.verbose 
+      fprintf('ps2pdfSB: input settings are:\n');
+      if isfield(gsData, 'paperSizes')
+          gsData = rmfield(gsData, 'paperSizes');
+      end
+      gsData  %#ok<NOPRT>
+      fprintf('ps2pdfSB: response file for Ghostscript is:\n');
+      type(gsData.responseFile);
+      gsDebug = 1;
+   end
+
+   %to hold results/status from system call
+   s = 0; %#ok<NASGU>
+   r = ''; %#ok<NASGU>
+
+   % run Ghostscript to convert the file
+   if gsData.useBuiltin 
+      [s, r] = gsData.cmd(['@' gsData.responseFile], gsData.psFile, gsDebug);
+   else 
+      [s, r] = system([gsData.cmd ' @"' gsData.responseFile '" "' gsData.psFile '"']);
+   end
+
+   if gsData.verbose
+      disp( ['Ghostscript STDOUT: ' num2str(s) ] );
+      disp( ['Ghostscript STDERR: ' r ] );
+   else
+      delete(gsData.responseFile)
+   end
+
+   if s && ~isempty(r)
+      error('ps2pdfSB:ghostscript',  ['Problem converting PostScript. System returned error: ' num2str(s) '.' r]) 
+   elseif s
+      error('ps2pdfSB:ghostscript',  ['Problem calling GhostScript. System returned error: ' num2str(s)]) 
+   end
+
+   %if after all this we still couldn't create the file, report the error
+   fid = fopen( gsData.pdfFile, 'r');
+   if ( fid == -1 )
+      error('ps2pdfSB:ghostscript', '%s', [ 'Ghostscript could not create ''' gsData.pfdFile '''.' ])
+   else
+      fclose( fid );
+   end
+
+   % if we get here, we successfully created pdf file; delete ps file if
+   % requested to do so
+   if gsData.deletePSFile 
+       delete(gsData.psFile);
+   end
+
+end
+
+%local function to parse arguments and fill in the gsData structure
+%  .psFile - postscript file to convert
+%  .pdfFile - pdf file to create
+%  .cmd     - path/name of Ghostscript command to run or handle to gscript
+%             builtin
+%  .useBuiltin - 1 if using builtin gs command 
+%  .fontPath - path to the Ghostscript fonts, if any
+%  .libPath - path to the Ghostscript libs (Ghostscript .ps files), if any) 
+%  .paperSize - paper size to set for resulting .pdf file 
+%  .deletePSFile - 0 to keep (not delete) the input ps file if pdf created ok
+%  .verbose - if non-zero, display some status/progress info to command window
+function gsData = LocalParseArgs(varargin) 
+    gsData.paperSizes = {'letter', 'ledger', 'legal', '11x17', 'archA', 'archB', ... 
+                   'archC', 'archD', 'archE', 'a0', 'a1', 'a2', 'a3','a4', 'a5', ...
+                   'a6', 'a7', 'a8', 'a9', 'a10'};
+
+    %default values for some settings
+    gsData.verbose      = 0; 
+    gsData.useBuiltin   = 0;
+    gsData.deletePSFile = 0; 
+    
+    for i = 1 : 2 : length(varargin)-1 
+        param_arg = varargin{i};
+        param_value = varargin{i+1};        
+        switch(lower(param_arg)) 
+            % path to ps file to conver
+            case 'psfile'
+               if ~exist(param_value, 'file')
+                  error('print:ghostscript', ...
+                      'Can not find postscript file <%s> to convert', ...
+                      param_value)
+               end
+               gsData.psFile = param_value;
+
+            % path to pdf file to create
+            case 'pdffile'
+                %verify we can create file at that location
+                pdf_fid = fopen(param_value,'w');
+                if pdf_fid < 0 
+                    error('ps2pdfSB:invalidPDFFIle', ... 
+                        'Can not open <%s> for writing', ...
+                        param_value);
+                end
+                fclose(pdf_fid); 
+                %delete temp file we created
+                delete(param_value); 
+                gsData.pdfFile = param_value;
+
+            % full path to gs executable
+            case 'gscommand' 
+               if ~exist(param_value, 'file')
+                  error('ps2pdfSB:ghostscriptCommand', ...
+                      'Can not find Ghostscript executable (''gscommand'') <%s>',...
+                      param_value)
+               end
+               if ispc && ~isempty(findstr(param_value, ' '))
+                   param_value = ['"' param_value '"']; %#ok<AGROW>
+               end
+               gsData.cmd = param_value; 
+                
+            % full path to gs font dir
+            case 'gsfontpath' 
+               if ~exist(param_value, 'dir')
+                   error('ps2pdfSB:ghostscriptFontPath', ...
+                         'Can not find the directory <%s> for Ghostscript fonts (''gsfontpath'')', ...
+                         param_value)
+               end
+               gsData.fontPath = param_value;
+
+            % full path to gs lib dir
+            case 'gslibpath' 
+               if ~exist(param_value, 'dir')
+                   error('ps2pdfSB:ghostscriptLibPath', ...
+                         'Can not find the directory <%s> for Ghostscript library files (''gslibpath'')', ...
+                         param_value)
+               end
+               gsData.libPath = param_value;
+                
+            % paper size 
+            case 'gspapersize'
+               idx = strcmpi(param_value, gsData.paperSizes);
+               if ~any(idx)
+                  warning('ps2pdfSB:papersize', ...
+                        '''gspapersize'' value <%s> not found in the list of known sizes, ignoring it.', param_value);
+               else
+                  gsData.paperSize = gsData.paperSizes{idx};
+               end
+
+            % deletePSFile
+            case 'deletepsfile'
+               if isnumeric(param_value) 
+                  gsData.deletePSFile = param_value; 
+               else
+                   warning('ps2pdfSB:deletepsfile', ...
+                         '''deletepsfile'' value <%s> class <%s> should be numeric, defaulting to 0', ...
+                         param_value, class(param_value));
+               end
+               
+            % verbose
+            case 'verbose'
+               if isnumeric(param_value) 
+                  gsData.verbose = param_value; 
+               else
+                   warning('ps2pdfSB:verbose', ...
+                         '''verbose'' value <%s> class <%s> should be numeric, defaulting to 0', ...
+                         param_value, class(param_value));
+               end
+               
+            otherwise
+               if isnumeric(param_value)
+                   param_value = num2str(param_value);
+               end
+                  warning('ps2pdfSB:unknown', ...
+                     'ignoring unknown parameter <%s> with value <%s>.', param_arg, param_value);
+        end
+    end    
+
+    if ~isfield(gsData, 'psFile') 
+        error('ps2pdfSB:noInputFile', ...
+               'No input (psfile) file specified');
+    end
+    
+    if ~isfield(gsData, 'pdfFile') 
+        error('ps2pdfSB:noOutputFile', ...
+               'No output (pdffile) file specified');
+    end
+    
+    if ~isfield(gsData, 'cmd') 
+        if isdeployed
+            error('ps2pdfSB:deployedNeedsGhostscript', ...
+                  'In order to use ''ps2pdfSB'' in a deployed application you must provide the path to a separate instance of Ghostscript.');
+        end
+
+        % updated code to find ghostscript - look for gs8x first, 
+        % then try old location. Don't depend on MATLAB version #
+        ghostDir = fullfile( matlabroot, 'sys', 'gs8x' );
+        if ~exist(ghostDir, 'dir')
+            [gsCmd, ghostDir] = Local_GetOldGhostscript();
+            gsData.cmd = gsCmd;
+        else
+           gsData.cmd = Local_GetGscriptFcnHandle;
+           if ~isempty(gsData.cmd)
+              gsData.useBuiltin = 1; % use builtin Ghostscript
+           end
+        end
+        if ~exist(ghostDir, 'dir')
+           error('ps2pdfSB:ghostscriptCommand', ...
+                 'Can not find Ghostscript installed with MATLAB in <%s>',...
+                 ghostDir);
+        end
+
+        if ~isempty(gsData.cmd)
+           % if using MATLAB's version of GhostScript, use same set of fonts and library files
+           if isfield(gsData, 'fontPath') || isfield(gsData, 'libPath')
+              warning('ps2pdfSB:ghostscriptPathOverride', ...
+                    'Using MATLAB''s version of Ghostscript; overriding ''gsfontpath'' and ''gslibpath'' to use builtin MATLAB version');
+           end
+           gsData.fontPath = fullfile( ghostDir, 'fonts', '');
+           gsData.libPath = fullfile( ghostDir, 'ps_files', '');
+        else 
+            error('ps2pdfSB:noGhostscriptCommand', ...
+                  'Can not find Ghostscript program in MATLAB');
+        end
+    else
+        % if gscommandpath was specified, 
+        if ~isfield(gsData, 'fontPath') || ~isfield(gsData, 'libPath')
+           warning('ps2pdfSB:ghostscriptCommandSuggestion', ...
+                 ['When specifying a Ghostscript executable (''gscommand'') you should also '...
+                 'specify both the ''gsfontpath'' and ''gslibpath'' locations']);
+   
+        end
+    end
+end
+
+%local function to create the input file needed for Ghostscript
+function gsData = LocalCreateResponseFile(gsData) 
+   % open a response file to write out Ghostscript commands
+   rsp_file = [tempname '.rsp'];
+   rsp_fid = fopen (rsp_file, 'w');
+
+   if (rsp_fid < 0)
+      error('ps2pdfSB:responseFileCreate', 'Unable to create response file')
+   end
+
+   fprintf(rsp_fid, '-dBATCH -dNOPAUSE\n');
+   if ~gsData.verbose
+       fprintf(rsp_fid, '-q\n');
+   end
+   if isfield(gsData, 'libPath')
+      fprintf(rsp_fid, '-I"%s"\n', gsData.libPath);
+   end
+   if isfield(gsData, 'fontPath')
+      fprintf(rsp_fid, '-I"%s"\n', gsData.fontPath);
+   end
+   if isfield(gsData, 'paperSize') 
+      fprintf( rsp_fid, '-sPAPERSIZE=%s\n', gsData.paperSize );
+   end
+   fprintf(rsp_fid, '-sOutputFile="%s"\n', gsData.pdfFile);
+   fprintf(rsp_fid, '-sDEVICE=%s\n', 'pdfwrite');
+   fclose(rsp_fid);
+   gsData.responseFile = rsp_file;
+end
+
+%local function to get a handle to MATLAB's Ghostscript implementation
+%NOTE: this may change or be removed in future releases
+function gs = Local_GetGscriptFcnHandle()
+  gs = '';
+  p = which('-all', 'gscript');
+  if ~isempty(p) 
+      p = p{1};
+      fpath = fileparts(p);
+      olddir = cd(fpath);
+      gs = @gscript;
+      cd(olddir);
+  end
+end
+
+% local function to try and get location of Ghostscript in older MATLAB
+function [gsCmd, ghostDir] = Local_GetOldGhostscript
+   ghostDir = fullfile( matlabroot, 'sys', 'ghostscript' );
+   gsCmd = '';
+   if ispc
+      if exist(fullfile(ghostDir,'bin','win32','gs.exe'), 'file')
+         gsCmd = fullfile(ghostDir,'bin','win32','gs.exe');
+      end
+   else 
+      if exist(fullfile(ghostDir,'bin',lower(computer),'gs'), 'file')
+         gsCmd = fullfile(ghostDir,'bin',lower(computer), 'gs');
+      end
+   end
+   gsCmd = ['"' gsCmd '"'];
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/ps/ps2pdfSB/ps2pdfSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/ps/ps2pdfSB/ps2pdfSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..0f4188d7b032eebcc1549bd8243f26d461b6c34d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/ps/ps2pdfSB/ps2pdfSB.m
@@ -0,0 +1,63 @@
+function ps2pdfSB(psfile,pdffile)
+% [DESCRIPTION]
+% Function to convert a PostScript file to PDF using Ghostscript.
+%
+% Converts a postscript file into PDF. The resulting PDF file will contain
+% one page for each page defined in the postscript files, so a multi-page
+% postscript file, like those generated by using the '-append' option of 
+% MATLAB's print command, can be used to generate a multi-page PDF file. 
+%
+% The source PS file is then deleted.
+%
+% [SYNTAX]
+% [] = ps2pdfSB(psfile,pdffile)
+%
+% [INPUT]
+% psfile:     full or relative path to the postscript file to convert
+% pdffile:    full or relative path to the pdf file to create
+%
+% [OUTPUT]
+%
+% [ASSUMPTIONS]
+%
+% [AUTHOR]
+% Henning Schmidt, henning.schmidt@novartis.com
+%
+% [DATE]
+% 11th August 2014
+%
+% [PLATFORM]
+% Windows, Unix
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+if ~isunix(),
+    % Get root folder for ghostscript
+    gsDir = [fileparts(which('installSB.m')) '/auxiliary/ps/gs/'];
+    
+    ps2pdf('psfile',psfile,'pdffile',pdffile, ...
+        'deletepsfile',1, ...
+        'gspapersize', 'a4', ...
+        'gscommand', [gsDir 'bin/gswin32c.exe'], ...
+        'gsfontpath', [gsDir 'fonts'], ...
+        'gslibpath', [gsDir 'lib'], ...
+		'verbose',0)
+else
+    system(sprintf('ps2pdf -dBATCH -dNOPAUSE -sPAPERSIZE=a4 -sDEVICE=pdfwrite -dPDFSETTINGS=/default %s %s',psfile,pdffile))
+    delete(psfile);
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/andSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/andSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..36d91c08bd939b9edf5dca3be0685de06e64941e
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/andSB.m
@@ -0,0 +1,53 @@
+function [result] = andSB(varargin)
+% andSB: This function is used instead of the MATLAB "and" function, 
+% allowing more than two input arguments, each of type "logical". Its use 
+% is mainly thought for evaluation of decision arguments in SBML piecewise 
+% statements.
+% 
+% USAGE:
+% ======
+% [result] = andSB(arg1,arg2,...,argn)   
+%
+% arg1...argn: input arguments of type boolean.
+%
+% Output Arguments:
+% =================
+% result: arg1 && arg2 && ... && argn
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK TYPE OF INPUT ARGUMENTS AND DO IT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+result = true;
+for k = 1:nargin,
+    if ~strcmp('logical', class(varargin{k})),
+        error('At least one input argument to the "andSB" function is not of type "logical".');
+    end
+    result = result && varargin{k};
+end
+return
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/delaySB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/delaySB.m
new file mode 100644
index 0000000000000000000000000000000000000000..1ed76b219a8d6165f7c16c7fe4513bcb7409bef6
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/delaySB.m
@@ -0,0 +1,59 @@
+function [output] = delaySB(input,tau,time,queuename)
+% delaySB: realizes a time delay of "tau" time units
+%
+% input:     the input that is to be delayed
+% tau:       the delay
+% time:      the time of the input
+% queuename: unique name for the variable storing the queue data
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+% get the queuedata for the current delay
+eval(sprintf('global %s',queuename));
+eval(sprintf('queue = %s;',queuename));
+
+if isempty(queue),
+% initialize the queue if first call
+    queue(1,1) = -1e10;
+    queue(1,2) = input;
+    queue(2,1) = time+tau;  % add delay to time in order to store the output time
+    queue(2,2) = input;
+else
+% add new time point to the queue
+    % if last time+tau < max stored time ... delete all time points larger
+    % than time + tau (can happen during event handling)
+    queue(find(queue(:,1)>=time+tau),:) = [];
+    % add the new point
+    queue(end+1,1) = time+tau;   % add delay to time in order to store the output time
+    queue(end,2) = input;
+end
+
+% % make unique time values (not necessary due to line 23 above???)
+% [dummy,indexunique] = unique(queue(:,1),'first');
+% queue = queue(indexunique,:);
+
+% interpolate to find the correct value for the current time. 
+% (linear interpolation)
+output = interp1SB(queue(:,1),queue(:,2),time);
+
+% store the queue under the right name again
+eval(sprintf('%s = queue;',queuename));
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/indexmaxSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/indexmaxSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..5b7aebd07023608b427668bea6d4b50b23a7d189
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/indexmaxSB.m
@@ -0,0 +1,39 @@
+function [result] = indexmaxSB(varargin)
+% matchmaxSB: This function searches for the maximum input argument and returns the
+% index of the max.
+% 
+% USAGE:
+% ======
+% [result] = matchmaxSB(arg1,arg2,...,argn)
+%
+% arg1...argn: scalar input arguments of type double.
+%
+% Output Arguments:
+% =================
+% result: index of the largest element of X
+
+% Information:
+% ============
+% Copyright (C) 2009  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DO IT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[v,result] = max([varargin{:}]);
+return
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/interp0SB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/interp0SB.m
new file mode 100644
index 0000000000000000000000000000000000000000..66595ae04f1934a365d2fa4f2357f5b9fd2c4a9c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/interp0SB.m
@@ -0,0 +1,44 @@
+function [yi] = interp0SB(x,y,xi)
+% interp0SB: zero order interpolation function (lookup table)
+% If of limits then the extreme points in y are taken as output. 
+% interp0SB can be used together with MEX simulation files. For MEX
+% simulation functions it is IMPORTANT that the elements of the x and y
+% vectors are numeric and SEPARATED BY COMMATA! 
+% 
+% USAGE:
+% ======
+% [yi] = interp0SB(x,y,xi)   
+%
+% x: vector of function arguments
+% y: vector of function values at the points given by x
+% xi: scalar value for which to determine y by zero order interpolation
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+yi = zeros(1,length(xi));
+for k=1:length(xi),
+    if xi(k) < x(2),
+        yi(k) = y(1);
+    elseif xi(k) >= x(end),
+        yi(k) = y(end);
+    else
+        yi(k) = y(max(find(x<=xi(k))));
+    end
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/interp1SB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/interp1SB.m
new file mode 100644
index 0000000000000000000000000000000000000000..6768a4cbbe7db243a77bf2d81623042a7e700bab
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/interp1SB.m
@@ -0,0 +1,44 @@
+function [yi] = interp1SB(x,y,xi)
+% interp1SB: linear interpolation function (lookup table)
+% Just the same as interp1 in MATLAB (except that if of limits then the extreme
+% points in y are taken as output instead of NaN). interp1SB can be used together 
+% with MEX simulation files. For MEX simulation functions it is IMPORTANT that 
+% the elements of the x and y vectors are numeric and SEPARATED BY COMMATA!
+%
+% USAGE:
+% ======
+% [yi] = interp1SB(x,y,xi)   
+%
+% x: vector of function arguments
+% y: vector of function values at the points given by x
+% xi: scalar value for which to determine y by linear interpolation
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+yi = zeros(1,length(xi));
+for k=1:length(xi),
+    if xi(k) < x(1),
+        yi(k) = y(1);
+    elseif xi(k) > x(end),
+        yi(k) = y(end);
+    else
+        yi(k) = interp1(x,y,xi(k));
+    end
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/interpcsSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/interpcsSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..77587f023b5fe8a3e2f48ae20b7ca61b543f865d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/interpcsSB.m
@@ -0,0 +1,689 @@
+function [yi] = interpcsSB(x,y,xi)
+% interpcsSB: cubic spline interpolation function (lookup table)
+% interpcsSB can be used together with MEX simulation functions. 
+% if xi is of limits of x then the extreme points in y are taken as output.
+% For MEX simulation functions it is IMPORTANT that the elements of the 
+% x and y vectors are numeric and SEPARATED BY COMMATA!
+% 
+% USAGE:
+% ======
+% [yi] = interpSBcs(x,y,xi)       
+%
+% x: vector of function arguments
+% y: vector of function values at the points given by x
+% xi: scalar value for which to determine y by linear interpolation
+%
+% Output Arguments:
+% =================
+% yi: the value of the dependent variable at xi.
+
+% Information:
+% ============
+% Copyright (C) 2008 Basti Bergdahl,
+%                    Department of Applied Microbiology
+%                    Lund Insitute of Technology.
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+% input check
+if length(x) ~= length(y),
+    error('interpcsSB: Different number of entries in x and y');
+end
+
+% number of data points
+n = length(x);
+
+% number of interpolations to compute
+ni = length(xi);
+
+% Calculate the derivatives
+d = spline_pchip_set(n, x, y);
+
+% Calculate the output
+yi = spline_pchip_val(n, x, y, d, ni, xi);
+
+% handle off limit values
+yi(find(xi<x(1))) = y(1);
+yi(find(xi>x(end))) = y(end);
+return
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SPLINE_PCHIP_SET
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function d = spline_pchip_set ( n, x, f )
+%% SPLINE_PCHIP_SET sets derivatives for a piecewise cubic Hermite interpolant.
+%
+%  Discussion:
+%
+%    This routine computes what would normally be called a Hermite 
+%    interpolant.  However, the user is only required to supply function
+%    values, not derivative values as well.  This routine computes
+%    "suitable" derivative values, so that the resulting Hermite interpolant
+%    has desirable shape and monotonicity properties.
+%
+%    The interpolant will have an extremum at each point where
+%    monotonicity switches direction.  
+%
+%    The resulting piecewise cubic Hermite function may be evaluated
+%    by SPLINE_PCHIP_VAL.
+%
+%    This routine was originally called "PCHIM".
+%
+%  Modified:
+%
+%    14 August 2005
+%
+%  Author:
+%
+%    Fred Fritsch,
+%    Mathematics and Statistics Division,
+%    Lawrence Livermore National Laboratory.
+%
+%    MATLAB translation by John Burkardt.
+%
+%  Reference:
+%
+%    Fred Fritsch and R Carlson,
+%    Monotone Piecewise Cubic Interpolation,
+%    SIAM Journal on Numerical Analysis,
+%    Volume 17, Number 2, April 1980, pages 238-246.
+%
+%    Fred Fritsch and J Butland,
+%    A Method for Constructing Local Monotone Piecewise Cubic Interpolants,
+%    LLNL Preprint UCRL-87559, April 1982.
+%
+%  Parameters:
+%
+%    Input, integer N, the number of data points.  N must be at least 2.
+%
+%    Input, real X(N), the strictly increasing independent
+%    variable values.
+%
+%    Input, real F(N), dependent variable values to be interpolated.  This
+%    routine is designed for monotonic data, but it will work for any F-array.
+%    It will force extrema at points where monotonicity switches direction.
+%
+%    Output, real D(N), the derivative values at the
+%    data points.  If the data are monotonic, these values will determine
+%    a monotone cubic Hermite function.
+%
+
+%
+%  Check the arguments.
+%
+  if ( n < 2 )
+    ierr = -1;
+    fprintf ( 1, '\n' );
+    fprintf ( 1, 'SPLINE_PCHIP_SET - Fatal error!\n' );
+    fprintf ( 1, '  Number of data points less than 2.\n' );
+    error ( 'SPLINE_PCHIP_SET - Fatal error!' );
+  end
+
+  for i = 2 : n
+    if ( x(i) <= x(i-1) )
+      ierr = -3;
+      fprintf ( 1, '\n' );
+      fprintf ( 1, 'SPLINE_PCHIP_SET - Fatal error!\n' );
+      fprintf ( 1, '  X array not strictly increasing.\n' );
+      error ( 'SPLINE_PCHIP_SET - Fatal error!' );
+    end
+  end
+
+  ierr = 0;
+  nless1 = n - 1;
+  h1 = x(2) - x(1);
+  del1 = ( f(2) - f(1) ) / h1;
+  dsave = del1;
+%
+%  Special case N=2, use linear interpolation.
+%
+  if ( n == 2 )
+    d(1) = del1;
+    d(n) = del1;
+    return
+  end 
+%
+%  Normal case, 3 <= N.
+%
+  h2 = x(3) - x(2);
+  del2 = ( f(3) - f(2) ) / h2;
+%
+%  Set D(1) via non-centered three point formula, adjusted to be
+%  shape preserving.
+%
+  hsum = h1 + h2;
+  w1 = ( h1 + hsum ) / hsum;
+  w2 = -h1 / hsum;
+  d(1) = w1 * del1 + w2 * del2;
+
+  if ( pchst( d(1), del1 ) <= 0.0 )
+
+    d(1) = 0.0;
+%
+%  Need do this check only if monotonicity switches.
+%
+  elseif ( pchst( del1, del2 ) < 0.0 )
+
+     dmax = 3.0 * del1;
+
+     if ( abs ( dmax ) < abs ( d(1) ) )
+       d(1) = dmax;
+     end
+
+  end
+%
+%  Loop through interior points.
+%
+  for i = 2 : nless1
+
+    if ( 2 < i )
+      h1 = h2;
+      h2 = x(i+1) - x(i);
+      hsum = h1 + h2;
+      del1 = del2;
+      del2 = ( f(i+1) - f(i) ) / h2;
+    end
+%
+%  Set D(I)=0 unless data are strictly monotonic.
+%
+    d(i) = 0.0;
+
+    temp = pchst( del1, del2 );
+
+    if ( temp < 0.0 )
+
+      ierr = ierr + 1;
+      dsave = del2;
+%
+%  Count number of changes in direction of monotonicity.
+%
+    elseif ( temp == 0.0 )
+
+      if ( del2 ~= 0.0D+00 )
+        if ( pchst( dsave, del2 ) < 0.0 )
+          ierr = ierr + 1;
+        end
+        dsave = del2;
+      end
+%
+%  Use Brodlie modification of Butland formula.
+%
+    else
+
+      hsumt3 = 3.0 * hsum;
+      w1 = ( hsum + h1 ) / hsumt3;
+      w2 = ( hsum + h2 ) / hsumt3;
+      dmax = max ( abs ( del1 ), abs ( del2 ) );
+      dmin = min ( abs ( del1 ), abs ( del2 ) );
+      drat1 = del1 / dmax;
+      drat2 = del2 / dmax;
+      d(i) = dmin / ( w1 * drat1 + w2 * drat2 );
+
+    end
+
+  end
+%
+%  Set D(N) via non-centered three point formula, adjusted to be
+%  shape preserving.
+%
+  w1 = -h2 / hsum;
+  w2 = ( h2 + hsum ) / hsum;
+  d(n) = w1 * del1 + w2 * del2;
+
+  if ( pchst( d(n), del2 ) <= 0.0 )
+    d(n) = 0.0;
+  elseif ( pchst( del1, del2 ) < 0.0 )
+%
+%  Need do this check only if monotonicity switches.
+%
+    dmax = 3.0 * del2;
+
+    if ( abs ( dmax ) < abs ( d(n) ) )
+      d(n) = dmax;
+    end
+
+  end
+  
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SPLINE_PCHIP_VAL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
+function fe = spline_pchip_val ( n, x, f, d, ne, xe )
+
+%% SPLINE_PCHIP_VAL evaluates a piecewise cubic Hermite function.
+%
+%  Description:
+%
+%    This routine may be used by itself for Hermite interpolation, or as an
+%    evaluator for SPLINE_PCHIP_SET.
+%
+%    This routine evaluates the cubic Hermite function at the points XE.
+%
+%    Most of the coding between the call to CHFEV and the end of
+%    the IR loop could be eliminated if it were permissible to
+%    assume that XE is ordered relative to X.
+%
+%    CHFEV does not assume that X1 is less than X2.  Thus, it would
+%    be possible to write a version of SPLINE_PCHIP_VAL that assumes a strictly
+%    decreasing X array by simply running the IR loop backwards
+%    and reversing the order of appropriate tests.
+%
+%    The present code has a minor bug, which I have decided is not
+%    worth the effort that would be required to fix it.
+%    If XE contains points in [X(N-1),X(N)], followed by points less than
+%    X(N-1), followed by points greater than X(N), the extrapolation points
+%    will be counted (at least) twice in the total returned in IERR.
+%
+%    The evaluation will be most efficient if the elements of XE are
+%    increasing relative to X; that is, for all J <= K,
+%      X(I) <= XE(J)
+%    implies
+%      X(I) <= XE(K).
+%
+%    If any of the XE are outside the interval [X(1),X(N)],
+%    values are extrapolated from the nearest extreme cubic,
+%    and a warning error is returned.
+%
+%    This routine was originally named "PCHFE".
+%
+%  Modified:
+%
+%    14 August 2005
+%
+%  Author:
+%
+%    Fred Fritsch,
+%    Mathematics and Statistics Division,
+%    Lawrence Livermore National Laboratory.
+%
+%    MATLAB translation by John Burkardt.
+%
+%  Reference:
+%
+%    Fred Fritsch and R Carlson,
+%    Monotone Piecewise Cubic Interpolation,
+%    SIAM Journal on Numerical Analysis,
+%    Volume 17, Number 2, April 1980, pages 238-246.
+%
+%  Parameters:
+%
+%    Input, integer N, the number of data points.  N must be at least 2.
+%
+%    Input, real X(N), the strictly increasing independent
+%    variable values.
+%
+%    Input, real F(N), the function values.
+%
+%    Input, real D(N), the derivative values.
+%
+%    Input, integer NE, the number of evaluation points.
+%
+%    Input, real XE(NE), points at which the function is to
+%    be evaluated.
+%
+%    Output, real FE(NE), the values of the cubic Hermite
+%    function at XE.
+%
+
+%
+%  Check arguments.
+%
+  if ( n < 2 )
+    ierr = -1;
+    fprintf ( 1, '\n' );
+    fprintf ( 1, 'SPLINE_PCHIP_VAL - Fatal error!\n' );
+    fprintf ( 1, '  Number of data points less than 2.\n' );
+    error ( 'SPLINE_PCHIP_VAL - Fatal error!' );
+  end
+
+  for i = 2 : n
+    if ( x(i) <= x(i-1) )
+      ierr = -3;
+      fprintf ( 1, '\n' );
+      fprintf ( 1, 'SPLINE_PCHIP_VAL - Fatal error!\n' );
+      fprintf ( 1, '  X array not strictly increasing.\n' );
+      error ( 'SPLINE_PCHIP_VAL - Fatal error!' );
+    end
+  end
+
+  if ( ne < 1 )
+    ierr = -4;
+    fprintf ( 1, '\n' );
+    fprintf ( 1, 'SPLINE_PCHIP_VAL - Fatal error!\n' );
+    fprintf ( 1, '  Number of evaluation points less than 1.\n' );
+    fe = [];
+    return
+  end
+
+  ierr = 0;
+%
+%  Loop over intervals.
+%  The interval index is IL = IR-1.
+%  The interval is X(IL) <= X < X(IR).
+%
+  j_first = 1;
+  ir = 2;
+
+  while ( 1 )
+%
+%  Skip out of the loop if have processed all evaluation points.
+%
+    if ( ne < j_first )
+      break
+    end
+%
+%  Locate all points in the interval.
+%
+    j_save = ne + 1;
+
+    for j = j_first : ne
+      if ( x(ir) <= xe(j) )
+        j_save = j;
+        if ( ir == n )
+          j_save = ne + 1;
+        end
+        break
+      end
+    end
+%
+%  Have located first point beyond interval.
+%
+    j = j_save;
+
+    nj = j - j_first;
+%
+%  Skip evaluation if no points in interval.
+%
+    if ( nj ~= 0 )
+%
+%  Evaluate cubic at XE(J_FIRST:J-1).
+%
+      [ fe(j_first:j-1), next, ierc ] = chfev ( x(ir-1), x(ir), f(ir-1), ...
+        f(ir), d(ir-1), d(ir),  nj, xe(j_first:j-1) );
+
+      if ( ierc < 0 )
+        ierr = -5;
+        fprintf ( 1, '\n' );
+        fprintf ( 1, 'SPLINE_PCHIP_VAL - Fatal error!\n' );
+        fprintf ( 1, '  Error return from CHFEV.\n' );
+        error ( 'SPLINE_PCHIP_VAL - Fatal error!' );
+      end
+%
+%  In the current set of XE points, there are NEXT(2) to the right of X(IR).
+%
+      if ( next(2) ~= 0 )
+
+        if ( ir < n )
+          ierr = -5;
+          fprintf ( 1, '\n' );
+          fprintf ( 1, 'SPLINE_PCHIP_VAL - Fatal error!\n' );
+          fprintf ( 1, '  IR < N.\n' );
+          error ( 'SPLINE_PCHIP_VAL - Fatal error!' );
+        end
+%
+%  These are actually extrapolation points.
+%
+        ierr = ierr + next(2);
+
+      end
+%
+%  In the current set of XE points, there are NEXT(1) to the left of X(IR-1).
+%
+      if ( next(1) ~= 0 )
+%
+%  These are actually extrapolation points.
+%
+        if ( ir <= 2 )
+          ierr = ierr + next(1);
+        else
+
+          j_new = -1;
+
+          for i = j_first : j-1
+            if ( xe(i) < x(ir-1) )
+              j_new = i;
+              break
+            end
+          end
+
+          if ( j_new == -1 )
+            ierr = -5;
+            fprintf ( 1, '\n' );
+            fprintf ( 1, 'SPLINE_PCHIP_VAL - Fatal error!\n' );
+            fprintf ( 1, '  Could not bracket the data point.\n' );
+            error ( 'SPLINE_PCHIP_VAL - Fatal error!' );
+          end
+%
+%  Reset J.  This will be the new J_FIRST.
+%
+          j = j_new;
+%
+%  Now find out how far to back up in the X array.
+%
+          for i = 1 : ir-1
+            if ( xe(j) < x(i) )
+              break
+            end
+          end
+%
+%  At this point, either XE(J) < X(1) or X(i-1) <= XE(J) < X(I) .
+%
+%  Reset IR, recognizing that it will be incremented before cycling.
+%
+          ir = max ( 1, i-1 );
+
+        end
+
+      end
+
+      j_first = j;
+
+    end
+
+    ir = ir + 1;
+
+    if ( n < ir )
+      break
+    end
+
+  end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHFEV
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
+function [ fe, next, ierr ] = chfev ( x1, x2, f1, f2, d1, d2, ne, xe )
+
+%% CHFEV evaluates a cubic polynomial given in Hermite form.
+%
+%  Discussion:
+%
+%    This routine evaluates a cubic polynomial given in Hermite form at an
+%    array of points.  While designed for use by SPLINE_PCHIP_VAL, it may
+%    be useful directly as an evaluator for a piecewise cubic
+%    Hermite function in applications, such as graphing, where
+%    the interval is known in advance.
+%
+%    The cubic polynomial is determined by function values
+%    F1, F2 and derivatives D1, D2 on the interval [X1,X2].
+%
+%  Modified:
+%
+%    14 August 2005
+%
+%  Author:
+%
+%    Fred Fritsch,
+%    Mathematics and Statistics Division,
+%    Lawrence Livermore National Laboratory.
+%
+%    MATLAB translation by John Burkardt.
+%
+%  Reference:
+%
+%    Fred Fritsch and R Carlson,
+%    Monotone Piecewise Cubic Interpolation,
+%    SIAM Journal on Numerical Analysis,
+%    Volume 17, Number 2, April 1980, pages 238-246.
+%
+%    David Kahaner, Clever Moler, Steven Nash,
+%    Numerical Methods and Software,
+%    Prentice Hall, 1988.
+%
+%  Parameters:
+%
+%    Input, real X1, X2, the endpoints of the interval of
+%    definition of the cubic.  X1 and X2 must be distinct.
+%
+%    Input, real F1, F2, the values of the function at X1 and
+%    X2, respectively.
+%
+%    Input, real D1, D2, the derivative values at X1 and
+%    X2, respectively.
+%
+%    Input, integer NE, the number of evaluation points.
+%
+%    Input, real XE(NE), the points at which the function is to
+%    be evaluated.  If any of the XE are outside the interval
+%    [X1,X2], a warning error is returned in NEXT.
+%
+%    Output, real FE(NE), the value of the cubic function
+%    at the points XE.
+%
+%    Output, integer NEXT(2), indicates the number of extrapolation points:
+%    NEXT(1) = number of evaluation points to the left of interval.
+%    NEXT(2) = number of evaluation points to the right of interval.
+%
+%    Output, integer IERR, error flag.
+%    0, no errors.
+%    -1, NE < 1.
+%    -2, X1 == X2.
+%
+  if ( ne < 1 )
+    ierr = -1;
+    fprintf ( 1, '\n' );
+    fprintf ( 1, 'CHFEV - Fatal error!\n' );
+    fprintf ( 1, '  Number of evaluation points is less than 1.\n' );
+    fprintf ( 1, '  NE = %d\n', ne );
+    error ( 'CHFEV - Fatal error!' )
+  end
+
+  h = x2 - x1;
+
+  if ( h == 0.0 )
+    ierr = -2;
+    fprintf ( 1, '\n' );
+    fprintf ( 1, 'CHFEV - Fatal error!\n' );
+    fprintf ( 1, '  The interval [X1,X2] is of zero length.\n' );
+    error ( 'CHFEV - Fatal error!' )
+  end
+%
+%  Initialize.
+%
+  ierr = 0;
+  next(1) = 0;
+  next(2) = 0;
+  xmi = min ( 0.0, h );
+  xma = max ( 0.0, h );
+%
+%  Compute cubic coefficients expanded about X1.
+%
+  delta = ( f2 - f1 ) / h;
+  del1 = ( d1 - delta ) / h;
+  del2 = ( d2 - delta ) / h;
+  c2 = -( del1 + del1 + del2 );
+  c3 = ( del1 + del2 ) / h;
+%
+%  Evaluation loop.
+%
+  for i = 1 : ne
+
+    x = xe(i) - x1;
+    fe(i) = f1 + x * ( d1 + x * ( c2 + x * c3 ) );
+%
+%  Count the extrapolation points.
+%
+    if ( x < xmi )
+      next(1) = next(1) + 1;
+    end
+
+    if ( xma < x )
+      next(2) = next(2) + 1;
+    end
+
+  end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PCHST
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
+function value = pchst( arg1, arg2 )
+
+%% PCHST: PCHIP sign-testing routine.
+%
+%  Discussion:
+%
+%    This routine essentially computes the sign of ARG1 * ARG2.
+%
+%    The object is to do this without multiplying ARG1 * ARG2, to avoid
+%    possible over/underflow problems.
+%
+%  Modified:
+%
+%    14 August 2005
+%
+%  Author:
+%
+%    Fred Fritsch,
+%    Mathematics and Statistics Division,
+%    Lawrence Livermore National Laboratory.
+%
+%    MATLAB translation by John Burkardt.
+%
+%  Reference:
+%
+%    Fred Fritsch and R Carlson,
+%    Monotone Piecewise Cubic Interpolation,
+%    SIAM Journal on Numerical Analysis,
+%    Volume 17, Number 2, April 1980, pages 238-246.
+%
+%  Parameters:
+%
+%    Input, real ARG1, ARG2, two values to check.
+%
+%    Output, real VALUE,
+%    -1.0, if ARG1 and ARG2 are of opposite sign.
+%     0.0, if either argument is zero.
+%    +1.0, if ARG1 and ARG2 are of the same sign.
+%
+  if ( arg1 == 0.0 )
+    value = 0.0;
+  elseif ( arg1 < 0.0 )
+    if ( arg2 < 0.0 )
+      value = 1.0;
+    elseif ( arg2 == 0.0 )
+      value = 0.0;
+    elseif ( 0.0 < arg2 )
+      value = -1.0;
+    end
+  elseif ( 0.0 < arg1 )
+    if ( arg2 < 0.0 )
+      value = -1.0;
+    elseif ( arg2 == 0.0 )
+      value = 0.0;
+    elseif ( 0.0 < arg2 )
+      value = 1.0;
+    end
+  end
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/interpcseSB.c b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/interpcseSB.c
new file mode 100644
index 0000000000000000000000000000000000000000..ef1b53610331b7a9bd235f523148468003aac2d8
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/interpcseSB.c
@@ -0,0 +1,442 @@
+/*
+ * interpcseSB.c: Cubic spline interpolation with endpoints
+ *
+ * MEX interface: Henning Schmidt
+ * Original C-code for spline interpolation taken from:
+ *   http://www.mech.uq.edu.au/staff/jacobs/nm_lib/cmathsrc/spline.c
+ *
+ * The syntax of this MEX functions is as follows:
+ *
+ * yy = interpcseSB(x,y,xx)
+ * yy = interpcseSB(x,y,xx,e1,e2)
+ *
+ * x:     x-values 
+ * y:     y-values
+ * xx:    x-values at which to evaluate the spline function (allow multiple)
+ * e1,e2: endpoint derivatives (if specified, both need to be given)
+ * yy:    interpolated value
+ */
+
+/* Some includes to be sure we got everything that is needed */
+#include <mex.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <stdarg.h>
+#include <string.h>
+#include <matrix.h>
+#include <math.h>
+
+/*
+ *========================================================================
+ * Initialization of the spline related functions
+ *========================================================================
+ */
+void spline (int n, int e1, int e2, double s1, double s2, double x[], double y[], double b[], double c[], double d[], int *flag);
+double seval (int n, double xx, double x[], double y[], double b[], double c[], double d[], int *last);
+
+/*
+ *========================================================================
+ * Definition of needed variables to be passed to the spline functions
+ *========================================================================
+ */
+int     n;          /* The number of data points or knots (n >= 2) */
+int     e1=0;       /* = 1 to specify the slopes at the end points, = 0 to obtain the default conditions */
+int     e2=0;       /* = 1 to specify the slopes at the end points, = 0 to obtain the default conditions */
+double  s1;         /* the slopes at the end point x[0] */
+double  s2;         /* the slopes at the end point x[n-1] */
+double* x;          /* the abscissas of the knots in strictly increasing order */
+double* y;          /* the ordinates of the knots */
+double* b=NULL;     /* arrays of spline coefficients (length n) */
+double* c=NULL;     /* arrays of spline coefficients (length n) */
+double* d=NULL;     /* arrays of spline coefficients (length n) */
+int     flag=0;     /* status flag = 0 normal return = 1 less than two data points; cannot interpolate = 2 x[] are not in ascending order */
+int     last;       /* the segment in which xx lies */
+double* xx;         /* the abscissa at which the spline is to be evaluated */
+double* yy=NULL;    /* the evaluated value at xx */
+int     nx;         /* number of xx values to interpolate the spline function at */
+int     k;          /* loop variable */
+double  b2; 
+double  c2; 
+double  d2; 
+
+/*
+ *===================================
+ * Definition of needed MEX variables
+ *===================================
+ */
+mxArray *xMX = NULL;
+mxArray *yMX = NULL;
+mxArray *xxMX = NULL;
+mxArray *s1MX = NULL;
+mxArray *s2MX = NULL;
+mxArray *yyMX = NULL;
+
+/*
+ *========================================================================
+ * MEX INTERFACE FUNCTION
+ *========================================================================
+ */
+void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
+{
+    /*************************************/
+    /* Check correct number of arguments */
+    /*************************************/
+    /* Check correct number of input arguments */
+    if (nrhs != 3 && nrhs != 5) mexErrMsgTxt("interpcseSB: Incorrect number of input arguments.");
+    /* Check correct number of output arguments */
+    if (nlhs != 1) mexErrMsgTxt("interpcseSB: Incorrect number of output arguments.");
+    
+    /**************************************************************************************/
+    /* Get and check input arguments and extract some first info for the spline functions */
+    /**************************************************************************************/
+    /* First input argument needs to be a double vector with length >= 2 */
+    if (!mxIsDouble(prhs[0])) mexErrMsgTxt("interpcseSB: Check first input argument, it needs to be a vector of x-values.");
+    xMX = (mxArray *) prhs[0];
+    n = mxGetM(xMX)*mxGetN(xMX);
+    if (n<2) mexErrMsgTxt("interpcseSB: please provide at least n points with n>=2 (add commata as element separators in the vectors!).");
+    else x = mxGetPr(xMX);    
+    
+    /* Second input argument needs to be a double vector with the same length as the first */
+    if (!mxIsDouble(prhs[1])) mexErrMsgTxt("interpcseSB: Check second input argument, it needs to be a vector of y-values.");
+    yMX = (mxArray *) prhs[1];
+    if (n != mxGetM(yMX)*mxGetN(yMX)) mexErrMsgTxt("interpcseSB: Second input argument (y-values) needs as many elements as first argument (x-values).");
+    y = mxGetPr(yMX);    
+    
+    /* Third input argument should be a scalar or a vector */
+    if (!mxIsDouble(prhs[2])) mexErrMsgTxt("interpcseSB: Check third input argument, it needs to be a scalar or vector of numeric values at which to evaluate the spline.");
+    xxMX = (mxArray *) prhs[2];
+    nx = mxGetM(xxMX)*mxGetN(xxMX);
+    if (n<1) mexErrMsgTxt("interpcseSB: please provide at least 1 points for the third input argument.");
+    xx = mxGetPr(xxMX);    
+
+    if (nrhs > 3) {
+        /* Fourth input argument needs to be a scalar double */
+        if (!mxIsDouble(prhs[3]) || !mxIsScalar(prhs[3])) mexErrMsgTxt("interpcseSB: Check fourth input argument, it needs to be a scalar numeric value with the first derivative.");
+        s1MX = (mxArray *) prhs[3];
+        s1 = mxGetScalar(s1MX);
+        e1 = 1; /* slope given */
+    
+        /* Fifth input argument needs to be a scalar double */
+        if (!mxIsDouble(prhs[4]) || !mxIsScalar(prhs[4])) mexErrMsgTxt("interpcseSB: Check fifth input argument, it needs to be a scalar numeric value with the last derivative.");
+        s2MX = (mxArray *) prhs[4];
+        s2 = mxGetScalar(s2MX);
+        e2 = 1; /* slope given */
+    } else {
+        e1 = 0;
+        e2 = 0;
+        s1 = 0.0;
+        s2 = 0.0;
+    }
+    
+    /**************************/
+    /* Create output argument */
+    /**************************/
+    yyMX = mxCreateDoubleMatrix(nx, 1, mxREAL);
+    yy = mxGetPr(yyMX);
+
+    /***********/
+    /* If n==2 */
+    /***********/
+    if (n==2) {        
+        if (e1 == 0 || e2 == 0) mexErrMsgTxt("interpcseSB: n=2 requires the definition of slopes.");
+        b2 = s1;
+        c2 = -(-3.0*y[1]+3.0*y[0]+(s2+2.0*s1)*x[1]+(-s2-2.0*s1)*x[0])/(pow(x[1],2.0)-2.0*x[0]*x[1]+pow(x[0],2.0));
+        d2 = (-2.0*y[1]+2.0*y[0]+(s2+s1)*x[1]+(-s2-s1)*x[0])/(pow(x[1],3.0)-3.0*x[0]*pow(x[1],2.0)+3.0*pow(x[0],2.0)*x[1]-pow(x[0],3.0));
+        
+        /***************************************/
+        /* Call the spline evaluation function */
+        /***************************************/
+        for (k=0;k<nx;k++) {
+            yy[k] = y[0] + b2*(xx[k]-x[0]) + c2*pow(xx[k]-x[0],2.0) + d2*pow(xx[k]-x[0],3.0);
+        }
+    } else {
+    /***********/
+    /* If n!=2 */
+    /***********/        
+        /********************************/
+        /* Allocate memory for b,c,d,yy */
+        /********************************/
+        b  = (double *) mxCalloc(n, sizeof(double));
+        c  = (double *) mxCalloc(n, sizeof(double));
+        d  = (double *) mxCalloc(n, sizeof(double));
+        
+        /****************************/
+        /* Call the spline function */
+        /****************************/
+        spline(n, e1, e2, s1, s2, x, y, b, c, d, &flag);
+        
+        /***************************************/
+        /* Call the spline evaluation function */
+        /***************************************/
+        for (k=0;k<nx;k++) {
+            yy[k] = seval(n, xx[k], x, y, b, c, d, &last);
+        }
+        
+        /*************************/
+        /* Free allocated memory */
+        /*************************/
+        mxFree(b);
+        mxFree(c);
+        mxFree(d);
+    }
+
+    /*******************************/
+    /* Return the result to MATLAB */
+    /*******************************/
+    plhs[0] = yyMX;
+}
+
+/*=========================================================================
+   Cubic spline coefficients
+   -------------------------
+   Evaluate the coefficients b[i], c[i], d[i], i = 0, 1, .. n-1 for
+   a cubic interpolating spline
+
+   S(xx) = Y[i] + b[i] * w + c[i] * w**2 + d[i] * w**3
+   where w = xx - x[i]
+   and   x[i] <= xx <= x[i+1]
+
+   The n supplied data points are x[i], y[i], i = 0 ... n-1.
+
+   Input :
+   -------
+   n       : The number of data points or knots (n >= 2)
+   end1,
+   end2    : = 1 to specify the slopes at the end points
+             = 0 to obtain the default conditions
+   slope1,
+   slope2  : the slopes at the end points x[0] and x[n-1]
+             respectively
+   x[]     : the abscissas of the knots in strictly
+             increasing order
+   y[]     : the ordinates of the knots
+
+   Output :
+   --------
+   b, c, d : arrays of spline coefficients as defined above
+             (See note 2 for a definition.)
+   iflag   : status flag
+            = 0 normal return
+            = 1 less than two data points; cannot interpolate
+            = 2 x[] are not in ascending order
+
+   This C code written by ...  Peter & Nigel,
+   ----------------------      Design Software,
+                               42 Gubberley St,
+                               Kenmore, 4069,
+                               Australia.
+
+   Version ... 1.1, 30 September 1987
+   -------     2.0, 6 April 1989    (start with zero subscript)
+                                     remove ndim from parameter list
+               2.1, 28 April 1989   (check on x[])
+               2.2, 10 Oct   1989   change number order of matrix
+
+   Notes ...
+   -----
+   (1) The accompanying function seval() may be used to evaluate the
+       spline while deriv will provide the first derivative.
+   (2) Using p to denote differentiation
+       y[i] = S(X[i])
+       b[i] = Sp(X[i])
+       c[i] = Spp(X[i])/2
+       d[i] = Sppp(X[i])/6  ( Derivative from the right )
+   (3) Since the zero elements of the arrays ARE NOW used here,
+       all arrays to be passed from the main program should be
+       dimensioned at least [n].  These routines will use elements
+       [0 .. n-1].
+   (4) Adapted from the text
+       Forsythe, G.E., Malcolm, M.A. and Moler, C.B. (1977)
+       "Computer Methods for Mathematical Computations"
+       Prentice Hall
+   (5) Note that although there are only n-1 polynomial segments,
+       n elements are requird in b, c, d.  The elements b[n-1],
+       c[n-1] and d[n-1] are set to continue the last segment
+       past x[n-1].
+=========================================================================*/
+void spline (int n, int end1, int end2,
+            double slope1, double slope2,
+            double x[], double y[],
+            double b[], double c[], double d[],
+            int *iflag)
+{  /* begin procedure spline() */
+
+int    nm1, ib, i;
+double t;
+int    ascend;
+
+nm1    = n - 1;
+*iflag = 0;
+
+if (n < 2)
+  {  /* no possible interpolation */
+  *iflag = 1;
+  return;
+  }
+
+ascend = 1;
+for (i = 1; i < n; ++i) if (x[i] <= x[i-1]) ascend = 0;
+if (!ascend)
+   {
+   *iflag = 2;
+   return;
+   }
+
+if (n >= 3)
+   {    /* ---- At least quadratic ---- */
+
+   /* ---- Set up the symmetric tri-diagonal system
+           b = diagonal
+           d = offdiagonal
+           c = right-hand-side  */
+   d[0] = x[1] - x[0];
+   c[1] = (y[1] - y[0]) / d[0];
+   for (i = 1; i < nm1; ++i)
+      {
+      d[i]   = x[i+1] - x[i];
+      b[i]   = 2.0 * (d[i-1] + d[i]);
+      c[i+1] = (y[i+1] - y[i]) / d[i];
+      c[i]   = c[i+1] - c[i];
+      }
+
+   /* ---- Default End conditions
+           Third derivatives at x[0] and x[n-1] obtained
+           from divided differences  */
+   b[0]   = -d[0];
+   b[nm1] = -d[n-2];
+   c[0]   = 0.0;
+   c[nm1] = 0.0;
+   if (n != 3)
+      {
+      c[0]   = c[2] / (x[3] - x[1]) - c[1] / (x[2] - x[0]);
+      c[nm1] = c[n-2] / (x[nm1] - x[n-3]) - c[n-3] / (x[n-2] - x[n-4]);
+      c[0]   = c[0] * d[0] * d[0] / (x[3] - x[0]);
+      c[nm1] = -c[nm1] * d[n-2] * d[n-2] / (x[nm1] - x[n-4]);
+      }
+
+   /* Alternative end conditions -- known slopes */
+   if (end1 == 1)
+      {
+      b[0] = 2.0 * (x[1] - x[0]);
+      c[0] = (y[1] - y[0]) / (x[1] - x[0]) - slope1;
+      }
+   if (end2 == 1)
+      {
+      b[nm1] = 2.0 * (x[nm1] - x[n-2]);
+      c[nm1] = slope2 - (y[nm1] - y[n-2]) / (x[nm1] - x[n-2]);
+      }
+
+   /* Forward elimination */
+   for (i = 1; i < n; ++i)
+     {
+     t    = d[i-1] / b[i-1];
+     b[i] = b[i] - t * d[i-1];
+     c[i] = c[i] - t * c[i-1];
+     }
+
+   /* Back substitution */
+   c[nm1] = c[nm1] / b[nm1];
+   for (ib = 0; ib < nm1; ++ib)
+      {
+      i    = n - ib - 2;
+      c[i] = (c[i] - d[i] * c[i+1]) / b[i];
+      }
+
+   /* c[i] is now the sigma[i] of the text */
+
+   /* Compute the polynomial coefficients */
+   b[nm1] = (y[nm1] - y[n-2]) / d[n-2] + d[n-2] * (c[n-2] + 2.0 * c[nm1]);
+   for (i = 0; i < nm1; ++i)
+      {
+      b[i] = (y[i+1] - y[i]) / d[i] - d[i] * (c[i+1] + 2.0 * c[i]);
+      d[i] = (c[i+1] - c[i]) / d[i];
+      c[i] = 3.0 * c[i];
+      }
+   c[nm1] = 3.0 * c[nm1];
+   d[nm1] = d[n-2];
+
+   }  /* at least quadratic */
+
+else  /* if n >= 3 */
+   {  /* linear segment only  */
+   b[0] = (y[1] - y[0]) / (x[1] - x[0]);
+   c[0] = 0.0;
+   d[0] = 0.0;
+   b[1] = b[0];
+   c[1] = 0.0;
+   d[1] = 0.0;
+   }
+}  /* end of spline() */
+
+
+/*-------------------------------------------------------------------*/
+/*-----------------------------------------------------------------*/
+/*-----------------------------------------------------------------*/
+double seval (int n, double u,
+              double x[], double y[],
+              double b[], double c[], double d[],
+              int *last)
+/*-----------------------------------------------------------------*/
+/*Purpose ...
+  -------
+  Evaluate the cubic spline function
+
+  S(xx) = y[i] + b[i] * w + c[i] * w**2 + d[i] * w**3
+  where w = u - x[i]
+  and   x[i] <= u <= x[i+1]
+  Note that Horner's rule is used.
+  If u < x[0]   then i = 0 is used.
+  If u > x[n-1] then i = n-1 is used.
+
+  Input :
+  -------
+  n       : The number of data points or knots (n >= 2)
+  u       : the abscissa at which the spline is to be evaluated
+  Last    : the segment that was last used to evaluate U
+  x[]     : the abscissas of the knots in strictly increasing order
+  y[]     : the ordinates of the knots
+  b, c, d : arrays of spline coefficients computed by spline().
+
+  Output :
+  --------
+  seval   : the value of the spline function at u
+  Last    : the segment in which u lies
+
+  Notes ...
+  -----
+  (1) If u is not in the same interval as the previous call then a
+      binary search is performed to determine the proper interval.
+
+*/
+/*-------------------------------------------------------------------*/
+{  /* begin function seval() */
+
+int    i, j, k;
+double w;
+
+i = *last;
+if (i >= n-1) i = 0;
+if (i < 0)  i = 0;
+
+if ((x[i] > u) || (x[i+1] < u))
+  {  /* ---- perform a binary search ---- */
+  i = 0;
+  j = n;
+  do
+    {
+    k = (i + j) / 2;         /* split the domain to search */
+    if (u < x[k])  j = k;    /* move the upper bound */
+    if (u >= x[k]) i = k;    /* move the lower bound */
+    }                        /* there are no more segments to search */
+  while (j > i+1);
+  }
+*last = i;
+
+/* ---- Evaluate the spline ---- */
+w = u - x[i];
+w = y[i] + w * (b[i] + w * (c[i] + w * d[i]));
+return (w);
+}
+/*-------------------------------------------------------------------*/
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/interpcseSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/interpcseSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..8ac19171b951e34795cecc03996cea6b881ecb1a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/interpcseSB.m
@@ -0,0 +1,40 @@
+% interpcseSB: Cubic spline interpolation with endpoints
+% This is a MEX function, so this .m file only contains the documentation.
+%
+% USAGE:
+% ======
+% yy = interpcseSB(x,y,xx)
+% yy = interpcseSB(x,y,xx,e1,e2)
+% 
+% x:     x-values 
+% y:     y-values
+% xx:    x-values at which to evaluate the spline function (allow multiple)
+% e1,e2: endpoint derivatives (if specified, both need to be given)
+% yy:    interpolated value
+%
+% DEFAULT VALUES:
+% ===============
+% e1, e2:   =0 (no endpoint slopes defined)
+%
+% Output Arguments:
+% =================
+% yy:    scalar or vector of interpolated values.
+
+% Information:
+% ============
+% Copyright (C) 2009 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/interpcseSlopeSB.c b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/interpcseSlopeSB.c
new file mode 100644
index 0000000000000000000000000000000000000000..147489c143c591c721ab11405fc7009a204930d2
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/interpcseSlopeSB.c
@@ -0,0 +1,443 @@
+/*
+ * interpcseSlopeSB.c: Cubic spline interpolation with endpoints (DERIVATIVE)
+ *
+ * MEX interface: Henning Schmidt
+ * Original C-code for spline interpolation taken from:
+ *   http://www.mech.uq.edu.au/staff/jacobs/nm_lib/cmathsrc/spline.c
+ *
+ * The syntax of this MEX functions is as follows:
+ *
+ * yy = interpcseSlopeSB(x,y,xx)
+ * yy = interpcseSlopeSB(x,y,xx,e1,e2)
+ *
+ * x:     x-values 
+ * y:     y-values
+ * xx:    x-values at which to evaluate the spline function (allow multiple)
+ * e1,e2: endpoint derivatives (if specified, both need to be given)
+ * yy:    DERIVATIVE OF SPLINE FUNCTION AT xx
+ */
+
+/* Some includes to be sure we got everything that is needed */
+#include <mex.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <stdarg.h>
+#include <string.h>
+#include <matrix.h>
+#include <math.h>
+
+/*
+ *========================================================================
+ * Initialization of the spline related functions
+ *========================================================================
+ */
+void spline (int n, int e1, int e2, double s1, double s2, double x[], double y[], double b[], double c[], double d[], int *flag);
+double deriv (int n, double xx, double x[], double b[], double c[], double d[], int *last);
+
+/*
+ *========================================================================
+ * Definition of needed variables to be passed to the spline functions
+ *========================================================================
+ */
+int     n;          /* The number of data points or knots (n >= 2) */
+int     e1=0;       /* = 1 to specify the slopes at the end points, = 0 to obtain the default conditions */
+int     e2=0;       /* = 1 to specify the slopes at the end points, = 0 to obtain the default conditions */
+double  s1;         /* the slopes at the end point x[0] */
+double  s2;         /* the slopes at the end point x[n-1] */
+double* x;          /* the abscissas of the knots in strictly increasing order */
+double* y;          /* the ordinates of the knots */
+double* b=NULL;     /* arrays of spline coefficients (length n) */
+double* c=NULL;     /* arrays of spline coefficients (length n) */
+double* d=NULL;     /* arrays of spline coefficients (length n) */
+int     flag=0;     /* status flag = 0 normal return = 1 less than two data points; cannot interpolate = 2 x[] are not in ascending order */
+int     last;       /* the segment in which xx lies */
+double* xx;         /* the abscissa at which the spline is to be evaluated */
+double* yy=NULL;    /* the evaluated value at xx */
+int     nx;         /* number of xx values to interpolate the spline function at */
+int     k;          /* loop variable */
+double  b2; 
+double  c2; 
+double  d2; 
+
+/*
+ *===================================
+ * Definition of needed MEX variables
+ *===================================
+ */
+mxArray *xMX = NULL;
+mxArray *yMX = NULL;
+mxArray *xxMX = NULL;
+mxArray *s1MX = NULL;
+mxArray *s2MX = NULL;
+mxArray *yyMX = NULL;
+
+/*
+ *========================================================================
+ * MEX INTERFACE FUNCTION
+ *========================================================================
+ */
+void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
+{
+    /*************************************/
+    /* Check correct number of arguments */
+    /*************************************/
+    /* Check correct number of input arguments */
+    if (nrhs != 3 && nrhs != 5) mexErrMsgTxt("interpcseSB: Incorrect number of input arguments.");
+    /* Check correct number of output arguments */
+    if (nlhs != 1) mexErrMsgTxt("interpcseSB: Incorrect number of output arguments.");
+    
+    /**************************************************************************************/
+    /* Get and check input arguments and extract some first info for the spline functions */
+    /**************************************************************************************/
+    /* First input argument needs to be a double vector with length >= 2 */
+    if (!mxIsDouble(prhs[0])) mexErrMsgTxt("interpcseSB: Check first input argument, it needs to be a vector of x-values.");
+    xMX = (mxArray *) prhs[0];
+    n = mxGetM(xMX)*mxGetN(xMX);
+    if (n<2) mexErrMsgTxt("interpcseSB: please provide at least n points with n>=2 (add commata as element separators in the vectors!).");
+    else x = mxGetPr(xMX);    
+    
+    /* Second input argument needs to be a double vector with the same length as the first */
+    if (!mxIsDouble(prhs[1])) mexErrMsgTxt("interpcseSB: Check second input argument, it needs to be a vector of y-values.");
+    yMX = (mxArray *) prhs[1];
+    if (n != mxGetM(yMX)*mxGetN(yMX)) mexErrMsgTxt("interpcseSB: Second input argument (y-values) needs as many elements as first argument (x-values).");
+    y = mxGetPr(yMX);    
+    
+    /* Third input argument should be a scalar or a vector */
+    if (!mxIsDouble(prhs[2])) mexErrMsgTxt("interpcseSB: Check third input argument, it needs to be a scalar or vector of numeric values at which to evaluate the spline.");
+    xxMX = (mxArray *) prhs[2];
+    nx = mxGetM(xxMX)*mxGetN(xxMX);
+    if (n<1) mexErrMsgTxt("interpcseSB: please provide at least 1 points for the third input argument.");
+    xx = mxGetPr(xxMX);    
+
+    if (nrhs > 3) {
+        /* Fourth input argument needs to be a scalar double */
+        if (!mxIsDouble(prhs[3]) || !mxIsScalar(prhs[3])) mexErrMsgTxt("interpcseSB: Check fourth input argument, it needs to be a scalar numeric value with the first derivative.");
+        s1MX = (mxArray *) prhs[3];
+        s1 = mxGetScalar(s1MX);
+        e1 = 1; /* slope given */
+    
+        /* Fifth input argument needs to be a scalar double */
+        if (!mxIsDouble(prhs[4]) || !mxIsScalar(prhs[4])) mexErrMsgTxt("interpcseSB: Check fifth input argument, it needs to be a scalar numeric value with the last derivative.");
+        s2MX = (mxArray *) prhs[4];
+        s2 = mxGetScalar(s2MX);
+        e2 = 1; /* slope given */
+    } else {
+        e1 = 0;
+        e2 = 0;
+        s1 = 0.0;
+        s2 = 0.0;
+    }
+    
+    /**************************/
+    /* Create output argument */
+    /**************************/
+    yyMX = mxCreateDoubleMatrix(nx, 1, mxREAL);
+    yy = mxGetPr(yyMX);
+
+    /***********/
+    /* If n==2 */
+    /***********/
+    if (n==2) {        
+        if (e1 == 0 || e2 == 0) mexErrMsgTxt("interpcseSB: n=2 requires the definition of endpoint-slopes.");
+        b2 = s1;
+        c2 = -(-3.0*y[1]+3.0*y[0]+(s2+2.0*s1)*x[1]+(-s2-2.0*s1)*x[0])/(pow(x[1],2.0)-2.0*x[0]*x[1]+pow(x[0],2.0));
+        d2 = (-2.0*y[1]+2.0*y[0]+(s2+s1)*x[1]+(-s2-s1)*x[0])/(pow(x[1],3.0)-3.0*x[0]*pow(x[1],2.0)+3.0*pow(x[0],2.0)*x[1]-pow(x[0],3.0));
+        
+        /***************************************/
+        /* Call the spline evaluation function */
+        /***************************************/
+        for (k=0;k<nx;k++) {
+            yy[k] = b2 + 2.0*c2*(xx[k]-x[0]) + 3.0*d2*pow(xx[k]-x[0],2.0);
+        }
+    } else {
+    /***********/
+    /* If n!=2 */
+    /***********/        
+        /********************************/
+        /* Allocate memory for b,c,d,yy */
+        /********************************/
+        b  = (double *) mxCalloc(n, sizeof(double));
+        c  = (double *) mxCalloc(n, sizeof(double));
+        d  = (double *) mxCalloc(n, sizeof(double));
+        
+        /****************************/
+        /* Call the spline function */
+        /****************************/
+        spline(n, e1, e2, s1, s2, x, y, b, c, d, &flag);
+        
+        /***************************************/
+        /* Call the spline evaluation function */
+        /***************************************/
+        for (k=0;k<nx;k++) {
+            yy[k] = deriv(n, xx[k], x, b, c, d, &last);
+        }
+        
+        /*************************/
+        /* Free allocated memory */
+        /*************************/
+        mxFree(b);
+        mxFree(c);
+        mxFree(d);
+    }
+
+    /*******************************/
+    /* Return the result to MATLAB */
+    /*******************************/
+    plhs[0] = yyMX;
+}
+
+/*=========================================================================
+   Cubic spline coefficients
+   -------------------------
+   Evaluate the coefficients b[i], c[i], d[i], i = 0, 1, .. n-1 for
+   a cubic interpolating spline
+
+   S(xx) = Y[i] + b[i] * w + c[i] * w**2 + d[i] * w**3
+   where w = xx - x[i]
+   and   x[i] <= xx <= x[i+1]
+
+   The n supplied data points are x[i], y[i], i = 0 ... n-1.
+
+   Input :
+   -------
+   n       : The number of data points or knots (n >= 2)
+   end1,
+   end2    : = 1 to specify the slopes at the end points
+             = 0 to obtain the default conditions
+   slope1,
+   slope2  : the slopes at the end points x[0] and x[n-1]
+             respectively
+   x[]     : the abscissas of the knots in strictly
+             increasing order
+   y[]     : the ordinates of the knots
+
+   Output :
+   --------
+   b, c, d : arrays of spline coefficients as defined above
+             (See note 2 for a definition.)
+   iflag   : status flag
+            = 0 normal return
+            = 1 less than two data points; cannot interpolate
+            = 2 x[] are not in ascending order
+
+   This C code written by ...  Peter & Nigel,
+   ----------------------      Design Software,
+                               42 Gubberley St,
+                               Kenmore, 4069,
+                               Australia.
+
+   Version ... 1.1, 30 September 1987
+   -------     2.0, 6 April 1989    (start with zero subscript)
+                                     remove ndim from parameter list
+               2.1, 28 April 1989   (check on x[])
+               2.2, 10 Oct   1989   change number order of matrix
+
+   Notes ...
+   -----
+   (1) The accompanying function seval() may be used to evaluate the
+       spline while deriv will provide the first derivative.
+   (2) Using p to denote differentiation
+       y[i] = S(X[i])
+       b[i] = Sp(X[i])
+       c[i] = Spp(X[i])/2
+       d[i] = Sppp(X[i])/6  ( Derivative from the right )
+   (3) Since the zero elements of the arrays ARE NOW used here,
+       all arrays to be passed from the main program should be
+       dimensioned at least [n].  These routines will use elements
+       [0 .. n-1].
+   (4) Adapted from the text
+       Forsythe, G.E., Malcolm, M.A. and Moler, C.B. (1977)
+       "Computer Methods for Mathematical Computations"
+       Prentice Hall
+   (5) Note that although there are only n-1 polynomial segments,
+       n elements are requird in b, c, d.  The elements b[n-1],
+       c[n-1] and d[n-1] are set to continue the last segment
+       past x[n-1].
+=========================================================================*/
+void spline (int n, int end1, int end2,
+            double slope1, double slope2,
+            double x[], double y[],
+            double b[], double c[], double d[],
+            int *iflag)
+{  /* begin procedure spline() */
+
+int    nm1, ib, i;
+double t;
+int    ascend;
+
+nm1    = n - 1;
+*iflag = 0;
+
+if (n < 2)
+  {  /* no possible interpolation */
+  *iflag = 1;
+  return;
+  }
+
+ascend = 1;
+for (i = 1; i < n; ++i) if (x[i] <= x[i-1]) ascend = 0;
+if (!ascend)
+   {
+   *iflag = 2;
+   return;
+   }
+
+if (n >= 3)
+   {    /* ---- At least quadratic ---- */
+
+   /* ---- Set up the symmetric tri-diagonal system
+           b = diagonal
+           d = offdiagonal
+           c = right-hand-side  */
+   d[0] = x[1] - x[0];
+   c[1] = (y[1] - y[0]) / d[0];
+   for (i = 1; i < nm1; ++i)
+      {
+      d[i]   = x[i+1] - x[i];
+      b[i]   = 2.0 * (d[i-1] + d[i]);
+      c[i+1] = (y[i+1] - y[i]) / d[i];
+      c[i]   = c[i+1] - c[i];
+      }
+
+   /* ---- Default End conditions
+           Third derivatives at x[0] and x[n-1] obtained
+           from divided differences  */
+   b[0]   = -d[0];
+   b[nm1] = -d[n-2];
+   c[0]   = 0.0;
+   c[nm1] = 0.0;
+   if (n != 3)
+      {
+      c[0]   = c[2] / (x[3] - x[1]) - c[1] / (x[2] - x[0]);
+      c[nm1] = c[n-2] / (x[nm1] - x[n-3]) - c[n-3] / (x[n-2] - x[n-4]);
+      c[0]   = c[0] * d[0] * d[0] / (x[3] - x[0]);
+      c[nm1] = -c[nm1] * d[n-2] * d[n-2] / (x[nm1] - x[n-4]);
+      }
+
+   /* Alternative end conditions -- known slopes */
+   if (end1 == 1)
+      {
+      b[0] = 2.0 * (x[1] - x[0]);
+      c[0] = (y[1] - y[0]) / (x[1] - x[0]) - slope1;
+      }
+   if (end2 == 1)
+      {
+      b[nm1] = 2.0 * (x[nm1] - x[n-2]);
+      c[nm1] = slope2 - (y[nm1] - y[n-2]) / (x[nm1] - x[n-2]);
+      }
+
+   /* Forward elimination */
+   for (i = 1; i < n; ++i)
+     {
+     t    = d[i-1] / b[i-1];
+     b[i] = b[i] - t * d[i-1];
+     c[i] = c[i] - t * c[i-1];
+     }
+
+   /* Back substitution */
+   c[nm1] = c[nm1] / b[nm1];
+   for (ib = 0; ib < nm1; ++ib)
+      {
+      i    = n - ib - 2;
+      c[i] = (c[i] - d[i] * c[i+1]) / b[i];
+      }
+
+   /* c[i] is now the sigma[i] of the text */
+
+   /* Compute the polynomial coefficients */
+   b[nm1] = (y[nm1] - y[n-2]) / d[n-2] + d[n-2] * (c[n-2] + 2.0 * c[nm1]);
+   for (i = 0; i < nm1; ++i)
+      {
+      b[i] = (y[i+1] - y[i]) / d[i] - d[i] * (c[i+1] + 2.0 * c[i]);
+      d[i] = (c[i+1] - c[i]) / d[i];
+      c[i] = 3.0 * c[i];
+      }
+   c[nm1] = 3.0 * c[nm1];
+   d[nm1] = d[n-2];
+
+   }  /* at least quadratic */
+
+else  /* if n >= 3 */
+   {  /* linear segment only  */
+   b[0] = (y[1] - y[0]) / (x[1] - x[0]);
+   c[0] = 0.0;
+   d[0] = 0.0;
+   b[1] = b[0];
+   c[1] = 0.0;
+   d[1] = 0.0;
+   }
+}  /* end of spline() */
+
+
+/*-------------------------------------------------------------------*/
+/*-----------------------------------------------------------------*/
+/*-----------------------------------------------------------------*/
+double deriv (int n, double u,
+              double x[],
+              double b[], double c[], double d[],
+              int *last)
+/*-----------------------------------------------------------------*/
+/* Purpose ...
+   -------
+   Evaluate the derivative of the cubic spline function
+
+   S(x) = B[i] + 2.0 * C[i] * w + 3.0 * D[i] * w**2
+   where w = u - X[i]
+   and   X[i] <= u <= X[i+1]
+   Note that Horner's rule is used.
+   If U < X[0] then i = 0 is used.
+   If U > X[n-1] then i = n-1 is used.
+
+   Input :
+   -------
+   n       : The number of data points or knots (n >= 2)
+   u       : the abscissa at which the derivative is to be evaluated
+   last    : the segment that was last used
+   x       : the abscissas of the knots in strictly increasing order
+   b, c, d : arrays of spline coefficients computed by spline()
+
+   Output :
+   --------
+   deriv : the value of the derivative of the spline
+           function at u
+   last  : the segment in which u lies
+
+   Notes ...
+   -----
+   (1) If u is not in the same interval as the previous call then a
+       binary search is performed to determine the proper interval.
+
+*/
+/*-------------------------------------------------------------------*/
+{  /* begin function deriv() */
+
+int    i, j, k;
+double w;
+
+i = *last;
+if (i >= n-1) i = 0;
+if (i < 0) i = 0;
+
+if ((x[i] > u) || (x[i+1] < u))
+  {  /* ---- perform a binary search ---- */
+  i = 0;
+  j = n;
+  do
+    {
+    k = (i + j) / 2;          /* split the domain to search */
+    if (u < x[k])  j = k;     /* move the upper bound */
+    if (u >= x[k]) i = k;     /* move the lower bound */
+    }                         /* there are no more segments to search */
+  while (j > i+1);
+  }
+*last = i;
+
+/* ---- Evaluate the derivative ---- */
+w = u - x[i];
+w = b[i] + w * (2.0 * c[i] + w * 3.0 * d[i]);
+return (w);
+
+} /* end of deriv() */
+/*-------------------------------------------------------------------*/
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/interpcseSlopeSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/interpcseSlopeSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..d3754d5d97a980213e2b55b752a5aebde5c5d15a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/interpcseSlopeSB.m
@@ -0,0 +1,40 @@
+% interpcseSlopeSB: Cubic spline interpolation with endpoints, returning
+% the derivative at the considered point.
+% This is a MEX function, so this .m file only contains the documentation.
+%
+% USAGE:
+% ======
+% yy = interpcseSlopeSB(x,y,xx)
+% yy = interpcseSlopeSB(x,y,xx,e1,e2)
+% 
+% x:     x-values 
+% y:     y-values
+% xx:    x-values at which to evaluate the derivative of the spline function (allow multiple)
+% e1,e2: endpoint derivatives (if specified, both need to be given)
+%
+% DEFAULT VALUES:
+% ===============
+% e1, e2:   =0 (no endpoint slopes defined)
+%
+% Output Arguments:
+% =================
+% yy:    derivative of spline at interpolation point
+
+% Information:
+% ============
+% Copyright (C) 2009 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/interpcsexSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/interpcsexSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..033d8ee278caa9e22a0d64a4324e92001b1ff4d5
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/interpcsexSB.m
@@ -0,0 +1,57 @@
+function [yy] = interpcsexSB(x,y,xx,varargin)
+% interpcsexSB: Cubic spline interpolation with endpoints
+% This is an interface function only to inerpcseSB. Only in the C-code
+% simulation of models there is a difference. interpcseSB does only
+% evaluate the spline coefficients once in the first call. Subsequent calls
+% only evaluate the spline function. This leads to a considerable speed-up.
+% On the other hand, interpcsexSB in the C-code simulation does evaluate
+% the spline coefficients each time it is called. => time dependent splines
+% can be implemented. However, for MATLAB simulation there is no
+% difference.
+%
+% USAGE:
+% ======
+% yy = interpcsexSB(x,y,xx)
+% yy = interpcsexSB(x,y,xx,e1,e2)
+% 
+% x:     x-values 
+% y:     y-values
+% xx:    x-values at which to evaluate the spline function (allow multiple)
+% e1,e2: endpoint derivatives (if specified, both need to be given)
+% yy:    interpolated value
+%
+% DEFAULT VALUES:
+% ===============
+% e1, e2:   =0 (no endpoint slopes defined)
+%
+% Output Arguments:
+% =================
+% yy:    scalar or vector of interpolated values.
+
+% Information:
+% ============
+% Copyright (C) 2009 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+if nargin < 3 || nargin > 5,
+    error('interpcsexSB: incorrect number of input arguments.');
+elseif nargin == 3,
+    yy = interpcseSB(x,y,xx);
+elseif nargin == 5,
+    yy = interpcseSB(x,y,xx,varargin{1},varargin{2});
+end    
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/interpcsexSlopeSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/interpcsexSlopeSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..5b663ea0b7268a37716cc6fecf7884dde9dc9657
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/interpcsexSlopeSB.m
@@ -0,0 +1,56 @@
+function [yy] = interpcsexSlopeSB(x,y,xx,varargin)
+% interpcsexSlopeSB: Cubic spline interpolation with endpoints (DERIVATIVE)
+% This is an interface function only to inerpcseSlopeSB. Only in the C-code
+% simulation of models there is a difference. inerpcseSlopeSB does only
+% evaluate the spline coefficients once in the first call. Subsequent calls
+% only evaluate the spline function. This leads to a considerable speed-up.
+% On the other hand, interpcsexSlopeSB in the C-code simulation does evaluate
+% the spline coefficients each time it is called. => time dependent splines
+% can be implemented. However, for MATLAB simulation there is no
+% difference.
+%
+% USAGE:
+% ======
+% yy = interpcsexSlopeSB(x,y,xx)
+% yy = interpcsexSlopeSB(x,y,xx,e1,e2)
+% 
+% x:     x-values 
+% y:     y-values
+% xx:    x-values at which to evaluate the derivative of the spline function (allow multiple)
+% e1,e2: endpoint derivatives (if specified, both need to be given)
+%
+% DEFAULT VALUES:
+% ===============
+% e1, e2:   =0 (no endpoint slopes defined)
+%
+% Output Arguments:
+% =================
+% yy:    spline derivative at the interpolated point (xx)
+
+% Information:
+% ============
+% Copyright (C) 2009 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+if nargin < 3 || nargin > 5,
+    error('interpcsexSlopeSB: incorrect number of input arguments.');
+elseif nargin == 3,
+    yy = interpcseSlopeSB(x,y,xx);
+elseif nargin == 5,
+    yy = interpcseSlopeSB(x,y,xx,varargin{1},varargin{2});
+end    
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/maxSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/maxSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..0c147de153301f04072457e8d8c477ca9243011a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/maxSB.m
@@ -0,0 +1,39 @@
+function [result] = maxSB(varargin)
+% maxSB: This function is used instead of the MATLAB "max" function, 
+% allowing more than two scalar input arguments, each of type "double".
+% 
+% USAGE:
+% ======
+% [result] = maxSB(arg1,arg2,...,argn)   
+%
+% arg1...argn: scalar input arguments of type double.
+%
+% Output Arguments:
+% =================
+% result: max(arg1,arg2,arg3, ....)
+
+% Information:
+% ============
+% Copyright (C) 2009  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DO IT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+result = max([varargin{:}]);
+return
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/minSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/minSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..543d7ba56d5b8a1882c9ab8b2aa12e6c818768e6
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/minSB.m
@@ -0,0 +1,39 @@
+function [result] = minSB(varargin)
+% minSB: This function is used instead of the MATLAB "min" function, 
+% allowing more than two scalar input arguments, each of type "double".
+% 
+% USAGE:
+% ======
+% [result] = minSB(arg1,arg2,...,argn)   
+%
+% arg1...argn: scalar input arguments of type double.
+%
+% Output Arguments:
+% =================
+% result: min(arg1,arg2,arg3, ....)
+
+% Information:
+% ============
+% Copyright (C) 2009  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DO IT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+result = min([varargin{:}]);
+return
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/multiplySB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/multiplySB.m
new file mode 100644
index 0000000000000000000000000000000000000000..238eb8127096321544f8d6178b6970e4838128c4
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/multiplySB.m
@@ -0,0 +1,32 @@
+function [result] = multiplySB(varargin)
+% multiplySB: Implementing the multiply MathML function
+% 
+% USAGE:
+% ======
+% [result] = multiplySB(arg1,arg2,...,argn)   
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+result = 1;
+for k = 1:nargin,
+    result = result * varargin{k};
+end
+return
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/orSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/orSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..1594e0e2f82198539d2f11f066071cbd750c4519
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/orSB.m
@@ -0,0 +1,52 @@
+function [result] = orSB(varargin)
+% orSB: This function is used instead of the MATLAB "or" function, 
+% allowing more than two input arguments, each of type "logical". Its use 
+% is mainly thought for evaluation of decision arguments in SBML piecewise 
+% statements.
+% 
+% USAGE:
+% ======
+% [result] = orSB(arg1,arg2,...,argn)   
+%
+% arg1...argn: input arguments of type boolean.
+%
+% Output Arguments:
+% =================
+% result: arg1 || arg2 || ... || argn
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK TYPE OF INPUT ARGUMENTS AND DO IT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+result = false;
+for k = 1:nargin,
+    if ~strcmp('logical', class(varargin{k})),
+        error('At least one input argument to the "SBor" function is not of type "logical".');
+    end
+    result = result || varargin{k};
+end
+return
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/piecewiseSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/piecewiseSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..a92d4fd163ab93aaca93ddc4a0d674743b74f1b5
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/piecewiseSB.m
@@ -0,0 +1,64 @@
+function [result] = piecewiseSB(varargin)
+% piecewiseSB: This function implements support for the SBML / MATHML
+% piecewise operator.
+% 
+% USAGE:
+% ======
+% [result] = piecewiseSB(resultiftrue1,decision1,resultiftrue2,decision2,...,resultiftruen,decisionn)   
+% [result] = piecewiseSB(resultiftrue1,decision1,resultiftrue2,decision2,...,resultiftruen,decisionn,defaultresult)    
+%
+% decision1,...,decisionn: logical argument, e.g. returned from a comparison
+% result1,...,resultn: returnvalue in case the corresponding decision is
+%   evaluated to be true
+% defaultresult: if none of the decisions are true this defaultresult is returned.
+%
+% Output Arguments:
+% =================
+% result: the result corresponding to the decision that is true. if no
+%   decision is true and no defaultresult i given an error will occurr.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE THE OUTPUT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+result = [];
+% check if odd or even number of input arguments
+oddnumber = mod(nargin,2);
+for k = 1:2:nargin-oddnumber,
+    if varargin{k+1},
+        result = varargin{k};
+        break;
+    end
+end
+if isempty(result),
+    if oddnumber,
+        result = varargin{nargin};
+    else
+        error('A piecewise statement is wrongly defined - missing (but needed) default value.');
+    end
+end
+return
+   
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/piecewiseSmoothSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/piecewiseSmoothSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..dc6814234c45d91bec1ec610091770d7e2aba01c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/piecewiseSmoothSB.m
@@ -0,0 +1,49 @@
+function y = piecewiseSmoothSB(t,y0,y1,alpha)
+% piecewiseSmoothSB: This function implements a smoothing function between
+% two values y0 and y1. alpha is the steepness factor. 
+% For alpha>>1, 
+%               y=y0 for t<0 and 
+%               y=y1 for t>0. 
+% For low values of alpha, the function provide a
+% smooth interpolation between y0 and y1 in function of t
+% 
+% 
+% USAGE:
+% ======
+% y = piecewiseSmoothSB(t,y0,y1,alpha)
+%
+% t: regression variable (i.e. y=y(t))
+% y0: output value for y when t-> -Inf
+% y1: output value for y when t-> +Inf
+% alpha: steepness factor
+%
+% Output Arguments:
+% =================
+% result: the result corresponding to the decision that is true. if no
+%   decision is true and no defaultresult i given an error will occurr.
+
+% Information:
+% ============
+% Copyright (C) 2011 Novartis Pharma AG
+% Main author: Antoine Soubret
+% 
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+y=(y0+y1.*exp(alpha.*t))./(1+exp(alpha.*t));
+
+
+   
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/piecewiseT0SB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/piecewiseT0SB.m
new file mode 100644
index 0000000000000000000000000000000000000000..614877e270655bde71e95dc05276f542747aab81
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/piecewiseT0SB.m
@@ -0,0 +1,68 @@
+function [result] = piecewiseT0SB(varargin)
+% piecewiseT0SB: This function is identical to the piecewiseSB function.
+% The only difference is that during model export to a simulation model the
+% trigger conditions for the piecewise expressions are not added to the
+% simulation model as events. Thus the main reason for having this function
+% here is to allow for a switching based on the initial conditions, rather
+% than for a switching during simulation.
+% 
+% USAGE:
+% ======
+% [result] = piecewiseT0SB(resultiftrue1,decision1,resultiftrue2,decision2,...,resultiftruen,decisionn)   
+% [result] = piecewiseT0SB(resultiftrue1,decision1,resultiftrue2,decision2,...,resultiftruen,decisionn,defaultresult)    
+%
+% decision1,...,decisionn: logical argument, e.g. returned from a comparison
+% result1,...,resultn: returnvalue in case the corresponding decision is
+%   evaluated to be true
+% defaultresult: if none of the decisions are true this defaultresult is returned.
+%
+% Output Arguments:
+% =================
+% result: the result corresponding to the decision that is true. if no
+%   decision is true and no defaultresult i given an error will occurr.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE THE OUTPUT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+result = [];
+% check if odd or even number of input arguments
+oddnumber = mod(nargin,2);
+for k = 1:2:nargin-oddnumber,
+    if varargin{k+1},
+        result = varargin{k};
+        break;
+    end
+end
+if isempty(result),
+    if oddnumber,
+        result = varargin{nargin};
+    else
+        error('A piecewise statement is wrongly defined - missing (but needed) default value.');
+    end
+end
+return
+   
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/xorSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/xorSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..62821343b9d25e0ce4e61d52d2748ebb0bd8de3b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/sbml/xorSB.m
@@ -0,0 +1,55 @@
+function [result] = xorSB(varargin)
+% xorSB: This function is used instead of the MATLAB "or" function, 
+% allowing more than two input arguments, each of type "logical". Its use 
+% is mainly thought for evaluation of decision arguments in SBML piecewise 
+% statements.
+% 
+% USAGE:
+% ======
+% [result] = xorSB(arg1,arg2,...,argn)   
+%
+% arg1...argn: input arguments of type boolean.
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK TYPE OF INPUT ARGUMENTS AND DO IT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+result = false;
+foundFalse = 0;
+foundTrue = 0;
+for k = 1:nargin,
+    if ~strcmp('logical', class(varargin{k})),
+        error('At least one input argument to the "SBor" function is not of type "logical".');
+    end
+    result = xor(result, varargin{k});
+%     if varargin{k},
+%         foundTrue = 1;
+%     else
+%         foundFalse = 1;
+%     end
+end
+% if foundTrue == 1 && foundFalse == 1,
+%     result = true;
+% else
+%     result = false;
+% end 
+return
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/smoothing/binnedmeanSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/smoothing/binnedmeanSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..c810c668b875ab3d5c1bd605028b9adc3053251c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/smoothing/binnedmeanSB.m
@@ -0,0 +1,36 @@
+function [xbin,ybinmean] = binnedmeanSB(x,y,numbins,FLAGlogX)
+
+if nargin <= 2,
+    numbins = 15;
+    FLAGlogX = 0;
+elseif nargin<=3,
+    FLAGlogX = 0;
+end    
+
+if length(numbins)==1,
+    if FLAGlogX,
+        bins = logspace(log10(min(x)), log10(max(x)), numbins);
+    else
+        bins = linspace(min(x), max(x), numbins);
+    end
+else
+    bins = numbins;
+    numbins = length(bins);
+end
+
+[n,bin] = histc(x, bins); %#ok<ASGLU>
+mu = NaN*zeros(size(bins));
+for k = [1:numbins], %#ok<NBRAK>
+  ind = find(bin==k);
+  if (~isempty(ind))
+    mu(k) = mean(y(ind));
+  end
+end
+
+% Remove NaNs
+Z = [bins(:) mu(:)];
+Z(isnan(Z(:,2)),:) = [];
+
+% Assign outputs
+xbin = Z(:,1);
+ybinmean = Z(:,2);
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/smoothing/binnedmedianSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/smoothing/binnedmedianSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..85a5bef137dfed5f567c9eccca7a4b3ac1adbb74
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/smoothing/binnedmedianSB.m
@@ -0,0 +1,36 @@
+function [xbin,ybinmedian] = binnedmedianSB(x,y,numbins,FLAGlogX)
+
+if nargin <= 2,
+    numbins = 15;
+    FLAGlogX = 0;
+elseif nargin<=3,
+    FLAGlogX = 0;
+end    
+
+if length(numbins)==1,
+    if FLAGlogX,
+        bins = logspace(log10(min(x)), log10(max(x)), numbins);
+    else
+        bins = linspace(min(x), max(x), numbins);
+    end
+else
+    bins = numbins;
+    numbins = length(bins);
+end
+
+[n,bin] = histc(x, bins); %#ok<ASGLU>
+mu = NaN*zeros(size(bins));
+for k = [1:numbins], %#ok<NBRAK>
+  ind = find(bin==k);
+  if (~isempty(ind))
+    mu(k) = median(y(ind));
+  end
+end
+
+% Remove NaNs
+Z = [bins(:) mu(:)];
+Z(isnan(Z(:,2)),:) = [];
+
+% Assign outputs
+xbin = Z(:,1);
+ybinmedian = Z(:,2);
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/smoothing/binnedquantilesSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/smoothing/binnedquantilesSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..f83748b00ce04740c32e6fb69b63c3d91b1b9bf4
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/smoothing/binnedquantilesSB.m
@@ -0,0 +1,55 @@
+function [xbin,ybinquantile] = binnedquantilesSB(x,y,quantile_value,binningInfo,FLAGlogX)
+
+if nargin <= 3,
+    binningInfo = 15;  % number bins
+    FLAGlogX = 0;
+elseif nargin<=4,
+    FLAGlogX = 0;
+end    
+
+if length(binningInfo) == 1,
+    % Bin equidistantly
+    numbins = binningInfo;
+    if FLAGlogX,
+        bins = logspace(log10(min(x)), log10(max(x)), numbins);
+    else
+        bins = linspace(min(x), max(x), numbins);
+    end
+    
+    try
+        [n,bin] = histc(x, bins); %#ok<ASGLU>
+    catch
+        'error'
+    end
+    
+    mu = NaN*zeros(size(bins));
+    for k = [1:numbins], %#ok<NBRAK>
+        ind = find(bin==k);
+        if (~isempty(ind))
+            mu(k) = quantile(y(ind),quantile_value);
+        end
+    end
+    
+    % Remove NaNs
+    Z = [bins(:) mu(:)];
+    Z(isnan(Z(:,2)),:) = [];
+    
+    % Assign outputs
+    xbin = Z(:,1);
+    ybinquantile = Z(:,2);
+else
+    % bin my mean binning value and look around range
+    bins_mean = binningInfo{1};
+    bins_lookaround = binningInfo{2};
+    
+    ybinquantile = [];
+    for k=1:length(bins_mean),
+        ix = find(x>=bins_mean(k)-bins_lookaround(k) & x<bins_mean(k)+bins_lookaround(k));
+        ybinquantile(k) = quantile(y(ix),quantile_value);
+    end
+    xbin = bins_mean;
+    ix = find(isnan(ybinquantile));
+    xbin(ix) = [];
+    ybinquantile(ix) = [];
+end
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/smoothing/movingSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/smoothing/movingSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..db7492b5ade0c3ff8674791cfd85b8acba3bbd1f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/smoothing/movingSB.m
@@ -0,0 +1,83 @@
+function [y]=movingSB(x,range,fun)
+%MOVING will compute moving averages of order n (best taken as odd)
+%
+%Usage: y=moving(x,n[,fun])
+%where x        is the input vector (or matrix) to be smoothed. 
+%      range 	percentage of number of points in x to be used to average over
+%               m in the original code is adjusted to be odd
+%      y        is output vector of same length as x
+%      fun  (optional) is a custom function rather than moving averages
+%
+% Note:if x is a matrix then the smoothing will be done 'vertically'.
+% 
+%
+% Example:
+%
+% x=randn(300,1);
+% plot(x,'g.'); 
+% hold on;
+% plot(movingSB(x,10),'k'); 
+% plot(movingSB(x,30,'median'),'c');
+% plot(movingSB(x,7,@(x)max(x)),'b'); 
+% legend('x','10% range moving mean','30% range moving median','7% range moving max','location','best')
+%
+% optimized Aslak Grinsted jan2004
+% enhanced Aslak Grinsted Apr2007
+%
+% Copyright (c) 2011, Aslak Grinsted
+% All rights reserved.
+%
+% Adapted for SBTOOLBOX2 by Henning Schmidt
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Adaptations by Henning Schmidt
+% Determine m based on range (in percent)
+m = length(x)*range/100;
+% make m odd, since it seems to be better
+m = 2*round(m/2)+1;
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+
+if m==1
+    y=x;
+    return
+end
+if size(x,1)==1
+    x=x';
+end
+
+if nargin<3
+    fun=[];
+elseif ischar(fun)
+    fun=eval(['@(x)' fun '(x)']);
+end
+
+if isempty(fun)
+
+    f=zeros(m,1)+1/m;
+    n=size(x,1);
+    isodd=bitand(m,1);
+    m2=floor(m/2);
+
+
+    if (size(x,2)==1)
+        y=filter(f,1,x);
+        y=y([zeros(1,m2-1+isodd)+m,m:n,zeros(1,m2)+n]);
+    else
+        y=filter2(f,x);
+        y(1:(m2-~isodd),:)=y(m2+isodd+zeros(m2-~isodd,1),:);
+        y((n-m2+1):end,:)=y(n-m2+zeros(m2,1),:);
+    end
+
+else
+    y=zeros(size(x));
+    sx=size(x,2);
+    x=[nan(floor(m*.5),sx);x;nan(floor(m*.5),sx)];
+    m1=m-1;
+    for ii=1:size(y,1);
+        y(ii,:)=fun(x(ii+(0:m1),:));
+    end
+    
+end
+
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/stringhandling/explodePCSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/stringhandling/explodePCSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..c5ffdeeab9fa5952a47b2ebe62e93715945c3c4f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/stringhandling/explodePCSB.m
@@ -0,0 +1,106 @@
+function [elements] = explodePCSB(text,varargin)
+% explodePCSB: This function does not(!!!) lead to an explosion of your
+% Personal Computer. It is an auxiliary function allowing to decompose a
+% string expression into its comma separated elements. Commas within
+% parentheses expressions are not considered. This is a useful function to
+% obtain the arguments of a function call, where some arguments might have
+% expressions involving commas but have parentheses around them.
+% Alternatively, a separator character, other then a comma, can be
+% specified by the user.
+%
+% USAGE:
+% ======
+% [elements] = explodePCSB(text)
+% [elements] = explodePCSB(text,separatorCharacter)
+% [elements] = explodePCSB(text,separatorCharacter,groupCharacterStart,groupCharacterEnd)
+%
+% text: text to decompose into its comma separated elements
+% separatorCharacter: one character that should be used for the explosion
+% of the string.
+%
+% DEFAULT VALUES:
+% ===============
+% separatorCharacter: ',' (comma)
+% groupCharacterStart: '(' can also be a cell-array with several
+%                      parenthesis types
+% groupCharacterEnd: ')'  can also be a cell-array with several
+%                      parenthesis types
+%
+% Output Arguments:
+% =================
+% elements: cell-array containing string elements, previously separated by
+% the separator character.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+separatorCharacter = ',';
+groupCharacterStart = {'('};
+groupCharacterEnd = {')'};
+if nargin == 1,
+elseif nargin == 2,
+    separatorCharacter = varargin{1};
+elseif nargin == 4,
+    separatorCharacter = varargin{1};
+    groupCharacterStart = varargin{2};
+    groupCharacterEnd = varargin{3};
+else
+    error('Incorrect number of input arguments.');
+end
+
+if ischar(groupCharacterStart),
+    groupCharacterStart = {groupCharacterStart};
+end
+if ischar(groupCharacterEnd),
+    groupCharacterEnd = {groupCharacterEnd};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DO THE EXPLOSION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+elements = {};
+openParenthesis = 0;
+lastIndex = 1;
+elementIndex = 1;
+doubletext = double(text);
+doublegroupCharacterStart = double(([groupCharacterStart{:}]));
+doublegroupCharacterEnd = double(([groupCharacterEnd{:}]));
+doubleseparatorCharacter = double(separatorCharacter);
+for k2 = 1:length(text),
+    if sum(doubletext(k2) == doublegroupCharacterStart),
+        openParenthesis = openParenthesis + 1;
+    elseif sum(doubletext(k2) == doublegroupCharacterEnd),
+        openParenthesis = openParenthesis - 1;
+    elseif (doubletext(k2) == doubleseparatorCharacter) && (openParenthesis == 0),
+        elements{elementIndex} = strtrim(text(lastIndex:k2-1));
+        elementIndex = elementIndex + 1;
+        lastIndex = k2+1;
+    end
+end
+elements{elementIndex} = strtrim(text(lastIndex:end));
+return
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/stringhandling/extractPSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/stringhandling/extractPSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..52e4ad166676451f7cecda16a050bc1d4d524376
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/stringhandling/extractPSB.m
@@ -0,0 +1,48 @@
+function [output] = extractPSB(text)
+% extractPSB: This function looks for the top level parentheses in the
+% given text string and returns the substring that is located between these
+% parentheses.
+%
+% USAGE:
+% ======
+% [output] = extractPSB(text)
+%
+% text: text to look for parentheses
+%
+% Output Arguments:
+% =================
+% output: string between the toplevel parantheses. ('' if no parentheses
+% present.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+output = '';
+openParentheses = strfind(text,'(');
+closeParentheses = strfind(text,')');
+if length(openParentheses) == length(closeParentheses) && ~isempty(openParentheses),
+    output = text(min(openParentheses)+1:max(closeParentheses)-1);
+end
+return
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/tempfilehandling/tempdirSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/tempfilehandling/tempdirSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..af667d833832f29028e763901a1f6662e6ce3d62
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/tempfilehandling/tempdirSB.m
@@ -0,0 +1,38 @@
+function [tmpdir] = tempdirSB()
+% tempdirSB:    returns the path to the desired temp folder to be used 
+% by the SBTOOLBOX2 and SBPD.
+
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+% just use the systems default temporary folder!
+tmpdir = tempdir;
+
+% if ispc,
+%     % on windows systems the standard C:/temp folder is used
+%     tmpdir = 'c:\temp';
+% else
+%     % on unix systems a folder in the users home folder is created and used
+%     % as temp folder
+%     if ~isdir('~/temp'),
+%         mkdir('~/temp');
+%     end
+%     tmpdir = ['~/temp/SBTOOLBOX2'];
+%     if ~isdir(tmpdir),
+%         mkdir(tmpdir);
+%     end
+% end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/tempfilehandling/tempnameSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/tempfilehandling/tempnameSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..bb860fc8082bbc02698e4a4b8d7aba6b3a957a31
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/auxiliary/tempfilehandling/tempnameSB.m
@@ -0,0 +1,23 @@
+function [tmpname] = tempnameSB( input_args )
+% tempnameSB does the same as tempname in MATLAB but uses the SBT2s own
+% TEMP folder.
+
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+[dummy, filename] = fileparts(tempname);
+tmpname = [tempdirSB,filename];
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBexperiment/SBexperiment.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBexperiment/SBexperiment.m
new file mode 100644
index 0000000000000000000000000000000000000000..76852d34aedd8d950e3cc1294935fa866631992b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBexperiment/SBexperiment.m
@@ -0,0 +1,168 @@
+function [exp] = SBexperiment(varargin)
+% SBexperiment: creates an experiment object defining experiment settings 
+%
+% USAGE:
+% ======
+% [exp] = SBexperiment()                creates an empty SBexperiment object
+% [exp] = SBexperiment(SBstructure)     creates an SBexperiment object from a MATLAB
+%                                       structure in the internal experiment format
+% [exp] = SBexperiment(expin)           construction from a given SBexperiment object (expin)
+% [exp] = SBexperiment('file.exp')      converting a experiment text description 
+%                                       to an SBexperiment object.
+% [exp] = SBexperiment('file.exp',path2paramset)  converting a experiment text description 
+%                                       to an SBexperiment object. When
+%                                       "activeSet" and/or "parameterSet"
+%                                       definitions are used then the path
+%                                       to the root folder of these
+%                                       definitions needs to be provided.
+%                                       Otherwise: ERROR.
+%
+% Output Arguments:
+% =================
+% exp: SBexperiment object 
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+% 6/1/2010  Henning Schmidt, henning.schmidt@novartis.com
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+flag = 0;
+path2paramset = '';
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK THE TYPE OF THE INPUT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin==0,
+    inputType = 'empty';
+elseif nargin == 1 || nargin == 2,
+    if strcmp('SBexperiment',class(varargin{1})),
+        inputType = 'SBexperiment';
+        expInput = varargin{1};
+    elseif isstruct(varargin{1}),
+        inputType = 'SBstructure';
+        SBstructure = varargin{1};
+    elseif ischar(varargin{1}),
+        % check if '.txt' given as extension. If yes, then import text
+        % description
+        filename = varargin{1};
+        if ~isempty(strfind(filename,'.exp')),
+            inputType = 'TextExpFile';
+            if nargin == 2,
+                path2paramset = varargin{2};
+            end
+        elseif nargin == 2,
+            if strcmp('ExperimentAsTextString', varargin{2}),
+                inputType = varargin{2};
+            end
+        else
+            error('Input argument of unknown type');
+        end
+    else 
+        error('Input argument of unknown type');
+    end
+else
+    error('Wrong number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONSTRUCT THE SBexperiment OBJECT 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp('empty',inputType),
+    % Create empty SBstructure
+    % parameter settings substructure
+    paramicsettingsStruct = struct('name',{},'formula',{},'notes',{},'icflag',{});
+    % parameter settings substructure
+    parameterchangesStruct = struct('name',{},'formula',{},'notes',{});
+    % event assignment substructure
+    eventassignmentStruct = struct('variable',{},'formula',{});
+    % state events substructure
+    stateeventsStruct = struct('name',{},'trigger',{},'assignment',eventassignmentStruct,'notes',{});
+    % Create SBstructure
+    SBstructure = struct('name','unnamed_experiment','notes','no notes','paramicsettings',paramicsettingsStruct,'parameterchanges',parameterchangesStruct,'stateevents',stateeventsStruct);
+    % construct the model object
+    exp = class(SBstructure,'SBexperiment');
+elseif strcmp('SBexperiment',inputType),
+    % copy the model object
+    exp = expInput;
+elseif strcmp('SBstructure',inputType),
+    % check if the given structure is a SBstructure (only check the
+    % top-level fields)
+    checkFields = {'name','notes','paramicsettings','parameterchanges','stateevents'};
+    for k = 1:length(checkFields),
+        if ~isfield(SBstructure,checkFields{k}),
+            error('Given structure is not a valid internal SBexperiment structure.');
+        end
+    end
+    % construct the model object
+    exp = class(SBstructure,'SBexperiment');
+elseif strcmp('TextExpFile',inputType),
+    % check if a file with given filename exists
+    [path,filename,ext] = fileparts(filename);
+    if isempty(path2paramset),
+        filename = fullfile(path, [filename '.exp']); 
+    else
+        filename = fullfile(path2paramset,path, [filename '.exp']); 
+    end
+    if ~exist(filename),
+        errorMsg = sprintf('Experiment file, "%s", does not exist.', filename);
+        error(errorMsg);
+    end
+    % If file exists then first load it
+    expText = fileread(filename);
+	% take commented lines out of the experiment description
+	expText = regexprep(expText,'\n%[^\n]*','');
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % CHECK IF "activeSet" and/or "parameterSet" 
+    % definitions are used. If yes, then preprocess
+    % the experiment text.
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    expText = checkProcessActiveSetParameterSetSB(expText,path2paramset);
+    % then convert it to SBstructure
+    [SBstructure, errorMsg] = convertTextToExpSB(expText);
+    % Check if error occurred while importing the SBML model
+    if ~isempty(errorMsg),
+        error(errorMsg);
+    end
+    % construct the model object
+    exp = class(SBstructure,'SBexperiment');
+elseif strcmp('ExperimentAsTextString', inputType),
+    expText = varargin{1};
+	% take commented lines out of the experiment description
+	expText = regexprep(expText,'\n%[^\n]*','');
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % CHECK IF "activeSet" and/or "parameterSet" 
+    % definitions are used. If yes, then preprocess
+    % the experiment text.
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    expText = checkProcessActiveSetParameterSetSB(expText,path2paramset);
+    % then convert text experiment to SBstructure
+    [SBstructure, errorMsg] = convertTextToExpSB(expText);
+    % Check if error occurred while importing the SBML model
+    if ~isempty(errorMsg),
+        error(errorMsg);
+    end
+    % construct the model object
+    exp = class(SBstructure,'SBexperiment');
+else
+    error('Wrong input arguments.');
+end
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBexperiment/SBstruct.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBexperiment/SBstruct.m
new file mode 100644
index 0000000000000000000000000000000000000000..1fb488b8f2d069afae016d9f4fa5c502972d50fa
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBexperiment/SBstruct.m
@@ -0,0 +1,42 @@
+function [SBstructure] = SBstruct(sbm)
+% SBstruct: This function returns the internal data structure
+% of an SBexp object
+%
+% USAGE:
+% ======
+% [SBstructure] = SBstruct(experiment) 
+%
+% experiment: SBexp object 
+%
+% Output Arguments:
+% =================
+% SBstructure: internal data structure of the SBexp object
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% VERY SIMPLE FUNCTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBstructure = struct(sbm);
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBexperiment/display.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBexperiment/display.m
new file mode 100644
index 0000000000000000000000000000000000000000..3145bcac74cd5f25f8a86ed73cabec7da6e3ebf0
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBexperiment/display.m
@@ -0,0 +1,47 @@
+function [] = display(exp)
+% display: Displays information about SBexp object. This function is 
+% called by MATLAB whenever an object is the result of a statement that
+% is not terminated by a semicolon. 
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% COLLECT INFORMATION ABOUT THE EXPERIMENT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+name = exp.name;
+notes = exp.notes;
+nrparamicsettings = length(exp.paramicsettings);
+nrparameterchanges = length(exp.parameterchanges);
+nrstatechanges = length(exp.stateevents);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DISPLAY INFORMATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+text = sprintf('\tSBexperiment\n\t============\n');
+text = sprintf('%s\tName:  %s\n',text,name);
+text = sprintf('%s\tNumber Param+IC Settings: %d\n',text,nrparamicsettings);
+text = sprintf('%s\tNumber Param Changes:     %d\n',text,nrparameterchanges);
+text = sprintf('%s\tNumber State Changes:     %d\n',text,nrstatechanges);
+disp(text);
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBmeasurement/SBmeasurement.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBmeasurement/SBmeasurement.m
new file mode 100644
index 0000000000000000000000000000000000000000..bb0160634b3d1898006a60180d900f18d060b979
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBmeasurement/SBmeasurement.m
@@ -0,0 +1,145 @@
+function [output] = SBmeasurement(varargin)
+% SBmeasurement: creates an object that is intended to contain 
+% measurement data - from real experiments or insilico computations
+%
+% USAGE:
+% ======
+% [output] = SBmeasurement()                creates an empty SBmeasurement object
+% [output] = SBmeasurement(struct)          creates an SBmeasurement object from
+%                                           a MATLAB structure in the internal 
+%                                           measurement object format
+% [output] = SBmeasurement(inputobject)     construction from a given SBmeasurement object 
+% [output] = SBmeasurement('filename.xls')  converting an excel file to 
+%                                           an SBmeasurement object.
+% [output] = SBmeasurement('filename.csv')  converting an CSV (comma
+%                                           separated value) file to  
+%                                           an SBmeasurement object
+%
+% Output Arguments:
+% =================
+% output: SBmeasurement object 
+%         In the case that several sets of measurement data are defined in 
+%         an Excel file (on separate sheets) the output will be cell-array
+%         in which the elements are SBmeasurement objects.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK THE TYPE OF THE INPUT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin==0,
+    inputType = 'empty';
+elseif nargin == 1,
+    if strcmp('SBmeasurement',class(varargin{1})),
+        inputType = 'SBmeasurement';
+        measurementinput = varargin{1};
+    elseif strcmp('struct',class(varargin{1})),
+        inputType = 'measurementstructure';
+        measurementstructure = varargin{1};
+    elseif strcmp('char',class(varargin{1})),
+        % assume filenamec given as input argument
+        % check if '.xls' given as extension. If yes, then import measurement from
+        % excel file format
+        filename = varargin{1};
+        if ~isempty(strfind(lower(filename),'.xls')),
+            inputType = 'XLSmeasurementFile';
+        elseif ~isempty(strfind(lower(filename),'.csv')),
+            inputType = 'CSVmeasurementFile';
+        else
+            error('Unknown filetype!');
+        end
+    else 
+        error('Input argument of unknown type');
+    end
+else
+    error('Wrong number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONSTRUCT THE SBMODEL OBJECT 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp('empty',inputType),
+    % Create empty measurement structure
+    % data substructure
+    datastructure = struct('name',{},'notes',{},'values',{},'maxvalues',{},'minvalues',{});
+    % Create measurement structure
+    measurementsStruct = struct('name','untitled','notes','','time',[],'data',datastructure);
+    output = class(measurementsStruct,'SBmeasurement');
+elseif strcmp('SBmeasurement',inputType),
+    % copy the model object
+    output = measurementinput;
+elseif strcmp('measurementstructure',inputType),
+    % check if the given structure is a measurement structure (only check the
+    % top-level fields)
+    checkFields = {'name','notes','time','data'};
+    for k = 1:length(checkFields),
+        if ~isfield(measurementstructure,checkFields{k}),
+            errorMsg = sprintf('Given structure is not a valid internal SBmeasurement structure.');
+            error(errorMsg);
+        end
+    end
+    % construct the data object
+    output = class(measurementstructure,'SBmeasurement');
+elseif strcmp('XLSmeasurementFile',inputType),
+    % check if a file with given filename exists
+    [path,filename,ext] = fileparts(filename);
+    filename = fullfile(path, [filename '.xls']); 
+    if ~exist(filename),
+        errorMsg = sprintf('XLS measurement file, "%s", does not exist.', filename);
+        error(errorMsg);
+    end
+    % If file exists then import it
+    [outputstructures,errorMsg] = SBimportXLSmeasurement(filename);
+    % Check if error occurred while importing the XLS data
+    if length(errorMsg) ~= 0,
+        error(errorMsg);
+    end
+    % construct the data objects (one for each sheet)
+    if length(outputstructures) == 1,
+        output = class(outputstructures{1},'SBmeasurement');
+    else
+        output = {};
+        for k = 1:length(outputstructures),
+            output{k} = class(outputstructures{k},'SBmeasurement');
+        end
+    end
+elseif strcmp('CSVmeasurementFile',inputType),
+    % check if a file with given filename exists
+    [path,filename,ext] = fileparts(filename);
+    filename = fullfile(path, [filename '.csv']); 
+    if ~exist(filename),
+        errorMsg = sprintf('CSV measurement file, "%s", does not exist.', filename);
+        error(errorMsg);
+    end
+    % If file exists then import it
+    [measurementstructure,errorMsg] = SBimportCSVmeasurement(filename);
+    % Check if error occurred while importing the CSV data
+    if length(errorMsg) ~= 0,
+        error(errorMsg);
+    end
+    % construct the measurement object
+    output = class(measurementstructure,'SBmeasurement');
+end
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBmeasurement/SBstruct.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBmeasurement/SBstruct.m
new file mode 100644
index 0000000000000000000000000000000000000000..c1e9185c3c87037f0fb11a7156eaa27b7ab0cf99
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBmeasurement/SBstruct.m
@@ -0,0 +1,42 @@
+function [datastructure] = SBstruct(dataobject)
+% SBstruct: This function returns the internal data structure
+% of an SBmeasurement object
+%
+% USAGE:
+% ======
+% [datastructure] = SBstruct(sbmeasurement) 
+%
+% sbmeasurement: SBmeasurement data object 
+%
+% Output Arguments:
+% =================
+% datastructure: internal data structure of the SBmeasurement object
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% VERY SIMPLE FUNCTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+datastructure = struct(dataobject);
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBmeasurement/display.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBmeasurement/display.m
new file mode 100644
index 0000000000000000000000000000000000000000..955d00a77371753cb57f973bbcea2e43a2abe45a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBmeasurement/display.m
@@ -0,0 +1,65 @@
+function [] = display(measurement)
+% display: Displays information about SBmeasurement. This function is 
+% called by MATLAB whenever an object is the result of a statement that
+% is not terminated by a semicolon. 
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% COLLECT INFORMATION ABOUT THE DATA OBJECT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+name = measurement.name;
+notes = measurement.notes;
+numbermeasurements = length(measurement.data);
+numbertimesteps = length(measurement.time);
+errorboundFlag = 0;
+allMeasurementsDone = 1;
+for k = 1:length(measurement.data),
+    % check if errorbounds are present
+    if ~isempty(measurement.data(k).maxvalues) && max(isnan(measurement.data(k).maxvalues))~=1,
+        errorboundFlag = 1;
+    end
+    % check if NaN present in data
+    if ~isempty(find(isnan(measurement.data(k).values))),
+        allMeasurementsDone = 0;
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DISPLAY INFORMATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+text = sprintf('\tSBmeasurement\n\t=============\n');
+text = sprintf('%s\tName: %s\n',text,name);
+text = sprintf('%s\tMeasured components:\t%d\n',text,numbermeasurements);
+text = sprintf('%s\tNumber time points: \t%d\n',text,numbertimesteps);
+if errorboundFlag == 1,
+    text = sprintf('%s\tError bound information present at least for one measurement.\n',text);
+end
+if allMeasurementsDone == 1,
+    text = sprintf('%s\tMeasurements for all time points present\n',text);
+else
+    text = sprintf('%s\tMeasurements not present for all time points\n',text);
+end
+disp(text);
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBmodel/SBmodel.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBmodel/SBmodel.m
new file mode 100644
index 0000000000000000000000000000000000000000..bd60b78d47367e138f6ac583cb79ae54d24fd4cb
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBmodel/SBmodel.m
@@ -0,0 +1,297 @@
+function [model] = SBmodel(varargin)
+% SBmodel: creates a model object for a biological system
+%
+% USAGE:
+% ======
+% [model] = SBmodel()               creates an empty SBmodel 
+% [model] = SBmodel(SBstructure)    creates an SBmodel from a MATLAB
+%                                   structure in the internal model format
+% [model] = SBmodel(modelin)        construction from a given SBmodel (modelin)
+% [model] = SBmodel('file.txt')     loading a ODE *.txt file description of
+%                                   a model.
+% [model] = SBmodel('file.txtbc')   loading a *.txtbc file description of
+%                                   a model.
+% [model] = SBmodel('file.xml')     converting an SBML model file to an 
+%                                   SBmodel.
+% [model] = SBmodel('file.xml',flag) converting an SBML model file to an 
+%                                    SBmodel. 
+% flag = 0: standard behavior.
+% flag = 1: special case of SBmodel. This functionality is mainly thought
+% for the import of (in)completely defined CellDesigner SBML models. It
+% does not require that a model is fully defined in terms of parameter
+% values, and rate equations, etc. Furthermore it does a name to id
+% conversion. This is necessary, since in CellDesigner the ids of the
+% elements are chosen automatically and in the SBT the ids are used as
+% names for states, variables, etc. It is made sure that all new ids are
+% unique. Only for Level 2 SBML models. It might also be used for models
+% defined using other modelling environments where the ids have no
+% interpretation.
+% flag = 2: same as flag 1, additionally all extra SBML related information
+% in the SBmodel is taken away.
+%
+% [model] = SBmodel('textfile.txt') converting a ODE text file description of a 
+%                                   model to an SBmodel. The textfile
+%                                   description has the format used in
+%                                   SBedit. If using this kind of model
+%                                   description the extension '.txt' needs to
+%                                   be specified!
+%
+% [model] = SBmodel('textfile.txtbc') converting a text file using a 
+%                                   biochemical description of a 
+%                                   model to an SBmodel. The textfile
+%                                   description has the format used in
+%                                   SBeditBC. If using this kind of model
+%                                   description the extension '.txtbc' needs to
+%                                   be specified!
+%
+% Output Arguments:
+% =================
+% model: SBmodel object 
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+flag = 0;
+if nargin == 2,
+    flag = varargin{2};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK THE TYPE OF THE INPUT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin==0,
+    inputType = 'empty';
+elseif nargin == 1 || nargin == 2,
+    if strcmp('SBmodel',class(varargin{1})),
+        inputType = 'SBmodel';
+        sbmInput = varargin{1};
+    elseif isstruct(varargin{1}),
+        inputType = 'SBstructure';
+        SBstructure = varargin{1};
+    elseif ischar(varargin{1}),
+        % check if '.txt' or '.txtbc' given as extension. If yes, then import text
+        % model, otherwise assume an SBML model is to be imported.
+        filename = varargin{1};
+        if ~isempty(strfind(filename,'.txtbc')),
+            inputType = 'TextBCModelFile';
+        elseif ~isempty(strfind(filename,'.txt')),
+            inputType = 'TextModelFile';
+        elseif strcmp('ModelAsTextString', flag),
+            modelText = varargin{1};
+            inputType = flag;
+        elseif strcmp('ModelAsTextBCString', flag),
+            modelText = varargin{1};
+            inputType = flag;
+        else
+            inputType = 'SBMLmodelFile';
+            if nargin == 2,
+                flag = flag;
+            end
+        end        
+    else 
+        error('Input argument of unknown type');
+    end
+else
+    error('Wrong number of input arguments.');
+end
+
+
+% model.inputs.name:       input name
+% model.inputs.factors:    cell-array with input factors
+% model.inputs.terms:      cell-array with complete input string (for
+%                          simpler removing)
+% model.inputs.stateindex: vector with stateindices to which the 
+%                          input is applied
+% model.inputs.parindex:   index of the INPUT* parameter definition in
+%                          the SBmodel (used to remove it when
+%                          parameters are written to (e.g.) an MLXTRAN
+%                          file).   
+% model.outputs.name:      output name
+% model.outputs.formula:   output formula
+% model.outputs.notes:     output notes
+% model.outputs.varindex:  index of output in model variables
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONSTRUCT THE SBMODEL OBJECT 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp('empty',inputType),
+    % Create empty SBstructure
+    % inputs substructure
+    inputsStruct = struct('name',{},'factors',{},'terms',{},'stateindex',{},'parindex',{});
+    % outputs substructure
+    outputsStruct = struct('name',{},'formula',{},'notes',{},'varindex',{});
+    % functions substructure
+    functionsStruct = struct('name',{},'arguments',{},'formula',{},'notes',{});
+    % states substructure
+    statesStruct = struct('name',{},'initialCondition',{},'ODE',{},'type',{},'compartment',{},'unittype',{},'notes',{});
+    % algebraic substructure
+    algebraicStruct = struct('name',{},'formula',{},'initialCondition',{},'type',{},'compartment',{},'unittype',{},'notes',{});
+    % parameters substructure
+    parametersStruct = struct('name',{},'value',{},'type',{},'compartment',{},'unittype',{},'notes',{});
+    % variables substructure
+    variablesStruct = struct('name',{},'formula',{},'type',{},'compartment',{},'unittype',{},'notes',{});
+    % reactions substructure
+    reactionsStruct = struct('name',{},'formula',{},'notes',{},'reversible',{},'fast',{});
+    % event assignment substructure
+    eventassignmentStruct = struct('variable',{},'formula',{});
+    % event substructure
+    eventStruct = struct('name',{},'trigger',{},'assignment',eventassignmentStruct,'notes',{});
+    % Create SBstructure
+    SBstructure = struct('name','unnamed_model','notes','','functions',functionsStruct,'states',statesStruct,'algebraic',algebraicStruct,'parameters',parametersStruct,'variables',variablesStruct,'reactions',reactionsStruct,'events',eventStruct,'functionsMATLAB','','inputs',inputsStruct,'outputs',outputsStruct);
+    % construct the model object
+    model = class(SBstructure,'SBmodel');
+elseif strcmp('SBmodel',inputType),
+    % copy the model object
+    model = sbmInput;
+elseif strcmp('SBstructure',inputType),
+    % check if given structure contains inputs and outputs. If not then add these 
+    if ~isfield(SBstructure,'inputs'),
+        SBstructure.inputs  = struct('name',{},'factors',{},'terms',{},'stateindex',{},'parindex',{});
+    end
+    if ~isfield(SBstructure,'outputs'),
+        SBstructure.outputs = struct('name',{},'formula',{},'notes',{},'varindex',{});
+    end
+    % check if the given structure is a SBstructure (only check the
+    % top-level fields)
+    checkFields = {'name','notes','functions','states','algebraic','parameters','variables','reactions','events','functionsMATLAB'};
+    for k = 1:length(checkFields),
+        if ~isfield(SBstructure,checkFields{k}),
+            errorMsg = sprintf('Given structure is not a valid internal SBmodel structure.');
+            error(errorMsg);
+        end
+    end
+    % construct the model object
+    model = class(SBstructure,'SBmodel');
+elseif strcmp('SBMLmodelFile',inputType),
+    % check if a file with given filename exists
+    [path,filename,ext] = fileparts(filename);
+    filename = fullfile(path, [filename '.xml']); 
+    test = dir(filename);
+    if isempty(test),
+        errorMsg = sprintf('SBML model, "%s", does not exist in given folder.', filename);
+        error(errorMsg);
+    end
+    % If file exists then import it
+    if flag == 0,
+        [SBstructure,errorMsg] = importSBMLSB(filename);
+        if ~isempty(errorMsg), error(errorMsg);  end
+    elseif flag == 1 || flag == 2,
+        [SBstructure,errorMsg] = importSBMLCDSB(filename);
+        if ~isempty(errorMsg), warning(errorMsg);  end
+    end
+    if flag == 2,
+        for k = 1:length(SBstructure.states),
+            SBstructure.states(k).type = '';
+            SBstructure.states(k).compartment = '';
+            SBstructure.states(k).unittype = '';
+        end
+        for k = 1:length(SBstructure.variables),
+            SBstructure.variables(k).type = '';
+            SBstructure.variables(k).compartment = '';
+            SBstructure.variables(k).unittype = '';
+        end
+        for k = 1:length(SBstructure.parameters),
+            SBstructure.parameters(k).type = '';
+            SBstructure.parameters(k).compartment = '';
+            SBstructure.parameters(k).unittype = '';
+        end
+    end
+    % construct the model object
+    model = class(SBstructure,'SBmodel');
+elseif strcmp('TextModelFile',inputType),
+    % check if a file with given filename exists
+    [path,filename,ext] = fileparts(filename);
+    filename = fullfile(path, [filename '.txt']); 
+    if ~exist(filename),
+        errorMsg = sprintf('TEXT model, "%s", does not exist.', filename);
+        error(errorMsg);
+    end
+    % If file exists then first load it
+    modelText = fileread(filename);  
+    % then convert it to SBstructure
+    [SBstructure, errorMsg] = convertTextToModelSB(modelText);
+    % Check if error occurred while importing the SBML model
+    if ~isempty(errorMsg),
+        error(errorMsg);
+    end
+    % handle arrays for TEXT models
+    SBstructure = convertTEXTArrayDefSB(SBstructure);
+    % construct the model object
+    model = class(SBstructure,'SBmodel');
+elseif strcmp('TextBCModelFile',inputType),
+    % check if a file with given filename exists
+    [path,filename,ext] = fileparts(filename);
+    filename = fullfile(path, [filename '.txtbc']); 
+    if ~exist(filename),
+        errorMsg = sprintf('TEXTBC model, "%s", does not exist.', filename);
+        error(errorMsg);
+    end
+    % If file exists then first load it
+    modelText = fileread(filename);
+    % then convert it to SBstructure
+    [SBstructure, errorMsg] = convertTextBCToModelSB(modelText);
+    % Check if error occurred while importing the SBML model
+    if ~isempty(errorMsg),
+        error(errorMsg);
+    end
+    % construct the model object
+    model = class(SBstructure,'SBmodel');
+elseif strcmp('ModelAsTextString', inputType),
+    % convert model text to SBstructure
+    [SBstructure, errorMsg] = convertTextToModelSB(modelText);
+    % Check if error occurred while importing the SBML model
+    if ~isempty(errorMsg),
+        error(errorMsg);
+    end
+    % construct the model object
+    model = class(SBstructure,'SBmodel');
+elseif strcmp('ModelAsTextBCString', inputType),
+    % then convert model text to SBstructure
+    [SBstructure, errorMsg] = convertTextBCToModelSB(modelText);
+    % Check if error occurred while importing the SBML model
+    if ~isempty(errorMsg),
+        error(errorMsg);
+    end
+    % construct the model object
+    model = class(SBstructure,'SBmodel');
+else
+    error('Wrong input arguments.');
+end
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle inputs and outputs (add info about them to the structure and
+% eventually add parameters for inputs)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+model = inputoutputSBmodelParsingSB(model);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DELETE WHITESPACES IN STRINGS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Useful for taking away whitespaces in kineticLaw formulas, as
+% seen in some example models
+function [outputString] = removeWhiteSpace(inputString)
+outputString = strrep(inputString,' ','');
+% return
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBmodel/SBstruct.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBmodel/SBstruct.m
new file mode 100644
index 0000000000000000000000000000000000000000..8e3e850c21b2ede71419301ce2a3891e4bb5f6e1
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBmodel/SBstruct.m
@@ -0,0 +1,44 @@
+function [SBstructure] = SBstruct(sbm)
+% SBstruct: This function returns the internal data structure
+% of an SBmodel
+%
+% USAGE:
+% ======
+% [SBstructure] = SBstruct(SBmodel) 
+%
+% SBmodel: SBmodel 
+%
+% Output Arguments:
+% =================
+% SBstructure: internal data structure of the SBmodel
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% VERY SIMPLE FUNCTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBstructure = struct(sbm);
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBmodel/display.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBmodel/display.m
new file mode 100644
index 0000000000000000000000000000000000000000..f88ae7d0b93567601305f75cd87e739807e1520c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBmodel/display.m
@@ -0,0 +1,83 @@
+function [] = display(sbm)
+% display: Displays information about SBmodel. This function is 
+% called by MATLAB whenever an object is the result of a statement that
+% is not terminated by a semicolon. 
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% COLLECT INFORMATION ABOUT THE MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+numberStates = length(sbm.states);
+numberVariables = length(sbm.variables);
+numberParameters = length(sbm.parameters);
+numberReactions = length(sbm.reactions);
+numberFunctions = length(sbm.functions);
+numberEvents = length(sbm.events);
+functionsMATLABpresent = ~isempty(sbm.functionsMATLAB);
+delaysPresent = usedelaySB(sbm);
+numberARs = length(sbm.algebraic);
+fastReactionsPresent = usefastSB(sbm);
+nnICsPresent = ~hasonlynumericICsSB(sbm);
+nrInputs = length(sbm.inputs);
+nrOutputs = length(sbm.outputs);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DISPLAY INFORMATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+text = sprintf('\tSBmodel\n\t=======\n');
+text = sprintf('%s\tName: %s\n',text,sbm.name);
+text = sprintf('%s\tNumber States:\t\t\t%d\n',text,numberStates);
+text = sprintf('%s\tNumber Variables:\t\t%d\n',text,numberVariables);
+text = sprintf('%s\tNumber Parameters:\t\t%d\n',text,numberParameters);
+text = sprintf('%s\tNumber Reactions:\t\t%d\n',text,numberReactions);
+text = sprintf('%s\tNumber Functions:\t\t%d\n',text,numberFunctions);
+if numberEvents > 0,
+    text = sprintf('%s\tNumber Events:\t\t\t%d\n',text,numberEvents);
+end
+if numberARs > 0,
+    text = sprintf('%s\tNumber Algebraic Rules:\t%d\n',text,numberARs);
+end
+if nrInputs > 0,
+    text = sprintf('%s\tNumber Inputs:\t\t\t%d\n',text,nrInputs);
+end
+if nrOutputs > 0,
+    text = sprintf('%s\tNumber Outputs:\t\t\t%d\n',text,nrOutputs);
+end
+if functionsMATLABpresent,
+    text = sprintf('%s\tMATLAB functions present\n',text);
+end
+if delaysPresent,
+    text = sprintf('%s\tDelay function(s) present',text);
+end
+if fastReactionsPresent,
+    text = sprintf('%s\tFast reactions are present in the model:\n\t\tPlease note that this information is ONLY taken into account\n\t\tduring simulation using SBsimulate. NO other function will\n\t\tconsider fast reactions.\n',text);
+end
+if nnICsPresent,
+    text = sprintf('%s\tNon-numeric initial conditions are present in the model.\n\t\tPlease check the documentation for further information.\n',text);
+end    
+if numberARs > 0,
+    text = sprintf('%s\tAlgebraic rules present in the model.\n\t\tYou should not use ANY other function on this model than SBsimulate.\n',text);
+end
+disp(text);
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBmodel/private/importSBMLCDSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBmodel/private/importSBMLCDSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..9dc1c48cbc54df55b47256e84529d773f0d998f8
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBmodel/private/importSBMLCDSB.m
@@ -0,0 +1,12 @@
+function [SBstructure,errorMsg] = importSBMLCDSB(model)
+% importSBMLSB: Just an interface to SBimportSBMLCD, which is an ACADEMIC function
+%               The dependency check (checkDependenciesSBPOP) then will ignore the 
+%               importSBMLCDSB function.
+
+% Check if SBimportSBMLSB is available in the SBPOP installation
+if exist('SBimportSBMLCD') ~= 2,
+    error('SBML import is not available in this installation of SBPOP/SBTOOLBOX2');
+end
+
+% Run SBimportSBML
+[SBstructure,errorMsg] = SBimportSBMLCD(model);
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBmodel/private/importSBMLSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBmodel/private/importSBMLSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..0c3367872b47adb2e158bc53a855b0921e51d7b3
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBmodel/private/importSBMLSB.m
@@ -0,0 +1,7 @@
+function [SBstructure,errorMsg] = importSBMLSB(model)
+% importSBMLSB: Just an interface to SBimportSBML, which is an ACADEMIC function
+%               The dependency check (checkDependenciesSBPOP) then will ignore the 
+%               importSBMLSB function.
+
+% Run SBimportSBML
+[SBstructure,errorMsg] = SBimportSBML(model);
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBmodel/private/inputoutputSBmodelParsingSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBmodel/private/inputoutputSBmodelParsingSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..45ca8e64a269d60af30c13b9adede7f325520a5e
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classes/@SBmodel/private/inputoutputSBmodelParsingSB.m
@@ -0,0 +1,564 @@
+function [model] = inputoutputSBmodelParsingSB(model)
+% inputoutputSBmodelParsing: This function is implemented as a private
+% method for SBmodels. It is not supposed to be used by any other function
+% than SBmodel. It takes a model, read in by the SBmodel function,
+% processes it in terms of INPUT and OUTPUT handling and stores the found
+% information in the internal model structure. The involved fields and
+% handling features are described below. Error checks are done to ensure
+% the model is compatible with the items, described below. The "inputs" and
+% "outputs" fields in the model structure are not used by the SBTOOLBOX2 or
+% SBPD but only by the SBPOP package (at least at the moment: 29JAN2009).
+%
+% Handling of INPUT* and OUTPUT* definitions in SBmodels:
+%
+% INPUT*:
+%       - "*": 1,2,3,4,5, ...
+%       - input definitions are only allowed in differential equations
+%         but also input definitions in reactions are allowed. In this case
+%         the reaction name in the ODE is replaced by the reaction
+%         expression to have the input definition in the ODE.
+%       - a prefactor is allowed, e.g. +1.5*INPUT1 or (k1+k2)*INPUT2
+%         the prefactors can be arbitrarily chosen. No postfactors are
+%         allowed. Additionally the INPUT* element needs to be a
+%         multiplicative factor.
+%       - Input terms (INPUT* identifier and prefactor) are only allowed to
+%         be added (+) to the differential equation.
+%       - If INPUT* is already also present as a parameter, it will be used
+%         as defined. If the model does not contain an INPUT* parameter, it
+%         is added and set by default to "0". INPUT* is only allowed to be
+%         defined as a parameter. Not as a variable and not as a reaction.
+%       - Only parameters (and numerical values) are allowed to be used in
+%         the definition of INPUT* prefactors. But no states, variables and
+%         reactions.
+%
+% OUTPUT*:
+%       - "*": 1,2,3,4,5, ... sequential indices, starting from 1.
+%              no number is allowed to be excluded.
+%       - output definitions are only allowed to appear in the model
+%         variables section
+%       - output RHS expressions can depend on parameters, states, and
+%         previously defined model variables.
+%         OUTPUT* variables are NOT allowed to depend on INPUT* components
+%
+% SBmodel structure changes:
+% model.inputs.name:       input name
+% model.inputs.factors:    cell-array with input factors
+% model.inputs.terms:      cell-array with complete input string (for
+%                          simpler removing)
+% model.inputs.stateindex: vector with stateindices to which the 
+%                          input is applied
+% model.inputs.parindex:   index of the INPUT* parameter definition in
+%                          the SBmodel (used to remove it when
+%                          parameters are written to (e.g.) an MLXTRAN
+%                          file).   
+% model.outputs.name:      output name
+% model.outputs.formula:   output formula
+% model.outputs.notes:     output notes
+% model.outputs.varindex:  index of output in model variables
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% IMPORTANT: ALWAYS CLEAR FIRST THE inputs and outputs substructures before
+% running this function ... 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% inputs substructure
+inputsStruct = struct('name',{},'factors',{},'terms',{},'stateindex',{},'parindex',{});
+% outputs substructure
+outputsStruct = struct('name',{},'formula',{},'notes',{},'varindex',{});
+% clear the substructures
+model.inputs = inputsStruct;
+model.outputs = outputsStruct;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE POSSIBLE INPUT DEFINITIONS IN REACTIONS
+% if present then replace reaction name in ODE
+% with reaction expression
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+model = handleInputsInReactions(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK MODEL: INPUTS ONLY ON STATES?
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~inputsonlyonstates(model),
+    error(sprintf('The model contains ''INPUT'' on other elements than ODEs.\nPlease note that ''INPUT'' is a reserved word for input definitions.\nIf you do not want to use this feature, please rename your model\ncomponents to NOT include the string ''INPUT''. If you want to use\ninput definitions then please note that these are only allowed in ODEs.'));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK MODEL: OUTPUTS ONLY IN VARIABLES?
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~outputsonlyasvariables(model),
+    error(sprintf('The model contains ''OUTPUT'' in at least one parameter, state or reaction name.\nPlease note that ''OUTPUT'' is a reserved word for output definitions.\nIf you do not want to use this feature, please rename your model\ncomponents to NOT include the string ''OUTPUT''. If you want to use\noutput definitions then please note that these are only allowed as variables.'));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE MODEL INPUT INFORMATION TO THE MODEL STRUCTURE AND DO SOME INITIAL CHECKING
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[statenames,ODEs] = SBstates(model);
+% get model input names (unique)
+inputnames = {};
+inputodeindex = [];
+for k=1:length(ODEs),
+    y = regexp(ODEs{k},'(INPUT\w*)','tokens');
+    for k2=1:length(y),
+        x = y{k2};
+        inputnames{end+1} = x{1};
+        inputodeindex(end+1) = k;
+    end
+end    
+% add the inputs into to the model structure 
+for k=1:length(inputnames),
+    inputindex = strmatchSB(inputnames{k},{model.inputs.name},'exact');
+    if isempty(inputindex),
+        model.inputs(end+1).name = inputnames{k};
+        model.inputs(end).stateindex = inputodeindex(k);
+    else
+        model.inputs(inputindex).stateindex = [model.inputs(inputindex).stateindex inputodeindex(k)];
+    end
+end
+% check if same input more than once on same ODE
+for k=1:length(model.inputs),
+    if length(model.inputs(k).stateindex) ~= length(unique(model.inputs(k).stateindex)),
+        error('Input ''%s'' appears more than once in the same ODE.',model.inputs(k).name);
+    end
+end
+% determine the input factors
+for k=1:length(model.inputs),
+    stateindex = model.inputs(k).stateindex;
+    for k2=1:length(stateindex),
+        [factor, term] = getInputFactorFromODE(ODEs{stateindex(k2)},model.inputs(k).name);
+        model.inputs(k).factors{end+1} = factor;
+        model.inputs(k).terms{end+1} = term;
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK THE INPUT NAMES FOR VALIDITY (only if inputs are present)
+% AND REORDER THE INPUTS IN THE MODEL STRUCTURE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Input names need to be numerically ordered. No index is allowed to be
+% omitted inbetween. INPUT1, INPUT2, INPUT3, ... allowed but NOT:
+% INPUT1, INPUT3, INPUT4, etc. Numbering always needs to start at 1.
+% It is probably not absolutely needed but to be consistent with the output
+% handling and consistent with the requirements of the input indexing, a
+% reordering of the inputs just makes sense.
+if ~isempty(model.inputs),
+    model = checkinputnumberingOKandreorder(model);
+end
+
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% % Check state, variable, reaction appearance in input factors (if yes => error)
+% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% sn = {model.states.name};
+% vn = {model.variables.name};
+% rn = {model.reactions.name};
+% allother = {sn{:} vn{:} rn{:}};
+% allfactors = {};
+% for k=1:length(model.inputs),
+%     allfactors = {allfactors{:} model.inputs(k).factors{:}};
+% end
+% for k=1:length(allfactors),
+%     test = ['#' allfactors{k} '#'];
+%     for k2=1:length(allother),
+%         index = regexp(test,['\W' allother{k2} '\W'], 'once' );
+%         if ~isempty(index),
+%             error(sprintf('The model component ''%s'' appears in an input pre-factor ''%s''.\nPlease note that no states, variables, or reactions are allowed to\nappear in these pre-factors. Only parameters and numerical values.',allother{k2},allfactors{k}));
+%         end
+%     end
+% end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE MODEL INPUT PARAMETERS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% For each INPUT* a parameter INPUT* needs to be defined. If not present in
+% the model, then it is added to the model with a default value of 0.
+% Also add the parameter index to the model.inputs structure.
+model = handleInputParameters(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET MODEL OUTPUT INFORMATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Outputs are defined be OUTPUT1 = ..., OUTPUT2 = ...
+% The ordering is done by the number after OUTPUT.
+% 1) Get all the OUTPUT* definitions in the model variable section
+vn = {model.variables.name};
+vf = {model.variables.formula};
+vnotes = {model.variables.notes};
+outputnames = {};
+outputformulas = {};
+outputnotes = {};
+outputvarindex = [];
+for k=1:length(vn),
+    y = regexp(vn{k},'(OUTPUT\w*)','tokens');
+    if ~isempty(y),
+        outputnames{end+1} = y{1}{1};
+        outputvarindex(end+1) = k;
+        outputformulas{end+1} = vf{k};
+        outputnotes{end+1} = vnotes{k};        
+    end
+end  
+% Check if same output defined several times
+if length(unique(outputnames)) ~= length(outputnames),
+    error('Each output identifier OUTPUT* is only allowed to be present once. (* = 1,2,3,4,...)');
+end
+% Add the outputs into to the model structure 
+for k=1:length(outputnames),
+    model.outputs(end+1).name = outputnames{k};
+    model.outputs(end).formula = outputformulas{k};
+    model.outputs(end).notes = outputnotes{k};
+    model.outputs(end).varindex = outputvarindex(k);
+end
+ 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK THE OUTPUT NAMES FOR VALIDITY (only if outputs are present)
+% AND REORDER THE OUTPUTS IN THE MODEL STRUCTURE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Output names need to be numerically ordered. No index is allowed to be
+% omitted inbetween. OUTPUT1, OUTPUT2, OUTPUT3, ... allowed but NOT:
+% OUTPUT1, INPUT3, OUTPUT4, etc. Numbering always needs to start at 1.
+% Outputs in the model structure are then ordered according to their name
+% for easier use of the information in later functions.
+if ~isempty(model.outputs),
+    model = checkoutputnumberingOKandreorder(model);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK THAT THE OUTPUT FORMULAS DO NOT DEPEND ON INPUT DEFINITIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% This is important since people might try ... but it simply does not make
+% sense because INPUT definitions are more abstract constructs.
+% HERE WE DO NOT NEED TO CHECK IT, SINCE ALREADY ABOVE IT IS CHECKED THAT
+% INPUT DEFINITIONS ARE NOT PRESENT IN ALL VARIABLES!!!
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ITS DONE ... RETURN
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+return
+        
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE POSSIBLE INPUT DEFINITIONS IN REACTIONS
+% if present then delete reaction name from ODE and add the input as new
+% term to the ODE. If species in amount then just add as it is, if in
+% concentration, then divide the input term with the compartment name (if
+% available). If compartment name is not available then error!
+% Oh, and take into account potential stoichiometric coefficients of the
+% reaction!
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [model] = handleInputsInReactions(model)
+[rn,rf] = SBreactions(model);
+removeReac = [];
+for k=1:length(rf),
+    if ~isempty(strfind(rf{k},'INPUT')),
+        % INPUT definition found in reaction
+        % Now remove the reaction name in ODEs with reaction formula. The
+        % reaction will then be appended to the ODE, taking into account
+        % the correct volume in the case of concentration ...
+        % We do not do any further checks regarding stoichiometric
+        % coefficients for this reaction etc. ... do it yourself:
+        disp('The following is not an error message, just a reminder:')
+        disp('  Please make sure that the reaction that contains the INPUT* definition');
+        disp('  does NOT have any stoichiometric factors associated with it!');
+        disp('  IT IS NOT ALLOWED TO INCLUDE THE REACTION IN THE ODE IN PARENTHESES!');
+        rfk = rf{k};
+        for k2=1:length(model.states),
+            ODE = model.states(k2).ODE;
+            % check if reaction name present in ODE
+            if ~isempty(strfind(ODE,rn{k})),
+                % reaction name is present => remove reaction in ODE and 
+                % append input reaction formula ...
+                ODE = regexprep(ODE,['\<' rn{k} '\>'],'0');
+                % remove "+0" and "-0" and "0"
+                ODE = regexprep(ODE,'+','#');
+                ODE = regexprep(ODE,['\<#0\>'],'');
+                ODE = regexprep(ODE,['\<-0\>'],'');
+                ODE = regexprep(ODE,['\<0\>'],'');
+                ODE = regexprep(ODE,'#','+');
+                % add input reaction formula to ODE:
+                comp = model.states(k2).compartment;
+                unittype = model.states(k2).unittype;
+                if strcmp(unittype,'concentration'),
+                    if isempty(comp),
+                        error('No compartment defined for species ''%s''.',model.states(k2).name);
+                    end
+                    ODE = [ODE sprintf('+1/%s*%s',comp,rfk)];
+                else
+                    % assume amount units and just add the reaction to the ODE
+                    ODE = [ODE sprintf('+%s',rfk)];
+                end
+                % check if ++ or +- or -+ present and exchange
+                ODE = regexprep(ODE,'++','+');
+                ODE = regexprep(ODE,'+-','-');
+                ODE = regexprep(ODE,'-+','-');
+                model.states(k2).ODE = ODE;
+            end
+        end
+        % Remove reaction from the model
+        removeReac = [removeReac k];
+    end
+end
+model.reactions(removeReac) = [];
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXTRACT INPUT TERMS and check for validity
+% Only prefixes/prefactors to inputs allowed - otherwise error
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [factor,term] = getInputFactorFromODE(ODE,name)
+% find the start-index for the input name
+si = strfind(ODE,name);
+% get ODE text before input
+ODEpre = strtrim(ODE(1:si-1));
+ODEpost = strtrim(ODE(si+length(name):end));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DO SOME CHECKS FIRST: 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% 1) the INPUT* identifier needs to be the last element in the input term.
+% => ODEpost needs to start by "+" or "-" and contain as many opening
+% parentheses than closing ones. Because otherwise INPUT* would be in at
+% least one parenthesis. => Not allowed. 
+if ~isempty(ODEpost),
+    if ODEpost(1) ~= '+' && ODEpost(1) ~= '-',
+        error(sprintf('The ''%s'' identifier must be the last element in the input term.\nExamplefor allowed syntax: d/dt(A) = ... + ("optional prefactor expresion")*INPUT1 + ...',name));
+    end
+end
+npo = length(strfind(ODEpost,'(')); 
+npc = length(strfind(ODEpost,')'));
+if npo ~= npc,
+    error(sprintf('The ''%s'' identifier is not allowed to be inside a parenthesis.\nExample for allowed syntax: d/dt(A) = ... + ("optional prefactor expresion")*INPUT1 + ...',name));
+end
+% 2) The last character in the ODEpre string needs to be a '+' or a '*'. So
+% that in the latter case the part in front of the INPUT* identifier can be
+% understood as a factor. 
+if ~isempty(ODEpre),
+    if ODEpre(end) ~= '+' && ODEpre(end) ~= '*',
+        error('The ''%s'' term is required to be multiplied to a prefactor.\nExample for allowed syntax: d/dt(A) = ... + ("optional prefactor expresion")*%s+...''.',name,name);
+    end
+end
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET THE FACTORS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% 3) If ODEpre is empty or ODEpre(end) = '+' then the factor is simply: 1
+if isempty(ODEpre),
+    factor = '1';
+    term = name;
+    return
+elseif ODEpre(end) == '+',
+    factor = '1';
+    term = ['+' name];
+    return
+end
+% 4) Parse the multiplicative input factor: We search for a '+' or '-'
+% outside of parentheses from right to left in ODEpre. If '-' then error.
+po = 0;
+for k=length(ODEpre):-1:1,
+    if ODEpre(k) == '(',
+        % count opening parenthesis
+        po = po+1;
+    end
+    if ODEpre(k) == ')',
+        % count closing parenthesis
+        po = po-1;
+    end
+    if ODEpre(k) == '+' && po == 0,
+        % start of factor found
+        break;
+    end
+    if ODEpre(k) == '-' && po == 0,
+        % start of factor found but '-' not allowed
+        error('The ''%s'' term is substracted from an ODE RHS. It is only allowed to ADD input terms.\nExample for allowed syntax: d/dt(A) = ... + ("optional prefactor expresion")*%s+...''.',name,name);        
+    end
+end
+% 5) extract the factor and return (ITS DONE :))
+factor = ODEpre(k:end-1);
+term = [ODEpre(k:end-1) '*' name];
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% inputsonlyonstates: checks that INPUT definitions are only made in ODEs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [output] = inputsonlyonstates(model)
+% INITIALIZE OUTPUT
+output = 1;
+% CHECK RHSs of ODEs, variables and reactions
+statenames = {model.states.name};
+ODEs = {model.states.ODE};
+if ~isempty(model.reactions),
+    reacnames = {model.reactions.name};
+    reacformulas = {model.reactions.formula};
+else
+    reacnames = {};
+    reacformulas = {};
+end
+if ~isempty(model.reactions),
+    varnames = {model.variables.name};
+    varformulas = {model.variables.formula};
+else
+    varnames = {};
+    varformulas = {};
+end
+% Check if "INPUT" defined in varformulas or reacformulas => error
+for k=1:length(varformulas),
+    if ~isempty(strfind(varformulas{k},'INPUT')),
+        output = 0; 
+        return
+    end
+end    
+for k=1:length(reacformulas),
+    if ~isempty(strfind(reacformulas{k},'INPUT')),
+        output = 0;
+        return
+    end
+end    
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% outputsonlyasvariables: checks that OUTPUT definitions only as variables
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [output] = outputsonlyasvariables(model)
+% INITIALIZE OUTPUT
+output = 1;
+% CHECK Names of states and reactions and parameters
+[statenames] = {model.states.name};
+if ~isempty(model.reactions),
+    reacnames = {model.reactions.name};
+else
+    reacnames = {};
+end
+if ~isempty(model.parameters),
+    paramnames = {model.parameters.name};
+else
+    paramnames = {};
+end
+% Check if "OUTPUT" defined as states or reactions
+for k=1:length(statenames),
+    if ~isempty(strfind(statenames{k},'OUTPUT')),
+        output = 0; 
+        return
+    end
+end    
+for k=1:length(reacnames),
+    if ~isempty(strfind(reacnames{k},'OUTPUT')),
+        output = 0;
+        return
+    end
+end    
+for k=1:length(paramnames),
+    if ~isempty(strfind(paramnames{k},'OUTPUT')),
+        output = 0;
+        return
+    end
+end    
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% checkinputnumberingOKandreorder: checks correct input naming/numbering
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% No ordering of inputs required ... just makes no sense and creates
+% problems later on. Therefor, the following text is not true anymore :-) :
+%
+% "Input names need to be numerically ordered. No index is allowed to be
+% omitted inbetween. INPUT1, INPUT2, INPUT3, ... allowed but NOT:
+% INPUT1, INPUT3, INPUT4, etc. Numbering always needs to start at 1."
+%
+% The following text already told us that the ordering is not needed:
+%
+% "It is probably not absolutely needed but to be consistent with the output
+% handling and consistent with the requirements of the input indexing, a
+% reordering of the inputs just makes sense."
+%
+% And no, ordering makes no sense but just problmes during merging with
+% dosing objects. E.g., INPUT1 defined in dosing but INPUT2 not. Then
+% INPUT2 would be left on nominal values in the model, INPUT1 would be
+% replaced ... => ERROR (which is unnecessary and undesired).
+function [model] = checkinputnumberingOKandreorder(model)
+% get input names
+inputnames = {model.inputs.name};
+% get input indices
+inputindices = str2double(regexprep(inputnames,'INPUT',''));
+% if NaN or 0 present as index then nonnumeric input numbering was used => error
+if ~isempty(find(isnan(inputindices), 1)) || ~isempty(find(inputindices==0, 1)),
+    error(sprintf('Non-numeric input naming has been used in the model.\nPlease note that the input identifiers "INPUT" are only allowed\nto be followed by a number. Starting at "1" and continuing with "2", "3", ...\nExample: INPUT1, INPUT2, INPUT3, ... But NOT: INPUT, INPUT0, INPUTx, INPUT2e, ...'));
+end
+% % check if it starts at 1 and that continues 2, 3, 4, 5, 6 ...
+% % sort indices
+% si = sort(inputindices);
+% % first entry needs to be a "1" .. 
+% if si(1) ~= 1,
+%     error('Input identifier numbering needs to start at 1. E.g.: INPUT1.');
+% end
+% % check that it continues 2, 3, 4, 5, 6, ...
+% if length(si) > 1,
+%     dsi = si(2:end)-si(1:end-1);
+%     if ~isempty(find(dsi~=1, 1)),
+%         error('Indexing of input identifiers needs to be sequential. E.g.: INPUT1,2,3, ... not leaving out an index.');
+%     end
+% end
+% % finally do reorder the inputs in the model structure according to their indices
+% model.inputs(inputindices) = model.inputs;
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% handleInputParameters: HANDLE MODEL INPUT PARAMETERS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% For each INPUT* a parameter INPUT* needs to be defined. If not present in
+% the model, then it is added to the model with a default value of 0.
+% Also add the parameter index to the model.inputs structure.
+function [model] = handleInputParameters(model)
+% get input names
+in = {model.inputs.name};
+% get parameter names 
+pn = {model.parameters.name};
+% check all input names
+for k=1:length(in),
+    parindex = strmatchSB(in{k},pn,'exact');
+    if isempty(parindex),
+        % add input parameter with 0 default value to the model
+        model.parameters(end+1).name = in{k};
+        model.parameters(end).value = 0; % default to 0
+        model.parameters(end).type = ''; % no need to export to SBML
+        model.parameters(end).compartment = ''; % no need to export to SBML
+        model.parameters(end).unittype = ''; % no need to export to SBML
+        model.parameters(end).notes = sprintf('default value for input function ''%s''',in{k});
+        % add the index of this parameter to the model.inputs.parindex field
+        model.inputs(k).parindex = length(model.parameters);
+    else
+        % input parameter is already defined. Just fill out the parindex field
+        model.inputs(k).parindex = parindex;
+    end
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% checkinputnumberingOKandreorder: % CHECK THE OUTPUT NAMES FOR VALIDITY 
+% AND REORDER THE OUTPUTS IN THE MODEL STRUCTURE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Output names need to be numerically ordered. No index is allowed to be
+% omitted inbetween. OUTPUT1, OUTPUT2, OUTPUT3, ... allowed but NOT:
+% OUTPUT1, INPUT3, OUTPUT4, etc. Numbering always needs to start at 1.
+% Outputs in the model structure are then ordered according to their name
+% for easier use of the information in later functions.
+function [model] = checkoutputnumberingOKandreorder(model)
+% get output names
+outputnames = {model.outputs.name};
+% get output indices
+outputindices = str2double(regexprep(outputnames,'OUTPUT',''));
+% if NaN or 0 present as index then nonnumeric output numbering was used => error
+if ~isempty(find(isnan(outputindices), 1)) || ~isempty(find(outputindices==0, 1)),
+    error(sprintf('Non-numeric output naming has been used in the model.\nPlease note that the output identifiers "OUTPUT" are only allowed\nto be followed by a number. Starting at "1" and continuing with "2", "3", ...\nExample: OUTPUT1, OUTPUT2, OUTPUT3, ... But NOT: OUTPUT, OUTPUT0, OUTPUTx, OUTPUT2e, ...'));
+end
+% check if it starts at 1 and that continues 2, 3, 4, 5, 6 ...
+% sort indices
+si = sort(outputindices);
+% first entry needs to be a "1" .. 
+if si(1) ~= 1,
+    error('Output identifier numbering needs to start at 1. E.g.: OUTPUT1.');
+end
+% check that it continues 2, 3, 4, 5, 6, ...
+if length(si) > 1,
+    dsi = si(2:end)-si(1:end-1);
+    if ~isempty(find(dsi~=1, 1)),
+        error('Indexing of output identifiers needs to be sequential. E.g.: OUTPUT1,2,3, ... not leaving out an index.');
+    end
+end
+% finally do reorder the outputs in the model structure according to their indices
+model.outputs(outputindices) = model.outputs;
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/experimenthandling/SBmergemodexp.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/experimenthandling/SBmergemodexp.m
new file mode 100644
index 0000000000000000000000000000000000000000..15d9867bc68eac5bb210d7764343ca2b1d8ef9c6
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/experimenthandling/SBmergemodexp.m
@@ -0,0 +1,221 @@
+function [expmodel] = SBmergemodexp(model, experiment)
+% SBmergemodexp: combines an experiment with a model, and produces a "merged 
+% model", as output. The original model and experiment arguments can be
+% given as textfiles, or SBexperiment objects. The output model is an
+% SBmodel.
+%
+% DESCRIPTIONS + SYNTAX:
+% ======================
+% To fill in!
+%
+% USAGE:
+% ======
+% [expmodel] = SBmergemodexp(model, experiment)        
+% [expmodel] = SBmergemodexp(model, experimentfile)        
+%
+% model: SBmodel 
+% experiment: An SBexperiment object describing an experiment that should be done
+%             with the model
+% experimentfile: String with the name of an experiment file
+%
+% Output Arguments:
+% =================
+% Merged model containing the original model and the experimental settings.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+expmodel = [];
+time = 0;   % per default time=0 is assumed
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check input arguments 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBmodel(model),
+    error('The first input argument needs to be an SBmodel.');
+else
+    modelstruct = SBstruct(model);
+end
+if ~isSBexperiment(experiment),
+    % Then see if this file exists
+    if (exist(experiment, 'file') == 2)
+       % try open this experiment file 
+       try
+          experiment = SBexperiment(experiment); 
+       catch exception
+           error('The second input argument needs to be either a SBexperiment or an experiment text file.');
+       end
+    else    
+        error('The second input argument needs to be either a SBexperiment or an experiment text file.');
+    end
+end
+expstruct = SBstruct(experiment);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Initialize the output model structure
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+newmodstruct = modelstruct;                    
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define all initial conditions and parameters in the workspace. Do not
+% define VARIABLES and REACTIONS! FIRST DEFINE PARAMETERS ... then ICs,
+% since ICs can depend on parameters.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for kkkloopnotuseinmodel = 1:length(newmodstruct.parameters),
+    if ~isempty(newmodstruct.parameters(kkkloopnotuseinmodel).value),
+        eval([newmodstruct.parameters(kkkloopnotuseinmodel).name '=' num2str(newmodstruct.parameters(kkkloopnotuseinmodel).value) ';']);
+    else
+        error('Value for parameter ''%s'' is undefined.',newmodstruct.parameters(kkkloopnotuseinmodel).name);
+    end
+end
+for kkkloopnotuseinmodel = 1:length(newmodstruct.states),
+    if ~isempty(newmodstruct.states(kkkloopnotuseinmodel).initialCondition),
+        eval([newmodstruct.states(kkkloopnotuseinmodel).name '=' num2str(newmodstruct.states(kkkloopnotuseinmodel).initialCondition) ';']);
+    else
+        error('Initial condition for state ''%s'' is undefined.',newmodstruct.states(kkkloopnotuseinmodel).name);
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Define all MODEL FUNCTIONS as inline objects to be used in the
+% determination of initial conditions and initial parameter settings
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for kkkloopnotuseinmodel = 1:length(newmodstruct.functions),
+    eval(sprintf('%s = @(%s)%s;',newmodstruct.functions(kkkloopnotuseinmodel).name,newmodstruct.functions(kkkloopnotuseinmodel).arguments,newmodstruct.functions(kkkloopnotuseinmodel).formula));
+end
+
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Now just evaluate the paramicsettings sequentially 
+% and add the new models to the structure
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for kkkloopnotuseinmodel = 1:length(expstruct.paramicsettings)
+    if ~isempty(expstruct.paramicsettings(kkkloopnotuseinmodel).formula),
+        try
+            % get value and assign value to variable in workspace
+            valuenotuseinmodel = eval(expstruct.paramicsettings(kkkloopnotuseinmodel).formula);
+            eval([expstruct.paramicsettings(kkkloopnotuseinmodel).name '=' num2str(valuenotuseinmodel) ';']);
+        catch
+            if expstruct.paramicsettings(kkkloopnotuseinmodel).icflag==1,
+                text = sprintf('Error in initial condition setting for state ''%s'':\n\n"%s"',expstruct.paramicsettings(kkkloopnotuseinmodel).name,lasterr);
+                text = sprintf('%s\n\nNote: Only a models states and parameters can be used in mathematical\nexpressions for the initial parameter and state settings.',text);
+                error(text);
+            else
+                text = sprintf('Error in initial condition setting for parameter ''%s'':\n\n"%s"',expstruct.paramicsettings(kkkloopnotuseinmodel).name,lasterr);
+                text = sprintf('%s\n\nOnly a models states and parameters can be used in mathematical\nexpressions for the initial parameter and state settings.',text);
+                error(text);
+            end
+        end
+    else
+        error('Formula for initial condition for state ''%s'' is undefined: %s',expstruct.paramicsettings(kkkloopnotuseinmodel).name,lasterr);
+    end
+    % value determined (valuenotuseinmodel). Add it to the model structure
+    if expstruct.paramicsettings(kkkloopnotuseinmodel).icflag==1,
+        % if initial condition then search states
+        indexnotuseinmodel = strmatchSB(expstruct.paramicsettings(kkkloopnotuseinmodel).name,{newmodstruct.states.name},'exact');
+        if isempty(indexnotuseinmodel),
+            error('Initial condition for ''%s'' defined in experiment but state does not exist in the model.',expstruct.paramicsettings(kkkloopnotuseinmodel).name);
+        end 
+        newmodstruct.states(indexnotuseinmodel).initialCondition = valuenotuseinmodel;
+        newmodstruct.states(indexnotuseinmodel).notes = expstruct.paramicsettings(kkkloopnotuseinmodel).notes;
+    else
+        % if not initial condition then search in parameters 
+        indexnotuseinmodel = strmatchSB(expstruct.paramicsettings(kkkloopnotuseinmodel).name,{newmodstruct.parameters.name},'exact');
+        if ~isempty(indexnotuseinmodel),
+            % only update value if parameter appears in the model (help
+            % variables are handled fine).
+            newmodstruct.parameters(indexnotuseinmodel).value = valuenotuseinmodel;
+            newmodstruct.parameters(indexnotuseinmodel).notes = expstruct.paramicsettings(kkkloopnotuseinmodel).notes;
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add the parameter changes to the model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Copy old variables to be able to add the new variables (parameters) first
+oldvariables = newmodstruct.variables;
+modelstructempty = struct(SBmodel());
+newmodstruct.variables = modelstructempty.variables;
+% Add new variables as first in the list
+for k = 1:length(expstruct.parameterchanges),
+    % check that no parameter is defined twice
+    if ~isempty(strmatchSB(expstruct.parameterchanges(k).name,{expstruct.paramicsettings.name},'exact')),
+        error('Parameter ''%s'' is defined twice (settings and changes).',expstruct.parameterchanges(k).name);
+    end
+    % delete this parameter from the model parameters
+    index = strmatchSB(expstruct.parameterchanges(k).name,{newmodstruct.parameters.name},'exact');
+    if isempty(index),
+        error('Parameter ''%s'' not present in the model but changed in the experiment.',expstruct.parameterchanges(k).name);
+    end
+    newmodstruct.parameters(index) = [];
+    newmodstruct.variables(end+1).name = expstruct.parameterchanges(k).name;
+    newmodstruct.variables(end).formula = expstruct.parameterchanges(k).formula;
+    newmodstruct.variables(end).notes = expstruct.parameterchanges(k).notes;
+    newmodstruct.variables(end).type = '';
+    newmodstruct.variables(end).compartment = '';
+    newmodstruct.variables(end).unittype = '';
+end
+% Add old variables at the end
+for k = 1:length(oldvariables),
+    newmodstruct.variables(end+1).name = oldvariables(k).name;
+    newmodstruct.variables(end).formula = oldvariables(k).formula;
+    newmodstruct.variables(end).notes = oldvariables(k).notes;
+    newmodstruct.variables(end).type = oldvariables(k).type;
+    newmodstruct.variables(end).compartment = oldvariables(k).compartment;
+    newmodstruct.variables(end).unittype = oldvariables(k).unittype;    
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add experiment events to the model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k = 1:length(expstruct.stateevents)
+    newmodstruct.events(end+1) = expstruct.stateevents(k);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% return the experiment model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+expmodel = SBmodel(newmodstruct);
+return
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%% The "find index" function
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [index] = find_index(name_array, comp_string)
+k = 0;
+l = length(name_array);
+index = inf;
+while k < l
+    k = k+1;
+    if strcmp(comp_string, name_array(k))
+        index = k;
+    end
+end
+if index == inf,
+    error('The experiment description contains the element ''%s'' that is not present in the model.',comp_string);
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/experimenthandling/auxiliary/exp2text/convertExpToTextSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/experimenthandling/auxiliary/exp2text/convertExpToTextSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..76fa80d23d4cdc9cc3854e5a19013dc96a972b51
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/experimenthandling/auxiliary/exp2text/convertExpToTextSB.m
@@ -0,0 +1,158 @@
+function [expTextStructure] = convertExpToTextSB(exp)
+% convertExpToTextSB: Converts an SBexp object to a structure containing the 
+% different parts of the text description of the experiment. 
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+% Initialize variables
+expTextStructure = [];
+% Get SBstructure
+SBstructure = SBstruct(exp);
+% Parse structure into the expTextStructure description
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Name
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+expTextStructure.name = SBstructure.name;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Notes
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+expTextStructure.notes = SBstructure.notes;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% error variables
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+informationErrorText = '';
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Parameters and Initial conditions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+listofstatesic = {};
+expTextStructure.paramicsettings = '';
+for k = 1:length(SBstructure.paramicsettings),
+    name = SBstructure.paramicsettings(k).name;
+    formula = SBstructure.paramicsettings(k).formula;
+    notes = SBstructure.paramicsettings(k).notes;
+    if SBstructure.paramicsettings(k).icflag == 0,
+        if ~isempty(notes),
+            expTextStructure.paramicsettings = sprintf('%s%s = %s %% %s\n',expTextStructure.paramicsettings,name,formula,notes);
+        else
+            expTextStructure.paramicsettings = sprintf('%s%s = %s\n',expTextStructure.paramicsettings,name,formula);
+        end
+    else
+        if ~isempty(notes),
+            expTextStructure.paramicsettings = sprintf('%s%s(0) = %s %% %s\n',expTextStructure.paramicsettings,name,formula,notes);
+        else
+            expTextStructure.paramicsettings = sprintf('%s%s(0) = %s\n',expTextStructure.paramicsettings,name,formula);
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Parameters changes
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+expTextStructure.parameterchanges = '';
+for k = 1:length(SBstructure.parameterchanges),
+    name = SBstructure.parameterchanges(k).name;
+    formula = SBstructure.parameterchanges(k).formula;
+    notes = SBstructure.parameterchanges(k).notes;
+%     % check if piecewise in formula
+%     % piecewise in formula can have two different origins. on one hand it
+%     % can come from a real piecewise expression in the original experiment
+%     % description. on the other hand it can come from the piecewise
+%     % shorthand syntax. just assume shorthand syntax and if it fails write
+%     % out the piecewise statement.
+%     if ~isempty(strfind(formula,'piecewiseSB')),
+%         formulabackup = formula;
+%         % delete piecewiseSB from formula
+%         formula = formula(13:end-1)
+%         % delete ge(time, ...) from formula
+%         terms = explodePCSB(formula,',');
+%         values = terms(1:2:end);
+%         triggers = terms(2:2:end);
+%         times = [];
+%         shorthand = 1;
+%         try
+%             % try to assume shorthand syntax
+%             for k2 = 1:length(triggers),
+%                 data = regexp(triggers{k2},'ge\(time,([^)]*)\),le\(time,([^)]*)\)','tokens');
+%                 times = [times, str2num(data{1}{1}), str2num(data{1}{2})];
+%             end
+%         catch
+%             shorthand = 0;
+%         end
+%         if shorthand,
+%             times = unique(times);
+%             timescell = {};
+%             for k2 = 1:length(times),
+%                 timescell{k2} = num2str(times(k2));
+%             end
+%             formuladata = {};
+%             formuladata(1:2:length(times)+length(values)) = timescell;
+%             formuladata(2:2:length(times)+length(values)) = values;
+%             formula = '';
+%             for k = 1:length(formuladata),
+%                 if mod(k,2) == 0,
+%                     formula = sprintf('%s%s, ',formula,formuladata{k});
+%                 else
+%                     formula = sprintf('%s%s, ',formula,formuladata{k});
+%                 end
+%             end
+%             formula = sprintf('{%s}',formula(1:end-2));
+%         else
+%             formula = formulabackup;
+%         end
+%     else
+        formula = formula;
+%     end
+    % update structure
+     if ~isempty(notes),
+         expTextStructure.parameterchanges = sprintf('%s%s = %s %% %s\n',expTextStructure.parameterchanges,name,formula,notes);
+     else
+         expTextStructure.parameterchanges = sprintf('%s%s = %s\n',expTextStructure.parameterchanges,name,formula);
+     end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% State events
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+expTextStructure.stateevents = '';
+for k = 1:length(SBstructure.stateevents),
+    name = SBstructure.stateevents(k).name;
+    trigger = SBstructure.stateevents(k).trigger;
+    notes = SBstructure.stateevents(k).notes;
+    % delete ge(time, ...) from trigger
+    trigger = trigger(9:end-1);
+    formula = sprintf('time = %s', trigger);
+    for k2 = 1:length(SBstructure.stateevents(k).assignment),
+        formula = sprintf('%s, %s = %s',formula,SBstructure.stateevents(k).assignment(k2).variable,SBstructure.stateevents(k).assignment(k2).formula);
+    end
+     if ~isempty(notes),
+         expTextStructure.stateevents = sprintf('%s%s %% %s\n',expTextStructure.stateevents,formula,notes);
+     else
+         expTextStructure.stateevents = sprintf('%s%s\n',expTextStructure.stateevents,formula);
+     end
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/experimenthandling/auxiliary/exp2text/setPartsToCompleteTextExpSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/experimenthandling/auxiliary/exp2text/setPartsToCompleteTextExpSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..49d719a324b2c9a76abb708e842b30b9cc6be451
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/experimenthandling/auxiliary/exp2text/setPartsToCompleteTextExpSB.m
@@ -0,0 +1,34 @@
+function [completeText] = setPartsToCompleteTextExpSB(expTextStructure)
+% setPartsToCompleteTextExpSB: Sets the different parts of an experiment description
+% of an SBexp object together to the complete text
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+completeText = sprintf('********** EXPERIMENT NAME\n%s\n',expTextStructure.name);
+completeText = sprintf('%s\n********** EXPERIMENT NOTES\n%s\n',completeText,expTextStructure.notes);
+completeText = sprintf('%s\n********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS\n%s',completeText,expTextStructure.paramicsettings);
+completeText = sprintf('%s\n********** EXPERIMENT PARAMETER CHANGES\n%s',completeText,expTextStructure.parameterchanges);
+completeText = sprintf('%s\n********** EXPERIMENT STATE CHANGES\n%s',completeText,expTextStructure.stateevents);
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/experimenthandling/auxiliary/text2exp/convertTextToExpSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/experimenthandling/auxiliary/text2exp/convertTextToExpSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..be28b9568487599865a375afdebc4b0efe861e36
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/experimenthandling/auxiliary/text2exp/convertTextToExpSB.m
@@ -0,0 +1,257 @@
+function [SBstructure,errorMsg] = convertTextToExpSB(expText)
+% convertTextToExpSB: Converts a text description of an SBexp object to 
+% the internal SBexp data structure representation.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+% initialize variables
+errorMsg = '';
+errorConditions = '';
+errorParameterChanges = '';
+errorStateEvents = '';
+SBstructure = [];
+
+% cut text into pieces
+expTextStructure = getPartsFromCompleteTextExpSB(expText);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%% Name
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBstructure.name = strtrim(removeCharacters(expTextStructure.name));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%% Notes
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBstructure.notes = strtrim(expTextStructure.notes);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%% Conditions (parameters and initial conditions)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try
+    [SBstructure.paramicsettings, errorConditions] = getConditions(expTextStructure.conditions);
+catch
+    errorMsg = sprintf('%sPlease check the syntax of the ''Parameter and initial conditions'' definitions.\n',errorMsg);
+end
+if ~isempty(errorConditions),
+    errorMsg = sprintf('%s%s\n',errorMsg,errorConditions);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%% Parameter changes
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%try
+    [SBstructure.parameterchanges, errorParameterChanges] = getParameterChanges(expTextStructure.parameterchanges);
+%catch
+%    errorMsg = sprintf('%sPlease check the syntax of the ''Parameter Changes'' definitions.\n',errorMsg);
+%end
+if ~isempty(errorParameterChanges),
+    errorMsg = sprintf('%s%s\n',errorMsg,errorParameterChanges);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%% State changes
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%try
+    [SBstructure.stateevents, errorStateEvents] = getStateEvents(expTextStructure.stateevents);
+%catch
+%    errorMsg = sprintf('%sPlease check the syntax of the ''States Changes'' definitions.\n',errorMsg);
+%end
+if ~isempty(errorStateEvents),
+    errorMsg = sprintf('%s%s\n',errorMsg,errorStateEvents);
+end
+return
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [paramicsettings, error] = getConditions(conditionsString)
+error = '';
+% create empty structures
+paramicsettings = struct('name',{},'formula',{},'notes',{},'icflag',{});
+% parse the strings and fill the structures
+conditionsString = char([double(conditionsString) 10]); % need to add a '\n' at the end
+allelements = regexp(conditionsString,'([^\n]*)=([^\n]*)\n','tokens');
+for k = 1:length(allelements),
+    element = allelements{k};
+    leftside = strtrim(removeCharacters(element{1}));
+    rightsideandcomment = strtrim(removeCharacters(element{2}));
+    % parse right side and comment (remove (0) from the right side)
+    rightsideandcomment = regexp(rightsideandcomment,'([^%]*)','tokens');
+    rightside = regexprep(strtrim(rightsideandcomment{1}{1}),'\(0\)','');
+    if length(rightsideandcomment) == 2,
+        comment = strtrim(rightsideandcomment{2}{1});
+    else
+        comment = '';
+    end
+    % check if state initial condition or if parameter definition
+    if isempty(strfind(leftside,'(0)')),
+        paramicsettings(end+1).name = leftside;
+        try
+            eval(['zzz =' rightside ';']);
+            paramicsettings(end).formula = num2str(zzz);
+        catch
+            paramicsettings(end).formula = rightside;
+        end
+        %paramicsettings(end).formula = rightside;
+        paramicsettings(end).notes = comment;
+        paramicsettings(end).icflag = 0;
+    else
+        paramicsettings(end+1).name = regexprep(leftside,'\(0\)','');
+        %%% ADD VARIABILITY - BRUNO
+        try
+            eval(['zzz =' rightside ';']);
+            paramicsettings(end).formula = num2str(zzz);
+        catch
+            paramicsettings(end).formula = rightside;
+        end
+        %%% Initial code 
+        %paramicsettings(end).formula = rightside;
+        paramicsettings(end).notes = comment;
+        paramicsettings(end).icflag = 1;
+    end
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [parameterchanges, error] = getParameterChanges(parameterchangesString)
+error = '';
+% create empty structure
+parameterchanges = struct('name',{},'formula',{},'notes',{});
+% parse the strings and fill the structures
+parameterchangesString = char([double(parameterchangesString) 10]); % need to add a '\n' at the end
+allelements = regexp(parameterchangesString,'([^\n]*)=([^\n]*)\n','tokens');
+for k = 1:length(allelements),
+    element = allelements{k};
+    leftside = strtrim(removeCharacters(element{1}));
+    rightsideandcomment = strtrim(removeCharacters(element{2}));
+    % parse right side and comment
+    rightsideandcomment = regexp(rightsideandcomment,'([^%]*)','tokens');
+    rightside = strtrim(removeCharacters(rightsideandcomment{1}{1}));
+    if length(rightsideandcomment) == 2,
+        comment = strtrim(removeCharacters(rightsideandcomment{2}{1}));
+    else
+        comment = '';
+    end
+    % check if a piecewisestatement is present
+    if ~isempty(strfind(rightside,'{')),
+        % construct piecewise statement
+        rightside = rightside(2:end-1);  % take away the outer parentheses
+        terms = explodePCSB(rightside,',');
+        if mod(length(terms),2) == 1, % (if uneven)
+            error = sprintf('%sParameter change for ''%s'' does not have a default value defined.',error,leftside);
+            return
+        end
+        if length(terms) <= 2,
+            error = sprintf('Wrong definition of parameter setting for parameter ''%s''.\n',leftside);
+            return
+        end
+        formula = 'piecewiseSB(';
+        times = terms(1:2:length(terms));
+        values = terms(2:2:length(terms));
+        triggers = {};
+        for k2 = 1:length(times)-1,
+            triggers{k2} = sprintf('and(ge(time,%s),le(time,%s))',times{k2},times{k2+1});
+        end
+        valuestimes = {};
+        valuestimes(1:2:length(triggers)+length(values)) = values;
+        valuestimes(2:2:length(triggers)+length(values)) = triggers;
+        % construct piecewise statement
+        formula = 'piecewiseSB(';
+        for k2 = 1:length(valuestimes),
+            formula = sprintf('%s%s,',formula,valuestimes{k2});
+        end
+        formula =sprintf('%s)',formula(1:end-1));
+    else
+        % no piecewise statement detected => just take formula as it is
+        formula = rightside;
+    end
+    % add data
+    parameterchanges(end+1).name = leftside;
+    parameterchanges(end).formula = formula;
+    parameterchanges(end).notes = comment;
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [stateevents, error] = getStateEvents(stateeventsString)
+error = '';
+% create empty structure
+eventassignment = struct('variable',{},'formula',{});
+stateevents = struct('name',{},'trigger',{},'assignment',eventassignment,'notes',{});
+% parse the strings and fill the structures
+stateeventsString = char([double(stateeventsString) 13 10]); % need to add a '\n' at the end
+if isempty(strtrim(stateeventsString)),
+    stateeventsString = strtrim(stateeventsString);
+end
+allelements = regexp(stateeventsString,'([^\n]*)\n','tokens');
+for k=1:length(allelements),
+    stateevents(end+1).name = sprintf('StateChange_%d',k);
+    % determine the comment
+    element = regexp(allelements{k}{1},'([^%]*)','tokens');
+    eventdata = element{1}{1};
+    if length(element) == 1,
+        comment = '';
+    else
+        comment = element{2}{1};
+    end
+    stateevents(end).notes = strtrim(removeCharacters(comment));
+    % get event data
+    terms = explodePCSB(eventdata,',');
+    if length(terms) < 2,
+        error = sprintf('%s\nState change nr. %d wrongly defined.',error,k);
+        return
+    end
+    % the first term needs to define the time of the event. format: time = xxx
+    test = explodePCSB(terms{1},'=');
+    if isempty(strcmp(test{1},'time')) || length(test) ~= 2,
+        error = sprintf('%s\nState change nr. %d wrongly defined ("time = numeric value" needs to be the first element).',error,k);
+        return
+    end
+    % get trigger function
+    stateevents(end).trigger = sprintf('ge(time,%s)',test{2});
+    % determine event assignments
+    for k2 = 2:length(terms),
+        assterms = explodePCSB(terms{k2},'=');
+        stateevents(end).assignment(k2-1).variable = assterms{1};
+        stateevents(end).assignment(k2-1).formula = assterms{2};
+    end
+end
+return
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [output] = removeCharacters(input)
+% delete all line breaks and tabs from the input string
+temp = double(input);
+temp(find(temp==13)) = 32;  % replace '\cr' by white space
+temp(find(temp==10)) = 32;  % replace '\n' by white space
+temp(find(temp==9)) = 32;   % replace '\t' by white space
+output = char(temp);
+% remove all spaces
+%    output = strrep(output,' ','');
+return
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/experimenthandling/auxiliary/text2exp/getPartsFromCompleteTextExpSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/experimenthandling/auxiliary/text2exp/getPartsFromCompleteTextExpSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..6db4cb832569c109be1e4b21b470c84c1c71118f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/experimenthandling/auxiliary/text2exp/getPartsFromCompleteTextExpSB.m
@@ -0,0 +1,44 @@
+function [expTextStructure] = getPartsFromCompleteTextExpSB(expText)
+% getPartsFromCompleteTextExpSB: Cuts a text description of an SBexp object
+% into the different parts and returns them in a structure
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+% take commented lines out of the experiment description
+expText = regexprep(expText,'\n%[^\n]*','');
+
+% Find the starts of the different view data
+nameStart = strfind(expText,'********** EXPERIMENT NAME');
+notesStart = strfind(expText,'********** EXPERIMENT NOTES');
+conditionsStart = strfind(expText,'********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS');
+parameterchangesStart = strfind(expText,'********** EXPERIMENT PARAMETER CHANGES');
+stateeventsStart = strfind(expText,'********** EXPERIMENT STATE CHANGES');
+% Cut out the different pieces and assign them to the expTextStructure structure
+expTextStructure.name = strtrim(expText(nameStart+length('********** EXPERIMENT NAME'):notesStart-1));
+expTextStructure.notes = strtrim(expText(notesStart+length('********** EXPERIMENT NOTES'):conditionsStart-1));
+expTextStructure.conditions = strtrim(expText(conditionsStart+length('********** EXPERIMENT INITIAL PARAMETER AND STATE SETTINGS'):parameterchangesStart-1));
+expTextStructure.parameterchanges = strtrim(expText(parameterchangesStart+length('********** EXPERIMENT PARAMETER CHANGES'):stateeventsStart-1));
+expTextStructure.stateevents = strtrim(expText(stateeventsStart+length('********** EXPERIMENT STATE CHANGES'):end));
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/experimenthandling/isSBexperiment.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/experimenthandling/isSBexperiment.m
new file mode 100644
index 0000000000000000000000000000000000000000..8f6a58167aa121de5840c8c25fba4e1feed5b001
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/experimenthandling/isSBexperiment.m
@@ -0,0 +1,23 @@
+function [output] = isSBexperiment(input)
+% isSBexperiment: check if input argument is an SBexperiment.
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+output = strcmp(class(input),'SBexperiment');
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/experimenthandling/methods/SBcreateEXPfile.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/experimenthandling/methods/SBcreateEXPfile.m
new file mode 100644
index 0000000000000000000000000000000000000000..852bec6083f0c942d91f5a1b8de19e41be17a36a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/experimenthandling/methods/SBcreateEXPfile.m
@@ -0,0 +1,97 @@
+function SBcreateEXPfile(varargin)
+% SBcreateEXPfile: creates a *.exp file with the experiments text description
+%
+% USAGE:
+% ======
+% [] = SBcreateEXPfile()         
+% [] = SBcreateEXPfile(filename)         
+% [] = SBcreateEXPfile(exp)         
+% [] = SBcreateEXPfile(exp,filename)
+%
+% exp: SBexp object to convert to a textfile description
+% filename: filename for the created textfile 
+%
+% If exp is undefined, then an empty experiment file will be created. 
+%
+% DEFAULT VALUES:
+% ===============
+% exp: the experiment to be exported as EXP file. 
+% filename: constructed from the experiments name
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 0,
+    % create empty experiment file with the name "unnamed.exp"
+    exp = SBexperiment();
+    filename = 'unnamed.exp';
+elseif nargin == 1,
+    % check if first input argument experiment or filename
+    if isSBexperiment(varargin{1}),
+        % experiment given
+        exp = varargin{1};
+        % if no filename provided then use the name of the SBexp object as filename
+        % remove unwanted characters first
+        es = struct(exp);
+%         functionName = regexprep(es.name,'\W','');
+        functionName = es.name;
+        filename = strcat(functionName,'.exp');
+    else
+        % filename given?
+        if ~ischar(varargin{1}),
+            error('Wrong input argument.');
+        end
+        filename = strcat(varargin{1},'.exp');
+        exp = SBexperiment();
+    end
+elseif nargin == 2,
+    exp = varargin{1};
+    filename = strcat(varargin{2},'.exp');
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK INPUT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBexperiment(exp),
+    error('No SBexperiment as first argument.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONVERT MODEL TO TEXT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[expTextStructure] = convertExpToTextSB(exp);
+[completeText] = setPartsToCompleteTextExpSB(expTextStructure);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% WRITE THE FILE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen(filename,'w');
+fwrite(fid,completeText);
+fclose(fid);
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/experimenthandling/methods/auxiliary/checkProcessActiveSetParameterSetSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/experimenthandling/methods/auxiliary/checkProcessActiveSetParameterSetSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..c2d6b0d648bbe6298c05028cf74048ac4833d848
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/experimenthandling/methods/auxiliary/checkProcessActiveSetParameterSetSB.m
@@ -0,0 +1,130 @@
+function [expText] = checkProcessActiveSetParameterSetSB(expText,path2paramset)
+% checkProcessActiveSetParameterSetSB checks the expText if "activeSet"
+% and/or "parameterSet" definitions are present. If yes, then these
+% SBexperiments are loaded first and then the contents added to expText.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check "activeSet", "parameterSet"
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(strfind(expText,'activeSet(')) && isempty(strfind(expText,'parameterSet(')),
+    % Nothing to be done
+    return
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if "path2paramset" is non-empty
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(path2paramset),
+    error(sprintf('The experiment contains "activeSet" and/or "parameterSet" definitions.\nFor that to be handled you need to provide the path to the root folder of these definitions.'));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Remove \r from expText
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+expText = double(expText);
+expText(expText==13) = [];
+expText = char(expText);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle the activeSet definitions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+index = strfind(expText,'activeSet(');
+while ~isempty(index),
+    % Handle first occurrence of "activeSet"
+    % 1) Get the corresponding line
+    row = double(expText(index:end)); 
+    i = find(row == 10);
+    row = char(row(1:i));
+    filename = [row(12:end-3) '.exp'];
+    % Read the corresponding "activeSet" experiment
+    file = fullfile(path2paramset,'Parameter Sets/Active Sets',filename);
+    content = getandcheckExpfile(file);
+    % Insert the "content" text into "expText" instead of "activeSet" definition
+    expText = strrep(expText,(expText(index(1):index(1)+i-2)),content);
+    % Search again for "activeSet("
+    index = strfind(expText,'activeSet(');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle the parameterSet definitions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+index = strfind(expText,'parameterSet(');
+while ~isempty(index),
+    % Handle first occurrence of "parameterSet"
+    % Get the corresponding line
+    row = double(expText(index:end));
+    i = find(row == 10);
+    row = char(row(1:i));
+    file = row(15:end-3);
+    % Check if direct file or if interpolation necessary
+    x = length(explodePCSB(file,','));
+    if x == 4,
+        % Handle interpolation
+        content = doInterpolation(file,path2paramset);
+    elseif x == 1,
+        filename = [file '.exp'];
+        % Read the corresponding "activeSet" experiment
+        filecomplete = fullfile(path2paramset,'Parameter Sets/Parameter Sets',filename);
+        content = getandcheckExpfile(filecomplete);
+        content = ['% ' file char(10) content char(10)];
+    else
+        error('checkProcessActiveSetParameterSetSB: error in parameterSet definition ... maybe a "," to much?');
+    end
+    % Insert the "content" text into "expText" instead of "parameterSet" definition
+    expText = strrep(expText,(expText(index(1):index(1)+i-2)),content);
+    % Search again for "parameterSet("
+    index = strfind(expText,'parameterSet(');
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Perform the parameterSet interpolation and construct the content text
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [content] = doInterpolation(file,path2paramset)
+terms = explodePCSB(file,',');
+% Check if linear interpolation (only supported for the moment)
+linear = strfind(terms{4},'Linear');
+if isempty(linear),
+    error('checkProcessActiveSetParameterSetSB: Only linear interpolation of parameter sets allowed at the moment.');
+end
+% Get coefficient
+coefficient = str2double(terms{3});
+% Get lower and upper experiments and remove "dirt" around the strings
+lowerfilename = fullfile(path2paramset,'Parameter Sets/Parameter Sets',[terms{1}(1:end-1) '.exp']);
+upperfilename = fullfile(path2paramset,'Parameter Sets/Parameter Sets',[terms{2}(2:end-1) '.exp']);
+% Check the two experiments for errors
+getandcheckExpfile(lowerfilename);
+getandcheckExpfile(upperfilename);
+% Load the two experiments
+eLs = struct(SBexperiment(lowerfilename));
+eUs = struct(SBexperiment(upperfilename));
+% Create interpolated experiment
+eIs = eLs;
+% Do the interpolation
+for k=1:length(eIs.paramicsettings),
+    vL = eval(eLs.paramicsettings(k).formula);
+    vH = eval(eUs.paramicsettings(k).formula);
+    vI = vL+coefficient*(vH-vL);
+    eIs.paramicsettings(k).formula = num2str(vI);
+end
+eI = SBexperiment(eIs);
+[eIstruct] = convertExpToTextSB(eI);
+content = ['% ''' file '''' char(10) eIstruct.paramicsettings];
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check parameterSet and activeSet SBexperiments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [content] = getandcheckExpfile(file)
+content = fileread(file);
+parts = getPartsFromCompleteTextExpSB(content);
+% Check if only "conditions" field filled in
+if ~isempty(parts.parameterchanges) || ~isempty(parts.stateevents),
+    error('checkProcessActiveSetParameterSetSB: parameter changes and state events not allowed in activeSet or parameterSet SBexperiments!');
+end
+content = parts.conditions;
+% Check if 'activeSet' or 'parameterSet' definitions present (not allowed)
+if ~isempty(strfind(content,'activeSet(')) || ~isempty(strfind(content,'parameterSet(')),
+    error('checkProcessActiveSetParameterSetSB: activeSet and parameterSet definitions in SBexperiments can not be nested!');
+end
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/measurementhandling/SBexportXLSmeasurements.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/measurementhandling/SBexportXLSmeasurements.m
new file mode 100644
index 0000000000000000000000000000000000000000..1252f9636b52cd087a12c2d6b5bb975b801174a1
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/measurementhandling/SBexportXLSmeasurements.m
@@ -0,0 +1,62 @@
+function [] = SBexportXLSmeasurements(measurements,filename)
+% SBexportXLSmeasurement
+% Exports several SBmeasurement objects to the same XLS (excel) file.
+% Each measurement will be added to a separate sheet in the file.
+%
+% USAGE:
+% ======
+% [] = SBexportXLSmeasurement(measurements,filename)
+%
+% measurements: A cell-array in which all the elements are SBmeasurement objects.
+% filename:     Desired filename for XLS file. The extension '.xls' is not
+%               required.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+[PATHSTR,filename,EXT] = fileparts(filename);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF MULTIPLE MEASUREMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~iscell(measurements),
+    input = {measurements};
+else
+    input = measurements;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DELETE FILE WITH FILENAME IF PRESENT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+warning off;
+delete(strcat(filename,'.xls'));
+warning on;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% LOOP THROUGH THE MEASUREMENTS AND EXPORT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for sheet=1:length(input),
+    measurement = input{sheet};
+    SBexportXLSmeasurement(measurement,strcat(filename,'.xls'),sheet);
+end
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/measurementhandling/SBmeasurementdata.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/measurementhandling/SBmeasurementdata.m
new file mode 100644
index 0000000000000000000000000000000000000000..ac80abbc5c59eaadabf855a4140a19ca5f8bd1e7
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/measurementhandling/SBmeasurementdata.m
@@ -0,0 +1,85 @@
+function [time, componentNames, values, minvalues, maxvalues] = SBmeasurementdata(measurement)
+% SBmeasurementdata
+% This functions allows to extract information from an SBmeasurement structure
+% 
+% USAGE:
+% ======
+% [time, componentNames] = SBmeasurementdata(measurement)
+% [time, componentNames, values] = SBmeasurementdata(measurement)
+% [time, componentNames, values,minvalues,maxvalues] = SBmeasurementdata(measurement)
+% 
+% measurement: SBmeasurement object
+%
+% Output Arguments:
+% =================
+% time: time vector of all measurement instants
+% componentNames: cell-array containing the names of the measured components
+% values: matrix containing all the measurements of the components.
+%   One row per time instant and one column per measured component.
+%   The ordering of the columns corresponds to the ordering of the names in
+%   the "componentNames" output variable. Non measured elements are set to
+%   NaN (not a number).
+% minvalues: matrix containing all the min values for the measured components.
+%   One row per time instant and one column per measured component.
+%   The ordering of the columns corresponds to the ordering of the names in
+%   the "componentNames" output variable. Non measured elements are set to
+%   NaN (not a number).
+% maxvalues: matrix containing all the max values for the measured components.
+%   One row per time instant and one column per measured component.
+%   The ordering of the columns corresponds to the ordering of the names in
+%   the "componentNames" output variable. Non measured elements are set to
+%   NaN (not a number).
+
+% Information:
+% ============
+% Copyright (C) 2008 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+if ~isSBmeasurement(measurement),
+    error('Input argument is not an SBmeasurement.');
+end
+measurement = struct(measurement);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF MODEL CONTAINS MEASUREMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if length(measurement.data) == 0,
+    error('The model does not contain any measurements');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET INFORMATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% get time vector
+time = measurement.time;
+% get component names
+componentNames = {};
+values = [];
+minvalues = [];
+maxvalues = [];
+for k=1:length(measurement.data),
+    componentNames{end+1} = measurement.data(k).name;
+    values(:,end+1) = measurement.data(k).values;
+    minvalues(:,end+1) = measurement.data(k).minvalues;
+    maxvalues(:,end+1) = measurement.data(k).maxvalues;
+end
+return
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/measurementhandling/SBvisualizemeasurement.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/measurementhandling/SBvisualizemeasurement.m
new file mode 100644
index 0000000000000000000000000000000000000000..ee6efc15b7c952a3d2d2247007d65c176f604688
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/measurementhandling/SBvisualizemeasurement.m
@@ -0,0 +1,111 @@
+function [varargout] = SBvisualizemeasurement(measurement)
+% SBvisualizemeasurement
+% Function allowing to visualize the content of an SBmeasurement object. 
+% The function just prepares the data. Display is then realized using
+% the SBplot function.
+% 
+% USAGE:
+% ======
+% [] = SBvisualizemeasurement(measurement)
+% [output] = SBvisualizemeasurement(measurement)
+%
+% measurement: SBmeasurement object containing the data
+%
+% Output Arguments:
+% =================
+% If an output argument is specified, the data are not plotted, but a
+% structure is returned that can be used as input argument for SBplot to
+% show the data.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+% convert SBmeasurement object to struct
+measurement = SBstruct(measurement);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF MODEL CONTAINS MEASUREMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if length(measurement.data) == 0,
+    error('The SBmeasurement object does not contain any measurements.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET TIME VECTOR
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+time = measurement.time;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS THE DATA INTO A MATRIX
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% also construct dataNames and legendtext data
+dataNames = {};
+dataMatrix = NaN*ones(length(measurement.time),length(measurement.data));
+timeMatrix = dataMatrix;
+dataErrorindices = [];
+dataMinvalues = [];
+dataMaxvalues = [];
+
+legendtext = {};
+for k = 1:length(measurement.data),
+    name = measurement.data(k).name;
+    dataNames{k} = name;
+    if ~isempty(measurement.data(k).notes),
+        legendtext{k} = sprintf('%s (%s)',name,measurement.data(k).notes);
+    else
+        legendtext{k} = sprintf('%s',name);
+    end
+    dataComponent = measurement.data(k).values;
+    timeComponent = measurement.time;
+    dataComponent = dataComponent;
+    timeComponent = timeComponent;
+    dataMatrix(1:length(dataComponent),k) = dataComponent;
+    timeMatrix(1:length(timeComponent),k) = timeComponent;
+
+    % Process error bounds if present (only if both are present)
+    if ~isempty(measurement.data(k).maxvalues) && ~isempty(measurement.data(k).minvalues),
+        if length(measurement.data(k).minvalues) ~= length(measurement.data(k).maxvalues),
+            warning('Measurement ''%s'' does have different numbers of max and min bounds.',measurement.data(k).name);
+        else
+            dataErrorindices(end+1) = k;
+            dataMinvalues(1:length(measurement.data(k).minvalues),end+1) = measurement.data(k).minvalues;
+            dataMaxvalues(1:length(measurement.data(k).maxvalues),end+1) = measurement.data(k).maxvalues;
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle variable output arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Keep the commented part as long as it works!
+if nargout==0,
+    % plot
+%    SBplot(timeMatrix,dataMatrix,dataNames,dataErrorindices,dataMinvalues,dataMaxvalues,legendtext,'*:',measurement.name);
+    SBplot(timeComponent,dataMatrix,dataNames,dataErrorindices,dataMinvalues,dataMaxvalues,legendtext,'*',measurement.name);
+elseif nargout == 1,
+%    varargout{1} = createdatastructSBplotSB(timeMatrix,dataMatrix,dataNames,dataErrorindices,dataMinvalues,dataMaxvalues,legendtext,'*:',measurement.name);
+    varargout{1} = createdatastructSBplotSB(timeComponent,dataMatrix,dataNames,dataErrorindices,dataMinvalues,dataMaxvalues,legendtext,'*',measurement.name);
+else
+    error('Incorrect number of output arguments.');
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/measurementhandling/isSBmeasurement.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/measurementhandling/isSBmeasurement.m
new file mode 100644
index 0000000000000000000000000000000000000000..fc71c04d9303c10e6c1dbf8b6aafa54508476b6f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/measurementhandling/isSBmeasurement.m
@@ -0,0 +1,23 @@
+function [output] = isSBmeasurement(input)
+% isSBmeasurement: check if input argument is an SBmeasurement.
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+output = strcmp(class(input),'SBmeasurement');
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/measurementhandling/methods/SBexportCSVmeasurement.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/measurementhandling/methods/SBexportCSVmeasurement.m
new file mode 100644
index 0000000000000000000000000000000000000000..fc7f11f814604a7656a2651e7cccd99fb8865e7b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/measurementhandling/methods/SBexportCSVmeasurement.m
@@ -0,0 +1,159 @@
+function [] = SBexportCSVmeasurement(varargin)
+% SBexportCSVmeasurement
+% Exports an SBmeasurement object to a CSV (comma separated value) file.
+% The format of the written CSV file is explained in the user's reference
+% manual and example files can be found in the SBTOOLBOX2/examples folder.
+% 
+% USAGE:
+% ======
+% [] = SBexportCSVdata(measurement)
+% [] = SBexportCSVdata(measurement,filename)
+%
+% measurement: SBmeasurement object containing the data
+% filename:    desired filename for CSV file. The extension '.csv' is not
+%              required.
+%
+% DEFAULT VALUES:
+% ===============
+% filename: constructed from the data objects name
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% Modified: Antoine Soubret 18/03/2011
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 1,
+    measurement = varargin{1};
+    % convert object to structure
+    measurement = struct(measurement);    
+    % if no filename provided then use the name of the SBmeasurement object 
+    % as filename. Just delete all the special characters.
+    filename = measurement.name;   % white spaces
+elseif nargin == 2,
+    measurement = varargin{1};
+    % convert object to structure
+    measurement = struct(measurement);    
+    % extract filename from input arguments to skip eventual extension
+    [PATHSTR,filename,EXT] = fileparts(varargin{2});
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF OBJECT CONTAINS MEASUREMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if length(measurement.data) == 0,
+    error('The object does not contain any measurements');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Create the file 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen(strcat(filename,'.csv'),'w');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Write header
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'%% Measurement file generated: %s\n\n',date);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% NAME
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'[Name]\n');
+fprintf(fid,'%s\n',measurement.name);
+fprintf(fid,'\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% NOTES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'[Notes]\n');
+fprintf(fid,'%s\n',measurement.notes);
+fprintf(fid,'\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% COMPONENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'[Components]\n');
+text = 'time,';
+for k=1:length(measurement.data),
+    text = sprintf('%s%s,',text,measurement.data(k).name);
+    % add error bound names
+    if ~isempty(measurement.data(k).maxvalues) && max(isnan(measurement.data(k).maxvalues))~=1,
+        text = sprintf('%s%s+,',text,measurement.data(k).name);
+    end
+    if ~isempty(measurement.data(k).minvalues) && max(isnan(measurement.data(k).minvalues))~=1,
+        text = sprintf('%s%s-,',text,measurement.data(k).name);
+    end
+end
+text = text(1:end-1);
+fprintf(fid,'%s\n',text);
+fprintf(fid,'\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% COMPONENTNOTES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'[Componentnotes]\n');
+for k=1:length(measurement.data),
+    if ~isempty(measurement.data(k).notes),
+        notes = regexprep(measurement.data(k).notes,'\n',' ');
+        notes = regexprep(notes,'  ',' ');
+        notes = regexprep(notes,'  ',' ');
+        if ~isempty(measurement.data(k).name),
+            fprintf(fid,'%s: %s\n',measurement.data(k).name,notes);
+        else
+            fprintf(fid,'%s: %s\n',measurement.data(k).formula,notes);
+        end
+    end
+end
+fprintf(fid,'\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Values
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'[Values]\n');
+experimentData = measurement.time(:);
+for k = 1:length(measurement.data),
+    experimentData(:,end+1) = measurement.data(k).values(:);
+    % add error bound values
+    if ~isempty(measurement.data(k).maxvalues) && max(isnan(measurement.data(k).maxvalues))~=1,
+        experimentData(:,end+1) = measurement.data(k).maxvalues(:);
+    end
+    if ~isempty(measurement.data(k).minvalues) && max(isnan(measurement.data(k).minvalues))~=1,
+        experimentData(:,end+1) = measurement.data(k).minvalues(:);
+    end
+end
+dataString = '';
+for k = 1:size(experimentData,1),
+    % Change for accurate printing of low values
+    %dataString = sprintf('%f,',experimentData(k,:));
+    dataString = sprintf('%14.12g,',experimentData(k,:));
+    fprintf(fid,'%s\n',dataString(1:end-1));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Close the file
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fclose(fid);
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/measurementhandling/methods/SBexportXLSmeasurement.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/measurementhandling/methods/SBexportXLSmeasurement.m
new file mode 100644
index 0000000000000000000000000000000000000000..bd392ecc0f255826e6dee97dbb56b4109812b19c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/measurementhandling/methods/SBexportXLSmeasurement.m
@@ -0,0 +1,175 @@
+function [] = SBexportXLSmeasurement(varargin)
+% SBexportXLSmeasurement
+% Exports an SBmeasurement object to an XLS (excel) file.
+% The format of the written XLS file is explained in the user's reference
+% manual and example files can be found in the SBTOOLBOX2/examples folder.
+%
+% USAGE:
+% ======
+% [] = SBexportXLSmeasurement(measurement)
+% [] = SBexportXLSmeasurement(measurement,filename)
+% [] = SBexportXLSmeasurement(measurement,filename,sheet)
+%
+% measurement: SBmeasurement object containing the data
+% filename:    desired filename for XLS file. The extension '.xls' is not
+%              required.
+% sheet:       number of the sheet in the Excel file to which the data
+%              should be written.
+%
+% DEFAULT VALUES:
+% ===============
+% filename: constructed from the data objects name
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+sheet = 1;
+if nargin == 1,
+    measurement = varargin{1};
+    % convert object to structure
+    measurement = struct(measurement);
+    % if no filename provided then use the name of the SBmeasurement object
+    % as filename. Just delete all the special characters.
+    filename = regexprep(measurement.name,'\s','');   % white spaces
+    filename = regexprep(filename,'\W','');    % other
+elseif nargin == 2,
+    measurement = varargin{1};
+    % convert object to structure
+    measurement = struct(measurement);
+    % extract filename from input arguments to skip eventual extension
+    [PATHSTR,filename,EXT] = fileparts(varargin{2});
+elseif nargin == 3,
+    measurement = varargin{1};
+    % convert object to structure
+    measurement = struct(measurement);
+    % extract filename from input arguments to skip eventual extension
+    [PATHSTR,filename,EXT] = fileparts(varargin{2});
+    sheet = varargin{3};
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF OBJECT CONTAINS MEASUREMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+numberComponents = length(measurement.data);
+if numberComponents == 0,
+    error('The object does not contain any measurements');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Construct Cell-Array Matrix of correct size
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+RAW = NaN*ones(4+length(measurement.time),numberComponents+2);
+RAW = num2cell(RAW);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% NAME
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+RAW{1,1} = 'Name';
+RAW{1,2} = measurement.name;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% NOTES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% It seems that matlab requires the entry sizes to be max 911.
+% So lets split them up. Make sure we truncate at a space.
+RAW{2,1} = 'Notes';
+offset = 0;
+if length(measurement.notes) <= 911,
+    RAW{2,2} = measurement.notes;
+else
+    notes = measurement.notes;
+    while length(notes) > 911,
+        index = 911;
+        while double(notes(index)) ~= 32,
+            index = index - 1;
+        end
+        RAW{2+offset,2} = notes(1:index-1);
+        offset = offset + 1;
+        notes = notes(index+1:end);
+    end
+    RAW{2+offset,2} = notes;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% COMPONENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+componentsall = {};
+RAW{4+offset,1} = 'Components';
+RAW{4+offset,2} = 'time';
+index = 3;
+for k=1:numberComponents,
+    RAW{4+offset,index} = measurement.data(k).name;
+    componentsall{end+1} = measurement.data(k).name;
+    index = index+1;
+    % add error bound names
+    if ~isempty(measurement.data(k).maxvalues) && max(isnan(measurement.data(k).maxvalues))~=1,
+        RAW{4+offset,index} = sprintf('%s+',measurement.data(k).name);
+        componentsall{end+1} = sprintf('%s+',measurement.data(k).name);
+        index = index + 1;
+    end
+    if ~isempty(measurement.data(k).minvalues) && max(isnan(measurement.data(k).minvalues))~=1,
+        RAW{4+offset,index} = sprintf('%s-',measurement.data(k).name);
+        componentsall{end+1} = sprintf('%s-',measurement.data(k).name);
+        index = index + 1;
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% COMPONENTNOTES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+RAW{3+offset,1} = 'Componentnotes';
+for k=1:numberComponents,
+    index = strmatchSB(measurement.data(k).name,componentsall,'exact');
+    RAW{3+offset,index+2} = measurement.data(k).notes;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% VALUES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+RAW{5+offset,1} = 'Values';
+RAW(5+offset:5+offset+length(measurement.time)-1,2) = num2cell(measurement.time);
+index = 3;
+for k=1:numberComponents,
+    RAW(5+offset:5+offset+length(measurement.data(k).values)-1,index) = num2cell(measurement.data(k).values);
+    index = index + 1;
+    if ~isempty(measurement.data(k).maxvalues) && max(isnan(measurement.data(k).maxvalues))~=1,
+        RAW(5+offset:5+offset+length(measurement.data(k).values)-1,index) = num2cell(measurement.data(k).maxvalues);
+        index = index + 1;
+    end
+    if ~isempty(measurement.data(k).minvalues) && max(isnan(measurement.data(k).minvalues))~=1,
+        RAW(5+offset:5+offset+length(measurement.data(k).values)-1,index) = num2cell(measurement.data(k).minvalues);
+        index = index + 1;
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% WRITE TO FILE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[success,message] = xlswrite(strcat(filename,'.xls'),RAW,sheet);
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/measurementhandling/methods/auxiliary/SBimportCSVmeasurement.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/measurementhandling/methods/auxiliary/SBimportCSVmeasurement.m
new file mode 100644
index 0000000000000000000000000000000000000000..578cc3de50fa78feaba48e2dd6953f34a433900c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/measurementhandling/methods/auxiliary/SBimportCSVmeasurement.m
@@ -0,0 +1,184 @@
+function [measurementstructure,errorMsg] = SBimportCSVmeasurement(filename)
+% SBimportCSVmeasurement
+% Imports experimental measurement data stored in an CSV (comma separated 
+% value) file into the measurement structure used by the SBmeasurement
+% object. Please note that a special format of the CSV measurement is
+% required. This format is explained in the user's reference manual and
+% example files can be found in the SBTOOLBOX2/examples folder.
+% 
+% filename: name of the .csv file containing the measurement
+%
+% measurementstructure: measurement structure used by SBmeasurement object 
+%                      (empty if error occurred)
+% errorMsg: string containing possible error messages. 
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INITIALIZATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+errorMsg = '';
+measurementstructure = struct(SBmeasurement());
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Open the file and read all its content 
+% Skip the comments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+content = sprintf('\n%s',fileread(filename));
+content = regexprep(content,'\n%[^\n]*','');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Extract the pieces
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Find the starts of the different view data
+nameStart = regexp(content,'\[Name\]');
+notesStart = regexp(content,'\[Notes\]');
+componentsStart = regexp(content,'\[Components\]');
+componentnotesStart = regexp(content,'\[Componentnotes\]');
+valuesStart = regexp(content,'\[Values\]');
+if isempty(nameStart) || isempty(notesStart) || isempty(componentsStart) || isempty(componentnotesStart) || isempty(valuesStart),
+    errorMsg = sprintf('%sAt least one of the identifiers in the measurement file is missing or misspelled.\n',errorMsg);
+end
+% Cut out the different pieces and assign them to the modelTextStructure structure
+nameraw = strtrim(content(nameStart+length('[Name]'):notesStart-1));
+notesraw = strtrim(content(notesStart+length('[Notes]'):componentsStart-1));
+componentsraw = strtrim(content(componentsStart+length('[Components]'):componentnotesStart-1));
+componentnotesraw = strtrim(content(componentnotesStart+length('[Componentnotes]'):valuesStart-1));
+valuesraw = strtrim(content(valuesStart+length('[Values]'):end));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get name
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(nameraw),
+    measurementstructure.name = 'untitled';
+else
+    % just remove special signs that are not allowed for file names.
+    measurementstructure.name = regexprep(nameraw,'\W','');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get notes
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+measurementstructure.notes = notesraw;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get components - check also for timeindex
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% explode the components
+components = explodePCSB(componentsraw);
+% remove spaces from comment names
+for k = 1:length(components),
+    components = regexprep(components,' ','');
+end
+% find 'time' component
+timeindex = strmatchSB('time',components,'exact');
+% initialize help structure for min max values (error bounds) + components
+errorbounddata = struct('name',{},'type',{},'indexvalues',{});
+componentdata = struct('name',{},'indexvalues',{});
+% fill in component names/formulas in structure
+for k=1:length(components),
+    if k ~= timeindex,
+        % check if componentname defines an upper or lower bound
+        if ~isempty(regexp(components{k},'[+]')),
+            % component defines an upper bound
+            errorbounddata(end+1).name = regexprep(components{k},'\W','');
+            errorbounddata(end).type = 'max';
+            errorbounddata(end).indexvalues = k;
+        elseif ~isempty(regexp(components{k},'[-]')),
+            % component defines a lower bound
+            errorbounddata(end+1).name = regexprep(components{k},'\W','');
+            errorbounddata(end).type = 'min';
+            errorbounddata(end).indexvalues = k;
+        else
+            measurementstructure.data(end+1).name = components{k};
+            componentdata(end+1).name = components{k};
+            componentdata(end).indexvalues = k;
+        end
+    end
+end
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get componentnotes
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    
+% parse the componentnotes
+componentnotesall = regexp(componentnotesraw,'([^\n]*)','tokens');
+for k = 1:length(componentnotesall),
+    componentnotesk = componentnotesall{k}{1};
+    % get componentname
+    index = strfind(componentnotesk,':');
+    componentname = componentnotesk(1:index(1)-1);
+    componentnotes = componentnotesk(index(1)+1:end);
+    index = strmatchSB(componentname,{componentdata.name},'exact');
+    if isempty(index),
+        errorMsg = sprintf('%sNote for component ''%s'' defined but the component does not exist.\n',errorMsg,componentname);
+    else
+        if ~isempty(componentnotes),
+            measurementstructure.data(index).notes = strtrim(componentnotes);
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get values and time
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% delete spaces
+values = regexprep(valuesraw,' ','');
+% replace ",," events by ",NaN,"
+values = regexprep(values,',,',',NaN,');
+values = regexprep(values,',,',',NaN,');
+% replace empty elements at the end of each row with ",NaN"
+values = regexprep(values,',\n',',NaN\n');
+valuesmatrix = eval(sprintf('[%s]',values));
+% assign the time vector into the structure
+measurementstructure.time = valuesmatrix(:,timeindex);
+% assign the measurement data into the structure
+for k=1:length(componentdata),
+    measurementstructure.data(k).values = valuesmatrix(:,componentdata(k).indexvalues);
+end
+% assign the error bound data if present (and corresponding component
+% present too ... otherwise warning).
+for k=1:length(errorbounddata),
+    indexcomponent = strmatchSB(errorbounddata(k).name,{componentdata.name},'exact');
+    if isempty(indexcomponent),
+        warning('Component ''%s'' has given error bound but does not exist in the data file.',errorbounddata(k).name);
+    else
+        if strcmp(errorbounddata(k).type,'max'),
+            measurementstructure.data(indexcomponent).maxvalues = valuesmatrix(:,errorbounddata(k).indexvalues);
+        else
+            measurementstructure.data(indexcomponent).minvalues = valuesmatrix(:,errorbounddata(k).indexvalues);
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Fill the nonavailable errorbounds with NaN
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(measurementstructure.data),
+    if isempty(measurementstructure.data(k).minvalues) || isempty(measurementstructure.data(k).maxvalues),
+        measurementstructure.data(k).maxvalues = NaN(size(measurementstructure.data(k).values));
+        measurementstructure.data(k).minvalues = NaN(size(measurementstructure.data(k).values));
+    end
+end
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/measurementhandling/methods/auxiliary/SBimportXLSmeasurement.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/measurementhandling/methods/auxiliary/SBimportXLSmeasurement.m
new file mode 100644
index 0000000000000000000000000000000000000000..1b389c5fde786af99e58f7f1e10cf03389bbfda0
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/measurementhandling/methods/auxiliary/SBimportXLSmeasurement.m
@@ -0,0 +1,277 @@
+function [output,errorMsg] = SBimportXLSdata(filename)
+% SBimportXLSdata
+% Imports experimental measurement data stored in an XLS Excel file
+% into the measurementstructure used by the SBmeasurement object.
+% Please note that a special format of the excel data is required. 
+% This format is explained in the user's reference manual and example 
+% files can be found in the SBTOOLBOX2/examples folder.
+% 
+% filename: name of the .xls file containing the data
+%
+% output: cell-array with data structures used by
+%         SBmeasurement object  (empty if error occurred).
+%         One element of the cell-array corresponds to one
+%         sheet in the excel file.
+% errorMsg: string containing possible error messages. 
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INITIALIZATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+errorMsg = '';
+measurementstructure = struct(SBmeasurement());
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Determine number of sheets
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[typ, dsc] = xlsfinfo(filename);
+nrsheets = length(dsc);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Process one sheet at a time
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output = {};
+for sheet=1:nrsheets,
+    % Read the current sheet
+    warning off;
+    [NUMERIC,TXT,RAW] = xlsread(filename,dsc{sheet});
+    warning on;
+    % Check if current sheet is a valid measurement sheet
+    % to be that it requires 'Name' in A1.
+    if iscell(RAW),
+        testSheet = RAW{1,1};
+        if ischar(testSheet),
+            if strcmp(strtrim(lower(RAW{1,1})),'name'),
+                % Sheet is valid (probably ;))
+                % Process the raw information and fill in the measurement data
+                % structure
+                [output{end+1}, errorMsg] = processData(RAW,sheet,errorMsg);
+            end
+        end
+    end
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Process RAW Data
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [measurementstructure,errorMsg] = processData(RAW,sheet,errorMsg)
+% initialize empty measurement structure
+measurementstructure = struct(SBmeasurement());
+% get size of RAW matrix
+[nrows, ncols] = size(RAW);
+% each identifier needs to appear but only once!
+% furthermore, the identifieres need to appear in the correct order!
+rowName = 0;
+rowNotes = 0;
+rowComponentnotes = 0;
+rowComponents = 0;
+rowValues = 0;
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% get rows of identifiers and check the order
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for row=1:nrows,
+    if ~isnan(RAW{row,1}),
+        if strcmp(strtrim(lower(RAW{row,1})),'name'),
+            rowName = row;
+            if rowNotes+rowComponents+rowComponentnotes+rowValues ~= 0,
+                errorMsg = sprintf('%sIdentifier ''Name'' in sheet %d does not come in correct order.\n',errorMsg,sheet);
+            end
+        end
+        if strcmp(strtrim(lower(RAW{row,1})),'notes'),
+            rowNotes = row;
+            if rowComponents+rowComponentnotes+rowValues ~= 0,
+                errorMsg = sprintf('%sIdentifier ''Notes'' in sheet %d does not come in correct order.\n',errorMsg,sheet);
+            end
+        end
+        if strcmp(strtrim(lower(RAW{row,1})),'componentnotes'),
+            rowComponentnotes = row;
+            if rowComponents + rowValues ~= 0,
+                errorMsg = sprintf('%sIdentifier ''Componentnotes'' in sheet %d does not come in correct order.\n',errorMsg,sheet);
+            end
+        end
+        if strcmp(strtrim(lower(RAW{row,1})),'components'),
+            rowComponents = row;
+            if rowValues ~= 0,
+                errorMsg = sprintf('%sIdentifier ''Components'' in sheet %d does not come in correct order.\n',errorMsg,sheet);
+            end
+        end
+        if strcmp(strtrim(lower(RAW{row,1})),'values'),
+            rowValues = row;
+        end
+        % check if all identifiers found then break the loop
+        if rowName*rowNotes*rowComponents*rowComponentnotes*rowValues ~= 0,
+            break;
+        end
+    end
+end
+% check if all identifiers present
+if rowName*rowNotes*rowComponents*rowComponentnotes*rowValues == 0,
+    errorMsg = sprintf('%sAt least one identifier is missing in in sheet %d.\n',errorMsg,sheet);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Name
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Name only one line but several columns
+name = '';
+for col=2:ncols,
+    if ~isnan(RAW{rowName,col}),
+        if ischar(RAW{rowName,col}),
+            name = sprintf('%s %s',name,RAW{rowName,col});
+        end
+    else
+        break;
+    end
+end
+measurementstructure.name = strtrim(name);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Notes
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Notes several lines and several columns
+notes = '';
+spaceYes = 1;
+for row=rowNotes:rowComponentnotes-1,
+    for col=2:ncols,
+        if ~isnan(RAW{row,col}),
+            if ischar(RAW{row,col}),
+                if spaceYes,
+                    notes = sprintf('%s %s',notes,strtrim(RAW{row,col}));
+                else
+                    notes = sprintf('%s%s',notes,strtrim(RAW{row,col}));
+                    spaceYes = 1;
+                end
+            end
+        end
+    end
+    notes = sprintf('%s\n',strtrim(notes)); 
+    spaceYes = 0;
+end
+measurementstructure.notes = notes;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Components
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+components = {};
+for col = 2:ncols,
+    if ~isnan(RAW{rowComponents,col}),
+        components{end+1} = regexprep(RAW{rowComponents,col},' ','');
+    else
+        break;
+    end
+end
+% find 'time' component
+timeindex = strmatchSB('time',components,'exact');
+% initialize help structure for min max values (error bounds) + components
+errorbounddata = struct('name',{},'type',{},'indexvalues',{});
+componentdata = struct('name',{},'indexvalues',{});
+% fill in component names/formulas in structure
+for k=1:length(components),
+    if k ~= timeindex,
+        % check if componentname defines an upper or lower bound
+        if ~isempty(regexp(components{k},'[+]')),
+            % component defines an upper bound
+            errorbounddata(end+1).name = regexprep(components{k},'\W','');
+            errorbounddata(end).type = 'max';
+            errorbounddata(end).indexvalues = k;
+        elseif ~isempty(regexp(components{k},'[-]')),
+            % component defines a lower bound
+            errorbounddata(end+1).name = regexprep(components{k},'\W','');
+            errorbounddata(end).type = 'min';
+            errorbounddata(end).indexvalues = k;
+        else
+            measurementstructure.data(end+1).name = components{k};
+            componentdata(end+1).name = components{k};
+            componentdata(end).indexvalues = k;
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Componentnotes
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+index = 1;
+for k = 1:length(componentdata)
+    col = componentdata(k).indexvalues+1;
+    if ~isnan(RAW{rowComponentnotes,col}),
+        if ischar(RAW{rowComponentnotes,col}),
+            componentnotes = RAW{rowComponentnotes,col};
+            measurementstructure.data(k).notes = strtrim(componentnotes);
+        end
+    else
+        measurementstructure.data(k).notes = '';
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Values and errorbounds
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% get values matrix
+try
+    valuesmatrix = cell2mat(RAW(rowValues:nrows,2:length(components)+1));
+catch
+    error('Please check the datatypes in the values section of the Excel file.');
+end
+time = valuesmatrix(:,timeindex);
+% check for first occurrence of NaN in time vector ... then cut off.
+indexNaN = find(isnan(time)==1);
+if isempty(indexNaN),
+    numbertimesteps = length(time);
+else
+    numbertimesteps = indexNaN(1)-1;
+end
+measurementstructure.time = time(1:numbertimesteps);
+% assign the measurement data into the structure
+% assign the measurement data into the structure
+for k=1:length(componentdata),
+    measurementstructure.data(k).values = valuesmatrix(1:numbertimesteps,componentdata(k).indexvalues);
+end
+% assign the error bound data if present (and corresponding component
+% present too ... otherwise warning).
+for k=1:length(errorbounddata),
+    indexcomponent = strmatchSB(errorbounddata(k).name,{componentdata.name},'exact');
+    if isempty(indexcomponent),
+        warning('Component ''%s'' has given error bound but does not exist in the data file.',errorbounddata(k).name);
+    else
+        if strcmp(errorbounddata(k).type,'max'),
+            measurementstructure.data(indexcomponent).maxvalues = valuesmatrix(1:numbertimesteps,errorbounddata(k).indexvalues);
+        else
+            measurementstructure.data(indexcomponent).minvalues = valuesmatrix(1:numbertimesteps,errorbounddata(k).indexvalues);
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Fill the nonavailable errorbounds with NaN
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(measurementstructure.data),
+    if isempty(measurementstructure.data(k).minvalues) || isempty(measurementstructure.data(k).maxvalues),
+        measurementstructure.data(k).maxvalues = NaN(size(measurementstructure.data(k).values));
+        measurementstructure.data(k).minvalues = NaN(size(measurementstructure.data(k).values));
+    end
+end
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBalgebraic.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBalgebraic.m
new file mode 100644
index 0000000000000000000000000000000000000000..1aeaa919be910fad846e2a371902b340487ab0d1
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBalgebraic.m
@@ -0,0 +1,48 @@
+function [names,formulas] = SBalgebraic(model)
+% SBalgebraic: Returns information about the algebraic equations in a model.
+%
+% USAGE:
+% ======
+% [names,formulas] = SBalgebraic(model)
+%
+% model: SBmodel or m-file ODE description of model
+%
+% Output Arguments:
+% =================
+% names: cell-array with names of the variables that are determined using
+% algebraic equations.
+% formulas: cell-array with right hand side formula for the algebraic rules
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS SBMODEL OR ODE FILE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isSBmodel(model),
+    sbm = SBstruct(model);
+    names = {sbm.algebraic.name};
+    formulas = {sbm.algebraic.formula};
+else
+    names = feval(model,'algebraic');
+    formulas = {};
+end
+names = names(:);
+formulas = formulas(:);
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBcalcICvector.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBcalcICvector.m
new file mode 100644
index 0000000000000000000000000000000000000000..ef4577ed71c652f9ff995395e97f8486b53269ad
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBcalcICvector.m
@@ -0,0 +1,176 @@
+function [output] = SBcalcICvector(model,varargin)
+% SBcalcICvector: This function determines an IC vector for models with
+% non-numeric initial conditions. These can depend on other initial
+% conditions and on the model parameters. If no new initial conditions or
+% parameters are specified as input arguments to the function the nominal
+% values are used that are stored in the model. Otherwise the information
+% in the additional input arguments is used to determine the new initial
+% conditions. For models with only numeric initial conditions either the
+% ones stored in the model are returned or the ICs provided as input
+% argument are returned. The definition of a parameter vector as input
+% argument will not have an effect in this case.
+%
+% USAGE:
+% ======
+% [output] = SBcalcICvector(model)
+% [output] = SBcalcICvector(model,IC)
+% [output] = SBcalcICvector(model,IC,parametervector)
+%
+% model: SBmodel, ODE, or MEX file model description
+% IC: cell-array with statenames for which to give back the initial
+%   conditions.
+% parametervector: vector with initial conditions to update the model with
+%
+% Output Arguments:
+% =================
+% output: determined numeric initial condition vector
+
+% Information:
+% ============
+% Copyright (C) 2009 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXTRACT SOME INFO FROM THE MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% get the models ICs and statenames
+if isSBmodel(model),
+    ms = struct(model);
+    if hasonlynumericICsSB(model),
+        mics = [ms.states.initialCondition];
+    else
+        mics = {ms.states.initialCondition};
+    end
+    sn = {ms.states.name};    
+else
+    % assume model is an ODE or MEX file
+    % We need to handle ODE and MEX files differently, since ODE files can use 
+    % algebraic expressions, but MEX files can not and this translates to different lengths in the IC vector
+    
+    % Handling MEX models
+    mics = feval(model);
+    sn = feval(model,'states'); 
+    
+    % Append some info if using ODE models and algebraic equations present
+    try
+        % only working for ODE models -  in case of MEX models an error will occurr
+        an = feval(model,'algebraic');
+        for ii = 1:length(an)
+            sn{end+ii} = an{ii};
+        end
+    catch
+        % do nothing in case of MEX models
+    end
+end
+% get the models parameter values
+[pn,pv] = SBparameters(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 1,
+    IC = [];
+    % use the models nominal parameters
+    parametervector = pv;
+elseif nargin == 2,
+    IC = varargin{1};
+    % use the models nominal parameters
+    parametervector = pv;
+elseif nargin == 3,
+    IC = varargin{1};
+    parametervector = varargin{2};
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK INPUTS (IC and parametervector)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(IC) && length(IC) ~= length(mics),
+    error('Length of initial condition vector does not fit the number of states in the model.');
+end
+if ~isempty(parametervector) && length(parametervector) ~= length(pv),
+    error('Length of parameter vector does not fit the number of parameters in the model.');
+end
+if isempty(parametervector),
+    parametervector = pv;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE MODEL WITH NUMERIC ICs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if hasonlynumericICsSB(model),
+    if isempty(IC),
+        % return the nominal initial condition vector in the model
+        output = mics(:);
+        return
+    else
+        % return the initial condition vector provided as input argument
+        output = IC(:);
+        return
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE MODEL WITH NON NUMERIC ICs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% mics is a cell-array, IC a double vector either empty or with new values.
+% the ones corresponding to non-numeric ICs are neglected. 
+% 1) update the mics vector by merging with the IC vector
+if ~isempty(IC),
+    for k=1:length(mics),
+        % do not change the non-numeric ICs
+        if isnumeric(mics{k}),
+            mics{k} = IC(k);
+        end
+    end
+end
+% 2) From now on we only need to handle mics and parametervector. For 
+% uniqueness "parametervector" is renamed to "pv_1a2b3c" and pn to 
+% "pn_1a2b3c", etc.
+pv_1a2b3c = parametervector;
+pn_1a2b3c = pn;
+mics_1a2b3c = mics;
+sn_1a2b3c = sn;
+% 3) define all model parameters (nominal or provided) in the workspace
+for k_1a2b3c = 1:length(pv_1a2b3c),
+    eval(sprintf('%s = pv_1a2b3c(k_1a2b3c);',pn_1a2b3c{k_1a2b3c}));
+end
+% 4) determine the output initial condition vector by evaluating all cells
+% in mics (in the order of mics).
+ic_1a2b3c = [];
+for k_1a2b3c = 1:length(mics_1a2b3c),
+    if isnumeric(mics_1a2b3c{k_1a2b3c}),
+        % if ic entry is numeric then copy it in ic_1a2b3c and 
+        % define the corresponding state in the workspace
+        ic_1a2b3c(end+1) = mics_1a2b3c{k_1a2b3c};
+        eval(sprintf('%s = ic_1a2b3c(end);',sn_1a2b3c{k_1a2b3c}));
+    else
+        % if ic entry is non-numeric then evaluate this entry, store it in
+        % the ic_1a2b3c vector and define the corresponding state in the
+        % workspace
+        try
+            ic_1a2b3c(end+1) = eval(mics_1a2b3c{k_1a2b3c});
+        catch
+            error('Problem with non-numeric initial condition for state ''%s''.\nNOTE: non-numeric ICs are evaluated in a certain order:\n  1) TEXT-models:   order given by the ordering of the ODEs.\n  2) TEXTBC-models: order given by the ordering of the initial conditions.',sn_1a2b3c{k_1a2b3c});
+        end
+        eval(sprintf('%s = ic_1a2b3c(end);',sn_1a2b3c{k_1a2b3c}));
+    end
+end
+% Its done, just return the calculated ic vector
+output = ic_1a2b3c;
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBconvertNonNum2NumIC.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBconvertNonNum2NumIC.m
new file mode 100644
index 0000000000000000000000000000000000000000..be6b73850a3046203d32fe93a39341bcc1c073c0
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBconvertNonNum2NumIC.m
@@ -0,0 +1,58 @@
+function [newmodel] = SBconvertNonNum2NumIC(model)
+% SBconvertNonNum2NumIC: This function converts non-numeric iniital
+% conditions to numeric initial conditions in the model and returns the
+% updated model. Models with numeric ICs are unaffected.
+%
+% USAGE:
+% ======
+% [newmodel] = SBconvertNonNum2NumIC(model)
+%
+% model: SBmodel
+%
+% Output Arguments:
+% =================
+% newmodel: SBmodel where non-numeric ICs have been replaced by numeric ICs
+
+% Information:
+% ============
+% Copyright (C) 2009 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBmodel(model),
+    error('Input argument needs to be an SBmodel.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% NUMERIC ICs ONLY
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if hasonlynumericICsSB(model),
+    newmodel = model;
+    return
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% NON-NUMERIC ICs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+numICs = SBcalcICvector(model);
+ms = struct(model);
+for k=1:length(ms.states),
+    ms.states(k).initialCondition = numICs(k);
+end
+newmodel = SBmodel(ms);
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBcreateTEXTBCmodel.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBcreateTEXTBCmodel.m
new file mode 100644
index 0000000000000000000000000000000000000000..447facb7e650fd6d4fdff2291d2f17f120fdc7cb
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBcreateTEXTBCmodel.m
@@ -0,0 +1,62 @@
+function [] = SBcreateTEXTBCmodel(name,varargin)
+% SBcreateTEXTBCmodel: Creates a new TEXTBC model, saves the corresponding
+% file in the current directory and opens it in the editor, if opening is
+% desired.
+%
+% USAGE:
+% ======
+% SBcreateTEXTBCmodel(name)
+% SBcreateTEXTBCmodel(name,openFlag)
+%
+% name: filename of the model and model name
+% openFlag: decides if the created model is automatically opened in the
+%           editor or not. (=0: do not open, =1: do open)
+%
+% DEFAULT VALUES:
+% ===============
+% openFlag: 1 (do open)
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+openFlag = 1;
+if nargin == 2,
+    openFlag = varargin{1};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CREATE NEW MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+model = SBmodel();
+ms = struct(model);
+ms.name = name;
+model = SBmodel(ms);
+SBcreateTEXTBCfile(model,name);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OPEN IF DESIRED
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if openFlag,
+    edit(strcat(name,'.txtbc'));
+end
+
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBcreateTEXTmodel.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBcreateTEXTmodel.m
new file mode 100644
index 0000000000000000000000000000000000000000..61b54010e6fc1813cea743070b99df1c41fe35be
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBcreateTEXTmodel.m
@@ -0,0 +1,62 @@
+function [] = SBcreateTEXTmodel(name,varargin)
+% SBcreateTEXTmodel: Creates a new TEXT model, saves the corresponding file
+% in the current directory and opens it in the editor, if opening is
+% desired.
+%
+% USAGE:
+% ======
+% SBcreateTEXTmodel(name)
+% SBcreateTEXTmodel(name,openFlag)
+%
+% name: filename of the model and model name
+% openFlag: decides if the created model is automatically opened in the
+%           editor or not. (=0: do not open, =1: do open)
+%
+% DEFAULT VALUES:
+% ===============
+% openFlag: 1 (do open)
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+openFlag = 1;
+if nargin == 2,
+    openFlag = varargin{1};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CREATE NEW MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+model = SBmodel();
+ms = struct(model);
+ms.name = name;
+model = SBmodel(ms);
+SBcreateTEXTfile(model,name);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OPEN IF DESIRED
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if openFlag,
+    edit(strcat(name,'.txt'));
+end
+
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBevents.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBevents.m
new file mode 100644
index 0000000000000000000000000000000000000000..96f7fcac8298ef696b3b2a4b7a369ee5823afdde
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBevents.m
@@ -0,0 +1,64 @@
+function [names,triggers,variables,formulas] = SBevents(model)
+% SBevents: Returns information about the events in an SBmodel.
+%
+% USAGE:
+% ======
+% [names,triggers,variables,formulas] = SBevents(model)
+%
+% model: SBmodel (function can not be used on M-file model)
+%
+% Output Arguments:
+% =================
+% names: cell-array with models event names
+% triggers: cell-array with triggers for the events
+% variables: cell-array with the variables affected by the events
+% formulas: cell-array with the formulas how to affect the variables if an
+%   event is fired
+%
+% The ordering of the elements in the cell-arrays is important. The i-th
+% elements in the output variables belongs to the i-th event.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS SBMODEL OR ODE FILE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp('SBmodel',class(model)),
+    sbm = SBstruct(model);
+    names = {};
+    triggers = {};
+    variables = {};
+    formulas = {};
+    for k = 1:length(sbm.events),
+        names{k} = sbm.events(k).name;
+        triggers{k} = sbm.events(k).trigger;
+        variables{k} = {sbm.events(k).assignment.variable};
+        formulas{k} = {sbm.events(k).assignment.formula};
+    end
+else
+    error('The function can only be used on SBmodels, not on M-file ODE models');
+end
+names = names(:);
+triggers = triggers(:);
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBfunctions.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBfunctions.m
new file mode 100644
index 0000000000000000000000000000000000000000..2c8f17cfccedb8664cf8f5a6a90a7c9c584a6f07
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBfunctions.m
@@ -0,0 +1,59 @@
+function [names,formulas,arguments] = SBfunctions(model)
+% SBfunctions: Returns information about the functions in an SBmodel.
+%
+% USAGE:
+% ======
+% [names,formulas,arguments] = SBfunctions(model)
+%
+% model: SBmodel (function can not be used on M-file model)
+%
+% Output Arguments:
+% =================
+% names: cell-array with models function names
+% formulas: cell-array with formuas for the functions
+% arguments: cell-array with arguments for the functions
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS SBMODEL OR ODE FILE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp('SBmodel',class(model)),
+    sbm = SBstruct(model);
+    if ~isempty(sbm.functions),
+        names = {sbm.functions.name};
+        formulas = {sbm.functions.formula};
+        arguments = {sbm.functions.arguments};
+    else
+        names = {};
+        formulas = {};
+        arguments = {};
+    end
+else
+    error('The function can only be used on SBmodels, not on M-file ODE models');
+end
+names = names(:);
+formulas = formulas(:);
+arguments = arguments(:);
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBfunctionsMATLAB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBfunctionsMATLAB.m
new file mode 100644
index 0000000000000000000000000000000000000000..ea38334af737bf7d89753d9b1aab25f018b57046
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBfunctionsMATLAB.m
@@ -0,0 +1,48 @@
+function [functionsMATLAB] = SBfunctionsMATLAB(model)
+% SBfunctionsMATLAB: Returns information about the MATLAB functions in an
+% SBmodel. 
+%
+% USAGE:
+% ======
+% [functionsMATLAB] = SBfunctionsMATLAB(model)
+%
+% model: SBmodel (function can not be used on M-file model)
+%
+% Output Arguments:
+% =================
+% functionsMATLAB: string containing eventual MATLAB functions defined in
+%   the model.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS SBMODEL OR ODE FILE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp('SBmodel',class(model)),
+    sbm = SBstruct(model);
+    functionsMATLAB = sbm.functionsMATLAB;
+else
+    error('The function can only be used on SBmodels, not on M-file ODE models');
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBinitialconditions.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBinitialconditions.m
new file mode 100644
index 0000000000000000000000000000000000000000..d2484a16a79d5835f2b460ba20bea0f327add78e
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBinitialconditions.m
@@ -0,0 +1,163 @@
+function [output] = SBinitialconditions(model,varargin)
+% SBinitialconditions: This functions does the following:
+%   1) Returns the initial conditions, stored in a model. For models with
+%      numeric initial conditions, these are returned in a vector. For
+%      models with non-numeric initial conditions the ICs are returned in a
+%      cell-array.
+%   2) Same as point 1) but for selected states.
+%   3) Changes the initial conditions in an SBmodel. The non-numeric ICs
+%      are unaffected. Only the numeric ones are changed. Despite that, a
+%      full numeric IC vector needs to be provided, in which the values
+%      corresponding to the non-numeric ICs are arbitrary and have no
+%      meaning.
+%
+% USAGE:
+% ======
+% [ICs] = SBinitialconditions(model)
+% [ICs] = SBinitialconditions(model,statenames) 
+% [model] = SBinitialconditions(model,values) 
+% [model] = SBinitialconditions(model,statenames,values) 
+%
+% model: SBmodel, ODE, or MEX file model description (in the two last cases
+%   the initial conditions can't be set!)
+% statenames: cell-array with statenames for which to give back the initial
+%   conditions.
+% values: vector with initial conditions to update the model with
+%
+% Output Arguments:
+% =================
+% ICs: initial conditions (vector or cell-array)
+% model: SBmodel with changed initial conditions
+
+% Information:
+% ============
+% Copyright (C) 2005-2009 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXTRACT SOME INFO FROM THE MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% get the models ICs and statenames
+if isSBmodel(model),
+    ms = struct(model);
+    if hasonlynumericICsSB(model),
+        ICs = [ms.states.initialCondition];
+    else
+        ICs = {ms.states.initialCondition};
+    end
+    sn = {ms.states.name};
+else
+    % assume model is an ODE or MEX file
+    ICs = feval(model);
+    sn = feval(model,'states');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 1,
+    % simply return the initial conditions for all states
+    output = ICs;
+elseif nargin == 2,
+    % check if values to be changed or ICs for certain states returned
+    if isnumeric(varargin{1}),
+        % change values
+        values = varargin{1};
+        % Check if SBmodel
+        if ~isSBmodel(model),
+            error('Initial conditions can only be changed for SBmodels.');
+        end
+        ms = struct(model);
+        % check length of values vector
+        if length(values) ~= length(ms.states),
+            error('The length of the values vector does not match the number of states in the model.');
+        end
+        % Check if numeric ICs
+        if hasonlynumericICsSB(model),
+            % model has only numeric ICs => simple update
+            cellvalues = mat2cell(values(:)',1,ones(1,length(values)));
+            [ms.states.initialCondition] = deal(cellvalues{:});
+        else
+            % model has non-numeric ICs => update only the numeric values
+            for k=1:length(ms.states),
+                if isnumeric(ms.states(k).initialCondition),
+                    ms.states(k).initialCondition = values(k);
+                end
+            end
+            disp('Please note that only the numeric ICs in the model have been set to the new values.');
+        end            
+
+        % Return the SBmodel with new initial values
+        output = SBmodel(ms);
+    elseif ischar(varargin{1}) || iscell(varargin{1}),
+        % return specific state values
+        statenames = varargin{1};
+        if ischar(statenames),
+            statenames = {statenames};
+        end
+        % check if numeric or non-numeric
+        if iscell(ICs),
+            % non-numeric
+            output = {};
+            for k=1:length(statenames),
+                index = strmatchSB(statenames{k},sn,'exact');
+                if isempty(index),
+                    error('State ''%s'' does not exist in the model.\n',statenames{k});
+                end
+                output{k} = ICs{index};
+            end
+        else
+            % numeric
+            output = [];
+            for k=1:length(statenames),
+                index = strmatchSB(statenames{k},sn,'exact');
+                if isempty(index),
+                    error('State ''%s'' does not exist in the model.\n',statenames{k});
+                end
+                output(k) = ICs(index);
+            end
+        end
+    else
+        error('Incorrect second input argument.');
+    end
+elseif nargin == 3,
+    states = varargin{1};
+    newvalues = varargin{2};
+    if ischar(states),
+        states = {states};
+    end
+    % check if given states exists in model and do the changes
+    modelstruct = SBstruct(model);
+    for k0 = 1:length(states),
+        state = states{k0};
+        newvalue = newvalues(k0);
+        stateIndex = strmatchSB(state,{modelstruct.states.name},'exact');
+        if isempty(stateIndex),
+            error(sprintf('State ''%s'' does not exist in model.\n',state));
+        end
+        if length(stateIndex) > 1,
+            error(sprintf('State ''%s'' is defined %d times.\n',state,length(stateIndex)));
+        end
+        % update state with new value
+        modelstruct.states(stateIndex).initialCondition = newvalue;
+    end
+    model = SBmodel(modelstruct);
+    output = model;    
+else
+    error('Incorrect number of input arguments.');
+end
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBmodelnotes.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBmodelnotes.m
new file mode 100644
index 0000000000000000000000000000000000000000..713e10f3c2c5920c68a770b21185a58c4ba9f8fd
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBmodelnotes.m
@@ -0,0 +1,37 @@
+function notes = SBmodelnotes(model)
+% SBmodelnotes: displays the notes in model.
+%
+% USAGE:
+% ======
+% [notes] = SBmodelnotes(model)
+%
+% model: SBmodel description of model
+%
+% Output Arguments:
+% =================
+% notes: notes, stored in the model
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+% Author: <a href="mailto:antoine.praz@novartis.com">Antoine Praz</a>
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+ms = struct(model);
+notes = ms.notes;
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBoverwriteICs.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBoverwriteICs.m
new file mode 100644
index 0000000000000000000000000000000000000000..fcae752841e06d3fd024c022abb8d1c70587ebd6
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBoverwriteICs.m
@@ -0,0 +1,52 @@
+function [newmodel] = SBoverwriteICs(model,icvector)
+% SBoverwriteICs: This function sets new initial conditions, specified as
+% input argument. If the input model contains non-numeric initial
+% conditions, these are overwritten (in contrast, the function
+% SBinitialconditions only overwrites the ICs that are defined by numerical
+% values).
+%
+% USAGE:
+% ======
+% [newmodel] = SBoverwriteICs(model,icvector)
+%
+% model: SBmodel
+% icvector: numeric vector, defining the new initial conditions for the model
+%
+% Output Arguments:
+% =================
+% newmodel: SBmodel with new initial conditions
+
+% Information:
+% ============
+% Copyright (C) 2009 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBmodel(model),
+    error('First input argument needs to be an SBmodel.');
+end
+if length(icvector) ~= length(SBinitialconditions(model)),
+    error('Provided initial condition vector does not have the correct length.');
+end
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% UPDATE MODEL WITH ICVECTOR
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+newmodel = SBconvertNonNum2NumIC(model);            % convert to numeric
+newmodel = SBinitialconditions(newmodel,icvector);  % then update ics
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBparameters.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBparameters.m
new file mode 100644
index 0000000000000000000000000000000000000000..b8301282bdb1cfd44df4c19489a7d894c0855862
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBparameters.m
@@ -0,0 +1,124 @@
+function [varargout] = SBparameters(model,varargin)
+% SBparameters: Returns information about the parameters in a model, can
+% also be used to set a parameter value.
+%
+% USAGE:
+% ======
+% [names,values] = SBparameters(model)
+% [values] = SBparameters(model,parameters)
+% [model] = SBparameters(model,parameters,newvalues)  (not working for ODE
+% file model)
+%
+% model: SBmodel or m-file ODE description of model
+% parameters: Name of the parameter for which the value is to be returned
+%   or for which a new value is to be set. Alternatively ''parameters'' can
+%   be a cell array, containing several parameter names.
+% newvalues: Vector of new parameter values for parameters defined by
+%   'parameters'
+%
+% Output Arguments:
+% =================
+% names: cell-array with models parameter names
+% values: vector with parameter values
+% model: if parameter value changed then this is the new model
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+errorMsg = '';
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS SBMODEL OR ODE FILE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp('SBmodel',class(model)),
+    sbm = SBstruct(model);
+    if ~isempty(sbm.parameters),
+        names = {sbm.parameters.name};
+        values = [sbm.parameters.value];
+    else
+        names = {};
+        values = {};
+    end
+else
+    if nargin > 2,
+        error('Parameters can not be changed when model is given as ODE file.');
+    end
+    names = feval(model,'parameters');
+    values = feval(model,'parametervalues');
+end
+names = names(:);
+values = values(:);
+
+% return values if information requested
+if nargin == 1,
+    varargout{1} = names;
+    varargout{2} = values;
+elseif nargin == 2,
+    parameters = varargin{1};
+    if ischar(parameters),
+        parameters = {parameters};
+    end
+    % check if given parameters exists in model and do the changes
+    outputvalues = [];
+    for k0 = 1:length(parameters),
+        parameter = parameters{k0};
+        parameterIndex = strmatchSB(parameter,names,'exact');
+        if isempty(parameterIndex),
+            errorMsg = sprintf('%sParameter ''%s'' does not exist in model.\n',errorMsg,parameter);
+        elseif length(parameterIndex) > 1,
+            errorMsg = sprintf('%sParameter ''%s'' is defined %d times.\n',errorMsg,parameter,length(parameterIndex));
+        else
+            outputvalues = [outputvalues values(parameterIndex)];
+        end
+    end
+    varargout{1} = outputvalues(:);
+elseif nargin == 3,
+    parameters = varargin{1};
+    newvalues = varargin{2};
+    if ischar(parameters),
+        parameters = {parameters};
+    end
+    % check if given parameters exists in model and do the changes
+    modelstruct = SBstruct(model);
+    for k0 = 1:length(parameters),
+        parameter = parameters{k0};
+        newvalue = newvalues(k0);
+        parameterIndex = strmatchSB(parameter,{modelstruct.parameters.name},'exact');
+        if isempty(parameterIndex),
+            errorMsg = sprintf('%sParameter ''%s'' does not exist in model.\n',errorMsg,parameter);
+        end
+        if length(parameterIndex) > 1,
+            errorMsg = sprintf('%sParameter ''%s'' is defined %d times.\n',errorMsg,parameter,length(parameterIndex));
+        end
+        % update parameter with new value
+        modelstruct.parameters(parameterIndex).value = newvalue;
+    end
+    model = SBmodel(modelstruct);
+    varargout{1} = model;
+else
+    error('Incorrect number of input arguments.');
+end
+if ~isempty(errorMsg),
+    error(errorMsg);
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBreactions.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBreactions.m
new file mode 100644
index 0000000000000000000000000000000000000000..b6056be27fcbe37293af06a5a7ec66a7aac9f16d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBreactions.m
@@ -0,0 +1,101 @@
+function [names,formulas,reversibleFlag,fastFlag,varargout] = SBreactions(model,varargin)
+% SBreactions: Returns information about the reactions in an SBmodel.
+% If a state vector is passed additionally, the corresponding reaction
+% rates are returned also.
+%
+% USAGE:
+% ======
+% [names,formulas,reversibleFlag,fastFlag] = SBreactions(model)
+% [names,formulas,reversibleFlag,fastFlag,reactionrates] = SBreactions(model,statevector)
+% [names,formulas,reversibleFlag,fastFlag,reactionrates] = SBreactions(model,time,statevector)
+%
+% model: SBmodel (function can not be used on M-file model)
+% statevector: vector with corresponding statevalues
+% time: time instant of the statevector (only needed for time variant
+% systems)
+%
+% DEFAULT VALUES:
+% ===============
+% statevector: not needed 
+% time: 0  (makes no difference for time invariant systems)
+%
+% Output Arguments:
+% =================
+% names: cell-array with models reaction names
+% formulas: cell-array with formuas for the kinetic laws of the reactions
+% reversibleFlag: vector with same number of entries as reactions. An entry
+%   of 0 indicates an irreversible reaction, an entry of 1 indicates a
+%   reversible reaction. The ordering is the same as the reaction names.
+% fastFlag: vector with same number of entries as reactions. An entry
+%   of 1 indicates a fast reaction, an entry of 0 indicates a
+%   reaction that is determined by its kinetic rate law.
+% reactionrates: the reaction rates at the given state and time
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS SBMODEL OR ODE FILE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp('SBmodel',class(model)),
+    sbm = SBstruct(model);
+    if ~isempty(sbm.reactions),
+        names = {sbm.reactions.name};
+        formulas = {sbm.reactions.formula};
+        reversibleFlag = [sbm.reactions.reversible];
+        fastFlag = [sbm.reactions.fast];
+    else 
+        names = {};
+        formulas = {};
+        reversibleFlag = [];
+        fastFlag = [];
+    end
+else
+    error('The function can only be used on SBmodels, not on M-file ODE models');
+end
+names = names(:);
+formulas = formulas(:);
+reversibleFlag = reversibleFlag(:);
+fastFlag = fastFlag(:);
+
+% check if the reaction rates need to be determined:
+if nargin == 2,    
+    statevector = varargin{1};
+    time = 0;
+    % create data file (using SBcreateTempODEfile function)
+    [ODEfctname, ODEfilefullpath, DATAfctname] = SBcreateTempODEfile(model,1);
+    data = feval(DATAfctname, time, statevector);
+    % delete all temporary m files
+    deleteTempODEfileSB(ODEfilefullpath);
+    varargout{1} = data.reactionvalues';
+elseif nargin == 3,
+    time = varargin{1};
+    statevector = varargin{2};
+    % create data file (using SBcreateTempODEfile function)
+    [ODEfctname, ODEfilefullpath, DATAfctname] = SBcreateTempODEfile(model,1);
+    data = feval(DATAfctname, time, statevector);
+    % delete all temporary m files
+    deleteTempODEfileSB(ODEfilefullpath);
+    varargout{1} = data.reactionvalues';
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBstates.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBstates.m
new file mode 100644
index 0000000000000000000000000000000000000000..4b1bcdb21c7a66ad969de8cbf1dec012ddaf3e79
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBstates.m
@@ -0,0 +1,57 @@
+function [names,ODEs,initialConditions] = SBstates(model)
+% SBstates: Returns information about the states in a model.
+%
+% USAGE:
+% ======
+% [names,ODEs,initialConditions] = SBstates(model)
+%
+% model: SBmodel or m-file ODE description of model
+%
+% Output Arguments:
+% =================
+% names: cell-array with models state names
+% ODEs: cell-array with right hand side formula for the states ODE
+%       This output variable is empty if the model is defined by an ODE
+%       file, and non-empty in case the model is defined as an SBmodel
+% initialConditions: vector with initial conditions for states
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS SBMODEL OR ODE FILE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp('SBmodel',class(model)),
+    sbm = SBstruct(model);
+    names = {sbm.states.name};
+    ODEs = {sbm.states.ODE};
+    initialConditions = SBinitialconditions(model);
+else
+    names = feval(model,'states');
+    ODEs = {};
+    initialConditions = SBinitialconditions(model);
+end
+names = names(:);
+ODEs = ODEs(:);
+initialConditions = initialConditions(:);
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBvariables.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBvariables.m
new file mode 100644
index 0000000000000000000000000000000000000000..3a44cc497f6f85de2a878fb03b3896a56aa57ac1
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/SBvariables.m
@@ -0,0 +1,89 @@
+function [names,formulas,varargout] = SBvariables(model,varargin)
+% SBvariables: Returns information about the variables in an SBmodel.
+% If a state vector is passed additionally, the corresponding values of the
+% variables are returned also.
+%
+% USAGE:
+% ======
+% [names,formulas] = SBvariables(model)
+% [names,formulas,variablevalues] = SBvariables(model,statevector)
+% [names,formulas,variablevalues] = SBvariables(model,time,statevector)
+%
+% model: SBmodel (function can not be used on M-file model)
+% statevector: vector with corresponding statevalues
+% time: time instant of the statevector (only needed for time variant
+% systems)
+%
+% DEFAULT VALUES:
+% ===============
+% statevector: not needed 
+% time: 0  (makes no difference for time invariant systems)
+%
+% Output Arguments:
+% =================
+% names: cell-array with models variable names
+% formulas: cell-array with formuals for the variables
+% variablevalues: the values of the variables in the model for the given state and time
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS SBMODEL OR ODE FILE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp('SBmodel',class(model)),
+    sbm = SBstruct(model);
+    if ~isempty(sbm.variables),
+        names = {sbm.variables.name};
+        formulas = {sbm.variables.formula};
+    else
+        names = {};
+        formulas = {};
+    end
+else
+    error('The function can only be used on SBmodels, not on M-file ODE models');
+end
+names = names(:);
+formulas = formulas(:);
+
+% check if the variable values need to be determined:
+if nargin == 2,    
+    statevector = varargin{1};
+    time = 0;
+    % create data file (using SBcreateTempODEfile function)
+    [ODEfctname, ODEfilefullpath, DATAfctname] = SBcreateTempODEfile(model,1);
+    data = feval(DATAfctname, time, statevector);
+    % delete all temporary m files
+    deleteTempODEfileSB(ODEfilefullpath);
+    varargout{1} = data.variablevalues';
+elseif nargin == 3,
+    time = varargin{1};
+    statevector = varargin{2};
+    % create data file (using SBcreateTempODEfile function)
+    [ODEfctname, ODEfilefullpath, DATAfctname] = SBcreateTempODEfile(model,1);
+    data = feval(DATAfctname, time, statevector);
+    % delete all temporary m files
+    deleteTempODEfileSB(ODEfilefullpath);
+    varargout{1} = data.variablevalues';
+end
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/addparameterSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/addparameterSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..97af33cda7637b1dc7fe0db4c5abe413e2a61530
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/addparameterSB.m
@@ -0,0 +1,77 @@
+function [output] = addparameterSB(model,parametername,parametervalue,varargin)
+% addparameterSB: Adds a parameter with given name and given value to the 
+% SBmodel. New parameters are appended at the end of the list.
+%
+% USAGE:
+% ======
+% [output] = addparameterSB(model,parametername,parametervalue)
+% [output] = addparameterSB(model,parametername,parametervalue,parameternotes)
+%
+% model: SBmodel to add the parameter to
+% parametername: name of the parameter to add (check is done to ensure that
+%   the name is not already used).
+% parametervalue: value of the new parameter
+% parameternotes: optional comment about the parameter
+%
+% Output Arguments:
+% =================
+% output: changed model with new parameter included
+
+% Information:
+% ============
+% Copyright (C) 2009  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBmodel(model),
+    error('First input argument is not an SBmodel.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+parameternotes = '';
+if nargin == 4,
+    parameternotes = varargin{1};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK if parametername already exists in the model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modelparamnames = SBparameters(model);
+if ~isempty(strmatchSB(parametername,modelparamnames,'exact')),
+    error('The parameter "%s" does already exist in the model and can not be added again.',parametername);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add the new parameter
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ms = struct(model);
+ms.parameters(end+1).name = parametername;
+ms.parameters(end).value = parametervalue;
+ms.parameters(end).notes = parameternotes;
+ms.parameters(end).type = '';
+ms.parameters(end).compartment = '';
+ms.parameters(end).unittype = '';
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Construct and return new model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output = SBmodel(ms);
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/addreactionrateSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/addreactionrateSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..df17eaac1bb311c1ca558ed65856f49fcecb75e8
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/addreactionrateSB.m
@@ -0,0 +1,75 @@
+function [output] = addreactionrateSB(model, name, formula, notes, reversibleFlag, fastFlag)
+% addreactionrateSB: Allows to add a reaction rate expression to an SBmodel. Only
+% the reaction rate expression is added, the ODE right hand sides are not
+% changed. It is checked if the given reaction rate name already exists
+% and an error is returned if it does.
+%
+% USAGE:
+% ======
+% [output] = addreactionrateSB(model, name, formula, notes, reversibleFlag, fastFlag)
+%
+% model: SBmodel to add the reaction rate to
+% name: name of the reaction rate (string)
+% formula: reaction rate expression (string)
+% notes: eventual notes about the reaction (string)
+% reversibleFlag: 0 = irreversible, 1 = reversible
+% fastFlag: 0 = slow, 1 = fast
+%
+% Output Arguments:
+% =================
+% output: changed model reaction rate added.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS SBMODEL OR ODE FILE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~strcmp('SBmodel',class(model)),
+    error('A reaction rate can not be added to an ODE file.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF reaction name ALREADY EXISTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+reactionsModel = SBreactions(model);
+for k = 1:length(reactionsModel),
+    if strcmp(strtrim(name), strtrim(reactionsModel{k})),
+        error('The reaction rate name %s exists already in the model',name);
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DO THE ADDING
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modelstruct = SBstruct(model);
+reactionsstruct = modelstruct.reactions;
+reactionIndex = length(reactionsstruct)+1;
+reactionsstruct(reactionIndex).name = name;
+reactionsstruct(reactionIndex).formula = formula;
+reactionsstruct(reactionIndex).notes = notes;
+reactionsstruct(reactionIndex).reversible = reversibleFlag;
+reactionsstruct(reactionIndex).fast = fastFlag;
+modelstruct.reactions = reactionsstruct;
+output = SBmodel(modelstruct);
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/cleanmodelSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/cleanmodelSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..70c047d596b07ddba680ecd7886aa2880751c3d2
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/cleanmodelSB.m
@@ -0,0 +1,135 @@
+function [model] = cleanmodelSB(model,varargin)
+% cleanmodelSB: Remove unused reactions, variables and parameters from a model
+%
+% USAGE:
+% ======
+% model = cleanmodelSB(model)
+% model = cleanmodelSB(model,silentflag)
+%
+% model: SBmodel to be cleaned
+% silentflag: =0 stats output on console (default) 
+%             =1 no output on console
+%
+% Output Arguments:
+% =================
+% model:   cleaned SBmodel
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+if nargin == 1,
+    silentflag = 0;
+elseif nargin == 2,
+    silentflag = varargin{1};
+else
+    error('Incorrect number of input arguments.');
+end
+
+removedReactions = {};
+removedVariables = {};
+removedParameters = {};
+
+doclean = 1;
+while doclean,
+    % Creates structure and extracts necessary data
+    sbs = SBstruct(model);
+
+    % extracts information from model
+    [sName, sFormula] = SBstates(model);
+    [vName, vFormula] = SBvariables(model);
+    [rName, rFormula] = SBreactions(model);
+    [pName] = SBparameters(model);
+
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Check ODEs and remove all reactions that do not appear in the ODEs
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    elements = {};
+    for k = 1:length(sFormula)
+        elements = unique(union(elements,regexp(sFormula{k},'\w+','match')));
+    end
+    ism = ismember(rName, elements)';
+removedReactions = {removedReactions{:}, sbs.reactions(~ism).name};
+    sbs.reactions(~ism) = '';
+    nrreactions = sum(ism==0);
+
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Check ODEs, variables, events, and reactions and remove all variables that do not appear
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    elements = {};
+    for k = 1:length(sFormula)
+        elements = unique(union(elements,regexp(sFormula{k},'\w+','match')));
+    end
+    for k = 1:length(vFormula)
+        elements = unique(union(elements,regexp(vFormula{k},'\w+','match')));
+    end
+    for k = 1:length(rFormula)
+        elements = unique(union(elements,regexp(rFormula{k},'\w+','match')));
+    end
+    for k = 1:length(sbs.events),
+        elements = unique(union(elements,regexp(sbs.events(k).trigger,'\w+','match')));
+        for k2 = 1:length(sbs.events(k).assignment),
+            elements = unique(union(elements,regexp(sbs.events(k).assignment(k2).formula,'\w+','match')));
+        end
+    end
+    ism = ismember(vName, elements)';
+removedVariables = {removedVariables{:}, sbs.variables(~ism).name};    
+    sbs.variables(~ism) = '';
+    nrvariables = sum(ism==0);
+
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % Check ODEs, variables, events, and reactions and remove all parameters that do not appear
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    ism = ismember(pName, elements)';
+removedParameters = {removedParameters{:}, sbs.parameters(~ism).name};        
+    sbs.parameters(~ism) = '';
+    nrparameters = sum(ism==0);
+
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % decide if to clean again
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    if nrparameters+nrvariables+nrreactions == 0,
+        doclean = 0;
+    end
+    model = SBmodel(sbs);
+end
+
+if ~silentflag,
+    if ~isempty({removedParameters{:} removedVariables{:} removedReactions{:}}),
+        if ~isempty(removedParameters),
+            disp(sprintf('Removed Parameters: %d',length(removedParameters)));
+            disp('==================');
+            disp(cell2wraptextSB(removedParameters,10));
+            disp(' ');
+        end
+        if ~isempty(removedVariables),
+            disp(sprintf('Removed Variables: %d',length(removedVariables)));
+            disp('=================');
+            disp(cell2wraptextSB(removedVariables,10));
+            disp(' ');
+        end
+        if ~isempty(removedReactions),
+            disp(sprintf('Removed Reactions: %d',length(removedReactions)));
+            disp('=================');
+            disp(cell2wraptextSB(removedReactions,10));
+            disp(' ');
+        end
+    else
+        disp('No unused components in the model');
+    end
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/deleteparametersSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/deleteparametersSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..47e3ec79f742007ad5511b275c8516aa846f214c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/deleteparametersSB.m
@@ -0,0 +1,82 @@
+function [output] = deleteparametersSB(model,parameters)
+% deleteparametersSB: Deletes the given parameters from the model. Will 
+% keep the parameters in the equations.
+%
+% USAGE:
+% ======
+% [output] = deleteparametersSB(model,parameters)
+%
+% model: SBmodel to delete the parameters from 
+% parameters: single parameter (string) or multiple parameters (cell-array)
+%   to delete from model
+%
+% Output Arguments:
+% =================
+% output: changed model without parameter definitions for given parameters
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS SBMODEL OR ODE FILE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~strcmp('SBmodel',class(model)),
+    error('Parameters can not be deleted from ODE file.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF parameters GIVEN AS CELL ARRAY
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ischar(parameters),
+    parameters = {parameters};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DO THE DELETIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modelstruct = SBstruct(model);
+oldparametersstruct = modelstruct.parameters;
+newparametersstruct = struct('name',{},'value',{},'type',{},'compartment',{},'unittype',{},'notes',{});%[];
+parameterIndex = 1;
+for k1 = 1:length(oldparametersstruct),
+    keepParameter = 1;
+    for k2 = 1:length(parameters),
+        if strcmp(oldparametersstruct(k1).name,parameters{k2}),
+            keepParameter = 0;
+            break;
+        end
+    end
+    if keepParameter == 1,
+        newparametersstruct(parameterIndex).name = oldparametersstruct(k1).name;
+        newparametersstruct(parameterIndex).value = oldparametersstruct(k1).value;
+        newparametersstruct(parameterIndex).type = oldparametersstruct(k1).type;
+        newparametersstruct(parameterIndex).compartment = oldparametersstruct(k1).compartment;
+        newparametersstruct(parameterIndex).unittype = oldparametersstruct(k1).unittype;
+        newparametersstruct(parameterIndex).notes = oldparametersstruct(k1).notes;
+        parameterIndex = parameterIndex + 1;
+    end
+end
+modelstruct.parameters = newparametersstruct;
+output = SBmodel(modelstruct);
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/deletereactionratesSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/deletereactionratesSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..7bfc6acb7daa0efdc02a59807f4f05038d30deb6
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/deletereactionratesSB.m
@@ -0,0 +1,82 @@
+function [output] = deletereactionratesSB(model,reactions)
+% deletereactionratesSB: Deletes the given reactions rate expression from
+% an SBmodel. Will keep the names of the reactions in the right hand sides
+% of the ODEs. 
+%
+% USAGE:
+% ======
+% [output] = deletereactionratesSB(model,reactions)
+%
+% model: SBmodel to delete the reactions from 
+% reactions: single reaction name (string) or multiple reaction names (cell-array)
+%   to delete from model
+%
+% Output Arguments:
+% =================
+% output: changed model without reaction definitions for given reactions
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS SBMODEL OR ODE FILE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~strcmp('SBmodel',class(model)),
+    error('Reactions can not be deleted from ODE file.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF reactions GIVEN AS CELL ARRAY
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ischar(reactions),
+    reactions = {reactions};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DO THE DELETIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modelstruct = SBstruct(model);
+oldreactionsstruct = modelstruct.reactions;
+newreactionsstruct = [];
+reactionIndex = 1;
+for k1 = 1:length(oldreactionsstruct),
+    keepReaction = 1;
+    for k2 = 1:length(reactions),
+        if strcmp(oldreactionsstruct(k1).name,reactions{k2}),
+            keepReaction = 0;
+            break;
+        end
+    end
+    if keepReaction == 1,
+        newreactionsstruct(reactionIndex).name = oldreactionsstruct(k1).name;
+        newreactionsstruct(reactionIndex).formula = oldreactionsstruct(k1).formula;
+        newreactionsstruct(reactionIndex).notes = oldreactionsstruct(k1).notes;
+        newreactionsstruct(reactionIndex).reversible = oldreactionsstruct(k1).reversible;
+        newreactionsstruct(reactionIndex).fast = oldreactionsstruct(k1).fast;
+        reactionIndex = reactionIndex + 1;
+    end
+end
+modelstruct.reactions = newreactionsstruct;
+output = SBmodel(modelstruct);
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/getnumberoftypeSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/getnumberoftypeSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..c38f2f0accfe059d80cc571cdd4a8a472970eef1
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/getnumberoftypeSB.m
@@ -0,0 +1,58 @@
+function n = getnumberoftypeSB(model,type)
+% getnumberoftypeSB: retrieve the number counts from SB model
+%
+% USAGE:
+% ======
+% n = getnumberoftypeSB(model,type)
+%
+% model: SBmodel
+% type:  instance type of which the number is to be known (possible values:
+%                       'functions','states:','algebraic','parameters',
+%                       'variables','reactions','events','inputs','outputs')
+%
+% Output Arguments:
+% =================
+% n:	number of instances for the type given
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+% inputs: - model SB model
+%         - typestring: string identifying which type to be counted;
+%         allowed =
+%         {'functions','states:','algebraic','parameters','variables','reac
+%         tions','events','inputs','outputs'}
+
+possibletypes = {'functions','states','algebraic','parameters','variables','reactions','events','inputs','outputs'};
+
+
+if class(model) == 'SBmodel'
+    model_struct = SBstruct(model);
+else
+    error('getnumberoftypeSB:WrongClassOfModel', 'Model not SB model.')
+end
+
+type = lower(type);
+if ~ismember(type,possibletypes)
+    error('getnumberoftypeSB:WrongType', 'Type string does not match possible types.')
+end
+    
+    
+eval(['n = length(model_struct.',type,');']);
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/hasmoietyconservationsSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/hasmoietyconservationsSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..d826a934470efd323fc85a2b2d589df2fb495b11
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/hasmoietyconservationsSB.m
@@ -0,0 +1,40 @@
+function [output] = hasmoietyconservationsSB(model)
+% hasmoietyconservationsSB: Checks if the model contains moiety
+% conservations.
+%
+% Output Arguments:
+% =================
+% output: =1 if MCs present, =0 if not
+
+% Information:
+% ============
+% Copyright (C) 2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+if ~isSBmodel(model),
+    error('Given model is not an SBmodel.');
+end
+
+% default setting
+output = 0; % no MCs present
+% check/determine MCs
+[depVarIndex, depVarConstant, depVarFactor, message] = SBmoietyconservations(model);
+if ~isempty(depVarIndex),
+    % the model seems to contain moiety conservations
+    output = 1;
+end
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/hasonlynumericICsSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/hasonlynumericICsSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..4e7648d308895a0b5de7310bd124c996f80420a9
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/hasonlynumericICsSB.m
@@ -0,0 +1,46 @@
+function [output] = hasonlynumericICsSB(model)
+% hasonlynumericICsSB: Checks if the model contains only numeric initial
+% conditions. The model can be an SBmodel or an ODE or MEX file model.
+%
+% Output Arguments:
+% =================
+% output: =1 if only numeric ICs, =0 if not
+
+% Information:
+% ============
+% Copyright (C) 2009  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+% default setting
+output = 1; % no non-numeric ICs present
+
+if isSBmodel(model),
+    ms = struct(model);
+    for k=1:length(ms.states),
+        if ~isnumeric(ms.states(k).initialCondition),
+            output = 0; % non-numeric ICs present
+            break
+        end
+    end
+else
+    ICs = feval(model);
+    if ~isnumeric(ICs),
+        output = 0;
+    end
+end
+return
+    
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/isparameterSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/isparameterSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..ab23d0bf51fc94b4e4dd30a0be05ebe75e83796b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/isparameterSB.m
@@ -0,0 +1,45 @@
+function [output] = isparameterSB(model,name)
+% isparameterSB: checks if "name" is a parameter in the provided model.
+% This function works both for SBmodels and ODE files. The check is of
+% course case sensitive
+%
+% Output Arguments:
+% =================
+% output: =1 if "name" is a parameter, =0 if not
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+% get all parameters of the model
+allParameters = SBparameters(model);
+
+% check if "name" is a parameter.
+output = 0;
+for k = 1:length(allParameters),
+    if strcmp(strtrim(name),allParameters{k}),
+        output = 1;
+        break;
+    end
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/isreactionSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/isreactionSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..90c120561e1f14ed538a2a61ead85a07750758cd
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/isreactionSB.m
@@ -0,0 +1,49 @@
+function [output] = isreactionSB(model,name)
+% isreactionSB: checks if "name" is a reaction in the provided model.
+% This function works only for SBmodels. The check is of
+% course case sensitive
+%
+% Output Arguments:
+% =================
+% output: =1 if "name" is a reaction, =0 if not
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+if ~strcmp(class(model),'SBmodel'),
+    error('Given model is not an SBmodel.');
+end
+
+% get all reactions of the model
+allReactions = SBreactions(model);
+
+% check if "name" is a reaction.
+output = 0;
+for k = 1:length(allReactions),
+    if strcmp(strtrim(name),allReactions{k}),
+        output = 1;
+        break;
+    end
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/isstateSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/isstateSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..70cf2657e5a7ec5ee5d5ce764324f7f4f36b16c5
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/isstateSB.m
@@ -0,0 +1,45 @@
+function [output] = isstateSB(model,name)
+% isstateSB: checks if "name" is a state in the provided model.
+% This function works both for SBmodels and ODE files. The check is of
+% course case sensitive
+%
+% Output Arguments:
+% =================
+% output: =1 if "name" is a state, =0 if not
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+% get all states of the model
+allStates = SBstates(model);
+
+% check if "name" is a state.
+output = 0;
+for k = 1:length(allStates),
+    if strcmp(strtrim(name),allStates{k}),
+        output = 1;
+        break;
+    end
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/isvariableSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/isvariableSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..4997d1a811f1398b6ec160d367a4616a1658ae1b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/isvariableSB.m
@@ -0,0 +1,49 @@
+function [output] = isvariableSB(model,name)
+% isvariableSB: checks if "name" is a variable in the provided model.
+% This function works only for SBmodels. The check is of
+% course case sensitive
+%
+% Output Arguments:
+% =================
+% output: =1 if "name" is a variable, =0 if not
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+if ~strcmp(class(model),'SBmodel'),
+    error('Given model is not an SBmodel.');
+end
+
+% get all variables of the model
+allVariables = SBvariables(model);
+
+% check if "name" is a variable.
+output = 0;
+for k = 1:length(allVariables),
+    if strcmp(strtrim(name),allVariables{k}),
+        output = 1;
+        break;
+    end
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/nonnumericICserrorSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/nonnumericICserrorSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..8967dbd290e91a5869ff85a9652e24cb14af6b43
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/nonnumericICserrorSB.m
@@ -0,0 +1,31 @@
+function [] = nonnumericICserrorSB(model)
+% nonnumericICserrorSB: returns an error if the model contains
+% non-numeric ICs
+
+% Information:
+% ============
+% Copyright (C) 2009  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+if ~isSBmodel(model),
+    error('Given model is not an SBmodel.');
+end
+
+% check
+if ~hasonlynumericICsSB(model),
+    error('The model contains non-numeric initial conditions. These are not supported by this function.');
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/reactionindexSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/reactionindexSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..d1e31a10452de864713bc589df707ed6cf6b510d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/reactionindexSB.m
@@ -0,0 +1,55 @@
+function [output] = reactionindexSB(model,reactionname)
+% reactionindexSB: returns the number of the reaction 'reactionname' in model
+% 'model'. If the reaction does not exist then [] is returned.
+%
+% Output Arguments:
+% =================
+% output = index of the reaction 'reactionname' in the model.
+%          If 'reactionname' is not a reaction in the model, [] is returned.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+if ischar(reactionname),
+    reactionname = {reactionname};
+end
+
+allreactions = SBreactions(model);
+
+if length(reactionname) == 1,
+    output = strmatchSB(reactionname,allreactions,'exact');
+    if isempty(output),
+        output = [];
+    end
+else    
+    output = [];
+    for k = 1:length(reactionname),
+        index = strmatchSB(reactionname{k},allreactions,'exact');
+        if isempty(index),
+            output(k) = -1;
+        else
+            output(k) = index;
+        end
+    end
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/removedelaySB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/removedelaySB.m
new file mode 100644
index 0000000000000000000000000000000000000000..894e3347e6cd962a2f45712681c0edc953832105
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/removedelaySB.m
@@ -0,0 +1,111 @@
+function [modelnew] = removedelaySB(model)
+% removedelaySB: removes the delay function from the model.
+% This is for example necessary for the determination of the 
+% steady-state. Thus this function is called, e.g., from SBsteadystate
+% in the case that delay functions have been detected in the model.
+%
+% Output Arguments:
+% =================
+% modelnew: model with removed delay function
+
+% Information:
+% ============
+% Copyright (C) 2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+if ~isSBmodel(model),
+    error('Given model is not an SBmodel.');
+end
+
+% get model structure
+ms = struct(model);
+
+% check all ODEs
+for k=1:length(ms.states),
+    ms.states(k).ODE = removeDelay(ms.states(k).ODE);
+end
+    
+% check all variables
+for k=1:length(ms.variables),
+    ms.variables(k).formula = removeDelay(ms.variables(k).formula);
+end
+
+% check all reactions
+for k=1:length(ms.reactions),
+    ms.reactions(k).formula = removeDelay(ms.reactions(k).formula);
+end
+
+% check all event triggers
+for k=1:length(ms.events),
+    ms.events(k).trigger = removeDelay(ms.events(k).trigger);
+end
+
+% check all event assignments
+for k=1:length(ms.events),
+    for k2=1:length(ms.events(k).assignment),
+        ms.events(k).assignment(k2).formula = removeDelay(ms.events(k).assignment(k2).formula);
+    end
+end
+
+% check all functions
+for k=1:length(ms.functions),
+    ms.functions(k).formula = removeDelay(ms.functions(k).formula);
+end
+
+% check MATLAB functions
+ms.functionsMATLAB = removeDelay(ms.functionsMATLAB);
+
+% return new model
+modelnew = SBmodel(ms);
+return
+
+% remove the delaySB function
+function [formula] = removeDelay(formula)
+% first remove the second input argument to delaySB
+count = 1;
+while 1,
+    index = strfind(formula,'delaySB(');
+    if length(index) < count,
+        break;
+    end
+    indexstart = index(count)+length('delaySB(');
+    indexend = indexstart;
+    % search the end of the delay argument definition
+    parOpen = 1;
+    while parOpen ~= 0,
+        if formula(indexend) == '(',
+            parOpen = parOpen + 1;
+        elseif formula(indexend) == ')',
+            parOpen = parOpen - 1;
+        end
+        indexend = indexend + 1;
+    end
+    argument = formula(indexstart:indexend-2);
+    % we only need the first argument
+    terms = explodePCSB(argument,',');
+    argument = terms{1};
+    % reconstruct formula
+    firstpart = formula(1:indexstart-1);
+    lastpart = formula(indexend-1:end);
+    middlepart = argument;
+    formula = char([double(firstpart) double(middlepart) double(lastpart)]);
+    % increase counters
+    count = count + 1;
+end
+% finally remove the delaySB call
+formula = regexprep(formula,'\<delaySB\>','');
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/replaceelementSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/replaceelementSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..667ad0c09bd25b7fc910a9532e0ef7231d184d3b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/replaceelementSB.m
@@ -0,0 +1,89 @@
+function [output] = replaceelementSB(model,oldelements,newelements)
+% replaceelementSB: Replaces a given string by a new string. Replacing is
+% only done in cases where the previous and next character in the code is
+% not a text element (a-z, A-Z, 0-9, _). Elements should ONLY be
+% statenames, reactionnames, variablenames, parameternames.
+%
+% USAGE:
+% ======
+% [output] = replaceelementSB(model,oldelement,newelement)
+%
+% model: SBmodel to replace an element in 
+% oldelements: string containing the name of a parameter, variable,
+%   reaction, state, function, etc. to replace
+%   alternatively a cell array with different old elements can be specified
+% newelements: string containing the new text
+%   alternatively a cell array with different new elements can be specified
+%
+% Output Arguments:
+% =================
+% output: changed model 
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS SBMODEL OR ODE FILE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~strcmp('SBmodel',class(model)),
+    error('In ODE files nothing can be replaced using this function.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK INPUT DATA
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ischar(oldelements),
+    oldelements = {oldelements};
+end
+if ischar(newelements),
+    newelements = {newelements};
+end
+if length(oldelements) ~= length(newelements),
+    error('Same number of old and new elements is required.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONVERT MODEL TO TEXT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modelTextStructure = convertModelToTextSB(model);
+modelText = setPartsToCompleteTextSB(modelTextStructure);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONSTRUCT REPLACE EXPRESSION AND DO REPLACE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+replaceexpression = {};
+for k = 1:length(oldelements),
+    replaceexpression{k} = char([double('\<') double(oldelements{k}) double('\>')]);
+end
+modelText = regexprep(modelText,replaceexpression,newelements);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONVERT TEXT TO MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[SBstructure,errorMsg] = convertTextToModelSB(modelText);
+if ~isempty(errorMsg),
+    error(errorMsg);
+end
+output = SBmodel(SBstructure);
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/stateindexSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/stateindexSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..d493c16d96ab1663f9f76c061363518eb8209c1a
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/stateindexSB.m
@@ -0,0 +1,55 @@
+function [output] = stateindexSB(model,statename)
+% stateindexSB: returns the number of the state 'statename' in model
+% 'model'. If the state does not exist then [] is returned.
+%
+% Output Arguments:
+% =================
+% output = index of the state 'statename' in the model.
+%          If 'statename' is not a state in the model, [] is returned.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+if ischar(statename),
+    statename = {statename};
+end
+
+allstates = SBstates(model);
+
+if length(statename) == 1,
+    output = strmatchSB(statename,allstates,'exact');
+    if isempty(output),
+        output = [];
+    end
+else    
+    output = [];
+    for k = 1:length(statename),
+        index = strmatchSB(statename{k},allstates,'exact');
+        if isempty(index),
+            output(k) = -1;
+        else
+            output(k) = index;
+        end
+    end
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/usealgebraicSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/usealgebraicSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..db09c70afa39a3aa81760b86f3b5341d57918db3
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/usealgebraicSB.m
@@ -0,0 +1,40 @@
+function [output] = usealgebraicSB(model)
+% usealgebraicSB: checks if an SBmodel contains algebraic rules.
+%
+% Output Arguments:
+% =================
+% output: =1 if algebraic rules are used, =0 if not
+
+% Information:
+% ============
+% Copyright (C) 2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+if ~isSBmodel(model),
+    error('Given model is not an SBmodel.');
+end
+
+% default setting
+output = 0; % no algebraic rule present
+
+% get model structure
+ms = struct(model);
+
+% check algebraic rules
+if ~isempty(ms.algebraic),
+    output = 1;
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/usedelaySB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/usedelaySB.m
new file mode 100644
index 0000000000000000000000000000000000000000..afa7b8a94fefaea385ff84bd89cf779c69f65932
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/usedelaySB.m
@@ -0,0 +1,98 @@
+function [output] = usedelaySB(model)
+% usedelaySB: checks if an SBmodel contains the delaySB function.
+%
+% Output Arguments:
+% =================
+% output: =1 if "delaySB" function is present in the model, =0 if not
+
+% Information:
+% ============
+% Copyright (C) 2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+if ~isSBmodel(model),
+    error('Given model is not an SBmodel.');
+end
+
+% default setting
+output = 0; % no delay present
+
+% get model structure
+ms = struct(model);
+
+% check all ODEs
+for k=1:length(ms.states),
+    output = delayPresent(ms.states(k).ODE);
+    if output,
+        return
+    end
+end
+    
+% check all variables
+for k=1:length(ms.variables),
+    output = delayPresent(ms.variables(k).formula);
+    if output,
+        return
+    end
+end
+
+% check all reactions
+for k=1:length(ms.reactions),
+    output = delayPresent(ms.reactions(k).formula);
+    if output,
+        return
+    end
+end
+
+% check all event triggers
+for k=1:length(ms.events),
+    output = delayPresent(ms.events(k).trigger);
+    if output,
+        return
+    end
+end
+
+% check all event assignments
+for k=1:length(ms.events),
+    for k2=1:length(ms.events(k).assignment),
+        output = delayPresent(ms.events(k).assignment(k2).formula);
+        if output,
+            return
+        end
+    end
+end
+
+% check all functions
+for k=1:length(ms.functions),
+    output = delayPresent(ms.functions(k).formula);
+    if output,
+        return
+    end
+end
+
+% check MATLAB functions
+output = delayPresent(ms.functionsMATLAB);
+return
+
+% help function not to have to write it to often
+function [result] = delayPresent(text)
+    if ~isempty(strfind(text,'delaySB')),
+        result = 1;
+    else
+        result = 0;
+    end
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/useeventSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/useeventSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..0ba3044351e6feeb9cbdf2e414b9e9f5d8d60a6b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/useeventSB.m
@@ -0,0 +1,40 @@
+function [output] = useeventSB(model)
+% useeventSB: checks if an SBmodel contains events.
+%
+% Output Arguments:
+% =================
+% output: =1 if events are used, =0 if not
+
+% Information:
+% ============
+% Copyright (C) 2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+if ~isSBmodel(model),
+    error('Given model is not an SBmodel.');
+end
+
+% default setting
+output = 0; % no event present
+
+% get model structure
+ms = struct(model);
+
+% check events
+if ~isempty(ms.events),
+    output = 1;
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/usefastSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/usefastSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..fa45f8b6f2f0d40776181e9610187582ba73ab45
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/usefastSB.m
@@ -0,0 +1,33 @@
+function [output] = usefastSB(model)
+% usefastSB: checks if an SBmodel contains "fast" reactions.
+%
+% Output Arguments:
+% =================
+% output: =1 if reactions with the "fast" flag set are present, =0 if not
+
+% Information:
+% ============
+% Copyright (C) 2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+if ~isSBmodel(model),
+    error('Given model is not an SBmodel.');
+end
+
+ms = struct(model);
+output = ~isempty(find([ms.reactions.fast]==1, 1));
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/variableindexSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/variableindexSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..e44e103049459423ab014d4720417a7267bb5616
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/additional/variableindexSB.m
@@ -0,0 +1,55 @@
+function [output] = variableindexSB(model,variablename)
+% variableindexSB: returns the number of the variable 'variablename' in model
+% 'model'. If the variable does not exist then [] is returned.
+%
+% Output Arguments:
+% =================
+% output = index of the variable 'variablename' in the model.
+%          If 'variablename' is not a variable in the model, [] is returned.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+if ischar(variablename),
+    variablename = {variablename};
+end
+
+allvariables = SBvariables(model);
+
+if length(variablename) == 1,
+    output = strmatchSB(variablename,allvariables,'exact');
+    if isempty(output),
+        output = [];
+    end
+else    
+    output = [];
+    for k = 1:length(variablename),
+        index = strmatchSB(variablename{k},allvariables,'exact');
+        if isempty(index),
+            output(k) = -1;
+        else
+            output(k) = index;
+        end
+    end
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/addpiecewiseeventsSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/addpiecewiseeventsSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..c1d4636a84dba1260553a1ae19a8d1d508876efc
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/addpiecewiseeventsSB.m
@@ -0,0 +1,196 @@
+function [modelout] = addpiecewiseeventsSB(model)
+% addpiecewiseeventsSB: In order to switch pieceswiseSB constructs at
+% precisely the right instants the trigger functions of all piecewise
+% statements in a model are additionally implemented as events with dummy
+% assignments.
+%
+% USAGE:
+% ======
+% [modelout] = addpiecewiseeventsSB(model)       
+%
+% model: SBmodel
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+if ~isSBmodel(model),
+    error('Function only defined for SBmodels.');
+end
+ms = struct(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% FIND ALL PIECEWISE TRIGGERS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+triggers = {};
+% Check in ODEs
+for k=1:length(ms.states),
+    addtriggers = gettrigger(ms.states(k).ODE);
+    triggers = {triggers{:}, addtriggers{:}};
+end
+% Check in variables
+for k=1:length(ms.variables),
+    addtriggers = gettrigger(ms.variables(k).formula);
+    triggers = {triggers{:}, addtriggers{:}};
+end
+% Check in reactions
+for k=1:length(ms.reactions),
+    addtriggers = gettrigger(ms.reactions(k).formula);
+    triggers = {triggers{:}, addtriggers{:}};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CYCLE THROUGH TRIGGERS AND FIND SOME WITH A SPECIAL FORMAT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Format: and(ge/gt(time, xyz),lt/le(time, abc))
+% These triggers are used to implement BOLUS inputs in the SBPOPdosing
+% framework. These event-pulses can be so short that they are not detected
+% by the integrator. Therefor we need to split them up into two events:
+% event1:   ge(time, xyz)
+% event2:   ge(time, abc)    => change from lt(time, abc) to fire correctly
+triggers = handlePulsePiecewiseExpressions(triggers,'andSB<ge<time,(.*)>,lt<time,(.*)>>');
+triggers = handlePulsePiecewiseExpressions(triggers,'andSB<ge<time,(.*)>,le<time,(.*)>>');
+triggers = handlePulsePiecewiseExpressions(triggers,'andSB<gt<time,(.*)>,lt<time,(.*)>>');
+triggers = handlePulsePiecewiseExpressions(triggers,'andSB<gt<time,(.*)>,le<time,(.*)>>');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ADD EVENTS WITH ABOVE TRIGGERS 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(triggers),
+    if ~isempty(ms.states),
+        sn = ms.states(1).name; % used for dummy assignments
+    else
+        sn = ms.parameters(1).name;
+    end
+    for k=1:length(triggers),
+        ms.events(end+1).name = sprintf('piecewise_event_%d',k);
+        ms.events(end).trigger = triggers{k};
+        ms.events(end).assignment(1).variable = sn;
+        ms.events(end).assignment(1).formula = sn;
+        ms.events(end).notes = 'Just a dummy assignment for correct piecewise timing';
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Run through all event triggers and remove double definitions (if same assignments)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get events structure to modify
+eventsOriginal = ms.events;
+% Get all trigger strings
+triggers = {eventsOriginal.trigger};
+% Derive unique trigger strings (ix_unique are the indices of the unique ones that are going to be kept)
+[triggers_unique,ix_unique,J] = unique(triggers);
+% Remove multiple events from the eventsReduced structure
+eventsReduced = eventsOriginal(ix_unique);
+eventsRemoved = eventsOriginal(setdiff(1:length(eventsOriginal),ix_unique));
+% Run through all the eventsReduced triggers and find the event in eventsRemoved and add assignments in eventsRemoved to eventsReduced
+for k=1:length(eventsReduced),
+    assignmentsWhere2Add = eventsReduced(k).assignment;
+    ix = strmatchSB(eventsReduced(k).trigger,{eventsRemoved.trigger},'exact');
+    if ~isempty(ix),
+        assignments2add = eventsRemoved(ix).assignment;
+        % Check if assignments already present (same variable and same formula)
+        ix_assignments2add = [];
+        for k2=1:length(assignments2add),
+            variable = assignments2add(k2).variable;
+            formula  = assignments2add(k2).formula;
+            % Find indices in assignmentsWhere2Add of same variable
+            ix2 = strmatchSB(variable,{assignmentsWhere2Add.variable},'exact');
+            if isempty(ix2),
+                % Not the same variable => add the assignment
+                ix_assignments2add(end+1) = k2;
+            else
+                % If same variable in the assignment then check if same formula. 
+                % If same formula then do not add, if different formula, then error.
+                for k3=1:length(ix2),
+                    % Check if different formula, then error
+                    if ~strcmp(formula,assignmentsWhere2Add(ix2).variable),
+                        error('Different events with same triggers and same assignment variables but different assignment formulas present in the model.');
+                    else
+                        % Do nothing (do not add assignment)
+                    end
+                end
+            end
+        end
+        % Select the assignments to add
+        assignments2add = assignments2add(ix_assignments2add);
+        % Add them
+        eventsReduced(k).assignment = [assignmentsWhere2Add assignments2add];
+    end
+end
+% Add modified events to ms structure
+ms.events = eventsReduced;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% FINISH IT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modelout = SBmodel(ms);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Helpfunction to get the trigger expressions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [triggers] = handlePulsePiecewiseExpressions(triggers,syntax)
+usetriggers = {};
+for k=1:length(triggers),
+    trigger = triggers{k};
+    % replace parentheses by "<" and ">" to use regexp for tokens
+    x = strrep(trigger,'(','<');
+    x = strrep(x,')','>');
+    y = regexp(x,syntax,'tokens');
+    if ~isempty(y),
+        % trigger of special format => replace it by two triggers as shown above
+        trigger1 = y{1}{1};
+        trigger2 = y{1}{2};
+        usetriggers{end+1} = ['ge(time,' trigger1 ')'];
+        usetriggers{end+1} = ['ge(time,' trigger2 ')'];
+    else
+        % if trigger not of special format then just keep the previous trigger
+        usetriggers{end+1} = trigger;
+    end
+end
+% copy back the triggers to right 
+triggers = usetriggers;
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Helpfunction to get the trigger expressions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [trigger] = gettrigger(input)
+trigger = {};
+% find the start indices 
+index = strfind(input,'piecewiseSB');
+% get the triggers
+for k=1:length(index),
+    work = input;
+    work = work(index(k)+12:end);
+    popen = 1; offset = 1;
+    while popen ~= 0,
+        if work(offset) == '(',
+            popen = popen + 1;
+        elseif work(offset) == ')',
+            popen = popen - 1;
+        end
+        offset = offset + 1;
+    end
+    work = work(1:offset-2);
+    % explode elements
+    terms = explodePCSB(work);
+    trigger = {trigger{:} terms{2:2:end}};
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/sbmodel2text/convertModelToTextBCSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/sbmodel2text/convertModelToTextBCSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..a2459955eca4d84b39a7ddda079a805c62a51d7d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/sbmodel2text/convertModelToTextBCSB.m
@@ -0,0 +1,382 @@
+function [modelTextBCStructure] = convertModelToTextBCSB(sbm)
+% convertModelToTextBCSB: Converts an SBmodel to a structure containing the 
+% different parts of the biochemical oriented text description of the
+% model.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+% first check if the complete stoichiometric matrix can be determined.
+% otherwise a biochemical representation is not fully possible and some
+% states still need to be defined by differential equations.
+% determine the names of that states that need to be described by ODEs
+rawFlag = 1;
+silentFlag = 1;
+[N,stateNamesBC] = SBstoichiometry(sbm,rawFlag,silentFlag);
+stateNames = SBstates(sbm);
+stateNamesODE = setdiff(stateNames,stateNamesBC);
+
+% Initialize variables
+modelTextBCStructure = [];
+% Get SBstructure
+SBstructure = SBstruct(sbm);
+% Parse structure into the modelTextBCStructure description
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% define filename used for intermediate saving
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+filename = strcat(tempdirSB,'tempsavingfile.temp');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Name
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modelTextBCStructure.name = SBstructure.name;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Notes
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modelTextBCStructure.notes = SBstructure.notes;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS THE states
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen(filename,'w');
+% first the definition of the states+ODEs that need to be described by ODEs
+for k = 1:length(stateNamesODE),
+    % get index of state name
+    index = strmatchSB(stateNamesODE{k},{SBstructure.states.name},'exact');
+    fprintf(fid,'d/dt(%s) = %s\n',stateNamesODE{k},SBstructure.states(index).ODE);
+end
+if ~isempty(stateNamesODE),
+	fprintf(fid,'\n');
+end
+
+% WRITE OUT ALGEBRAIC RULES
+for k = 1:length(SBstructure.algebraic),
+    if ~isempty(SBstructure.algebraic(k).name),
+        fprintf(fid,'0 = %s : %s\n',SBstructure.algebraic(k).formula,SBstructure.algebraic(k).name);
+    else
+        fprintf(fid,'0 = %s\n',SBstructure.algebraic(k).formula);
+    end
+end
+if ~isempty(SBstructure.algebraic),
+	fprintf(fid,'\n');
+end
+
+% WRITE OUT INITIAL CONDITIONS
+% definition of the initial conditions of the states.
+% additionally for each component optional additional information
+% is processed and written behind the initial conditions.
+% states.type
+% states.compartment
+% states.unittype
+% now construct the states text
+for k = 1:length(SBstructure.states),
+    name = SBstructure.states(k).name;
+    if isnumeric(SBstructure.states(k).initialCondition),
+        fprintf(fid,'%s(0) = %1.6g',name,SBstructure.states(k).initialCondition);
+    else
+        fprintf(fid,'%s(0) = %s',name,SBstructure.states(k).initialCondition);
+    end
+    % construct and the additional information
+    type = strtrim(SBstructure.states(k).type);
+    compartment = strtrim(SBstructure.states(k).compartment);
+    unittype = strtrim(SBstructure.states(k).unittype);
+    % check if all information is given
+    if ~isempty(strfind(lower(type),'specie')),
+        informationText = strcat('{',type,':',compartment,':',unittype,'}');
+    elseif ~isempty(strfind(lower(type),'compartment')),
+        informationText = strcat('{',type,':',compartment,'}');
+    elseif ~isempty(strfind(lower(type),'parameter')),
+        informationText = strcat('{',type,'}');
+    else
+        informationText = '';
+    end
+    fprintf(fid,' %s',informationText);
+    if ~isempty(SBstructure.states(k).notes)
+        fprintf(fid,' %% %s',SBstructure.states(k).notes);
+    end
+    fprintf(fid,'\n');
+end
+% do the same for algebraic variable initial conditions
+for k = 1:length(SBstructure.algebraic),
+    if ~isempty(SBstructure.algebraic(k).name),
+        name = SBstructure.algebraic(k).name;
+        if isnumeric(SBstructure.algebraic(k).initialCondition),
+            fprintf(fid,'%s(0) = %1.6g',name,SBstructure.algebraic(k).initialCondition);
+        else
+            fprintf(fid,'%s(0) = %s',name,SBstructure.algebraic(k).initialCondition);
+        end
+        % construct the additional information
+        type = strtrim(SBstructure.algebraic(k).type);
+        compartment = strtrim(SBstructure.algebraic(k).compartment);
+        unittype = strtrim(SBstructure.algebraic(k).unittype);
+        % check if all information is given
+        if ~isempty(strfind(lower(type),'specie')),
+            informationText = strcat('{',type,':',compartment,':',unittype,'}');
+        elseif ~isempty(strfind(lower(type),'compartment')),
+            informationText = strcat('{',type,':',compartment,'}');
+        elseif ~isempty(strfind(lower(type),'parameter')),
+            informationText = strcat('{',type,'}');
+        else
+            informationText = '';
+        end
+        fprintf(fid,' %s',informationText);
+        if ~isempty(SBstructure.algebraic(k).notes)
+            fprintf(fid,' %% %s',SBstructure.algebraic(k).notes);
+        end
+        fprintf(fid,'\n');
+    end
+end
+% rewind the file and read it out
+fclose(fid); fid = fopen(filename,'r');
+modelTextBCStructure.states = fread(fid,inf,'uint8=>char')';
+fclose(fid);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% add the parameters
+% additionally for each parameter optional additional information
+% is processed and written behind the parameters.
+% parameters.type
+% parameters.compartment
+% parameters.unittype
+fid = fopen(filename,'w');
+for k = 1:length(SBstructure.parameters),
+    fprintf(fid,'%s = %1.6g',SBstructure.parameters(k).name,SBstructure.parameters(k).value);
+    % construct and the additional information
+    type = strtrim(SBstructure.parameters(k).type);
+    compartment = strtrim(SBstructure.parameters(k).compartment);
+    unittype = strtrim(SBstructure.parameters(k).unittype);
+    % check if all information is given
+    if ~isempty(strfind(lower(type),'specie')),
+        informationText = strcat('{',type,':',compartment,':',unittype,'}');
+    elseif ~isempty(strfind(lower(type),'compartment')),
+        informationText = strcat('{',type,':',compartment,'}');
+    elseif ~isempty(strfind(lower(type),'parameter')),
+        informationText = strcat('{',type,'}');
+    else
+        informationText = '';
+    end
+    fprintf(fid,' %s',informationText);
+    if ~isempty(SBstructure.parameters(k).notes)
+        fprintf(fid,' %% %s',SBstructure.parameters(k).notes);
+    end
+    fprintf(fid,'\n');
+end
+% rewind the file and read it out
+fclose(fid); fid = fopen(filename,'r');
+modelTextBCStructure.parameters = fread(fid,inf,'uint8=>char')';
+fclose(fid);
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Variables
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen(filename,'w');
+for k = 1:length(SBstructure.variables),
+    fprintf(fid,'%s = %s',SBstructure.variables(k).name,SBstructure.variables(k).formula);
+    % construct and the additional information
+    type = strtrim(SBstructure.variables(k).type);
+    compartment = strtrim(SBstructure.variables(k).compartment);
+    unittype = strtrim(SBstructure.variables(k).unittype);
+    % check if all information is given
+    if ~isempty(strfind(lower(type),'specie')),
+        informationText = strcat('{',type,':',compartment,':',unittype,'}');
+    elseif ~isempty(strfind(lower(type),'compartment')),
+        informationText = strcat('{',type,':',compartment,'}');
+    elseif ~isempty(strfind(lower(type),'parameter')),
+        informationText = strcat('{',type,'}');
+    else
+        informationText = '';
+    end
+    fprintf(fid,' %s',informationText);
+    if ~isempty(SBstructure.variables(k).notes)
+        fprintf(fid,' %% %s',SBstructure.variables(k).notes);
+    end
+    fprintf(fid,'\n');
+end
+% rewind the file and read it out
+fclose(fid); fid = fopen(filename,'r');
+modelTextBCStructure.variables = fread(fid,inf,'uint8=>char')';
+fclose(fid);
+
+[N, stateNames] = reverseMoietyConservationsSB(sbm);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS THE REACTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Use the stoichiometric matrix determined above (by eventually adding
+% species that are defined by variables)
+% get reaction names, kinetics, and reversibility flag
+[reactionNames,reactionFormulas,reactionRevFlags] = SBreactions(sbm);
+% now the reaction text can be built
+fid = fopen(filename,'w');
+% cycle through the columns of the stoichiometric matrix N to build the 
+% reaction expressions
+for k1 = 1:size(N,2),
+    Ncol = N(:,k1);
+    % first get the substrates by finding the negative elements in Ncol
+    substrateIndices = find(Ncol < 0);
+    % then get the products by finding the positive elements in Ncol
+    productIndices = find(Ncol > 0);
+    % determine the needed information
+    reactionName = reactionNames{k1};
+    reactionRevFlag = reactionRevFlags(k1);
+    reactionFormula = reactionFormulas{k1};
+    substrateNames = stateNames(substrateIndices);
+    productNames = stateNames(productIndices);
+    substrateStoichiometries = abs(Ncol(substrateIndices));
+    productStoichiometries = abs(Ncol(productIndices));
+    % if reversible split up the reaction rate in two parts. if this is not
+    % possible, issue a warning and set the reaction as irreversible
+    if reactionRevFlag ~= 0,
+        irreversibleRates = explodePCSB(reactionFormula,'-');
+        if length(irreversibleRates) ~= 2,
+            % Need to have two parts that are separated by a '-' sign. (Forward
+            % first, then reverse reaction kinetics).
+            warning(sprintf('Reaction ''%s'' is marked reversible but rate expression is not given in the\nrequired format (R = Rf-Rr). The reaction will be treated as irreversible.\n', reactionName));
+            reactionRevFlag = 0;
+        else
+            reactionForward = irreversibleRates{1};
+            reactionReverse = irreversibleRates{2};
+        end
+    end
+    % format the output of the reaction text
+    % first the reaction expression, e.g. 2*A + 4*C => 3*B
+    % the substrates
+    if ~isempty(substrateNames),
+        if substrateStoichiometries(1) ~= 1,
+            fprintf(fid,'%g*%s',substrateStoichiometries(1),substrateNames{1});
+        else
+            fprintf(fid,'%s',substrateNames{1});
+        end
+    end
+    for k2 = 2:length(substrateNames),
+        if substrateStoichiometries(k2) ~= 1,
+            fprintf(fid,'+%g*%s',substrateStoichiometries(k2),substrateNames{k2});
+        else
+            fprintf(fid,'+%s',substrateNames{k2});
+        end
+    end
+    % the reaction equation sign
+    if reactionRevFlag == 0,
+        fprintf(fid,' => ');  % irreversible
+    else
+        fprintf(fid,' <=> '); % reversible
+    end
+    % the products
+    if ~isempty(productNames),
+        if productStoichiometries(1) ~= 1,
+            fprintf(fid,'%g*%s',productStoichiometries(1),productNames{1});
+        else
+            fprintf(fid,'%s',productNames{1});
+        end
+    end
+    for k2 = 2:length(productNames),
+        if productStoichiometries(k2) ~= 1,
+            fprintf(fid,'+%g*%s',productStoichiometries(k2),productNames{k2});
+        else
+            fprintf(fid,'+%s',productNames{k2});
+        end
+    end
+    % separator and reaction name
+    fprintf(fid,' : %s',reactionName); 
+    % fast flag
+    if SBstructure.reactions(k1).fast == 1,
+        fprintf(fid,' {fast}'); 
+    end
+    % notes
+    if ~isempty(SBstructure.reactions(k1).notes),
+        fprintf(fid,' %% %s',SBstructure.reactions(k1).notes);
+    end
+    % new line 
+    fprintf(fid,'\n'); 
+    % now the reaction rate expression(s)
+    if reactionRevFlag == 0,
+        fprintf(fid,'\tvf = %s\n',reactionFormula); 
+    else
+        fprintf(fid,'\tvf = %s\n\tvr = %s\n',reactionForward,reactionReverse); 
+    end
+    % new line after reaction definition
+    fprintf(fid,'\n'); 
+end
+% rewind the file and read it out
+fclose(fid); fid = fopen(filename,'r');
+modelTextBCStructure.reactions = fread(fid,inf,'uint8=>char')';
+fclose(fid);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Functions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen(filename,'w');
+for k = 1:length(SBstructure.functions),
+    fprintf(fid,'%s(%s) = %s',SBstructure.functions(k).name,SBstructure.functions(k).arguments,SBstructure.functions(k).formula);
+    if ~isempty(SBstructure.functions(k).notes)
+        fprintf(fid,' %% %s\n',SBstructure.functions(k).notes);
+    else
+        fprintf(fid,'\n');
+    end
+end
+% rewind the file and read it out
+fclose(fid); fid = fopen(filename,'r');
+modelTextBCStructure.functions = fread(fid,inf,'uint8=>char')';
+fclose(fid);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Events
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen(filename,'w');
+for k = 1:length(SBstructure.events),
+    fprintf(fid,'%s = %s',SBstructure.events(k).name,SBstructure.events(k).trigger);
+    for k2 = 1:length(SBstructure.events(k).assignment),
+        fprintf(fid,',%s,%s',SBstructure.events(k).assignment(k2).variable,SBstructure.events(k).assignment(k2).formula);
+    end
+    if ~isempty(SBstructure.events(k).notes)
+        fprintf(fid,' %% %s\n',SBstructure.events(k).notes);
+    else
+        fprintf(fid,'\n');
+    end
+end
+% rewind the file and read it out
+fclose(fid); fid = fopen(filename,'r');
+modelTextBCStructure.events = fread(fid,inf,'uint8=>char')';
+fclose(fid);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% MATLAB functions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modelTextBCStructure.functionsMATLAB = SBstructure.functionsMATLAB;
+
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DELETE WHITESPACES IN STRINGS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Useful for taking away whitespaces in kineticLaw formulas, as
+% seen in some example models
+function [outputString] = removeWhiteSpace(inputString)
+outputString = strrep(inputString,' ','');
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/sbmodel2text/convertModelToTextSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/sbmodel2text/convertModelToTextSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..ca7bb48bd551e449d23224a4139098c20d9da830
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/sbmodel2text/convertModelToTextSB.m
@@ -0,0 +1,324 @@
+function [modelTextStructure] = convertModelToTextSB(sbm)
+% convertModelToTextSB: Converts an SBmodel to a structure containing the 
+% different parts of the text description of the model. 
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+% Initialize variables
+modelTextStructure = [];
+% Get SBstructure
+SBstructure = SBstruct(sbm);
+% Parse structure into the modelTextStructure description
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% define filename used for intermediate saving
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+filename = strcat(tempdirSB,'tempsavingfile.temp');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Name
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modelTextStructure.name = SBstructure.name;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Notes
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modelTextStructure.notes = SBstructure.notes;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% error variables
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+informationErrorText = '';
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% States and algebraic rules
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen(filename,'w');
+for k = 1:length(SBstructure.states),
+    % Get ODEs
+    fprintf(fid,'d/dt(%s) = %s',SBstructure.states(k).name,SBstructure.states(k).ODE);
+    % construct the additional information (type, compartment, unittype)
+    type = SBstructure.states(k).type;
+    compartment = SBstructure.states(k).compartment;
+    unittype = SBstructure.states(k).unittype;
+    if ~isempty(type) || ~isempty(compartment) || ~isempty(unittype),
+        % at least one information present
+        if ~isempty(strfind(lower(type),'specie')),
+            % all three information fields need to be written out
+            informationText = strcat('{',type,':',compartment,':',unittype,'}');
+        elseif ~isempty(strfind(lower(type),'parameter')),
+            % just the type
+            informationText = strcat('{',type,'}');
+        elseif ~isempty(strfind(lower(type),'compartment')),
+            % type and compartment
+            informationText = strcat('{',type,':',compartment,'}');
+        else
+            % error
+            informationErrorText = sprintf('%sType information for state ''%s'' seems to be wrong.\n',informationErrorText,SBstructure.states(k).name);
+        end
+    else
+        % no text needed, since no information provided
+        informationText = '';
+    end
+    % add information text
+    fprintf(fid,' %s',informationText);    
+    % add eventual notes
+    if ~isempty(SBstructure.states(k).notes)
+        fprintf(fid,' %%%s',SBstructure.states(k).notes);
+    end
+    % add line break
+    fprintf(fid,'\n');
+end
+% WRITE OUT ALGEBRAIC RULES
+for k = 1:length(SBstructure.algebraic),
+    if ~isempty(SBstructure.algebraic(k).name),
+        fprintf(fid,'\n0 = %s : %s',SBstructure.algebraic(k).formula,SBstructure.algebraic(k).name);
+    else
+        fprintf(fid,'\n0 = %s',SBstructure.algebraic(k).formula);
+    end
+    % construct the additional information (type, compartment, unittype)
+    type = SBstructure.algebraic(k).type;
+    compartment = SBstructure.algebraic(k).compartment;
+    unittype = SBstructure.algebraic(k).unittype;
+    if ~isempty(type) || ~isempty(compartment) || ~isempty(unittype),
+        % at least one information present
+        if ~isempty(strfind(lower(type),'specie')),
+            % all three information fields need to be written out
+            informationText = strcat('{',type,':',compartment,':',unittype,'}');
+        elseif ~isempty(strfind(lower(type),'parameter')),
+            % just the type
+            informationText = strcat('{',type,'}');
+        elseif ~isempty(strfind(lower(type),'compartment')),
+            % type and compartment
+            informationText = strcat('{',type,':',compartment,'}');
+        else
+            % error
+            informationErrorText = sprintf('%sType information for algebraic rule ''%s'' seems to be wrong.\n',informationErrorText,SBstructure.algebraic(k).name);
+        end
+    else
+        % no text needed, since no information provided
+        informationText = '';
+    end
+    % add information text
+    fprintf(fid,' %s',informationText);    
+    % add notes if present
+    if ~isempty(SBstructure.algebraic(k).notes),
+        fprintf(fid,' %% %s',SBstructure.algebraic(k).notes);
+    end    
+end
+if ~isempty(SBstructure.algebraic),
+	fprintf(fid,'\n');
+end
+% WRITE OUT INITIAL CONDITIONS
+% states
+for k = 1:length(SBstructure.states),
+    if isnumeric(SBstructure.states(k).initialCondition),
+        fprintf(fid,'\n%s(0) = %1.6g',SBstructure.states(k).name,SBstructure.states(k).initialCondition);
+    else
+        fprintf(fid,'\n%s(0) = %s',SBstructure.states(k).name,SBstructure.states(k).initialCondition);
+    end
+end
+% algebraic variables
+for k = 1:length(SBstructure.algebraic),
+    if ~isempty(SBstructure.algebraic(k).name),
+        if isnumeric(SBstructure.algebraic(k).initialCondition),
+            fprintf(fid,'\n%s(0) = %1.6g',SBstructure.algebraic(k).name,SBstructure.algebraic(k).initialCondition);
+        else
+            fprintf(fid,'\n%s(0) = %s',SBstructure.algebraic(k).name,SBstructure.algebraic(k).initialCondition);
+        end
+    end
+end
+% rewind the file and read it out
+fclose(fid); fid = fopen(filename,'r');
+modelTextStructure.states = fread(fid,inf,'uint8=>char')';
+fclose(fid);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen(filename,'w');
+for k = 1:length(SBstructure.parameters),
+    fprintf(fid,'%s = %1.6g',SBstructure.parameters(k).name,SBstructure.parameters(k).value);
+    % construct the additional information (type, compartment, unittype)
+    type = SBstructure.parameters(k).type;
+    compartment = SBstructure.parameters(k).compartment;
+    unittype = SBstructure.parameters(k).unittype;
+    if ~isempty(type) || ~isempty(compartment) || ~isempty(unittype),
+        % at least one information present
+        if ~isempty(strfind(lower(type),'specie')),
+            % all three information fields need to be written out
+            informationText = strcat('{',type,':',compartment,':',unittype,'}');
+        elseif ~isempty(strfind(lower(type),'parameter')),
+            % just the type
+            informationText = strcat('{',type,'}');
+        elseif ~isempty(strfind(lower(type),'compartment')),
+            % type and compartment
+            informationText = strcat('{',type,':',compartment,'}');
+        else
+            % error
+            informationErrorText = sprintf('%sType information for parameter ''%s'' seems to be wrong.\n',informationErrorText,SBstructure.parameters(k).name);
+        end
+    else
+        % no text needed, since no information provided
+        informationText = '';
+    end
+    % add information text
+    fprintf(fid,' %s',informationText);    
+    % add eventual notes
+    if ~isempty(SBstructure.parameters(k).notes)
+        fprintf(fid,' %%%s',SBstructure.parameters(k).notes);
+    end
+    % add a line break
+    fprintf(fid,'\n');
+end
+% rewind the file and read it out
+fclose(fid); fid = fopen(filename,'r');
+modelTextStructure.parameters = fread(fid,inf,'uint8=>char')';
+fclose(fid);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Variables
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen(filename,'w');
+for k = 1:length(SBstructure.variables),
+    fprintf(fid,'%s = %s',SBstructure.variables(k).name,SBstructure.variables(k).formula);
+    % construct the additional information (type, compartment, unittype)
+    type = SBstructure.variables(k).type;
+    compartment = SBstructure.variables(k).compartment;
+    unittype = SBstructure.variables(k).unittype;
+    if ~isempty(type) || ~isempty(compartment) || ~isempty(unittype),
+        % at least one information present
+        if ~isempty(strfind(lower(type),'specie')),
+            % all three information fields need to be written out
+            informationText = strcat('{',type,':',compartment,':',unittype,'}');
+        elseif ~isempty(strfind(lower(type),'parameter')),
+            % just the type
+            informationText = strcat('{',type,'}');
+        elseif ~isempty(strfind(lower(type),'compartment')),
+            % type and compartment
+            informationText = strcat('{',type,':',compartment,'}');
+        else
+            % error
+            informationErrorText = sprintf('%sType information for variable ''%s'' seems to be wrong.\n',informationErrorText,SBstructure.variables(k).name);
+        end
+    else
+        % no text needed, since no information provided
+        informationText = '';
+    end
+    % add information text
+    fprintf(fid,' %s',informationText);    
+    % add eventual notes
+    if ~isempty(SBstructure.variables(k).notes)
+        fprintf(fid,' %%%s',SBstructure.variables(k).notes);
+    end
+    % add a line break
+    fprintf(fid,'\n');
+end
+% rewind the file and read it out
+fclose(fid); fid = fopen(filename,'r');
+modelTextStructure.variables = fread(fid,inf,'uint8=>char')';
+fclose(fid);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check information text error
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(informationErrorText),
+    error(informationErrorText);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Reactions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen(filename,'w');
+for k = 1:length(SBstructure.reactions),
+    fprintf(fid,'%s = %s',SBstructure.reactions(k).name,SBstructure.reactions(k).formula);
+    if SBstructure.reactions(k).reversible == 1,
+        fprintf(fid,' {reversible}');
+    end
+    if SBstructure.reactions(k).fast == 1,
+        fprintf(fid,' {fast}');
+    end
+    if ~isempty(SBstructure.reactions(k).notes)
+        fprintf(fid,' %%%s\n',SBstructure.reactions(k).notes);
+    else
+        fprintf(fid,'\n');
+    end
+end
+% rewind the file and read it out
+fclose(fid); fid = fopen(filename,'r');
+modelTextStructure.reactions = fread(fid,inf,'uint8=>char')';
+fclose(fid);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Functions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen(filename,'w');
+for k = 1:length(SBstructure.functions),
+    fprintf(fid,'%s(%s) = %s',SBstructure.functions(k).name,SBstructure.functions(k).arguments,SBstructure.functions(k).formula);
+    if ~isempty(SBstructure.functions(k).notes)
+        fprintf(fid,' %%%s\n',SBstructure.functions(k).notes);
+    else
+        fprintf(fid,'\n');
+    end
+end
+% rewind the file and read it out
+fclose(fid); fid = fopen(filename,'r');
+modelTextStructure.functions = fread(fid,inf,'uint8=>char')';
+fclose(fid);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Events
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen(filename,'w');
+for k = 1:length(SBstructure.events),
+    fprintf(fid,'%s = %s',SBstructure.events(k).name,SBstructure.events(k).trigger);
+    for k2 = 1:length(SBstructure.events(k).assignment),
+        fprintf(fid,',%s,%s',SBstructure.events(k).assignment(k2).variable,SBstructure.events(k).assignment(k2).formula);
+    end
+    if ~isempty(SBstructure.events(k).notes)
+        fprintf(fid,' %%%s\n',SBstructure.events(k).notes);
+    else
+        fprintf(fid,'\n');
+    end
+end
+% rewind the file and read it out
+fclose(fid); fid = fopen(filename,'r');
+modelTextStructure.events = fread(fid,inf,'uint8=>char')';
+fclose(fid);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% MATLAB functions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+modelTextStructure.functionsMATLAB = SBstructure.functionsMATLAB;
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DELETE WHITESPACES IN STRINGS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Useful for taking away whitespaces in kineticLaw formulas, as
+% seen in some example models
+function [outputString] = removeWhiteSpace(inputString)
+outputString = strrep(inputString,' ','');
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/sbmodel2text/reverseMoietyConservationsSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/sbmodel2text/reverseMoietyConservationsSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..c202933997ed1173eeebc3758be6687003ae551c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/sbmodel2text/reverseMoietyConservationsSB.m
@@ -0,0 +1,159 @@
+function [N,stateNames] = reverseMoietyConservationsSB(sbm,varargin)
+% reverseMoietyConservationsSB: Function searching for moietyconservations
+% in the system. Then an augmented stoichiometric matrix is calculated in 
+% which also the species determined by moiety conservations appear.
+%
+% input arguments: sbm, specieFlag (optional)
+% if the flag is set only variables that are species will be considered
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+specieFlag = 0;
+if nargin == 2,
+    specieFlag = varargin{1};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET INFORMATION ABOUT EVENTUAL MOIETY CONSERVATIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% This is done by searching all variables for a variable defined in the
+% format of:    VARIABLE = PARAMETER - factor*STATE ... - factor*STATE ... - factor*STATE 		
+% Then it is assumed that VARIABLE + factor*STATE + ... is a conserved moiety and
+% stored as such for later use. The "factor*" is optional but if existent
+% has to be numerical.
+
+if ~specieFlag,
+    % just consider all variables
+    [allVariables, allVariableFormulas] = SBvariables(sbm);
+else
+    allVariables = {};
+    allVariableFormulas = {};
+    sbmstruct = struct(sbm);
+    for k=1:length(sbmstruct.variables),
+        if strcmp(sbmstruct.variables(k).type,'isSpecie'),
+            allVariables{end+1} = sbmstruct.variables(k).name;
+            allVariableFormulas{end+1} = sbmstruct.variables(k).formula;
+        end
+    end
+end
+
+moietyconservations = [];
+indexMC = 1;
+for k1 = 1:length(allVariables),
+    variableFormula = allVariableFormulas{k1};
+    terms = explodePCSB(variableFormula,'-');
+    if length(terms) > 1,
+        % process the terms only in the case that there are more than one single term.
+        % first check if the first term is composed only of a parameter
+        % name or a numeric value
+        firstTerm = strtrim(terms{1});
+        if isparameterSB(sbm,firstTerm) || ~isempty(str2num(firstTerm)),
+            % only continue if first term was a parameter
+            % now cycle through the remaining terms and check if they 
+            % are states or factor*states
+            formatCorrect = 1;
+            listofstates = {};  % list of states in conservation
+            listoffactors = []; % list of factors in conservation
+            indexstates = 1;
+            for k2 = 2:length(terms),
+                checkStateTerms = explodePCSB(terms{k2},'*');
+                % only accept lengths 1 or 2 (possibly with or without
+                % factor) otherwise break
+                if length(checkStateTerms) == 1,
+                    if isstateSB(sbm,strtrim(checkStateTerms{1})),
+                        % yes, state found => add it to the list
+                        listofstates{indexstates} = strtrim(checkStateTerms{1});
+                        listoffactors(indexstates) = 1;
+                        indexstates = indexstates + 1;
+                    else
+                        formatCorrect = 0;
+                        break;
+                    end
+                elseif length(checkStateTerms) == 2,
+                    % second term needs to be a state
+                    % if this is the case the first term needs to be
+                    % numeric
+                    if isstateSB(sbm,strtrim(checkStateTerms{2})),
+                        % yes, state found => check if first term is
+                        % numeric
+                        value = str2num(checkStateTerms{1});
+                        if ~isempty(value),
+                            listofstates{indexstates} = strtrim(checkStateTerms{2});
+                            listoffactors(indexstates) = value;
+                            indexstates = indexstates + 1;
+                        else
+                            formatCorrect = 0;
+                            break;
+                        end
+                    else
+                        formatCorrect = 0;
+                        break;
+                    end
+                else
+                    formatCorrect = 0;
+                    break;
+                end
+            end
+            % if formatCorrect = 1 use it as moiety conservation
+            if formatCorrect == 1,
+                % it has the right format for defining a moiety
+                % conservation => accept it
+                moietyconservations(indexMC).variablename = allVariables{k1};
+                moietyconservations(indexMC).states = listofstates;
+                moietyconservations(indexMC).factors = listoffactors;
+                indexMC = indexMC + 1;
+            end
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONVERT A NONSINGULAR SYSTEM TO A SINGULAR IN CASE OF MOIETY CONSERVATIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% first get the stoichiometric matrix of the system
+% Determine the stoichiometric matrix and the state names
+[N,stateNames] = SBstoichiometry(sbm,1,1);
+% now differentiate the moietyconservations and add the components defined
+% by variables to the stoichiometric matrix
+for k1 = 1:length(moietyconservations),
+    % construct the row for the stoichiometric matrix, belonging to the variable
+    Nrownew = zeros(1,length(SBreactions(sbm)));
+    for k2 = 1:length(moietyconservations(k1).states),
+        name = moietyconservations(k1).states{k2};
+        % find the index of the statename
+        stateIndex = strmatchSB(name,stateNames,'exact');
+        % get its row of the stoichiometric matrix multiplied by the factor
+        % of the state in the moiety conservation and substract from
+        % Nrownew
+        Nrownew = Nrownew - moietyconservations(k1).factors(k2)*N(stateIndex,:);
+    end
+    % add species to stateNames (its not a state in the original model but
+    % in the singular version that is constructed now)
+    stateNames{end+1} = moietyconservations(k1).variablename;
+    % add new row to N
+    N = [N; Nrownew];
+end
+
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/sbmodel2text/setPartsToCompleteTextBCSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/sbmodel2text/setPartsToCompleteTextBCSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..7c1061b6feea00afc0c822b21a10ff656043da0e
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/sbmodel2text/setPartsToCompleteTextBCSB.m
@@ -0,0 +1,37 @@
+function [completeTextBC] = setPartsToCompleteTextBCSB(modelTextStructureBC)
+% setPartsToCompleteTextBCSB: Sets the different parts of a biochemical
+% oriented text description of an SBmodel together to the complete text
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+completeTextBC = sprintf('********** MODEL NAME\n%s\n',modelTextStructureBC.name);
+completeTextBC = sprintf('%s\n********** MODEL NOTES\n%s\n',completeTextBC,modelTextStructureBC.notes);
+completeTextBC = sprintf('%s\n********** MODEL STATE INFORMATION\n%s\n',completeTextBC,modelTextStructureBC.states);
+completeTextBC = sprintf('%s\n********** MODEL PARAMETERS\n%s\n',completeTextBC,modelTextStructureBC.parameters);
+completeTextBC = sprintf('%s\n********** MODEL VARIABLES\n%s\n',completeTextBC,modelTextStructureBC.variables);
+completeTextBC = sprintf('%s\n********** MODEL REACTIONS\n%s\n',completeTextBC,modelTextStructureBC.reactions);
+completeTextBC = sprintf('%s\n********** MODEL FUNCTIONS\n%s\n',completeTextBC,modelTextStructureBC.functions);
+completeTextBC = sprintf('%s\n********** MODEL EVENTS\n%s\n',completeTextBC,modelTextStructureBC.events);
+completeTextBC = sprintf('%s\n********** MODEL MATLAB FUNCTIONS\n%s\n',completeTextBC,modelTextStructureBC.functionsMATLAB);
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/sbmodel2text/setPartsToCompleteTextSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/sbmodel2text/setPartsToCompleteTextSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..8e090bc8dc2b79f03e4c56ed395b50f1302be6fa
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/sbmodel2text/setPartsToCompleteTextSB.m
@@ -0,0 +1,38 @@
+function [completeText] = setPartsToCompleteTextSB(modelTextStructure)
+% setPartsToCompleteTextSB: Sets the different parts of a text description
+% of an SBmodel together to the complete text
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+completeText = sprintf('********** MODEL NAME\n%s\n',modelTextStructure.name);
+completeText = sprintf('%s\n********** MODEL NOTES\n%s\n',completeText,modelTextStructure.notes);
+completeText = sprintf('%s\n********** MODEL STATES\n%s\n',completeText,modelTextStructure.states);
+completeText = sprintf('%s\n********** MODEL PARAMETERS\n%s\n',completeText,modelTextStructure.parameters);
+completeText = sprintf('%s\n********** MODEL VARIABLES\n%s\n',completeText,modelTextStructure.variables);
+completeText = sprintf('%s\n********** MODEL REACTIONS\n%s\n',completeText,modelTextStructure.reactions);
+completeText = sprintf('%s\n********** MODEL FUNCTIONS\n%s\n',completeText,modelTextStructure.functions);
+completeText = sprintf('%s\n********** MODEL EVENTS\n%s\n',completeText,modelTextStructure.events);
+completeText = sprintf('%s\n********** MODEL MATLAB FUNCTIONS\n%s\n',completeText,modelTextStructure.functionsMATLAB);
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/text2sbmodel/convertTextBCToModelSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/text2sbmodel/convertTextBCToModelSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..0c40476473e78d352e66e2d66e89417796470466
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/text2sbmodel/convertTextBCToModelSB.m
@@ -0,0 +1,1116 @@
+function [SBstructure,errorMsg] = convertTextBCToModelSB(modelTextBC)
+% convertTextBCToModelSB: Converts a biochemiccaly oriented text description 
+% of an SBmodel to the internal data structure representation.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+% initialize variables
+errorMsg = '';
+errorFunctions = '';
+errorStates = '';
+errorParameters = '';
+errorVariables = '';
+errorReactions = '';
+errorEvents = '';
+
+SBstructure = struct(SBmodel());
+
+% cut text into pieces
+modelTextBCStructure = getPartsFromCompleteTextBCSB(modelTextBC);
+
+% First the standard parts are parsed and put into the model structure.
+% This means: name, notes, functions, parameters, events, and MATLAB functions
+% State information and reactions need to be considered together and need
+% the information about parameters and variables to handle boundary
+% species, constant species, etc.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%% Name
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBstructure.name = removeCharacters(modelTextBCStructure.name);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%% Notes
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBstructure.notes = strtrim(removeCharacters2(modelTextBCStructure.notes));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%% Functions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try
+    [SBfunctions, errorFunctions] = getFunctions(modelTextBCStructure.functions);
+catch
+    error('%sPlease check the syntax of the ''Functions'' definitions.\n',errorMsg);
+end
+if ~isempty(errorFunctions),
+    errorMsg = sprintf('%s%s\n',errorMsg,errorFunctions);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%% Parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try
+    [SBparameters, errorParameters] = getParameters(modelTextBCStructure.parameters);
+catch
+    error('%sPlease check the syntax of the ''Parameter'' definitions (No "=" characters allowed in comment).\n',errorMsg);
+end
+if ~isempty(errorParameters),
+    errorMsg = sprintf('%s%s\n',errorMsg,errorParameters);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%% Variables
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try
+    [SBvariables, errorVariables] = getVariables(modelTextBCStructure.variables);
+catch
+    error('%sPlease check the syntax of the ''Variables'' definitions.\n',errorMsg);
+end
+if ~isempty(errorVariables),
+    errorMsg = sprintf('%s%s\n',errorMsg,errorVariables);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%% Events
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try
+    [SBevents, errorEvents] = getEvents(modelTextBCStructure.events);
+catch
+    error('%sPlease check the syntax of the ''Events'' definitions.\n',errorMsg);
+end
+if ~isempty(errorEvents),
+    errorMsg = sprintf('%s%s\n',errorMsg,errorEvents);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%% MATLAB functions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBfunctionsMATLAB = modelTextBCStructure.functionsMATLAB;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PARSING OF REACTIONS 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% parse reaction expressions and make a list of all species and reaction
+% information to be used to construct the ODEs
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% 1) parse reaction expressions, use ':' as indicator of reactions. this
+% means then that ':' is not allowed in any comment
+% use vf= and vr= for indicators of reaction rate expressions
+reactions = modelTextBCStructure.reactions;
+SBreactions = struct('name',{},'formula',{},'notes',{},'reversible',{},'fast',{});
+% get the starting indices for the reactions by finding the index
+% of the last '\n' before the ':' for each reaction
+reactionsStart = [];
+temp = strfind(reactions,':');
+for k = 1:length(temp),
+    % add a line break in the beginning since the first reaction might
+    % not have one in front of it
+    temp2 = [10 double(reactions(1:temp(k)))];
+    temp3 = find(temp2==10);
+    reactionsStart = [reactionsStart temp3(end)];
+end
+
+% run through the reactions and process them (+1 since endindex = end-1)
+% make a structure with all reaction information
+% additionally determine a list of all species in the model
+allReactions = [];
+allReactions.name = [];
+allReactions.substratenames = [];
+allReactions.substratefactors = [];
+allReactions.productnames = [];
+allReactions.productfactors = [];
+allSpecies = {};
+numberReactions = 1;
+reactionsStart = [reactionsStart length(reactions)+1];
+for k = 1:length(reactionsStart)-1,
+    reactionString = reactions(reactionsStart(k):reactionsStart(k+1)-1);
+    % check and get notes
+    indexCommentSign = strfind(reactionString,'%');
+    if isempty(indexCommentSign),
+        reactionComment = '';
+    elseif length(indexCommentSign) > 1,
+        errorMsg = sprintf('%s\nSyntax error in a reaction equation.\nThe ''%%'' sign is only allowed once to separate the comment.',errorMsg);
+    else
+        x = double(reactionString);
+        indexCommentEnd = find(x==10);
+        reactionComment = strtrim(reactionString(indexCommentSign+1:indexCommentEnd(1)-1));
+        reactionString = [reactionString(1:indexCommentSign-1) reactionString(indexCommentEnd(1):end)];
+    end
+    reactionString = removeCharacters(reactionString);
+    % check fast flag
+    temp = strfind(lower(reactionString),'{fast}');
+    if ~isempty(temp),
+        % fast identifier is present - take it away and 
+        % set the flag to one, otherwise leave the expression untouched and
+        % set it to 0
+        reactionString = strrep(reactionString,'{fast}','');
+        fastFlag = 1;
+    else
+        fastFlag = 0;
+    end    
+    % check location of separator ':'
+    indexSeparator = strfind(reactionString,':');
+    if isempty(indexSeparator), 
+        errorMsg = sprintf('%s\nSyntax error in reaction equation #%d (or one earlier).\nThe char '':'' is only allowed as name separator! Not within a comment!',errorMsg, k);
+    end
+    % check start of forward rate
+    indexForwardRate = strfind(reactionString,'vf=');
+    % check start of reverse rate
+    indexReverseRate = strfind(reactionString,'vr=');
+    % check if '<=>' is present
+    indexReversibleIdentifier = strfind(reactionString,'<=>');
+    % check if '=>' is present (only if '<=>' is not present)
+    if isempty(indexReversibleIdentifier),
+        indexIrreversibleIdentifier = strfind(reactionString,'=>');
+    else 
+        indexIrreversibleIdentifier = [];
+    end
+    % get reaction equation
+    reactionEquation = reactionString(1:indexSeparator-1);
+    % do a bit of syntax check
+    if length(indexForwardRate) > 1 || length(indexReverseRate) > 1,
+        errorMsg = sprintf('%s\nSyntax error in reaction equation #%d.\nAt least one reaction name is not defined. Or you might have written ''vf='' twice for a reaction:\n%s',errorMsg,k,reactionString);
+    end
+    if ~isempty(indexForwardRate) && ~isempty(indexReverseRate) && ~isempty(indexIrreversibleIdentifier),
+        errorMsg = sprintf('%s\nSyntax error in reaction equation #%d.\nDefined as irreversible but forward and reverse rate are defined.\n%s',errorMsg,k,reactionString);
+    end
+    if (isempty(indexForwardRate) || isempty(indexReverseRate)) && ~isempty(indexReversibleIdentifier),
+        errorMsg = sprintf('%s\nSyntax error in reaction equation #%d.\nDefined as reversible but at least one rate is missing.\n%s',errorMsg,k,reactionString);
+    end
+    if isempty(indexForwardRate) && isempty(indexReverseRate),
+        errorMsg = sprintf('%s\nSyntax error in reaction equation #%d.\nNo rates are defined.\n%s',errorMsg,k,reactionString);
+    end
+    if isempty(indexForwardRate) && ~isempty(indexReverseRate),
+        errorMsg = sprintf('%s\nSyntax error in reaction equation #%d.\nOnly a reverse rate is defined.\n%s',errorMsg,k,reactionString);
+    end
+    if indexForwardRate > indexReverseRate,
+       errorMsg = sprintf('%s\nSyntax error in reaction equation #%d.\nForward rate has to be defined before reverse rate.\n%s',errorMsg,k,reactionString);
+    end 
+    % get the reaction name
+    reactionName = reactionString(indexSeparator+1:indexForwardRate-1);
+    % check reaction name
+    if isempty(reactionName),
+        errorMsg = sprintf('%s\nSyntax error in reaction #%d.\nNor reaction name specified.\n%s',errorMsg,k,reactionString);
+    end
+    % get the forward rate and eventually also the reverse rate
+    if isempty(indexReverseRate),
+        reactionForwardRate = reactionString(indexForwardRate+3:end);
+        reactionReverseRate = '';
+        if isempty(reactionForwardRate),
+            errorMsg = sprintf('%s\nNo forward reaction rate defined for reaction ''%s''',errorMsg,reactionName);
+        end
+    else
+        reactionForwardRate = reactionString(indexForwardRate+3:indexReverseRate-1);
+        reactionReverseRate = reactionString(indexReverseRate+3:end);
+        if isempty(reactionForwardRate),
+            errorMsg = sprintf('%s\nNo forward reaction rate defined for reaction ''%s''',errorMsg,reactionName);
+        end
+        if isempty(reactionReverseRate),
+            errorMsg = sprintf('%s\nNo reverse reaction rate defined for reaction ''%s''',errorMsg,reactionName);
+        end
+    end
+    % parse reaction equation
+    if ~isempty(indexReversibleIdentifier),
+        substratePart = reactionEquation(1:indexReversibleIdentifier-1);
+        productPart = reactionEquation(indexReversibleIdentifier+3:end);
+    else
+        substratePart = reactionEquation(1:indexIrreversibleIdentifier-1);
+        productPart = reactionEquation(indexIrreversibleIdentifier+2:end);
+    end
+    % define reversible flag
+    reactionReversible = ~isempty(reactionReverseRate);
+    % parse the substrate and product parts
+    try
+        substrateTerms = getReactionTerms(substratePart);
+        productTerms = getReactionTerms(productPart);
+    catch
+        errorMsg = sprintf('%sPlease check the syntax of the reaction ''%s''.\n',errorMsg,reactionName);
+    end
+    % add all information into the reaction structure
+    allReactions(numberReactions).name = reactionName;
+    allReactions(numberReactions).substratenames = substrateTerms.names;
+    allReactions(numberReactions).substratefactors = substrateTerms.factors;
+    allReactions(numberReactions).productnames = productTerms.names;
+    allReactions(numberReactions).productfactors = productTerms.factors;
+    numberReactions = numberReactions + 1;
+    % add products and species to allSpecies list (unique entries)
+    allSpecies = unique({allSpecies{:} substrateTerms.names{:} productTerms.names{:}});
+    % add reaction to model structure
+    SBreactions(k).name = reactionName;
+    if reactionReversible,
+        SBreactions(k).formula = strcat(reactionForwardRate,'- (',reactionReverseRate,')');
+        SBreactions(k).reversible = 1;
+    else
+        SBreactions(k).formula = reactionForwardRate;
+        SBreactions(k).reversible = 0;
+    end
+    SBreactions(k).notes = reactionComment;
+    SBreactions(k).fast = fastFlag;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PARSING OF STATE INFORMATION AND CONSTRUCTING STATES AND ODES
+% ALSO TAKE CARE OF DIFFERENTIAL EQUATIONS THAT ARE DEFINED IN THE TEXT!!!
+% Additionally, handle algebraic rules
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% 2) check the list of species against variables and parameters to
+%    determine the states. 
+% 4) check unittypes ........ BIG THING!!!
+% define the state substructure
+SBstates = struct('name',{},'initialCondition',{},'ODE',{},'type',{},'compartment',{},'unittype',{},'notes',{});
+SBalgebraic = struct('name',{},'formula',{},'initialCondition',{},'type',{},'compartment',{},'unittype',{},'notes',{});
+% run through allSpecies and check which ones are defined by variables or
+% parameters. 
+allSpeciesStates = {};
+for k = 1:length(allSpecies),
+    if ~isempty(allSpecies{k}),
+        parameterIndex = strmatchSB(allSpecies{k},{SBparameters.name},'exact');
+        variableIndex = strmatchSB(allSpecies{k},{SBvariables.name},'exact');
+        if isempty(parameterIndex) && isempty(variableIndex) && ~isempty(allSpecies{k}),
+            allSpeciesStates{end+1} = allSpecies{k};
+        end
+    end
+end
+% now add all species that are states to the structure. add default initial
+% condition, add ODE, default notes, default information
+for k = 1:length(allSpeciesStates),
+    SBstates(k).name = allSpeciesStates{k};
+    SBstates(k).initialCondition = 0;
+    SBstates(k).ODE = '';
+    SBstates(k).type = '';          % default: empty
+    SBstates(k).compartment = '';   % default: empty
+    SBstates(k).unittype = '';      % default: empty
+    SBstates(k).notes = '';
+end
+% now run throught the reaction structure and update the state informations (ODE)
+for k1 = 1:length(allReactions),
+    reactionname = allReactions(k1).name;
+    substratenames = allReactions(k1).substratenames;
+    substratefactors = allReactions(k1).substratefactors;
+    productnames = allReactions(k1).productnames;
+    productfactors = allReactions(k1).productfactors;
+    % go through all substrate names
+    for k2 = 1:length(substratenames),
+        substrate = substratenames{k2};
+        % find substrate in species states structure
+        stateIndex = strmatchSB(substrate,{SBstates.name},'exact');
+        % add reaction name to state ODE if substrate found
+        if ~isempty(stateIndex),
+            if substratefactors(k2) == 1,
+                SBstates(stateIndex).ODE = strcat(SBstates(stateIndex).ODE,'-',reactionname);
+            else
+                SBstates(stateIndex).ODE = strcat(SBstates(stateIndex).ODE,'-',num2str(substratefactors(k2)),'*',reactionname);
+            end
+        end
+    end
+    % go through all product names
+    for k2 = 1:length(productnames),
+        product = productnames{k2};
+        % find product in species states structure
+        stateIndex = strmatchSB(product,{SBstates.name},'exact');
+        % add reaction name to state ODE if substrate found
+        if ~isempty(stateIndex),
+            if productfactors(k2) == 1,
+                SBstates(stateIndex).ODE = strcat(SBstates(stateIndex).ODE,'+',reactionname);
+            else
+                SBstates(stateIndex).ODE = strcat(SBstates(stateIndex).ODE,'+',num2str(productfactors(k2)),'*',reactionname);
+            end
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PARSE STATE INFORMATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ODEs are updated now. last thing is to parse the state information in
+% order to update the fields initialCondition, type, compartment, unittype,
+% and notes
+% get the stateinformation text and trim it
+states = strtrim(modelTextBCStructure.states);
+states = char([10 double(states) 10]);
+% START OF THE ODEs
+ODEsStart = strfind(states,'d/dt(');
+% START OF THE ALGEBRAIC RULES
+ARsStart = regexp(states,'\n0')+1;
+% START OF THE INITIAL CONDITIONS
+% (finding the index of the last '\n' before the '(0)' for each initial condition)
+initialConditionsStart = [];
+temp = strfind(states,'(0)');
+for k = 1:length(temp),
+    temp2 = double(states(1:temp(k)));
+    temp3 = find(temp2==10);
+    initialConditionsStart = [initialConditionsStart temp3(end)+1];
+end
+
+%%%%%%%%%%%%%
+% PARSE ODEs
+%%%%%%%%%%%%%
+
+%%%
+stateConstraintInfo = [];
+
+
+% run through the ODEs and process them
+if isempty(ARsStart) && isempty(initialConditionsStart),
+    % if no initial conditions are present then use end of states
+    % string as end index (+1)
+    ODEsStart = [ODEsStart length(states)+1];
+elseif isempty(ARsStart)
+    ODEsStart = [ODEsStart initialConditionsStart(1)];
+else
+    ODEsStart = [ODEsStart ARsStart(1)];
+end
+% process ODEs
+for k = 1:length(ODEsStart)-1,
+    stateString = removeCharacters(states(ODEsStart(k):ODEsStart(k+1)-1));
+    % check if additional information and/or comment is present => error
+    if ~isempty(strfind(stateString,'{')) || ~isempty(strfind(stateString,'%')),
+        errorMsg = sprintf('Additional information and comment should be added behind initial conditions.');
+    end
+    % get name and ODE
+    % extract the state name
+    temp = strfind(stateString,')');
+    test = stateString(6:temp(1)-1);
+    % check if state name given
+    if isempty(test),
+        errorMsg = sprintf('At least on state name in\nODE definition is not given.');
+        return
+    end
+    SBstates(end+1).name = removeWhiteSpace(test);
+    % extract the state ODE
+    temp = strfind(stateString,'=');
+    test = stateString(temp+1:end);
+    % check if state ODE given
+    if isempty(test),
+        errorMsg = sprintf('At least one RHS of an ODE is not given.');
+        return
+    end
+    % The test string contains now the ODE
+    ODE = removeWhiteSpace(test);
+    SBstates(end).ODE = ODE;
+    SBstates(end).notes = '';
+    % add default value for initial condition
+    SBstates(end).initialCondition = 0;
+    % add information to state
+    SBstates(end).type = '';
+    SBstates(end).compartment = '';
+    SBstates(end).unittype = '';
+end
+
+%%%%%%%%%%%%%
+% PARSE ARs
+%%%%%%%%%%%%%
+if isempty(initialConditionsStart),
+    ARsStart = [ARsStart length(states)+1];
+else
+    ARsStart = [ARsStart initialConditionsStart(1)];
+end
+for k=1:length(ARsStart)-1,
+    % get each single AR
+    ARk = strtrim(states(ARsStart(k):ARsStart(k+1)-1));
+    % separate comment from AR definition
+    index1 = strfind(ARk,'=');
+    index2 = strfind(ARk,'%');
+    if ~isempty(index2),
+        ARformulak = strtrim(ARk(index1(1)+1:index2(1)-1));
+        ARnotek = strtrim(ARk(index2(1)+1:end));
+    else
+        ARformulak = strtrim(ARk(index1(1)+1:end));
+        ARnotek = '';
+    end        
+    % split rhs in formula and variable name
+    terms = explodepcSB(ARformulak,':');
+    if length(terms) ~= 2,
+        ARformulak = strtrim(terms{1});
+        ARnamek = '';
+        ARick = [];
+    else
+        ARformulak = strtrim(terms{1});
+        ARnamek = strtrim(terms{2});
+        ARick = 0; % default setting (determined by the integrator)
+    end
+    % update structure
+    SBalgebraic(k).name = ARnamek;
+    SBalgebraic(k).formula = ARformulak;
+    SBalgebraic(k).initialCondition = ARick; 
+    SBalgebraic(end).type = '';
+    SBalgebraic(end).compartment = '';
+    SBalgebraic(end).unittype = '';
+    SBalgebraic(k).notes = ARnotek;
+end
+
+%%%%%%%%%%%%%
+% PARSE ICs
+%%%%%%%%%%%%%
+definedICs4Ordering = {};
+% remove ODEs and ARs from the text
+states = states(initialConditionsStart:end);
+% get the starting indices for the initial conditions by finding the index
+% of the last '\n' before the '(0)' for each initial condition
+statesStart = [];
+temp = strfind(states,'(0)');
+for k = 1:length(temp),
+    temp2 = [10 double(states(1:temp(k)))];
+    temp3 = find(temp2==10);
+    statesStart = [statesStart temp3(end)];
+end
+if ~isempty(statesStart),
+    statesStart = [statesStart length(states)+1];
+end
+% run through each state information and update state structure
+for k1 = 1:length(statesStart)-1,
+    stateText = strtrim(states(statesStart(k1):statesStart(k1+1)-1));
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle possible constraints on state variables in the SBmodel
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if constraint information is present on a state. Syntax: {constraints:[min,max]}
+stateConstraints = {};
+infoStartConstraints = strfind(stateText,'{constraints:');
+if ~isempty(infoStartConstraints),
+    % find the end of the constraint information
+    offset = 11; po = 1;
+    while 1,
+        if stateText(infoStartConstraints+offset) == '}',
+            break;
+        end
+        offset = offset + 1;
+    end
+    constraintsString = stateText(infoStartConstraints:infoStartConstraints+offset);
+    % remove constraint information from stateString
+    stateText = stateText([1:infoStartConstraints-1 infoStartConstraints+offset+1:end]);
+    % parse the constraints string
+    constraintsString = strrep(constraintsString,' ',''); % remove spaces
+    constraintsString = constraintsString(15:end-2);
+    stateConstraints = explodePCSB(constraintsString,',');
+    if length(stateConstraints) ~= 2,
+        error('A state-constraint information seems to be wrongly defined');
+    end
+    % convert numeric bounds to numbers
+    for k2=1:2,
+        try
+            temp = eval(stateConstraints{k2});
+            stateConstraints{k2} = temp;
+        catch
+        end
+    end
+end    
+    
+    % find index of '(0)'
+    indexIdentifier = strfind(stateText,'(0)');
+    % find '='
+    indexEqualSign = strfind(stateText,'=');
+    % find start of additional information
+    indexInfoStart = strfind(stateText,'{');
+    % find end of additional information
+    indexInfoEnd = strfind(stateText,'}');
+    % find comment start
+    indexComment = strfind(stateText,'%');
+    % get the state name
+    stateName = stateText(1:indexIdentifier(1)-1);
+    % Save the stateName in the "definedICs4Ordering" list
+    definedICs4Ordering{end+1} = stateName;
+    % do some error checking
+    if (isempty(indexInfoStart) && ~isempty(indexInfoEnd)) || (isempty(indexInfoStart) && ~isempty(indexInfoEnd)),
+        errorMsg = sprintf('%s\nSyntax error in state information for state ''%s''.',errorMsg,stateName);
+    end
+    % get all the pieces
+    stateComment = '';
+    if isempty(indexInfoStart) && isempty(indexComment),
+        stateICx = (stateText(indexEqualSign(1)+1:end));
+        stateInfo = '';
+        stateComment = '';
+    elseif isempty(indexInfoStart) && ~isempty(indexComment),
+        stateICx = (stateText(indexEqualSign(1)+1:indexComment(1)-1));
+        stateInfo = '';
+        stateComment = stateText(indexComment(1)+1:end);
+    elseif ~isempty(indexInfoStart) && isempty(indexComment),
+        stateICx = (stateText(indexEqualSign(1)+1:indexInfoStart(1)-1));
+        stateInfo = stateText(indexInfoStart+1:indexInfoEnd-1);
+        stateComment = '';
+    elseif ~isempty(indexInfoStart) && ~isempty(indexComment),
+        stateICx = (stateText(indexEqualSign(1)+1:indexInfoStart(1)-1));
+        stateInfo = stateText(indexInfoStart+1:indexInfoEnd-1);
+        stateComment = stateText(indexComment+1:end);
+    end
+    stateIC = str2double(stateICx);
+    if isnan(stateIC),
+%         disp(sprintf('At least one initial condition has a non-numerical value assigned.\nThis might lead to problems with certain toolbox functions.'));
+        stateIC = strtrim(stateICx);
+    end
+    % process state information
+    type = '';
+    compartment = '';
+    unittype = '';
+    % Handle additional information for species states
+    if ~isempty(strmatchSB(stateName,allSpeciesStates)),
+        if ~isempty(stateInfo),
+            terms = explodePCSB(stateInfo,':');
+            if length(terms) ~= 3,
+                errorMsg = sprintf('%s\nError in a state information.',errorMsg);
+            elseif strcmpi(terms{1},'isspecie'),
+                type = terms{1};
+                compartment = terms{2};
+                unittype = terms{3};
+            else
+                errorMsg = sprintf('%s\nError in a state information.',errorMsg);
+            end
+        end
+    else
+        % handle additional information for ODE state
+        if ~isempty(stateInfo),
+            % explode the information text with ':'
+            terms = explodePCSB(stateInfo,':');
+            if length(terms) == 1 && ~isempty(strfind(lower(terms{1}),'parameter')),
+                type = strtrim(terms{1});
+                compartment = '';
+                unittype = '';
+            elseif length(terms) == 2 && ~isempty(strfind(lower(terms{1}),'compartment')),
+                type = strtrim(terms{1});
+                compartment = strtrim(terms{2});
+                unittype = '';
+            elseif length(terms) == 3 && ~isempty(strfind(lower(terms{1}),'specie')),
+                type = strtrim(terms{1});
+                compartment = strtrim(terms{2});
+                unittype = strtrim(terms{3});
+            else
+                errorMsg = 'Error in a state information';
+                return
+            end
+        end
+    end
+    % update state structure with state information
+    % state or algebraic variable !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+    % first find the index of the state where to add it to
+    stateIndex = strmatchSB(stateName,{SBstates.name},'exact');
+    if ~isempty(stateIndex),
+        SBstates(stateIndex).initialCondition = stateIC;
+        SBstates(stateIndex).notes = stateComment;
+        if ~isempty(type),
+            SBstates(stateIndex).type = type;
+        end
+        SBstates(stateIndex).compartment = compartment;
+        if ~isempty(unittype),
+            SBstates(stateIndex).unittype = unittype;
+        end
+        
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle possible constraints on state variables in the SBmodel
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    
+if ~isempty(stateConstraints),
+    % ok, state constraints have been defined for this state
+    % save some information to be able to add it later to the model
+    stateConstraintInfo(end+1).statename = stateName;
+    stateConstraintInfo(end).stateindex = stateIndex;
+    stateConstraintInfo(end).lowbound = stateConstraints{1};
+    stateConstraintInfo(end).highbound = stateConstraints{2};
+    stateConstraintInfo(end).ODE = SBstates(stateIndex).ODE;
+end
+    else
+        % if not state found then it should be an algebraic variable!
+        algebraicIndex = strmatchSB(stateName,{SBalgebraic.name},'exact');
+        if ~isempty(algebraicIndex),
+            SBalgebraic(algebraicIndex).initialCondition = stateIC;
+            SBalgebraic(algebraicIndex).notes = stateComment;
+            if ~isempty(type),
+                SBalgebraic(algebraicIndex).type = type;
+            end
+            SBalgebraic(algebraicIndex).compartment = compartment;
+            if ~isempty(unittype),
+                SBalgebraic(algebraicIndex).unittype = unittype;
+            end
+        else
+            errorMsg = sprintf('An initial condition is defined for which not state exists: ''%s''',stateName);
+            return
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CORRECT ODES WITH COMPARTMENT INFORMATION TO CONVERT RATE TYPES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k = 1:length(SBstates),
+    type = SBstates(k).type;
+    compartment = SBstates(k).compartment;
+    unittype = SBstates(k).unittype;
+    % check if state is a specie and compartment given and in concentration
+    if strcmp(lower(type),'isspecie') && ~isempty(compartment) && strcmp(lower(unittype),'concentration'),
+        addCompartmentText = strcat('/',compartment);
+        SBstates(k).ODE = strcat('(',SBstates(k).ODE,')',addCompartmentText);
+    end
+end
+
+% Combining the parts of the SBmodel structure (name and notes are already
+% added)
+SBstructure.functions = SBfunctions;
+SBstructure.states = SBstates;
+SBstructure.algebraic = SBalgebraic;
+SBstructure.parameters = SBparameters;
+SBstructure.variables = SBvariables;
+SBstructure.reactions = SBreactions;
+SBstructure.events = SBevents;
+SBstructure.functionsMATLAB = SBfunctionsMATLAB;
+
+% Finally we need to reorder the states in the order given by the list of
+% initial conditions in the model. Non defined initial conditions come
+% first, followed by the ones defined in the same order ... this is
+% important only for the handling of non-numeric ICs.
+allStateNames = {SBstructure.states.name};
+orderedStateNames = definedICs4Ordering;
+% get the indices of the ordered states in the current structure
+currentIndex = [];
+for k=1:length(orderedStateNames),
+    currentIndex(end+1) = strmatchSB(orderedStateNames{k},allStateNames,'exact');
+end
+% get permutation vector
+allIndex = [1:length(allStateNames)];
+notOrder = setdiff(allIndex,currentIndex);
+permutvec = [notOrder currentIndex];
+% do permutation
+SBstructure.states(1:length(allIndex)) = SBstructure.states(permutvec);
+% It's done ... enjoy!
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%% State Constraints
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% First, since states can have been reordered we need to get the correct
+% indices in the stateConstraintInfo stucture:
+for k=1:length(stateConstraintInfo),
+    sname = stateConstraintInfo(k).statename;
+    stateConstraintInfo(k).stateindex = strmatchSB(sname,{SBstructure.states.name},'exact');
+end
+% Handle possible constraints on state variables in the SBmodel:
+% add the needed piecewise expressions and the factors on the ODEs
+% as last reactions in the model. We need to add it as reactions in order
+% to evaluate these as last elements before evaluating the ODEs.
+for k=1:length(stateConstraintInfo),
+    statename = stateConstraintInfo(k).statename;
+    stateindex = stateConstraintInfo(k).stateindex;
+    lowbound = stateConstraintInfo(k).lowbound;
+    highbound = stateConstraintInfo(k).highbound;
+    ODE = stateConstraintInfo(k).ODE;
+    % add a factor "constraints_factor_statename" to the ODE for the state
+    SBstructure.states(k).ODE = ['constraints_factor_' statename ' * (' ODE ')'];
+    % define the "constraints_factor_statename" in the reactions
+    SBstructure.reactions(end+1).name = ['constraints_factor_' statename];
+    % construct the piecewise expression
+    if ~checkboundIsInf(lowbound) && ~checkboundIsInf(highbound),
+        pwtext = sprintf('piecewiseSB(0,orSB(andSB(ge(%s,%s),gt(%s,0)),andSB(le(%s,%s),lt(%s,0))),1)',statename,num2str(highbound,20),ODE,statename,num2str(lowbound,20),ODE);
+    elseif checkboundIsInf(lowbound) && ~checkboundIsInf(highbound),
+        pwtext = sprintf('piecewiseSB(0,andSB(ge(%s,%s),gt(%s,0)),1)',statename,num2str(highbound,20),ODE);
+    elseif checkboundIsInf(lowbound) && ~checkboundIsInf(highbound),
+        pwtext = sprintf('piecewiseSB(0,andSB(le(%s,%s),lt(%s,0)),1)',statename,num2str(lowbound,20),ODE);
+    else
+        pwtext = '1'; % always unconstrained
+    end
+    % add the piecewise expression as last reaction and do the rest
+    SBstructure.reactions(end).formula = pwtext;
+    SBstructure.reactions(end).notes = sprintf('Implementation of constraints on state %s',statename);
+    SBstructure.reactions(end).reversible = 0;
+    SBstructure.reactions(end).fast = 0;
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [output] = checkboundIsInf(bound)
+if ischar(bound),
+    output = 0;
+    return
+end
+if isnumeric(bound),
+    output = isinf(bound);
+    return
+end
+error('Problem with constraints - bound definition.');
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET SPECIES AND STOICHIOMETRIC COEFFICIENTS FROM REACTION PARTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [reactionterms,errorMsg] = getReactionTerms(reactionPart,errorMsg)
+% explode the substrate and product parts into species and
+% stoichiometric coefficients
+% expect the terms to be of the format:
+% factor*species + factor*species + ...
+allTerms = explodePCSB(reactionPart,'+');
+% check the syntax of the single terms (name or numeric*name)
+reactionterms = [];
+reactionterms.names = {};
+reactionterms.factors = [];
+for k = 1:length(allTerms),
+    checkTerms = explodePCSB(allTerms{k},'*');
+    % only accept lengths 1 or 2 (possibly with or without
+    % factor) otherwise error
+    if length(checkTerms) == 1,
+        reactionterms.names{end+1} = checkTerms{1};
+        reactionterms.factors(end+1) = 1;
+    elseif length(checkTerms) == 2 && ~isnan(str2double(checkTerms{1})),
+        % first term needs to be numeric
+        reactionterms.names{end+1} = checkTerms{2};
+        reactionterms.factors(end+1) = str2double(checkTerms{1});
+    else
+        errorMsg = sprintf('Syntax error in a reaction equation.');
+    end
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [SBparameters, error] = getParameters(parameters)
+error = '';
+%    parameters = removeWhiteSpace(parameters);
+SBparameters = struct('name',{},'value',{},'type',{},'compartment',{},'unittype',{},'notes',{});
+
+% get the starting indices for the parameters by finding the index
+% of the last '\n' before the '=' for each parameter
+parametersStart = regexp([10 parameters],['\n[^\n=]*=']);
+% run through the parameters and process them (+1 since endindex = end-1)
+parametersStart = [parametersStart length(parameters)+1];
+
+parNAN = 0;
+for k = 1:length(parametersStart)-1,
+%    parameterString = removeCharacters(parameters(parametersStart(k):parametersStart(k+1)-1));
+    parameterString = strtrim(parameters(parametersStart(k):parametersStart(k+1)-1));
+    % check if additional information is present ... if yes, cut it out
+    infoStart = strfind(parameterString,'{');
+    infoEnd = strfind(parameterString,'}');
+    informationText = '';
+    if length(infoStart) + length(infoEnd) > 2,
+        error = 'To many square parentheses in a parameter definition';
+        return
+    end
+    if length(infoStart) ~= length(infoEnd),
+        error = 'At least one parameter information not properly defined';
+        return
+    end
+    if length(infoStart) == 1,
+        informationText = parameterString(infoStart+1:infoEnd-1);
+        parameterString = parameterString([1:infoStart-1, infoEnd+1:end]);
+    end
+    if ~isempty(informationText),
+        % explode the information text with ':'
+        terms = explodePCSB(informationText,':');
+        if length(terms) == 1 && ~isempty(strfind(lower(terms{1}),'parameter')),
+            type = strtrim(terms{1});
+            compartment = '';
+            unittype = '';
+        elseif length(terms) == 2 && ~isempty(strfind(lower(terms{1}),'compartment')),
+            type = strtrim(terms{1});
+            compartment = strtrim(terms{2});
+            unittype = '';
+        elseif length(terms) == 3 && ~isempty(strfind(lower(terms{1}),'specie')),
+            type = strtrim(terms{1});
+            compartment = strtrim(terms{2});
+            unittype = strtrim(terms{3});
+        else
+            error = sprintf('Error in a parameter information (Do not use ''{'' and/or ''}'' in state, parameter or variable comments).');
+            return           
+        end
+    else 
+        type = '';
+        compartment = '';
+        unittype = '';
+    end
+    % extract the parameter name
+    temp = strfind(parameterString,'=');
+    test = parameterString(1:temp(1)-1);
+    % check if parameter name given
+    if isempty(test),
+        error = sprintf('At least one parameter name not given.');
+        return
+    end
+    SBparameters(k).name = removeWhiteSpace(test);
+    % extract the parameter value
+    % check if it has a numerical value
+    test = parameterString(temp+1:end);
+    % The test string contains now the parameter value and eventually also a
+    % comment that should be written into notes.
+    % check if a comment is present
+    temp = strfind(test,'%');
+    if ~isempty(temp),
+        value = str2double(removeWhiteSpace(test(1:temp(1)-1)));
+        notes = strtrim(test(temp(1)+1:end));
+    else
+        value = str2double(removeWhiteSpace(test));
+        notes = '';
+    end
+    if isnan(value),
+        % initial condition was not a numerical value
+        parNAN = 1;
+    else
+        SBparameters(k).value = value;
+    end
+    % add default notes to parameter
+    SBparameters(k).notes = notes;
+    % add information to parameter
+    SBparameters(k).type = type;
+    SBparameters(k).compartment = compartment;
+    SBparameters(k).unittype = unittype;
+end
+if parNAN,
+    error = sprintf('At least one parameter has a\nnon-numerical value assigned');
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [SBvariables, error] = getVariables(variables)
+error = '';
+SBvariables = struct('name',{},'formula',{},'type',{},'compartment',{},'unittype',{},'notes',{});
+
+% get the starting indices for the variables by finding the index
+% of the last '\n' before the '=' for each variable
+variablesStart = regexp([10 variables],['\n[^\n=]*=']);
+% run through the variables and process them (+1 since endindex = end-1)
+variablesStart = [variablesStart length(variables)+1];
+
+for k = 1:length(variablesStart)-1,
+%     variableString = removeCharacters(variables(variablesStart(k):variablesStart(k+1)-1));
+    variableString = strtrim(variables(variablesStart(k):variablesStart(k+1)-1));
+    % check if additional information is present ... if yes, cut it out
+    infoStart = strfind(variableString,'{');
+    infoEnd = strfind(variableString,'}');
+    informationText = '';
+    if length(infoStart) + length(infoEnd) > 2,
+        error = 'To many square parentheses in a variable definition';
+        return
+    end
+    if length(infoStart) ~= length(infoEnd),
+        error = 'At least one variable information not properly defined';
+        return
+    end
+    if length(infoStart) == 1,
+        informationText = variableString(infoStart+1:infoEnd-1);
+        variableString = variableString([1:infoStart-1, infoEnd+1:end]);
+    end
+    if ~isempty(informationText),
+        % explode the information text with ':'
+        terms = explodePCSB(informationText,':');
+        if length(terms) == 1 && ~isempty(strfind(lower(terms{1}),'parameter')),
+            type = strtrim(terms{1});
+            compartment = '';
+            unittype = '';
+        elseif length(terms) == 2 && ~isempty(strfind(lower(terms{1}),'compartment')),
+            type = strtrim(terms{1});
+            compartment = strtrim(terms{2});
+            unittype = '';
+        elseif length(terms) == 3 && ~isempty(strfind(lower(terms{1}),'specie')),
+            type = strtrim(terms{1});
+            compartment = strtrim(terms{2});
+            unittype = strtrim(terms{3});
+        else
+            error = 'Error in a variable information';
+            return           
+        end
+    else 
+        type = '';
+        compartment = '';
+        unittype = '';
+    end
+    % extract the variable name
+    temp = strfind(variableString,'=');
+    test = variableString(1:temp(1)-1);
+    % check if variable name given
+    if isempty(test),
+        error = sprintf('At least one variable name not given.');
+        return
+    end
+    SBvariables(k).name = removeWhiteSpace(test);
+    % extract the variable value
+    test = variableString(temp+1:end);
+    % The test string contains now the variable expression and
+    % eventually also a comment that should be written into notes.
+    % check if a comment is present
+    temp = strfind(test,'%');
+    if ~isempty(temp),
+        formula = removeWhiteSpace(test(1:temp(1)-1));
+        notes = strtrim(test(temp(1)+1:end));
+    else
+        formula = removeWhiteSpace(test);
+        notes = '';
+    end
+    % check if variable expression given
+    if isempty(formula),
+        error = sprintf('At least one variable definition not given.');
+        return
+    end
+    SBvariables(k).formula = formula;
+    % add default notes to variable
+    SBvariables(k).notes = notes;
+    % add information to parameter
+    SBvariables(k).type = type;
+    SBvariables(k).compartment = compartment;
+    SBvariables(k).unittype = unittype;    
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [SBfunctions, error] = getFunctions(functions)
+error = '';
+%    functions = removeWhiteSpace(functions);
+SBfunctions = struct('name',{},'arguments',{},'formula',{},'notes',{});
+
+% get the starting indices for the functions by finding the index
+% of the last '\n' before the '=' for each function
+functionsStart = regexp([10 functions],['\n[^\n=]*=']);
+% run through the functions and process them (+1 since endindex = end-1)
+functionsStart = [functionsStart length(functions)+1];
+
+for k = 1:length(functionsStart)-1,
+%    functionString = removeCharacters(functions(functionsStart(k):functionsStart(k+1)-1));
+    functionString = strtrim(functions(functionsStart(k):functionsStart(k+1)-1));
+    % extract the function name
+    temp = strfind(functionString,'(');
+    test = functionString(1:temp(1)-1);
+    % check if function name given
+    if isempty(test),
+        error = sprintf('At least one function name not given.');
+        return
+    end
+    SBfunctions(k).name = removeWhiteSpace(test);
+    % extract the arguments
+    temp2 = strfind(functionString,')');
+    test = functionString(temp+1:temp2-1);
+    % check if function arguments given
+    if isempty(test),
+        error = sprintf('At least for one function no arguments given.');
+        return
+    end
+    SBfunctions(k).arguments = removeWhiteSpace(test);
+    % extract the formula
+    temp3 = strfind(functionString,'=');
+    test = functionString(temp3+1:end);
+    % The test string contains now the formula and
+    % eventually also a comment that should be written into notes.
+    % check if a comment is present
+    temp = strfind(test,'%');
+    if ~isempty(temp),
+        formula = removeWhiteSpace(test(1:temp(1)-1));
+        notes = strtrim(test(temp(1)+1:end));
+    else
+        formula = removeWhiteSpace(test);
+        notes = '';
+    end
+    % check if function formula given
+    if isempty(formula),
+        error = sprintf('At least for one function no formula given.');
+        return
+    end
+    SBfunctions(k).formula = formula;
+    % add default notes to function
+    SBfunctions(k).notes = notes;
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [SBevents, error] = getEvents(events)
+error = '';
+% event substructure
+eventassignmentStruct = struct('variable',{},'formula',{});
+SBevents = struct('name',{},'trigger',{},'assignment',eventassignmentStruct,'notes',{});
+
+% get the starting indices for the events by finding the index
+% of the last '\n' before the '=' for each event
+eventsStart = regexp([10 events],['\n[^\n=]*=']);
+% run through the events and process them (+1 since endindex = end-1)
+eventsStart = [eventsStart length(events)+1];
+
+for k = 1:length(eventsStart)-1,
+%     eventString = removeCharacters(events(eventsStart(k):eventsStart(k+1)-1));
+    eventString = strtrim(events(eventsStart(k):eventsStart(k+1)-1));
+    % check if comment present
+    startNotes = strfind(eventString,'%');
+    notes = '';
+    if ~isempty(startNotes),
+        notes = eventString(startNotes(1)+1:end);
+        eventString = eventString(1:startNotes(1)-1);
+    end
+    SBevents(k).notes = notes;
+    % extract the event name
+    temp = strfind(eventString,'=');
+    test = strtrim(eventString(1:temp(1)-1));
+    % check if event name given
+    if isempty(test),
+        error = sprintf('At least one event has no name given.');
+        return
+    end
+    SBevents(k).name = removeWhiteSpace(test);
+    % get the right hand side
+    eventRHS = eventString(temp(1)+1:end);
+    % decompose the eventRHS into its comma separated elements
+    % taking into account parentheses
+    elementsRHS = explodePCSB(eventRHS);
+    % check number of elements
+    if length(elementsRHS) < 3 || mod(length(elementsRHS),2) == 0,
+        error = sprintf('At least one event has no full information given.');
+        return
+    end
+    % first element is assumed to be the trigger function
+    SBevents(k).trigger = removeWhiteSpace(elementsRHS{1});
+    % add the event assignments
+    indexAssignment = 1;
+    for k2 = 2:2:length(elementsRHS),
+        SBevents(k).assignment(indexAssignment).variable = removeWhiteSpace(elementsRHS{k2});
+        SBevents(k).assignment(indexAssignment).formula = removeWhiteSpace(elementsRHS{k2+1});
+        indexAssignment = indexAssignment + 1;
+    end
+
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DELETE WHITESPACES IN STRINGS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Useful for taking away whitespaces in kineticLaw formulas, as
+% seen in some example models
+function [outputString] = removeWhiteSpace(inputString)
+outputString = strrep(inputString,' ','');
+% return
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [output] = removeCharacters(input)
+% delete all line breaks and tabs from the input string
+temp = double(input);
+temp(find(temp==13)) = 32;  % replace '\cr' by white space
+temp(find(temp==10)) = 32;  % replace '\n' by white space
+temp(find(temp==9)) = 32;   % replace '\t' by white space
+output = char(temp);
+output = strrep(output,' ','');
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [output] = removeCharacters2(input)
+% delete all line breaks and tabs from the input string
+temp = double(input);
+temp(find(temp==13)) = 32;  % replace '\cr' by white space
+output = char(temp);
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/text2sbmodel/convertTextToModelSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/text2sbmodel/convertTextToModelSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..24777e5e10ac73ce2035b1f6d9a7d52b0321eced
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/text2sbmodel/convertTextToModelSB.m
@@ -0,0 +1,965 @@
+function [SBstructure,errorMsg] = convertTextToModelSB(modelText)
+% convertTextToModelSB: Converts a text description of an SBmodel to 
+% the internal data structure representation.r
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+% global variable for passing array state initial conditions to
+% convertTEXTArrayDefSB.m
+global arrayInitialConditions_qayxsw
+arrayInitialConditions_qayxsw = [];
+
+% initialize variables
+errorMsg = '';
+errorFunctions = '';
+errorStates = '';
+errorParameters = '';
+errorVariables = '';
+errorReactions = '';
+errorEvents = '';
+
+SBstructure = struct(SBmodel());
+
+% cut text into pieces
+modelTextStructure = getPartsFromCompleteTextSB(modelText);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%% Name
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBstructure.name = removeCharacters(modelTextStructure.name);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%% Notes
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBstructure.notes = strtrim(modelTextStructure.notes);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%% Functions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try
+    [SBstructure.functions, errorFunctions] = getFunctions(modelTextStructure.functions);
+catch
+    errorMsg = sprintf('%sPlease check the syntax of the ''Functions'' definitions.\n',errorMsg);
+end
+if ~isempty(errorFunctions),
+    errorMsg = sprintf('%s%s\n',errorMsg,errorFunctions);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%% States and algebraic rules
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try
+    [SBstructure.states, SBstructure.algebraic, stateConstraintInfo, errorStates] = getStates(modelTextStructure.states);
+catch
+    errorMsg = sprintf('%sPlease check the syntax of the ''ODE'' and\n''initial condition'' definitions.\n',errorMsg);
+end
+if ~isempty(errorStates),
+    errorMsg = sprintf('%s%s\n',errorMsg,errorStates);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%% Parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try
+    [SBstructure.parameters, errorParameters] = getParameters(modelTextStructure.parameters);
+catch
+    errorMsg = sprintf('%sPlease check the syntax of the ''Parameter'' definitions.\n',errorMsg);
+end
+if ~isempty(errorParameters),
+    errorMsg = sprintf('%s%s\n',errorMsg,errorParameters);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%% Variables
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try
+    [SBstructure.variables, errorVariables] = getVariables(modelTextStructure.variables);
+catch
+    errorMsg = sprintf('%sPlease check the syntax of the ''Variables'' definitions.\n',errorMsg);
+end
+if ~isempty(errorVariables),
+    errorMsg = sprintf('%s%s\n',errorMsg,errorVariables);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%% Reactions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try
+    [SBstructure.reactions, errorReactions] = getReactions(modelTextStructure.reactions);
+catch
+    errorMsg = sprintf('%sPlease check the syntax of the ''Reactions'' definitions.\n',errorMsg);
+end
+if ~isempty(errorReactions),
+    errorMsg = sprintf('%s%s\n',errorMsg,errorReactions);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%% Events
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try
+    [SBstructure.events, errorEvents] = getEvents(modelTextStructure.events);
+catch
+    errorMsg = sprintf('%sPlease check the syntax of the ''Events'' definitions.\n',errorMsg);
+end
+if ~isempty(errorEvents),
+    errorMsg = sprintf('%s%s\n',errorMsg,errorEvents);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%% MATLAB functions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBstructure.functionsMATLAB = modelTextStructure.functionsMATLAB;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%% Check errorMessage
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(errorMsg),
+    SBstructure = [];
+    return
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%% State Constraints
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle possible constraints on state variables in the SBmodel:
+% add the needed piecewise expressions and the factors on the ODEs
+% as last reactions in the model. We need to add it as reactions in order
+% to evaluate these as last elements before evaluating the ODEs.
+for k=1:length(stateConstraintInfo),
+    statename = stateConstraintInfo(k).statename;
+    stateindex = stateConstraintInfo(k).stateindex;
+    lowbound = stateConstraintInfo(k).lowbound;
+    highbound = stateConstraintInfo(k).highbound;
+    ODE = stateConstraintInfo(k).ODE;
+    % add a factor "constraints_factor_statename" to the ODE for the state
+    SBstructure.states(k).ODE = ['constraints_factor_' statename ' * (' ODE ')'];
+    % define the "constraints_factor_statename" in the reactions
+    SBstructure.reactions(end+1).name = ['constraints_factor_' statename];
+    % construct the piecewise expression
+    if ~checkboundIsInf(lowbound) && ~checkboundIsInf(highbound),
+        pwtext = sprintf('piecewiseSB(0,orSB(andSB(ge(%s,%s),gt(%s,0)),andSB(le(%s,%s),lt(%s,0))),1)',statename,num2str(highbound,20),ODE,statename,num2str(lowbound,20),ODE);
+    elseif checkboundIsInf(lowbound) && ~checkboundIsInf(highbound),
+        pwtext = sprintf('piecewiseSB(0,andSB(ge(%s,%s),gt(%s,0)),1)',statename,num2str(highbound,20),ODE);
+    elseif checkboundIsInf(lowbound) && ~checkboundIsInf(highbound),
+        pwtext = sprintf('piecewiseSB(0,andSB(le(%s,%s),lt(%s,0)),1)',statename,num2str(lowbound,20),ODE);
+    else
+        pwtext = '1'; % always unconstrained
+    end
+    % add the piecewise expression as last reaction and do the rest
+    SBstructure.reactions(end).formula = pwtext;
+    SBstructure.reactions(end).notes = sprintf('Implementation of constraints on state %s',statename);
+    SBstructure.reactions(end).reversible = 0;
+    SBstructure.reactions(end).fast = 0;
+end
+
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [output] = checkboundIsInf(bound)
+if ischar(bound),
+    output = 0;
+    return
+end
+if isnumeric(bound),
+    output = isinf(bound);
+    return
+end
+error('Problem with constraints - bound definition.');
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [SBstates, SBalgebraic, stateConstraintInfo, error] = getStates(states)
+global arrayInitialConditions_qayxsw
+error = '';
+%    states = removeWhiteSpace(states);
+SBstates = struct('name',{},'initialCondition',{},'ODE',{},'type',{},'compartment',{},'unittype',{},'notes',{});
+SBalgebraic = struct('name',{},'formula',{},'initialCondition',{},'type',{},'compartment',{},'unittype',{},'notes',{});
+% check if ode definitions are present
+if isempty(strfind(states,'d/dt(')),
+    error = 'The model does not contain any states';
+    return
+end
+% get start of ODEs, ARs, and ICs
+ODEtest = strfind(states,'d/dt(');
+ARtest = strfind(states,'0 = ');
+ICtest = strfind(states,'(0)');
+% check if they come subsequently
+if ~isempty(ICtest),
+    if max(ODEtest)>min(ICtest),
+        error = sprintf('Initial conditions have to be defined\nafter the definition of the ODEs.');
+        return
+    end
+end
+if ~isempty(ARtest),
+    if max(ODEtest)>min(ARtest),
+        error = sprintf('Algebraic rules have to be defined\nafter the definition of the ODEs.');
+        return
+    end
+end
+if ~isempty(ARtest) && ~isempty(ICtest),
+    if max(ARtest)>min(ICtest),
+        error = sprintf('Initial conditions have to be defined\nafter the definition of the algebraic rules.');
+        return
+    end
+end
+% START OF THE ODEs
+ODEsStart = strfind(states,'d/dt(');
+% START OF THE ALGEBRAIC RULES
+ARsStart = regexp(states,'\n0')+1;
+% START OF THE INITIAL CONDITIONS
+% (finding the index of the last '\n' before the '(0)' for each initial condition)
+initialConditionsStart = [];
+temp = strfind(states,'(0)');
+for k = 1:length(temp),
+    temp2 = double(states(1:temp(k)));
+    temp3 = find(temp2==10);
+    initialConditionsStart = [initialConditionsStart temp3(end)+1];
+end
+
+%%%%%%%%%%%%%%%%%%%
+% PROCESS ODEs
+%%%%%%%%%%%%%%%%%%%
+stateConstraintInfo = [];
+
+% run through the ODEs and process them
+if isempty(ARsStart) && isempty(initialConditionsStart),
+    % if no initial conditions are present then use end of states
+    % string as end index (+1)
+    ODEsStart = [ODEsStart length(states)+1];
+elseif isempty(ARsStart)
+    ODEsStart = [ODEsStart initialConditionsStart(1)];
+else
+    ODEsStart = [ODEsStart ARsStart(1)];
+end
+for k = 1:length(ODEsStart)-1,
+    stateString = removeCharacters(states(ODEsStart(k):ODEsStart(k+1)-1));
+
+    
+
+    
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle possible constraints on state variables in the SBmodel
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if constraint information is present on a state. Syntax: {constraints:[min,max]}
+stateConstraints = {};
+infoStartConstraints = strfind(stateString,'{constraints:');
+if ~isempty(infoStartConstraints),
+    % find the end of the constraint information
+    offset = 11; po = 1;
+    while 1,
+        if stateString(infoStartConstraints+offset) == '}',
+            break;
+        end
+        offset = offset + 1;
+    end
+    constraintsString = stateString(infoStartConstraints:infoStartConstraints+offset);
+    % remove constraint information from stateString
+    stateString = stateString([1:infoStartConstraints-1 infoStartConstraints+offset+1:end]);
+    % parse the constraints string
+    constraintsString = strrep(constraintsString,' ',''); % remove spaces
+    constraintsString = constraintsString(15:end-2);
+    stateConstraints = explodePCSB(constraintsString,',');
+    if length(stateConstraints) ~= 2,
+        error('A state-constraint information seems to be wrongly defined');
+    end
+    % convert numeric bounds to numbers
+    for k2=1:2,
+        try
+            temp = eval(stateConstraints{k2});
+            stateConstraints{k2} = temp;
+        catch
+        end
+    end
+end
+    
+
+
+    % check if additional information is present ... if yes, cut it out
+    infoStart = strfind(stateString,'{');
+    infoEnd = strfind(stateString,'}');
+    informationText = '';
+    if length(infoStart) + length(infoEnd) > 2,
+        error = 'To many curly parentheses in a state definition';
+        return
+    end
+    if length(infoStart) ~= length(infoEnd),
+        error = 'At least one state information not properly defined';
+        return
+    end
+    if length(infoStart) == 1,
+        informationText = stateString(infoStart+1:infoEnd-1);
+        stateString = stateString([1:infoStart-1, infoEnd+1:end]);
+    end
+    if ~isempty(informationText),
+        % explode the information text with ':'
+        terms = explodePCSB(informationText,':');
+        if length(terms) == 1 && ~isempty(strfind(lower(terms{1}),'parameter')),
+            type = strtrim(terms{1});
+            compartment = '';
+            unittype = '';
+        elseif length(terms) == 2 && ~isempty(strfind(lower(terms{1}),'compartment')),
+            type = strtrim(terms{1});
+            compartment = strtrim(terms{2});
+            unittype = '';
+        elseif length(terms) == 3 && ~isempty(strfind(lower(terms{1}),'specie')),
+            type = strtrim(terms{1});
+            compartment = strtrim(terms{2});
+            unittype = strtrim(terms{3});
+        else
+            error = 'Error in a state information';
+            return           
+        end
+    else 
+        type = '';
+        compartment = '';
+        unittype = '';
+    end
+    % extract the state name
+    temp = strfind(stateString,')');
+    test = stateString(6:temp(1)-1);
+    % check if state name given
+    if isempty(test),
+        error = sprintf('At least on state name in\nODE definition is not given.');
+        return
+    end
+    SBstates(k).name = removeWhiteSpace(test);
+    % extract the state ODE
+    temp = strfind(stateString,'=');
+    test = stateString(temp+1:end);
+    % check if state ODE given
+    if isempty(test),
+        error = sprintf('At least one RHS of an ODE is not given.');
+        return
+    end
+    % The test string contains now the ODE and eventually also a
+    % comment that should be written into notes.
+    % check if a comment is present
+    temp = strfind(test,'%');
+    if ~isempty(temp),
+        ODE = removeWhiteSpace(test(1:temp(1)-1));
+        notes = strtrim(test(temp(1)+1:end));
+    else
+        ODE = removeWhiteSpace(test);
+        notes = '';
+    end
+    SBstates(k).ODE = ODE;
+    SBstates(k).notes = notes;
+    % add default value for initial condition
+    SBstates(k).initialCondition = 0;
+    % add information to state
+    SBstates(k).type = type;
+    SBstates(k).compartment = compartment;
+    SBstates(k).unittype = unittype;
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle possible constraints on state variables in the SBmodel
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    
+if ~isempty(stateConstraints),
+    % ok, state constraints have been defined for this state
+    % save some information to be able to add it later to the model
+    stateConstraintInfo(end+1).statename = SBstates(k).name;
+    stateConstraintInfo(end).stateindex = k;
+    stateConstraintInfo(end).lowbound = stateConstraints{1};
+    stateConstraintInfo(end).highbound = stateConstraints{2};
+    stateConstraintInfo(end).ODE = SBstates(k).ODE;
+end
+
+end
+
+%%%%%%%%%%%%%%%%%%%
+% PROCESS ARs
+%%%%%%%%%%%%%%%%%%%
+if isempty(initialConditionsStart),
+    ARsStart = [ARsStart length(states)+1];
+else
+    ARsStart = [ARsStart initialConditionsStart(1)];
+end
+for k=1:length(ARsStart)-1,
+    % get each single AR
+    ARk = strtrim(states(ARsStart(k):ARsStart(k+1)-1));
+    % check if additional information is present ... if yes, cut it out
+    infoStart = strfind(ARk,'{');
+    infoEnd = strfind(ARk,'}');
+    informationText = '';
+    if length(infoStart) + length(infoEnd) > 2,
+        error = 'To many curly parentheses in an algebraic rule definition';
+        return
+    end
+    if length(infoStart) ~= length(infoEnd),
+        error = 'At least one algebraic rule not properly defined';
+        return
+    end
+    if length(infoStart) == 1,
+        informationText = ARk(infoStart+1:infoEnd-1);
+        ARk = ARk([1:infoStart-1, infoEnd+1:end]);
+    end
+    if ~isempty(informationText),
+        % explode the information text with ':'
+        terms = explodePCSB(informationText,':');
+        if length(terms) == 1 && ~isempty(strfind(lower(terms{1}),'parameter')),
+            type = strtrim(terms{1});
+            compartment = '';
+            unittype = '';
+        elseif length(terms) == 2 && ~isempty(strfind(lower(terms{1}),'compartment')),
+            type = strtrim(terms{1});
+            compartment = strtrim(terms{2});
+            unittype = '';
+        elseif length(terms) == 3 && ~isempty(strfind(lower(terms{1}),'specie')),
+            type = strtrim(terms{1});
+            compartment = strtrim(terms{2});
+            unittype = strtrim(terms{3});
+        else
+            error = 'Error in an algebraic rule information';
+            return           
+        end
+    else 
+        type = '';
+        compartment = '';
+        unittype = '';
+    end
+    % separate comment from AR definition
+    index1 = strfind(ARk,'=');
+    index2 = strfind(ARk,'%');
+    if ~isempty(index2),
+        ARformulak = strtrim(ARk(index1(1)+1:index2(1)-1));
+        ARnotek = strtrim(ARk(index2(1)+1:end));
+    else
+        ARformulak = strtrim(ARk(index1(1)+1:end));
+        ARnotek = '';
+    end        
+    % split rhs in formula and variable name
+    terms = explodePCSB(ARformulak,':');
+    if length(terms) ~= 2,
+        ARformulak = terms{1};
+        ARnamek = ''; % keep it empty
+        ARick = [];
+    else
+        ARformulak = strtrim(terms{1});
+        ARnamek = strtrim(terms{2});
+        ARick = 0; % default setting (determined by the integrator)
+    end
+    % update structure
+    SBalgebraic(k).name = ARnamek;
+    SBalgebraic(k).formula = ARformulak;
+    SBalgebraic(k).initialCondition = ARick; % default setting (determined by the integrator)
+    SBalgebraic(k).type = type;
+    SBalgebraic(k).compartment = compartment;
+    SBalgebraic(k).unittype = unittype;
+    SBalgebraic(k).notes = ARnotek;
+end
+
+%%%%%%%%%%%%%%%%%%%
+% PROCESS ICs
+%%%%%%%%%%%%%%%%%%%
+% run through the initial conditions and add them
+% they can have a different order than the odes. if an initial
+% condition is not defined for a certain state then it is set to zero
+% by default
+% First check if any initial conditions are given - if not then don't
+% execute this part!
+if ~isempty(strfind(states,'(0)')),
+    initialConditionsStart = [initialConditionsStart length(states)+1];
+    for k1 = 1:length(initialConditionsStart)-1,
+        ICString = removeWhiteSpace(removeCharacters(states(initialConditionsStart(k1):initialConditionsStart(k1+1)-1)));
+        % extract the state name
+        temp = strfind(ICString,'(0)');
+        stateName = ICString(1:temp(1)-1);
+        % extract the states' initial condition
+        temp = strfind(ICString,'=');
+        stateIC = ICString(temp+1:end);
+        % cycle through the states in the SBstructure and add the initial
+        % condition at the correct state
+        statefound = 0;
+        for k2 = 1:length(SBstates),
+            if strcmp(stateName,SBstates(k2).name),
+                statefound = 1;
+                test = str2double(stateIC);
+                if isnan(test),
+                    % initial condition was not a numerical value
+%                     disp(sprintf('At least one initial condition has a non-numerical value assigned.\nThis might lead to problems with certain toolbox functions.'));
+                    SBstates(k2).initialCondition = strtrim(stateIC);
+                else
+                    SBstates(k2).initialCondition = test;
+                end
+                break;
+            end
+        end
+        % add initial conditions to the algebraic variables if defined
+        for k2 = 1:length(SBalgebraic),
+            if strcmp(stateName,SBalgebraic(k2).name),
+                statefound = 1;
+                test = str2double(stateIC);
+                if isnan(test),
+                    % initial condition was not a numerical value
+                    error = sprintf('At least one initial condition for an algebraic state has a non-numerical value assigned');
+                    return;
+                else
+                    SBalgebraic(k2).initialCondition = test;
+                end
+                break;
+            end
+        end
+        if ~statefound,
+            % check if the state IC stems from an array definition
+            if isempty(strfind(stateName,'<')),
+                % no it doesn't
+                error = sprintf('At least one initial condition given\nfor a statename that does not appear\nin the ODE definitions.');
+                return;
+            else
+                % yes it does! so don't output an error but do something
+                % different. I will for now pass the IC information for
+                % array states using a global variable. Not nice but it
+                % should do the trick.
+                arrayInitialConditions_qayxsw(end+1).name = stateName;
+                arrayInitialConditions_qayxsw(end).ic = stateIC;
+            end
+        else
+            % state could have been found but it still is an array thing
+            % check it here
+            if ~isempty(strfind(stateName,'<')),
+                arrayInitialConditions_qayxsw(end+1).name = stateName;
+                arrayInitialConditions_qayxsw(end).ic = stateIC;    
+            end
+        end
+    end
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [SBparameters, error] = getParameters(parameters)
+error = '';
+%    parameters = removeWhiteSpace(parameters);
+SBparameters = struct('name',{},'value',{},'type',{},'compartment',{},'unittype',{},'notes',{});
+% get the starting indices for the parameters by finding the index
+% of the last '\n' before the '=' for each parameter
+parametersStart = regexp([10 parameters],['\n[^\n=]*=']);
+% run through the parameters and process them (+1 since endindex = end-1)
+parametersStart = [parametersStart length(parameters)+1];
+parNAN = 0;
+for k = 1:length(parametersStart)-1,
+    parameterString = removeCharacters(parameters(parametersStart(k):parametersStart(k+1)-1));
+    % check if additional information is present ... if yes, cut it out
+    infoStart = strfind(parameterString,'{');
+    infoEnd = strfind(parameterString,'}');
+    informationText = '';
+    if length(infoStart) + length(infoEnd) > 2,
+        error = 'To many curly parentheses in a parameter definition';
+        return
+    end
+    if length(infoStart) ~= length(infoEnd),
+        error = 'At least one parameter information not properly defined';
+        return
+    end
+    if length(infoStart) == 1,
+        informationText = parameterString(infoStart+1:infoEnd-1);
+        parameterString = parameterString([1:infoStart-1, infoEnd+1:end]);
+    end
+    if ~isempty(informationText),
+        % explode the information text with ':'
+        terms = explodePCSB(informationText,':');
+        if length(terms) == 1 && ~isempty(strfind(lower(terms{1}),'parameter')),
+            type = strtrim(terms{1});
+            compartment = '';
+            unittype = '';
+        elseif length(terms) == 2 && ~isempty(strfind(lower(terms{1}),'compartment')),
+            type = strtrim(terms{1});
+            compartment = strtrim(terms{2});
+            unittype = '';
+        elseif length(terms) == 3 && ~isempty(strfind(lower(terms{1}),'specie')),
+            type = strtrim(terms{1});
+            compartment = strtrim(terms{2});
+            unittype = strtrim(terms{3});
+        else
+            error = 'Error in a parameter information';
+            return           
+        end
+    else 
+        type = '';
+        compartment = '';
+        unittype = '';
+    end
+    % extract the parameter name
+    temp = strfind(parameterString,'=');
+    test = parameterString(1:temp(1)-1);
+    % check if parameter name given
+    if isempty(test),
+        error = sprintf('At least one parameter name not given.');
+        return
+    end
+    SBparameters(k).name = removeWhiteSpace(test);
+    % extract the parameter value
+    % check if it has a numerical value
+    test = parameterString(temp+1:end);
+    % The test string contains now the parameter value and eventually also a
+    % comment that should be written into notes.
+    % check if a comment is present
+    temp = strfind(test,'%');
+    if ~isempty(temp),
+        value = str2double(removeWhiteSpace(test(1:temp(1)-1)));
+        notes = strtrim(test(temp(1)+1:end));
+    else
+        value = str2double(removeWhiteSpace(test));
+        notes = '';
+    end
+    if isnan(value),
+        % initial condition was not a numerical value
+        parNAN = 1;
+    else
+        SBparameters(k).value = value;
+    end
+    % add default notes to parameter
+    SBparameters(k).notes = notes;
+    % add information to parameter
+    SBparameters(k).type = type;
+    SBparameters(k).compartment = compartment;
+    SBparameters(k).unittype = unittype;
+end
+if parNAN,
+    error = sprintf('At least one parameter has a\nnon-numerical value assigned');
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [SBvariables, error] = getVariables(variables)
+error = '';
+%    variables = removeWhiteSpace(variables);
+SBvariables = struct('name',{},'formula',{},'type',{},'compartment',{},'unittype',{},'notes',{});
+% get the starting indices for the variables by finding the index
+% of the last '\n' before the '=' for each variable
+variablesStart = regexp([10 variables],['\n[^\n=]*=']);
+% run through the variables and process them (+1 since endindex = end-1)
+variablesStart = [variablesStart length(variables)+1];
+for k = 1:length(variablesStart)-1,
+    variableString = removeCharacters(variables(variablesStart(k):variablesStart(k+1)-1));
+    % check if additional information is present ... if yes, cut it out
+    infoStart = strfind(variableString,'{');
+    infoEnd = strfind(variableString,'}');
+    informationText = '';
+    if length(infoStart) + length(infoEnd) > 2,
+        error = 'To many curly parentheses in a variable definition';
+        return
+    end
+    if length(infoStart) ~= length(infoEnd),
+        error = 'At least one variable information not properly defined';
+        return
+    end
+    if length(infoStart) == 1,
+        informationText = variableString(infoStart+1:infoEnd-1);
+        variableString = variableString([1:infoStart-1, infoEnd+1:end]);
+    end
+    if ~isempty(informationText),
+        % explode the information text with ':'
+        terms = explodePCSB(informationText,':');
+        if length(terms) == 1 && ~isempty(strfind(lower(terms{1}),'parameter')),
+            type = strtrim(terms{1});
+            compartment = '';
+            unittype = '';
+        elseif length(terms) == 2 && ~isempty(strfind(lower(terms{1}),'compartment')),
+            type = strtrim(terms{1});
+            compartment = strtrim(terms{2});
+            unittype = '';
+        elseif length(terms) == 3 && ~isempty(strfind(lower(terms{1}),'specie')),
+            type = strtrim(terms{1});
+            compartment = strtrim(terms{2});
+            unittype = strtrim(terms{3});
+        else
+            error = 'Error in a variable information';
+            return           
+        end
+    else 
+        type = '';
+        compartment = '';
+        unittype = '';
+    end
+    % extract the variable name
+    temp = strfind(variableString,'=');
+    test = variableString(1:temp(1)-1);
+    % check if variable name given
+    if isempty(test),
+        error = sprintf('At least one variable name not given.');
+        return
+    end
+    SBvariables(k).name = removeWhiteSpace(test);
+    % extract the variable value
+    test = variableString(temp+1:end);
+    % The test string contains now the variable expression and
+    % eventually also a comment that should be written into notes.
+    % check if a comment is present
+    temp = strfind(test,'%');
+    if ~isempty(temp),
+        formula = removeWhiteSpace(test(1:temp(1)-1));
+        notes = strtrim(test(temp(1)+1:end));
+    else
+        formula = removeWhiteSpace(test);
+        notes = '';
+    end
+    % check if variable expression given
+    if isempty(formula),
+        error = sprintf('At least one variable definition not given.');
+        return
+    end
+    SBvariables(k).formula = formula;
+    % add default notes to variable
+    SBvariables(k).notes = notes;
+    % add information to parameter
+    SBvariables(k).type = type;
+    SBvariables(k).compartment = compartment;
+    SBvariables(k).unittype = unittype;    
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [SBreactions, error] = getReactions(reactions)
+error = '';
+%    reactions = removeWhiteSpace(reactions);
+SBreactions = struct('name',{},'formula',{},'notes',{},'reversible',{},'fast',{});
+% get the starting indices for the reactions by finding the index
+% of the last '\n' before the '=' for each reaction
+reactionsStart = regexp([10 reactions],['\n[^\n=]*=']);
+% run through the reactions and process them (+1 since endindex = end-1)
+reactionsStart = [reactionsStart length(reactions)+1];
+for k = 1:length(reactionsStart)-1,
+    reactionString = removeCharacters(reactions(reactionsStart(k):reactionsStart(k+1)-1));
+    % extract the reaction name
+    temp = strfind(reactionString,'=');
+    test = reactionString(1:temp(1)-1);
+    % check if reaction name given
+    if isempty(test),
+        error = sprintf('At least one reaction name not given.');
+        return
+    end
+    SBreactions(k).name = removeWhiteSpace(test);
+    % extract the reaction value
+    test = reactionString(temp+1:end);
+    % The test string contains now the reaction expression, an optional
+    % "[reversible]" identifier and eventually also a comment that should be
+    % written into notes. 
+    % check if a comment is present
+    temp = strfind(test,'%');
+    if ~isempty(temp),
+        reaction = removeWhiteSpace(test(1:temp(1)-1));
+        notes = strtrim(test(temp(1)+1:end));
+    else
+        reaction = removeWhiteSpace(test);
+        notes = '';
+    end
+    % finally check if the "{reversible}" identifier is present.
+    temp = strfind(lower(reaction),'{reversible}');
+    if ~isempty(temp),
+        % reversible identifier is present - take it away and 
+        % set the flag to one, otherwise leave the expression untouched and
+        % set it to 0
+        reaction = strrep(reaction,'{reversible}','');
+        reversibleFlag = 1;
+    else
+        reversibleFlag = 0;
+    end
+    % finally finally check if the "{fast}" identifier is present.
+    temp = strfind(lower(reaction),'{fast}');
+    if ~isempty(temp),
+        % fast identifier is present - take it away and 
+        % set the flag to one, otherwise leave the expression untouched and
+        % set it to 0
+        reaction = strrep(reaction,'{fast}','');
+        fastFlag = 1;
+    else
+        fastFlag = 0;
+    end
+    % check if reaction expression given
+    reaction = removeWhiteSpace(reaction);
+    if isempty(reaction),
+        error = sprintf('At least one reaction definition not given.');
+        return
+    end
+    SBreactions(k).formula = reaction;
+    % add default notes to reaction
+    SBreactions(k).notes = notes;
+    % add the reversible flag
+    SBreactions(k).reversible = reversibleFlag;
+    % add the fast flag
+    SBreactions(k).fast = fastFlag;
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [SBfunctions, error] = getFunctions(functions)
+error = '';
+%    functions = removeWhiteSpace(functions);
+SBfunctions = struct('name',{},'arguments',{},'formula',{},'notes',{});
+% % get the starting indices for the function by finding the index
+% % of the last '\n' before the '=' for each function
+% functionsStart = [];
+% temp = strfind(functions,'=');
+% for k = 1:length(temp),
+%     % add a line break in the beginning since the first function might
+%     % not have one in front of it
+%     temp2 = [10 double(functions(1:temp(k)))];
+%     temp3 = find(temp2==10);
+%     functionsStart = [functionsStart temp3(end)];
+% end
+% % run through the reactions and process them (+1 since endindex = end-1)
+% functionsStart = [functionsStart length(functions)+1];
+
+% get the starting indices for the functions by finding the index
+% of the last '\n' before the '=' for each function
+functionsStart = regexp([10 functions],['\n[^\n=]*=']);
+% run through the functions and process them (+1 since endindex = end-1)
+functionsStart = [functionsStart length(functions)+1];
+
+for k = 1:length(functionsStart)-1,
+    functionString = removeCharacters(functions(functionsStart(k):functionsStart(k+1)-1));
+    % extract the function name
+    temp = strfind(functionString,'(');
+    test = functionString(1:temp(1)-1);
+    % check if function name given
+    if isempty(test),
+        error = sprintf('At least one function name not given.');
+        return
+    end
+    SBfunctions(k).name = removeWhiteSpace(test);
+    % extract the arguments
+    temp2 = strfind(functionString,')');
+    test = functionString(temp+1:temp2-1);
+    % check if function arguments given
+    if isempty(test),
+        error = sprintf('At least for one function no arguments given.');
+        return
+    end
+    SBfunctions(k).arguments = removeWhiteSpace(test);
+    % extract the formula
+    temp3 = strfind(functionString,'=');
+    test = functionString(temp3+1:end);
+    % The test string contains now the formula and
+    % eventually also a comment that should be written into notes.
+    % check if a comment is present
+    temp = strfind(test,'%');
+    if ~isempty(temp),
+        formula = removeWhiteSpace(test(1:temp(1)-1));
+        notes = strtrim(test(temp(1)+1:end));
+    else
+        formula = removeWhiteSpace(test);
+        notes = '';
+    end
+    % check if function formula given
+    if isempty(formula),
+        error = sprintf('At least for one function no formula given.');
+        return
+    end
+    SBfunctions(k).formula = formula;
+    % add default notes to function
+    SBfunctions(k).notes = notes;
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [SBevents, error] = getEvents(events)
+error = '';
+% event substructure
+eventassignmentStruct = struct('variable',{},'formula',{});
+SBevents = struct('name',{},'trigger',{},'assignment',eventassignmentStruct,'notes',{});
+
+% % get the starting indices for the events by finding the index
+% % of the last '\n' before the '=' for each event
+% eventsStart = [];
+% temp = strfind(events,'=');
+% for k = 1:length(temp),
+%     % add a line break in the beginning since the first event might
+%     % not have one in front of it
+%     temp2 = [10 double(events(1:temp(k)))];
+%     temp3 = find(temp2==10);
+%     eventsStart = [eventsStart temp3(end)];
+% end
+% eventsStart = [eventsStart length(events)+1];
+
+% get the starting indices for the events by finding the index
+% of the last '\n' before the '=' for each event
+eventsStart = regexp([10 events],['\n[^\n=]*=']);
+% run through the events and process them (+1 since endindex = end-1)
+eventsStart = [eventsStart length(events)+1];
+
+for k = 1:length(eventsStart)-1,
+    eventString = removeCharacters(events(eventsStart(k):eventsStart(k+1)-1));
+    % check if comment present
+    startNotes = strfind(eventString,'%');
+    notes = '';
+    if ~isempty(startNotes),
+        notes = eventString(startNotes(1)+1:end);
+        eventString = eventString(1:startNotes(1)-1);
+    end
+    SBevents(k).notes = notes;
+    % extract the event name
+    temp = strfind(eventString,'=');
+    test = strtrim(eventString(1:temp(1)-1));
+    % check if event name given
+    if isempty(test),
+        error = sprintf('At least one event has no name given.');
+        return
+    end
+    SBevents(k).name = removeWhiteSpace(test);
+    % get the right hand side
+    eventRHS = eventString(temp(1)+1:end);
+    % decompose the eventRHS into its comma separated elements
+    % taking into account parentheses
+    elementsRHS = explodePCSB(eventRHS);
+    % check number of elements
+    if length(elementsRHS) < 3 || mod(length(elementsRHS),2) == 0,
+        error = sprintf('At least one event has no full information given.');
+        return
+    end
+    % first element is assumed to be the trigger function
+    SBevents(k).trigger = removeWhiteSpace(elementsRHS{1});
+    % add the event assignments
+    indexAssignment = 1;
+    for k2 = 2:2:length(elementsRHS),
+        SBevents(k).assignment(indexAssignment).variable = removeWhiteSpace(elementsRHS{k2});
+        SBevents(k).assignment(indexAssignment).formula = removeWhiteSpace(elementsRHS{k2+1});
+        indexAssignment = indexAssignment + 1;
+    end
+
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DELETE WHITESPACES IN STRINGS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Useful for taking away whitespaces in kineticLaw formulas, as
+% seen in some example models
+function [outputString] = removeWhiteSpace(inputString)
+outputString = strrep(inputString,' ','');
+% return
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [output] = removeCharacters(input)
+% delete all line breaks and tabs from the input string
+temp = double(input);
+temp(find(temp==13)) = 32;  % replace '\cr' by white space
+temp(find(temp==10)) = 32;  % replace '\n' by white space
+temp(find(temp==9)) = 32;   % replace '\t' by white space
+output = char(temp);
+return
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/text2sbmodel/getPartsFromCompleteTextBCSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/text2sbmodel/getPartsFromCompleteTextBCSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..ad17202d38ce3c83a03adf149d0b1822c286c360
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/text2sbmodel/getPartsFromCompleteTextBCSB.m
@@ -0,0 +1,52 @@
+function [modelTextStructure] = getPartsFromCompleteTextSB(modelText)
+% getPartsFromCompleteTextSB: Cuts a text description of an SBmodel
+% into the different parts and returns them in a structure
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+% take commented lines out of the model description
+modelText = regexprep(modelText,'\n%[^\n]*','');
+
+% Find the starts of the different view data
+nameStart = strfind(modelText,'********** MODEL NAME');
+notesStart = strfind(modelText,'********** MODEL NOTES');
+statesStart = strfind(modelText,'********** MODEL STATE INFORMATION');
+parametersStart = strfind(modelText,'********** MODEL PARAMETERS');
+variablesStart = strfind(modelText,'********** MODEL VARIABLES');
+reactionsStart = strfind(modelText,'********** MODEL REACTIONS');
+functionsStart = strfind(modelText,'********** MODEL FUNCTIONS');
+eventsStart = strfind(modelText,'********** MODEL EVENTS');
+functionsMATLABStart = strfind(modelText,'********** MODEL MATLAB FUNCTIONS');
+% Cut out the different pieces and assign them to the modelTextStructure structure
+modelTextStructure.name = strtrim(modelText(nameStart+length('********** MODEL NAME'):notesStart-1));
+modelTextStructure.notes = strtrim(modelText(notesStart+length('********** MODEL NOTES'):statesStart-1));
+modelTextStructure.states = strtrim(modelText(statesStart+length('********** MODEL STATE INFORMATION'):parametersStart-1));
+modelTextStructure.parameters = strtrim(modelText(parametersStart+length('********** MODEL PARAMETERS'):variablesStart-1));
+modelTextStructure.variables = strtrim(modelText(variablesStart+length('********** MODEL VARIABLES'):reactionsStart-1));
+modelTextStructure.reactions = strtrim(modelText(reactionsStart+length('********** MODEL REACTIONS'):functionsStart-1));
+modelTextStructure.functions = strtrim(modelText(functionsStart+length('********** MODEL FUNCTIONS'):eventsStart-1));
+modelTextStructure.events = strtrim(modelText(eventsStart+length('********** MODEL EVENTS'):functionsMATLABStart-1));
+modelTextStructure.functionsMATLAB = strtrim(modelText(functionsMATLABStart+length('********** MODEL MATLAB FUNCTIONS'):end));
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/text2sbmodel/getPartsFromCompleteTextSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/text2sbmodel/getPartsFromCompleteTextSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..49e33933276f7c9db51f5550c9027b9b9c0d9d31
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/auxiliary/text2sbmodel/getPartsFromCompleteTextSB.m
@@ -0,0 +1,52 @@
+function [modelTextStructure] = getPartsFromCompleteTextExpSB(modelText)
+% getPartsFromCompleteTextSB: Cuts a text description of an SBmodel object
+% into the different parts and returns them in a structure
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+% take commented lines out of the model description
+modelText = regexprep(modelText,'\n%[^\n]*','');
+
+% Find the starts of the different view data
+nameStart = strfind(modelText,'********** MODEL NAME');
+notesStart = strfind(modelText,'********** MODEL NOTES');
+statesStart = strfind(modelText,'********** MODEL STATES');
+parametersStart = strfind(modelText,'********** MODEL PARAMETERS');
+variablesStart = strfind(modelText,'********** MODEL VARIABLES');
+reactionsStart = strfind(modelText,'********** MODEL REACTIONS');
+functionsStart = strfind(modelText,'********** MODEL FUNCTIONS');
+eventsStart = strfind(modelText,'********** MODEL EVENTS');
+functionsMATLABStart = strfind(modelText,'********** MODEL MATLAB FUNCTIONS');
+% Cut out the different pieces and assign them to the modelTextStructure structure
+modelTextStructure.name = strtrim(modelText(nameStart+length('********** MODEL NAME'):notesStart-1));
+modelTextStructure.notes = strtrim(modelText(notesStart+length('********** MODEL NOTES'):statesStart-1));
+modelTextStructure.states = strtrim(modelText(statesStart+length('********** MODEL STATES'):parametersStart-1));
+modelTextStructure.parameters = strtrim(modelText(parametersStart+length('********** MODEL PARAMETERS'):variablesStart-1));
+modelTextStructure.variables = strtrim(modelText(variablesStart+length('********** MODEL VARIABLES'):reactionsStart-1));
+modelTextStructure.reactions = strtrim(modelText(reactionsStart+length('********** MODEL REACTIONS'):functionsStart-1));
+modelTextStructure.functions = strtrim(modelText(functionsStart+length('********** MODEL FUNCTIONS'):eventsStart-1));
+modelTextStructure.events = strtrim(modelText(eventsStart+length('********** MODEL EVENTS'):functionsMATLABStart-1));
+modelTextStructure.functionsMATLAB = strtrim(modelText(functionsMATLABStart+length('********** MODEL MATLAB FUNCTIONS'):end));
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/isSBmodel.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/isSBmodel.m
new file mode 100644
index 0000000000000000000000000000000000000000..f7db78de534fc0bd668d343e15a819801dacdecd
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/isSBmodel.m
@@ -0,0 +1,23 @@
+function [output] = isSBmodel(model)
+% isSBmodel: check if input argument is an SBmodel.
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+output = strcmp(class(model),'SBmodel');
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/SBconvert2MA.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/SBconvert2MA.m
new file mode 100644
index 0000000000000000000000000000000000000000..4c33441c72c1e96f9d9e633a9cb55a73fd53ea4d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/SBconvert2MA.m
@@ -0,0 +1,150 @@
+function [MAstructure] = SBconvert2MA(model)
+% SBconvert2MA: Takes an SBmodel and if possible returns the stoichiometric
+% matrix, the numeric kinetic parameters, and the initial conditions. The
+% SBmodel is not allowed to contain variables, functions, events, or
+% functionsMATLAB. All right hand sides of the ODEs have to be defined in
+% terms of reaction names. All reactions need to be irreversible and mass action type! 
+%
+% Please note that the function is NOT parsing the reaction kinetics to
+% check if they are correct mass action kinetic rate laws. The user needs
+% to make sure that this is the case. Examples of correct expressions are:
+%   Reaction = k * species1 * species2
+%   Reaction = species1 * species2 * k
+%   Reaction = k * species1
+%   Reaction = 3.141592 * species1^2
+%   Reaction = species1^2
+% The kinetic rate constant is then simply determined by setting all
+% species concentrations to 1 and evaluating the rate expressions.
+%
+% USAGE:
+% ======
+% [MAstructure] = SBconvert2MA(model) 
+%
+% model: SBmodel 
+%
+% Output Arguments:
+% =================
+% MAstructure: structure containing information about the MA model
+%          MAstructure.N: stoichiometric matrix
+%          MAstructure.L: reactant stoichiometric matrix
+%          MAstructure.kineticParameters: vector containing the kinetic
+%               parameters for each reaction
+%          MAstructure.initialConditions: vector of initial conditions for all
+%               species
+%          MAstructure.species: cell-array with species names
+%          MAstructure.reactions: cell-array with reaction names
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE NON-NUMERIC INITIAL CONDITIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% just by replacing them
+model = SBconvertNonNum2NumIC(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Process the model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% make all reactions irreversible (if necessary)
+modelirr = SBmakeirreversible(model);
+% take away parenthesis around backward reaction expressions
+ms = struct(modelirr);
+for k = 1:length(ms.reactions),
+    ms.reactions(k).formula = strrep(ms.reactions(k).formula,'(','');
+    ms.reactions(k).formula = strrep(ms.reactions(k).formula,')','');
+end
+model = SBmodel(ms);
+SBstructure = SBstruct(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF NON DESIRED ELEMENTS ARE PRESENT IN THE MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% undesired: 
+%            - functions
+%            - variables
+%            - events
+%            - functionsMATLAB
+%            - states defined by rule
+% check functions, variables, events, functionsMATLAB
+if ~isempty(SBstructure.functions),
+    error('The model contains functions. This is not allowed when converting it to an MA representation.');
+end
+if ~isempty(SBstructure.variables),
+    error('The model contains variables. This is not allowed when converting it to an MA representation.');
+end
+if ~isempty(SBstructure.events),
+    error('The model contains events. This is not allowed when converting it to an MA representation.');
+end
+if ~isempty(SBstructure.functionsMATLAB),
+    error('The model contains MATLAB functions. This is not allowed when converting it to an MA representation.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK FOR REVERSIBLE REACTIONS (NOT ALLOWED)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[reactionNames, reactionFormulas] = SBreactions(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET THE (REACTANT) STOICHIOMETRIC MATRIX 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% also check if states are defined by rules, that is, not by summation of
+% reaction terms. easily done by checking the stoichiometric matrix and 
+% comparing number of components in it and number of all states in the
+% model.
+allStates = SBstates(model);
+[N,componentNames,reactionNames,reversibleFlag] = SBstoichiometry(model);
+if length(allStates) ~= length(componentNames),
+    error('Not all ODEs are expressed in terms of reactions. The full stoichiometric matrix can thus not be determined.');
+end
+L = SBreactantstoichiometry(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET THE KINETIC PARAMETERS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% do it very easy ... just set all concentrations to 1 and evaluate the
+% rate expressions. Under the required format for the rate expressions this
+% gives the kinetic parameters.
+[x,y,z,a,kineticParameters] = SBreactions(model,ones(1,length(allStates)));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET THE INITIAL CONDITIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+initialconditions = SBinitialconditions(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% FORMAT OUTPUT VALUES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+MAstructure.N = N;
+MAstructure.L = L;
+MAstructure.kineticParameters = kineticParameters(:);
+MAstructure.initialConditions = initialconditions(:);
+MAstructure.species = allStates;
+MAstructure.reactions = {SBstructure.reactions.name}';
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% RETURN
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+return
+
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/SBcreateODEfile.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/SBcreateODEfile.m
new file mode 100644
index 0000000000000000000000000000000000000000..36eb489d928fe924ec568d49b15f6fb0605f2684
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/SBcreateODEfile.m
@@ -0,0 +1,612 @@
+function SBcreateODEfile(varargin)
+% SBcreateODEfile: creates an m-file that can be simulated by 
+% using standard MATLAB integrators (ODE45, ODE23s, etc.)
+%
+% USAGE:
+% ======
+% [] = SBcreateODEfile(sbm)         
+% [] = SBcreateODEfile(sbm,filename)
+% [] = SBcreateODEfile(sbm,filename,dataFileFlag)
+% [] = SBcreateODEfile(sbm,filename,dataFileFlag,eventFlag)
+% [] = SBcreateODEfile(sbm,filename,dataFileFlag,eventFlag,augmKernelName)
+%
+% sbm: SBmodel to convert to an ODE file description
+% filename: filename for the created ODE file (without extension)
+% dataFileFlag: =1: creates an additional file allowing to determine
+%                   variable and reaction rate values for given state values 
+%                   and time vector.
+%               =0: doe not create the additional file
+% eventFlag: =1: creates 2 additional files for the handling of events in the model. 
+%            =0: does not create these two files.
+%            THE EVENT FILES ARE ONLY CREATED IN CASE THAT EVENTS ARE
+%            PRESENT IN THE MODEL
+% augmKernelName: needed for the simulation of fast reactions. It is the
+%           name of the global variable in which the mass matrix is
+%           defined. The name comes from the fact that the null space of
+%           the fast stoichiometric matrix is contained in the mass matrix.
+%            
+% DEFAULT VALUES:
+% ===============
+% filename: constructed from the models name
+% dataFileFlag: 0
+% eventFlag: 0
+% augmKernelName: ''
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GENERATE DELAY BASE NAME
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[dummy,delaybase] = fileparts(tempname);
+delaybase = char([double('delaybase_') double(delaybase(1:8))]);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+dataFileFlag = 0;
+eventFlag = 0;
+augmKernelName = '';
+tempFlag = 0;
+if nargin == 1,
+    sbm = varargin{1};
+    % convert object to structure
+    sbmstruct = struct(sbm);
+    % if no filename provided then use the name of the SBmodel as filename
+    % remove white spaces from the name.
+    functionName = strrep(sbmstruct.name,' ','');
+    functionName = strrep(functionName,'-','');
+    functionName = strrep(functionName,'+','');
+    functionName = strrep(functionName,'*','');
+    functionName = strrep(functionName,'/','');
+    filename = strcat(functionName,'.m');
+elseif nargin == 2,
+    sbm = varargin{1};
+    % convert object to structure
+    sbmstruct = struct(sbm);    
+    % extract filename from input argument number 2 - needed since 
+    % SBsimulate gives a whole path as filename
+    [PATHSTR,functionName,EXT] = fileparts(varargin{2});
+    if isempty(PATHSTR),
+        filename = strcat(functionName,'.m');
+    else
+        filename = strcat(PATHSTR,'/',functionName,'.m');
+    end
+elseif nargin == 3,
+    sbm = varargin{1};
+    % convert object to structure
+    sbmstruct = struct(sbm);    
+    % extract filename from input argument number 2 - needed since 
+    % SBsimulate gives a whole path as filename
+    [PATHSTR,functionName,EXT] = fileparts(varargin{2});
+    if isempty(PATHSTR),
+        filename = strcat(functionName,'.m');
+    else
+        filename = strcat(PATHSTR,'/',functionName,'.m');
+    end
+    dataFileFlag = varargin{3};
+elseif nargin == 4,
+    sbm = varargin{1};
+    % convert object to structure
+    sbmstruct = struct(sbm);    
+    % extract filename from input argument number 2 - needed since 
+    % SBsimulate gives a whole path as filename
+    [PATHSTR,functionName,EXT] = fileparts(varargin{2});
+    if isempty(PATHSTR),
+        filename = strcat(functionName,'.m');
+    else
+        filename = strcat(PATHSTR,'/',functionName,'.m');
+    end
+    dataFileFlag = varargin{3};
+    eventFlag = varargin{4};
+elseif nargin == 5,
+    sbm = varargin{1};
+    % convert object to structure
+    sbmstruct = struct(sbm);    
+    % extract filename from input argument number 2 - needed since 
+    % SBsimulate gives a whole path as filename
+    [PATHSTR,functionName,EXT] = fileparts(varargin{2});
+    if isempty(PATHSTR),
+        filename = strcat(functionName,'.m');
+    else
+        filename = strcat(PATHSTR,'/',functionName,'.m');
+    end
+    dataFileFlag = varargin{3};
+    eventFlag = varargin{4};   
+    augmKernelName = varargin{5};
+elseif nargin == 6,
+    sbm = varargin{1};
+    % convert object to structure
+    sbmstruct = struct(sbm);    
+    % extract filename from input argument number 2 - needed since 
+    % SBsimulate gives a whole path as filename
+    [PATHSTR,functionName,EXT] = fileparts(varargin{2});
+    if isempty(PATHSTR),
+        filename = strcat(functionName,'.m');
+    else
+        filename = strcat(PATHSTR,'/',functionName,'.m');
+    end
+    dataFileFlag = varargin{3};
+    eventFlag = varargin{4};   
+    augmKernelName = varargin{5};
+    tempFlag = varargin{6}; % set only by SBcreateTempODEfile to avoid event error message ... its annoying
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% MAKE augmKernelName a global variable
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(augmKernelName),
+    eval(sprintf('global %s',augmKernelName));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF MODEL CONTAINS STATES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(sbmstruct.states),
+    error('The model does not contain any states');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE THE EVENT FLAG
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% if the eventflag is set to a non-zero value AND at least on event is
+% present in the model an event function file is created that has to be 
+% used when calling the integrator. additionally a function is created 
+% that determines the new values to which the states have to be set. 
+if eventFlag == 1 && ~isempty(sbmstruct.events),
+    filenameEvent = strrep(filename,functionName,strcat('event_',functionName));
+    filenameEventAssignment = strrep(filename,functionName,strcat('event_assignment_',functionName));
+    SBcreateEventFunction(sbm,filenameEvent,delaybase);
+    SBcreateEventAssignmentFunction(sbm,filenameEventAssignment,delaybase);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE THE DATAFILE FLAG
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if dataFileFlag == 1,
+    filenameDataFile = strrep(filename,functionName,strcat('datafile_',functionName));
+    SBcreateSimulationDataFunction(sbm,filenameDataFile,delaybase);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% WRITE WARNING MESSAGE IN CASE EVENT FLAG IS NOT SET AND EVENTS ARE PRESENT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if eventFlag == 0 && ~isempty(sbmstruct.events) && tempFlag ~= 1,
+    if length(sbmstruct.events) == 1,
+        disp(sprintf('Warning: 1 event is present in the model.\nFor this analysis it is not taken into account.'));
+    else
+        disp(sprintf('Warning: %d events are present in the model.\nFor this analysis they are not taken into account.',length(sbmstruct.events)));
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OPEN FILE FOR WRITING
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen(filename,'w');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% WRITE FUNCTION DEFINITION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'function [output] = %s(varargin)\n',functionName);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% WRITE THE HEADER
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+fprintf(fid,'%% %s\n',sbmstruct.name);
+fprintf(fid,'%% Generated: %s\n',datestr(now));
+fprintf(fid,'%% \n');
+fprintf(fid,'%% [output] = %s() => output = initial conditions in column vector\n',functionName);
+fprintf(fid,'%% [output] = %s(''states'') => output = state names in cell-array\n',functionName);
+fprintf(fid,'%% [output] = %s(''algebraic'') => output = algebraic variable names in cell-array\n',functionName);
+fprintf(fid,'%% [output] = %s(''parameters'') => output = parameter names in cell-array\n',functionName);
+fprintf(fid,'%% [output] = %s(''parametervalues'') => output = parameter values in column vector\n',functionName);
+fprintf(fid,'%% [output] = %s(time,statevector) => output = time derivatives in column vector\n',functionName);
+fprintf(fid,'%% \n');
+fprintf(fid,'%% State names and ordering:\n');
+fprintf(fid,'%% \n');
+for k = 1:length(sbmstruct.states),
+    fprintf(fid,'%% statevector(%d): %s\n',k,sbmstruct.states(k).name);
+end
+fprintf(fid,'%% \n');
+if ~isempty(sbmstruct.algebraic),
+    didWriteStart = 0;
+    offset = length(sbmstruct.states);
+    offset2 = 1;
+    for k = 1:length(sbmstruct.algebraic),
+        if ~isempty(sbmstruct.algebraic(k).name) && didWriteStart == 0,    
+            fprintf(fid,'%% Algebraic variable names and ordering (included in state and IC vector):\n');
+            fprintf(fid,'%% \n'); 
+            didWriteStart = 1;
+        end
+        if ~isempty(sbmstruct.algebraic(k).name),
+            fprintf(fid,'%% statevector(%d): %s\n',offset+offset2,sbmstruct.algebraic(k).name);
+            offset2 = offset2 + 1;
+        end
+    end
+    if didWriteStart == 1,
+        fprintf(fid,'%% \n');
+    end
+end
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+fprintf(fid,'\n');
+fprintf(fid,'global time\n');
+if ~isempty(augmKernelName),
+    fprintf(fid,'global %s\n',augmKernelName);
+end 
+fprintf(fid,'parameterValuesNew = [];\n\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARARGINS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+fprintf(fid,'%% HANDLE VARIABLE INPUT ARGUMENTS\n');
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+fprintf(fid,'if nargin == 0,\n');
+    % Return initial conditions for state variables
+    % If all initial conditions are numeric then a vector is defined.
+    % Otherwise a cell-array with the corresponding entries. An additional
+    % outside function then needs to be used to calculate the correct ICs
+    % from the IC cellarray, IC values, and parameter values.
+    fprintf(fid,'\t%% Return initial conditions of the state variables (and possibly algebraic variables)\n');
+    if hasonlynumericICsSB(sbm),
+        icvector = [sbmstruct.states.initialCondition sbmstruct.algebraic.initialCondition];
+        if ~isempty(icvector),
+            fprintf(fid,'\toutput = [');
+        else
+            fprintf(fid,'\toutput = [];\n');
+        end
+        count = 0;
+        for k = 1:length(icvector)-1,
+            fprintf(fid,'%1.6g, ',icvector(k));
+            count = count + 1;
+            if count == 10, fprintf(fid,'...\n\t\t'); count = 0; end
+        end
+        if ~isempty(icvector),
+            fprintf(fid,'%1.6g];\n',icvector(end));
+        end
+        fprintf(fid,'\toutput = output(:);\n');
+    else
+        % the model contains non-numeric initial conditions
+        % get the ICs as cell-array
+        icvector = {sbmstruct.states.initialCondition sbmstruct.algebraic.initialCondition};
+        if ~isempty(icvector),
+            fprintf(fid,'\toutput = {');
+        else
+            fprintf(fid,'\toutput = {};\n');
+        end
+        count = 0;
+        for k = 1:length(icvector)-1,
+            if isnumeric(icvector{k}),
+                fprintf(fid,'%g, ',icvector{k});
+            else
+                fprintf(fid,'''%s'', ',strtrim(icvector{k}));
+            end
+            count = count + 1;
+            if count == 10, fprintf(fid,'...\n\t\t'); count = 0; end
+        end
+        if ~isempty(icvector),
+            if isnumeric(icvector{end}),
+                fprintf(fid,'%g};\n',icvector{end});
+            else
+                fprintf(fid,'''%s''};\n',strtrim(icvector{end}));
+            end
+        end
+    end
+    fprintf(fid,'\treturn\n');
+fprintf(fid,'elseif nargin == 1,\n');
+	fprintf(fid,'\tif strcmp(varargin{1},''states''),\n');
+        fprintf(fid,'\t\t%% Return state names in cell-array\n');
+        if ~isempty(sbmstruct.states),
+            fprintf(fid,'\t\toutput = {');
+        else
+            fprintf(fid,'\t\toutput = {};\n');
+        end 
+        count = 0;
+        for k = 1:length(sbmstruct.states)-1,
+            fprintf(fid,'''%s'', ',sbmstruct.states(k).name);
+            count = count + 1;
+            if count == 10, fprintf(fid,'...\n\t\t\t'); count = 0; end
+        end
+        if ~isempty(sbmstruct.states),
+            fprintf(fid,'''%s''};\n',sbmstruct.states(end).name);
+        end
+	fprintf(fid,'\telseif strcmp(varargin{1},''algebraic''),\n');
+        fprintf(fid,'\t\t%% Return algebraic variable names in cell-array\n');
+        if ~isempty(sbmstruct.algebraic),
+            fprintf(fid,'\t\toutput = {');
+        else
+            fprintf(fid,'\t\toutput = {};\n');
+        end 
+        count = 0;
+        for k = 1:length(sbmstruct.algebraic)-1,
+            if ~isempty(sbmstruct.algebraic(k).name),
+                fprintf(fid,'''%s'', ',sbmstruct.algebraic(k).name);
+                count = count + 1;
+                if count == 10, fprintf(fid,'...\n\t\t\t'); count = 0; end
+            end
+        end
+        if ~isempty(sbmstruct.algebraic),
+            if ~isempty(sbmstruct.algebraic(end).name),
+                fprintf(fid,'''%s''};\n',sbmstruct.algebraic(end).name);
+            else
+                fprintf(fid,'};\n');
+            end
+        end
+    fprintf(fid,'\telseif strcmp(varargin{1},''parameters''),\n');
+        fprintf(fid,'\t\t%% Return parameter names in cell-array\n');
+        if ~isempty(sbmstruct.parameters),
+            fprintf(fid,'\t\toutput = {');
+        else
+            fprintf(fid,'\t\toutput = {};\n');
+        end 
+        count = 0;
+        for k = 1:length(sbmstruct.parameters)-1,
+            fprintf(fid,'''%s'', ',sbmstruct.parameters(k).name);
+            count = count + 1;
+            if count == 10, fprintf(fid,'...\n\t\t\t'); count = 0; end
+        end
+        if ~isempty(sbmstruct.parameters),
+            fprintf(fid,'''%s''};\n',sbmstruct.parameters(length(sbmstruct.parameters)).name);
+        end
+    fprintf(fid,'\telseif strcmp(varargin{1},''parametervalues''),\n');
+        fprintf(fid,'\t\t%% Return parameter values in column vector\n');
+        if ~isempty(sbmstruct.parameters),
+            fprintf(fid,'\t\toutput = [');
+        else
+            fprintf(fid,'\t\toutput = [];\n');
+        end 
+        count = 0;
+        for k = 1:length(sbmstruct.parameters)-1,
+            fprintf(fid,'%1.6g, ',sbmstruct.parameters(k).value);
+            count = count + 1;
+            if count == 10, fprintf(fid,'...\n\t\t\t'); count = 0; end
+        end
+        if ~isempty(sbmstruct.parameters),
+            fprintf(fid,'%1.6g];\n',sbmstruct.parameters(length(sbmstruct.parameters)).value);
+        end
+    fprintf(fid,'\telse\n');
+        fprintf(fid,'\t\terror(''Wrong input arguments! Please read the help text to the ODE file.'');\n');
+    fprintf(fid,'\tend\n');
+    fprintf(fid,'\toutput = output(:);\n');
+    fprintf(fid,'\treturn\n');
+fprintf(fid,'elseif nargin == 2,\n');
+    fprintf(fid,'\ttime = varargin{1};\n');
+    fprintf(fid,'\tstatevector = varargin{2};\n');
+fprintf(fid,'elseif nargin == 3,\n');
+    fprintf(fid,'\ttime = varargin{1};\n');
+    fprintf(fid,'\tstatevector = varargin{2};\n');
+    fprintf(fid,'\tparameterValuesNew = varargin{3};\n');
+    fprintf(fid,'\tif length(parameterValuesNew) ~= %d,\n',length(sbmstruct.parameters));
+    fprintf(fid,'\t\tparameterValuesNew = [];\n');
+    fprintf(fid,'\tend\n');
+fprintf(fid,'elseif nargin == 4,\n');
+    fprintf(fid,'\ttime = varargin{1};\n');
+    fprintf(fid,'\tstatevector = varargin{2};\n');
+    fprintf(fid,'\tparameterValuesNew = varargin{4};\n');
+fprintf(fid,'else\n');
+    fprintf(fid,'\terror(''Wrong input arguments! Please read the help text to the ODE file.'');\n');
+fprintf(fid,'end\n');
+fprintf(fid,'\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INITIALIZE THE STATES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+fprintf(fid,'%% STATES\n');
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+for k = 1:length(sbmstruct.states)
+    fprintf(fid,'%s = statevector(%d);\n',sbmstruct.states(k).name,k);
+end
+fprintf(fid,'\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INITIALIZE THE ALGEBRAIC VARIABLES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(sbmstruct.algebraic),
+    didWriteStart = 0;
+    offset = length(sbmstruct.states);
+    offset2 = 1;
+    for k = 1:length(sbmstruct.algebraic)
+        if ~isempty(sbmstruct.algebraic(k).name) && didWriteStart == 0,
+            fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+            fprintf(fid,'%% ALGEBRAIC VARIABLES\n');
+            fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+            didWriteStart = 1;
+        end
+        if ~isempty(sbmstruct.algebraic(k).name),
+            fprintf(fid,'%s = statevector(%d);\n',sbmstruct.algebraic(k).name,offset+offset2);
+            offset2 = offset2 + 1;
+        end
+    end
+    if didWriteStart == 1,
+        fprintf(fid,'\n');
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INITIALIZE THE PARAMETES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(sbmstruct.parameters),
+    fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+    fprintf(fid,'%% PARAMETERS\n');
+    fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+    fprintf(fid,'if isempty(parameterValuesNew),\n');
+    for k = 1:length(sbmstruct.parameters),
+        fprintf(fid,'\t%s = %1.6g;\n',sbmstruct.parameters(k).name,sbmstruct.parameters(k).value);
+    end
+    fprintf(fid,'else\n');
+    for k = 1:length(sbmstruct.parameters),
+        fprintf(fid,'\t%s = parameterValuesNew(%d);\n',sbmstruct.parameters(k).name,k);
+    end
+    fprintf(fid,'end\n');
+    fprintf(fid,'\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INITIALIZE THE VARIABLES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(sbmstruct.variables),
+    fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+    fprintf(fid,'%% VARIABLES\n');
+    fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+    for k = 1:length(sbmstruct.variables),
+        delayname = [delaybase '_var_' sprintf('%d',k)];
+        fprintf(fid,'%s = %s;\n',sbmstruct.variables(k).name,processFormulaSB(sbmstruct.variables(k).formula,delayname));
+    end
+    fprintf(fid,'\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INITIALIZE THE REACTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(sbmstruct.reactions),
+    fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+    fprintf(fid,'%% REACTION KINETICS \n');
+    fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+    for k = 1:length(sbmstruct.reactions),
+        delayname = [delaybase '_reac_' sprintf('%d',k)];
+        fprintf(fid,'%s = %s;\n',sbmstruct.reactions(k).name,processFormulaSB(sbmstruct.reactions(k).formula,delayname));
+    end
+    fprintf(fid,'\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE ALSO EVENTASSIGNMENTS (NEEDED TO BE ABLE TO HANDEL DELAYS IN
+% EVENT ASSIGNMENTS (for delayed events)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(sbmstruct.events),
+    fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+    fprintf(fid,'%% EVENT ASSIGNMENTS AND TRIGGERS ... to handle delayed events\n');
+    fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+    for k = 1:length(sbmstruct.events),
+        delayname = [delaybase '_eventtrigger_' sprintf('%d',k)];        
+        fprintf(fid,'eventtrigger_%d = %s;\n',k,processFormulaSB(sbmstruct.events(k).trigger,delayname));
+        for k2 = 1:length(sbmstruct.events(k).assignment),
+            delayname = [delaybase '_eventassign_' sprintf('%d',k) '_' sprintf('%d',k2)];        
+            fprintf(fid,'eventassign_%d_%d = %s;\n',k,k2,processFormulaSB(sbmstruct.events(k).assignment(k2).formula,delayname));
+        end
+    end
+    fprintf(fid,'\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% WRITE THE ODES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+fprintf(fid,'%% DIFFERENTIAL EQUATIONS\n');
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+for k = 1:length(sbmstruct.states),   
+    delayname = [delaybase '_ode_' sprintf('%d',k)];
+    fprintf(fid,'%s_dot = %s;\n',sbmstruct.states(k).name,processFormulaSB(sbmstruct.states(k).ODE,delayname));
+end
+fprintf(fid,'\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% WRITE THE ALGEBRAIC RULES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(sbmstruct.algebraic),
+    fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+    fprintf(fid,'%% ALGEBRAIC RULES\n');
+    fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+    for k = 1:length(sbmstruct.algebraic)
+        fprintf(fid,'AlgebraicRule_%d = %s;\n',k,sbmstruct.algebraic(k).formula);
+    end
+    fprintf(fid,'\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% WRITE RETURN VALUES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+fprintf(fid,'%% RETURN VALUES\n');
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+if isempty(augmKernelName),
+    fprintf(fid,'%% STATE ODEs\n');
+    for k = 1:length(sbmstruct.states),
+        fprintf(fid,'output(%d) = %s_dot;\n',k,sbmstruct.states(k).name);
+    end
+    if ~isempty(sbmstruct.algebraic),
+        fprintf(fid,'%% ARs\n');
+        offset = length(sbmstruct.states);
+        for k = 1:length(sbmstruct.algebraic),
+            fprintf(fid,'output(%d) = AlgebraicRule_%d;\n',k+offset,k);
+        end
+    end
+else
+    fprintf(fid,'%% STATE ODEs ... HANDLING FAST REACTIONS\n');
+    for k = 1:length(sbmstruct.states),
+        fprintf(fid,'states(%d) = %s_dot;\n',k,sbmstruct.states(k).name);
+    end
+    fprintf(fid,'%% MULTIPLY WITH AUGMENTED KERNEL\n');
+    fprintf(fid,'output = %s*states(:);\n',augmKernelName);
+    if ~isempty(sbmstruct.algebraic),
+        fprintf(fid,'%% ARs\n');
+        offset = eval(sprintf('size(%s,1);',augmKernelName));
+        for k = 1:length(sbmstruct.algebraic),
+            fprintf(fid,'output(%d) = AlgebraicRule_%d;\n',k+offset,k);
+        end
+    end    
+end
+fprintf(fid,'%% return a column vector \n');
+% Return a column vector
+fprintf(fid,'output = output(:);\n');
+fprintf(fid,'return\n');
+fprintf(fid,'\n');
+fprintf(fid,'\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% WRITE THE FUNCTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(sbmstruct.functions),
+    fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+    fprintf(fid,'%% FUNCTIONS\n');
+    fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+    for k = 1:length(sbmstruct.functions),
+        fprintf(fid,'function [result] = %s(%s)\n',sbmstruct.functions(k).name,sbmstruct.functions(k).arguments);
+        fprintf(fid,'global time\n');
+        delayname = [delaybase '_func_' sprintf('%d',k)];        
+        fprintf(fid,'result = %s;\n',processFormulaSB(sbmstruct.functions(k).formula,delayname));
+        fprintf(fid,'return\n');
+        fprintf(fid,'\n');
+    end
+    fprintf(fid,'\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% WRITE THE MATLAB FUNCTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(sbmstruct.functionsMATLAB),
+    fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+    fprintf(fid,'%% MATLAB FUNCTIONS\n');
+    fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+    delayname = [delaybase '_funcmatlab'];
+    fprintf(fid,'%s',processFormulaSB(sbmstruct.functionsMATLAB,delayname));
+    fprintf(fid,'\n');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CLOSE THE FILE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+status = fclose(fid);
+rehash
+% Return
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/SBcreateTEXTBCfile.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/SBcreateTEXTBCfile.m
new file mode 100644
index 0000000000000000000000000000000000000000..96c1fc2b45ddf6d6696d753876d3abbcb6b165c3
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/SBcreateTEXTBCfile.m
@@ -0,0 +1,70 @@
+function SBcreateTEXTBCfile(varargin)
+% SBcreateTEXTBCfile: creates a *.txtbc file with the models text
+% description in a biochemically oriented format
+%
+% USAGE:
+% ======
+% [] = SBcreateTEXTBCfile(sbm)         
+% [] = SBcreateTEXTBCfile(sbm,filename)
+%
+% sbm: SBmodel to convert to a textfile description
+% filename: filename for the created textfile (.txtbc)
+%
+% DEFAULT VALUES:
+% ===============
+% filename: constructed from the models name
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 1,
+    sbm = varargin{1};
+    % convert object to structure
+    ms = struct(sbm);    
+    % if no filename provided then use the name of the SBmodel as filename
+    % remove unwanted characters first
+    functionName = regexprep(ms.name,'\W','');
+    filename = strcat(functionName,'.txtbc');
+elseif nargin == 2,
+    sbm = varargin{1};
+    filename = strcat(varargin{2},'.txtbc');
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONVERT MODEL TO TEXT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[modelTextBCStructure] = convertModelToTextBCSB(sbm);
+[completeTextBC] = setPartsToCompleteTextBCSB(modelTextBCStructure);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% WRITE THE FILE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen(filename,'w');
+fwrite(fid,completeTextBC);
+fclose(fid);
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/SBcreateTEXTfile.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/SBcreateTEXTfile.m
new file mode 100644
index 0000000000000000000000000000000000000000..91512bbea1340ee3af2f4c5b987af5d5603b7113
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/SBcreateTEXTfile.m
@@ -0,0 +1,72 @@
+function SBcreateTEXTfile(varargin)
+% SBcreateTEXTfile: creates a *.txt file with the models text description
+% based on ordinary differential equations
+%
+% USAGE:
+% ======
+% [] = SBcreateTEXTfile(sbm)         
+% [] = SBcreateTEXTfile(sbm,filename)
+%
+% sbm: SBmodel to convert to a textfile description
+% filename: filename for the created textfile 
+%
+% DEFAULT VALUES:
+% ===============
+% filename: constructed from the models name
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 1,
+    sbm = varargin{1};
+    % convert object to structure
+    ms = struct(sbm);    
+    % if no filename provided then use the name of the SBmodel as filename
+    % remove unwanted characters first
+    functionName = regexprep(ms.name,'\W','');
+    filename = strcat(functionName,'.txt');
+elseif nargin == 2,
+    sbm = varargin{1};
+    filename = strcat(varargin{2},'.txt');
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONVERT MODEL TO TEXT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[modelTextStructure] = convertModelToTextSB(sbm);
+[completeText] = setPartsToCompleteTextSB(modelTextStructure);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% WRITE THE FILE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen(filename,'w');
+fwrite(fid,completeText);
+fclose(fid);
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/SBcreateTempODEfile.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/SBcreateTempODEfile.m
new file mode 100644
index 0000000000000000000000000000000000000000..a92ceaa04cd7fb74eef9be21b072bbf32627ed5b
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/SBcreateTempODEfile.m
@@ -0,0 +1,122 @@
+function [ODEfctname, ODEfilefullpath, DATAfctname, EVENTfctname, EVENTASSGNfctname] = SBcreateTempODEfile(varargin)
+% SBcreateTempODEfile: creates a temporary ODE file, same as
+% SBcreateODEfile, but the file is written in the systems temporary
+% directory. Creates also datafile and eventhandling files if wanted.
+% No filename is passed, but a temporary filename is chosen automatically
+% and returned back as output argument.
+%
+% USAGE:
+% ======
+% [ODEfctname, ODEfilefullpath] = SBcreateTempODEfile(sbm)
+% [ODEfctname, ODEfilefullpath, DATAfctname] = SBcreateTempODEfile(sbm,dataFileFlag)
+% [ODEfctname, ODEfilefullpath, DATAfctname, EVENTfctname, EVENTASSGNfctname] = SBcreateTempODEfile(sbm,dataFileFlag,eventFlag)
+% [ODEfctname, ODEfilefullpath, DATAfctname, EVENTfctname, EVENTASSGNfctname] = SBcreateTempODEfile(sbm,dataFileFlag,eventFlag,augmKernelName)
+%
+% sbm: SBmodel to convert to an ODE file description
+% dataFileFlag: =1: creates an additional file allowing to determine
+%                   variable and reaction rate values for given state values 
+%                   and time vector.
+%               =0: doe not create the additional file
+% eventFlag: =1: creates 2 additional files for the handling of events in the model. 
+%            =0: does not create these two files.
+%            THE EVENT FILES ARE ONLY CREATED IN CASE THAT EVENTS ARE
+%            PRESENT IN THE MODEL            
+%
+% DEFAULT VALUES:
+% ===============
+% dataFileFlag: 0
+% eventFlag: 0
+%
+% OUTPUT ARGUMENTS:
+% =================
+% ODEfctname: name of the function (filename without .m extension)
+% DATAfctname: name of the datafile function (filename without .m extension)
+% EVENTfctname: name of the event function (filename without .m extension)
+% EVENTASSGNfctname: name of the event assignment function (filename without .m extension)
+% ODEfilefullpath: complete path to the created ODE file (including .m extension)
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% TEMPDIR 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+addpath(tempdirSB);   % add it to the path
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+eventFlag = 0;
+dataFileFlag = 0;
+augmKernelName = '';
+if nargin == 1,
+    sbm = varargin{1};
+elseif nargin == 2,
+    sbm = varargin{1};
+    dataFileFlag = varargin{2};
+elseif nargin == 3,
+    sbm = varargin{1};
+    dataFileFlag = varargin{2};
+    eventFlag = varargin{3};
+elseif nargin == 4,
+    sbm = varargin{1};
+    dataFileFlag = varargin{2};
+    eventFlag = varargin{3};
+    augmKernelName = varargin{4};
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET TEMP FILE NAME
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get temporary filenme
+tempfilefullpath = tempnameSB;
+[pathstr,tempfilename,ext] = fileparts(tempfilefullpath);     
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CREATE THE FILES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+tempFlag = 1; % to avoid the event warning when creating files for models with events w/o setting the event flag
+SBcreateODEfile(sbm,tempfilefullpath,dataFileFlag,eventFlag,augmKernelName,tempFlag);
+rehash;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CREATE THE FILE NAMES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ODEfctname = tempfilename;
+if dataFileFlag == 1,
+    DATAfctname = strcat('datafile_',ODEfctname);
+else 
+    DATAfctname = '';
+end
+if eventFlag == 1,
+    EVENTfctname = strcat('event_',ODEfctname);
+    EVENTASSGNfctname = strcat('event_assignment_',ODEfctname);
+else
+    EVENTfctname = '';
+    EVENTASSGNfctname = '';
+end
+ODEfilefullpath = strcat(tempfilefullpath,'.m');
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/auxiliary/SBcreateEventAssignmentFunction.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/auxiliary/SBcreateEventAssignmentFunction.m
new file mode 100644
index 0000000000000000000000000000000000000000..e17b6ea54662bde104847b030db753d3dc071c73
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/auxiliary/SBcreateEventAssignmentFunction.m
@@ -0,0 +1,192 @@
+function [] = SBcreateEventAssignmentFunction(sbm,filename,varargin)
+% SBcreateEventAssignmentFunction: writes the event assignments to be
+% performed
+%
+% USAGE:
+% ======
+% [] = SBcreateEventFunction(sbm,filename)
+%
+% sbm: SBmodel  (ODE file model description is not possible to use)
+% filename: the filename to which wo write the model
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+%
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+%
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
+% USA.
+
+if nargin == 3,
+    delaybase = varargin{1};
+else
+    delaybase = '';
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF SBmodel (not really needed but safer)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBmodel(sbm),
+    error('Function only defined for SBmodels.');
+end
+sbmstruct = struct(sbm);
+
+[PATHSTR,functionName,EXT] = fileparts(filename);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OPEN FILE FOR WRITING AND WRITE HEADER
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen(filename,'w');
+fprintf(fid,'function [newstates,parameterValuesNew] = %s(eventIndex,time_local,statevector,parameterValuesNew)\n',functionName);
+fprintf(fid,'%% This function is used to determine the resulting new states when an event has fired.\n\n');
+fprintf(fid,'global time\n');
+fprintf(fid,'time = time_local;\n\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% WRITE THE MODEL STUFF TO INITIALIZE all eventually needed data
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+fprintf(fid,'%% MODEL DATA\n');
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+% PROCESS STATES
+stateNames = SBstates(sbm);
+for k = 1:length(stateNames),
+    fprintf(fid,'%s = statevector(%d);\n',stateNames{k},k);
+end
+% ALGEBRAIC VARIABLES
+if ~isempty(sbmstruct.algebraic),
+    didWriteStart = 0;
+    algebraicNames = {sbmstruct.algebraic.name};
+    offset = length(stateNames);
+    offset2 = 1;
+    for k = 1:length(algebraicNames),
+        if didWriteStart == 0 && ~isempty(algebraicNames{k}),
+            fprintf(fid,'%% ALGEBRAIC VARIABLES\n');
+            didWriteStart = 1;
+        end
+        if ~isempty(algebraicNames{k}),
+            fprintf(fid,'%s = statevector(%d);\n',algebraicNames{k},offset+offset2);
+            offset2 = offset2+1;
+        end
+    end
+else
+    algebraicNames = {};
+end
+
+% PROCESS PARAMETERS
+[parameterNames,parameterValues] = SBparameters(sbm);
+fprintf(fid,'if isempty(parameterValuesNew),\n');
+for k = 1:length(parameterNames),
+    fprintf(fid,'\t%s = %g;\n',parameterNames{k},parameterValues(k));
+end
+fprintf(fid,'else\n');
+for k = 1:length(parameterNames),
+    fprintf(fid,'\t%s = parameterValuesNew(%d);\n',parameterNames{k},k);
+end
+fprintf(fid,'end\n');
+% PROCESS VARIABLES
+[variableNames,variableFormulas] = SBvariables(sbm);
+for k = 1:length(variableNames),
+    delayname = [delaybase '_var_' sprintf('%d',k)];
+    fprintf(fid,'%s = %s;\n',variableNames{k},processFormulaSB(variableFormulas{k},delayname));
+end
+% PROCESS REACTIONS
+[reactionNames,reactionFormulas] = SBreactions(sbm);
+for k = 1:length(reactionNames),
+    delayname = [delaybase '_var_' sprintf('%d',k)];
+    fprintf(fid,'%s = %s;\n',reactionNames{k},processFormulaSB(reactionFormulas{k},delayname));
+end
+% PROCESS EVENT ASSIGNMENTS
+for k = 1:length(sbmstruct.events),
+    for k2 = 1:length(sbmstruct.events(k).assignment),
+        delayname = [delaybase '_eventassign_' sprintf('%d',k) '_' sprintf('%d',k2)];
+        fprintf(fid,'eventassign_%d_%d = %s;\n',k,k2,processFormulaSB(sbmstruct.events(k).assignment(k2).formula,delayname));
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXECUTE THE EVENT ASSIGNMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+fprintf(fid,'%% EVENT ASSIGNMENTS\n');
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+% assign new states with old states
+for k = 1:length(stateNames),
+    fprintf(fid,'%s_new = %s;\n',stateNames{k},stateNames{k});
+end
+% assign new algebraic with old
+for k = 1:length(algebraicNames),
+    if ~isempty(algebraicNames{k}),
+        fprintf(fid,'%s_new = %s;\n',algebraicNames{k},algebraicNames{k});
+    end
+end
+% assign new parameters with old parameters
+for k = 1:length(parameterNames),
+    fprintf(fid,'%s_new = %s;\n',parameterNames{k},parameterNames{k});
+end
+
+% then do the event assignments
+for k = 1:length(sbmstruct.events),
+    fprintf(fid,'if sum(ismember(eventIndex,%d)) ~= 0,\n',k);
+    for k2 = 1:length(sbmstruct.events(k).assignment),
+        fprintf(fid,'\t%s_new = eventassign_%d_%d;\n',sbmstruct.events(k).assignment(k2).variable,k,k2);
+    end
+    fprintf(fid,'end\n');
+end
+
+% then return the changed new states and new parameters
+for k = 1:length(stateNames),
+    fprintf(fid,'newstates(%d) = %s_new;\n',k,stateNames{k});
+end
+offset = length(stateNames);
+for k = 1:length(algebraicNames),
+    if ~isempty(algebraicNames{k}),
+        fprintf(fid,'newstates(%d) = %s_new;\n',k+offset,algebraicNames{k});
+    end
+end
+for k = 1:length(parameterNames),
+    fprintf(fid,'parameterValuesNew(%d) = %s_new;\n',k,parameterNames{k});
+end
+fprintf(fid,'\n');
+% return
+fprintf(fid,'return\n');
+fprintf(fid,'\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Continue writing model stuff
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% WRITE MODEL FUNCTIONS
+[functionNames,functionFormulas,functionArguments] = SBfunctions(sbm);
+for k = 1:length(functionNames),
+    fprintf(fid,'function [result] = %s(%s)\n',functionNames{k},functionArguments{k});
+    fprintf(fid,'global time\n');
+    delayname = [delaybase '_func_' sprintf('%d',k)];
+    fprintf(fid,'result = %s;\n',processFormulaSB(functionFormulas{k},delayname));
+    fprintf(fid,'return\n');
+    fprintf(fid,'\n');
+end
+% WRITE THE MATLAB FUNCTIONS
+functionsMATLAB = SBfunctionsMATLAB(sbm);
+if ~isempty(functionsMATLAB),
+    delayname = [delaybase '_funcmatlab'];
+    fprintf(fid,'%s',processFormulaSB(functionsMATLAB,delayname));
+    fprintf(fid,'\n');
+end
+% CLOSE FILE
+fclose(fid);
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/auxiliary/SBcreateEventFunction.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/auxiliary/SBcreateEventFunction.m
new file mode 100644
index 0000000000000000000000000000000000000000..79cb3e526df38e91b22c0fc322a0af5741cdde0c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/auxiliary/SBcreateEventFunction.m
@@ -0,0 +1,179 @@
+function [] = SBcreateEventFunction(sbm,filename,varargin)
+% SBcreateEventFunction: writes the event handling function that is
+% necessary to pass to the intergrator in order to be able to deal with
+% discrete state events when doing simulations. This function is called is
+% called by the function SBcreateODEfile in the case that the event flag is
+% set and at least one event is present in the model.
+%
+% USAGE:
+% ======
+% [] = SBcreateEventFunction(sbm,filename)
+%
+% sbm: SBmodel  (ODE file model description is not possible to use)
+% filename: the filename to which wo write the model
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+if nargin == 3,
+    delaybase = varargin{1};
+else
+    delaybase = '';
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF SBmodel (not really needed but safer)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBmodel(sbm),
+    error('Function only defined for SBmodels.');
+end
+sbmstruct = struct(sbm);
+
+[PATHSTR,functionName,EXT] = fileparts(filename);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EVENT TRIGGER DATA
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+triggerVector = '';
+for k = 1:length(sbmstruct.events),
+    delayname = [delaybase '_eventtrigger_' sprintf('%d',k)];    
+    trigger = processFormulaSB(sbmstruct.events(k).trigger,delayname);
+    triggerString = sprintf('double(%s)-0.5',trigger);
+    % add trigger to vector
+    triggerVector = sprintf('%s%s\n',triggerVector,triggerString);
+end
+triggerVector = triggerVector(1:end-1);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OPEN FILE FOR WRITING AND WRITE HEADER
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen(filename,'w');
+fprintf(fid,'function [value,isterminal,direction] = %s(time_local,statevector,varargin)\n',functionName);
+fprintf(fid,'%% This function is passed to the MATLAB integrator in order to detect\n%% events that are present in the model.\n\n');
+fprintf(fid,'global time\n');
+fprintf(fid,'time = time_local;\n\n');
+
+fprintf(fid,'parameterValuesNew = [];\n');
+fprintf(fid,'if nargin == 3,\n');
+fprintf(fid,'    parameterValuesNew = varargin{1};\n');
+fprintf(fid,'end\n\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% WRITE THE MODEL STUFF TO INITIALIZE all eventually needed data
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+fprintf(fid,'%% MODEL DATA\n');
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+% PROCESS STATES
+stateNames = SBstates(sbm);
+for k = 1:length(stateNames),
+   fprintf(fid,'%s = statevector(%d);\n',stateNames{k},k);
+end
+% ALGEBRAIC VARIABLES
+if ~isempty(sbmstruct.algebraic),
+    didWriteStart = 0;
+    algebraicNames = {sbmstruct.algebraic.name};
+    offset = length(stateNames);
+    offset2 = 1;
+    for k = 1:length(algebraicNames),
+        if didWriteStart == 0 && ~isempty(algebraicNames{k}),
+            fprintf(fid,'%% ALGEBRAIC VARIABLES\n');
+            didWriteStart = 1;
+        end
+        if ~isempty(algebraicNames{k}),
+            fprintf(fid,'%s = statevector(%d);\n',algebraicNames{k},offset+offset2);
+            offset2 = offset2+1;
+        end
+    end
+end
+
+
+% PROCESS PARAMETERS
+[parameterNames,parameterValues] = SBparameters(sbm);
+fprintf(fid,'if isempty(parameterValuesNew),\n');
+for k = 1:length(parameterNames),
+    fprintf(fid,'\t%s = %g;\n',parameterNames{k},parameterValues(k));
+end
+fprintf(fid,'else\n'); 
+for k = 1:length(parameterNames),
+    fprintf(fid,'\t%s = parameterValuesNew(%d);\n',parameterNames{k},k);
+end
+fprintf(fid,'end\n');
+% PROCESS VARIABLES
+[variableNames,variableFormulas] = SBvariables(sbm);
+for k = 1:length(variableNames),
+   delayname = [delaybase '_var_' sprintf('%d',k)];        
+   fprintf(fid,'%s = %s;\n',variableNames{k},processFormulaSB(variableFormulas{k},delayname));
+end 
+% PROCESS REACTIONS
+[reactionNames,reactionFormulas] = SBreactions(sbm);
+for k = 1:length(reactionNames),
+   delayname = [delaybase '_reac_' sprintf('%d',k)];    
+   fprintf(fid,'%s = %s;\n',reactionNames{k},processFormulaSB(reactionFormulas{k},delayname));
+end
+% PROCESS EVENT ASSIGNMENTS
+for k = 1:length(sbmstruct.events),
+    for k2 = 1:length(sbmstruct.events(k).assignment),
+        delayname = [delaybase '_eventassign_' sprintf('%d',k) '_' sprintf('%d',k2)];
+        fprintf(fid,'eventassign_%d_%d = %s;\n',k,k2,processFormulaSB(sbmstruct.events(k).assignment(k2).formula,delayname));
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% WRITE THE EVENT DATA
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+fprintf(fid,'%% EVENT DATA\n');
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+fprintf(fid,'value = [%s]'';\n',triggerVector);
+fprintf(fid,'isterminal = ones(1,%d);\n',length(sbmstruct.events));
+fprintf(fid,'direction = ones(1,%d);\n',length(sbmstruct.events));
+fprintf(fid,'\n');
+
+% return
+fprintf(fid,'return\n');
+fprintf(fid,'\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Continue writing model stuff
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% WRITE MODEL FUNCTIONS
+[functionNames,functionFormulas,functionArguments] = SBfunctions(sbm);
+for k = 1:length(functionNames),
+    fprintf(fid,'function [result] = %s(%s)\n',functionNames{k},functionArguments{k});
+    fprintf(fid,'global time\n');
+    delayname = [delaybase '_func_' sprintf('%d',k)];    
+    fprintf(fid,'result = %s;\n',processFormulaSB(functionFormulas{k},delayname));
+    fprintf(fid,'return\n');
+    fprintf(fid,'\n');
+end
+% WRITE THE MATLAB FUNCTIONS
+functionsMATLAB = SBfunctionsMATLAB(sbm);
+if ~isempty(functionsMATLAB),
+    delayname = [delaybase '_funcmatlab'];    
+    fprintf(fid,'%s',processFormulaSB(functionsMATLAB,delayname));
+    fprintf(fid,'\n');
+end
+% CLOSE FILE
+fclose(fid);
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/auxiliary/SBcreateSimulationDataFunction.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/auxiliary/SBcreateSimulationDataFunction.m
new file mode 100644
index 0000000000000000000000000000000000000000..08809c73cc80b37519abe63934bf56a54fe56bfd
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/auxiliary/SBcreateSimulationDataFunction.m
@@ -0,0 +1,300 @@
+function [] = SBcreateSimulationDataFunction(sbm,filename,varargin)
+% SBcreateSimulationDataFunction: is called by SBcreateODEfile to create a
+% function that is able to calculate the values of the variables and
+% parameters for given state or state time series.
+%
+% USAGE:
+% ======
+% [] = SBcreateSimulationDataFunction(sbm, filename)
+%
+% sbm: SBmodel
+% filename: the name of the file to be created
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+if nargin == 3,
+    delaybase = varargin{1};
+else
+    delaybase = '';
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF SBmodel (not really needed but safer)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBmodel(sbm),
+    error('Function only defined for SBmodels.');
+end
+sbmstruct = struct(sbm);
+
+[PATHSTR,functionName,EXT] = fileparts(filename);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OPEN FILE FOR WRITING AND WRITE HEADER
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fid = fopen(filename,'w');
+fprintf(fid,'function [output] = %s(varargin)\n',functionName);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% WRITE THE HEADER
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+fprintf(fid,'%% %s\n',sbmstruct.name);
+fprintf(fid,'%% Generated: %s\n',datestr(now));
+fprintf(fid,'%% \n');
+fprintf(fid,'%% [output] = %s(statevector) => time=0\n',functionName);
+fprintf(fid,'%% [output] = %s(time,statevector)\n',functionName);
+fprintf(fid,'%% \n');
+fprintf(fid,'%% output: structure containing information about the values of the variables\n');
+fprintf(fid,'%%         and reaction rates for given time and state information.\n');
+fprintf(fid,'%% \n');
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+fprintf(fid,'\n');
+fprintf(fid,'parameterValuesNew_ALL = [];\n\n');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARARGINS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+fprintf(fid,'%% HANDLE VARIABLE INPUT ARGUMENTS\n');
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+fprintf(fid,'if nargin == 1,\n');
+
+    fprintf(fid,'\ttime_vector = [0];\n');
+    fprintf(fid,'\tstatevector = varargin{1};\n');
+
+fprintf(fid,'elseif nargin == 2,\n');
+
+    fprintf(fid,'\ttime_vector = varargin{1};\n');
+    fprintf(fid,'\tstatevector = varargin{2};\n');
+
+fprintf(fid,'elseif nargin == 3,\n');
+
+    fprintf(fid,'\ttime_vector = varargin{1};\n');
+    fprintf(fid,'\tstatevector = varargin{2};\n');
+    fprintf(fid,'\tparameterValuesNew_ALL = varargin{3};\n');
+
+fprintf(fid,'else\n');
+    fprintf(fid,'\terror(''Incorrect number of input arguments.'');\n');
+fprintf(fid,'end\n');
+fprintf(fid,'\n');
+
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+fprintf(fid,'%% DETERMINE DATA\n');
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+fprintf(fid,'variableValuesTotal = [];\n');
+fprintf(fid,'reactionValuesTotal = [];\n');
+fprintf(fid,'if length(time_vector) == 1,\n');
+    fprintf(fid,'\tstatevector = statevector(:)'';\n');
+    fprintf(fid,'\t[variableValuesTotal, reactionValuesTotal] = getValues(time_vector,statevector,parameterValuesNew_ALL);\n');
+fprintf(fid,'else\n');
+    fprintf(fid,'\tfor k = 1:length(time_vector),\n');
+        fprintf(fid,'\t\tif ~isempty(parameterValuesNew_ALL),\n');
+        fprintf(fid,'\t\t\t[variableValues, reactionValues] = getValues(time_vector(k),statevector(k,:),parameterValuesNew_ALL(k,:));\n');
+        fprintf(fid,'\t\telse\n');
+        fprintf(fid,'\t\t\t[variableValues, reactionValues] = getValues(time_vector(k),statevector(k,:),[]);\n');
+        fprintf(fid,'\t\tend\n');    
+        fprintf(fid,'\t\tvariableValuesTotal = [variableValuesTotal; variableValues];\n');
+        fprintf(fid,'\t\treactionValuesTotal = [reactionValuesTotal; reactionValues];\n');
+    fprintf(fid,'\tend\n');
+fprintf(fid,'end\n');
+
+variableNames = SBvariables(sbm);
+reactionNames = SBreactions(sbm);
+stateNames = SBstates(sbm);
+algebraicNames = SBalgebraic(sbm);
+
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+fprintf(fid,'%% CONSTRUCT OUTPUT VARIABLE\n');
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+fprintf(fid,'output.time = time_vector;\n');
+fprintf(fid,'output.states = ');
+if ~isempty(stateNames),
+    fprintf(fid,'{');
+    for k = 1:length(stateNames),
+        fprintf(fid,'''%s'',',stateNames{k});
+    end
+    fprintf(fid,'};\n');
+else
+    fprintf(fid,'{};\n');
+end
+fprintf(fid,'output.statevalues = statevector(:,1:%d);\n',length(stateNames));
+
+if ~isempty(algebraicNames),
+    didWriteStart = 0;
+    for k = 1:length(algebraicNames),
+        if didWriteStart == 0 && ~isempty(algebraicNames{k}),
+            fprintf(fid,'output.algebraic = ');
+            fprintf(fid,'{');
+            didWriteStart = 1;
+        end
+        if ~isempty(algebraicNames{k}),
+            fprintf(fid,'''%s'',',algebraicNames{k});
+        end
+    end
+    if didWriteStart == 1,
+        fprintf(fid,'};\n');
+        fprintf(fid,'output.algebraicvalues = statevector(:,%d:end);\n',length(stateNames)+1);
+    end
+end
+
+
+
+
+
+fprintf(fid,'output.variables = ');
+if ~isempty(variableNames),
+    fprintf(fid,'{');
+    for k = 1:length(variableNames),
+        fprintf(fid,'''%s'',',variableNames{k});
+    end
+    fprintf(fid,'};\n');
+else
+    fprintf(fid,'{};\n');
+end
+fprintf(fid,'output.variablevalues = variableValuesTotal;\n');
+fprintf(fid,'output.reactions = ');
+if ~isempty(reactionNames),
+    fprintf(fid,'{');
+    for k = 1:length(reactionNames),
+        fprintf(fid,'''%s'',',reactionNames{k});
+    end
+    fprintf(fid,'};\n');
+else 
+    fprintf(fid,'{};\n');
+end
+fprintf(fid,'output.reactionvalues = reactionValuesTotal;\n');
+
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+fprintf(fid,'%% Clear global variables used for delay handling\n');
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+fprintf(fid,'clear global %s*\n\n',delaybase);
+
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+fprintf(fid,'%% RETURN\n');
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+fprintf(fid,'return\n');
+fprintf(fid,'\n');
+fprintf(fid,'\n');
+
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+fprintf(fid,'%% getValues FUNCTION\n');
+fprintf(fid,'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
+fprintf(fid,'function [variableValues, reactionValues] = getValues(time_local,statevector,parameterValuesNew)\n');
+fprintf(fid,'global time\n');
+
+fprintf(fid,'variableValues = [];\n');
+fprintf(fid,'reactionValues = [];\n\n');
+
+fprintf(fid,'time = time_local;\n\n');
+
+% PROCESS STATES
+fprintf(fid,'%% STATES\n');
+stateNames = SBstates(sbm);
+for k = 1:length(stateNames),
+   fprintf(fid,'%s = statevector(%d);\n',stateNames{k},k);
+end
+
+% PROCESS ALGEBRAIC VARIABLES (IF PRESENT)
+if ~isempty(sbmstruct.algebraic),
+    didWriteStart = 0;
+    algebraicNames = {sbmstruct.algebraic.name};
+    offset = length(stateNames);
+    offset2 = 1;
+    for k = 1:length(algebraicNames),
+        if didWriteStart == 0 && ~isempty(algebraicNames{k}),
+            fprintf(fid,'%% ALGEBRAIC VARIABLES\n');
+            didWriteStart = 1;
+        end
+        if ~isempty(algebraicNames{k}),
+            fprintf(fid,'%s = statevector(%d);\n',algebraicNames{k},offset+offset2);
+            offset2 = offset2+1;
+        end
+    end
+end
+
+% PROCESS PARAMETERS
+fprintf(fid,'%% PARAMETERS\n');
+[parameterNames,parameterValues] = SBparameters(sbm);
+fprintf(fid,'if isempty(parameterValuesNew),\n');
+for k = 1:length(parameterNames),
+    fprintf(fid,'\t%s = %g;\n',parameterNames{k},parameterValues(k));
+end
+fprintf(fid,'else\n');
+for k = 1:length(parameterNames),
+    fprintf(fid,'\t%s = parameterValuesNew(%d);\n',parameterNames{k},k);
+end
+fprintf(fid,'end\n');
+fprintf(fid,'\n');
+
+% PROCESS VARIABLES
+fprintf(fid,'%% VARIABLES\n');
+[variableNames,variableFormulas] = SBvariables(sbm);
+for k = 1:length(variableNames),
+   delayname = [delaybase '_var_' sprintf('%d',k)];    
+   fprintf(fid,'%s = %s;\n',variableNames{k},processFormulaSB(variableFormulas{k},delayname));
+end
+
+% PROCESS REACTIONS
+fprintf(fid,'%% REACTIONS\n');
+[reactionNames,reactionFormulas] = SBreactions(sbm);
+for k = 1:length(reactionNames),
+   delayname = [delaybase '_reac_' sprintf('%d',k)];
+   fprintf(fid,'%s = %s;\n',reactionNames{k},processFormulaSB(reactionFormulas{k},delayname));
+end
+
+% WRITE OUTPUT VARIABLES
+fprintf(fid,'%% OUTPUT\n');
+for k = 1:length(variableNames),
+   fprintf(fid,'variableValues(%d) = %s;\n',k,variableNames{k});
+end 
+for k = 1:length(reactionNames),
+   fprintf(fid,'reactionValues(%d) = %s;\n',k,reactionNames{k});
+end 
+fprintf(fid,'return\n');
+fprintf(fid,'\n');
+
+% WRITE MODEL FUNCTIONS
+fprintf(fid,'%% FUNCTIONS\n');
+[filenames,functionFormulas,functionArguments] = SBfunctions(sbm);
+for k = 1:length(filenames),
+    fprintf(fid,'function [result] = %s(%s)\n',filenames{k},functionArguments{k});
+    fprintf(fid,'global time\n');
+    delayname = [delaybase '_func_' sprintf('%d',k)];
+    fprintf(fid,'result = %s;\n',processFormulaSB(functionFormulas{k},delayname));
+    fprintf(fid,'return\n');
+    fprintf(fid,'\n');
+end
+
+% WRITE THE MATLAB FUNCTIONS
+fprintf(fid,'%% MATLAB FUNCTIONS\n');
+functionsMATLAB = SBfunctionsMATLAB(sbm);
+if ~isempty(functionsMATLAB),
+    delayname = [delaybase '_funcmatlab'];
+    fprintf(fid,'%s',processFormulaSB(functionsMATLAB,delayname));
+    fprintf(fid,'\n');
+end
+
+% CLOSE FILE
+fclose(fid);
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/auxiliary/convertTEXTArrayDefSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/auxiliary/convertTEXTArrayDefSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..c4f65d50cc9ae759e4b9743fed53b014758942fb
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/auxiliary/convertTEXTArrayDefSB.m
@@ -0,0 +1,378 @@
+function [msnew] = convertTEXTArrayDefSB(ms)
+
+% global variable for passing array state initial conditions from
+% convertTextToModelSB.m
+global arrayInitialConditions_qayxsw
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF MODEL CONTAINS ARRAYS, OTHERWISE RETURN
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+containsArrays = 0;
+for k=1:length(ms.states),
+    if ~isempty(strfind(ms.states(k).name,'<')),
+        containsArrays = 1;
+        break;
+    end
+end
+if containsArrays == 0,
+    for k=1:length(ms.variables),
+        if ~isempty(strfind(ms.variables(k).name,'<')),
+            containsArrays = 1;
+            break;
+        end
+    end
+end
+if containsArrays == 0,
+    for k=1:length(ms.reactions),
+        if ~isempty(strfind(ms.reactions(k).name,'<')),
+            containsArrays = 1;
+            break;
+        end
+    end
+end
+if containsArrays == 0,
+    msnew = ms;
+    return
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CREATE NEW MODELSTRUCT AND COPY UNCHANGED
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+msnew = struct(SBmodel);
+msnew.name              = ms.name;
+msnew.notes             = ms.notes;
+msnew.functions         = ms.functions;
+msnew.algebraic         = ms.algebraic;
+msnew.parameters        = ms.parameters;
+msnew.events            = ms.events;
+msnew.functionsMATLAB   = ms.functionsMATLAB;
+msnew.inputs            = ms.inputs;
+msnew.outputs           = ms.outputs;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE SPECIAL ARRAY FUNCTIONS 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Currently there is a single function that can be used: 'arraysumSB'.
+% However, there might be more in the future.
+% These functions can ONLY be used in the variable formulas. All other uses
+% are leading to errors.
+% Check all parts of the model first
+% States
+for k=1:length(ms.states),
+    if ~isempty(strfind(ms.states(k).ODE,'arraysumSB')),
+        error('arraysumSB is only allowed in the MODEL VARIABLES definition.');
+    end
+end
+% Reactions
+for k=1:length(ms.reactions),
+    if ~isempty(strfind(ms.reactions(k).formula,'arraysumSB')),
+        error('arraysumSB is only allowed in the MODEL VARIABLES definition.');
+    end
+end
+% Now check the variables
+for k=1:length(ms.variables),
+    if ~isempty(strfind(ms.variables(k).formula,'arraysumSB')),
+        ms.variables(k).formula = handleArraySumSB(ms.variables(k).name,ms.variables(k).formula,ms.parameters);
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE STATES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(ms.states),
+    % Check if array definition (<index,arrayrange>) by checking the name
+    arraydef = regexp(ms.states(k).name,'<[^<>]+>','match');
+    if isempty(arraydef),
+        % Just a normal state definition. Need to copy it and 
+        % deal with array elements that might appear on the RHS
+        msnew.states(end+1) = ms.states(k);
+        msnew.states(end).ODE = handleRHSs(msnew.states(end).ODE,msnew.parameters,[],[],'noeval');
+    else
+        % Its an array state. Need to handle the RHS as above and expand
+        % the array definition into single states. The LHS gives
+        % information about range and indexvariable.
+        arraydef = arraydef{1};
+        [indexvariable,range] = handleLHSs(arraydef,msnew.parameters,ms.states(k).name,'state');
+        % Get the base name of the state, etc.
+        basename = ms.states(k).name(1:end-length(arraydef));
+        ODEbase = ms.states(k).ODE;
+        % Expand the array
+        for k2=range,
+            if k2 >= 0,
+                newstate.name = sprintf('%s%d',basename,k2);
+            else
+                newstate.name = sprintf('%s_%d',basename,abs(k2));
+            end                
+            newstate.initialCondition = ms.states(k).initialCondition;
+            newstate.ODE = handleRHSs(ODEbase,ms.parameters,indexvariable,k2,'noeval');
+            newstate.type = ms.states(k).type;
+            newstate.compartment = ms.states(k).compartment;
+            newstate.unittype = ms.states(k).unittype;
+            newstate.notes = ms.states(k).notes;
+            msnew.states(end+1) = newstate;
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE REACTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(ms.reactions),
+    % Check if array definition (<index,arrayrange>) by checking the name
+    arraydef = regexp(ms.reactions(k).name,'<[^<>]+>','match');
+    if isempty(arraydef),
+        % Just a normal reaction definition. Need to copy it and 
+        % deal with array elements that might appear on the RHS
+        msnew.reactions(end+1) = ms.reactions(k);
+        msnew.reactions(end).formula = handleRHSs(msnew.reactions(end).formula,msnew.parameters,[],[],'noeval');
+    else
+        % Its an array reaction. Need to handle the RHS as above and expand
+        % the array definition into single reactions. The LHS gives
+        % information about range and indexvariable.
+        arraydef = arraydef{1};
+        [indexvariable,range] = handleLHSs(arraydef,msnew.parameters,ms.reactions(k).name,'reaction');
+        % Get the base name of the reaction, etc.
+        basename = ms.reactions(k).name(1:end-length(arraydef));
+        formulabase = ms.reactions(k).formula;
+        % Expand the array
+        for k2=range,
+            if k2 >= 0,
+                newreaction.name = sprintf('%s%d',basename,k2);
+            else
+                newreaction.name = sprintf('%s_%d',basename,abs(k2));
+            end                
+            newreaction.formula = handleRHSs(formulabase,ms.parameters,indexvariable,k2,'noeval');
+            newreaction.notes = ms.reactions(k).notes;
+            newreaction.reversible = ms.reactions(k).reversible;
+            newreaction.fast = ms.reactions(k).fast;
+            msnew.reactions(end+1) = newreaction;
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABLES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(ms.variables),
+    % Check if array definition (<index,arrayrange>) by checking the name
+    arraydef = regexp(ms.variables(k).name,'<[^<>]+>','match');
+    if isempty(arraydef),
+        % Just a normal variable definition. Need to copy it and 
+        % deal with array elements that might appear on the RHS
+        msnew.variables(end+1) = ms.variables(k);
+        msnew.variables(end).formula = handleRHSs(msnew.variables(end).formula,msnew.parameters,[],[],'noeval');
+    else
+        % Its an array variable. Need to handle the RHS as above and expand
+        % the array definition into single variables. The LHS gives
+        % information about range and indexvariable.
+        arraydef = arraydef{1};
+        [indexvariable,range] = handleLHSs(arraydef,msnew.parameters,ms.variables(k).name,'variable');
+        % Get the base name of the variable, etc.
+        basename = ms.variables(k).name(1:end-length(arraydef));
+        formulabase = ms.variables(k).formula;
+        % Expand the array
+        for k2=range,
+            if k2 >= 0,
+                newvariable.name = sprintf('%s%d',basename,k2);
+            else
+                newvariable.name = sprintf('%s_%d',basename,abs(k2));
+            end                
+            newvariable.formula = handleRHSs(formulabase,ms.parameters,indexvariable,k2,'noeval');
+            newvariable.type = ms.variables(k).type;
+            newvariable.compartment = ms.variables(k).compartment;
+            newvariable.unittype = ms.variables(k).unittype;
+            newvariable.notes = ms.variables(k).notes;
+            msnew.variables(end+1) = newvariable;
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE INITIAL CONDITIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isempty(arrayInitialConditions_qayxsw),
+    % There are initial conditions we need to take care of
+    ICdata = arrayInitialConditions_qayxsw;
+    icnames = {};
+    icvalues = [];
+    for k=1:length(ICdata),
+        name = ICdata(k).name;
+        ic = ICdata(k).ic;
+        % Check if array definition (<index,arrayrange>) by checking the name
+        arraydef = regexp(name,'<[^<>]+>','match');
+        if isempty(arraydef),
+            % There must have been an error
+            error('There seems to be a problem with the definition of the initial condition ''%''',name);
+        else
+            % Its an array IC. Need to handle the RHS as above and expand
+            % the array definition into single ICs. The LHS gives
+            % information about range and indexvariable. Then the data is
+            % added to the states.
+            arraydef = arraydef{1};
+            [indexvariable,range] = handleLHSs(arraydef,msnew.parameters,name,'IC');
+        end
+        % Get the base name of the ICstates, etc.
+        basename = name(1:end-length(arraydef));
+        formulabase = ic;
+        % Expand the array and build the icnames and the icvalues
+        for k2=range,
+            if k2 >= 0,
+                icnames{end+1} = sprintf('%s%d',basename,k2);
+            else
+                icnames{end+1} = sprintf('%s_%d',basename,abs(k2));
+            end
+            icvalues(end+1) = handleRHSs(formulabase,ms.parameters,indexvariable,k2,'eval');
+        end       
+        % Finally fit the ICs into the states structure
+        for k2=1:length(icnames),
+            stateindex = strmatchSB(icnames{k2},{msnew.states.name},'exact');
+            if isempty(stateindex),
+                error('The state ''%s'' for which an array-type initial condition is defined is not present in the model.',icnames{k2});
+            end
+            msnew.states(stateindex).initialCondition = icvalues(k2);
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% FINISHED
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+return
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE ARRAY SUM
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [newformula] = handleArraySumSB(name,formula,parameters)
+    newformula = formula;
+    % Allow only one call to arraysumSB per formula
+    index = strfind(newformula,'arraysumSB');
+    if length(index)>1,
+        error('Only one call to ''arraysumSB'' allowed per variable definition.');
+    end
+    % Split formula in three parts: before arraysumSB, the arguments of arraysumSB, and
+    % after arraysumSB
+    formulabefore = newformula(1:index-1);
+    help = newformula(index+length('arraysumSB('):end);
+    indexend = 0;
+    popen = 1;
+    while popen ~= 0,
+        indexend = indexend + 1;
+        if help(indexend) == '(',
+            popen = popen + 1;
+        end
+        if help(indexend) == ')',
+            popen = popen - 1;
+        end
+    end
+    formulaas = help(1:indexend-1);
+    formulaafter = help(indexend+1:end);
+    % Get the array information
+    arraydef = regexp(formulaas,'<[^<>]+>','match');
+    arraydef = arraydef{1};
+    [indexvariable,range] = handleLHSs(arraydef,parameters,name,'arraysumSB');
+    % Expand the expression
+    expression = '';
+    for k=range,
+        expressionk = formulaas;
+        % Replace index
+        if k>=0,
+            repindex = num2str(k);
+        else
+            repindex = ['_',num2str(abs(k))];
+        end
+        expressionk = strrep(expressionk,arraydef,repindex);
+        % Replace the index variable
+        regsearch = ['\<' indexvariable '\>'];
+        expressionk = regexprep(expressionk,regsearch,num2str(k));        
+        % Add to overall expression
+        if k==range(1),
+            expression = ['(' expressionk ')'];
+        else
+            expression = [expression '+' '(' expressionk ')'];
+        end
+    end
+    % put together the new forumla
+    newformula = [formulabefore expression formulaafter];
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE ARRAY <> THINGS IN LHSs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [indexvariable_qayxsw,range_qayxsw] = handleLHSs(arraydef_qayxsw,parameters_qayxsw,name_qayxsw,type_qayxsw)
+    % Get the index variable and its range
+    terms_qayxsw = explodePCSB(arraydef_qayxsw(2:end-1),',','[',']');
+    if length(terms_qayxsw)~=2,
+        error('Incorrect %s-array definition for %s ''%s''.',type_qayxsw,type_qayxsw,name_qayxsw);
+    end
+    indexvariable_qayxsw = terms_qayxsw{1};
+    range_qayxsw = terms_qayxsw{2};
+    if isempty(indexvariable_qayxsw) || isempty(range_qayxsw),
+        error('Incorrect %s-array definition for %s ''%s''.',type_qayxsw,type_qayxsw,name_qayxsw);
+    end
+    % Define all model parameters locally in this function (needed for the
+    % evaluation of the range)
+    for k_qayxsw=1:length(parameters_qayxsw),
+        eval(sprintf('%s = %g;',parameters_qayxsw(k_qayxsw).name,parameters_qayxsw(k_qayxsw).value));
+    end
+    % Evaluate the range variable
+    try
+        range_qayxsw = eval(range_qayxsw);
+    catch
+        error('Incorrect definition of the range for %s ''%s''.',type_qayxsw,name_qayxsw);
+    end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE ARRAY <> THINGS IN RHSs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [newRHS_qayxsw] = handleRHSs(RHS,parameters_qayxsw,indexvariable_qayxsw,indexvalue_qayxsw,eval_qayxsw)
+    newRHS_qayxsw = RHS;
+    % Get all the elements in <> and evaluate them
+    elements_qayxsw = unique(regexp(newRHS_qayxsw,'<[^<>]+>','match'));
+    % Define all model parameters locally in this function
+    for k_qayxsw=1:length(parameters_qayxsw),
+        eval(sprintf('%s = %g;',parameters_qayxsw(k_qayxsw).name,parameters_qayxsw(k_qayxsw).value));
+    end
+    % Handle and define indexvariable
+    if ~isempty(indexvariable_qayxsw),
+        % Check if indexvariable already exists (in the model) ... would be an error
+        errorIndexvariable_qayxsw = 0;
+        try 
+            eval(indexvariable_qayxsw);
+            errorIndexvariable_qayxsw = 1;
+        catch
+        end
+        if errorIndexvariable_qayxsw,
+            error('The index variable ''%s'' is defined as model parameter. This is not allowed.',indexvariable_qayxsw);
+        end
+        % Define the index variable
+        eval(sprintf('%s = %d;',indexvariable_qayxsw,indexvalue_qayxsw));
+    end
+    % Evaluate the contents of the brackets (they are indices for the array)
+    elements_values_qayxsw = [];
+    for k_qayxsw=1:length(elements_qayxsw),
+        elements_values_qayxsw(k_qayxsw) = eval(sprintf('%s;',elements_qayxsw{k_qayxsw}(2:end-1)));
+    end
+    % Replace the brackets with the values
+    for k_qayxsw=1:length(elements_qayxsw),
+        if elements_values_qayxsw(k_qayxsw) >= 0,
+            newRHS_qayxsw = strrep(newRHS_qayxsw,elements_qayxsw{k_qayxsw},sprintf('%d',elements_values_qayxsw(k_qayxsw)));
+        else
+            newRHS_qayxsw = strrep(newRHS_qayxsw,elements_qayxsw{k_qayxsw},sprintf('_%d',abs(elements_values_qayxsw(k_qayxsw))));
+        end
+    end    
+    % Replace the indexvariable in a second step
+    if ~isempty(indexvariable_qayxsw),
+        regsearch_qayxsw = ['\<' indexvariable_qayxsw '\>'];
+        newRHS_qayxsw = regexprep(newRHS_qayxsw,regsearch_qayxsw,num2str(indexvalue_qayxsw));
+    end
+    % Evaluate the RHS is desired
+    if length(eval_qayxsw) == 4,  % ('eval')
+        try
+            newRHS_qayxsw = eval(newRHS_qayxsw);
+        catch
+            error('Error evaluating the RHS (needs to lead to a numeric value): ''%s''',newRHS_qayxsw);
+        end
+    end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/auxiliary/processFormulaSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/auxiliary/processFormulaSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..cb2aa42ec639ae3802720b0e1addfeaba3451155
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/classeshandling/modelhandling/methods/auxiliary/processFormulaSB.m
@@ -0,0 +1,58 @@
+function [formula] = processFormulaSB(formula,delaybasename)
+% processFormulaSB: process different things in formulas for the ODE file
+% export. Right now we only take care of delaySB functions where some info
+% needs to be added.
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+count = 1;
+while 1,
+    index = strfind(formula,'delaySB(');
+    if length(index) < count,
+        break;
+    end
+    indexstart = index(count)+length('delaySB(');
+    indexend = indexstart;
+    
+    % search the end of the delay argument definition
+    parOpen = 1;
+    while parOpen ~= 0,
+        if formula(indexend) == '(',
+            parOpen = parOpen + 1;
+        elseif formula(indexend) == ')',
+            parOpen = parOpen - 1;
+        end
+        indexend = indexend + 1;
+    end
+    % check if the delaybasename has to be changed
+    if length(index) > 1,
+        delayname = [delaybasename '_' sprintf('%d', count)];
+    else
+        delayname = delaybasename;
+    end
+    % add info to delaySB call
+    firstpart = formula(1:indexend-2);
+    lastpart = formula(indexend-1:end);
+    middlepart = sprintf(',time,''%s''',delayname);
+    formula = char([double(firstpart) double(middlepart) double(lastpart)]);
+    % increase counter
+    count = count + 1;
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/installSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/installSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..b4028f497b724118ac6ae660d4416bf9ff9c6d63
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/installSB.m
@@ -0,0 +1,124 @@
+function [] = installSB()
+% installSB
+% Installation function for the SBTOOLBOX2. 
+% Edit the data below to match your system and run it.
+%
+%       installSB
+%
+% This function can be called with the optional syntax:
+%
+%       installSB('quick')
+%
+% This adds the SBTOOLBOX2 and all subdirectories to the MATLAB path.
+% Additionally all needed c-code functions are compiled for your system.
+
+% Information:
+% ============
+% Copyright (C) 2005-2010 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EDIT THE FOLLOWING VARIABLES TO MATCH YOUR SYSTEM
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% libSBML - only needed if not WINDOWS
+% ====================================
+% Add the path to the folder in which the TranslateSBML and the OutputSBML 
+% MEX functions are located. Only needed for Unix/Linux/Mac users, since
+% the Windows MEX functions are included in the SBTOOLBOX2.
+%
+% You can obtain the required files for installation from here:
+% http://sourceforge.net/projects/sbml/files/libsbml/
+PATH_libSBMLfunctions = ''; 
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% BELOW NO MANUAL CHANGES ARE REQUIRED
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check that installSB is started in the right folder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+currentDir = pwd;
+installSBDir = fileparts(which('installSB.m'));
+if ~strcmp(currentDir,installSBDir),
+    error('Run the ''installSB'' script from the folder where it is located.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check that correct local path (network paths are not allowed)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp(currentDir(1:2),'\\'),
+    error(sprintf('The installation can not be run from a network path (\\\\...).\nPlease run the installation from a local path.'));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if SBTOOLBOX2 already installed
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+SBT2ver = ver('SBTOOLBOX2');
+if length(SBT2ver) >= 1,
+    error('You seem to already have an installation of SBTOOLBOX2. Please use "restoredefaultpath" before installing a different version.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add SBTOOLBOX2 etc. to the path 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+addpath(genpath(pwd));
+addpath(genpath(PATH_libSBMLfunctions));
+addpath(tempdirSB)
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Compile and install the needed packages 
+% Compilation is done for Unix AND Windows systems
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+PATH_SBTOOLBOX2 = pwd();
+try
+    % interpcseSB
+    cd(fileparts(which('interpcseSB.m')));
+    mex interpcseSB.c
+    mex interpcseSlopeSB.c
+catch, end
+cd(PATH_SBTOOLBOX2)
+try
+    % isrsort
+    cd(fileparts(which('isrsort.c')));
+    mex isrsort.c
+catch, end
+cd(PATH_SBTOOLBOX2)
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Output license information, etc.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+disp(sprintf('SBTOOLBOX2 for MATLAB\n'));
+disp(sprintf('Developed by Henning Schmidt, info@sbtoolbox2.org.'));
+disp(sprintf('The SBTOOLBOX2 contains several third party packages, therefor'));
+disp(sprintf('copyright statements are present in the individual functions.'));
+disp(' ');
+disp(sprintf('This program is Free Open Source Software: you can redistribute it and/or modify '));
+disp(sprintf('it under the terms of the GNU General Public License as published by '));
+disp(sprintf('the Free Software Foundation, either version 3 of the License, or '));
+disp(sprintf('(at your option) any later version. '));
+disp(sprintf(' '));
+disp(sprintf('This program is distributed in the hope that it will be useful, '));
+disp(sprintf('but WITHOUT ANY WARRANTY; without even the implied warranty of '));
+disp(sprintf('MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the '));
+disp(sprintf('GNU General Public License for more details. '));
+disp(sprintf(' '));
+disp(sprintf('You should have received a copy of the GNU General Public License '));
+disp(sprintf('along with this program. If not, see <http://www.gnu.org/licenses/>.'));
+disp(sprintf(' '));
+disp(sprintf(' '));
+disp(sprintf(' '));
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/license.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/license.txt
new file mode 100644
index 0000000000000000000000000000000000000000..65e0ebf47690538cf3e698281babeb102a06b81f
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/license.txt
@@ -0,0 +1,674 @@
+					 GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/analysis/SBjacobian.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/analysis/SBjacobian.m
new file mode 100644
index 0000000000000000000000000000000000000000..58de0da216cf2d59f8f6f1293000c29edf95cb10
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/analysis/SBjacobian.m
@@ -0,0 +1,147 @@
+function [jacobian,statenames] = SBjacobian(varargin)
+% SBjacobian: determines the Jacobian of a given SBmodel or an ODE file 
+% description. This function should only be used for time-invariant systems.
+% If used for time-variant systems an error will occur.
+%
+% USAGE:
+% ======
+% [jacobian] = SBjacobian(model,state)         
+% [jacobian] = SBjacobian(model,state,delta)         
+% [jacobian,statenames] = SBjacobian(model,state)         
+% [jacobian,statenames] = SBjacobian(model,state,delta)         
+%
+% model: SBmodel or ODE file model description
+% state: state at which to determine the Jacobian
+% delta: stepsize used for numerical differentiation. in case of nonzero
+%        states the applied change is relative, in case of a zero value the
+%        applied change is absolute.
+%
+% DEFAULT VALUES:
+% ===============
+% delta: 1e-4
+%
+% Output Arguments:
+% =================
+% jacobian: Jacobian of the model at the given state
+% statenames: cell-array with the names of the states of the model
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GLOBAL VARIABLE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+global ODEfctname
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PARAMETERS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Default stepsize for numerical differentiation
+DEFAULT_DELTA = 1e-4;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF SBMODEL OR FILENAME
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isSBmodel(varargin{1}),
+    % SBmodel
+    sbm = varargin{1};
+    % check delays and events
+    if usedelaySB(sbm),
+        error('The model contains delays. These can not be handled by this function.');
+    end
+    % Create temporary ODE file
+    [ODEfctname, ODEfilefullpath] = SBcreateTempODEfile(sbm);    
+else
+    % ODEfctname of ODE file
+    ODEfctname = varargin{1};
+    % Check if file exists
+    if exist(strcat(ODEfctname,'.m')) ~= 2,
+        error('ODE file could not be found.');
+    end
+end
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 2,
+    state = varargin{2};
+    delta = DEFAULT_DELTA;
+elseif nargin == 3,
+    state = varargin{2};
+    delta = varargin{3};
+else
+    error('Wrong number of input arguments');
+end
+% Check if correct number of elements in "state".
+teststate = feval(ODEfctname);
+if length(state) ~= length(teststate),
+    error('Number of elements in provided state-vector does not match the number of states in the model.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET JACOBIAN AT GIVEN STATE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+jacobian = calculateJacobian(state,delta);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET THE STATE NAMES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+statenames = feval(ODEfctname,'states');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DELETE FILE IF SBMODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp('SBmodel',class(varargin{1})),
+    deleteTempODEfileSB(ODEfilefullpath);
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Calculate Jacobian 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [jacobian] = calculateJacobian(state,delta)
+n = length(state);          % size of system
+jacobian = zeros(n,n);      % initialize jacobian variable
+% determine the Jacobian by numerical differentiation
+for k = 1:n,                
+    statedn = state;
+    stateup = state; 
+    if stateup(k) == 0,
+        stateup(k) = stateup(k) + delta;
+        jacobian(:,k) = (model(stateup)'-model(statedn)')/delta;
+    else
+        stateup(k) = stateup(k)*(1+delta);
+        jacobian(:,k) = (model(stateup)'-model(statedn)')/(delta*stateup(k));
+    end
+end
+return 
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [xdot] = model(x)
+    global ODEfctname
+    xdot = feval(ODEfctname,0,x);
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/analysis/SBmakeirreversible.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/analysis/SBmakeirreversible.m
new file mode 100644
index 0000000000000000000000000000000000000000..dc35df9a77a70875833910b1ddd43fe5fa500ed0
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/analysis/SBmakeirreversible.m
@@ -0,0 +1,308 @@
+function [output] = SBmakeirreversible(model)
+% SBmakeirreversible
+% For certain analysis methods it is useful that all reaction rate
+% expressions in a model are irreversible. This function takes an SBmodel
+% as input and replaces all reversible reactions by irreversible ones. This
+% is done by splitting up reversible reaction rates into one forward and one
+% backward rate. For this to be possible it is IMPORTANT that the reaction
+% rate expressions that are marked as reversible in the model are defined
+% in the following format:
+%
+%     ReactionRate = RateForward - RateReverse
+%
+% where "ReactionRate" can be any reaction rate name, and the terms
+% "RateForward" and "RateReverse" can be any mathematical expressions,
+% involving parameters, states, functions, and/or variables.
+% However, it is IMPORTANT that there is only one minus sign in the top
+% level of the formula. Minus signs in eventual parentheses are not taken
+% into account for the parsing and are therefor, of course, allowed to be
+% present.
+%
+% Examples: R1 = Rf1 - Rr1
+%           R2 = k1*A - k2*B
+%           R3 = (k1-k2*A) - (k3+k4*B)
+%
+% This function requires that each reaction only appears once in each ODE.
+% Example:    d/dt(A) = -R1 + R2        is OK
+%             d/dt(B) = -R1 + R2 + R1   is not OK 
+% 
+% Replace last ODE by:    d/dt(B) = R2   or do the irreversible making manually.
+%
+% USAGE:
+% ======
+% [output] = SBmakeirreversible(model)
+%
+% model: SBmodel for which to convert reversible reactions to irreversible ones.
+%
+% Output Arguments:
+% =================
+% output: converted model
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF SBmodel
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~strcmp('SBmodel',class(model)),
+    error('Function only defined for SBmodels.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SAVE ORIGINAL MODEL FOR LATER USE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+originalmodel = model;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK THAT ALL ODE EXPRESSIONS ARE DEFINED VIA REACTION TERMS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[Ntest,componentsTest] = SBstoichiometry(model,1);  % set rawFlag to 1 
+componentsModel = SBstates(model);
+if length(componentsTest) ~= length(componentsModel),
+    error('Not all ODEs seem to be constructed by reaction terms. Therefor the full stoichiometric information is not possible to determine.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET NAMES AND DATA OF REVERSIBLE REACTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[names,formulas,reversibleFlag,fastFlag] = SBreactions(model);
+reversibleReactionsAll = reversibleFlag;
+% check if reversible reactions are present
+if sum(reversibleFlag) == 0,
+    output = model;
+    disp('The model does not contain any reversible reactions.');
+    return
+end
+% get indices of reversible reactions
+reversibleIndices = find(reversibleFlag ~= 0);
+reactionsStore = [];
+for k = 1:length(reversibleIndices),
+    reactionsStore(k).name = names{reversibleIndices(k)};
+    reactionsStore(k).formula = formulas{reversibleIndices(k)};
+    reactionsStore(k).fastFlag = fastFlag(reversibleIndices(k));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK SYNTAX OF REACTION RATES (R = Rf-Rr)
+% AND SPLIT THEM UP INTO Rf and Rr
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+errorReversibleRateDefinitions = '';
+for k = 1:length(reactionsStore),
+    irreversibleRates = explodePCSB(reactionsStore(k).formula,'-');
+    if length(irreversibleRates) ~= 2,
+        % Need to have two parts that are separated by a '-' sign. (Forward
+        % first, then reverse reaction kinetics).
+        errorReversibleRateDefinitions = sprintf('%sError in rate definition of reaction rate ''%s''. It does not seem to be reversible.\n', errorReversibleRateDefinitions, reactionsStore(k).name);
+    else
+        % Seems fine ... save the different parts
+        reactionsStore(k).forwardRate = irreversibleRates{1};
+        reactionsStore(k).reverseRate = irreversibleRates{2};        
+    end
+end
+if ~isempty(errorReversibleRateDefinitions),
+    error(errorReversibleRateDefinitions);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DELETE REVERSIBLE RATES AND ADD IRREVERSIBLE ONES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k = 1:length(reactionsStore),
+    model = deletereactionratesSB(model, reactionsStore(k).name);
+    forwardReactionName = strcat(reactionsStore(k).name,'_forward');
+    reverseReactionName = strcat(reactionsStore(k).name,'_reverse');
+    reversibleFlag = 0;
+    notes = '';
+    model = addreactionrateSB(model, forwardReactionName, reactionsStore(k).forwardRate, notes, reversibleFlag, reactionsStore(k).fastFlag);
+    model = addreactionrateSB(model, reverseReactionName, reactionsStore(k).reverseRate, notes, reversibleFlag, reactionsStore(k).fastFlag);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET AND SAVE COMPARTMENT INFORMATION (original model)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[allComponentNames,allODEs] = SBstates(originalmodel);
+compartmentInformation = {}; % Strings ordered in the same way as states in the model
+% check if a scaling by the compartment volume is done.
+% in this case the expected syntax is 
+% ODE = ("reactionterms")/compartmentvolume
+% the compartment information is saved and used later to restore the ODEs
+for k = 1:length(allODEs),     
+    ODE = strtrim(allODEs{k});
+    numberOpenParentheses = length(find(ODE == '('));
+    numberClosedParentheses = length(find(ODE == ')'));
+    % all eventual errorneous cases are caught in the beginning of this
+    % function by calling SBstoichiometry
+    if ODE(1) == '(',
+        % if the first character is an open parenthesis then assume that 
+        % this is due to a adjustement to compartment sizes. here we only
+        % need to keep the compartment information.
+        % cut out the content of the parentheses
+        closeParenthesis = find(ODE == ')');
+        compartmentInformation{k} = ODE(closeParenthesis+1:end);
+    else
+        compartmentInformation{k} = '';
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% UPDATE RIGHT HAND SIDE OF THE ODES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% get model structure
+modelstruct = SBstruct(model);
+% determine stoichiometric information of original model to 
+% see where and with which stoichiometric coefficient the reversible
+% reactions come into play. The stoichiometry function takes care of
+% compartment factors by itself 
+N = SBstoichiometry(originalmodel,1); % set rawFlag to 1
+% get info about non elementary reactions and delete them from the
+% stoichiometric matrix (will be taken care off later)
+L = SBreactantstoichiometry(originalmodel,1); % reactant stoichiometry
+Lnone = L+N.*(N<0);
+if sum(sum(abs(Lnone))) ~= 0,
+    error('Same reaction appears in at least one ODE more than once. Please see the help text to SBmakeirreversible.');
+end
+% Rnone = N.*(Lnone~=0)+L.*(Lnone>0);
+% % now delete
+% N = N.*(Lnone == 0).*(Rnone == 0);
+
+% get the submatrix of N corresponding only to the irreversible reactions
+% reversibleIndices is same as determined above and irreversibleIndices can
+% be determined by
+irreversibleIndices = setdiff(1:length(SBreactions(originalmodel)),reversibleIndices);
+Nirrev = N(:,irreversibleIndices);
+% get the submatrix of N corresponding only to the reversible reactions
+% reversibleIndices is same as determined above
+Nrev = N(:,reversibleIndices);
+% clear all ODEs
+for k = 1:length(modelstruct.states),
+    modelstruct.states(k).ODE = '';
+end
+% cycle through the columns of Nirrev (irreversible reaction rates) and
+% construct the corresponding ODEs
+reactionNamesOriginal = SBreactions(originalmodel);
+irrevReactionNames = reactionNamesOriginal(irreversibleIndices);
+for k1 = 1:size(Nirrev,2),
+    % get indices of state number where to add the terms
+    addTermsIndices = find(Nirrev(:,k1) ~= 0);
+    for k2 = 1:length(addTermsIndices),
+        % construct expression
+        stoichCoeff = Nirrev(addTermsIndices(k2),k1);
+        if stoichCoeff > 0,
+            if stoichCoeff ~= 1,
+                addTerm = sprintf('+%g*%s',abs(stoichCoeff),irrevReactionNames{k1});
+            else
+                addTerm = sprintf('+%s',irrevReactionNames{k1});
+            end
+        elseif stoichCoeff < 0,
+            if stoichCoeff ~= -1,
+                addTerm = sprintf('-%g*%s',abs(stoichCoeff),irrevReactionNames{k1});
+            else
+                addTerm = sprintf('-%s',irrevReactionNames{k1});
+            end
+        else
+            error('This can not happen :)');
+        end
+        % add the new term to the corresponding ODE
+        modelstruct.states(addTermsIndices(k2)).ODE = strcat(modelstruct.states(addTermsIndices(k2)).ODE, addTerm);
+    end
+end
+% cycle trough the columns of Nrev (reversible reaction rates) and add the
+% corresponding terms to the corresponding ODE expressions
+for k1 = 1:size(Nrev,2),
+    % get indices of state number where to add the terms
+    addTermsIndices = find(Nrev(:,k1) ~= 0);
+    for k2 = 1:length(addTermsIndices),
+        % construct expression
+        stoichCoeff = Nrev(addTermsIndices(k2),k1);
+        if stoichCoeff > 0,
+            if stoichCoeff ~= 1,
+                addTerm = sprintf('+%g*%s_forward-%g*%s_reverse',abs(stoichCoeff),reactionsStore(k1).name,abs(stoichCoeff),reactionsStore(k1).name);
+            else
+                addTerm = sprintf('+%s_forward-%s_reverse',reactionsStore(k1).name,reactionsStore(k1).name);
+            end                
+        elseif stoichCoeff < 0,
+            if stoichCoeff ~= -1,
+                addTerm = sprintf('-%g*%s_forward+%g*%s_reverse',abs(stoichCoeff),reactionsStore(k1).name,abs(stoichCoeff),reactionsStore(k1).name);
+            else
+                addTerm = sprintf('-%s_forward+%s_reverse',reactionsStore(k1).name,reactionsStore(k1).name);
+            end
+        else
+            error('This can not happen :)');
+        end
+        % add the new term to the corresponding ODE
+        modelstruct.states(addTermsIndices(k2)).ODE = strcat(modelstruct.states(addTermsIndices(k2)).ODE, addTerm);
+    end
+end
+
+% % handle non elementary reactions
+% if sum(sum(abs(Lnone))) ~= 0,
+%     % non elementary reactions are present ... need to add those reactions
+%     % to the ODEs
+%     for k = 1:size(N,1),
+%         Lrow = Lnone(k,:);
+%         Rrow = Rnone(k,:);
+%         if sum(Lrow) ~= 0,
+%             for k2 = 1:length(Lrow),
+%                 if Lrow(k2) ~= 0,
+%                     if ~reversibleReactionsAll(k2),
+%                         modelstruct.states(k).ODE = sprintf('%s-%g*%s',modelstruct.states(k).ODE, Lrow(k2), reactionNamesOriginal{k2});
+%                     else
+%                         addTerm = sprintf('-%g*%s_forward+%g*%s_reverse',Lrow(k2),reactionNamesOriginal{k2},Rrow(k2),reactionNamesOriginal{k2});
+%                         modelstruct.states(k).ODE = sprintf('%s%s',modelstruct.states(k).ODE, addTerm);
+%                     end
+%                 end
+%             end
+%         end
+%         if sum(Rrow) ~= 0,
+%             for k2 = 1:length(Rrow),
+%                 if Rrow(k2) ~= 0,
+%                     if ~reversibleReactionsAll(k2),
+%                         modelstruct.states(k).ODE = sprintf('%s+%g*%s',modelstruct.states(k).ODE, Rrow(k2), reactionNamesOriginal{k2});
+%                     else
+%                         addTerm = sprintf('-%g*%s_forward+%g*%s_reverse',Rrow(k2),reactionNamesOriginal{k2},Lrow(k2),reactionNamesOriginal{k2});
+%                         modelstruct.states(k).ODE = sprintf('%s%s',modelstruct.states(k).ODE, addTerm);
+%                     end
+%                 end
+%             end
+%         end
+%     end
+% end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ADD EVENTUAL COMPARTMENT INFORMATION TO ODEs
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k = 1:length(compartmentInformation),
+    if ~isempty(compartmentInformation{k}),
+        modelstruct.states(k).ODE = strcat('(',modelstruct.states(k).ODE,')',compartmentInformation{k});
+    end
+end
+
+% convert structure to model again
+model = SBmodel(modelstruct);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% OUTPUT THE MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output = model;
+return
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/analysis/SBmoietyconservations.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/analysis/SBmoietyconservations.m
new file mode 100644
index 0000000000000000000000000000000000000000..d97d2f9faf9f25c98299233fc38f27d031985c20
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/analysis/SBmoietyconservations.m
@@ -0,0 +1,273 @@
+function [varargout] = SBmoietyconservations(varargin)
+% SBmoietyconservations: determines the moitey conservations that are
+% present in a model. The model can be specified as SBmodel or as ODE file.
+%
+% USAGE:
+% ======
+% [] = SBmoietyconservations(model)         
+% [] = SBmoietyconservations(model,stateValues)         
+% [] = SBmoietyconservations(model,stateValues,tol)         
+% [formulas,constants] = SBmoietyconservations(model,stateValues,tol)         
+% [depVarIndex, depVarConstant, depVarFactor, message] = SBmoietyconservations(model)         
+% [depVarIndex, depVarConstant, depVarFactor, message] = SBmoietyconservations(model,stateValues)         
+% [depVarIndex, depVarConstant, depVarFactor, message] = SBmoietyconservations(model,stateValues,tol)         
+%
+% model: SBmodel or ODE file model description
+% stateValues: values of the state variables for which to perform the
+%   analysis
+% tol: Tolerance for the determination of the number of algebraic
+% 	relationships in the model. If the method fails than this
+%   might be due to a wrong rank computation and in this case
+%   the tolerance should be increased. If set, the same tolerance
+%   setting is used when determining the indices of the
+%   dependent variables.
+%
+%
+% DEFAULT VALUES:
+% ===============
+% stateValues: if not given, the state stored in the model is used to
+%   determine the moiety conservations. It is a good idea to a systems
+%   steady-state for the computation of the conservations
+%
+% Output Arguments:
+% =================
+% depVarIndex: index of dependent states
+% depVarConstant: Sum of states taking part in conservation
+% depVarFactor: Factor for states - non-zero values for the ones that take
+%   part in conservation
+% message: Any message that otherwise is printed to the MATLAB window
+% formulas: A cell-array containing the equations of the found algebraic
+%           relations
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+global message
+message = '';
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF SBMODEL OR FILENAME
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp('SBmodel',class(varargin{1})),
+    % SBmodel
+    sbm = varargin{1};
+    % Create temporary ODE file
+    [ODEfctname, ODEfilefullpath] = SBcreateTempODEfile(sbm);    
+else
+    % ODEfctname of ODE file
+    ODEfctname = varargin{1};
+    % set sbm to empty!
+    sbm = [];
+    % Check if file exists
+    if exist(strcat(ODEfctname,'.m')) ~= 2,
+        error('ODE file could not be found.');
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 1,
+    % handle numeric and non-numeric ICs
+    stateValues = SBcalcICvector(ODEfctname);
+    tol = 0;
+elseif nargin == 2,
+    stateValues = varargin{2};
+    stateValues = stateValues(:);
+    tol = 0;
+elseif nargin == 3,
+    stateValues = varargin{2};
+    stateValues = stateValues(:);
+    tol = varargin{3};
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE THE MOIETY CONSERVATIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[depVarIndex, depVarConstant, depVarFactor] = getMoietyConservations(sbm,ODEfctname,stateValues,tol);
+% invert order of moiety conservations (to be able to evaluate them
+% sequentially in case of model reduction)
+depVarIndex(1:end) = depVarIndex(end:-1:1);
+depVarConstant(1:end) = depVarConstant(end:-1:1);
+depVarFactor(1:end,:) = depVarFactor(end:-1:1,:);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONSTRUCT RESULT MESSAGE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+MCarray = {};
+MCconstants = [];
+if ~isempty(depVarIndex),
+    message = sprintf('%s\nFollowing moitey conservations have been found:\n',message);
+    variableNames = feval(ODEfctname,'states');
+    for k1 = 1:length(depVarIndex),
+        MCarray{k1} = sprintf('%s = moietyConserv_%d',variableNames{depVarIndex(k1)},k1);
+        MCconstants(k1) = depVarConstant(k1);
+        message = sprintf('%s\n%s = %g',message,variableNames{depVarIndex(k1)},depVarConstant(k1));
+        for k2 = 1:length(depVarFactor(k1,:)),
+            if abs(depVarFactor(k1,k2)) > 0,
+                % Here a check against 0 can be done since zerocheck
+                % already done and small values set to identically zero.
+                if depVarFactor(k1,k2) > 0
+                    element = sprintf('+%g*',depVarFactor(k1,k2));
+                else
+                    element = sprintf('-%g*',abs(depVarFactor(k1,k2)));
+                end
+                MCarray{k1} = sprintf('%s%s%s',MCarray{k1},element,variableNames{k2});
+                message = sprintf('%s%s%s',message,element,variableNames{k2});
+            end
+        end
+    end
+    message = sprintf('%s\n',message);
+else
+    message = sprintf('%sNo moiety conservations have been found.\n',message);
+end
+message = sprintf('%s\nIf this result does not seem correct, do the analysis\nusing a different initial condition and/or tolerance setting.',message);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS VARIABLE OUTPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargout == 0,
+    % no output argument => simply display the results
+    disp(message);
+elseif nargout == 2,
+    varargout{1} = MCarray;
+    varargout{2} = MCconstants;
+elseif nargout == 4,
+    varargout{1} = depVarIndex;
+    varargout{2} = depVarConstant;
+    varargout{3} = depVarFactor;
+    varargout{4} = message;
+else
+    error('Incorrect number of output arguments');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DELETE FILE IF SBMODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp('SBmodel',class(varargin{1})),
+    deleteTempODEfileSB(ODEfilefullpath);
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET THE MOIETY CONSERVATIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% the function works either based on the jacobian or if it is possible on
+% the stoichiometric matrix. the latter is only possible if the model is
+% given as SBmodel and the odes are fully described in terms of reaction
+% rates.
+function [depVarIndex, depVarConstant, depVarFactor] = getMoietyConservations(sbm,ODEfctname,stateValues,tol)
+global message;
+% initialize return variables
+depVarIndex = [];
+depVarConstant = [];
+depVarFactor = [];
+% get initial condition 
+initialCondition = stateValues;
+% check if model given as SBmodel:
+if ~isempty(sbm),
+    % check if stoichiometric matrix gives full information
+    N = SBstoichiometry(sbm,0,1); % no rawFlag but silentFlag!
+    if length(initialCondition) == size(N,1),
+        % yes, full information available
+        useStoich = 1;
+    else
+        useStoich = 0;
+    end
+else
+    useStoich = 0;
+end
+% handle stoich and jac differently
+if useStoich == 0,
+    % use Jacobian!
+    % Get jacobian and determine its rankdeficiency - use default deltaX for
+    % numerical differentiation
+    J = SBjacobian(ODEfctname,initialCondition);
+
+% handle ARs by reducing J
+nrARs = length(feval(ODEfctname,'algebraic'));
+J = J(1:end-nrARs, 1:end-nrARs);
+  
+    if tol == 0,
+        d = length(J) - rank(J);        
+    else
+        d = length(J) - rank(J,tol);
+    end
+else
+    % use stoichiometry
+    if tol == 0,
+        X = rref([N,eye(size(N,1))]);
+    else
+        X = rref([N,eye(size(N,1))],tol);
+    end        
+    Nx = X(:,1:size(N,2));
+    d = length(find(sum(abs(Nx)')'==0));
+end
+if d > 0,
+    % print out a message
+    message = sprintf('%sThe system has a rank deficiency of %d. This might be due to moiety or\nother conservations in the model, to the excessive use of zero initial\nconditions and/or integrating behavior of the system. If this does\nnot seem to be correct, please check the initial conditions and/or\nset a different value for the tolerance "tol" in the options.\n',message,d);
+    % The systems contains algebraic relationships (moiety conservations)
+    % Handle stoich and jac differently
+    if useStoich == 0,
+        message = sprintf('%s\nThe algebraic relationships are determined using the Jacobian.\nThis is numerically not very stable and you need eventually\nto change tolerance "tol" settings.\n',message);
+        % Use the singular value decomposition of the Jacobian to determine
+        % the algebraic relationships
+        [U,S,V] = svd(J);
+        U0 = U(:,length(J)-d+1:length(J));
+        if tol == 0,
+            factors = rref(U0');
+        else
+            factors = rref(U0',tol);
+        end
+    else
+        message = sprintf('%s\nThe algebraic relationships are determined using the Stoichiometric matrix.\n',message);
+        % Use rref of the Stoichiometric Matrix
+        factors = X(end-d+1:end,size(N,2)+1:end);
+    end    
+    % set smaller values than tolerance to zero
+    factors(find(abs(factors)<tol)) = 0;
+% handle ARs by reducing initialConditions
+nrARs = length(feval(ODEfctname,'algebraic'));
+iCs = initialCondition(1:end-nrARs);    
+    constantValues = factors*iCs;
+    % Process the result and get the algebraic equations
+    for k = 1:size(factors,1),
+        relation = [factors(k,:) constantValues(k)];
+        % find largest element (abs) in the first n-1 elements
+        [value,index] = max(abs(relation(1:length(relation)-1)));
+        % normalize the relation
+        relation = relation./relation(index);
+        % the index of the largest element is the index of a dependent variable
+        depVarIndex = [depVarIndex index];
+        % the constant value is given by the last element in relation
+        depVarConstant = [depVarConstant; relation(length(relation))];
+        % the factor vector is constructed as follows:
+        factorVector = -relation(1:length(relation)-1); factorVector(index) = 0;
+        depVarFactor = [depVarFactor; factorVector];
+    end
+end
+return
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/analysis/SBreactantstoichiometry.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/analysis/SBreactantstoichiometry.m
new file mode 100644
index 0000000000000000000000000000000000000000..e8cc9ee44df81ba165e1e26fd99f482c680f9ce6
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/analysis/SBreactantstoichiometry.m
@@ -0,0 +1,262 @@
+function [L] = SBreactantstoichiometry(model,varargin)
+% SBreactantstoichiometry
+% Determines the stoichiometric coefficients of only the reactants. 
+% Non-elementary reactions are taken into account ... otherwise this 
+% function would not really make sense.
+%
+% USAGE:
+% ======
+% [L] = SBreactantstoichiometry(model)
+%
+% model: SBmodel to determine the reactant stoichiometric matrix for
+%
+% DEFAULT VALUES:
+% ===============
+%
+% Output Arguments:
+% =================
+% L: stoichiometric matrix with coefficients only for the reactants
+
+% Information:
+% ============
+% Copyright (C) Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF SBmodel
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~strcmp('SBmodel',class(model)),
+    error('Function only defined for SBmodels.');
+end
+% get the datastructure of the model
+modelstruct = SBstruct(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK EXTRA INPUT ARGUMENT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% the first extra input argument is used to force the SBstoichiometry function 
+% not to correct the elements of the stoichiometric matrix for the
+% compartment information in cases where species are given in
+% concentrations. This is needed for model construction (BC type of
+% representation and for other things)
+% the second is used for silent use of the function
+% both flags are not further documented and should not be used by others
+% unless they fully understand their meaning
+
+rawFlag = 0;
+silentFlag = 0;
+if nargin == 2,
+    rawFlag = varargin{1};
+elseif nargin == 3,
+    rawFlag = varargin{1};
+    silentFlag = varargin{2};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get all reaction names
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[reactionNames, dummy, reversibleFlag]  = SBreactions(model);
+if isempty(reactionNames),
+    if silentFlag == 0,
+        error('No reactions present in the model');
+    else
+        N = [];
+        componentNames = {};
+        reactionNames = {};
+        reversibleFlag = [];
+        return
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Go trough all ODEs and check reactions ...
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% go through all ODEs and check for which components the ODEs only
+% consist of reaction terms - this returns already positive and negative
+% terms and coefficients
+componentNames = {};
+[parameterNames, parameterValues] = SBparameters(model);
+N = [];
+for k = 1:length(modelstruct.states),
+    ODE = modelstruct.states(k).ODE;
+    % check if ODE contains only reaction terms - otherwise do not 
+    % consider the current state as component for the stoichiometric matrix
+    Nrow = getStoichiometryInformation(ODE,reactionNames,parameterNames,parameterValues,rawFlag,silentFlag);
+    if ~isempty(Nrow),
+        N = [N; Nrow];
+        componentNames{size(N,1)} = modelstruct.states(k).name;
+    end
+end
+% check for zero rows in N and take them away both from N and from the
+% list of component names
+%useIndices = find(sum(abs(N')) ~= 0);
+%notUseIndices = find(sum(abs(N')) == 0);
+
+nonReactionStates = setdiff(SBstates(model),componentNames);
+if ~isempty(nonReactionStates) && silentFlag == 0,
+    disp('For the following components no stoichiometries could be determined.');
+    disp('This is due to the syntax of the corresponding ODEs.');
+    text = '';
+    for k = 1:length(nonReactionStates),
+        text = sprintf('%s %s\n',text,nonReactionStates{k});
+    end
+    disp(text);
+end
+%componentNames = componentNames(useIndices);
+%N = N(useIndices,:);
+L = N;
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK ODEs for reactions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% check if given ODE expression contains only reaction terms - then return
+% the stoichiometry for this ODE. Otherwise if not only reactions are
+% present, return an empty vector.
+% in cases that the reaction rate is adjustet by the compartment volume
+% (happens especially in cases of import of SBML models containing species
+% with concentration rates and compartment volumes different from one) the
+% adjustment term and the needed parentheses should be detected and
+% neglected.
+function [Nrow] = getStoichiometryInformation(ODE,reactionNames,parameterNames,parameterValues,rawFlag,silentFlag)
+errorFlag = 0;
+% delete all white spaces from the ODE
+ODE = regexprep(ODE,'\s*','');
+% first of all check if a scaling by the compartment volume is done.
+% in this case the expected syntax is 
+% ODE = ("reactionterms")/compartmentvolume
+numberOpenParentheses = length(find(ODE == '('));
+numberClosedParentheses = length(find(ODE == ')'));
+compartmentSize = 1;
+if numberOpenParentheses ~= numberClosedParentheses,
+    % parentheses need to appear in pairs - otherwise error
+    errorFlag = 1;
+elseif numberOpenParentheses > 1,
+    % if there is more than one pair of parentheses, then error
+    errorFlag = 1;
+elseif numberOpenParentheses == 0,
+    errorFlag = 0;
+elseif ODE(1) == '(',
+    % if the first character is an open parenthesis then assume that 
+    % this is due to a adjustement to compartment sizes
+    % cut out the content of the parentheses
+    closeParenthesis = find(ODE == ')');
+    ODERHS = ODE;
+    ODE = ODERHS(2:closeParenthesis-1);
+    % check part outside parenthesis
+    rest = ODERHS(closeParenthesis+1:end);
+    % first character needs to be a '/'
+    if rest(1) ~= '/',
+        errorFlag = 1;
+    else
+        rest = rest(2:end);
+        % check if this rest corresponds to a parameter name and if yes get
+        % its value
+        index = strmatchSB(rest,parameterNames,'exact');
+        if ~isempty(index),
+            compartmentSize = parameterValues(index);
+            errorFlag = 0;
+        else
+            if silentFlag == 0,
+                error('The stoichimetric matrix can not be computed. A compartment size seems not to be given as a parameter.');
+            else 
+                errorFlag = 1;
+            end
+        end
+    end
+else
+    % parentheses is expected as first non white space character in
+    % reaction string ... therefor an error.
+    errorFlag = 1;
+end
+% continue with the algorithm if no error occurred
+if errorFlag == 0,
+    ODE = char([double(ODE) double('+')]);  % fastest strcat
+    % first explode the ODE in additive terms
+    terms = [];
+    termIndex = 1;
+    % check the sign of the first term (first character in string)
+    if ODE(1) == '-',
+        signCurrent = -1;
+        lastIndex = 2;
+    elseif ODE(1) == '+',
+        signCurrent = +1;
+        lastIndex = 2;
+    else
+        signCurrent = +1;
+        lastIndex = 1;
+    end
+    % explode in terms, check if term has the right format and if the
+    % second term features a reactionname. then construct the row of the
+    % stoichiometric matrix
+    Nrow = zeros(1,length(reactionNames));
+    startk = lastIndex;
+    for k = startk:length(ODE),
+        % check for positive term
+        if ODE(k) == '+' || ODE(k) == '-',
+            element = ODE(lastIndex:k-1);
+            % check the element if composed of term in the right format
+            multIndex = find(element == '*');
+            if length(multIndex) == 0,
+                stoichiometry = signCurrent*1;
+                reactionterm = element;
+            elseif length(multIndex) == 1,
+                absStoichiometry = str2double(element(1:multIndex-1));
+                if isempty(absStoichiometry),
+                    errorFlag = 1;
+                    break;
+                end
+                stoichiometry = signCurrent*absStoichiometry;
+                reactionterm = element(multIndex+1:end);
+            else
+                % to many multiplication signs (only one allowed)
+                errorFlag = 1;
+                break;
+            end
+            % find the index of the reaction name and add the
+            % stoichiometric information to Nrow
+            indexReaction = strmatchSB(reactionterm,reactionNames,'exact');
+            if isempty(indexReaction),
+                errorFlag = 1;
+                break;
+            end
+            % only add the coefficient if sign is negative (reactant)
+            if signCurrent == -1,
+                Nrow(indexReaction) = Nrow(indexReaction) + abs(stoichiometry);
+            end
+            % increment
+            termIndex = termIndex + 1;
+            lastIndex = k+1;
+            if ODE(k) == '+',
+                signCurrent = +1;
+            else
+                signCurrent = -1;
+            end
+        end
+    end
+end
+% if an error occurred for the current ODE the Nrow is set to zero
+if errorFlag == 1,
+    Nrow = [];
+end
+% adjust stoichiometries with compartment size
+if rawFlag == 0,
+    Nrow = Nrow / compartmentSize;
+end
+return
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/analysis/SBreducemodel.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/analysis/SBreducemodel.m
new file mode 100644
index 0000000000000000000000000000000000000000..a26b26796a8725a348d3c0c374ad2a5b86a184f4
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/analysis/SBreducemodel.m
@@ -0,0 +1,364 @@
+function [reducedmodel] = SBreducemodel(varargin)
+% SBreducemodel: Reduces an SBmodel by identifying algebraic relations 
+% between time dependent variable, defined by differential equations, and 
+% deleting the dependent variables. This function first checks if the 
+% SBmodel contains algebraic relations between the state variables. If 
+% there are, it lets the user decide which variables to choose as dependent
+% ones and to replace the ODEs by algebraic relations.
+%
+% Due to moiety conservations algebraic relations are often present in 
+% biological systems. However, for several analysis methods models are 
+% required to be non-singular. This function helps to avoid this problem.
+%
+% USAGE:
+% ======
+% [reducedmodel] = SBreducemodel(model)         
+% [reducedmodel] = SBreducemodel(model,tol)         
+%
+% model: SBmodel model to reduce
+% tol: tolerance to be used to determine moiety conservations
+%
+% DEFAULT VALUES:
+% ===============
+% tol: same as for SBmoietyconservations
+%
+% Output Arguments:
+% =================
+% reducedmodel: Reduced SBmodel. If no algebraic relations were present in
+%       the model, the initial model is returned unchanged.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% NEEDED GLOBAL VARIABLES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+global ODEfctname 
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF SBMODEL OR FILENAME
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp('SBmodel',class(varargin{1})),
+    % SBmodel
+    sbm = varargin{1};
+    % Create temporary ODE file
+    [ODEfctname, ODEfilefullpath] = SBcreateTempODEfile(sbm);    
+else
+    error('This function can not be applied to ODE files.');
+end
+
+if nargin == 1,
+    tol = 0;
+elseif nargin == 2,
+    tol = varargin{2};
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK AND REDUCE THE MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+reducedmodel = reduceModel(sbm,tol);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DELETE FILE 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+deleteTempODEfileSB(ODEfilefullpath);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK AND REDUCE THE MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [sbmReduced] = reduceModel(sbm,tol)
+% needed global variables
+global ODEfctname
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE THE MOIETY CONSERVATIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get initial conditions (numeric and non-numeric ICs)
+initialCondition = SBcalcICvector(ODEfctname);
+[depVarIndex, depVarConstant, depVarFactor, message] = SBmoietyconservations(sbm,initialCondition,tol);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF REDUCTION NECESSARY
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(depVarIndex),
+    % System is non-singular - return the original system
+    disp('Model is non-singular. Nothing is done.');
+    sbmReduced = sbm; 
+    return
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% REMOVE NON-NUMERIC ICs (if present)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% print a warning if non-numeric initial conditions (reduction will be
+% correct but non-numeric ICs have been replaced by numeric ones).
+if ~hasonlynumericICsSB(sbm),
+    numICs = SBcalcICvector(sbm);
+    ms = struct(sbm);
+    for k=1:length(ms.states),
+        ms.states(k).initialCondition = numICs(k);
+    end
+    sbm = SBmodel(ms);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK THE CONSERVATION EQUATIONS 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% To be able to include them as variables in an SBmodel it is important
+% that the moietyconservations are independent of each other. No algebraic
+% loop is allowed.
+% for k1 = 1:size(depVarFactor,1),
+%     for k2 = 1:size(depVarFactor,1),
+%         if k1 ~= k2,
+%            if ~isempty(intersect(find(depVarFactor(k1,:)~=0),find(depVarFactor(k2,:)~=0))),
+%                error(sprintf('The model can not be reduced due to dependency among the conservations.\nIn the future the toolbox will support these kind of things, but not today.\nSorry!'));
+%            end
+%         end
+%     end
+% end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONVERSION OF THE MOIETY CONSERVATIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% need to convert these results to a different format.
+% result format: dependentVariable = constantTerm + factor1*variable1 + ... + factorn*variablen
+% needed format: constantTerm = dependentVariable + NewFactor1*variable1 -
+% ... + NewFactorn*variablen
+% => change sign in depVarFactor and add a 1 in the places corresponding to
+% the dependent variables.
+depVarFactor = -depVarFactor;
+for k = 1:length(depVarIndex),
+    depVarFactor(k,depVarIndex(k)) = 1;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS SYSTEM
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% System is singular - process the algebraic relations
+d = length(depVarIndex);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DISPLAY ALL ALGEBRAIC RELATIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+disp(message);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DECIDE WHICH STATES TO REMOVE (USER)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+text = sprintf('You need to decide, for each algebraic relation, which state to remove from the model.\n');
+disp(text);
+% handle the case when events are present in the model (the states that are
+% changed by events can not be removed). If this leads to no reducable
+% states an error message will be displayed.
+sbms = struct(sbm);
+eventvariables = {};
+eventstateindices = [];
+if ~isempty(sbms.events),
+    for k=1:length(sbms.events),
+        eventvariables = {eventvariables{:} sbms.events(k).assignment(1:end).variable};
+    end
+    eventvariables = unique(eventvariables);
+    % check which of these eventvariables are states 
+    eventstateindices = stateindexSB(sbm,eventvariables); 
+    % remove the elements that are -1 (no states) ... the rest are indices
+    % of states that are changed by events
+    eventstateindices(eventstateindices<0) = [];
+    % mark the elements that correspond to state variables that have
+    % a zero right hand side of the ODE (these become parameters and thus
+    % can be changed by events).
+    for k=1:length(eventstateindices),
+        if sbms.states(eventstateindices(k)).ODE == '0',
+            eventstateindices(k) = -1;
+        end
+    end
+    % and remove them
+    eventstateindices(eventstateindices<0) = [];
+    % eventstateindices now contains the indices of the states that are not
+    % allowed to be removed from the set of ODEs. simply because these can
+    % be changed by events and this is only possible if they are kept as
+    % states.
+end
+statesRemove = [];
+variableNames = feval(ODEfctname,'states');
+% cycle through all the algebraic relations, display them and let the
+% user decide which state to remove.
+for k1 = 1:length(depVarConstant),
+    % delete the eventstateindices states from the states that are removable
+    removableStates = setdiff(find(depVarFactor(k1,:) ~= 0), eventstateindices);
+    % remove the already removed states
+    indices = setdiff(removableStates,statesRemove);
+    % check if at least one state removable
+    if isempty(indices),
+        error(sprintf('There is a moiety conservation but none of the states can be removed.\nThis is most certainly due to the fact that at least one event is present\nin the model that changes the states involved in this moiety conservation.\nDeleting the states would lead to an incorrect event behavior.'));
+    end
+    text = sprintf('Relation %d: %s',k1,getTextAlgebraicRelation(depVarConstant(k1),depVarFactor(k1,:)));
+    disp(text);
+    text = sprintf('Choose the number of the state that should be removed (1-%d).',length(indices));
+    disp(text);
+    text = '';
+    for k2 = 1:length(indices),
+        text = sprintf('%s (%d)%s  ',text,k2,variableNames{indices(k2)});
+    end
+    disp(text);
+    indexRemove = input('State to remove: ');
+    if indexRemove > length(indices) || indexRemove < 1,
+        error('Wrong input!');
+    end
+    statesRemove = [statesRemove indices(indexRemove)];
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONSTRUCT REDUCED MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% get the structure of the SBmodel
+modelStructure = SBstruct(sbm); % will contain the reduced information
+fullModelStructure = SBstruct(sbm); % contains the full information (needed only for updating the additional information fields of the variables)
+% create new "states" entry and copy only the states that are not
+% deleted into it
+states = [];
+statesCount = 1;
+for k1 = 1:length(modelStructure.states),
+    if sum(ismember(statesRemove,k1)) == 0,
+        % copy this state information to new model
+        states(statesCount).name = modelStructure.states(k1).name;
+        states(statesCount).initialCondition = modelStructure.states(k1).initialCondition;
+        states(statesCount).ODE = modelStructure.states(k1).ODE;
+        states(statesCount).type = modelStructure.states(k1).type;
+        states(statesCount).compartment = modelStructure.states(k1).compartment;
+        states(statesCount).unittype = modelStructure.states(k1).unittype;
+        states(statesCount).notes = modelStructure.states(k1).notes;
+        statesCount = statesCount + 1;
+    end
+end
+% Include the state information in the model structure
+modelStructure.states = states;
+% Now add the algebraic relations as variables.
+% It is important to add the relations before all other variables!
+% Since they might be used in the other variables!
+variables = [];
+variableCount = 1;
+parameterCount = length(modelStructure.parameters)+1;
+% First add the algebraic relations
+for k1 = 1:length(depVarConstant),
+    % Construct variable formula corresponding to algebraic relation
+    % Get the constant term
+    constantTerm = depVarConstant(k1);
+    % Scale the factor vector with -1 and set reduced element to zero
+    factor = depVarFactor(k1,:);
+    scaleFactor = 1/abs(factor(statesRemove(k1)));
+    factor = -factor*scaleFactor;
+    factor(statesRemove(k1)) = 0;
+    % Scale the constant term
+    constantTerm = constantTerm*scaleFactor;
+    % get the variableName
+    variable = variableNames{statesRemove(k1)};
+    % Construct the formula string
+    moietyConservationName = sprintf('conserv%d',k1);
+    formula = sprintf('%s',moietyConservationName);
+    % CHECK factor ... if all zero then add MC thing as parameter not as
+    % variable!
+    if sum(abs(factor)) ~= 0,
+        for k2 = 1:length(factor),
+            if factor(k2) > 0,
+                % here 0 can be used (zerocheck already done)
+                formula = sprintf('%s+%g*%s',formula,abs(factor(k2)),variableNames{k2});
+            elseif factor(k2) < 0,
+                % here 0 can be used (zerocheck already done)
+                formula = sprintf('%s-%g*%s',formula,abs(factor(k2)),variableNames{k2});
+            end
+        end
+        % Add algebraic relation as variable
+        variables(variableCount).name = variable;
+        variables(variableCount).formula = formula;
+        variables(variableCount).notes = 'Removed algebraic relation';
+        variables(variableCount).type = fullModelStructure.states(statesRemove(k1)).type;
+        variables(variableCount).compartment = fullModelStructure.states(statesRemove(k1)).compartment;
+        variables(variableCount).unittype = fullModelStructure.states(statesRemove(k1)).unittype;
+        variableCount = variableCount + 1;
+        % add the constant term as a parameter
+        modelStructure.parameters(parameterCount).name = moietyConservationName;
+        modelStructure.parameters(parameterCount).value = str2num(sprintf('%g',constantTerm));
+        moietyConservationNotes = sprintf('Moiety conservation for: %s',getTextAlgebraicRelation(depVarConstant(variableCount-1),depVarFactor(variableCount-1,:)));
+        moietyConservationNotes = moietyConservationNotes(1:strfind(moietyConservationNotes,'=')-1);
+        modelStructure.parameters(parameterCount).type = 'isParameter';
+        modelStructure.parameters(parameterCount).compartment = '';
+        modelStructure.parameters(parameterCount).unittype = '';
+        modelStructure.parameters(parameterCount).notes = moietyConservationNotes;
+        parameterCount = parameterCount + 1;
+    else
+        % add the constant term as a parameter
+        modelStructure.parameters(parameterCount).name = variable;
+        modelStructure.parameters(parameterCount).value = str2num(sprintf('%g',constantTerm));
+        moietyConservationNotes = sprintf('Moiety conservation for: %s',variable);
+        modelStructure.parameters(parameterCount).type = fullModelStructure.states(statesRemove(k1)).type;
+        modelStructure.parameters(parameterCount).compartment = fullModelStructure.states(statesRemove(k1)).compartment;
+        modelStructure.parameters(parameterCount).unittype = fullModelStructure.states(statesRemove(k1)).unittype;
+        modelStructure.parameters(parameterCount).notes = moietyConservationNotes;
+        parameterCount = parameterCount + 1;        
+    end
+end
+% Now add the other variables
+for k = 1:length(fullModelStructure.variables),
+    variables(variableCount).name = fullModelStructure.variables(k).name;
+    variables(variableCount).formula = fullModelStructure.variables(k).formula;
+    variables(variableCount).type = fullModelStructure.variables(k).type;
+    variables(variableCount).compartment = fullModelStructure.variables(k).compartment;
+    variables(variableCount).unittype = fullModelStructure.variables(k).unittype;
+    variables(variableCount).notes = fullModelStructure.variables(k).notes;
+    variableCount = variableCount + 1;
+end
+% Include the variable information in the model structure
+modelStructure.variables = variables;
+% Create SBmodel with reduced model structure
+sbmReduced = SBmodel(modelStructure);
+
+if ~hasonlynumericICsSB(sbm),
+    disp('Please note: The model contains non-numeric initial conditions. In the reduced model');
+    disp('these have been replaced by corresponding numeric initial conditions.');
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DISPLAY THE ALGEBRAIC RELATIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [text] = getTextAlgebraicRelation(depVarConstant,depVarFactor)
+    % needed global variables
+    global ODEfctname
+    % get variable names from ODE file
+    variableNames = feval(ODEfctname,'states');
+    text = sprintf(' = %g',depVarConstant);
+    for k2 = 1:length(depVarFactor),
+        if abs(depVarFactor(k2)) > 0,    % here 0 can be used (zerocheck already done)
+            if depVarFactor(k2) > 0
+                element = sprintf('+ %g',depVarFactor(k2));
+            else 
+                element = sprintf('- %g',abs(depVarFactor(k2)));
+            end
+            text = sprintf('%s %s %s',element,variableNames{k2},text);
+        end
+    end
+return
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/analysis/SBsteadystate.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/analysis/SBsteadystate.m
new file mode 100644
index 0000000000000000000000000000000000000000..cc17e334dc249effb250e8cd93578d4063f3ce15
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/analysis/SBsteadystate.m
@@ -0,0 +1,351 @@
+function [varargout] = SBsteadystate(varargin)
+% SBsteadystate: determines a steady-state of an SBmodel or an ODE file 
+% description created by SBcreateODEfile. This function should only be used 
+% for time-independent systems. Otherwise an error will
+% occur. The function is able to deal with models having a singular 
+% Jacobian, e.g., due to moity conservations.
+%
+% USAGE:
+% ======
+% [steadystate,residual,message] = SBsteadystate(model)         
+% [steadystate,residual,message] = SBsteadystate(model,initialCondition)         
+% [steadystate,residual,message] = SBsteadystate(model,initialCondition,OPTIONS)
+% [steadystate,residual] = SBsteadystate(model)         
+% [steadystate,residual] = SBsteadystate(model,initialCondition)         
+% [steadystate,residual] = SBsteadystate(model,initialCondition,OPTIONS)
+% [steadystate] = SBsteadystate(model)         
+% [steadystate] = SBsteadystate(model,initialCondition)         
+% [steadystate] = SBsteadystate(model,initialCondition,OPTIONS)
+%                                   
+% model: SBmodel model or name of ODE file (without .m suffix)
+% initialCondition: Array with initial conditions around which to start the
+%   search for a steady-state. If not given the initial conditions or given
+%   as an empty vector the initial values are taken from the SBmodel.
+% OPTIONS: structure containing options
+%          OPTIONS.TolFun: Tolerance for max element in function evaluation
+%          OPTIONS.tol: Tolerance for the determination of the number of algebraic
+%               relationships in the model. If the method fails than this
+%               might be due to a wrong rank computation and in this case
+%               the tolerance should be increased. If set, the same tolerance
+%               setting is used when determining the indices of the
+%               dependent variables.
+%          OPTIONS.MaxIter: Maximum number of iterations
+%          OPTIONS.Delta: Step length for numerical differentiation to obtain 
+%               the Jacobian.
+%
+% DEFAULT VALUES:
+% ===============
+% initialCondition: the initial conditions stored in the model
+% OPTIONS.TolFun:   1e-11
+% OPTIONS.tol:      standard MATLAB tolerance: s = svd(A); tol = max(size(A))*eps(max(s));
+% OPTIONS.MaxIter:  1000
+% OPTIONS.Delta:    1e-6
+%
+% Output Arguments:
+% =================
+% steadystate: array with steadystate values
+% residual: 2-norm of the derivatives at the found steady-state. residual
+%           is optional
+% message: message about the steady state not able to find and/or message about 
+%          found algebraic relationships / moiety conservations.
+%          Message as output argument is optional. If omitted, the message
+%          will be displayed in the Matlab window.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% NEEDED GLOBAL VARIABLES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+global ODEfctname TolFun tol MaxIter Delta message
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INITIALIZATION OF MESSAGE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+message = '';
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF SBMODEL OR FILENAME
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isSBmodel(varargin{1}),
+    % SBmodel
+    sbm = varargin{1};
+    % check if the model uses delays ... if yes then take care of it
+    if usedelaySB(sbm),
+        disp('Delays are present in the model. They are going to be');
+        disp('removed automatically for steady-state computation.');
+        sbm = removedelaySB(sbm);
+    end
+    % Create temporary ODE file
+    [ODEfctname, ODEfilefullpath] = SBcreateTempODEfile(sbm);    
+else
+    % ODEfctname of ODE file
+    ODEfctname = varargin{1};
+    % empty sbm variable
+    sbm = [];
+    % Check if file exists
+    if exist(strcat(ODEfctname,'.m')) ~= 2,
+        error('ODE file could not be found.');
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Set default values
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+TolFun  = 1e-11;
+tol     = 0; % standard MATLAB tolerance: s = svd(A); tol = max(size(A))*eps(max(s));
+MaxIter = 1000;
+Delta   = 1e-6;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 1,
+    % handle non-numeric and numeric ICs
+    initialCondition = SBcalcICvector(ODEfctname);
+    OPTIONS = []; % default options
+elseif nargin == 2,
+    initialCondition = varargin{2};
+    OPTIONS = []; % default options
+elseif nargin == 3,
+    initialCondition = varargin{2};
+    OPTIONS = varargin{3};
+else
+    error('Wrong number of input arguments');
+end
+% if empty initial condition => default values
+if isempty(initialCondition),
+    % handle non-numeric and numeric ICs
+    initialCondition = SBcalcICvector(ODEfctname);
+end    
+% initialCondition should be a column vector!
+initialCondition = initialCondition(:); 
+% if OPTIONS = [] then use default values
+if ~isempty(OPTIONS),
+    % TolFun
+    if isfield(OPTIONS,'TolFun'),
+        if ~isempty(OPTIONS.TolFun),
+            TolFun = OPTIONS.TolFun;
+        end
+    end
+    % tol
+    if isfield(OPTIONS,'tol'),
+        if ~isempty(OPTIONS.tol),
+            tol = OPTIONS.tol;
+        end
+    end
+    % MaxIter
+    if isfield(OPTIONS,'MaxIter'),
+        if ~isempty(OPTIONS.MaxIter),
+            MaxIter = OPTIONS.MaxIter;
+        end
+    end
+    % Delta
+    if isfield(OPTIONS,'Delta'),
+        if ~isempty(OPTIONS.Delta),
+            Delta = OPTIONS.Delta;
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET THE STEADY STATE FOR THE MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+steadystate = getSteadyState(initialCondition,sbm);
+if ~isempty(steadystate),
+    residual = norm(feval(ODEfctname,0,steadystate));
+else
+    messageText = 'Steady state could not be found. Try different options and/or a different starting guess.';
+    message = sprintf('%s\n%s\n',message,messageText);
+    residual = [];
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS VARIABLE OUTPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargout == 2,
+    varargout{1} = steadystate;
+    varargout{2} = residual;
+    disp(message);
+elseif nargout == 3,
+    varargout{1} = steadystate;
+    varargout{2} = residual;
+    varargout{3} = message;
+elseif nargout < 2, 
+    varargout{1} = steadystate;
+    disp(message);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DELETE FILE IF SBMODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if strcmp('SBmodel',class(varargin{1})),
+    deleteTempODEfileSB(ODEfilefullpath);
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET THE STEADY STATE OF THE MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [steadystate] = getSteadyState(initialCondition,sbm)
+% Define some global variables that are needed in other functions
+global depVar factors constantValues ODEfctname TolFun tol MaxIter Delta message
+EXITFLAG = 0;
+% Before determining the steady-state it is necessary to check if there are
+% some algebraic relationships in the model. If there are not the
+% steady-state is determined directly. If there are, the algebraic
+% relations are determined and the steady-state is calculated for a reduced
+% system.
+% check if model given as SBmodel:
+if ~isempty(sbm),
+    % check if stoichiometric matrix gives full information
+    N = SBstoichiometry(sbm,0,1); % no rawFlag,  but silentFlag
+    if length(initialCondition) == size(N,1),
+        % yes, full information available
+        useStoich = 1;
+    else
+        useStoich = 0;
+    end
+else
+    useStoich = 0;
+end
+% handle stoich and jac differently
+if useStoich == 0,
+    % use Jacobian!
+    % Get jacobian and determine its rankdeficiency - use default deltaX for
+    % numerical differentiation
+    J = SBjacobian(ODEfctname,initialCondition);
+    if tol == 0,
+        d = length(J) - rank(J);        
+    else
+        d = length(J) - rank(J,tol);
+    end
+else
+    % use stoichiometry
+    if tol == 0,
+        X = rref([N,eye(size(N,1))]);
+    else
+        X = rref([N,eye(size(N,1))],tol);
+    end        
+    Nx = X(:,1:size(N,2));
+    d = length(find(sum(abs(Nx)')'==0));
+end
+if d == 0,
+    % Jacobian has full rank => no algebraic relations => "simple"
+    % computation of the steady-state
+    % The systems does not contain algebraic relations
+    OPTIONS = [];
+    OPTIONS.MaxIter = MaxIter;
+    OPTIONS.TolFun = TolFun;
+    OPTIONS.Delta = Delta;
+    [steadystate,FVAL,EXITFLAG] = fsolveSB(@model,initialCondition,OPTIONS);
+else
+    % message
+    messageText = sprintf('The system has a rank deficiency of %d. This might be due to moiety or\nother conservations in the model, to the excessive use of zero initial\nconditions and/or integrating behavior of the system. If this does\nnot seem to be correct, please check the initial conditions and/or\nset a different value for the tolerance "tol" in the options.',d);
+    message = sprintf('%s\n%s\n',message,messageText);
+    % Jacobian is singular => assume that algebraic relations are present
+    % and solve for the steady-state by taking into account these algebraic
+    % relations, by considering the singular output directions
+    % Handle stoich and jac differently
+    if useStoich == 0,
+        message = sprintf('%s\nThe algebraic relationships are determined using the Jacobian.\nThis is numerically not very stable and you need eventually\nto change tolerance "tol" settings.\n',message);
+        % Use the singular value decomposition of the Jacobian to determine
+        % the algebraic relationships
+        [U,S,V] = svd(J);
+        U0 = U(:,end-d+1:end);
+        if tol == 0,
+            factors = rref(U0');
+        else
+            factors = rref(U0',tol);
+        end
+    else
+        message = sprintf('%s\nThe algebraic relationships are determined using the Stoichiometric matrix.\n',message);
+        % Use rref of the Stoichiometric Matrix
+       factors = X(end-d+1:end,size(N,2)+1:end);
+    end
+    constantValues = factors*initialCondition;
+    % determine the indices of the dependent variables. this is simple. 
+    % just take the index of the first non zero element in each row as 
+    % index for dependent a variable.
+    depVar = [];
+    for k = 1:size(factors,1),
+        nonZeroIndices = find(factors(k,:)~=0);
+        depVar = [depVar nonZeroIndices(1)];
+    end
+    % now do the solving for the steady-state
+    OPTIONS = [];
+    OPTIONS.MaxIter = MaxIter;
+    OPTIONS.TolFun = TolFun;
+    OPTIONS.Delta = Delta;  
+    [ssVarInDep,FVAL,EXITFLAG] = fsolveSB(@modelIndependentVariables,getIndependentVariables(initialCondition),OPTIONS);
+    % Obtain the full state vector from the independent variables
+    steadystate = getAllVariables(ssVarInDep);
+end
+% If fsolve has not converged to a solution then return an empty vector
+if EXITFLAG ~= 1,
+    steadystate = [];
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% REMOVE THE TIME FROM THE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [xdot] = model(x)
+    global ODEfctname 
+    xdot = feval(ODEfctname,0,x);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CALL MODEL BASED ON INDEPENDENT VARIABLES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [xdotVarInDep] = modelIndependentVariables(varInDep)
+    global ODEfctname 
+    variables = getAllVariables(varInDep);
+    xdot = feval(ODEfctname,0,variables);
+    xdotVarInDep = getIndependentVariables(xdot);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET INDEPENDENT VARIABLES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [varInDep] = getIndependentVariables(variables)
+    global depVar
+    varInDep = variables(setxor([1:length(variables)],depVar));
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET ALL VARIABLES FROM INDEPENDENT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [variables] = getAllVariables(varInDep)
+    global depVar factors constantValues
+    n = size(factors,2);
+    m = length(depVar);
+    varInDepIndex = setxor(1:n,depVar);
+    A = factors(1:m,depVar);
+    B = constantValues - factors(1:m,varInDepIndex)*varInDep;
+    depVarValues = linsolve(A,B);
+    variables = zeros(n,1);
+    variables(varInDepIndex) = varInDep;
+    variables(depVar) = depVarValues;
+return      
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/analysis/SBstoichiometry.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/analysis/SBstoichiometry.m
new file mode 100644
index 0000000000000000000000000000000000000000..d0b0e083ad031af69076cabccc2bf34a3434c182
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/analysis/SBstoichiometry.m
@@ -0,0 +1,290 @@
+function [N,componentNames,reactionNames,reversibleFlag] = SBstoichiometry(model,varargin)
+% SBstoichiometry
+% Determines the stoichiometric matrix for the given model. In order to be
+% able to do that the differential equations for the components have to be
+% expressed in terms of reaction rates. The stoichiometric constants need 
+% to be numeric and multiplied to the reaction terms.
+%
+% Examples: d/dt(A) = -1*Re1+2*Re3-Re5+3.141*Re8
+%
+% Especially when importing models from SBML the right hand side of the
+% ODEs might show a correction term that is needed for transport between two
+% different compartments in the case that the species is defined in
+% concentration units. In this case the ODE can look as follows:
+%
+%           d/dt(B): (-1*Re1+2*Re3-Re5+3.141*Re8)/compartmentsize
+%
+% This syntax is also accepted. In this case the stoichiometric elements
+% in the parenthesis will be divided by 'compartmentsize'.
+%
+% The 'compartmentsize' is only allowed to be a parameter! It can not be a 
+% numeric value, a state, a variable, or a function!
+%
+% Except the above shown pair of parentheses, no additional parentheses are
+% allowed to appear in the ODE definitions. Otherwise, and in case that not
+% only reaction rates are present in the ODE expression, the corresponding
+% component is not taken into account for the stoichiometric matrix.
+%
+% USAGE:
+% ======
+% [N,componentNames,reactionNames,reversibleFlag] = SBstoichiometry(model)
+%
+% model: SBmodel to determine the stoichiometric matrix for
+%
+% DEFAULT VALUES:
+% ===============
+%
+% Output Arguments:
+% =================
+% N: stoichiometric matrix
+% componentNames: cell-array with the names of the components present in
+%   the stoichiometric matrix
+% reactionNames: cell-array with the names of the reactions present in the
+%   stoichiometric matrix
+% reversibleFlag: vector with same number of entries as reactions. An entry
+%   of 0 indicates an irreversible reaction, an entry of 1 indicates a
+%   reversible reaction. The ordering is the same as the reaction names.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF SBmodel
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~strcmp('SBmodel',class(model)),
+    error('Function only defined for SBmodels.');
+end
+% get the datastructure of the model
+modelstruct = SBstruct(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK EXTRA INPUT ARGUMENT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% the first extra input argument is used to force the SBstoichiometry function 
+% not to correct the elements of the stoichiometric matrix for the
+% compartment information in cases where species are given in
+% concentrations. This is needed for model construction (BC type of
+% representation and for other things)
+% the second is used for silent use of the function
+% both flags are not further documented and should not be used by others
+% unless they fully understand their meaning
+
+rawFlag = 0;
+silentFlag = 0;
+if nargin == 2,
+    rawFlag = varargin{1};
+elseif nargin == 3,
+    rawFlag = varargin{1};
+    silentFlag = varargin{2};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Get all reaction names
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[reactionNames, dummy, reversibleFlag]  = SBreactions(model);
+if isempty(reactionNames),
+    if silentFlag == 0,
+        error('No reactions present in the model');
+    else
+        N = [];
+        componentNames = {};
+        reactionNames = {};
+        reversibleFlag = [];
+        return
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Go trough all ODEs and check reactions ...
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% go through all ODEs and check for which components the ODEs only
+% consist of reaction terms - this returns already positive and negative
+% terms and coefficients
+componentNames = {};
+[parameterNames, parameterValues] = SBparameters(model);
+N = [];
+for k = 1:length(modelstruct.states),
+    ODE = modelstruct.states(k).ODE;
+    % check if ODE contains only reaction terms - otherwise do not 
+    % consider the current state as component for the stoichiometric matrix
+    Nrow = getStoichiometryInformation(ODE,reactionNames,parameterNames,parameterValues,rawFlag,silentFlag);
+    if ~isempty(Nrow) && isempty(find(isnan(Nrow)==1, 1)),
+        N = [N; Nrow];
+        componentNames{size(N,1)} = modelstruct.states(k).name;
+    end
+end
+% check for zero rows in N and take them away both from N and from the
+% list of component names
+%useIndices = find(sum(abs(N')) ~= 0);
+%notUseIndices = find(sum(abs(N')) == 0);
+
+nonReactionStates = setdiff(SBstates(model),componentNames);
+if ~isempty(nonReactionStates) && silentFlag == 0,
+    disp('For the following components no stoichiometries could be determined.');
+    disp('This is due to the syntax of the corresponding ODEs.');
+    text = '';
+    for k = 1:length(nonReactionStates),
+        text = sprintf('%s %s\n',text,nonReactionStates{k});
+    end
+    disp(text);
+end
+%componentNames = componentNames(useIndices);
+%N = N(useIndices,:);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK ODEs for reactions
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% check if given ODE expression contains only reaction terms - then return
+% the stoichiometry for this ODE. Otherwise if not only reactions are
+% present, return an empty vector.
+% in cases that the reaction rate is adjustet by the compartment volume
+% (happens especially in cases of import of SBML models containing species
+% with concentration rates and compartment volumes different from one) the
+% adjustment term and the needed parentheses should be detected and
+% neglected.
+function [Nrow] = getStoichiometryInformation(ODE,reactionNames,parameterNames,parameterValues,rawFlag,silentFlag)
+errorFlag = 0;
+% delete all white spaces from the ODE
+ODE = regexprep(ODE,'\s*','');
+% first of all check if a scaling by the compartment volume is done.
+% in this case the expected syntax is 
+% ODE = ("reactionterms")/compartmentvolume
+numberOpenParentheses = length(find(ODE == '('));
+numberClosedParentheses = length(find(ODE == ')'));
+compartmentSize = 1;
+if numberOpenParentheses ~= numberClosedParentheses,
+    % parentheses need to appear in pairs - otherwise error
+    errorFlag = 1;
+elseif numberOpenParentheses > 1,
+    % if there is more than one pair of parentheses, then error
+    errorFlag = 1;
+elseif numberOpenParentheses == 0,
+    errorFlag = 0;
+elseif ODE(1) == '(',
+    % if the first character is an open parenthesis then assume that 
+    % this is due to a adjustement to compartment sizes
+    % cut out the content of the parentheses
+    closeParenthesis = find(ODE == ')');
+    ODERHS = ODE;
+    ODE = ODERHS(2:closeParenthesis-1);
+    % check part outside parenthesis
+    rest = ODERHS(closeParenthesis+1:end);
+    % first character needs to be a '/'
+    if rest(1) ~= '/',
+        errorFlag = 1;
+    else
+        rest = rest(2:end);
+        % check if this rest corresponds to a parameter name and if yes get
+        % its value
+        index = strmatchSB(rest,parameterNames,'exact');
+        if ~isempty(index),
+            compartmentSize = parameterValues(index);
+            errorFlag = 0;
+        else
+            if silentFlag == 0,
+                error('The stoichimetric matrix can not be computed. A compartment size seems not to be given as a parameter.');
+            else 
+                errorFlag = 1;
+            end
+        end
+    end
+else
+    % parentheses is expected as first non white space character in
+    % reaction string ... therefor an error.
+    errorFlag = 1;
+end
+% continue with the algorithm if no error occurred
+if errorFlag == 0,
+    
+    ODE = char([double(ODE) double('+')]);  % fastest strcat
+    % first explode the ODE in additive terms
+    terms = [];
+    termIndex = 1;
+    % check the sign of the first term (first character in string)
+    if ODE(1) == '-',
+        signCurrent = -1;
+        lastIndex = 2;
+    elseif ODE(1) == '+',
+        signCurrent = +1;
+        lastIndex = 2;
+    else
+        signCurrent = +1;
+        lastIndex = 1;
+    end
+    % explode in terms, check if term has the right format and if the
+    % second term features a reactionname. then construct the row of the
+    % stoichiometric matrix
+    Nrow = zeros(1,length(reactionNames));
+    startk = lastIndex;
+    for k = startk:length(ODE),
+        % check for positive term
+        if ODE(k) == '+' || ODE(k) == '-',
+            element = ODE(lastIndex:k-1);
+            % check the element if composed of term in the right format
+            multIndex = find(element == '*');
+            if length(multIndex) == 0,
+                stoichiometry = signCurrent*1;
+                reactionterm = element;
+            elseif length(multIndex) == 1,
+                absStoichiometry = str2double(element(1:multIndex-1));
+                if isempty(absStoichiometry),
+                    errorFlag = 1;
+                    break;
+                end
+                stoichiometry = signCurrent*absStoichiometry;
+                reactionterm = element(multIndex+1:end);
+            else
+                % to many multiplication signs (only one allowed)
+                errorFlag = 1;
+                break;
+            end
+            % find the index of the reaction name and add the
+            % stoichiometric information to Nrow
+            indexReaction = strmatchSB(reactionterm,reactionNames,'exact');
+            if isempty(indexReaction),
+                errorFlag = 1;
+                break;
+            end
+            Nrow(indexReaction) = Nrow(indexReaction) + stoichiometry;
+            % increment
+            termIndex = termIndex + 1;
+            lastIndex = k+1;
+            if ODE(k) == '+',
+                signCurrent = +1;
+            else
+                signCurrent = -1;
+            end
+        end
+    end
+end
+% if an error occurred for the current ODE the Nrow is set to zero
+if errorFlag == 1,
+    Nrow = [];
+end
+% adjust stoichiometries with compartment size
+if rawFlag == 0,
+    Nrow = Nrow / compartmentSize;
+end
+return
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/gui/SBplot_dir/SBplot.fig b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/gui/SBplot_dir/SBplot.fig
new file mode 100644
index 0000000000000000000000000000000000000000..ce254d8236cd9a85d1381fa8c210bbd5c088294c
Binary files /dev/null and b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/gui/SBplot_dir/SBplot.fig differ
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/gui/SBplot_dir/SBplot.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/gui/SBplot_dir/SBplot.m
new file mode 100644
index 0000000000000000000000000000000000000000..dc09a385119dfcdc3a94e1007433db375d987fc7
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/gui/SBplot_dir/SBplot.m
@@ -0,0 +1,360 @@
+function varargout = SBplot(varargin)
+% SBplot - plots given data.
+%
+% USAGE:
+% ======
+% [] = SBplot(time,data)
+% [] = SBplot(time,data,names)
+% [] = SBplot(time,data,names,name)
+% [] = SBplot(time,data,names,legendtext,name)
+% [] = SBplot(time,data,names,legendtext,marker,name)
+% [] = SBplot(time,data,names,errorindices,minvalues,maxvalues,legendtext,marker,name)
+%
+% [] = SBplot(datastruct1)
+% [] = SBplot(datastruct1,datastruct2)
+% [] = SBplot(datastruct1,datastruct2, ..., datastructN)
+%
+% The datastructures are created most easily using the function
+% createdatastructSBplotSB.
+%
+% time: column vector with time information
+% data: matrix with data where each row corresponds to one time point and
+%   each column to a different variable
+% names: cell-array with the names of the data variables
+% legendtext: cell-array of same length as names with text to be used for
+%   the legend.
+% marker: marker and line style for plot
+% errorindices: indices of the data for which errorbounds are available
+% minvalues: error bounds for data ... to be shown by error bars
+% maxvalues: error bounds for data ... to be shown by error bars
+% name: name describing the datastruct
+%
+% datastruct: datastructure with all the plotting data (allows for
+%   displaying several datastructs at a time in the same GUI).
+%
+% DEFAULT VALUES:
+% ===============
+% names: the plotted variables obtain the name 'x1', 'x2', ...
+% legendtext: same as names
+% marker: '-'
+% min/maxvalues: no errorbars shown
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+% Begin initialization code - DO NOT EDIT
+gui_Singleton = 1;
+gui_State = struct('gui_Name',       mfilename, ...
+                   'gui_Singleton',  gui_Singleton, ...
+                   'gui_OpeningFcn', @SBplot_OpeningFcn, ...
+                   'gui_OutputFcn',  @SBplot_OutputFcn, ...
+                   'gui_LayoutFcn',  [] , ...
+                   'gui_Callback',   []);
+if nargin && ischar(varargin{1})
+    gui_State.gui_Callback = str2func(varargin{1});
+end
+if nargout
+    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
+else
+    gui_mainfcn(gui_State, varargin{:});
+end
+% End initialization code - DO NOT EDIT
+
+% --- Executes just before SBplot is made visible.
+function SBplot_OpeningFcn(hObject, eventdata, handles, varargin)
+% check if datastructure or normal data as input
+if ~isstruct(varargin{1}),
+    % assume normal input arguments
+    runcmd = 'datastruct = createdatastructSBplotSB(';
+    for k=1:nargin-3,
+        runcmd = sprintf('%s varargin{%d},',runcmd,k);
+    end
+    runcmd = runcmd(1:end-1);
+    runcmd = [runcmd ');'];
+    eval(runcmd);
+    handles.dataSets = {datastruct};
+else
+    % Each argument is assumed to correspond to one datastructure
+    handles.dataSets = varargin;        % save all datastructs in handles
+end
+handles = switchDataSet(handles,1);     % switch to first datastruct
+% Initialize datastructs pulldown menu
+datastructnames = {};
+for k = 1:length(handles.dataSets),
+    datastructnames{k} = handles.dataSets{k}.name;
+end
+set(handles.datastructs,'String',datastructnames);
+% select plottype to start with
+handles.dataPlotType = 'plot';          
+% Initialize export figure handle
+handles.exportFigureHandle = [];
+handles.grid = 0;
+% Doing a first plot
+doPlot(handles);
+% Choose default command line output for SBplot
+handles.output = hObject;
+% Update handles structure
+guidata(hObject, handles);
+return
+
+% --- Executes just before SBplot is made visible.
+function Exit_Callback(hObject, eventdata, handles, varargin)
+clear global doRemoveZeroComponentFlag
+closereq
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SWITCH GIVEN DATASTRUCTS 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [handles] = switchDataSet(handles,indexDataSet)
+dataSet = handles.dataSets{indexDataSet};
+% Set all the plot data also in the handles structure to be accessed by 
+% all callback functions
+% get number of yaxisdata in old plot
+if isfield(handles,'dataNames'),
+    ynumberold = length(handles.dataNames);
+else
+    ynumberold = 0;
+end
+handles.time = dataSet.time;
+handles.data = dataSet.data;
+handles.dataNames = dataSet.dataNames;
+handles.legentext = dataSet.legendtext;
+handles.marker = dataSet.marker;
+handles.errorindices = dataSet.errorindices;
+handles.minvalues = dataSet.minvalues;
+handles.maxvalues = dataSet.maxvalues;
+handles.name = dataSet.name;
+% update selection menu
+set(handles.xaxisselection,'String',{'TIME',dataSet.dataNames{:}});
+set(handles.yaxisselection,'String',dataSet.dataNames);
+set(handles.xaxisselection,'Value',1);
+% change selection only if unequal numbers of data in the sets
+if ynumberold ~= length(handles.dataNames),
+    set(handles.yaxisselection,'Value',1);
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DATASTRUCTS SELECTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function datastructs_Callback(hObject, eventdata, handles)
+dataSetIndex = get(handles.datastructs,'Value');
+handles = switchDataSet(handles,dataSetIndex);
+doPlot(handles);
+% Update handles structure
+guidata(hObject, handles);
+return
+
+% --- Outputs from this function are returned to the command line.
+function varargout = SBplot_OutputFcn(hObject, eventdata, handles) 
+varargout{1} = handles.output;
+return
+
+% --- Executes on button press in zoombutton.
+function zoombutton_Callback(hObject, eventdata, handles)
+% toogle the zoom in the figure
+zoom
+return
+
+% --- Executes on selection change in xaxisselection.
+function xaxisselection_Callback(hObject, eventdata, handles)
+try
+    doPlot(handles);
+catch
+    errordlg('This selection is not possible.','Error','on');               
+end
+% Update handles structure
+guidata(hObject, handles);
+return
+
+% --- Executes on selection change in yaxisselection.
+function yaxisselection_Callback(hObject, eventdata, handles)
+try
+    doPlot(handles);
+catch
+    errordlg('This selection is not possible.','Error','on');               
+end
+% Update handles structure
+guidata(hObject, handles);
+return
+
+% --- Executes on button press in gridbutton.
+function gridbutton_Callback(hObject, eventdata, handles)
+% toogle the grid in the figure
+grid
+if handles.grid == 1,
+    handles.grid = 0;
+else
+    handles.grid = 1;
+end
+% Update handles structure
+guidata(hObject, handles);
+return
+
+% --- From R2014B the radiobutton groups are handled differently ...
+function plotAxesSelection_SelectionChangeFcn(hObject, eventdata, handles)
+handles.dataPlotType = eventdata.NewValue.String;
+% Update handles structure
+guidata(hObject, handles);
+doPlot(handles);
+return
+
+
+% --- Executes on button press in plot.
+function plot_Callback(hObject, eventdata, handles)
+handles.dataPlotType = 'plot';
+% Update handles structure
+guidata(hObject, handles);
+doPlot(handles);
+return
+
+% --- Executes on button press in loglog.
+function semilogx_Callback(hObject, eventdata, handles)
+handles.dataPlotType = 'semilogx';
+% Update handles structure
+guidata(hObject, handles);
+doPlot(handles);
+return
+
+% --- Executes on button press in semilogx.
+function semilogy_Callback(hObject, eventdata, handles)
+handles.dataPlotType = 'semilogy';
+% Update handles structure
+guidata(hObject, handles);
+doPlot(handles);
+return
+
+% --- Executes on button press in loglog.
+function loglog_Callback(hObject, eventdata, handles)
+handles.dataPlotType = 'loglog';
+% Update handles structure
+guidata(hObject, handles);
+doPlot(handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EXPORT FIGURE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function export_Callback(hObject, eventdata, handles)
+warning off;
+if isempty(handles.exportFigureHandle),
+    figH = figure;
+    handles.exportFigureHandle = figH;
+    % Update handles structure
+    guidata(hObject, handles);
+else
+    figH = handles.exportFigureHandle;
+    figure(figH);
+end
+nrow = str2num(get(handles.nrow,'String'));
+ncol = str2num(get(handles.ncol,'String'));
+nnumber = str2num(get(handles.nnumber,'String'));
+subplot(nrow,ncol,nnumber);
+doPlot(handles);
+if handles.grid == 1,
+    grid;
+end
+% set axes
+XLim = get(handles.plotarea,'Xlim');
+YLim = get(handles.plotarea,'Ylim');
+axis([XLim, YLim]);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% REQUEST NEW EXPORT FIGURE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function newexportfigure_Callback(hObject, eventdata, handles)
+handles.exportFigureHandle = [];
+% Update handles structure
+guidata(hObject, handles);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PLOT FUNCTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function doPlot(handles)
+warning off;
+colorvector = {'b','g','r','c','m','y','k'};
+time = handles.time;
+data = handles.data;
+dataNames = handles.dataNames;
+errorindices = handles.errorindices;
+maxvalues = handles.maxvalues;
+minvalues = handles.minvalues;
+xaxis = handles.xaxisselection;
+yaxis = handles.yaxisselection;
+% get variable that is chosen for the x-axis
+indexX = get(xaxis,'Value');
+% get variables that are chosen for the y-axis
+indexY = get(yaxis,'Value');
+if indexX == 1,
+    if size(time,2) == 1,
+        xvariable = time;
+    else
+        xvariable = time(:,indexY);
+    end
+else
+    xvariable = data(:,indexX-1);
+end
+yvariables = data(:,indexY);
+yvariablesNames = dataNames(indexY);
+
+% select linewidth
+if ~isempty(errorindices),
+    % wider line in case of data with error bounds
+    addOption = sprintf(',''linewidth'',2');
+else
+    addOption = '';
+end
+
+% plot
+eval(sprintf('feval(handles.dataPlotType,xvariable,yvariables,handles.marker%s);',addOption))
+
+% plot error bounds 
+hold on;
+if indexX == 1,
+    % only if time on X-axis
+    for k=1:length(errorindices),
+        if ~isempty(find(indexY==errorindices(k))),
+            color = find(indexY==errorindices(k));
+            color = colorvector{mod(color(1)-1,7)+1};
+            for k1 = 1:size(xvariable,1),
+                feval(handles.dataPlotType,[xvariable(k1),xvariable(k1)],[minvalues(k1,k),maxvalues(k1,k)],['.:',color]);
+            end
+        end
+    end
+end
+hold off;
+
+hlhlx = legend(handles.legentext(indexY)); 
+set(hlhlx,'Interpreter','none');
+% write axis labels
+if indexX == 1,
+    xlabel('Time');
+else
+    hlhlx = xlabel(dataNames(indexX-1));
+    set(hlhlx,'Interpreter','none');
+end
+% write title (name)
+hlhlx = title(handles.name);
+set(hlhlx,'Interpreter','none');
+return
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/gui/SBplot_dir/createdatastruct2SBplotSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/gui/SBplot_dir/createdatastruct2SBplotSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..3a35cdaa02d3aa5c0ad493311fde1a23a94017f9
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/gui/SBplot_dir/createdatastruct2SBplotSB.m
@@ -0,0 +1,73 @@
+function [datastruct] = createdatastruct2SBplotSB(simdata,varargin)
+% createdatastruct2SBplotSB: Converts simulation data, 
+% returned from SBsimulate or SBPDsimulate to a datastruct that 
+% can be passed to SBplot for plotting.
+%
+% USAGE:
+% ======
+% [datastruct] = createdatastruct2SBplotSB(simdata)
+% [datastruct] = createdatastruct2SBplotSB(simdata,name)
+%
+% simdata: simulation data returned by SBsimulate and SBPDsimulate
+% name: name for the datastruct
+%  
+% DEFAULT SETTINGS:
+% =================
+% name: 'unnamed'
+%
+% Output Arguments:
+% =================
+% datastruct: structure that can be displayed by SBplot   (>> SBplot(datastruct))
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle variable input arguments
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+name = 'untitled';
+if nargin == 2,
+    name = varargin{1};
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONVERT SIMDATA TO DATASTRUCT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+time = simdata.time;
+datanames = {};
+dataindex = 1;
+for k = 1:length(simdata.states),
+    datanames{dataindex} = sprintf('%s (state)',simdata.states{k});
+    dataindex = dataindex + 1;
+end
+if isfield(simdata,'variables'),
+    for k = 1:length(simdata.variables),
+        datanames{dataindex} = sprintf('%s (variable)',simdata.variables{k});
+        dataindex = dataindex + 1;
+    end
+    for k = 1:length(simdata.reactions),
+        datanames{dataindex} = sprintf('%s (reaction rate)',simdata.reactions{k});
+        dataindex = dataindex + 1;
+    end
+    datavalues = [simdata.statevalues, simdata.variablevalues, simdata.reactionvalues];
+else
+    datavalues = [simdata.statevalues];
+end
+datastruct = createdatastructSBplotSB(time(:),datavalues,datanames,name);
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/gui/SBplot_dir/createdatastructSBplotSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/gui/SBplot_dir/createdatastructSBplotSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..7ba10f01066b6da944e99a9a91bde6aff4912794
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/gui/SBplot_dir/createdatastructSBplotSB.m
@@ -0,0 +1,115 @@
+function [datastruct] = createdatastructSBplotSB(varargin)
+% createdatastructSBplotSB: Creates a datastruct for the SBplot function
+%
+% USAGE:
+% ======
+% [datastruct] = createdatastructSBplotSB(time,data)
+% [datastruct] = createdatastructSBplotSB(time,data,names)
+% [datastruct] = createdatastructSBplotSB(time,data,names,name)
+% [datastruct] = createdatastructSBplotSB(time,data,names,legendtext,name)
+% [datastruct] = createdatastructSBplotSB(time,data,names,legendtext,marker,name)
+% [datastruct] = createdatastructSBplotSB(time,data,names,errorindices,minvalues,maxvalues,legendtext,marker,name)
+%
+% time: column vector with time information
+% data: matrix with data where each row corresponds to one time point and
+%       each column to a different variable
+% names: cell-array with the names of the data variables
+%
+% name: name for the datastruct
+%
+% legendtext: cell-array of same length as names with text to be used for
+%             the legend.
+% marker: marker and line style for plot
+% errorindices: indices of the data for which errorbounds are available
+% minvalues: error bounds for data ... to be shown by error bars
+% maxvalues: error bounds for data ... to be shown by error bars
+%  
+% DEFAULT data:
+% ===============
+% names: the plotted variables obtain the name 'x1', 'x2', ...
+% legendtext: same as names
+% marker: '-'
+% min/maxvalues: no errorbars shown
+% name: 'unnamed'
+%
+% Output Arguments:
+% =================
+% datastruct: structure that can be displayed by SBplot   (>> SBplot(datastruct))
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% initializing the datastruct structure and setting default values
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+datastruct = [];
+datastruct.time = varargin{1};
+datastruct.data = varargin{2};
+datastruct.name = 'unnamed';
+datastruct.dataNames = {};
+for k = 1:size(datastruct.data,2);
+    datastruct.dataNames{end+1} = sprintf('x%d',k);
+end
+datastruct.errorindices = [];
+datastruct.minvalues = [];
+datastruct.maxvalues = [];
+datastruct.marker = '-';
+
+if nargin == 2,
+    % do nothing ... all done already
+    datastruct.legendtext = datastruct.dataNames;
+elseif nargin == 3,
+    datastruct.dataNames = varargin{3};
+    datastruct.legendtext = datastruct.dataNames;
+elseif nargin == 4,
+    datastruct.dataNames = varargin{3};
+    datastruct.name = varargin{4};
+    datastruct.legendtext = datastruct.dataNames;
+elseif nargin == 5,
+    datastruct.dataNames = varargin{3};
+    datastruct.legendtext = varargin{4};
+    datastruct.name = varargin{5};
+elseif nargin == 6,
+    datastruct.dataNames = varargin{3};
+    datastruct.legendtext = varargin{4};
+    datastruct.marker = varargin{5};
+    datastruct.name = varargin{6};
+elseif nargin == 9,
+    datastruct.dataNames = varargin{3};
+    datastruct.errorindices = varargin{4};
+    datastruct.minvalues = varargin{5};
+    datastruct.maxvalues = varargin{6};
+    datastruct.legendtext = varargin{7};
+    datastruct.marker = varargin{8};
+    datastruct.name = varargin{9};
+else
+    error('Wrong number of input arguments.');
+end
+if isempty(datastruct.legendtext),
+    datastruct.legendtext = datastruct.dataNames;
+end
+
+
+% Check data consistency
+if size(datastruct.time,1) ~= size(datastruct.data,1),
+    error('Different number of time points and time points in data.');
+end
+if length(datastruct.dataNames) ~= size(datastruct.data,2),
+    error('Different number of variable data and variable names.');
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/simulation/SBsimulate.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/simulation/SBsimulate.m
new file mode 100644
index 0000000000000000000000000000000000000000..013b320e305eb83cee4625f0c3b06a103d4a6fd8
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/simulation/SBsimulate.m
@@ -0,0 +1,369 @@
+function [varargout] = SBsimulate(varargin)
+% SBsimulate: simulates an SBmodel or an ODE file created by
+% SBcreateODEfile. In case the model is given as an SBmodel, not only the 
+% trajectories for the models states are determined, but also the time 
+% trajectories for all variables and reaction rates in the model 
+% 
+% The SBsimulate function can deal automatically with models that contain 
+% state events. However, this is only possible in the case where a model is
+% specified as an SBmodel, not as an ODE file model. 
+%
+% USAGE:
+% ======
+% [output] = SBsimulate(model)         
+% [output] = SBsimulate(model,time)         
+% [output] = SBsimulate(model,method,time)         
+% [output] = SBsimulate(model,method,time,ic)         
+% [output] = SBsimulate(model,method,time,ic,options)         
+%
+% model: SBmodel or ODE file model description
+% time: scalar value for simulation end time (default start time is 0),
+%       vector with two elements indicating start and end time, or vector
+%       with time instants for which the simulation results are to be
+%       returned.
+% method: name of a MATLAB integrator (ode45, ode23s, etc.) 
+% ic: initial conditions of the model to be simulated
+% options: standard MATLAB integrator options, set by ODESET
+%
+% DEFAULT VALUES:
+% ===============
+% time: 20 time units (=> tspan: [0 20])
+% method: 'ode23s' ('ode15s' IF algebraic rules present in the model)
+% ic: the initial conditions stored in the model
+% options: []
+%
+% Output Arguments:
+% =================
+% If no output arguments are given, the result of the simulation is plotted
+% 1) online during the simulation for monitoring purposes - the simulation 
+% can here be stopped at every instant by just clicking on the "Stop"
+% button. 2) after the simulation is finished the simulation data is plotted 
+% using the SBplot function, allowing to browse the data.
+%
+% The output of SBsimulate is realized as a structure:
+% output.time:              vector with time instants for the results
+% output.states:            cell-array with state names
+% output.statevalues:       matrix with state values. Each row corresponds to
+%                           one time instant.
+%
+% The following fields are only present in case the model as been given
+% as an SBmodel:
+%
+% output.variables:         cell-array with variable names
+% output.variablevalues:    matrix with variable values. Each row corresponds to
+%                           one time instant.
+% output.reactions:         cell-array with reaction names
+% output.reactionvalues:    matrix with reaction values. Each row corresponds to
+%                           one time instant.
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+parameterValuesNew_ALL = []; % for handling events on parameters
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INITIALIZE STUFF
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+t = [];
+x = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DEAL WITH VARIABLE ARGUMENT NUMBER
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 1,
+    model = varargin{1};
+    method = 'ode23s';
+    tspan = [0 20];
+    ic = [];
+    options = [];
+elseif nargin == 2,
+    model = varargin{1};
+    method = 'ode23s';
+    if length(varargin{2}) == 1,
+        tspan = [0 varargin{2}];
+    else
+        tspan = varargin{2};
+    end
+    ic = [];
+    options = [];
+elseif nargin == 3,
+    model = varargin{1};
+    method = varargin{2};
+    if length(varargin{3}) == 1,
+        tspan = [0 varargin{3}];
+    else
+        tspan = varargin{3};
+    end
+    ic = [];
+    options = [];
+elseif nargin == 4,
+    model = varargin{1};
+    method = varargin{2};
+    if length(varargin{3}) == 1,
+        tspan = [0 varargin{3}];
+    else
+        tspan = varargin{3};
+    end
+    ic = varargin{4};
+    options = [];
+elseif nargin == 5,
+    model = varargin{1};
+    method = varargin{2};
+    if length(varargin{3}) == 1,
+        tspan = [0 varargin{3}];
+    else
+        tspan = varargin{3};
+    end
+    ic = varargin{4};
+    options = varargin{5};
+else
+    error('Incorrect number of input arguments');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% STUPID HANDLING OF 0 STATE MODELS (HALLELUJA SBML)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isSBmodel(model) && nargout == 1,
+    if isfield(options,'stupidstupidsbml'),
+        if options.stupidstupidsbml == 1,
+            if isempty(SBstates(model)),
+                varargout{1} = handle0statemodel4SBML(model,tspan);
+                return
+            end
+        end
+    end
+end
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ADD PIECEWISE TRIGGERS AS EVENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isSBmodel(model),
+    model = addpiecewiseeventsSB(model);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% IF DELAYS AND/OR EVENTS ARE PRESENT THEN USE A DEFAULT MAXSTEP
+% Only do that in case of an SBmodel
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isSBmodel(model),
+    if usedelaySB(model) || useeventSB(model),
+        if ~isfield(options,'MaxStep'),
+            % change only if not user provided 
+            options = odeset(options,'MaxStep',tspan(end)/1000);
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF SBmodel AND FAST REACTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+fastFlag = 0;
+fastIndex = [];
+if isSBmodel(model),
+    if usefastSB(model),
+        [model,K,nrODEsNorm,nrARs,fastIndex] = convertFastReacModelSB(model);
+        % create global variable for the kernel
+        [a,b] = fileparts(tempname);
+        augmKernelName = sprintf('kernel_augm_%s',b);
+        eval(sprintf('global %s',augmKernelName));
+        fastFlag = 1;
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE ALGEBRAIC RULES IF PRESENT!
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ARnames = SBalgebraic(model);
+ARpresent = 0;
+if ~isempty(ARnames),
+    ARpresent = 1;
+    % override integrator selection
+    method = 'ode15s';
+    % determine the mass matrix (take into account the kernel coming from
+    % the fast reactions if necessary)
+    STnames = SBstates(model);
+    if ~fastFlag,
+        % no fast reactions
+        massM = zeros(length(ARnames)+ length(STnames));
+        massM(1:length(STnames),1:length(STnames)) = eye(length(STnames));
+    else
+        % fast reactions
+        % build the mass matrix
+        massM = zeros(nrODEsNorm+size(K,1)+length(ARnames));
+        massM(1:nrODEsNorm,1:nrODEsNorm) = eye(nrODEsNorm);
+        massM(nrODEsNorm+1:nrODEsNorm+size(K,1),nrODEsNorm+1:nrODEsNorm+size(K,2)) = K;
+        % build the matrix to multiply the ODEs with
+        augmKernelValue = zeros(nrODEsNorm+size(K,1),nrODEsNorm+size(K,2));
+        augmKernelValue(1:nrODEsNorm,1:nrODEsNorm) = eye(nrODEsNorm);
+        augmKernelValue(nrODEsNorm+1:nrODEsNorm+size(K,1),nrODEsNorm+1:nrODEsNorm+size(K,2)) = K;
+        %Remove the column corrsponding to the algebraic equations since
+        %the model does not contain them in the multiplication K*states
+        %augmKernelValue=augmKernelValue(:,1:size(augmKernelValue,2)-nrARs); 
+        eval(sprintf('%s = augmKernelValue;',augmKernelName));
+    end
+    % add the mass matrix to the options
+    options = odeset(options,'Mass',massM);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK NUMBER OF OUTPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargout ~= 0 && nargout ~= 1,
+    error('Incorrect number of output arguments');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% PROCESS SBMODEL OR ODE FILE - CHECK IF EVENTS PRESENT IN SBmodel
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+eventFlag = 0;
+if strcmp('SBmodel',class(model)),
+    % check for events
+    if ~isempty(SBevents(model)) > 0,
+        eventFlag = 1;
+    end
+    if fastFlag == 0,
+        [ODEfctname, ODEfilefullpath, DATAfctname, EVENTfctname, EVENTASSGNfctname] = SBcreateTempODEfile(model,1,eventFlag);
+    else
+        [ODEfctname, ODEfilefullpath, DATAfctname, EVENTfctname, EVENTASSGNfctname] = SBcreateTempODEfile(model,1,eventFlag,augmKernelName);
+    end        
+else
+    % ODEfctname of ODE file
+    ODEfctname = model;
+    % Check if file exists
+    if exist(strcat(ODEfctname,'.m')) ~= 2,
+        error('ODE file could not be found.');
+    end
+end
+ 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% UPDATE INITIAL CONDITIONS (also handles non-numeric initial conditions)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% idea: if ic provided by user then use these. otherwise get the initial
+% conditions stored in the model. if non-numeric then calculate them
+if isempty(ic),
+    % Handle also non-numeric initial condition
+    ic = SBcalcICvector(ODEfctname);
+    % gumpehe1: reverting these changes as initial conditions for the AR
+    % are required for the MATLAB ODE solvers
+    % % If algebraic rules present then we need to add the ICs of these at the end
+    % % algebraic ICs can NOT be non-numeric => always numeric
+    %     ic_algebraic = [];
+    %     allICs = feval(ODEfctname);
+    %     for k=1:length(ARnames),
+    %         ic_algebraic(end+1) = allICs{end-length(ARnames)+k};
+    %     end
+    %     ic = [ic(:)' ic_algebraic(:)'];
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% IF NO OUTPUT ARGUMENTS GIVEN THEN DISPLAY ONLINE INFORMATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargout == 0,
+    figure; drawnow;
+    options = odeset(odeset(options),'OutputFcn',@odeplot);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SIMULATE MODEL WITH GIVEN METHOD (DIFFERENT HANDLING IN CASE OF EVENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if eventFlag == 0,
+    eval(sprintf('[t,x] = %s(@%s,tspan,ic,options);',method,ODEfctname));
+else
+    % handle the events that are present in the model
+    [t,x,dummy1,dummy2,dummy3,parameterValuesNew_ALL] = eventsimulateSB(ODEfctname,method,tspan,ic,options,EVENTfctname,EVENTASSGNfctname);
+end
+    
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CLOSE ONLINE PLOT AGAIN IF IT WAS PRESENT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargout == 0,
+    close gcf;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE OUTPUT VARIABLE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+output.time = t;
+output.states = SBstates(ODEfctname)';
+output.statevalues = x(:,1:length(output.states));
+if strcmp('SBmodel',class(model)),
+    % determine the simulation data using the 'DATAfctname'
+    [dataoutput] = feval(DATAfctname,t,x,parameterValuesNew_ALL);
+    if isfield(dataoutput,'algebraic'),
+        output.algebraic = dataoutput.algebraic;
+        output.algebraicvalues = dataoutput.algebraicvalues;
+    end
+    output.variables = dataoutput.variables;
+    output.variablevalues = dataoutput.variablevalues;
+    output.reactions = dataoutput.reactions;
+    output.reactionvalues = dataoutput.reactionvalues;
+end
+if nargout == 0,
+    % prepare data for plotting
+    time = output.time;
+    datanames = {};
+    dataindex = 1;
+    for k = 1:length(output.states),
+        datanames{dataindex} = sprintf('%s (state)',output.states{k});
+        dataindex = dataindex + 1;
+    end
+    if isfield(output,'algebraic'),
+        for k = 1:length(output.algebraic),
+            datanames{dataindex} = sprintf('%s (algebraic)',output.algebraic{k});
+            dataindex = dataindex + 1;
+        end
+    end
+    if strcmp('SBmodel',class(model)),
+        for k = 1:length(output.variables),
+            datanames{dataindex} = sprintf('%s (variable)',output.variables{k});
+            dataindex = dataindex + 1;
+        end
+        for k = 1:length(output.reactions),
+            if ~ismember(k,fastIndex),
+                datanames{dataindex} = sprintf('%s (reaction rate)',output.reactions{k});
+            else    
+                datanames{dataindex} = sprintf('%s (reaction rate - fast)',output.reactions{k});
+            end
+            dataindex = dataindex + 1;
+        end
+        if isfield(output,'algebraic'),
+            datavalues = [output.statevalues, output.algebraicvalues, output.variablevalues, output.reactionvalues];
+        else
+            datavalues = [output.statevalues, output.variablevalues, output.reactionvalues];
+        end            
+    else
+        datavalues = [output.statevalues];
+    end
+    SBplot(createdatastructSBplotSB(time,datavalues,datanames));
+elseif nargout == 1,
+    varargout{1} = output;
+else 
+    error('Incorrect number of output arguments!');
+end
+
+% Delete all temporary files (if SBmodel)
+if isSBmodel(model),
+    deleteTempODEfileSB(ODEfilefullpath);
+end
+
+% clear temp global variables
+if fastFlag == 1,
+    eval(sprintf('clear global %s',augmKernelName));
+end
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/simulation/auxiliary/convertFastReacModelSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/simulation/auxiliary/convertFastReacModelSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..a94729e28efd9f5a079834b29cfdfe2570ac39d8
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/simulation/auxiliary/convertFastReacModelSB.m
@@ -0,0 +1,236 @@
+function [convmodel,K,nrODEsNorm,nrARs,fastIndex] = convertFastReacModelSB(model)
+% convertFastReacModelSB
+% Processes a given model which contains fast reactions and returns a
+% converted simulatable model together with the Kernel (left null space) of
+% the fast reaction stoichiometric matrix that needs to be part of the mass
+% matrix for simulation.
+%
+% The function needs to be interactive in the case that moiety
+% conservations are present in the model. ... MAYBE
+%
+% LIMITATION: "stoichiometry math" does not lead to an entry in the
+% stoichiometric matrix and thus might lead to wrong results if in
+% combination with fast reactions.
+%
+% USAGE:
+% ======
+% [convmodel,K,nrODEsNorm,nrARs,fastIndex] = convertFastReacModelSB(model)
+%
+% model: SBmodel to process
+%
+% Output Arguments:
+% =================
+% convmodel: converted model that can be simulated (using K as part of the
+%   mass matrix).
+% K: left null space of the fast reaction stoichiometric matrix that needs to
+%   be part of the mass matrix for simulation.
+% nrODEsNorm: number of the ODEs that are not affected by the
+%   transformation (these come first).
+% nrARs: number of the algebraic rules that have been added due to the fast
+%   reactions.
+% fastIndex: indices of the fast reactions
+
+% Information:
+% ============
+% Copyright (C) 2008 Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF SBmodel
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~isSBmodel(model),
+    error('Function only defined for SBmodels.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE NON-NUMERIC INITIAL CONDITIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% just by replacing them
+model = SBconvertNonNum2NumIC(model);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF fast flag present in the model
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if ~usefastSB(model),
+    error('The model does not contain any fast reactions.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK IF MOIETY CONSERVATIONS ARE PRESENT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%
+if hasmoietyconservationsSB(model),
+    error(sprintf('The model contains moiety conservations. Please reduce these conservations laws\nusing the ''SBreducemodel'' function prior to running the previous function.\n\nThe reason for not reducing the model automatically is the fact that sometimes\nit is necessary to choose a tolerance setting manually in order to obtain correct\nreduction results.'));
+end    
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE THE STOICHIOMETRIC MATRIX (RAW settings)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[N,componentNames,reactionNames] = SBstoichiometry(model,1,1);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET THE FAST REACTIONS AND SPLIT N INTO Nf AND Ns
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[reac_names,reac_formulas,reversibleFlag,fastFlag] = SBreactions(model);
+fastIndex = find(fastFlag~=0);
+slowIndex = [1:length(reac_names)];
+slowIndex(fastIndex) = [];
+Nf = N(:,fastIndex);
+Ns = N; Ns(:,fastIndex) = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE THE LEFT NULL SPACE OF Nf (K)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+[U,S,V] = svd(Nf);
+K = U(rank(Nf)+1:end,:);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CONSTRUCT THE NEW MODEL
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ms = struct(model);
+cms = struct(SBmodel());
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% COPY THE UNCHANGED STUFF
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% FUNCTIONS
+cms.functions = ms.functions;
+% FUNCTIONSMATLAB
+cms.functionsMATLAB = ms.functionsMATLAB;
+% REACTIONS 
+cms.reactions = ms.reactions;
+% VARIABLES
+cms.variables = ms.variables;
+% PARAMETERS
+cms.parameters = ms.parameters;
+% EVENTS
+cms.events = ms.events;
+% NAME
+cms.name = [ms.name,'_(converted_to_handle_fast_reactions)'];
+% NOTES
+cms.notes = sprintf('PLEASE NOTE: This model has been converted due to fast reactions in the\noriginal model. Direct simulation is not possible / does lead to an\nerroneous behavior. The null space matrix K needs to be taken into account\nwhen building the ODE m-file and additionally it needs to be part of the\nmass-matrix that is used for integration.\n\n%s',ms.notes);
+% ALGEBRAIC (just copy the ones that have been in the model from the start)
+cms.algebraic = ms.algebraic;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% COPY THE ODEs NOT BEING PART OF THE STOICHIOMETRIC MATRIX
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+nonReacStates = setdiff(SBstates(model),componentNames);
+nonReacStatesIndex = stateindexSB(model,nonReacStates);
+cms.states = ms.states(nonReacStatesIndex);
+nrODEsNorm = length(cms.states);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% BUILD THE ALGEBRAIC RULES (0 = Nf*vf)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+vf = reac_names(fastIndex);
+% process Nf
+Nf = rref(Nf);
+% remove zero rows 
+Nf(find(sum(abs(Nf),2)==0),:) = [];
+% build ARs
+nrARs = 0;
+for k=1:size(Nf,1),
+    Nfk = Nf(k,:);
+    ARk = '';
+    for k2 = 1:length(Nfk),
+        if Nfk(k2) > 0,
+            ARk = sprintf('%s+%g*%s',ARk,Nfk(k2),vf{k2});
+        elseif Nfk(k2) < 0,
+            ARk = sprintf('%s-%g*%s',ARk,abs(Nfk(k2)),vf{k2});
+        end
+    end
+    if ~isempty(ARk),
+        % add the AR to the model structure
+        cms.algebraic(end+1).name = '';
+        cms.algebraic(end).formula = ARk;
+        cms.algebraic(end).initialCondition = [];
+        cms.algebraic(end).notes = 'Algebraic rule due to fast reactions';
+        nrARs = nrARs + 1;
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% BUILD THE REAC ODEs (Ns*vs)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Remove states if Nsk only zeros (then a state is only defined by a fast
+% reaction and it should be added as variable to the corresponding
+% algebraic rule. 
+vs = reac_names(slowIndex);
+addStatesToARs = {};
+addStatesToARsICs = [];
+for k=1:length(componentNames),
+    Nsk = Ns(k,:);
+    if sum(abs(Nsk)) ~= 0,
+        % copy the easy information
+        cms.states(end+1).name = componentNames{k};
+        index = stateindexSB(model,componentNames{k});
+        cms.states(end).notes = ms.states(index).notes;
+        cms.states(end).initialCondition = ms.states(index).initialCondition;
+        cms.states(end).type = ms.states(index).type;
+        cms.states(end).unittype = ms.states(index).unittype;
+        cms.states(end).compartment = ms.states(index).compartment;
+        % construct the ODE
+        ODEk = '';
+        for k2 = 1:length(Nsk),
+            if Nsk(k2) > 0,
+                ODEk = sprintf('%s+%g*%s',ODEk,Nsk(k2),vs{k2});
+            elseif Nsk(k2) < 0,
+                ODEk = sprintf('%s-%g*%s',ODEk,abs(Nsk(k2)),vs{k2});
+            end
+        end
+        cms.states(end).ODE = ODEk;
+    else
+        addStatesToARs{end+1} = componentNames{k};
+        index = stateindexSB(model,componentNames{k});
+        addStatesToARsICs(end+1) = ms.states(index).initialCondition;
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% ADD STATES TO ARs IF REMOVED AS STATES SINCE ONLY DETERMINED BY FAST REACTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+for k=1:length(addStatesToARs),
+    for k2=1:length(cms.algebraic),
+        % where these names are added is unimportant. so just add them to 
+        % the ARs appearing first and having no vars assigned
+        if isempty(cms.algebraic(k2).name),
+            cms.algebraic(k2).name = addStatesToARs{k};
+            cms.algebraic(end).initialCondition = addStatesToARsICs(k);
+            % continue with next state to add
+            break;
+        end
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHANGE NULLSPACE IN THE CASE THAT Ns HAS ZERO ROWS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% Comments: A.Soubret 27/10/2009
+% The function below do not works since we need to keep all the column of
+% the matrix for the mass matrix, i.e. K*dx_dt
+% Determine zero rows in Ns
+%nonzeroindices = find(sum(abs(Ns'))~=0);
+% Keep only the corresponding COLUMNS of K
+%K = K(:,nonzeroindices);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% MAKE SBmodel
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+convmodel = SBmodel(cms);
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/simulation/auxiliary/eventsimulateSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/simulation/auxiliary/eventsimulateSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..fa98fd89dbdf236d0897701265dedaf0e8cdbbf4
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tasks/simulation/auxiliary/eventsimulateSB.m
@@ -0,0 +1,121 @@
+function [t,x,te,xe,ie,parameterValuesNew_ALL] = eventsimulateSB(model,method,tspan,ic,options,eventFunction,eventAssignmentFunction)
+% eventsimulateSB: Function realizing the simulation of systems with events
+% that cause discrete state changes. Implementation as auxiliary function
+% in order to be able to reuse the code when simulating systems with events
+% during parameter sensitivity analysis.
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+parameterValuesNew = []; % for changing parameter values using events
+parameterValuesNew_ALL = []; % save new parameter values for later generation of data ...
+nominalParameters = feval(model,'parametervalues')';
+
+% initialize simulation results
+t = [];
+x = [];
+te = [];
+xe = [];
+ie = [];
+% add the eventFunction to the integrator options
+options = odeset(options,'Events',eventFunction);
+
+
+% simulate the system until end time is reached
+% in case the user provided a defined time instant vector when results are
+% to be returned, it is necessary to delete 2 event instants from the
+% vectors ...
+% in case that the event time is not a measured time instant then delete
+% the last element from the previous piece and the first element from the
+% following piece
+% in case that the event time is a member of tspan, the last two elements
+% of the previous simulation data should be deleted. 
+tspansim = tspan;
+deleteFirstElementNext = 0;
+while 1,
+    % Do the simulation until event or finished
+    parameterValuesNew = parameterValuesNew(:)';    
+    [tpiece,xpiece,tepiece,xepiece,iepiece] = eval(sprintf('feval(@%s,@%s,tspansim,ic,options,parameterValuesNew);',method,model));
+    % get the state and final piece time
+    pieceEndState = xpiece(end,:);
+    pieceEndTime = tpiece(end);
+    % check if an event has happened
+    if ~isempty(tepiece) && max(tepiece) == pieceEndTime,
+        % an event has happened ... 
+        eventTime = tepiece(end);
+        eventIndex = iepiece(end);        
+        % just delete the last element (its the event time anyway)
+        if eventTime ~= max(tspan),        
+            tpiece = tpiece(1:end-1);
+            xpiece = xpiece(1:end-1,:);
+        end
+    end
+    
+    % collect simulation data
+    t = [t; tpiece];
+    x = [x; xpiece];
+    te = [te; tepiece(:)]; 
+    ie = [ie; iepiece(:)];
+    xe = [xe; xepiece];
+    
+    if length(tspan) > 2,
+        % time vector given ...
+        % delete the time instants that DO NOT appear in
+        % the time span vector
+        index = find(~ismember(t,tspan));
+        t(index) = [];
+        x(index,:) = [];
+        
+        % if the event is at a value in the time vector give, 
+        % then must remove the first instance of this time point
+        [b m] = unique(t, 'last');
+        t = t(m);
+        x = x(m, :);
+    end
+    
+    % save parameter values for this piece
+    if isempty(parameterValuesNew),
+        parameterValuesNew_ALL = [parameterValuesNew_ALL; nominalParameters(ones(1,length(tpiece)),:)];
+    else
+        parameterValuesNew_ALL = [parameterValuesNew_ALL; parameterValuesNew(ones(1,length(tpiece)),:)];
+    end
+
+    % check if integration is finished - then break the loop and continue
+    if pieceEndTime >= max(tspansim),
+        break;
+    end
+
+    % set new initial conditions and new time vector for simulation
+    [ic,parameterValuesNew] = feval(eventAssignmentFunction,eventIndex,eventTime,pieceEndState,parameterValuesNew);
+    % set new tspansim
+    if length(tspansim) == 2,
+        % if tspansim has 2 elements:
+        tspansim = [eventTime tspansim(2)];
+    else
+        % if tspansim given as vector of time instants
+        tspansimhelp = tspansim(find(tspansim > eventTime));
+        tspansim = [eventTime tspansimhelp(:)'];
+    end
+end
+return
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/auxiliary/handleLowHighBoundsSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/auxiliary/handleLowHighBoundsSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..f9e3d944398c9d9db6feabb3975af8480cedbc89
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/auxiliary/handleLowHighBoundsSB.m
@@ -0,0 +1,83 @@
+function [lowbounds,highbounds] = handleLowHighBoundsSB(OPTIONS,X,lowbounds,highbounds)
+% handleLowHighBoundsSB: Handles low and high bounds definitions in the options
+% for all optimizers.
+
+% Information:
+% ============
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+ndim = length(X);
+
+% lowbounds
+if isfield(OPTIONS,'lowbounds'),
+    if ~isempty(OPTIONS.lowbounds),
+        if length(OPTIONS.lowbounds) == ndim,
+            lowbounds = OPTIONS.lowbounds;
+        else
+            if length(OPTIONS.lowbounds) == 1,
+                if ~isempty(find(X<0, 1)),
+                    error('Please specify a vector for the lower bounds using OPTIONS.lowbounds.');
+                end
+                lowbounds = X*OPTIONS.lowbounds;
+            else
+                error('The OPTIONS.lowbounds setting is not correct.');
+            end
+        end
+    else
+        lowbounds = -Inf(1,ndim);
+    end
+else
+    if ~isempty(find(X<0, 1)),
+        error('Please specify a vector for the lower bounds using OPTIONS.lowbounds.');
+    end
+end
+% highbounds
+if isfield(OPTIONS,'highbounds'),
+    if ~isempty(OPTIONS.highbounds),
+        if length(OPTIONS.highbounds) == ndim,
+            highbounds = OPTIONS.highbounds;
+        else
+            if length(OPTIONS.highbounds) == 1,
+               if ~isempty(find(X<0, 1)),
+                    error('Please specify a vector for the higher bounds using OPTIONS.highbounds.');
+               end
+                highbounds = X*OPTIONS.highbounds;
+            else
+                error('The OPTIONS.highbounds setting is not correct.');
+            end
+        end
+    else
+        highbounds = Inf(1,ndim);
+    end
+else
+    if ~isempty(find(X<0, 1)),
+        error('Please specify a vector for the higher bounds using OPTIONS.highbounds.');
+    end
+end
+lowbounds = lowbounds(:)';
+highbounds = highbounds(:)';
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK BOUND VIOLATION FOR INITIAL GUESS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+indexXhi = find(X(:) > highbounds(:), 1);
+if ~isempty(indexXhi),
+    error('Initial guess does violate high parameter bounds.');
+end
+indexXlo = find(X(:) < lowbounds(:), 1);
+if ~isempty(indexXlo),
+    error('Initial guess does violate low parameter bounds.');
+end
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/auxiliary/isres/isrsort.c b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/auxiliary/isres/isrsort.c
new file mode 100644
index 0000000000000000000000000000000000000000..b5d5972166414cba9047e004a22a3ec1bc464889
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/auxiliary/isres/isrsort.c
@@ -0,0 +1,69 @@
+/*
+ * Optimized SRSORT Stochastic Ranking Procedure (Stochastic Bubble Sort)
+ * based on the code by Thomas Philip Runarsson (e-mail: tpr@verk.hi.is).
+ *
+*/
+
+#include "mex.h"
+#define MAX(A,B) ((A) > (B) ? (A):(B))
+
+void mexFunction(int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[])
+{
+  int n ;
+  double *P, *f, *phi ;  
+  int i, j ;
+  double pf, *I, Is, *G ;
+
+  /* check input arguments */
+  if (nrhs != 3)
+    mexErrMsgTxt("usage: I = isrsort(f,phi,pf) ;") ;
+
+  /* get pointers to input */
+  n = mxGetM(prhs[0]) ;
+  f = mxGetPr(prhs[0]) ;
+  phi = mxGetPr(prhs[1]) ;
+  P = mxGetPr(prhs[2]) ;
+  pf = P[0] ;
+
+  /* initialize index */
+  plhs[0] = mxCreateDoubleMatrix(n,1,mxREAL) ;
+  I = mxGetPr(plhs[0]) ;
+  for (i=1;i<=n;i++)
+    I[i-1] =(double)i ;
+
+  /* allocate random vector */
+  if ((G = (double *) mxCalloc(n-1,sizeof(double))) == NULL)
+    mexErrMsgTxt("fault: memory allocation error in mxCalloc") ;
+
+  /* Set evil seed (initial seed) */
+  srand((unsigned)time(NULL));
+  
+  /* perform stochastic bubble sort */
+  for (i=0;i<n;i++) {
+    Is = 0 ;
+    
+    /* Faster randomize */
+    for (i=0;i<n-1;i++)
+        G[i] = rand()/((double)RAND_MAX);
+
+    for (j=0;j<(n-1);j++) {
+      if (((phi[(int)I[j]-1]==phi[(int)I[j+1]-1]) && (phi[(int)I[j]-1]==0)) || (G[j]<pf) ) {
+        if (f[(int)I[j]-1]>f[(int)I[j+1]-1]) {
+          Is = I[j] ;
+          I[j] = I[j+1] ;
+          I[j+1] = Is ;
+        }
+      }
+      else {
+        if (phi[(int)I[j]-1]>phi[(int)I[j+1]-1]) { 
+          Is = I[j] ;
+          I[j] = I[j+1] ;
+          I[j+1] = Is ;
+        }
+      }
+    }
+    if (Is == 0)
+      break ;
+  }
+  mxFree(G) ;
+}
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/auxiliary/pswarm/InitPatternSearch.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/auxiliary/pswarm/InitPatternSearch.m
new file mode 100644
index 0000000000000000000000000000000000000000..0133833b16959682a6ced7c03cd56810761da605
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/auxiliary/pswarm/InitPatternSearch.m
@@ -0,0 +1,30 @@
+function [Problem]=InitPatternSearch(Problem)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+% Subrotine InitPatternSearch
+%
+%  This subroutine initializes the search directions for the poll step
+%
+%  User provided directions can be included in the
+%                        Problem.Poll.SearchDirections.UserSpecified matrix
+%
+%  Provides the coordinate directions
+%
+%  Input:
+%    Problem - The problem structure
+%
+%  Output:
+%    Problem - The problem structure updated
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% aivaz@dps.uminho.pt 01/12/2006
+
+% Coordinate Search for Variables
+Problem.Poll.SearchDirections.Base=[eye(Problem.Variables) ...
+                                   -eye(Problem.Variables)];
+
+% A set of directions specified by user
+Problem.Poll.SearchDirections.UserSpecified =[];
+
+return;
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/auxiliary/pswarm/PenaltyEval.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/auxiliary/pswarm/PenaltyEval.m
new file mode 100644
index 0000000000000000000000000000000000000000..f8b27417cac766b5445ae9a61ddd1ef1b6aa6655
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/auxiliary/pswarm/PenaltyEval.m
@@ -0,0 +1,40 @@
+function [Problem,ObjValue] = PenaltyEval(Problem, x)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+% Subrotine PenaltyEval
+%  This subrotine is called to evaluate the objective function
+%
+%  Input:
+%    Problem - The problem structure
+%    x - Real part of point to evaluate
+%    varargin - Extra parameters for objective function
+%
+%  Output:
+%    Problem - The problem structure updated
+%    ObjValue - Objective function value. Returns +Inf for unfeasible
+%       points
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%aivaz@dps.uminho.pt 06/12/2006
+
+% adapted for SBTOOLBOX by Henning Schmidt 
+
+% Bound feasibility is enforced by the projection onto the bound feasible
+% domain
+% LB <= x' && x'<=UB
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Continue with original function
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+try
+    ObjValue=feval(Problem.ObjFunction, x);
+    % update counter
+    Problem.Stats.ObjFunCounter=Problem.Stats.ObjFunCounter+1;
+catch
+    error('pswarm:ObjectiveError', ...
+        ['Cannot continue because user supplied objective function' ...
+        ' failed with the following error:\n%s'], lasterr)
+end
+
+return;
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/auxiliary/pswarm/PollStep.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/auxiliary/pswarm/PollStep.m
new file mode 100644
index 0000000000000000000000000000000000000000..e9a1a319743ecc2c19516dcd2a98f5e4d2be7dbb
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/auxiliary/pswarm/PollStep.m
@@ -0,0 +1,67 @@
+function [Problem,Population]=PollStep(Problem,Population)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+%  subroutine PollStep
+%
+%  Performe a poll step for the pattern search on the leader particle of
+%  the particle swarm.
+%
+%  Input:
+%    Problem - Problem structure
+%    Population - The population
+%
+%  Output:
+%    Poblem - Problem structure updated
+%    Population - Population updated
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% aivaz@dps.uminho.pt 30/03/2007
+
+%
+% Proceed with a poll step on the leader
+%
+
+% Columnwise search directions.
+D= [Problem.Poll.SearchDirections.Base, ...
+    Problem.Poll.SearchDirections.UserSpecified];
+
+% Columnwise Leader
+Leader=Population.y(Population.Leader,:)';
+
+% for all directions
+for i=1:size(D,2)
+    % Compute trial point
+    Trial=Projection(Leader+Population.Delta*D(:,i),Problem.LB,Problem.UB);
+    % Compute objective function
+    [Problem,ObjTrial]= PenaltyEval(Problem, Trial');
+    
+    % Check for progress
+    if Population.fy(Population.Leader)>ObjTrial
+        % a successful poll step. Update counter.
+        Problem.Stats.SuccPollSteps=Problem.Stats.SuccPollSteps+1;
+        % update leader
+        Population.y(Population.Leader,:)=Trial;
+        Population.fy(Population.Leader)=ObjTrial;
+        
+        % Success obtained along the previous successful direction?
+        if ~isempty(Problem.Poll.LastSuccess) && ...
+                isequal(Problem.Poll.LastSuccess(:),D(:,i))
+            % Yes. Increase Delta
+            Population.Delta=Population.Delta*Problem.IncreaseDelta;
+        else
+            % No. Update previous direction
+            Problem.Poll.LastSuccess=D(:,i);
+        end
+        
+        % Return. Successful poll step
+        return;
+    end
+end
+
+% No success in poll step. Decrease Delta.
+if Population.Delta>Problem.Tolerance
+    Population.Delta=Population.Delta*Problem.DecreaseDelta;
+end
+
+return;
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/auxiliary/pswarm/Projection.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/auxiliary/pswarm/Projection.m
new file mode 100644
index 0000000000000000000000000000000000000000..73428c677a2c1c0830d6626067c7e792f2a89a2d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/auxiliary/pswarm/Projection.m
@@ -0,0 +1,27 @@
+function X=Projection(X, L, U)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+%  subrotine Projection
+%
+%  Input:
+%    X - Point to be projected
+%    L - Domain lower bound
+%    U - Domain upper bound
+%
+%  Output:
+%    X - Projected point
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% aivaz@dps.uminho.pt 06/12/2006
+
+%Do you really need comments?
+for i=1:length(X)
+    if X(i)<L(i)
+        X(i)=L(i);
+    end
+    if X(i)>U(i)
+        X(i)=U(i);
+    end
+end
+
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/auxiliary/pswarm/lgpl.txt b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/auxiliary/pswarm/lgpl.txt
new file mode 100644
index 0000000000000000000000000000000000000000..5ab7695ab8cabe0c5c8a814bb0ab1e8066578fbb
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/auxiliary/pswarm/lgpl.txt
@@ -0,0 +1,504 @@
+		  GNU LESSER GENERAL PUBLIC LICENSE
+		       Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL.  It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+			    Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+  This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it.  You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+  When we speak of free software, we are referring to freedom of use,
+not price.  Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+  To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights.  These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+  For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you.  You must make sure that they, too, receive or can get the source
+code.  If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it.  And you must show them these terms so they know their rights.
+
+  We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+  To protect each distributor, we want to make it very clear that
+there is no warranty for the free library.  Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+
+  Finally, software patents pose a constant threat to the existence of
+any free program.  We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder.  Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+  Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License.  This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License.  We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+  When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library.  The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom.  The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+  We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License.  It also provides other free software developers Less
+of an advantage over competing non-free programs.  These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries.  However, the Lesser license provides advantages in certain
+special circumstances.
+
+  For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard.  To achieve this, non-free programs must be
+allowed to use the library.  A more frequent case is that a free
+library does the same job as widely used non-free libraries.  In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+  In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software.  For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+  Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.  Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library".  The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+
+		  GNU LESSER GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+  A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+  The "Library", below, refers to any such software library or work
+which has been distributed under these terms.  A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language.  (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+  "Source code" for a work means the preferred form of the work for
+making modifications to it.  For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+  Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it).  Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+  
+  1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+  You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+  2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) The modified work must itself be a software library.
+
+    b) You must cause the files modified to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    c) You must cause the whole of the work to be licensed at no
+    charge to all third parties under the terms of this License.
+
+    d) If a facility in the modified Library refers to a function or a
+    table of data to be supplied by an application program that uses
+    the facility, other than as an argument passed when the facility
+    is invoked, then you must make a good faith effort to ensure that,
+    in the event an application does not supply such function or
+    table, the facility still operates, and performs whatever part of
+    its purpose remains meaningful.
+
+    (For example, a function in a library to compute square roots has
+    a purpose that is entirely well-defined independent of the
+    application.  Therefore, Subsection 2d requires that any
+    application-supplied function or table used by this function must
+    be optional: if the application does not supply it, the square
+    root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library.  To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License.  (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.)  Do not make any other change in
+these notices.
+
+  Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+  This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+  4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+  If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library".  Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+  However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library".  The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+  When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library.  The
+threshold for this to be true is not precisely defined by law.
+
+  If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work.  (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+  Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+  6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+  You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License.  You must supply a copy of this License.  If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License.  Also, you must do one
+of these things:
+
+    a) Accompany the work with the complete corresponding
+    machine-readable source code for the Library including whatever
+    changes were used in the work (which must be distributed under
+    Sections 1 and 2 above); and, if the work is an executable linked
+    with the Library, with the complete machine-readable "work that
+    uses the Library", as object code and/or source code, so that the
+    user can modify the Library and then relink to produce a modified
+    executable containing the modified Library.  (It is understood
+    that the user who changes the contents of definitions files in the
+    Library will not necessarily be able to recompile the application
+    to use the modified definitions.)
+
+    b) Use a suitable shared library mechanism for linking with the
+    Library.  A suitable mechanism is one that (1) uses at run time a
+    copy of the library already present on the user's computer system,
+    rather than copying library functions into the executable, and (2)
+    will operate properly with a modified version of the library, if
+    the user installs one, as long as the modified version is
+    interface-compatible with the version that the work was made with.
+
+    c) Accompany the work with a written offer, valid for at
+    least three years, to give the same user the materials
+    specified in Subsection 6a, above, for a charge no more
+    than the cost of performing this distribution.
+
+    d) If distribution of the work is made by offering access to copy
+    from a designated place, offer equivalent access to copy the above
+    specified materials from the same place.
+
+    e) Verify that the user has already received a copy of these
+    materials or that you have already sent this user a copy.
+
+  For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it.  However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+  It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system.  Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+  7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+    a) Accompany the combined library with a copy of the same work
+    based on the Library, uncombined with any other library
+    facilities.  This must be distributed under the terms of the
+    Sections above.
+
+    b) Give prominent notice with the combined library of the fact
+    that part of it is a work based on the Library, and explaining
+    where to find the accompanying uncombined form of the same work.
+
+  8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License.  Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License.  However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+  9. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Library or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+  10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+
+  11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded.  In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+  13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation.  If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+  14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission.  For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this.  Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+			    NO WARRANTY
+
+  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+		     END OF TERMS AND CONDITIONS
+
+           How to Apply These Terms to Your New Libraries
+
+  If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change.  You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+  To apply these terms, attach the following notices to the library.  It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the library's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Lesser General Public
+    License as published by the Free Software Foundation; either
+    version 2.1 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Lesser General Public License for more details.
+
+    You should have received a copy of the GNU Lesser General Public
+    License along with this library; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the
+  library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+  <signature of Ty Coon>, 1 April 1990
+  Ty Coon, President of Vice
+
+That's all there is to it!
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/auxiliary/pswarm/unifrndSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/auxiliary/pswarm/unifrndSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..190dcd2844331bcda116ef2e4b9171e28a7d2074
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/auxiliary/pswarm/unifrndSB.m
@@ -0,0 +1,68 @@
+function [output] = unifrndSB(lower,upper,varargin)
+% unifrndSB: creates an array of uniformly distributed random variables for
+%   which the lower and upper bounds can be specified.
+%
+% USAGE:
+% ======
+% [output] = unifrndSB(lower,upper)         
+% [output] = unifrndSB(lower,upper,dim)         
+% [output] = unifrndSB(lower,upper,dim1,dim2)         
+% 
+% lower: lower bound(s). Either a scalar or a vector (same size as 'upper' or scalar allowed).
+% upper: upper bound(s). Either a scalar or a vector (same size as 'lower' or scalar allowed).
+% dim: in case lower and upper are scalars this defined the dimensions of
+%      the random matrix
+% dim1,dim2:  in case lower and upper are scalars this defined the dimensions of
+%      the random matrix
+
+% Information:
+% ============
+% Author: Henning Schmidt, henning@sbtoolbox2.org
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHECK INPUTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if size(lower,2) ~= size(upper,2) || size(lower,1) ~= size(upper,1),
+    if (size(lower,1) == 1 || size(lower,2) == 1) && (size(upper,1) == 1 || size(upper,2) == 1),
+        if isscalar(lower),
+            lower = lower*ones(size(upper));
+        elseif isscalar(upper),
+            upper = upper*ones(size(lower));
+        else
+            error('Wrong dimensions of ''lower'' and ''upper''.');
+        end
+    else
+        error('Wrong dimensions of ''lower'' and ''upper''.');
+    end
+end
+     
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin < 2 || nargin > 4,
+    error('Incorrect number of input arguments'); 
+end
+if nargin > 2 && length(lower) > 1,
+    error('If dimensions are specified, the ''lower'' and ''upper'' arguments need to be scalars.');
+end
+if nargin == 3,
+    dim1 = varargin{1};
+    dim2 = dim1;
+elseif nargin == 4,
+    dim1 = varargin{1};
+    dim2 = varargin{2};
+else
+    dim1 = size(upper,1);
+    dim2 = size(upper,2);
+end
+
+output = lower/2+upper/2 + (lower/2-upper/2) .* (2*rand(dim1,dim2)-1);
+
+% Handle trouble with higher low bounds than upper
+if ~isscalar(lower) || ~isscalar(upper)
+    output(lower > upper) = NaN;
+elseif lower > upper
+    output(:) = NaN;
+end
+return
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/isresSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/isresSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..4e671bc24be4b4bb8084bf11a95f5bba0eb73e06
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/isresSB.m
@@ -0,0 +1,415 @@
+function [X,FVAL,EXITFLAG] = isresSB(varargin)
+% isresSB: Stochastic Ranking for Constrained Evolutionary Minimization.
+%
+% The algorithm is described in:
+% Thomas Philip Runarsson and Xin Yao, Search Biases in Constrained 
+% Evolutionary Optimization. IEEE Transactions on Systems, Man and 
+% Cybernetics -- Part C: Applications and Reviews. Vol. 35, No. 2, 
+% pp 233-243, May 2005.
+%
+% The code of this function is based on the original code written by
+% Thomas Philip Runarsson (e-mail: tpr@verk.hi.is)
+%
+% If global variable stopOptimization is set to 1, the optimization is
+% stopped. This allows for stopping parameter estimation functions on user
+% request. 
+% 
+% USAGE:
+% ======
+% [info] = isresSB()
+% [X,FVAL,EXITFLAG] = isresSB(FUN,X)
+% [X,FVAL,EXITFLAG] = isresSB(FUN,X,OPTIONS)
+%
+% FUN: Function to optimize
+%      The cost function is required to have the following calling syntax:
+%         [output] = FUN(X)
+%      The 'output' can be a scalar defining the 'cost', or the 'output'
+%      can be a cell array with two elements: {'cost', 'constraints'}.
+%      The 'cost' output argument has a scalar value indicating the 'cost'
+%      of a given set of parameter values X.
+%      The algorithm is able to handle inequality constraints, where
+%      feasible parameter sets are defined by negative values of the
+%      corresponding constraint functions. The 'constraints' output
+%      argument is a vector, where each entry corresponds to one
+%      constraint. If the value of an element is positive the corresponding
+%      contraint is active. Simple min/max bounds on parameters need not be
+%      specified using constraint functions but are taken care of by the
+%      isresSBAO algorithm. 
+%
+% X: Starting Guess for parameter vector
+%
+% OPTIONS: structure containing options for the algorithm:
+%        OPTIONS.lowbounds: vector containing upper bounds for parameters
+%           Instead of a vector highbounds can also be a scalar > 1. In the
+%           latter case the highbounds are determined by multiplying this
+%           scalar to the initial parameter guess X. This latter case works
+%           only for positive X(i) ... if negative present then the user
+%           needs to specify a whole lowbounds vector. 
+%        OPTIONS.higbounds: vector containing lower bounds for parameters.
+%           Instead of a vector lowbounds can also be a scalar < 1. In the
+%           latter case the lowbounds are determined by multiplying this
+%           scalar to the initial parameter guess X. This latter case works
+%           only for positive X(i) ... if negative present then the user
+%           needs to specify a whole highbounds vector. 
+%        OPTIONS.linlog: string, either 'linear' or 'log'. 'linear' means
+%               that the parameters are optimized based on their real
+%               values, while 'log' means that the parameters are optimized
+%               based on their exponent to the base 10. Choose 'linear' for
+%               tight min max bounds, and choose 'log' for very wide
+%               bounds. The parameter bounds are always given as "real
+%               values" and not as exponents!
+%        OPTIONS.lambda: scalar, integer, population size (number of offspring) (100 to 400)
+%        OPTIONS.maxgen: maximum number of generations
+%        OPTIONS.maxtime: Maximum time (in minutes) for optimization
+%        OPTIONS.mu: parent number (mu/lambda usually 1/7)
+%        OPTIONS.pf: pressure on fitness in [0 0.5] try around 0.45
+%        OPTIONS.varphi: expected rate of convergence (usually 1)
+%        OPTIONS.outputFunction: string with output function name. If
+%               not given or if empty then no output function will be used.
+%               This output function can be used to display data, or to 
+%               save optimization information to a file. The function needs
+%               to be in the MATLAB path. Its calling syntax is:
+%
+%                   'outputFunction'(g,BestParameters,BestMin,Min,Mean,Std,NrFeas,Time)
+%
+%                   g: current generation number
+%                   BestParameters: the currently best set of parameters
+%                   BestMin: the currently minimal cost function value    
+%                   Min: min costfunction value in current generation (only feasible parameter sets count) 
+%                   Mean: mean costfunction value in current generation (only feasible parameter sets count)  
+%                   Std: standard deviation of cost function in current generation  (only feasible parameter sets count) 
+%                   NrFeas: number of feasible parameter sets in current generation   
+%                   Time: elapsed time
+%        OPTIONS.silent: =0: output of info, =1: no output
+%
+% DEFAULT VALUES:
+% ===============
+% OPTIONS.lowbounds:    0.1  => lowbounds = 0.1*X 
+% OPTIONS.highbounds:   10   => highbounds = 10*X 
+% OPTIONS.linlog:       'linear'
+% OPTIONS.lambda:       200
+% OPTIONS.maxgen:       ndim*200
+% OPTIONS.maxtime:      inf
+% OPTIONS.mu:           lambda*1/7
+% OPTIONS.pf:           0.45
+% OPTIONS.varphi:       1
+% OPTIONS.outputFunction: '' (no output function)
+% OPTIONS.silent:         0 (no output of info)
+%
+% Output Arguments:
+% =================
+% info: calling the function w/o input argument returns information about
+%       the options and a flag indicating if the algorithm can handle
+%       constraints or not
+% X: Best feasible individual           ([] if EXITFLAG = 0)
+% FVAL: Value of the function FUN at X  ([] if EXITFLAG = 0)
+% EXITFLAG: =1 if solution is feasible, =0 if solution is infeasible
+
+% Information:
+% ============
+% Function adapted for the toolbox by Henning Schmidt, henning@sbtoolbox2.org
+
+global stopOptimization
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check if isrsort.c is compiled to MEX function
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if exist('isrsort') ~= 3,
+    % Is not compiled yet, do it
+    currentpath = pwd;
+    cd(fileparts(which('isrsort.c')));
+    mex isrsort.c;
+    cd(currentpath);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 0,
+    X = [];
+    X.name = 'isresSB';
+    X.constrained = 1;
+    X.description = 'Stochastic Ranking for Constrained Evolutionary Minimization (global)';  
+    X.defaultOptions.names = {'maxgen', 'maxtime'};
+    X.defaultOptions.values = {'1000','500'};
+    X.defaultOptions.description = {'Maximum number of generations', 'Maximum time in minutes'};
+    FVAL = [];
+    EXITFLAG = [];
+    return
+elseif nargin == 2,
+    FUN = varargin{1};
+    X = varargin{2};
+    OPTIONS = [];
+elseif nargin == 3,
+    FUN = varargin{1};
+    X = varargin{2};
+    OPTIONS = varargin{3};
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Set default values
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ndim = length(X);
+% Default parameter bounds
+lowbounds = 0.1*X;
+highbounds = 10*X;
+% Other
+lambda = 200;
+maxgen = ndim*200;
+mu = ceil(lambda * 1/7);
+pf = 0.45;
+varphi = 1;
+maxtime = inf;
+linlog = 0;  % 0='linear', 1='log'
+silent = 0;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle OPTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% silent
+if isfield(OPTIONS,'silent'),
+    if ~isempty(OPTIONS.silent),
+        silent = OPTIONS.silent;
+    end
+end
+% linlog
+if isfield(OPTIONS,'linlog'),
+    if strcmp(OPTIONS.linlog,'linear'),
+        linlog = 0;
+    elseif strcmp(OPTIONS.linlog,'log'),
+        linlog = 1;
+    else
+        error('Wrong setting for OPTIONS.linlog.');
+    end
+end
+% lamba
+if isfield(OPTIONS,'lambda'),
+    if ~isempty(OPTIONS.lambda),
+        lambda = OPTIONS.lambda;
+    end
+    if ~isfield(OPTIONS,'mu'),
+        % set also mu in case mu not defined by options
+        mu = ceil(lambda*1/7);
+    end
+end
+% maxgen
+if isfield(OPTIONS,'maxgen'),
+    if ~isempty(OPTIONS.maxgen),
+        maxgen = OPTIONS.maxgen;
+    end
+end
+% maxtime
+if isfield(OPTIONS,'maxtime'),
+    if ~isempty(OPTIONS.maxtime),
+        maxtime = OPTIONS.maxtime;
+    end
+end
+% mu
+if isfield(OPTIONS,'mu'),
+    if ~isempty(OPTIONS.mu),
+        mu = OPTIONS.mu;
+    end
+end
+% pf
+if isfield(OPTIONS,'pf'),
+    if ~isempty(OPTIONS.pf),
+        pf = OPTIONS.pf;
+    end
+end
+% varphi
+if isfield(OPTIONS,'varphi'),
+    if ~isempty(OPTIONS.varphi),
+        varphi = OPTIONS.varphi;
+    end
+end
+% outputFunction
+outputFunction = '';
+if isfield(OPTIONS,'outputFunction'),
+    if ~isempty(OPTIONS.outputFunction),
+        outputFunction = OPTIONS.outputFunction;
+    end
+end
+% low and highbounds:
+[lowbounds, highbounds] = handleLowHighBoundsSB(OPTIONS,X,lowbounds,highbounds);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle linlog
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if linlog == 1, % 'log'
+    lowbounds = log10(lowbounds);
+    highbounds = log10(highbounds);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Initialize population
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+parameterPopulation = ones(lambda,1)*lowbounds+rand(lambda,ndim).*(ones(lambda,1)*(highbounds-lowbounds));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Selection index vector
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+sI = (1:ceil(mu))'*ones(1,ceil(lambda/mu)); sI = sI(1:lambda);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Initial algorithm parameter settings
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+eta = ones(lambda,1)*(highbounds-lowbounds)/sqrt(ndim);
+gamma = 0.85;
+alpha = 0.2;
+chi = (1/(2*ndim)+1/(2*sqrt(ndim)));
+varphi = sqrt((2/chi)*log((1/alpha)*(exp(varphi^2*chi/2)-(1-alpha))));
+tau  = varphi/(sqrt(2*sqrt(ndim)));
+tau_ = varphi/(sqrt(2*ndim));
+ub = ones(lambda,1)*highbounds;
+lb = ones(lambda,1)*lowbounds;
+eta_u = eta(1,:);
+nretry = 10;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Other
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+f = zeros(lambda,1); 
+phi = zeros(lambda,ndim);
+BestMin = inf;
+BestMean = inf;
+BestStd = inf;
+BestParameters = [];
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Loop over 'maxgen' generations
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+tic;
+if ~silent,
+    disp(sprintf('    #g        BestMin          Min(g)        Mean(g)         Std(g)     NrFeas     Time'));
+end
+for g=1:maxgen,
+    % fitness evaluation
+    for loop=1:lambda,
+        if linlog == 0, % linear
+            funoutput = feval(FUN,parameterPopulation(loop,:));
+        else % log
+            funoutput = feval(FUN,10.^parameterPopulation(loop,:));
+        end
+        if iscell(funoutput),
+            f(loop) = funoutput{1};
+            phivec = funoutput{2};
+        else
+            f(loop) = funoutput;
+            phivec = [];
+        end
+        if ~isempty(phivec),
+            phi(loop,:) = phivec(:)';
+        end
+    end
+    
+    FeasiblePhi = find((sum((phi>0),2)<=0));
+    NonFeasibleNaN = find(isnan(f));
+    NonFeasibleInf = find(isnan(f));
+    Feasible = setdiff(FeasiblePhi, union(NonFeasibleNaN,NonFeasibleInf));
+    
+    % Performance / statistics
+    if ~isempty(Feasible),
+        [MinGeneration,MinInd] = min(f(Feasible));
+        MinInd = Feasible(MinInd);
+        MeanGeneration = mean(f(Feasible));
+        StdGeneration = std(f(Feasible));
+        if MinGeneration < BestMin,
+            BestParameters = parameterPopulation(MinInd,:);
+            BestMin = MinGeneration;
+            BestMean = MeanGeneration;
+            BestStd = StdGeneration;
+        end    
+    else
+        MinGeneration = NaN; MeanGeneration = NaN;
+    end
+    NrFeas = length(Feasible);
+
+    % Compute penalty function "quadratic loss function" (or any other)
+    phi(find(phi<=0)) = 0;
+    phi = sum(phi.^2,2);
+
+    % Selection using stochastic ranking 
+    I = isrsort(f,phi,pf);
+    parameterPopulation = parameterPopulation(I(sI),:); 
+    eta = eta(I(sI),:);
+
+    % Update eta (traditional technique using exponential smoothing)
+    eta_ = eta;
+    eta(mu:end,:) = eta(mu:end,:).*exp(tau_*randn(lambda-mu+1,1)*ones(1,ndim)+tau*randn(lambda-mu+1,ndim));
+
+    % Upper bound on eta (used?)
+    for i=1:ndim,
+        I = find(eta(:,i)>eta_u(i));
+        eta(I,i) = eta_u(i)*ones(size(I));
+    end
+
+    % make a copy of the individuals for repeat ...
+    x_ = parameterPopulation;
+
+    % differential variation
+    parameterPopulation(1:mu-1,:) = parameterPopulation(1:mu-1,:) + gamma*(ones(mu-1,1)*parameterPopulation(1,:) - parameterPopulation(2:mu,:));
+
+    % Mutation
+    parameterPopulation(mu:end,:) = parameterPopulation(mu:end,:) + eta(mu:end,:).*randn(lambda-mu+1,ndim);
+
+    % If variables are out of bounds retry "nretry" times
+    I = find((parameterPopulation>ub) | (parameterPopulation<lb));
+    retry = 1 ;
+    while ~isempty(I)
+        parameterPopulation(I) = x_(I) + eta(I).*randn(length(I),1);
+        I = find((parameterPopulation>ub) | (parameterPopulation<lb));
+        if (retry>nretry), 
+            break; 
+        end
+        retry = retry + 1;
+    end
+    % ignore failures
+    if ~isempty(I),
+        parameterPopulation(I) = x_(I);
+    end
+
+    % exponential smoothing
+    eta(mu:end,:) = eta_(mu:end,:) + alpha*(eta(mu:end,:) - eta_(mu:end,:));
+
+    % output
+    if ~silent,
+        disp(sprintf(' %5.0f   %12.6f   %12.6g   %12.6g   %12.6g       %5.0f     %1.2e sec', g, BestMin, MinGeneration, MeanGeneration, StdGeneration, NrFeas, toc));
+    end
+    % call output function if defined
+    if ~isempty(outputFunction),
+        if linlog == 0, % linear
+            feval(outputFunction, g, BestParameters, BestMin, MinGeneration, MeanGeneration, StdGeneration, NrFeas, toc);
+        else % log
+            feval(outputFunction, g, 10.^BestParameters, BestMin, MinGeneration, MeanGeneration, StdGeneration, NrFeas, toc);
+        end
+    end
+    
+    if toc/60 > maxtime,
+        % Break the loop when more than 'OPTIONS.maxtime' minutes elapsed
+        break;
+    end
+    if stopOptimization == 1,
+        disp('User Interrupt.');
+        break;
+    end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check results and define output
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if isempty(BestParameters),
+    % only infeasible parameter sets
+    EXITFLAG = 0;
+    X = [];
+    FVAL = [];
+else
+    EXITFLAG = 1;
+    if linlog == 0, % linear
+        X = BestParameters;
+    else % log
+        X = 10.^BestParameters;
+    end
+    FVAL = BestMin;
+end
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/pswarmSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/pswarmSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..c9d54d3ef152f9bdc54e811627f7fb7ab5fe766e
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/pswarmSB.m
@@ -0,0 +1,520 @@
+function [X,FVAL,RunData] = pswarmSB(varargin)
+% pswarmSB: Particle swarm pattern search algorithm for global optimization.
+%
+% Algorithm developed by A. Ismael F. Vaz and L. N. Vicente.
+% aivaz@dps.uminho.pt 04/04/2007
+% More information: http://www.norg.uminho.pt/aivaz/pswarm/
+%
+% In case of a publication that was prepared using pswarm, users
+% are asked to cite the following publication:
+% A. I. F. Vaz and L. N. Vicente, A particle swarm pattern search method
+% for bound constrained global optimization,
+% Journal of Global Optimization, 39 (2007) 197-219.
+%
+% The PSwarm algorithm takes advantage of the particle swarm algorithm in
+% looking for a global optimum in the search phase of the pattern search
+% algorithm. The pattern search enforces convergence for a local optimum.
+%
+% If the global variable stopOptimization is set to 1, the optimization is
+% stopped. This allows for stopping parameter estimation functions on user
+% request. 
+% 
+% USAGE:
+% ======
+% [info] = pswarmSB()
+% [X,FVAL,RunData] = pswarmSB(FUN,X)
+% [X,FVAL,RunData] = pswarmSB(FUN,X,OPTIONS)
+%
+% FUN:      Function to optimize
+% X:        Starting Guess
+% OPTIONS:  Structure containing options for the algorithm. 
+%       OPTIONS.lowbounds: vector with lower bounds for variables 
+%       OPTIONS.highbounds: vector with lower bounds for variables
+%       OPTIONS.logFlag: Flag indicating if the parameter space should be
+%               searched linearly (0) or logarithmically (1).
+%       OPTIONS.Cognitial: cognitial parameter in the velocity equation
+%       OPTIONS.InerciaFinalWeight: The value of the inercia parameter in the velocity
+%             at last iteration.
+%       OPTIONS.InerciaInitialWeight: The value of the inercia parameter in the
+%             velocity equation at first iteration.
+%       OPTIONS.maxfunevals: Maximum number of objective function evaluations. Since the
+%             algorithm is population based this maximum number of
+%             objective function evaluation may be sligtly exceeded.
+%       OPTIONS.maxiter: Maximum number of iterations allowed.
+%       OPTIONS.popsize: Population size.
+%       OPTIONS.Social: Social parameter in the velocity equation.
+%       OPTIONS.MaxVelocityFactor: Velocity will be projected in the set
+%             (UB-LB)*MaxVelocityFactor.
+%       OPTIONS.CPTolerance: Stopping criteria tolerance.
+%       OPTIONS.InitialDelta: Initial pattern search grid step.
+%       OPTIONS.DeltaIncreseFactor: Delta will be increased by this factor (on
+%             successful poll steps).
+%       OPTIONS.DeltaDecreaseFactor: Delta willbe decreased by this factor (on
+%             unsuccessful poll steps).
+%       OPTIONS.InitialDeltaFactor: The inicial Delta will be the min(UB-LB) times this
+%             factor.
+%       OPTIONS.silent: 0=show iterations, 1=do not show iterations.
+%
+% DEFAULT VALUES:
+% ===============
+%       OPTIONS.lowbounds:              1e-3*X
+%       OPTIONS.highbounds:             1e3*X
+%       OPTIONS.Cognitial:              0.5000
+%       OPTIONS.InerciaFinalWeight:     0.4000
+%       OPTIONS.InerciaInitialWeight:   0.9000
+%       OPTIONS.maxfunevals:            5000*length(X);
+%       OPTIONS.maxiter:                1000*length(X);
+%       OPTIONS.popsize:                20*length(X);
+%       OPTIONS.Social:                 0.5000
+%       OPTIONS.MaxVelocityFactor:      0.5000
+%       OPTIONS.CPTolerance:            1.0000e-005
+%       OPTIONS.InitialDelta:           2
+%       OPTIONS.DeltaIncreaseFactor:    2
+%       OPTIONS.DeltaDecreaseFactor:    0.5000
+%       OPTIONS.InitialDeltaFactor:     5
+%       OPTIONS.silent:                 0
+%
+% Output Arguments:
+% =================
+% info: calling the function w/o input argument returns information about
+%       the options and a flag indicating if the algorithm can handle
+%       constraints or not
+% X:        Found solution (The best particle obtained for the population (Leader))
+% FVAL:     Value of the function FUN at X 
+% RunData:  Some statistics obout the algorithm run
+%
+% Copyright Information:
+% ======================
+% Copyright (C) 2007 A. Ismael F. Vaz and L. N. Vicente.
+% aivaz@dps.uminho.pt 04/04/2007
+% http://www.norg.uminho.pt/aivaz
+% http://www.mat.uc.pt/~lnv
+%
+% Algorithm adapted and included in the SBTOOLBOX2 by Henning Schmidt, 
+% with permission of the authors.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GLOBAL VARIABLES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+global stopOptimization
+if isempty(stopOptimization),
+    stopOptimization = 0;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 0,
+    X = [];
+    X.name = 'pswarmSB';
+    X.constrained = 1;
+    X.description = 'Particle swarm pattern search algorithm (global)';       
+    X.defaultOptions.names = {'maxfunevals', 'maxiter'};
+    X.defaultOptions.values = {'100000','40000'};
+    X.defaultOptions.description = {'Maximum number of function evaluations', 'Maximum number of iterations'};
+    FVAL = [];
+    RunData = [];
+    return
+elseif nargin == 2,
+    FUN = varargin{1};
+    X = varargin{2};
+    OPTIONS = [];
+elseif nargin == 3,
+    FUN = varargin{1};
+    X = varargin{2};
+    OPTIONS = varargin{3};
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE OPTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+DefaultOpt.lowbounds = 1e-3*X;
+DefaultOpt.highbounds = 1e3*X;
+DefaultOpt.Cognitial = 0.5000;
+DefaultOpt.InerciaFinalWeight = 0.4000;
+DefaultOpt.InerciaInitialWeight = 0.9000;
+DefaultOpt.maxfunevals = 5000*length(X);
+DefaultOpt.maxiter = 1000*length(X);
+DefaultOpt.popsize = 20*length(X);
+DefaultOpt.Social = 0.5000;
+DefaultOpt.MaxVelocityFactor = 0.5000;
+DefaultOpt.CPTolerance = 1.0000e-005;
+DefaultOpt.InitialDelta = 2;
+DefaultOpt.DeltaIncreaseFactor = 2;
+DefaultOpt.DeltaDecreaseFactor = 0.5000;
+DefaultOpt.InitialDeltaFactor = 5;
+DefaultOpt.silent = 0;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CREATE INITIAL POPULATION STRUCTURE (just one entry)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+InitialPopulation(1).x = X;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CREATE PROBLEM STRUCTURE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+Problem = [];
+Problem.ObjFunction = FUN;
+Problem.LB = GetOption('lowbounds',OPTIONS,DefaultOpt);
+Problem.UB = GetOption('highbounds',OPTIONS,DefaultOpt);
+Problem.Variables = length(X);
+if length(Problem.LB)~=length(Problem.UB)
+    error('Lower bound and upper bound arrays length mismatch.');
+end
+
+% Start clock
+tic;
+
+% Initialize options. GetOption returns the user specified value, if the
+% option exists. Otherwise returns the default option.
+
+% These are local options. Not needed for the subrotines
+MaxIterations=GetOption('maxiter',OPTIONS,DefaultOpt);
+MaxEvals=GetOption('maxfunevals',OPTIONS,DefaultOpt);
+InerciaInitial=GetOption('InerciaInitialWeight',OPTIONS,DefaultOpt);
+InerciaFinal=GetOption('InerciaFinalWeight',OPTIONS,DefaultOpt);
+Cognitial=GetOption('Cognitial',OPTIONS,DefaultOpt);
+Social=GetOption('Social',OPTIONS,DefaultOpt);
+
+% These are global options. Need to be available to subrotines.
+Problem.Verbose=~GetOption('silent', OPTIONS, DefaultOpt);
+Problem.IncreaseDelta=GetOption('DeltaIncreaseFactor',OPTIONS,DefaultOpt);
+Problem.DecreaseDelta=GetOption('DeltaDecreaseFactor',OPTIONS,DefaultOpt);
+Problem.Tolerance=GetOption('CPTolerance', OPTIONS, DefaultOpt);
+
+% Compute minimum delta for pattern search
+% The minimum delta available should be at least twice the Tolerance
+InitialDelta=min(Problem.UB-Problem.LB);
+InitialDelta = InitialDelta / GetOption('InitialDeltaFactor', ...
+    OPTIONS, DefaultOpt);
+if InitialDelta < 2*Problem.Tolerance
+    InitialDelta = 2*Problem.Tolerance;
+end
+
+
+% compute the maximum allowed velocity. High velocities will be "pushing"
+% particle to the border.
+MaxVelocityVect=(Problem.UB(1:Problem.Variables)-Problem.LB(1:Problem.Variables))*...
+    GetOption('MaxVelocityFactor',OPTIONS,DefaultOpt);
+
+disp('pswarmSB: In case of a publication that was prepared using the pswarm');
+disp('users are asked to cite the following publication:');
+disp('A. I. F. Vaz and L. N. Vicente, A particle swarm pattern search method');
+disp('for bound constrained global optimization, Journal of Global Optimization,');
+disp('39 (2007) 197-219.');
+
+if Problem.Verbose
+    disp(' Nr Iter    Nr Fun Eval         Min function');
+end
+
+
+% Initialize counters
+% Iteration counter
+Problem.Stats.IterCounter=0;
+% How many consecutive iterations without success (progress in the leader
+% particle).
+IterUnsuccess=0;
+% Maximum velcity among all perticles velocity
+MaxVelocity=+Inf;
+
+
+% Initialize statistics counters
+
+% Number of objective function calls. This is the number of calls to
+% Problem.ObjFunction. Since particle swarm relies in a infinite penalty
+% function strategy the penalty number of evaluation may be different.
+Problem.Stats.ObjFunCounter=0;
+
+% Number of Poll steps taken
+Problem.Stats.PollSteps=0;
+
+% How many poll step had success
+Problem.Stats.SuccPollSteps=0;
+
+% Keep track of what direction had success in the last poll step. The Delta
+% parameter is incremented only of a success occours twice in the same
+% direction.
+Problem.Poll.LastSuccess=[];
+
+
+% Generate initial population. Include initial population provided by user
+%  if available
+[Problem,Population]=InitPopulation(Problem, InitialPopulation, ...
+    GetOption('popsize', OPTIONS, DefaultOpt));
+
+% Delta for the pattern search.
+Population.Delta=InitialDelta;
+
+% Initialize patter search. Initialize the coordinate search directions.
+Problem=InitPatternSearch(Problem);
+
+% Main cycle of the algorithm
+% Run pattern search until no success is attained. Call for a poll step in
+% the leader particle whenever no success is recorded.
+
+% Stop if the maximum number of iterations or objective function
+% evaluations is reached.
+while(Problem.Stats.IterCounter<MaxIterations && Problem.Stats.ObjFunCounter<MaxEvals && stopOptimization == 0),
+
+    % Stop also if particle swarm velocity is bellow Tolerance and pattern
+    % search Delta is bellow Tolerance
+    if MaxVelocity<Problem.Tolerance && Population.Delta<Problem.Tolerance
+        disp('Stopping due to velocity and tolerance');
+        break;
+    end
+    
+    % Stop if the number of active particles is equal to 1 and pattern
+    % search Tolerance was attained.
+    if Population.ActiveParticles <=1 && Population.Delta<Problem.Tolerance
+        disp('Stopping due to single particle and tolerance');
+        break;
+    end
+    
+    % Increment iteration counter.    
+    Problem.Stats.IterCounter=Problem.Stats.IterCounter+1;
+
+    % No success iteration at begining
+    Success=false;
+    
+    % For all particles in the swarm
+    for i=1:Population.popsize
+        % If particle is active
+        if(Population.Active(i))
+            % Compute Objective function value
+            [Problem,ObjValue]=...
+                PenaltyEval(Problem, Population.x(i,:));
+            % Was progress attained for the current particle?
+            if Population.fy(i)>ObjValue
+                % Yes. Update best particle position
+                Population.fy(i)=ObjValue;
+                Population.y(i,:)=Population.x(i,:);
+                               
+                % Check if new leader is available
+                if Population.fy(Population.Leader)>Population.fy(i) || Population.Leader==i
+                    Population.Leader=i;
+                    % Particle swarm iteration declared as successful
+                    Success=true;
+                    % Reset last success direction for pattern search
+                    Problem.Poll.LastSuccess=[];
+                end
+            end
+        end
+    end
+    
+    % Successful iteration?
+    if ~Success
+        % No success in searh phase. Proceed to a poll step if possible.
+        if Population.Delta >= Problem.Tolerance
+            [Problem,Population]=PollStep(Problem,Population);
+            Problem.Stats.PollSteps=Problem.Stats.PollSteps+1;
+            % Reset on the number of unsuccessful iterations without a poll
+            % step
+            IterUnsuccess=0;
+        else
+            % An unsuccessful iteration without poll step
+            IterUnsuccess=IterUnsuccess+1;
+        end
+    else
+        % Success
+        IterUnsuccess=0;
+        % Leader changed.
+        % Increase Delta. Reset on the local search.
+        if Population.Delta<InitialDelta
+            Population.Delta=Population.Delta*Problem.IncreaseDelta;
+        end
+        % check for lower bounds
+        if Population.Delta<Problem.Tolerance
+            Population.Delta=2*Problem.Tolerance;
+        end
+    end
+    
+    
+    % Compute inercia.
+    Inercia = InerciaInitial - ...
+        (InerciaInitial-InerciaFinal)*Problem.Stats.IterCounter/MaxIterations;
+
+    % Update velocity and new particle positions
+    % For all particles
+    for i=1:Population.popsize
+        % Is active?
+        if Population.Active(i)
+            % Update velocity for real variables
+            Population.vx(i,:)=Projection(Inercia*Population.vx(i,:)+ ...
+                Cognitial*unifrndSB(0,ones(1,Problem.Variables)).*...
+                  (Population.y(i,:)-Population.x(i,:))+...
+                Social*unifrndSB(0,ones(1,Problem.Variables)).*...
+                  (Population.y(Population.Leader,:)-Population.x(i,:)),...
+                -MaxVelocityVect,MaxVelocityVect);
+            % Update particle position and check bound limits
+            Population.x(i,:)=Projection(Population.x(i,:)+Population.vx(i,:),...
+                Problem.LB(1:Problem.Variables), ...
+                Problem.UB(1:Problem.Variables));
+        end
+    end
+
+    % To compute population norm. Start with Leader.
+    MaxVelocity=norm(Population.x(Population.Leader));
+    
+    % Reset number of active particles.
+    Population.ActiveParticles=0;
+    for i=1:Population.popsize
+        % Check if particle is active and we do not want to remove the
+        % leader.
+        if Population.Active(i) && Population.Leader~=i
+            % compute particle velocity norm (for the stopping criteria.
+            VelocityNorm=norm(Population.vx(i,:));
+            Distance=norm(Population.x(i,:)-Population.x(Population.Leader,:));
+            if Distance<Population.Delta && VelocityNorm<Population.Delta
+                % Is neighbour
+                Population.Active(i)=false;
+            else
+                % Is integer, but not real neighbour
+                MaxVelocity=MaxVelocity+VelocityNorm;
+            end
+        end
+        % Account for active particles.
+        if Population.Active(i)
+            Population.ActiveParticles=Population.ActiveParticles+1;
+        end
+    end
+    
+    if Problem.Verbose,
+        disp(sprintf(' %5.0f        %5.0f           %12.6g            %s', Problem.Stats.IterCounter, Problem.Stats.ObjFunCounter, Population.fy(Population.Leader)));
+    end
+
+end
+
+
+% End of main cycle ...
+
+% print final time
+toc;
+
+% Print if it was stopped due to the maximum of iterations or objective
+% function evaluations
+if Problem.Stats.IterCounter>=MaxIterations || Problem.Stats.ObjFunCounter>=MaxEvals
+    disp('Maximum number of iterations or objective function evaluations reached');
+end
+
+if stopOptimization == 1,
+    disp('User Interrupt.');
+end
+
+% return leader position and objective function value
+BestParticle=[Population.y(Population.Leader,:)];
+BestParticleObj=Population.fy(Population.Leader);
+RunData=Problem.Stats;
+
+if Problem.Verbose
+    % display some statistics
+    disp(Problem.Stats);
+end
+X = BestParticle;
+FVAL = BestParticleObj;
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+% subrotine InitPopulation
+%    Randomly initialize the population
+%    Include initial guesses, if provided by the user
+%
+% Input:
+%   Problem - problem data
+%   InitialPopulation - Inicial population provided by user
+%   popsize - Requested size for the population
+%
+% Output:
+%   Problem - problem data (problem data may be update)
+%   Population - population data
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [Problem,Population]=InitPopulation(Problem, ...
+    InitialPopulation, popsize)
+% Check if user provides a valid initial population
+if ~isempty(InitialPopulation) && ~isstruct(InitialPopulation)
+    error('pswarm:InitPopulation:InitialPopulation', 'Initial population must be defined in a structure.');
+else
+    % Check for size
+    if length(InitialPopulation)>popsize
+        % User provided an initial population greater then the population
+        % size
+        if Problem.Verbose
+            fprintf('Initial population is greater then population size. Incresing population size from ');
+            fprintf(popsize);
+            fprintf(' to ');
+            fprintf(length(InitialPopulation));
+        end
+        % Population size is increased to fit the number of initial guesses
+        Population.popsize=length(InitialPopulation);
+    else
+        % Otherwise just accept the proposed population size
+        Population.popsize=popsize;
+    end 
+    % Copy the initial population for the population and initialize them
+    for i=1:length(InitialPopulation)
+        % Particle position.
+        Population.x(i,:)=Projection(InitialPopulation(i).x,...
+                Problem.LB(1:Problem.Variables), ...
+                Problem.UB(1:Problem.Variables));
+        % Best particle position.
+        Population.y(i,:)=Population.x(i,:);
+        % Particle velocities.
+        Population.vx(i,:)=zeros(1,Problem.Variables);
+        % Particle is active at begining
+        Population.Active(i)=true;
+        [Problem,Population.fy(i)]=...
+            PenaltyEval(Problem, Population.x(i,:));
+    end
+end
+% Ramdomly generate the remaining population
+for i=length(InitialPopulation)+1:Population.popsize
+    % Particle positions.
+    Population.x(i,:)=unifrndSB(Problem.LB(1:Problem.Variables),...
+        Problem.UB(1:Problem.Variables));
+    % Best particle position.
+    Population.y(i,:)=Population.x(i,:);
+    % Particle velocities
+    Population.vx(i,:)=zeros(1,Problem.Variables);
+    % Particle active or inactive
+    Population.Active(i)=true;
+    [Problem,Population.fy(i)]=...
+        PenaltyEval(Problem, Population.x(i,:));
+end
+Population.ActiveParticles=Population.popsize;
+Population.Leader=1;
+return;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%  subrotine GetOption
+%
+%  Input:
+%    Option - option to get the value
+%    OPTIONS - a list of options provided by user
+%    DefaultOpt -  a list of default options
+%
+%  Output:
+%    Value - The value specified by user for Option or the default
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [Value]=GetOption(Option, OPTIONS, DefaultOpt)
+% Check for user provided options
+if isempty(OPTIONS) || ~isstruct(OPTIONS)
+    % User does not provides OPTIONS
+    Value=DefaultOpt.(Option);
+    return;
+end
+% Try the option provided by user
+try
+    Value=OPTIONS.(Option);
+catch
+    Value=[];
+end
+% Option not provided by user
+if isempty(Value)
+    Value=DefaultOpt.(Option);    
+end
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/simannealingSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/simannealingSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..31775a6dc1c98c5eeebb364a0b2d13647cebc03c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/simannealingSB.m
@@ -0,0 +1,449 @@
+function [X,FVAL,EXITFLAG] = simannealingSB(varargin)
+% simannealingSB: Minimization by simulated annealing. Algorithm partly 
+% based on section 10.4 in "Numerical Recipes in C", ISBN 0-521-43108-5.
+% The implementation of this simmulated annealing method uses a nonlinear
+% simplex search as basis. The algorithm has been modified in order to be
+% able to take into account simple box constraints on parameter values.
+%
+% If global variable stopOptimization is set to 1, the optimization is
+% stopped. This allows for stopping parameter estimation functions on user
+% request. 
+% 
+% USAGE:
+% ======
+% [info] = simannealingSB()
+% [X,FVAL,EXITFLAG] = simannealingSB(FUN,X,OPTIONS)
+%
+% FUN: Function to optimize
+% X: Starting Guess
+% OPTIONS: structure containing options for the algorithm:
+%        OPTIONS.tempstart: Starting temperature (should be around the
+%           order of magnitude (or higher) than the cost function at the
+%           initial guess)
+%        OPTIONS.tempend: Ending temperature (When performed all iterations
+%           for this temperature, the temperature is set to 0 and the
+%           simannealingSBAO function converges to a normal simplex search)
+%        OPTIONS.tempfactor: Reduction factor for temperature after running
+%           through all iterations for current temperature
+%        OPTIONS.maxitertemp: Number of iterations to carry put for each
+%           non-zero temperature
+%        OPTIONS.maxitertemp0: Number of iterations to carry out for 0
+%           temperature
+%        OPTIONS.maxtime: Maximum time (in minutes) for optimization
+%        OPTIONS.tolx: Tolerance for max difference between the coordinates
+%           of the vertices.
+%        OPTIONS.tolfun: Tolerance for difference between best and worst
+%           function evaluation in simplex
+%        OPTIONS.highbounds: vector containing upper bounds for parameters
+%           Instead of a vector highbounds can also be a scalar > 1. In the
+%           latter case the highbounds are determined by multiplying this
+%           scalar to the initial parameter guess X. This latter case works
+%           only for positive X(i) ... if negative present then the user
+%           needs to specify a whole highbounds vector. 
+%        OPTIONS.lowbounds: vector containing lower bounds for parameters.
+%           Instead of a vector lowbounds can also be a scalar < 1. In the
+%           latter case the lowbounds are determined by multiplying this
+%           scalar to the initial parameter guess X. This latter case works
+%           only for positive X(i) ... if negative present then the user
+%           needs to specify a whole lowbounds vector. 
+%        OPTIONS.outputFunction: string with output function name. If
+%           not given or if empty then no output function will be used.
+%           This output function can be used to display data, or to 
+%           save optimization information to a file. The function needs
+%           to be in the MATLAB path. Its calling syntax is:
+%                   'outputFunction'(bestparameters,bestfunctionvalue,currentsimplex)
+%        OPTIONS.silent: =0: output of info, =1: no output
+%
+% DEFAULT VALUES:
+% ===============
+% OPTIONS.tempstart = 10*magnitude of function value at initial guess
+% OPTIONS.tempend = 0.1
+% OPTIONS.tempfactor = chosen such that 10 reductions of temperature
+% OPTIONS.maxitertemp = 50*numberVariables
+% OPTIONS.maxitertemp0 = 200*numberVariables
+% OPTIONS.maxtime = 120
+% OPTIONS.tolx = 1e-10
+% OPTIONS.tolfun = 1e-10
+% OPTIONS.lowbounds:    0.1  => lowbounds = 0.1*X 
+% OPTIONS.highbounds:    10  => highbounds = 10*X 
+% OPTIONS.outputFunction: no output function ('')
+% OPTIONS.silent:         0 (no output of info)
+%
+% Output Arguments:
+% =================
+% info: calling the function w/o input argument returns information about
+%       the options and a flag indicating if the algorithm can handle
+%       constraints or not
+% X: Found solution
+% FVAL: Value of the function FUN at X
+% EXITFLAG: 1=success, 0=not found
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GLOBAL VARIABLES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+global ndim nfunk Xguess lowbounds highbounds Temp ybest pbest tempstart stopOptimization
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 0,
+    X = [];
+    X.name = 'simannealingSB';
+    X.constrained = 1;
+    X.description = 'Simulated annealing based on Nelder-Mead (global)';       
+    X.defaultOptions.names = {'tempstart','tempend','tempfactor','maxitertemp', 'maxitertemp0', 'maxtime'};
+    X.defaultOptions.values = {'1000','0.1','0.2','1000','1000','500'};
+    X.defaultOptions.description = {'Starting temperature', 'Ending temperature before assuming T=0', 'Reduction factor for temperature', 'Number of iterations if T~=0', 'Number of iterations if T==0','Maximum time in minutes'};
+    FVAL = [];
+    EXITFLAG = [];
+    return
+elseif nargin == 2,
+    FUN = varargin{1};
+    X = varargin{2};
+    OPTIONS = [];
+elseif nargin == 3,
+    FUN = varargin{1};
+    X = varargin{2};
+    OPTIONS = varargin{3};
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Set default values
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+EXITFLAG = 1;
+ndim = length(X);
+tempstart = -1;     % default value calculation later
+tempend = 0.1;
+tempfactor = -1;    % default value calculation later
+maxitertemp = 50*ndim;
+maxitertemp0 = 200*ndim;
+maxtime = 120;
+tolx = 1e-10;
+tolfun = 1e-10;
+lowbounds = 0.1*X;
+highbounds = 10*X;
+outputFunction = '';
+silent = 0;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE OPTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% silent
+if isfield(OPTIONS,'silent'),
+    if ~isempty(OPTIONS.silent),
+        silent = OPTIONS.silent;
+    end
+end
+% tolfun
+if isfield(OPTIONS,'tolfun'),
+    if ~isempty(OPTIONS.tolfun),
+        tolfun = OPTIONS.tolfun;
+    end
+end
+% tolx
+if isfield(OPTIONS,'tolx'),
+    if ~isempty(OPTIONS.tolx),
+        tolx = OPTIONS.tolx;
+    end
+end
+% maxtime
+if isfield(OPTIONS,'maxtime'),
+    if ~isempty(OPTIONS.maxtime),
+        maxtime = OPTIONS.maxtime;
+    end
+end
+% maxitertemp0
+if isfield(OPTIONS,'maxitertemp0'),
+    if ~isempty(OPTIONS.maxitertemp0),
+        maxitertemp0 = OPTIONS.maxitertemp0;
+    end
+end
+% maxitertemp
+if isfield(OPTIONS,'maxitertemp'),
+    if ~isempty(OPTIONS.maxitertemp),
+        maxitertemp = OPTIONS.maxitertemp;
+    end
+end
+% tempfactor
+if isfield(OPTIONS,'tempfactor'),
+    if ~isempty(OPTIONS.tempfactor),
+        tempfactor = OPTIONS.tempfactor;
+    end
+end
+% tempend
+if isfield(OPTIONS,'tempend'),
+    if ~isempty(OPTIONS.tempend),
+        tempend = OPTIONS.tempend;
+    end
+end
+% tempstart
+if isfield(OPTIONS,'tempstart'),
+    if ~isempty(OPTIONS.tempstart),
+        tempstart = OPTIONS.tempstart;
+    end
+end
+% outputFunction
+outputFunction = '';
+if isfield(OPTIONS,'outputFunction'),
+    if ~isempty(OPTIONS.outputFunction),
+        outputFunction = OPTIONS.outputFunction;
+    end
+end
+% low and highbounds:
+[lowbounds, highbounds] = handleLowHighBoundsSB(OPTIONS,X,lowbounds,highbounds);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INITIALIZE EMPTY SIMPLEX DATA
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+p = zeros(ndim+1,ndim);     % vertice vectors in rows
+y = zeros(ndim+1,1);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% EVALUATE FUNCTION IN INITIAL GUESS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ybest = inf;
+pbest = X(:)';
+ybest = costFunction(FUN,pbest);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% DETERMINE START TEMP AND TEMPFACTOR (if not given by the user)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if tempstart < 0,
+    % tempstart not given by the user => determine here a default value
+    tempstart = 10*abs(ybest);
+end
+if tempfactor < 0,
+    % tempfactor not given by the user => determine here a default value
+    tempfactor = (tempstart/tempend)^(-1/9);
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% TEMPERATURE LOOP - STARTING FROM BEST POINT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+Temp = tempstart;
+tic % start timer
+nfunk = 1;
+nriterations = 0;
+while(1),
+    if Temp < tempend,
+        Temp = 0;
+        MAXITERTEMP = maxitertemp0;
+    else 
+        MAXITERTEMP = maxitertemp;
+    end
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % FIRST POINT OF INITIAL SIMPLEX
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    if ~silent,
+        disp(sprintf(' Current best estimation: [%s]',sprintf('%g ', pbest)));
+    end
+    Xguess = pbest;
+    p(1,:) = Xguess;
+    y(1) = costFunction(FUN,Xguess);
+    if ~silent,
+        disp(' Nr Iter  Nr Fun Eval    Min function       Best function       Temp      Algorithm Step');
+        if Temp == tempstart,
+            disp(sprintf(' %5.0f   %5.0f       %12.6g       %12.6g   %12.6g       %s', nriterations, nfunk, y(1), ybest, Temp, 'initial guess'));
+        else
+            disp(sprintf(' %5.0f   %5.0f       %12.6g       %12.6g   %12.6g       %s', nriterations, nfunk, y(1), ybest, Temp, 'best point'));
+        end
+    end
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % REMAINING POINTS OF INITIAL SIMPLEX
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % construct vertices by modifying one element each
+    % relative changes in case that elements are non-zero,
+    % absolute changes in case that elements are zero
+    relativeDelta = 0.25;
+    absoluteDelta = 0.5;
+    for k = 1:ndim
+        Xmodify = Xguess;
+        if Xmodify(k) == 0
+            % absolute change
+            if highbounds(k) > absoluteDelta,
+                Xmodify(k) = absoluteDelta;
+            else 
+                Xmodify(k) = -absoluteDelta;
+            end
+        else
+            % relative change
+            Xmodify(k) = (1 + relativeDelta)*Xmodify(k);
+        end
+        p(k+1,:) = Xmodify;
+        y(k+1) = costFunction(FUN,Xmodify);
+    end
+    algostep = 'initial simplex';
+    nriterations = nriterations + 1;
+    nfunk = nfunk + ndim + 1;
+    
+    % if output function given then run output function to plot
+    % intermediate result
+    if length(outputFunction) ~= 0,
+        feval(outputFunction,p(1,:), y(1),p);
+    end
+    
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % MAIN ALGORITHM
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % reorder y and p so that the first row corresponds to the
+    % lowest function value
+    for itertemp = 1:MAXITERTEMP,
+        % add random thermal fluctuations
+        yfluct = y + Temp*abs(log(rand(ndim+1,1)));
+        % do sorting instead of determining the indices of the best, worst,
+        % next worst
+        help = sortrows([yfluct,y,p],1);
+        yfluct = help(:,1);
+        y = help(:,2);
+        p = help(:,3:end);
+        if ~silent,
+            disp(sprintf(' %5.0f   %5.0f       %12.6g       %12.6g   %12.6g       %s', nriterations, nfunk, y(1), ybest, Temp, algostep));
+        end
+        % if output function given then run output function to plot
+        % intermediate result
+        if length(outputFunction) ~= 0,
+            feval(outputFunction,p(1,:), y(1),p);
+        end
+        % end the optimization if the difference between best and worst
+        % function evaluation in simplex is smaller than tolfun and the
+        % max difference between the coordinates of the verttices is less than
+        % tolx
+        if abs(max(y)-min(y)) < tolfun && max(max(abs(p(2:ndim+1)-p(1:ndim)))) < tolx,
+            break;
+        end
+        % check number of iterations
+        if toc/60 > maxtime,
+            EXITFLAG = 0;
+            disp('Exceeded maximum time.');
+            break;
+        end
+        if stopOptimization == 1,
+            disp('User Interrupt.');
+            break;
+        end
+        % Begin a new iteration. First extrapolate by a factor -1 through the face of the simplex
+        % across from the high point, i.e., reflect the simplex from the high point.
+        [yftry, ytry,ptry] = amotry(FUN, p, -1);
+        % check the result
+        if yftry <= yfluct(1),
+            % Gives a result better than the best point, so try an additional
+            % extrapolation by a factor 2.
+            [yftryexp, ytryexp,ptryexp] = amotry(FUN, p, -2);
+            if yftryexp < yftry,
+                p(end,:) = ptryexp;
+                y(end) = ytryexp;
+                algostep = 'extrapolation';
+            else
+                p(end,:) = ptry;
+                y(end) = ytry;
+                algostep = 'reflection';
+            end
+        elseif yftry >= yfluct(ndim),
+            % The reflected point is worse than the second-highest, so look
+            % for an intermediate lower point, i.e., do a one-dimensional
+            % contraction.
+            [yftrycontr,ytrycontr,ptrycontr] = amotry(FUN, p, -0.5);
+            if yftrycontr < yfluct(end),
+                p(end,:) = ptrycontr;
+                y(end) = ytrycontr;
+                algostep = 'one dimensional contraction';
+            else
+                % Can�t seem to get rid of that high point. Better contract
+                % around the lowest (best) point.
+                x = ones(ndim,ndim)*diag(p(1,:));
+                p(2:end,:) = 0.5*(p(2:end,:)+x);
+                for k=2:ndim,
+                    y(k) = costFunction(FUN,p(k,:));
+                end
+                algostep = 'contraction around best point';
+            end
+        else
+            % if ytry better than second-highest point then use this point
+            p(end,:) = ptry;
+            y(end) = ytry;
+            algostep = 'reflection';
+        end
+        nriterations = nriterations + 1;
+    end
+    % Break because of max number iterations, max time, minimum found
+    % (tolerances)
+    if itertemp < MAXITERTEMP,
+        break;
+    end
+    Temp = Temp*tempfactor;
+    % Break because 0 temperature has been run
+    if Temp == 0,
+        break;
+    end
+end
+X = pbest;
+FVAL = ybest;
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% AMOTRY FUNCTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [yftry,ytry,ptry] = amotry(FUN, p, fac)
+% Extrapolates by a factor fac through the face of the simplex across from 
+% the high point, tries it, and replaces the high point if the new point is 
+% better.
+global ndim nfunk Temp lowbounds highbounds tempstart
+psum = sum(p(1:ndim,:))/ndim;
+ptry = psum*(1-fac) + p(end,:)*fac;
+
+% Deal with low and high parameter bounds
+indexXhi = find(ptry > highbounds);
+indexXlo = find(ptry < lowbounds);
+for k=1:length(indexXhi),
+    ptry(indexXhi(k)) = highbounds(indexXhi(k))-rand(1)*(highbounds(indexXhi(k))-lowbounds(indexXhi(k)))*Temp/tempstart;
+end
+for k=1:length(indexXlo),
+    ptry(indexXlo(k)) = lowbounds(indexXlo(k))+rand(1)*(highbounds(indexXlo(k))-lowbounds(indexXlo(k)))*Temp/tempstart;
+end
+
+% Evaluate the function at the trial point.
+ytry = costFunction(FUN,ptry);
+yftry = ytry - Temp*abs(log(rand(1)));
+nfunk = nfunk + 1;
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% COST FUNCTION EVALUATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [ytry] = costFunction(FUN,ptry)
+global ybest pbest lowbounds highbounds
+ytry = feval(FUN,ptry);
+% save the best point ever (only if it is feasible, that is it fits the
+% high and low bounds)
+indexXhi = find(ptry > highbounds);
+indexXlo = find(ptry < lowbounds);
+if ytry < ybest && isempty(indexXhi) && isempty(indexXlo),
+    ybest = ytry;
+    pbest = ptry;
+end    
+return
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/simplexSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/simplexSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..89e6d4d70644e51839acfbaca0485d5442b3b9e0
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/optimization/simplexSB.m
@@ -0,0 +1,412 @@
+function [X,FVAL,EXITFLAG] = simplexSB(varargin)
+% simplexSB: Downhill Simplex Method in Multidimensions. Algorithm based on
+% section 10.4 in "Numerical Recipes in C", ISBN 0-521-43108-5.
+% The algorithm has been modified in order to be able to take into account
+% simple box constraints on parameter values. 
+%
+% If global variable stopOptimization is set to 1, the optimization is
+% stopped. This allows for stopping parameter estimation functions on user
+% request. 
+% 
+% USAGE:
+% ======
+% [info] = simplexSB()
+% [X,FVAL,EXITFLAG] = simplexSB(FUN,X,OPTIONS)
+%
+% FUN: Function to optimize
+% X: Starting Guess
+% OPTIONS: structure containing options for the algorithm:
+%        OPTIONS.maxfunevals: Maximum number of function evaluations
+%        OPTIONS.maxiter: Maximum number of iterations
+%        OPTIONS.maxtime: Maximum time (in minutes) for optimization
+%        OPTIONS.tolfun: Tolerance for difference between best and worst
+%                        function evaluation in simplex
+%        OPTIONS.tolx: Tolerance for max difference between the coordinates of
+%                      the vertices.
+%        OPTIONS.highbounds: vector containing upper bounds for parameters
+%           Instead of a vector highbounds can also be a scalar > 1. In the
+%           latter case the highbounds are determined by multiplying this
+%           scalar to the initial parameter guess X. This latter case works
+%           only for positive X(i) ... if negative present then the user
+%           needs to specify a whole highbounds vector. 
+%           If argument is empty ([]) then highbounds are set to +Inf;
+%        OPTIONS.lowbounds: vector containing lower bounds for parameters.
+%           Instead of a vector lowbounds can also be a scalar < 1. In the
+%           latter case the lowbounds are determined by multiplying this
+%           scalar to the initial parameter guess X. This latter case works
+%           only for positive X(i) ... if negative present then the user
+%           needs to specify a whole lowbounds vector. 
+%           If argument is empty ([]) then lowbounds are set to -Inf;
+%        OPTIONS.outputFunction: string with output function name. If
+%               not given or if empty then no output function will be used.
+%               This output function can be used to display data, or to 
+%               save optimization information to a file. The function needs
+%               to be in the MATLAB path. Its calling syntax is:
+%                   'outputFunction'(bestparameters,bestfunctionvalue,currentsimplex)
+%        OPTIONS.silent: =0: output of info, =1: no output
+%
+% DEFAULT VALUES:
+% ===============
+% OPTIONS.maxfunevals:    200*numberVariables
+% OPTIONS.maxiter:        200*numberVariables
+% OPTIONS.maxtime:        120
+% OPTIONS.tolx:           1e-10
+% OPTIONS.tolfun:         1e-10
+% OPTIONS.lowbounds:      1e-3  => lowbounds = 1e-3*X 
+% OPTIONS.highbounds:     1e3   => highbounds = 1e3*X 
+% OPTIONS.outputFunction: no output function ('')
+% OPTIONS.silent:         0 (no output of info)
+%
+% Output Arguments:
+% =================
+% info: calling the function w/o input argument returns information about
+%       the options and a flag indicating if the algorithm can handle
+%       constraints or not
+% X: Found solution
+% FVAL: Value of the function FUN at X
+% EXITFLAG: 1=success, 0=not found
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GLOBAL VARIABLES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+global ndim nfunk Xguess lowbounds highbounds stopOptimization
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% VARIABLE INPUT ARGUMENTS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+if nargin == 0,
+    X = [];
+    X.name = 'simplexSB';
+    X.constrained = 1;
+    X.description = 'Nelder-Mead nonlinear simplex (local)';    
+    X.defaultOptions.names = {'maxfunevals', 'maxiter', 'tolfun', 'tolx'};
+    X.defaultOptions.values = {'50000','20000','1e-10','1e-10'};
+    X.defaultOptions.description = {'Maximum number of function evaluations', 'Maximum number of iterations', 'Termination tolerance on the function value', 'Termination tolerance on X'};
+    FVAL = [];
+    EXITFLAG = [];
+    return
+elseif nargin == 2,
+    FUN = varargin{1};
+    X = varargin{2};
+    OPTIONS = [];
+elseif nargin == 3,
+    FUN = varargin{1};
+    X = varargin{2};
+    OPTIONS = varargin{3};
+else
+    error('Incorrect number of input arguments.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Set default values
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+EXITFLAG = 1;
+ndim = length(X);
+maxfunevals = 200*ndim;
+maxiter = 200*ndim;
+maxtime = 120;
+tolx = 1e-10;
+tolfun = 1e-10;
+outputFunction = '';
+lowbounds = 1e-3*X;
+highbounds = 1e3*X;
+silent = 0;
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Handle OPTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% silent
+if isfield(OPTIONS,'silent'),
+    if ~isempty(OPTIONS.silent),
+        silent = OPTIONS.silent;
+    end
+end
+% tolfun
+if isfield(OPTIONS,'tolfun'),
+    if ~isempty(OPTIONS.tolfun),
+        tolfun = OPTIONS.tolfun;
+    end
+end
+% tolx
+if isfield(OPTIONS,'tolx'),
+    if ~isempty(OPTIONS.tolx),
+        tolx = OPTIONS.tolx;
+    end
+end
+% maxiter
+if isfield(OPTIONS,'maxtime'),
+    if ~isempty(OPTIONS.maxtime),
+        maxtime = OPTIONS.maxtime;
+    end
+end
+% maxiter
+if isfield(OPTIONS,'maxiter'),
+    if ~isempty(OPTIONS.maxiter),
+        maxiter = OPTIONS.maxiter;
+    end
+end
+% maxfunevals
+if isfield(OPTIONS,'maxfunevals'),
+    if ~isempty(OPTIONS.maxfunevals),
+        maxfunevals = OPTIONS.maxfunevals;
+    end
+end
+% outputFunction
+outputFunction = '';
+if isfield(OPTIONS,'outputFunction'),
+    if ~isempty(OPTIONS.outputFunction),
+        outputFunction = OPTIONS.outputFunction;
+    end
+end
+% low and highbounds:
+[lowbounds, highbounds] = handleLowHighBoundsSB(OPTIONS,X,lowbounds,highbounds);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% INITIALIZE EMPTY SIMPLEX DATA
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+p = zeros(ndim+1,ndim);     % vertice vectors in rows
+y = zeros(ndim+1,1);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% FIRST POINT OF INITIAL SIMPLEX
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+Xguess = X(:)'; 
+p(1,:) = Xguess;    
+y(1) = feval(FUN,Xguess);
+
+if ~silent,
+    disp(' Nr Iter    Nr Fun Eval         Min function          Algorithm Step');
+    disp(sprintf(' %5.0f        %5.0f           %12.6g            %s', 0, 1, y(1), 'initial guess'));
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% RESTART MODIFICATION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+finished = 0;
+ndimmult = 20;  % factor for ndim to get the number of iterations to do until restart (adapted later)
+OLDmeanimprovement = 1/eps;
+nriterations = 1;
+nfunk = ndim+1;
+
+while ~finished,
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % REMAINING POINTS OF INITIAL SIMPLEX
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % construct vertices by modifying one element each
+    % relative changes in case that elements are non-zero,
+    % absolute changes in case that elements are zero
+    relativeDelta = 0.05;
+    absoluteDelta = 0.00025;
+    for k = 1:ndim
+        Xmodify = p(1,:);
+        if Xmodify(k) == 0
+            % absolute change
+            if highbounds(k) > absoluteDelta,
+                Xmodify(k) = absoluteDelta;
+            else
+                Xmodify(k) = -absoluteDelta;
+            end
+        else
+            % relative change
+            Xmodify(k) = (1 + relativeDelta)*Xmodify(k);
+        end
+        p(k+1,:) = Xmodify;
+        y(k+1) = feval(FUN,Xmodify);
+    end
+    algostep = 'initial simplex';
+
+    % if output function given then run output function to plot
+    % intermediate result
+    if ~isempty(outputFunction),
+        feval(outputFunction,p(1,:), y(1),p);
+    end
+
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % MAIN ALGORITHM
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % reorder y and p so that the first row corresponds to the
+    % lowest function value
+    tic % start timer
+counter = 1;    
+fvalues_history = [];    
+    while(1),
+        % do sorting instead of determining the indices of the best, worst,
+        % next worst
+        help = sortrows([y,p],1);
+        y = help(:,1);
+        p = help(:,2:end);
+        if ~silent,
+            disp(sprintf(' %5.0f        %5.0f           %12.6g            %s', nriterations, nfunk, y(1), algostep));
+        end
+        
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE THE RESTART OF THE SIMPLEX
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% collect information about the improvement in the last 2*ndim iterations
+fvalues_history(end+1) = y(1);
+if counter > ndimmult*ndim,
+    meanimprovement = mean(fvalues_history(end-2*ndim:end-1)-fvalues_history(end-2*ndim+1:end));
+    if OLDmeanimprovement-100*eps(OLDmeanimprovement) >= meanimprovement,
+        ndimmult = ndimmult*1.5;
+%        disp('Restart later')
+    else
+        ndimmul = ndimmult*0.9;
+%        disp('Restart earlier');
+    end   
+    OLDmeanimprovement = meanimprovement;
+    finished = 0; % make a restart at current optimum
+    break;
+end
+counter = counter + 1;
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% HANDLE THE RESTART OF THE SIMPLEX - END
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+        
+        % if output function given then run output function to plot
+        % intermediate result
+        if ~isempty(outputFunction),
+            feval(outputFunction,p(1,:), y(1),p);
+        end
+        % end the optimization if the difference between best and worst
+        % function evaluation in simplex is smaller than tolfun and the
+        % max difference between the coordinates of the verttices is less than
+        % tolx
+        if abs(y(end)-y(1)) < tolfun && max(max(abs(p(2:ndim+1)-p(1:ndim)))) < tolx,
+            finished = 1; % exit also the restart loop
+            break;
+        end
+        % check number of function evaluations
+        if nfunk >= maxfunevals,
+            EXITFLAG = 0;
+            if ~silent,
+                disp('Exceeded maximum number of function evaluations.');
+            end
+            finished = 1; % exit also the restart loop
+            break;
+        end
+        % check number of iterations
+        if nriterations >= maxiter,
+            EXITFLAG = 0;
+            if ~silent,
+                disp('Exceeded maximum number of iterations.');
+            end
+            finished = 1; % exit also the restart loop
+            break;
+        end
+        if toc/60 > maxtime,
+            EXITFLAG = 0;
+            if ~silent,
+                disp('Exceeded maximum time.');
+            end
+            finished = 1; % exit also the restart loop
+            break;
+        end
+        if stopOptimization == 1,
+            EXITFLAG = 0;
+            disp('User Interrupt.');
+            finished = 1; % exit also the restart loop
+            break;
+        end
+        % Begin a new iteration. First extrapolate by a factor -1 through the face of the simplex
+        % across from the high point, i.e., reflect the simplex from the high point.
+        [ytry,ptry] = amotry(FUN, p, y, -1);
+        % check the result
+        if ytry <= y(1),
+            % Gives a result better than the best point, so try an additional
+            % extrapolation by a factor 2.
+            [ytryexp,ptryexp] = amotry(FUN, p, y, -2);
+            if ytryexp < ytry,
+                p(end,:) = ptryexp;
+                y(end) = ytryexp;
+                algostep = 'extrapolation';
+            else
+                p(end,:) = ptry;
+                y(end) = ytry;
+                algostep = 'reflection';
+            end
+        elseif ytry >= y(ndim),
+            % The reflected point is worse than the second-highest, so look
+            % for an intermediate lower point, i.e., do a one-dimensional
+            % contraction.
+            [ytrycontr,ptrycontr] = amotry(FUN, p, y, -0.5);
+            if ytrycontr < y(end),
+                p(end,:) = ptrycontr;
+                y(end) = ytrycontr;
+                algostep = 'one dimensional contraction';
+            else
+                % Can�t seem to get rid of that high point. Better contract
+                % around the lowest (best) point.
+                x = ones(ndim,ndim)*diag(p(1,:));
+                p(2:end,:) = 0.5*(p(2:end,:)+x);
+                for k=2:ndim,
+                    y(k) = feval(FUN,p(k,:));
+                    nfunk = nfunk+1;
+                end
+                algostep = 'contraction around best point';
+            end
+        else
+            % if ytry better than second-highest point then use this point
+            p(end,:) = ptry;
+            y(end) = ytry;
+            algostep = 'reflection';
+        end
+        nriterations = nriterations + 1;
+    end
+    % do the sorting a last time
+    help = sortrows([y,p],1);
+    y = help(:,1);
+    p = help(:,2:end);
+end
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% RESTART MODIFICATION END
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+X = p(1,:);
+FVAL = y(1);
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% AMOTRY FUNCTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [ytry,ptry] = amotry(FUN, p, y, fac)
+% Extrapolates by a factor fac through the face of the simplex across from 
+% the high point, tries it, and replaces the high point if the new point is 
+% better.
+global ndim nfunk lowbounds highbounds
+psum = sum(p(1:ndim,:))/ndim;
+ptry = psum*(1-fac) + p(end,:)*fac;
+
+% Deal with low and high parameter bounds
+indexXhi = find(ptry > highbounds);
+indexXlo = find(ptry < lowbounds);
+ptry(indexXhi) = highbounds(indexXhi);
+ptry(indexXlo) = lowbounds(indexXlo);
+
+% Evaluate the function at the trial point.
+ytry = feval(FUN,ptry);
+nfunk = nfunk + 1;
+return
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/solvers/fsolveSB.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/solvers/fsolveSB.m
new file mode 100644
index 0000000000000000000000000000000000000000..db2ffca5faed035635405ed5c532bb2f88940c4e
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SBTOOLBOX2/tools/solvers/fsolveSB.m
@@ -0,0 +1,120 @@
+function [X,FVAL,EXITFLAG] = fsolveSB(FUN,X,varargin)
+% fsolveSB: attempts to solve equations of the form FUN(X)=0    
+% where FUN and X may be vectors. Newton iteration.
+% 
+% USAGE:
+% ======
+% [X,FVAL,EXITFLAG] = fsolveSB(FUN,X)
+% [X,FVAL,EXITFLAG] = fsolveSB(FUN,X,OPTIONS)
+%
+% FUN: Sunction to minimize/solve
+% X: Starting Guess
+% OPTIONS: structure containing options 
+%          OPTIONS.MaxIter: Maximum number of iterations
+%          OPTIONS.TolFun:  Tolerance for max element in function evaluation
+%          OPTIONS.Delta:   Step length for numerical differentiation to 
+%                           obtain the Jacobian
+%
+% DEFAULT VALUES:
+% ===============
+% OPTIONS.MaxIter: 1000
+% OPTIONS.TolFun: 1e-11
+% OPTIONS.Delta: 1e-8
+%
+% Output Arguments:
+% =================
+% X: Found solution
+% FVAL: Value of the equations FUN at X
+% EXITFLAG: 1=success, 0=not found
+
+% Information:
+% ============
+% Copyright (C) 2005-2007 Fraunhofer Chalmers Centre, Gothenburg, Sweden
+% Main author: Henning Schmidt
+% 
+% Changes for the SBTOOLBOX2:
+% 1/1/2008  Henning Schmidt, henning@sbtoolbox2.org
+%
+% This program is free software; you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation; either version 2 of the License, or
+% (at your option) any later version.
+% 
+% This program is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+% 
+% You should have received a copy of the GNU General Public License
+% along with this program; if not, write to the Free Software
+% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
+% USA.
+
+
+MaxIter = 1000;
+TolFun = 1e-11; 
+Delta = 1e-8;
+
+% Handle OPTIONS if given
+if nargin == 3,
+    OPTIONS = varargin{1};
+    % TolFun
+    if isfield(OPTIONS,'TolFun'),
+        if ~isempty(OPTIONS.TolFun),
+            TolFun = OPTIONS.TolFun;
+        end
+    end
+    % MaxIter
+    if isfield(OPTIONS,'MaxIter'),
+        if ~isempty(OPTIONS.MaxIter),
+            MaxIter = OPTIONS.MaxIter;
+        end
+    end
+    % Delta
+    if isfield(OPTIONS,'Delta'),
+        if ~isempty(OPTIONS.Delta),
+            Delta = OPTIONS.Delta;
+        end
+    end
+end
+
+EXITFLAG = 0;
+for k = 1:MaxIter,
+    FVAL = feval(FUN,X);
+    Jacobian = getJacobian(FUN,X,Delta);
+    X = X - 0.5*pinv(Jacobian)*FVAL;
+    if norm(FVAL) < TolFun,
+        EXITFLAG = 1;
+        break
+    end
+end
+
+if nargout < 3 && EXITFLAG == 0,
+    disp('SBsteadystate/fsolveSB: Exceeded maximum number of iterations - check options');
+    disp(sprintf('Last residual: %g',max(abs(FVAL))));
+end
+return
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% GET JACOBIAN AT GIVEN STATE
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [Jacobian] = getJacobian(FUN,X,DELTA)
+% size of system
+n = length(X);          
+% initialize jacobian variable
+Jacobian = zeros(n,n);  
+% determine the Jacobian by numerical differentiation
+for k = 1:n,                
+    Xup = X;
+    Xup(k) = Xup(k)+DELTA;
+    Jacobian(:,k) = (FUN(Xup)'-FUN(X)')/DELTA;
+end
+return
+
+
+
+
+
+
+
+
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/SETUP_PATHS_TOOLS.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/SETUP_PATHS_TOOLS.m
new file mode 100644
index 0000000000000000000000000000000000000000..43ddb9b45bdcdd5a1e2a6f1fa72a15a5e813c24d
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/SETUP_PATHS_TOOLS.m
@@ -0,0 +1,25 @@
+% In this file you need to provide the names and potentially the paths to
+% the executables for tools, such as NONMEM, MONOLIX, SAS, etc.
+% If executables in the system
+% path, then only the names of the executables are needed.
+%
+% It is possible to define paths for Windows and Unix independently,
+% allowing to use the package on different systems without the need to
+% re-edit the paths. If a tool is not available on a system, then just
+% leave the path empty.
+
+% NONMEM (currently tested version: 7.2)
+PATH_SYSTEM_NONMEM_WINDOWS          = '';
+PATH_SYSTEM_NONMEM_UNIX             = 'nmfe72';
+
+% NONMEM PARALLEL
+PATH_SYSTEM_NONMEM_PARALLEL_WINDOWS = '';
+PATH_SYSTEM_NONMEM_PARALLEL_UNIX    = 'nmfe72par';
+
+% MONOLIX STANDALONE (tested versions 4.2.0-4.3.2)
+PATH_SYSTEM_MONOLIX_WINDOWS         = 'C:\LOCAL\Monolix\Monolix432s\bin\Monolix.bat';
+PATH_SYSTEM_MONOLIX_UNIX            = '/CHBS/apps/dev_apps/Monolix/4.3.2/Standalone/Monolix432grid-Matlab2008/bin/Monolix.sh';
+
+% SAS
+PATH_SYSTEM_SAS_WINDOWS             = '';
+PATH_SYSTEM_SAS_UNIX                = 'sas-9.4';
\ No newline at end of file
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/installSBPOPpackage.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/installSBPOPpackage.m
new file mode 100644
index 0000000000000000000000000000000000000000..586420c7c4ab8de7660a4cc1b32a9ebad4577dc6
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/installSBPOPpackage.m
@@ -0,0 +1,89 @@
+function [] = installSBPOPpackage(varargin)
+% installSBPOPpackage
+% Installation function for the complete SBPOP package, including all
+% additionally needed software. Note that this function needs to be run
+% from the folder in which the function is located.
+%
+%       installSBPOPpackage
+%
+% This adds the complete SBPOP package and all subpackages and subdirectories 
+% to the MATLAB path. If you are in a computer environment in which MATLAB
+% is not able to store the path settings you can run this 
+% installation function each time when starting MATLAB (ideally add the call
+% to your startup.m script in the homefolder).
+
+% Information:
+% ============
+% Copyright (c) 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+clc
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check that installSBPOPpackage is started in the right folder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+currentDir = pwd;
+installSBPOPDir = fileparts(which('installSBPOPpackage.m'));
+if ~strcmp(currentDir,installSBPOPDir),
+    error('Run the ''installSBPOPpackage'' script from the folder where it is located.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add folders to path
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+addpath(genpath(pwd));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add temp folder path
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+addpath(tempdirSB);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Show all versions used
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ver
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Final installation information, version, etc.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+disp(' ');
+disp(' ');
+disp(sprintf('The SBPOP Package for MATLAB'));
+disp(sprintf('Developed by Henning Schmidt, info@sbtoolbox2.org.'));
+disp(sprintf('The SBPOP Package contains several third party packages, therefor'));
+disp(sprintf('copyright statements are present in the individual functions and subpackages.'));
+disp(sprintf(' '));
+disp(sprintf('This program is Free Open Source Software: you can redistribute it and/or modify '));
+disp(sprintf('it under the terms of the GNU General Public License as published by '));
+disp(sprintf('the Free Software Foundation, either version 3 of the License, or '));
+disp(sprintf('(at your option) any later version. '));
+disp(sprintf(' '));
+disp(sprintf('This program is distributed in the hope that it will be useful, '));
+disp(sprintf('but WITHOUT ANY WARRANTY; without even the implied warranty of '));
+disp(sprintf('MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the '));
+disp(sprintf('GNU General Public License for more details. '));
+disp(sprintf(' '));
+disp(sprintf('You should have received a copy of the GNU General Public License '));
+disp(sprintf('along with this program. If not, see <http://www.gnu.org/licenses/>.'));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Final installation information, version, etc.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+disp(' ');
+disp(' ');
+disp(sprintf('The SBPOP PACKAGE was installed from path: ''%s''',pwd));
+
+% Set default seed ... to allow for reproducibility
+setseedSBPOP(123456)
diff --git a/scripts/suport/SBPOP_PACKAGE_Rev_98/installSBPOPpackageInitial.m b/scripts/suport/SBPOP_PACKAGE_Rev_98/installSBPOPpackageInitial.m
new file mode 100644
index 0000000000000000000000000000000000000000..46c2b3b83048e7d229b0eb64f423ac1e4c14b84c
--- /dev/null
+++ b/scripts/suport/SBPOP_PACKAGE_Rev_98/installSBPOPpackageInitial.m
@@ -0,0 +1,79 @@
+function [] = installSBPOPpackageInitial()
+% installSBPOPpackageInitial
+% Function to be run upon first installation of the SBPOP package.
+% It will compile all necessary C, etc. files.
+% In a server environment with a central installation of SBPOP package, this
+% function will be run once by the systems administrator.
+% Every user then has to run the installSBPOPpackage.m command to make 
+% SBPOP available (see help text to installSBPOPpackage.m).
+%
+% Additionally, this adds the complete SBPOP package and all subpackages 
+% and subdirectories to the MATLAB path. 
+%
+%       installSBPOPpackageInitial
+
+% Information:
+% ============
+% Copyright � 2012 Novartis Pharma AG
+% 
+% This program is Free Open Source Software: you can redistribute it and/or modify 
+% it under the terms of the GNU General Public License as published by 
+% the Free Software Foundation, either version 3 of the License, or 
+% (at your option) any later version. 
+% 
+% This program is distributed in the hope that it will be useful, 
+% but WITHOUT ANY WARRANTY; without even the implied warranty of 
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+% GNU General Public License for more details. 
+% 
+% You should have received a copy of the GNU General Public License 
+% along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+clc
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check that installSBPOPpackageInitial is started in the right folder
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+currentDir = pwd;
+installSBPOPDir = fileparts(which('installSBPOPpackageInitial.m'));
+if ~strcmp(currentDir,installSBPOPDir),
+    error('Run the ''installSBPOPpackageInitial'' script from the folder where it is located.');
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Install sub packages
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+cd('SBTOOLBOX2');
+installSB
+cd('../SBPD');
+installSBPD
+cd('../SBPOP');
+installSBPOP
+cd('..');
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add folders to path
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+addpath(genpath(pwd));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Add temp folder path
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+addpath(tempdirSB);
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Show all versions used
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ver
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Final installation information, version, etc.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+disp(' ');
+disp(' ');
+disp(sprintf('SBPOP PACKAGE installed from path: ''%s''',pwd));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% Check dependencies
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+checkDependenciesSB
\ No newline at end of file