function [Kp,Td,PM,wc,alfa,beta,a]=...
    pd_tun_maxdelay(K,tau,delta,c,itun)
% PURPOSE. Tuning PD controller for double 
% integrating plus time delay plant.
% h_p(s)=K*exp(-tau*s)/s^2 where K=plant gain, 
% tau=time delay. Default c=2.5, itun=2
% [Kp,Td]=pd_tun_maxdelay(K,tau,delta) 
% [Kp,Td,PM,wc,alfa,beta]=...
%   pd_tun_maxdelay(K,tau,delta,c,itun)
% On Input
% K, tau- DIPTD param., K gain, tau time-delay.
% c     - Constant, method product parameter.
%         c = 2.5 default.
% delta - The max. relative time delay error.
% itun  = itun=1 (DM=dtau_max=delta*tau). 
%         Ms constant
%         itun=2 (DM=dtau_max=delta. Varying Ms.
% On output
% Kp   - Proportional constant in PD controller
% Td   - Derivative time constant in PD control.
% PM   - The phase margin
% wc   - The gain crossover frequency
% alfa - Kp=alfa/(k*tau)
% beta - Ti=beta*tau

% Alg. tuning PD controller for DIPTD process
if nargin == 4; itun=2; end
if nargin == 3; itun=2; c=2.5; end
if nargin == 2; itun=2; c=2.5; delta=1.6; end
if itun == 1
    %delta % Alg. 2.1 Alt. 1 Alg. 2.1, 
    % DM=dtau_max=delta*tau. Ms constant.
else
   delta=delta/tau; % Alt. 2 Alg. 2.1 
   %DM=dtau_max=delta, varying Ms
end
[alfa,beta,PM,a,f]=pi_tun_maxdelay(c,delta);
Td=beta*tau;
Kp=alfa/(K*tau*Td); % The PD controller param.
wc=sqrt(f)*Kp*K*Td;
% end pd_tun_maxdelay.m