function [Raw_Data, beta, beta_error, norm] = fit_all_data(Sparky_data_path, resnames, Model, conditions, modes)
%------------------- LineShapeKin FIT_ALL_DATA -----------------------------
%-- version 3.0 
%
% 3/17/08
% Written by Evgenii Kovrigin, Medical College of Wisconsin

% This program fits one residue at a time. First it performs 'quasi'-grid search 
% for Koff (doing actual fitting every time) and then does fitting with error estimate
% staring from optimal conditions




global YES NO B_vector Raw_Data;



%- concatenated data sets
Xfull=[];
Yfull=[];

%--- combine data for all residues ---
res_number=length(resnames);
disp(sprintf('Fitting %d residue(s)', res_number));
resStr=['']; %--- combined name of the residues in the fitting 
%-- main storage of raw and normalized spectral data used in the project
Raw_Data=cell(1,res_number);

for i=1:res_number
  
    cur_res=resnames{i};
    disp(sprintf('%s',cur_res));

    [res_data] = prepare_residue_data(Sparky_data_path, cur_res, conditions, modes);


    Xfull =[ Xfull ; res_data.Xcomposite]; 
	Yfull=[ Yfull ; res_data.Ytotal]; 
    Raw_Data{i}= res_data;    %-- collect all raw data used in the project
    
    %--- form a name for global fitting result
    if i>1 
        resStr=[resStr '.' resnames{i}];
    else
        resStr=[resnames{1}];
    end
end
disp(sprintf('Resulting dataset name:  %s', resStr));

%--- run grid-search fitting for koff (no error determination for the sake of speed)---
beta0=B_vector.starting_values';
modes.estimate_error=NO;
modes.grid_search=YES;

[beta,beta_error,norm]=fit_run(resStr, beta0, Xfull, Yfull, conditions, modes);

%--- re-run fitting for optimized parameter values at minimum norm  ---
beta0=beta; %-- use optimized values for fitting parameters
modes.estimate_error=YES;  %- to skip grid search and estimate errors 
modes.grid_search=NO;

[beta,beta_error,norm]=fit_run(resStr, beta0, Xfull, Yfull, conditions, modes);




 
