clear;
clc;

% Transmission line
% Movie of the transmitted and reflected waves
% Ideal or not (8.), r (13.)

ideal = 1;         % Ideal line (1) or not (0)

l   = 300000;      % Length = 300km
z   = [0:l/100:l]; % Points along the line

r   = 1;           % Reflexion coefficient at the end

R   = 5/1000;      % Ohm/m
L   = 2e-3/1000;   % H/m
G   = 0.5e-6/1000; % S/m
C   = 6e-9/1000;   % F/m

U2p = 0.3;         % U2+
if ideal,
    G=0; 
    R=0;
end;

f  = 5000;        % Frequncy
w  = 2*pi*f;      % Angular frequency

Z0 = sqrt( (R + j*w*L) / (G + j*w*C) );
Gm = sqrt( (R + j*w*L) * (G + j*w*C) );
L  = 2*pi/imag(Gm); % Wavelength
disp(['Wavelength = ' num2str(L/1000) 'km']);

U1p =     U2p * exp(Gm*l);
U1m = r * U2p * exp(-Gm*l);

% Movie
for i = 1:72,
    t   = i/f/72;
    Up  = U1p * exp(-Gm*z); % U+
    Um  = U1m * exp( Gm*z); % U-
    U   = real((Up + Um) * exp(j*w*t));
       
    Upt = real(Up * exp(j*w*t));
    Umt = real(Um * exp(j*w*t));
    
    figure(1), cla, hold on;
    plot(z,U,'r','LineWidth',2);
    plot(z,Upt,'b',z,Umt,'k');
    axis([0 l -1.2 1.2]);
    plot([L L],[-1.2 1.2],':r');
    legend('U^{+}(t)+U^{-}(t)','U^{+}(t)','U^{-}(t)');
    xlabel('z [m]');
    ylabel('u(z,t) [V]');
    title(['r = ' num2str(r)]);
    set(gca,'Box','on');
    saveas(gcf,['Transmission' num2str(i)],'bmp');
    pause(0.001);
end;