clearvars -global
global tpoint Sdata sigma1 sigma

%data we have

data = fopen ('Activation.txt');
headline = textscan(data,'%s%s%s%s%s',1);
Z = textscan(data,'%f %f %f %f %f','delimiter','\t');
fclose(data);

tpoint= Z{1,1};
Sdata = [Z{1,2} Z{1,3} Z{1,4} Z{1,5}];

%calculate the standard deviation
Sdata_transform = Sdata';

Cas = Sdata_transform([1 2],:);
SEAP = Sdata_transform([3 4],:);

sigma1 = sqrt(sum(var(Cas))) / size(Cas,2);
sigma = sqrt(sum(var(SEAP))) / size(SEAP,2);
disp(sigma1);

%Parameter initialization using a latin hypercube sampling. The sampling is
%done in the logarithmic space

N = 500; %sample size for parameter

k_start = lhs_setup(N , [-5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5], [5 5 5 5 5 5 5 5 5 5 5 5 5 5 5]);

k_start=10.^(k_start);

%definition of the parameters, which are fixed during the minimization
%process

qfit = [ 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1];

%initialization of to matrices which contain the results of the N different
%minimization processes, the second number is the number of each kind of parameters
kf = zeros(N, sum(qfit));
kn = zeros(N, length(qfit) - sum(qfit) );

%divide the matrices in fixed and flexible variables
for i = 1:N
    [kf(i,:), kn(i,:)] = divide_k(k_start(i,:),qfit);
    kf(i,:) = log10(kf(i,:));
end

%initialization of the matrices in which the minimal error and the
%according parameter values are stored
Error_min = ones(1,N);
kmin = zeros(N,sum(qfit));

%Minimization of the error function with respect to k 
for i = 1:N
    disp('sample number');
    disp(i);
    options = optimset('Display','iter','MaxIter',1000);
 
    if ~isempty(kn)
        kn1 = kn(i,:);
    else
        kn1=kn;
    end
    
    try
        [kmin_temp, Error_min_temp] = fminsearch(@ActFit,kf(i,:),options, kn1, qfit);
        kmin(i,:) = kmin_temp;
        Error_min(i) = Error_min_temp;
        disp('Found minimum!')
    catch
        kmin(i,:) = NaN(size(kf(i,:)));
        Error_min(i) = NaN;
        disp('Fit not converged!')
    end
end   

% Alle NaN  rausschmeißen

kmin = kmin(~isnan(kmin(:,1)),:);
Error_min = Error_min(~isnan(Error_min));


if ~isempty(kmin)   % do nothing if fis is not successfull

    %connect fixed and static parameters
    kmin=10.^(kmin);
    k_end = zeros(length(Error_min),length(qfit));
    for i = 1:length(Error_min)
        k_end(i,:) = connect_k(kmin(i,:),kn(i,:),qfit);
    end

    %plot the fit for the best error value
    [wert,stelle]=min(Error_min);
    figure(1)
    plotFit(tpoint, Sdata, k_end(stelle,:));
    
    %plot a diagramm which shows the different error values
    figure(2)
    plotError(Error_min); 
    
    
    % display the parameters and the least-square value
    disp('Estimated parameters k(i):');
    disp(k_end)
    disp('Smallest value of the error Q:');
    disp(Error_min)
else
    disp('No fit converged!')
end
