function error = ActFit (kf, kn, qfit)
%minimization function = Errorfunction
%the three parameters are kf= constants which are variable and change during
%the fit; kn = parameters which are fixed; qfit = an array which contains
%only 0 and 1 and is needed to combine kf and kn to k, 0 means on this
%position is a fixed parameter, 1 means there is a varible one

%kf contains log values, reversing this
kf=10.^(kf);
%combine kf and kn, by using qfit
k = connect_k(kf,kn,qfit);

%extract the start values from the parameter vector
S0 = k(11:14);

%define the global variable, because they are needed here and in paramFit

global tpoint Sdata sigma s sigma1
s=2;

%differential equations to describe the system's behaviour


    function dS = activation_red(t,S)
        dS = zeros (4,1);
        dS(1)= k(1) - k(2) .* S(1)-k(5).*S(1).*S(2)+ k(6) .* S(3); %Cas
        dS(2) = k(3) - k(4) .* S(2)-k(5).*S(1).*S(2);  %tracr/crRNA                                
        dS(3) = k(5).*S(1).*S(2) - k(6) .* S(3); %tracr/crRNA/Cas9
        dS(4)= k(7) + k(8).*(S(3)./(k(9)+S(3))); %SEAP
        
    end

%Solve the differential equation by using the ode15s solver

[tsol,ssol]=ode15s(@activation_red,tpoint,S0);


%observation function

%Cas
s_pred_red1 = ssol(:,1) + ssol(:,3);
S_data_red3 = Sdata(:,1);
S_data_red4 = Sdata(:,2);

% SEAP
s_pred_red = ssol(:,4);
S_data_red1 = Sdata(:,3);
S_data_red2 = Sdata(:,4);

%error function we want to minimize later
%here we calculate the least square error, by summing up the squared
%difference between the calculated data and the measured points of all 
%different substrates. This is done for each time point and for all
%samples( in our case two). The result of all samples is also summed up and divided by
%the variance 

if length(tsol)<size(Sdata(:,3),1)
   return
end    
error = (sum((k(10).*s_pred_red(:)-S_data_red1(:)).^2) + sum((k(10).*s_pred_red(:)-S_data_red2(:)).^2))/sigma^2+(sum((k(10).*s_pred_red1(:)-S_data_red3(:)).^2) + sum((k(10).*s_pred_red1(:)-S_data_red4(:)).^2))/sigma1^2;
end

