function [u e_past] = PIcontroller(Kp,Ti,y0,y,u0,e_past,saturation)
%******** PI-Controller *************************************************%
% This function calculates the control signal u, based on input
% y0=setpoint, y=measurement-vector containing all all measurements so far,
% Kp=proportional Gain, Ti=Integral Time. u0=current control signal
% controlStart is the time from when the controller should be applied
% u=Kp*e+(Kp/Ti)*integral(e)
%************************************************************************%

%% Calculate Error and Integral Gain
e=y0-y(end);   %Error Pressure Bottom Hole Control
Ki=1/Ti;       %Integral Gain 

%% Proportional Term
proportional=Kp*e;

%% Integral Term with anti-windup reset term for saturation 
umin=0;
umax=1;


%if u0(1)>umin && u0(1)<umax 
%     e_past=e_past+e;
%end

if sign(Kp)==1
    if u0(1)>umin && u0(1)<umax
        e_past=e_past+e;
    elseif u0(1)>=umax && e>=0
        e_past=e_past;
    elseif u0(1)>=umax && e<=0
        e_past=e_past+e;
    elseif u0(1)<=umin && e<=0
        e_past=e_past;
    elseif u0(1)<=umin && e>=0
        e_past=e_past+e;
    end
    
elseif sign(Kp)==-1
    if u0(1)>umin && u0(1)<umax
        e_past=e_past+e;
    elseif u0(1)>=umax && e<=0
        e_past=e_past;
    elseif u0(1)>=umax && e>=0
        e_past=e_past+e;
    elseif u0(1)<=umin && e>=0
        e_past=e_past;
    elseif u0(1)<=umin && e<=0
        e_past=e_past+e;
    end
end

    
integral=Kp*Ki*e_past;


%% PI Controller Output
u=proportional+integral;%Control Signal


%% Saturation Effect
if isequal(saturation,'on')
    if u>umax    
        u=umax;
    elseif u<umin    
        u=umin;
    end
end


end

