function [conditions, modes, Model ] =load_setup(general_setup_name, model_setup_name)
%------------------- LineshapeKin Simulation -----------------------------
% Load simulation settings 
%
% 5/12/09
% Written by Evgenii Kovrigin 
% Medical College of Wisconsin
%
% This function loads parameters from plain-text files. 
% It uses a helper Python program to parse files into a
% prepare simple file structure and then reads the data in.
%
% One file is  with general parameters of simulations.
% The other file has the current parameter of the specific model.
% Both files are passed as function arguments without '.txt' extension
% which is added later.  This scheme 
% allows one to run simulations of multiple model variations using 
% the same output layout and series of titration points as well as 
% vary layout and titration series design for the same model.
%
%
% Conventions: 
% - we use association or formation equilibrium constants Ka=[new
%    species]/[old species]
% - we use reverse rate constants k2 so forward rate k1= k2*Ka
% 
global   YES NO ;




%% Check if files exist
general_setup_file_name=sprintf('%s.txt',general_setup_name);
model_setup_file_name=sprintf('%s.txt',model_setup_name);
if ~exist(general_setup_file_name,'file')
    error('File %s not found!', general_setup_file_name);
end
if ~exist(model_setup_file_name,'file')
    error('File %s not found!', model_setup_file_name);
end



%% ===============  LOAD MODEL-SPECIFIC SETTINGS =========

%% Execute data preparation program for a model-specific input file 
% It creates temporary files with values that are 
% easy to read with Matlab data import functions.
converter_name='lineshapekin_load_setup.py';

system(sprintf('%s %s', converter_name, model_setup_file_name));



%% Load model-specific parameters
standard_folder_name='temp';

% Unique model identifier
Model.code=load_word(standard_folder_name,'Model_code');

%       Model.name = 'B_test1';  % assign in Simulate from a file name
Model.description=load_string(standard_folder_name,'Description');
  
%-- names of species for display
Model.species_names=load_word_array(standard_folder_name,'Species_names');
Model.NMR_invisible_species_names=load_word_array(standard_folder_name,'NMR_invisible_species_names');

%-- association constants
Model.Ka_names=load_word_array(standard_folder_name,'Ka_names');
Model.Ka  =load_float_array(standard_folder_name,'Ka');

%-- rate constants of REVERSE reactions
Model.k_names=load_word_array(standard_folder_name,'k_names');
Model.k2  =load_float_array(standard_folder_name,'k2');

%-- chemical shifts of pure species, 1/s
Model.w0  =load_float_array(standard_folder_name,'w0');

%-- Relaxation rates of pure species, 1/s
Model.R2 =load_float_array(standard_folder_name,'R2');

%-- Heat of formation of the species, relative units
Model.dH =load_float_array(standard_folder_name,'dH');

%-- Values of dependent parameters: start empty to be populated during calculations
Model.Ka_dependent_names={};  % names of dependent transitions
Model.Ka_dependent = [];             % values of dependent equilibrium constants
Model.k1 = [];                              % values of forward rate constants 



  
        




%% ============= Consistency checking ================
%-- test whether all the parameters correspond to a correct number of species
if length(Model.R2)~=length(Model.w0) 
     error('ERROR in model_setup.m: I have %d R2 values but %d w0 values!', ...
         length(Model.R2), length(Model.w0));
end
if length(Model.R2)~=length(Model.species_names) 
     error('ERROR in model_setup.m: I have %d R2 values but %d species names!', ...
         length(Model.R2), length(Model.species_names));
end


Model.species=length(Model.R2);


%% Remove temporary files
rmdir(standard_folder_name,'s'); 

%% =============== END OF LOADING MODEL-SPECIFIC SETTINGS =========
















%% ===== LOAD GENERAL SIMULATION SETTINGS =============

% Execute data preparation program for a model-specific input file 
% It creates temporary files with values that are 
% easy to read with Matlab data import functions.
converter_name='lineshapekin_load_setup.py';

system(sprintf('%s %s', converter_name, general_setup_file_name));


% Total Ligand/Receptor ratio at each titration point
% NOTE: first point L/R=0 has to be non-zero very small number 
%           to prevent /0 
conditions.LRratio= load_float_array(standard_folder_name,'LRratio');
conditions.total_titration_points=length(conditions.LRratio);


% Number of points on smooth population curves and on ITC profile
conditions.LRpoints= load_float_value(standard_folder_name,'LRpoints');

