% bodesecond.m - generate bode plot for second order system
% KJA, 2006

aminit;

w=logspace(-2,2,500);
w1=logspace(-2,0,20);
w2=logspace(0,2,20);
one=ones(size(w1));

%Bode plot of second order factor
z=0.01;g='1./(s.^2+2*z*s+1)';
s=i*w;gv=eval(g);
g005=abs(gv);
p005=180/pi*unwrap(angle(gv));

z=0.08;%g='s.^2+2*z*s+1';
s=i*w;gv=eval(g);
g01=abs(gv);
p01=180/pi*unwrap(angle(gv));

z=0.2;%g='s.^2+2*z*s+1';
s=i*w;gv=eval(g);
g02=abs(gv);
p02=180/pi*unwrap(angle(gv));

z=0.5;%g='s.^2+2*z*s+1';
s=i*w;gv=eval(g);
g05=abs(gv);
p05=180/pi*unwrap(angle(gv));

z=1;%g='s.^2+2*z*s+1';
s=i*w;gv=eval(g);
g1=abs(gv);
p1=180/pi*unwrap(angle(gv));

% Generate an initial bode plot that we can draw on top of
figure(1); clf; axes('position', [0.13 0.4096 0.3347 0.5]);
linewidth = AM_ref_linewidth;
old_linewidth = AM_bode_linewidth;
AM_bode_linewidth = linewidth;
[magh, phaseh] = ambode(tf([1], [1 2*0.01 1]));
AM_bode_linewidth = old_linewidth;

subplot(magh); hold on;
loglog(w1, one,'r--', w2, 1./w2.^2, 'r--', 'LineWidth', AM_thick_linewidth);
pl=loglog(w,g005,'b-',w,g01,'b-',w,g02,'b-',w,g05,'b-',w,g1,'b-');
set(pl,'Linewidth', linewidth);

amaxis([0.01 100 0.005 200])
set(gca, 'Xtick', [0.01 0.1 1 10 100], 'XTickLabel', [])
set(gca,'Ytick',[0.01 0.1 1 10 100]);
set(gca,'YtickLabel', {'1m2' '' '1e0' '' '1e2'});

lgh = legend('Exact', 'Approx');
legend(lgh, 'boxoff');

% Now draw the phase
subplot(phaseh); hold on;
pl = semilogx( w1, 0*one, 'r--', [1 1], [0 -180], 'r--', w2, -180*one, 'r--');
set(pl, 'LineWidth', AM_thick_linewidth);
semilogx([0.01 0.1 10 100], [0 0 -180 -180], 'r--', 'LineWidth', AM_thick_linewidth);
pl=semilogx(w,p005,'b-',w,p01,'b-',w,p02,'b-',w,p05,'b-',w,p1,'b-');
set(pl,'Linewidth', linewidth);
amaxis([0.01 100 -180-30 0+30])
set(gca,'Xtick',[0.01 0.1 1 10 100])
set(gca,'XtickLabel', {'w0/100' 'w0/10' 'w0' '10w0' '100w0'});
% set(gca,'Ytick',[-180 -135 -90 -45 0])
% set(gca,'YtickLabel', {'-180' '' '-90' '' '0'});
%title('Phase')

amprint('secord-bode.eps');
