filename = 'corrected_026_g.asc'
col_pres = 1;
binmode = 'median'

z0 = 1.0	% midpoint of topmost bin
dz = 0.5	% bin spacing
zmax = []; % determine automagically
% for example z0=1.0 and dz=0.5 yields bins [0.75,1.25) [1.25,1.75)
% [1.75,2.25) ...

data = textread(filename);

zmax = ceil(max(data(:,col_pres))/z0)*z0

binz = z0:dz:zmax

bdata = nan(length(binz),size(data,2)+1);

for kb = 1:length(binz)
	
	zlo = binz(kb)-0.5*dz;
	zhi = binz(kb)+0.5*dz;
	matches = data(:,col_pres)>=zlo & data(:,col_pres)<zhi;
	nsamp = length(find(matches))
	
	if strcmpi(binmode,'median')
		tmp = nanmedian(data(matches,:));
	elseif strcmpi(binmode,'mean')
		tmp = nanmean(data(matches,:));
	elseif strcmpi(binmode,'std')
		tmp = nanstd(data(matches,:));
		error('Invalid binmode')
	end
	bdata(kb,:) = [tmp nsamp];

end

bdata(:,col_pres) = binz;


bfilename = strrep(filename, 'corrected', 'binned')
dlmwrite(bfilename, bdata, 'delimiter','\t','precision','%g')
