function c = FitCost_BasalFitness(x)
% x = [100*rij 100*rji log10(Si) log10(Sj)]

%% Calculates the cost function for monocultures (i.e. the difference between the target mechanistic model dynamics
%% and the dynamics obtained from the pairwise model)
 
% This code is free to use for any purposes, provided any publications resulting from the use of this code reference the original code/author.
% Author:  Babak Momeni (bmomeni@gmail.com); August 2016
% The code is not guaranteed to be free of errors. Please notify the author of any bugs, and contribute any modifications or bug fixes back to the original author.

global nm Nt dtau ExtTh CSD

taurng = 0:dtau:Nt*dtau;

r0 = 0.01*x(1);
rs = 0.01*x(2);
Si = 10.^x(3);

XLV = CSD; % initial number of each cell type

tau0 = 0; % in hours
tau = tau0;

XLVlm = zeros(1,Nt);
ctLV = 0;
while (tau<Nt*dtau),

    ctLV = ctLV+1;
    tau = taurng(ctLV);
    rLVz = r0 + rs*(XLV/(XLV+Si));
    XLV = XLV + dtau*(rLVz*XLV);
    XLV(XLV<ExtTh) = 0;
    XLVlm(:,ctLV) = XLV;

end

nLV = XLVlm(1,1:ctLV);
% disp(Nt)
% disp(XLVlm(:,max(ctLV,1)))
%
% figure
% semilogy(taurng(1:Nt),n1(1:Nt))
% hold on
% semilogy(taurng(1:Nt),nLV1(1:Nt),':')
% pause

Nsec = 4; % number of sections for calculating the cost function
c = zeros(1,Nsec);
Nti = round(linspace(1,Nt,Nsec+1));
for i = 1:Nsec,
    c(i) = dtau*sum(sum(abs(log(nm(Nti(i):Nti(i+1)))-log(nLV(Nti(i):Nti(i+1)))).^2));
end
% disp(c)

return;