function FDM_tapsim( detx, dety,  RES, sm, fsize, SaveFileName)
%This function plots a field desorption map of inputted detector
%co-ordinates. Note slices ~ 1-2 million atoms usually show clearest FDM

% Author: Andrew Breen, MPIE, 09/07/2018

%detx - inputted X co-ordinates
%dety - inputted Y co-ordinates
%RES - the number of bins in SDM along each axis, usually ~ 500
%col - colour profile for FDM e.g. 'jet', 'default', 'autumn' 
%sm - smooth SDM? (1 = yes, 0 = no)
%fsize - font size, usually ~ 30
%SaveFileName - file name of outputted FDM. Note figure saved in .tif, .eps
%takes too long to save


%note - good conditions were observed for RES = 280, 200 slices, ~2 million
%atoms per slice. Have slices overlap for smoother transistion.


%% calculating bin centers for FDM

%mi = min(min(detx),min(dety));
%mx = max(max(detx),max(dety));

mi = -1;
mx = 1;



ctr{1} = linspace(mi,mx,RES);
ctr{2} = ctr{1};

%% plot the FDM
fig_dim_x = 10;
fig_dim_y = 10;

fig = figure('Units', 'centimeters');
fig.Position = [5,5,fig_dim_x, fig_dim_y];

f_size = 9;

FDM = hist3([dety; detx]',ctr); % note: for the hist3 function, Y must be in the first column and X in the second column

%[FDM, xedges, yedges] = histcounts2(detx,dety, RES);

%FDM = hist3([detx; dety]', 'Ctrs', ctr, 'CDatamode', 'auto', 'Facecolor',
%'interp'); %for some reason this appears to be wrong!!!!

%hist3([detx; dety]', 'Ctrs', ctr, 'CDatamode', 'auto', 'Facecolor', 'interp');

%h = pcolor(xb,yb,N);

if sm == 1
    %FDM = smoothn(FDM,'robust');
    FDM = smoothn(FDM, 0.1);
end 
    
    surf(meshgrid(ctr{1}), meshgrid(ctr{1})', FDM)
    %surf(xedges(1:end-1)+norm(xedges(1)-xedges(2)), yedges(1:end-1)+norm(xedges(1)-xedges(2)), FDM);
    %colormap 'hot'
    %colormap hot
    %colormap jet
    shading interp
    view(2)
    axis square
    grid off
    colorbar off
    %xlabel('Detector X position (mm)','fontsize',fsize)
    %ylabel('Detector Y position (mm)','fontsize',fsize)
    ax1 = gca;
    set(ax1,'XColor','k','YColor','k','fontsize',fsize,'linewidth', 2, 'box','on');
    %set(ax1,'XColor','k','YColor','k','fontsize',fsize,'linewidth', 2, 'box','on', 'XTickLabel', [], 'YTickLabel', []);
    %axis off
    %xlim([min(detx) max(detx)])
    %ylim([min(dety) max(dety)])
    %xlim([-0.2 0.2])
    %ylim([-0.2 0.2])
    
    xlim([-0.05 0.05]);
    ylim([-0.05 0.05]);
    
    set(gcf, 'PaperPositionMode','auto');
    set(gcf, 'InvertHardCopy', 'off');
    set(gcf, 'color', 'white');
    %axis off
    %set(gca, 'position', [0 0 1 1], 'units', 'normalized');
    %axis normal
    %axis equal
    f = getframe(gcf);       
    %imwrite(f.cdata,SaveFileName ,'jpg');
    export_fig(SaveFileName, '-png', '-r500');
    export_fig(SaveFileName, '-jpg', '-r500');
    %export_fig SaveFileName '-eps' 
end

