improved average_in_bins subfunction