function Demo1(action)
%   Demo1 shows the voltage and current at the source side, 
%   load side and on the transmission line.
%   This demonstration illustrates the transmission line       
%   transion progress with pure resistant load, pure 
%   capacitance load and pure inductance load.             
%                                                  
%   Use the popup menus to select source resistor     
%   and the load resistor. Then by   
%   pushing the "Run" button, you can watch an     
%   animation of the voltage and current on the transmission line.
%   The voltage and current at the source side and load side of the 
%   transmission line are also showed here with varing time.                                    
%                                                  
%   Use the "Pure Resistance", "Pure Capacitance" and "Pure Inductance"    
%   radio buttons to choose which type of load you   
%   want to view.                                  

%   Xiaowei He & Markus Zahn, 2004
%   All Rights Reserved

old_format=get(0,'Format');

if nargin<1,
   action='initialize';
end;

%   Initialize the Frame
if strcmp(action,'initialize'),
   oldfigNumber=watchon;
   
   figNumber=figure( ...
      'Name','Transmission Line Demo', ...
      'NumberTitle','off', ...
      'Visible','off', ...
      'BackingStore','off');
   set(figNumber,'Position',[43,251,966,437]);
   axes( ...
      'Units','normalized', ...
      'Position',[0.05 0.10 0.65 0.80], ...
      'Visible','off', ...
      'NextPlot','add');
   set(figNumber,'Menubar','none');
   set(gca,'YDir','reverse');
   % Load and show the figure of transmission line trans1 is for pure resistant
   % trans2 is for pure capacitance and trans3 is for pure inductance
   load('TransFig.mat','trans1','trans2','trans3');
   image(trans1);
   axis off;
     
   %===================================
   % Information for all buttons
   top=0.95;
   bottom=0.05;
   labelColor=[0.8 0.8 0.8];
   yInitPos=0.90;
   left=0.70;
   btnWid=0.25;
   btnHt=0.08;
   % Spacing between the button and the next command's label
   spacing=0.02;
   
   %====================================
   % The CONSOLE frame
   frmBorder=0.02;
   frmPos=[left-frmBorder bottom-frmBorder btnWid+2*frmBorder 0.9+2*frmBorder];
   h=uicontrol( ...
      'Style','frame', ...
      'Units','normalized', ...
      'Position',frmPos, ...
      'BackgroundColor',[0.5 0.5 0.5]);
   
   %====================================
   % The RUN button
   btnNumber=1;
   yPos=top-btnHt-(btnNumber-1)*(btnHt+spacing);
   labelStr='Run';
   cmdStr='run';
   callbackStr='Demo1(''run'');';
   
   % Generic button information
   btnPos=[left yPos-spacing btnWid btnHt];
   runHndl=uicontrol( ...
      'Style','pushbutton', ...
      'Units','normalized', ...
      'Position',btnPos, ...
      'String',labelStr, ...
      'Callback',callbackStr);
   
   %====================================
   % The Rs popup button
   btnNumber=2;
   yPos=top-btnHt-(btnNumber-1)*(btnHt+spacing);
   labelStr='R_s(ohm)';
   popupStr=str2mat('0','25','50','100','200','1000','infinite');
   RsData=[0.001; 25; 50; 100; 200; 1000; 100000];
   
   % Generic button information
   btnPos1=[left yPos-spacing+btnHt/2 btnWid btnHt/2];
   btnPos2=[left yPos-spacing btnWid btnHt/2];
   SourceHndl=uicontrol( ...
      'Style','text', ...
      'Units','normalized', ...
      'Position',btnPos1, ...
      'String',labelStr);
   popupHndl1=uicontrol( ...
      'Style','popup', ...
      'Units','normalized', ...
      'Position',btnPos2, ...
      'String',popupStr, ...
      'value',4,...
      'UserData',RsData);
   
   %====================================
   % The Rl popup button
   btnNumber=3;
   yPos=top-btnHt-(btnNumber-1)*(btnHt+spacing);
   labelStr='R_L(ohm)';
   
   % Generic button information
   btnPos1=[left yPos-spacing+btnHt/2 btnWid btnHt/2];
   btnPos2=[left yPos-spacing btnWid btnHt/2];
   LoadHndl=uicontrol( ...
      'Style','text', ...
      'Units','normalized', ...
      'Position',btnPos1, ...
      'String',labelStr);
   popupHndl2=uicontrol( ...
      'Style','popup', ...
      'Units','normalized', ...
      'Position',btnPos2, ...
      'String',popupStr, ...
      'Value',4, ...
      'UserData',RsData);
   
   %====================================
   % The PURE RESISTANCE radio button
   btnNumber=4;
   yPos=top-btnHt-(btnNumber-1)*(btnHt+spacing);
   labelStr='Pure Resistance Load';
   callbackStr='Demo1(''pureresistance'');';
   
   % Generic button information
   btnPos=[left yPos-spacing btnWid btnHt];
   PureRHndl=uicontrol( ...
      'Style','radiobutton', ...
      'Units','normalized', ...
      'Position',btnPos, ...
      'String',labelStr, ...
      'Value',1, ...
      'Callback',callbackStr);
   
   %====================================
   % The PURE CAPACITANCE radio button
   btnNumber=5;
   yPos=top-btnHt-(btnNumber-1)*(btnHt+spacing);
   labelStr='Pure Capacitance Load';
   callbackStr='Demo1(''pureresistance'');';
   
   % Generic button information
   btnPos=[left yPos-spacing btnWid btnHt];
   PureCHndl=uicontrol( ...
      'Style','radiobutton', ...
      'Units','normalized', ...
      'Position',btnPos, ...
      'String',labelStr, ...
      'Value',0, ...
      'Callback',callbackStr);
  
   %====================================
   % The PURE INDUCTANCE radio button
   btnNumber=6;
   yPos=top-btnHt-(btnNumber-1)*(btnHt+spacing);
   labelStr='Pure Inductance Load';
   callbackStr='Demo1(''pureresistance'');';
   
   % Generic button information
   btnPos=[left yPos-spacing btnWid btnHt];
   PureLHndl=uicontrol( ...
      'Style','radiobutton', ...
      'Units','normalized', ...
      'Position',btnPos, ...
      'String',labelStr, ...
      'Value',0, ...
      'Callback',callbackStr); 
  
   %====================================
   % The SPEED popup button
   btnNumber=7;
   yPos=top-btnHt-(btnNumber-1)*(btnHt+spacing);
   labelStr='Simulation running time';
   speedStr=str2mat('8 round trips','4 round trips');
   speedData=[10; 20];
   
   % Generic button information
   btnPos1=[left yPos-spacing+btnHt/2 btnWid btnHt/2];
   btnPos2=[left yPos-spacing btnWid btnHt/2];
   SpeedHndl=uicontrol( ...
      'Style','text', ...
      'Units','normalized', ...
      'Position',btnPos1, ...
      'String',labelStr);
   popupHndl3=uicontrol( ...
      'Style','popup', ...
      'Units','normalized', ...
      'Position',btnPos2, ...
      'String',speedStr, ...
      'Value',1, ...
      'UserData',speedData);
  
   %====================================
   % The INFO button
   labelStr='Info';
   callbackStr='Demo1(''info'')';
   infoHndl=uicontrol( ...
      'Style','push', ...
      'Units','normalized', ...
      'Position',[left bottom+btnHt+spacing btnWid btnHt], ...
      'String',labelStr, ...
      'Callback',callbackStr);
   
   %====================================
   % The CLOSE button
   labelStr='Close';
   callbackStr='close(gcf)';
   closeHndl=uicontrol( ...
      'Style','push', ...
      'Units','normalized', ...
      'Position',[left bottom btnWid btnHt], ...
      'String',labelStr, ...
      'Callback',callbackStr);
   
   % Uncover the figure
   hndlList=[popupHndl1 popupHndl2 PureRHndl PureCHndl PureLHndl SourceHndl LoadHndl popupHndl3];
   set(figNumber, ...
      'Visible','on', ...
      'UserData',hndlList);
   % Now run the demo. 
   watchoff(oldfigNumber);
   figure(figNumber);
   
