% Non-etalon_2plus n-component analyzis improvement
% run after Nonetalon_n.m

tic
% bootstrap loop for concentrations retrieve
concentration = zeros(nB,nc); % bootstrap concentrations
curves_matrix = zeros(nx,nc);  %?

% discrepancy is the best after previous trials
icCycle = 3;
fixed = zeros(nc,1);
fixed(1) = 105;
fixed(2) = 18;
fixed(3) = 0;
% fixed(4) = 109;
% 
% fixed(i) = 0; means component i is in bootstrap cycle search
% fixed(i) = k, k > 0; means component i is fixed in bootstrap trials
% at case number k.
for iB = 1:nB
    fixed(icCycle) = iB;
    for jB = 1:nB
        for ic = 1:nc
            ibb = jB;
            k = fixed(ic);
            if (k > 0), ibb = k; end 
            Dy=zeros(nx,ni(ic));
    %         freqsB = FrInt{ic,1};
    %         absintsB = FrInt{ic,2};
    %         sigma = FrInt{ic,3};
            for j=1:ni(ic)
               Dy(:,j)=(FrInt{ic,2}(ibb,j)/(2.5*FrInt{ic,3}(j)))* ...
                   exp(-(0.5/FrInt{ic,3}(j)^2)*(x0-FrInt{ic,1}(ibb,j)).^2);
            end %j
            y=(sum(Dy'))';
            curves_matrix(:,ic) = y';
        end % ic
        inv_curves_matrix = pinv(curves_matrix);
        concentration(iB,:) = inv_curves_matrix*exp_curve;
        % improvement
        theor_curveB = curves_matrix*concentration(iB,:)';
        discr = (theor_curveB-exp_curve).^2;
        discr_sum = sum(discr);
        if discr_sum < discrepancy
            discrepancy = discr_sum;
            i_best = iB;
            j_best = jB;
            c_bestB = concentration(iB,:);
            discr_bestB = discr;
            inv_curves_matrix_best = inv_curves_matrix;
            theor_curveB_best = theor_curveB;
    %        plot(x0,discr_bestB)
        end %if
    end % jB
end % iB

% statistics on concentration
c1c2 = zeros(nc,4);
% c1c2(:,1) = mean(concentration);
% c1c2(:,2) = std(concentration);
% c1c2(:,3) = min(concentration);
% c1c2(:,4) = max(concentration);

arr = mean(concentration);
c1c2(:,1) = arr;
arr = std(concentration);
c1c2(:,2) = arr;
arr = min(concentration);
c1c2(:,3) = arr;
arr = max(concentration);
c1c2(:,4) = arr;

cGribov = c_bestB;
cGr_discr = norm(cGribov-exp_concentr');
%     hist(concentration(:,1))
% 
%     hist(concentration(:,2))
toc