%% Wrote by Q. Peter Su on Mar 29 2013
%  Used to delete the dots/localizations in the *.dat file
%  as the BF-frame-index.txt output by the ST22_IndexBF_and_GenDrift

%% Input
%   1. BF Index.txt file output by ST22_IndexBF_and_GenDrift(Xpixel,Ypixel) 
%   2. dat file of Dots/Localizations output by Insight or Matlab

%% Output
%  1. new deleted BF *.dat file
%  2. raw image and deleted image

%% Revised by Q.Peter Su on Apr 11 2013
%  Delete Dots in former 5 frames and later 5 frames of BF index 
%% Revised by Q.Peter Su on May 20 2013
%  ST11_2_DeleteBFframe(Afname)


function ST11_2_DeleteBFframe(Afname)
[FileNameIndex, PathNameIndex] = uigetfile('*BfIndex.txt',...
    'Index File Output by ST22_IndexBF_and_GenDrift','MultiSelect','off');
AfnameIndex=char(FileNameIndex);
cd(PathNameIndex);disp(PathNameIndex);disp(FileNameIndex);
BFIndex = importdata(AfnameIndex);

if nargin<1
[FileName, PathName] = uigetfile('*.dat',...
    '*.dat file of dots/localizations in STORM imaging','MultiSelect','off');
Afname=char(FileName);
end

disp(Afname);
DataAll = importdata(Afname);

%%
DataOut=DataAll;
%k=0;
index=[];
for i=1:length(BFIndex)
    range=BFIndex(i)-5 : BFIndex(i)+5;
    for j=1:11
        indextemp=find(DataAll(:,12)==range(j));
        index=[index;indextemp];
    end
end
DataOut(index,:)=[];
deletepoint=size(DataAll,1)-size(DataOut,1);
str=['Totally, there are -' num2str(deletepoint) '- dots deleted from the movie.'];
disp(str);
%%
outfile = [Afname(1:end-4)];
outfilename = [outfile '-DelBF.dat'];
save(outfilename, 'DataOut', '-ascii', '-tabs');
%%
close all
figure1 = figure;
%whitebg([0 0 0])
axes1 = axes('Parent',figure1,'YDir','reverse',...
    'PlotBoxAspectRatio',[434 342.3 42.7875],...
    'DataAspectRatio',[1 1 1]);
box on
hold(axes1,'all');

plot(DataAll(:,1),DataAll(:,2),'r.');hold on
plot(DataOut(:,1),DataOut(:,2),'g.');hold off
axis equal
xlabel('X in um');
ylabel('Y in um');
title([Afname(1:end-4),sprintf('\n'),'Red-Raw Data. Green-Deleted Final Iamge.'],...
    'FontWeight','bold',...
    'FontSize',14);
figurefilename = strcat(outfile, '-DelBF.fig'); 
saveas(gcf,figurefilename);

end