algorithm to fill histograms