elseif strcmp(action,'run'),
   %====================================
   % Get all the Handle information
   axHndl=gca;
   figNumber=watchon;
   hndlList=get(figNumber,'Userdata');
   popupHndl1=hndlList(1);
   popupHndl2=hndlList(2);
   PureRHndl=hndlList(3);
   PureCHndl=hndlList(4);
   PureLhndl=hndlList(5);
   SourceHndl=hndlList(6);
   LoadHndl=hndlList(7);
   popupHndl3=hndlList(8);
   
   %======= Start of Demo
   % Gain the information of each selected button
   Re1Value=get(popupHndl1,'Value');
   Re2Value=get(popupHndl2,'Value');
   SpeedValue=get(popupHndl3,'Value');
   Re1Matrix=get(popupHndl1,'UserData');
   Re2Matrix=get(popupHndl2,'UserData');
   SpeedMatrix=get(popupHndl3,'UserData');
   Re1=Re1Matrix(Re1Value,:);
   Re2=Re2Matrix(Re2Value,:);
   Speed=SpeedMatrix(SpeedValue,:);
   [Mssize, Masize]=size(Re1Matrix);
   
   % Gain the information of Load type. 1 is for pure resistance, 2 is for pure capacitance and inductance.
   if Mssize==7
       Retype=1;
   else
       Retype=2;
   end
   
   draft(Re1,Re2,Retype,Speed);
   
   % ====== End of Demo
   watchoff(figNumber);
   
