%%
clear

DISP = 25285;
[ tI, yI ] = leia_TCABR( DISP, 'IP' );
[ tn, yn ] = leia_TCABR( DISP, 'ne' );
[ tM, yM ] = leia_TCABR( DISP, 'Mref' );

figure( 'position', [50 50 800 650] )
handle_MASTER = subplot( 5, 1, 1:3 );
plot( tI, yI*1e-3, '-b', tn, yn*1e-20, '-r', tM, yM/10, '-k' )
xlim( [25 160] )
ylim( [-0.1 0.2] )
ylabel( 'I_P (MA), n_e (10^{20}m^{-3}), Mirnov (a.u.)', 'fontsize', 16 )
% xlabel( 'time (ms)', 'fontsize', 16 )
% legend( 'I_P', 'n_e', 'Mirnov', 'fontsize', 14 )
title( sprintf( 'TCABR #%d', DISP ), 'fontsize', 16 )
set( gca, 'fontsize', 14, 'tickdir', 'out' )
XLIM_MASTER = xlim;
YLIM_MASTER = ylim;
hold on

handle_LINHA(4) = ...
    plot( handle_MASTER, [NaN NaN], YLIM_MASTER, [ '-m' ] );
handle_LINHA(5) = ...
    plot( handle_MASTER, [NaN NaN], YLIM_MASTER, [ '-b' ] );

VALENDO = 1;
while( VALENDO )
    [X,Y,BUTTON] = ginput(1);
    SUBPLOTATIVO = 0;
    if isempty( BUTTON ), BUTTON = ' '; end
    switch( BUTTON )
        case{ '1' }
            SUBPLOTATIVO = 4;
            CORATIVA = 'm';
        case{ '2' }
            SUBPLOTATIVO = 5;
            CORATIVA = 'b';
        case{ 'q' 'f' 27 }
            VALENDO = 0;
    end
    if SUBPLOTATIVO>0
        subplot( 5, 1, SUBPLOTATIVO )
        indSEL = find( tM>=X(1) & tM<=(X(1)+1) );
        plot( tM( indSEL ), yM( indSEL ), ['-' CORATIVA] )
        axis tight
        set( handle_LINHA(SUBPLOTATIVO), 'XData', [X(1) X(1)] )
        
        t = tM( indSEL );
        Yfit = yM( indSEL );
        ind0up = find( Yfit(1:end-1)<0 & Yfit(2:end)>=0 );
        T = median( diff( t(ind0up) ) );
        Ts = T+.1*T*(-1:.1:1);
        for qTs = 1:length(Ts)
            Xfit = [ cos( 2*pi*t/Ts(qTs) )  sin( 2*pi*t/Ts(qTs) ) ];
            [ A, sA, Q2(qTs), NGL, VA, Fs(:,qTs) ] = mmqLINCOV( Xfit, Yfit, ones(size(Yfit)) );
        end
        Tfit = Ts( Q2==min(Q2) );
        ylabel( sprintf( 'T=%.2f f=%.1f', Tfit, 1./Tfit ) )
        hold on
        plot( t, Fs(:, Q2==min(Q2) ), '-r' )
        hold off
        axes( handle_MASTER )
    end
end