% constant M_ligand/Receptor ratio (in models that use it, otherwise - ignored)
Model.MRratio =  load_float_value(standard_folder_name,'MRratio');
% MRatio goes into Model because it is a fixed parameter in simulations, 
% yet being loaded from general setup because it is truly variable solution
% condition, relatively to 'fixed' physical parameters of the model system.


% ======== Concentration of receptor, M ======== 
% You may have Rtotal vary corresponding to your experimental conditions and all calculations
% at specific titration points given by LRratio will be correct. However,
% the smooth curves will only be computed for fixed Rtotal.

conditions.Rtotal= load_float_array(standard_folder_name,'Rtotal');

%--- Folder where to save results
conditions.results_path=load_word(standard_folder_name,'Results_Path');

% -- Plotting options

% stacked or overlayed plotting
stacked_plot_mode= load_word(standard_folder_name,'Stacked_Plot');
switch stacked_plot_mode
    case 'YES'
        modes.Stacked_Plot = YES;
    case 'yes'
        modes.Stacked_Plot = YES;
    otherwise
        modes.Stacked_Plot = NO;
end
% vertical displacement for stacked plotting
modes.Percent_Shift= load_float_value(standard_folder_name,'Percent_Shift');   

%-- Color array for plotting (I put RGB sets for more species than ever to be used)
conditions.Colors=[ ...
    0 0 0
    1 0 0
    0 0 1
    0 1 0
    1 0 1
    0 1 1
    1 1 0
    0.5 0.5 0.5
    1 0.5 0.5
    0.5 1 0.5
    0.5 0.5 1
    1 1 0.5
    0.5 1 1
    1 0.5 1
    0 0.5 0.5
    0.5 0 0.5
    0.5 0.5 0
    0 0 0.5
    0.5 0 0
    0 0.5 0
    ];


%-- number of points in each individual spectral trace                                
conditions.Spectral_Points= load_float_value(standard_folder_name,'Spectral_Points'); 


% - limits of a spectral window /s
conditions.w_min= load_float_value(standard_folder_name,'w_min');   
conditions.w_max= load_float_value(standard_folder_name,'w_max'); 
 


%% Remove temporary files
rmdir(standard_folder_name,'s'); 


%% Consistency checks
if length(conditions.LRratio)~=length(conditions.Rtotal)
    error('Rtotal and LRratio arrays have different length: %d and %d !', ...
        length(conditions.Rtotal), length(conditions.LRratio));
end

if conditions.w_min>=conditions.w_max
    error('Spectral window limits are unusable:\n w_min= %f, w_max=%f !', conditions.w_min, conditions.w_max);
end


%% ===== END OF LOADING OF GENERAL SIMULATION SETTINGS =============


end
    

%% =============== Data import functions ========================
% These functions utilize conventions of data format set by Python text-conversion program
    
function word= load_word(folder_name,parameter_name)
%  Open file and read a single word (first word found there)
    fid=fopen(fullfile(folder_name,sprintf('%s.txt',parameter_name)));
    temp=textscan(fid,'%d'); % eat up default '1'
    temp=textscan(fid,'%s',1);
    temp=temp{1};
    word=temp{1};
    fclose(fid);
   
end

function words= load_word_array(folder_name,parameter_name)
%  Open file and load a cell array of words
    fid=fopen(fullfile(folder_name,sprintf('%s.txt',parameter_name)));
    temp=textscan(fid,'%d');
    N=temp{1};
    temp=textscan(fid,'%s',N);
    words=temp{1}';
    fclose(fid);
end

function outstring= load_string(folder_name,parameter_name)
%  Open file, load an array of words and connect them to a string
    fid=fopen(fullfile(folder_name,sprintf('%s.txt',parameter_name)));
    temp=textscan(fid,'%d');
    N=temp{1};
    words=textscan(fid,'%s',N);
    fclose(fid);
    % connect them together
    outstring='';
    for counter=1:N
       outstring=sprintf('%s %s', outstring, words{1}{counter});
    end
    
end


function float_value= load_float_value(folder_name,parameter_name)
%  Open file and load one floating point value
    fid=fopen(fullfile(folder_name,sprintf('%s.txt',parameter_name)));
    temp=textscan(fid,'%f');
    temp=temp{1};
    float_value=temp(2);
    fclose(fid);
end

function float_array= load_float_array(folder_name,parameter_name)
%  Open file and load a floating-point array
    fid=fopen(fullfile(folder_name,sprintf('%s.txt',parameter_name)));
    temp=textscan(fid,'%f');
    temp=temp{1};
    float_array=temp(2:end)';
    fclose(fid);
end

