% Sleep2D.m - matab script to crate 2D contour D-3M movie frames
%
clear all
clc
%%%% Input File %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
file2load='a2nn.dat';
%%%%% Main Parameters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
T=1200.0/60.0;      % sec/60=min time interval to display in one frame
Tshift=300.0/60.0;  % sec/60=min time shift between frames (if no overlap => Tshift=T)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Movie frames will be stored in Sleep2D folder:
ImageDIR='a2nn_2D';
mkdir(ImageDIR);

f2l=load(file2load);
t=f2l(:,2);
t=t-t(1);
t=t/60.0; % sec2min
rr=f2l(:,1);

scrsz = get(0,'ScreenSize');

k1=1;
k2=find(t>=T,1);
Kmax=2002000; % max # of frames
% Kmax=5; % 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);

    [ctrs1, ctrs2, F, hAxes] = dscatter2(y1,y2,'PLOTTYPE','contour');
    close
    F = F./max(F(:));
 
    fig1=figure('Position',...
    [0.05*scrsz(3) 0.05*scrsz(4) 0.3*scrsz(3) 0.8*scrsz(4)],...
    'Color',[1 1 1]);

    subplot(4,1,[1 3])
    contour(ctrs1, ctrs2, F,'LineWidth',2,'LevelStep',0.015)
    colorbar;
    xlim([0.3 1.5])
    ylim([0.3 1.5])
    grid on
    axis square
    title('Contour Map');
    xlabel('RR(n), sec');
    ylabel('RR(n+1), sec');   
    
    subplot(4,1,4)
    plot(t_disp,rr_disp,'r','LineWidth',1.5)
    grid on
    xlim([min(t_disp) max(t_disp)])
    ylim([0 2])
    title('Cardiac Interbeat Interval Time Series');
    ylabel('RR, sec');
    xlabel('Time, min');
    
    % 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

