%% rahul: Aug15, 2011
% opens a .tif stack file and shows localizations per frame

%% Revised by Q Peter Su on Nov 13 2012
%  press e to exit the code

function ST01_ViewPointFits2()

[FileName,PathName] = uigetfile('*.tif',...
               'Select original *.tif file to view STORM localizations',...
               'MultiSelect', 'off');
cd(PathName);
display(FileName);
datafile = uigetfile('*.dat','Select .dat file for STORM localizations',...
                      'MultiSelect', 'off');
Frm = input('Range of frames to load [Start End] (between 1 and 400)'); 
Start = Frm(1); End = Frm(2); index = (Start:1:End); 
%% Figure
scrsz = get(0,'ScreenSize');
figure('OuterPosition',[1 0.25*scrsz(4) 0.75*scrsz(4) 0.75*scrsz(4)]);
hdl1=gcf;
clf;
figure('OuterPosition',[0.6*scrsz(3) scrsz(4)/2 scrsz(4)/2 scrsz(4)/2]);
hdl2 = gcf;
clf;
%%
Afname=char(FileName);
TT = (Afname(end-2:end)=='tif');
if TT
    fname=Afname(1:end-4)
    images = arrayfun(@(image) double(image.data),...
          tiffread30(FileName,index), 'UniformOutput', false);   
    Data = importdata(datafile);
else
    'incorrect stack file selected'
end
%% First figure
      figure(hdl2);
      scatter(Data(:,1),Data(:,2),2,Data(:,4), 'filled');
      title([ 'file:' fname]);
      axis ij;
      colormap;
      grid on;
      zoom on;
%% 
j= Start-1;
i = 0;
while (j< End)
    j = j+1;     i = i+1;    
    figure(hdl1);
    imagesc(images{i});
    colormap(gray);
    title(['Frame Number ' num2str(j)]);
    hold on;
           
    frameSel = Data(:,11) == j;
    xx = Data(frameSel,1) -1;
    yy = Data(frameSel,2) -1;
    scatter(xx, yy,'r.');
    hold off;
%%%%%%% judge CRR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%           
    disp('press f to fast forward(10), press g to go to X frame')
    CRR=input('press p to previous frame, and press e to exit  ','s');
    
    if CRR=='f'					%fast forward
        j = j+10;
    end
    if CRR=='g'					%to skip to a designated molecule
        nml = input('which molecule?');
        j=nml - 1;      
    end   
    if CRR=='p'				    %to go back to the previous molecule
        j=j-2;
    end
    if CRR=='e'                 % exit the code
        j=End;
    end
end
end
