fid = popen("ffmpeg -y -r 25 -i - -vcodec libx264 Anim4.mkv", "w")

frame_name = [ tmpnam '.png' ];

randn("seed", 1234);

N = 100;
R = 0.4 * sqrt(rand(1,N));
P = rand(1,N) * 2 * pi;

X = [ linspace(0, 0.4, N); zeros(1,N) ];
Ellipse = [ 0.4 * cos(linspace(0, 2*pi, 100)) ; 0.4 * sin(linspace(0, 2*pi, 100)); ];

Beta = 7.84311; % mm/pi.mrad
Alpha = 0;

T = [ sqrt(Beta) 0 ; -Alpha/sqrt(Beta) 1/sqrt(Beta) ];
X = T * X;
Ellipse = T * Ellipse;

Nslice = 100;

Lq = 0.4;
Ld = 1.6;
Kf = 1.02780070155859;
E0 = 1;
E = 1;

kk = Kf * E0 / E; % 1/m**2
ksqrt = sqrt(kk);
dS = Lq / Nslice;
C = cos(ksqrt*dS);
S = sin(ksqrt*dS);
Ch = cosh(ksqrt*dS);
Sh = sinh(ksqrt*dS);
ksqrt_S  =  ksqrt*S;
ksqrt_Sh = -ksqrt*Sh;
S_over_ksqrt  =  S/ksqrt;
Sh_over_ksqrt = Sh/ksqrt;

Qf = [ C S_over_ksqrt ; -ksqrt_S C ];
Qd = [ Ch Sh_over_ksqrt ; -ksqrt_Sh Ch ];
D = [ 1 Ld/Nslice ; 0 1 ];

f = figure;
set(f, "visible", "off");

R = Qf;
title_str = 'F - O - D - O';

if false
    kk = Kf * E0 / E; % 1/m**2
    ksqrt = sqrt(kk);
    dS = Lq / 1;
    C = cos(ksqrt*dS);
    S = sin(ksqrt*dS);
    Ch = cosh(ksqrt*dS);
    Sh = sinh(ksqrt*dS);
    ksqrt_S  =  ksqrt*S;
    ksqrt_Sh = -ksqrt*Sh;
    S_over_ksqrt  =  S/ksqrt;
    Sh_over_ksqrt = Sh/ksqrt;
    
    Qf_full = [ C S_over_ksqrt ; -ksqrt_S C ];
    Qd_full = [ Ch Sh_over_ksqrt ; -ksqrt_Sh Ch ];
    D_full = [ 1 Ld ; 0 1 ];

    mu = acos(0.5 * trace(Qf_full * ...
                          D_full * ...
                          Qd_full * ...
                          D_full))
    mu_deg = mu/pi*180
end

for nCell=1:8
for i=1:(4*Nslice)
    
    if i>Nslice/2; R = D; title_str = 'O - D - O - F'; end
    if i>Nslice/2 + Nslice; R = Qd; title_str = 'D - O - F - O'; end
    if i>Nslice/2 + 2*Nslice; R = D; title_str = 'O - F - O - D'; end
    if i>Nslice/2 + 3*Nslice; R = Qf; title_str = 'F - O - D - O'; end
    
    X = R * X;
    Ellipse = R * Ellipse;

    clf;
    hold on
    plot(Ellipse(1,:), Ellipse(2,:), 'b-');
    plot(X(1,:), X(2,:), 'bo.');

    title(sprintf('cell #%d : %s', nCell, title_str));
    axis([ -1.5 1.5 -0.4 0.4 ]);
    xlabel('x [um]');
    ylabel('x'' [urad]');
    
    print(f, frame_name, '-dpng', '-S520,480', '-FTimes New Roman:8');
    fid2 = fopen(frame_name, 'r');
    buffer = fread(fid2);
    fwrite(fid, buffer);
    fclose(fid2);
end
end

delete(tmpnam);

fclose(fid);