%--------------------------------------------------------------------------
%Copyright 2016, Mengqiu Li

%The following code is licensed under a Creative Commons 
%Attribution-NonCommercial-ShareAlike 4.0 International Public License.

%Under the following terms:

%1) Attribution - You must give appropriate credit, provide a link to the 
%license, and indicate if changes were made. You may do so in any 
%reasonable manner, but not in any way that suggests the licensor 
%endorses you or your use. 

%Preferred method of attribution is citing or referring to the published 
%paper associated with this work: 
%Journal of the American Chemical Society, 2015, 137 (51), pp 16055–16063.

%2) NonCommercial - You may not use the material for commercial purposes.

%3) ShareAlike - If you remix, transform, or build upon the material, 
%you must distribute your contributions under the same license as the 
%original.

%4) No additional restrictions - You may not apply legal terms or 
%technological measures that legally restrict others from doing anything 
%the license permits.

%Under the above terms, you are free to:

%1) Share - copy and redistribute the material in any medium or format
%2) Adapt - remix, transform, and build upon the material

%The license in full: 
%   http://creativecommons.org/licenses/by-nc-sa/4.0/legalcode
%--------------------------------------------------------------------------

function Error=fourline_fitting(Parameters,TurningPoints,X,Y,Length)
    X=X(1:Length);
    Y=Y(1:Length);
    
    [Coor1,Coor2]=size(X);
    if Coor2==1 && Coor1>1
    else
        error('   Unexpected X dimension, use a vertical vector');
    end
    [Coor1,Coor2]=size(Parameters);
    if min(Coor1,Coor2)==1 && max(Coor1,Coor2)==5
    else
        error('   Unexpected Parameter numbers');
    end
    [Coor1,Coor2]=size(TurningPoints);
    if min(Coor1,Coor2)==1 && max(Coor1,Coor2)==3
    else
        error('   Unexpected TurningPoints numbers');
    end
    A1=Parameters(1);
    B1=Parameters(2);
    A2=Parameters(3);
    A3=Parameters(4);
    A4=Parameters(5);
    TP1=TurningPoints(1);
    TP2=TurningPoints(2);
    TP3=TurningPoints(3);
    B2=(A1-A2)*TP1+B1;
    B3=(A2-A3)*TP2+B2;
    B4=(A3-A4)*TP3+B3;
    Coefficients=turningpointcheck([TP1,TP2,TP3],X);
    Error=Y-((Coefficients(:,:,1)).*(A1*X+B1)+(Coefficients(:,:,2)).*(A2*X+B2)+(Coefficients(:,:,3)).*(A3*X+B3)+(Coefficients(:,:,4)).*(A4*X+B4));
end