Compute optimal number of bins, fix corner cases.