% AF_3D.m - matab script to create 2D contour & 3D surface D-3M movie frames
%
clear all
clc
%%%% Input File %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
file2load='a2nn.dat';
%%%%% Main Parameters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
T=1200.0;      % sec time interval to display in one frame
Tshift=300;  % sec time shift between frames 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Movie frames will be stored in Sleep3D folder:
ImageDIR='AF_3D_2';
mkdir(ImageDIR);

f2l=load(file2load);
t=f2l(:,2);
t=t-t(1);
rr=f2l(:,1);

minRR=0.2;
maxRR=1.5;

minRR1=0.2;
maxRR1=1.5;

scrsz = get(0,'ScreenSize');

k1=1;
k2=find(t>=T,1);
% Kmax=2002; % max number of frames
Kmax=100000; % max # of frames

for k=1:Kmax

    t1=t(k1);
    t2=t(k2);

    t_disp=t(k1:k2);
    rr_disp=rr(k1:k2);

    y1=rr_disp(1:end-1);
    y2=rr_disp(2:end);

    figure
    [ctrs1, ctrs2, F, hAxes] = dscatter2(y1,y2,'PLOTTYPE','contour');
    close

    fig1=figure('Position',...
    [0.05*scrsz(3) 0.05*scrsz(4) 0.8*scrsz(3) 0.89*scrsz(4)],...
    'Color',[0 0 0]);
    colormap jet
       
    subplot(4,1,[1 2])
    surf(ctrs1, ctrs2, F, 'FaceColor','interp',...
    'EdgeColor','none',...
    'FaceLighting','phong')
    xlim([minRR maxRR])
    ylim([minRR maxRR])
    colormap jet
    view(5,65)
    axis off
    subplot(4,1, 3)
    contour(ctrs1, ctrs2, F,'LineWidth',2,'LevelStep',0.00015)
    view(5,90)
    colormap jet

    xlim([minRR maxRR])
    ylim([minRR maxRR])
    zlim([0.0  0.001])
    axis off
   
    subplot(4,1,4)
    plot(t_disp,rr_disp,'r','LineWidth',2.0)
    xlim([(min(t_disp)-60) (max(t_disp)+60)])
%     xlim([(min(t_disp)) (max(t_disp))])
    ylim([minRR1 maxRR1])
    axis off
 
    % capture frame here 
    Fr1=getframe(fig1);
    [Im1, Im1_map]=frame2im(Fr1);

    im_file=[ImageDIR '\' int2str(k) '.bmp'];
    imwrite(Im1,im_file);
    
    clear Fr1 Im1 Im1_map im_file;
    close(fig1);
    
    k1=find(t>=t1+Tshift,1);
    k2=find(t>=t2+Tshift,1);
end

