function [tt,v1,fo,fs,t1,vc,th1,fn,c,vo]=pll(fii,foo,Kd,T,th0,dt);
%
% [t1,vc,th1,fn,c,vo]=pll(fi,fo,Kd,T,th0,dt);
% Default:pll(800,1000,1,.1,[0 0],.00025);BBI 99
global K fi fo
if nargin<5;th0=[0 0];end ;
if nargin<2;foo=1000;end;
if nargin<1;fii=800;end;
if nargin<3;Kd=1;end;
if nargin<4;T=100/foo;end;
if nargin<6;dt=.25/foo;end;
fo=foo;fi=fii;Kv=2*pi*fo;K=Kv*Kd;
vs=version;vs=vs(1);
if strcmp (vs,'4');
[t,th]=ode23('equation',0,T,th0);whitebg('w');delete(1);
else
dT=.25/fi;[t,th]=ode45('equation',0:dT:T,th0');
end;
t1=0:dt:T-dt;
th1=spline(t,th(:,1),t1);th2=spline(t,th(:,2),t1);
vo=cos(2*pi*fo*t1+th1);
fn=1/T;n=length(vo);c=abs(fft(vo))/n*2;
I=1:n/2;fn=fn*(I-1);c=c(I);
I=find(c>.01);fn=fn(I);cn=20*log10(c(I));
vc=th2/Kv;f=th2/(2*pi)+fo;
%================================================================================
nstr=['Phase-Locked Loop(PLL)fo='num2str(fo)'(kHz),Kv='];
nstr=[nstr num2str(Kv)'x 1e03(rad/V-s),Kd='num2str(Kd)'];
nstr=[nstr 'BBI 99'];
figure('Units','normal','Pos',[0.006 .05 .985 .88]);
set(gcf,'NumberTitle','off','Name',nstr);
subplot(221);plot(t1,vc,'b');title('Control Voltage');
xlabel('t(ms)');v=axis;v3=v(3)*1.17;zoom xon;
if abs(v3)<1e-06;v3=-0.084;end;
if abs(min(vc)+max(vc))<1e-04;v3=-1.337;end;
subplot(223);plot(t1,f,'k');
title('Frequency');xlabel('t(ms)');
subplot(224);plot(t1,th1,'k');
title('Phase');xlabel('t(ms)');
m=length(I);
for i=1:m;
subplot(222);
plot(fn(i)+[0 0],[-40 cn(i)],'b');hold on;
end;
plot(fn(m)+2/T,0,'b',fn(1)-2/T,0,'b');
title('Spectrum');hold off;xlabel('f(kHz)');pause(3);
%==============================================================================
m=10*4;n=length(t1);n2=n-m+1;
dt=t1(2);T=m*dt;dt=.1*dt;fs=1/dt;
tt=0:dt:T;tt2=t1(n2)+tt;
v1=spline(t1(1:m),vc(1:m),tt);
v2=spline(t1(n2:n),vc(n2:n),tt2);
y1=vco(v1,fo,fs);y2=vco(v2,fo,fs);
nstr=['SCOPE blue:vo(t)red:vi(t)fi='];
nstr=[nstr num2str(fi)'(kHz),fo='num2str(fo)'(kHz),'];
H2=figure('Name',nstr,'Num','off','Pos',[5 100 790 400]);
subplot(211);plot(tt,y1,'b',tt,sin(2*pi*fi*tt),'r');
set(gca,'units','pix','pos',[40 240 720 140]);xlabel('t(ms)');
subplot(212);plot(tt2,sin(2*pi*fi*tt2),'r',tt2,h2,'b');
set(gca,'units','pix','pos',[40 45 720 140]);
axis([tt2(1) tt2(length(tt2)) -1 1]);
xlabel('t(ms)');v=axis;zoom xon;