elseif strcmp(action,'pureresistance'),
   % Get all the Handle information
   axHndl=gca;
   figNumber=watchon;
   drawnow;
   hndlList=get(figNumber,'Userdata');
   popupHndl1=hndlList(1);
   popupHndl2=hndlList(2);
   PureRHndl=hndlList(3);
   PureCHndl=hndlList(4);
   PureLHndl=hndlList(5);
   SourceHndl=hndlList(6);
   LoadHndl=hndlList(7);
   load('TransFig.mat','trans1','trans2','trans3');
   
   switch gco
       
   % Reset all the buttons for pure resistance load
   case PureRHndl,
      set(PureRHndl,'Value',1);
      set(PureCHndl,'Value',0);
      set(PureLHndl,'Value',0);
      set(SourceHndl,'String','R_s(ohm)');
      set(LoadHndl,'String','R_L(ohm)','Visible','on');
      popupStr=str2mat('0','25','50','100','200','1000','infinite');
      RsData=[0.001; 25; 50; 100; 200; 1000; 100000];
      set(popupHndl1,'String',popupStr,'UserData',RsData,'Value',4);
      set(popupHndl2,'String',popupStr,'UserData',RsData,'Value',4);
      image(trans1);
      
   % Reset all the buttons for pure capacitance load
   case PureCHndl
      set(PureRHndl,'Value',0);
      set(PureCHndl,'Value',1);
      set(PureLHndl,'Value',0);
      set(SourceHndl,'String','C(pF)');
      set(LoadHndl,'String','Laugh','Visible','off');
      ZStr1=str2mat('75','100','200');
      ZData=[0.0075; 0.01; 0.02];
      NStr1=str2mat('Select Capacitance');
      NData=[1977];
      set(popupHndl1,'String',ZStr1,'UserData',ZData,'Value',2);
      set(popupHndl2,'String',NStr1,'UserData',NData,'Value',1);
      image(trans2);
      
   % Reset all the buttons for pure inductance load
   case PureLHndl
      set(PureRHndl,'Value',0);
      set(PureCHndl,'Value',0);
      set(PureLHndl,'Value',1);
      set(SourceHndl,'String','L(muH)');
      set(LoadHndl,'String','Laugh','Visible','off');
      ZStr1=str2mat('1','2','5');
      ZData=[100; 200; 500];
      NStr1=str2mat('Select Inductance');
      NData=[817];
      set(popupHndl1,'String',ZStr1,'UserData',ZData,'Value',2);
      set(popupHndl2,'String',NStr1,'UserData',NData,'Value',1);
      image(trans3); 
      
   otherwise
       
   end;
   
   watchoff(figNumber);
   
