%% Modified by Q.Peter SU from ST08_1_fastmap
%




%%
function ST08_1_fastmap_2C_3D(Afname,x,y,Xpixel,Ypixel,Xsize,Ysize,bin,resolution)
%%
    xwidth  = Xsize* Xpixel/1000;
    yheight = Ysize* Ypixel/1000;
%% binning of data
    binsize = bin/1000.;   % binsize in um
    nxbins = ceil(xwidth/binsize);
    nybins = ceil(yheight/binsize);
    xc = linspace(0,xwidth, nxbins);
    yc = linspace(0,yheight, nybins)';    
    %IHis = zeros([length(xc) length(yc)]);
    IHis = hist2d(x, y, xc, yc);
%% gaussian convolution and centroid extraction
disp('------------------------------------------------------------------');
disp('... Gaussian Smooth ing ...');
GaussianBottom=ceil(resolution*3/bin); % unit - pixel
% resolution is 2.355fold of standard deviation (sigma)
% the bottome of the gaussian peak is 3-fold of resolution 
if mod(GaussianBottom,2)==1
    GaussianBottom=GaussianBottom;
else
    GaussianBottom=GaussianBottom+1;
end
GaussianStd=floor(GaussianBottom/6); % unit - pixel
if GaussianStd<1
    GaussianStd=1;
end
h1 = fspecial('gaussian', GaussianBottom , GaussianStd);
tic
IHisg = imfilter(IHis, h1); 
toc
norm = double(max(max(IHisg)));
nNorm = double(IHisg)./norm; 
tiffilename = strcat(Afname(1:end-4),'-Bin',num2str(bin),'-Res',num2str(resolution),'-Rend1w.tif');
%imwrite(uint16(10000*IHisg),tiffilename,'tif', 'Compression', 'none', 'WriteMode',  'overwrite');
imwrite(uint16(10000*nNorm),tiffilename,'tif', 'Compression', 'none', 'WriteMode',  'overwrite');
% 
% tiffilename = strcat(Afname(1:end-4),'-Bin',num2str(bin),'-Res',num2str(resolution),'-Rend6w.tif');
% imwrite(uint16(60000*nNorm),tiffilename,'tif', 'Compression', 'none', 'WriteMode',  'overwrite');
end