%% Image Alignment Part 1: Pick single elements
% 20180407-Hannah S. Heil, AG Heinze, RVZ, University of Würzburg
% ORCID: 0000-0003-4279-7022, hannah.heil@uni-wuerzburg.de
% Pick single Elements in reconstructed Image and save related localizations in
% singel textfile
% Input: Tiff image of reconstructed image, localizations file
% (id,"frame","x [nm]","y [nm]","sigma [nm]","intensity [photon]","offset [photon]","bkgstd [photon]","chi2","uncertainty [nm]","detections")
% Output: .txt files with localization data of singel elements, image with
% markers for each element
clear all
close all

%% Import Image
disp('Open Image')
% Set path directory via standard GUI interface
[FileName, PathName] = uigetfile('*.tif','Image');
fullpath = fullfile(PathName,FileName);                                     % Create full path adress
Image=imread(fullpath); % open source image
disp(FileName)

    clear fullpath FileName;

% Pixelsize
disp('Pixelsize in reconstructed image')
prompt = {'Pixelsize in reconstructed image in nm'};
dlg_title = 'Pixelsize [nm]';
num_lines = 1;
def = {'5.1'};
info = inputdlg(prompt,dlg_title,num_lines,def);
Pixelsize=str2num(info{1});

% Filename base
disp('Filename')
prompt = {'Filename'};
dlg_title = 'Filename';
num_lines = 1;
def = {'20170718_Sub1_33'};
info = inputdlg(prompt,dlg_title,num_lines,def);
Filename=(info{1});

% Open localizations file
disp('Open Localization Data')
    % Set path dir via standard GUI interface
[FileNameTD, PathNameTD] = uigetfile('*.csv','Localization Data');
fullpathTD = fullfile(PathNameTD,FileNameTD); % Erzeuge full path adress
LocData=csvread(fullpathTD,1,0);   % Open data
clear fullpathTD FileNameTD PathNameTD;
    %clear fullpath FileName PathName;

% Figure of reconstructed image

PixelsizeX=103.75/20;
PixelsizeY=100.2/20;

Xarray=1+0.5:1:size(Image,1)+0.5; % Array with pixel center index
Yarray=1+0.5:1:size(Image,2)+0.5;
Xarray=Xarray*PixelsizeX; % Array with pixel center index in nm
Yarray=Yarray*PixelsizeY;
Cmax=0.2*(max(max(Image)));

%Message = msgbox('Pick center postions in figure and finish with right click.');

figure(1)
clf
hold on
imagesc(Xarray,Yarray,Image) % draw image
colormap(hot)
%colormap(flipud(gray)) % color with inverted gray scale
axis square % plot formate square
caxis([0 Cmax])
xlim([0 12000])
ylim([0 12000])
%scatter(SelElement(:,3),SelElement(:,4),'xg');
set(gcf,'units','normalized','outerposition',[0 0 1 1])
%scatter(LocData(1:(ceil(0.5*size(LocData,1))),3),LocData(1:(ceil(0.5*size(LocData,1))),4),'xg');

ax = gca;
fig = ancestor(ax, 'figure');
CenterPos = []; % Picked Center Positions
hold(ax, 'on');
Index=1;

% Pick center postions in figure, finish with right click
while true
  c = ginput(1);
  sel = get(fig, 'SelectionType');
  if strcmpi(sel, 'alt'); break; end
  scatter(c(1),c(2));
  rectangle('Position',[c(1)-110,c(2)-110,220,220],...
         'EdgeColor','g','LineWidth',2)
  textstr=[num2str(Index)];
    text(double(c(1)+115),double(c(2)+115),textstr,'Color','w','FontSize', 12) % add index to each filament
  CenterPos=[CenterPos;c];
  Index=Index+1;
end
clear c
% save figure
ImageFileNameFig=[PathName Filename '_RingSelection.fig'];
ImageFileNamepng=[PathName Filename '_RingSelection.png'];
saveas(1,ImageFileNameFig)
saveas(1,ImageFileNamepng)


SelElement=[];
%% Save selected elements localization data in .txt file
for n=1:size(CenterPos,1) %loop through all elements
    tic
    SelElement=LocData((LocData(:,3)>=CenterPos(n,1)-120)& (LocData(:,3)<= CenterPos(n,1)+120)&(LocData(:,4)>=CenterPos(n,2)-120)&(LocData(:,4)<=CenterPos(n,2)+120),:);
    SelElementNorm=SelElement;
    SelElementNorm(:,3)=SelElementNorm(:,3)-CenterPos(n,1)+120;
    SelElementNorm(:,4)=SelElementNorm(:,4)-CenterPos(n,2)+120;
    %save .txt file
    FullName=[PathName Filename '_Element' num2str(n) '.txt'];
    FullNameNorm=[PathName Filename '_Norm_Element' num2str(n) '.txt'];
    save(FullName,'SelElement','-ascii')
    save(FullNameNorm,'SelElementNorm','-ascii')
    %scatter(SelElement(:,3),SelElement(:,4),'xg');
    SelElement=[];
    clear c
    toc
    %figure of single element
    figure(2)
    clf
    hold on
    imagesc(Xarray,Yarray,Image)% draw image
    xlim([CenterPos(n,1)-120 CenterPos(n,1)+120])
    ylim([CenterPos(n,2)-120 CenterPos(n,2)+120])
    colormap(hot)
    axis square % plot formate square
    caxis([0 Cmax])
    axis off
    %scatter(SelElement(:,3),SelElement(:,4),'xg');
    title([Filename ': Element' num2str(n)])
    ImageFileNamepng2=[PathName Filename '_Element' num2str(n) '.png'];
    saveas(2,ImageFileNamepng2)
end