elseif strcmp(action,'info'),
   helpinfo=strvcat(['This software is used to illustate the demonstrations'... 
      ' related to 6.013 Electromagnetics and Applications.'],[' '],...
      [' '],[' @2004 Xiaowei He & Markus Zahn. All Rights Reserved.']);
   diagHndl=helpdlg(helpinfo,'Information');
   
end;    

%  Restore Format
set(0,'Format',old_format)

function pos=draft(Re1, Re2, Retype, Speed)
%   Draft draw the voltage and current at the source side, 
%   load side and on the transmission line.                            

%   Xiaowei He & Markus Zahn, 2004
%   All Rights Reserved

%   Define the constant
z0=100; % The character impedance of transmission line (ohm)
V0=1; % The voltage of the source (V)
n=Speed; % The steps for a time peroid
cont=10; % The number of points in each step
m=160/n; % The total period to show
helpinfo=strvcat(['The Demo is not ready'... 
      .'],[' '],...
      [' '],[' @2004 Xiaowei He & Markus Zahn. All Rights Reserved.']);
  
if nargin==0,
   diagHndl=helpdlg(helpinfo,'Information');
   
elseif nargin==1,
   diagHndl=helpdlg(helpinfo,'Information');
   
elseif nargin==2,
   diagHndl=helpdlg(helpinfo,'Information');
   
elseif nargin==3,
   diagHndl=helpdlg(helpinfo,'Information');
   
elseif nargin==4,
    
   if Retype==1
       Rs=Re1;
       RL=Re2;
       
       if Rs+RL==0
           helpinfo=strvcat(['There is no such way on transmission line with']... 
           ,['Rs = ', num2str(Rs), ', and RL = ', num2str(RL), '.'],...
           [' '],[' @2004 Xiaowei He & Markus Zahn. All Rights Reserved.']);
           diagHndl=helpdlg(helpinfo,'Information');
       else
           
           % Define the arrays
           t=linspace(0,m,m*n*cont); % The array for total time period
           x=linspace(0,1,n*cont); % The array for transmission line
           Vx=zeros(1,n*cont); % The array for voltage on transmission line
           Ix=zeros(1,n*cont); % The array for current on transmission line
           Vs=zeros(1,m*n*cont); % The array for voltage on source side
           Is=zeros(1,m*n*cont); % The array for current on source side
           VL=zeros(1,m*n*cont); % The array for voltage on load side
           IL=zeros(1,m*n*cont); % The array for current on load side
           VLt=zeros(1,(m+1)*n*cont); % The array for voltage tracking
           % Define reflect coefficients
           gamma0=z0/(z0+Rs); 
           gammas=(Rs-z0)/(z0+Rs);
           gammaL=(RL-z0)/(RL+z0);
           
           if RL>10000
               gammaL=1;
           end
           
           figmovie=figure( ...
              'Name','Voltage on Transmission Line', ...
              'NumberTitle','off', ...
              'Visible','off', ...
              'BackingStore','off');
           set(figmovie,'Position',[100 100 840 480]);
           % General a movie matrix to record each frame
           M = moviein(m*n);
           
           vmax=1;
           vmin=0;
           imax=1;
           imin=0;
        
           for i=1:m*n
               i=i-1;
               peri=floor(i/n)+1; % The nth period of the wave
               nperi=floor((peri+1)/2); % Make 2*nperi-1=peri;
               Vforward=gamma0*V0*(1-(gammas*gammaL)^nperi)/(1-gammas*gammaL);
               Vbackward=gammaL*Vforward;
               v=(Vforward+Vbackward);
               i=(Vforward-Vbackward);
               if v>vmax
                   vmax=v;
               end
               if v<vmin
                   vmin=v;
               end
               if i>imax
                   imax=i;
               end
               if i<imin
                   imin=i;
               end
           end
           Isrange=[0 m 1.1*imin 1.1*imax*V0];
           ILrange=[0 m 1.1*imin 1.1*imax*V0];
           Ixrange=[0 1 1.1*imin 1.1*imax*V0];
           Vsrange=[0 m 1.1*vmin 1.1*vmax*V0];
           VLrange=[0 m 1.1*vmin 1.1*vmax*V0];
           Vxrange=[0 1 1.1*vmin 1.1*vmax*V0];
           for i=1:m*n
               i=i-1;
               posi=mod(i,n); % The position of the wave front on tansmission line
               peri=floor(i/n)+1; % The nth period of the wave
               nperi=floor((peri+1)/2); % Make 2*nperi-1=peri;
               Vforward=gamma0*V0*(1-(gammas*gammaL)^nperi)/(1-gammas*gammaL);
               Vbackward=gammaL*Vforward;
               
               if nperi == 0
                   Vbackward0=0;
               else
                   Vbackward0=gammaL*gamma0*V0*(1-(gammas*gammaL)^(nperi-1))/(1-gammas*gammaL);
               end
               
               Vs(i*cont+1:(i+1)*cont)=Vforward+Vbackward0;
               Is(i*cont+1:(i+1)*cont)=(V0-(Vforward+Vbackward0));
               VLt((i+n)*cont+1:(i+n+1)*cont)=Vforward+Vbackward;
               ILt((i+n)*cont+1:(i+n+1)*cont)=Vforward-Vbackward;
               VL((i)*cont+1:(i+1)*cont)=VLt((i)*cont+1:(i+1)*cont);
               IL((i)*cont+1:(i+1)*cont)=ILt((i)*cont+1:(i+1)*cont);
               
               if mod(peri,2)==1
                   Vx((posi)*cont+1:(posi+1)*cont)=Vforward+Vbackward0;
                   Ix((posi)*cont+1:(posi+1)*cont)=Vforward-Vbackward0;
               else
                   Vx(n*cont-(posi+1)*cont+1:n*cont-posi*cont)=Vbackward+Vforward;
                   Ix(n*cont-(posi+1)*cont+1:n*cont-posi*cont)=Vforward-Vbackward;
               end
               
               % Plot the voltage and current on the transmission line 
               subplot(2,3,3);
               plot(x,Vx);
			   xlabel('x/d');
			   ylabel('V(x,t)/V_0');
			   title('Voltage on the Transmission Line');
			   axis(Vxrange);
               
               subplot(2,3,6);
               plot(x,Ix);
			   xlabel('x/d');
			   ylabel('I(x,t)Z_0/V_0');
			   title('Current on the Transmission Line');
			   axis(Ixrange);
               
               % Plot the voltage and current on the source 
			   subplot(2,3,1);
			   plot(t(1:(i+1)*cont),Vs(1:(i+1)*cont));
			   xlabel('t = d/c');
			   ylabel('V_s/V_0');
			   title('Source Side Voltage');
			   axis(Vsrange);
               
               subplot(2,3,4);
			   plot(t(1:(i+1)*cont),Is(1:(i+1)*cont)*z0/Rs);
			   xlabel('t = d/c');
			   ylabel('I_sZ_0/V_0');
			   title('Current through Source Resistor');
			   axis(Isrange);
               
               % Plot the voltage and current on the load 
               subplot(2,3,2);
			   plot(t(1:(i+1)*cont),VL(1:(i+1)*cont));
			   xlabel('t = d/c');
			   ylabel('V_L/V_0');
			   title('Load Voltage');
			   axis(VLrange);
               
               subplot(2,3,5);
			   plot(t(1:(i+1)*cont),IL(1:(i+1)*cont));
			   xlabel('t = d/c');
			   ylabel('I_LZ_0/V_0');
			   title('Load Current');
			   axis(ILrange);
               M(:,i+1) = getframe(gcf);
           end
           
       end
       
   elseif Retype==2
       % Define the constant to draw for pure capacitance and pure inductance
       cont=10; % The number of points in each step
       n=Speed; % The steps for a time peroid       
       m=160/n; % The total period to show
%        n=n*cont/4;
       z0=100;
       z0=100; % The character impedance of transmission line (ohm)
       V0=1; % The voltage of the source (V)       
       Julia=Re2; % Load type use my wife's name
       tit1=strvcat(['Voltage across the Capacitor'],['Voltage across the Inductor']);
       tit2=strvcat(['Current through the Capacitor'],['Current through the Inductor']);
       VC=zeros(1,n*m*cont); % Voltage on load
       IC=zeros(1,n*m*cont); % Current on load
       Out=zeros(2,n*m*cont);
       Sout=zeros(2,n*m*cont);
       Lineout=zeros(2,n*m*cont);
       t=linspace(0,m,m*n*cont);
       x=linspace(0,1,n*cont);
       
       if Julia==1977
           C=Re1;
           tau=z0*C;
           Lei=1;
           
       elseif Julia==817
           L=Re1;
           tau=L/z0;
           Lei=2;
           
       end
       
       figmovie=figure( ...
          'Name','Voltage on Transmission Line', ...
          'NumberTitle','off', ...
          'Visible','off', ...
          'BackingStore','off');
       set(figmovie,'Position',[100 100 840 480]);
       M = moviein(m*n);
       
       n = n*cont;
       for i=1:m*n
           
           Lineout(1,mod(i-1,n)+1)=V0/2;
           Lineout(2,mod(i-1,n)+1)=V0/2;
           tu(1,mod(i-1,n)+1)=V0/2;
           tu(2,mod(i-1,n)+1)=V0/2;
           
           if i>(n)
               VC(i)=1-exp(-(i-n)/n/tau);
               IC(i)=exp(-(i-n)/n/tau);
               Out(1,i)=VC(i);
               Out(2,i)=IC(i);
               
               if i>2*n
                   Lineout(1,i-n+1:i)=Out(1,i-n+1:i);
                   Lineout(2,i-n+1:i)=Out(2,i-n+1:i);
                   tu(1,:)=Out(1,i-n+1:i);
                   tu(2,:)=Out(2,i-n+1:i);
               else
                   j=i-n;
                   tu(1,n-j+1:n)=Out(1,i-j+1:i);
                   tu(2,n-j+1:n)=Out(2,i-j+1:i);
               end
               
           end
           
           Sout(1,i)=tu(1,1);
           Sout(2,i)=tu(2,1);
       end
       n=n/cont;
       HeHe(1:n*cont) = V0/2;
       HeHe(n*cont+1:2*n*cont) = 0;
       for j = 1:m*n
           i = j*cont;
                
           % Plot the voltage and current on the transmission line 
           subplot(2,3,3);
           if j>n
               plot(x,Lineout(Lei,i-n*cont+1:i));
           else
               plot(x,HeHe(n*cont+1-i:2*n*cont-i));
           end
		   xlabel('x/d');
		   ylabel('V(x,t)/V_0');
		   title('Voltage on the Transmission Line');
		   axis([0 1 0 1.1*V0]);
           
           subplot(2,3,6);
           if j>n
               plot(x,Lineout(mod(Lei,2)+1,i-n*cont+1:i));
           else
               plot(x,HeHe(n*cont+1-i:2*n*cont-i));
           end
           xlabel('x/d');
		   ylabel('I(x,t)Z_0/V_0');
		   title('Current on the Transmission Line');
		   axis([0 1 0 1.1*V0]);
           
           %Plot the voltage and current on the source 
		   subplot(2,3,1);
		   plot(t(1:i),Sout(Lei,1:i));
		   xlabel('t = d/c');
		   ylabel('V_s/V_0');
		   title('Source Side Voltage');
		   axis([0 m 0 1.1*V0]);
           
           subplot(2,3,4);
		   plot(t(1:i),Sout(mod(Lei,2)+1,1:i));
		   xlabel('t = d/c');
		   ylabel('I_sZ_0/V_0');
		   title('Current through Source Resistor');
		   axis([0 m 0 1.1*V0]);
           
           %Plot the voltage and current on the load 
           subplot(2,3,2);
           plot(t(1:i),Out(Lei,1:i));
		   xlabel('t = d/c');
		   ylabel('V_L/V_0');
		   title(tit1(Lei,:));
		   axis([0 m 0 1.1*V0]);
           
		   subplot(2,3,5);
		   plot(t(1:i),Out(mod(Lei,2)+1,1:i));
		   xlabel('t = d/c');
		   ylabel('I_LZ_0/V_0');
		   title(tit2(Lei,:));
		   axis([0 m 0 1.1*V0]);

         
           M(:,j) = getframe(gcf);
           
       end
       
   end   

end