+ half bin widths, so that the labels are aesthetically pleasing ones.
+ Otherwise we are likely to get labels such as -3 -1 1 3 instead of -2 0 2 4
+ */
+ if ( lower_limit % 2 == 0)
+ {
+ /* If there is not enough slack at either end to perform a shift,
+ then we must extend the range so that there is. We must extend
+ by two half bin widths in order to preserve the EVEN condition
+ established above. Also, we extend on the end with the least
+ slack, in order to keep things as balanced as possible. */
+ if ( upper_slack > lower_slack && upper_slack <= half_bin_width)
+ {
+ lower_limit -= 2;
+ lower_slack += 2 * half_bin_width;
+ }
+
+ if (lower_slack > upper_slack && lower_slack < half_bin_width)
+ {
+ upper_limit += 2;
+ upper_slack += 2 * half_bin_width;
+ }
+
+ if (upper_slack > lower_slack)
+ {
+ testing_assert (upper_slack > half_bin_width);
+
+ /* Adjust the range to the left */
+ lower_limit --;
+ upper_limit --;
+ upper_slack -= half_bin_width;
+ lower_slack += half_bin_width;
+ }
+ else
+ {
+ testing_assert (lower_slack >= half_bin_width);
+
+ /* Adjust the range to the right */
+ lower_limit ++;
+ upper_limit ++;
+ lower_slack -= half_bin_width;
+ upper_slack += half_bin_width;
+ }
+ }
+
+ /* If there are any completely empty bins, then remove them,
+ since empty bins don't really add much information to the histogram.
+ */
+ if (upper_slack > 2 * half_bin_width)
+ {
+ upper_slack -= 2 * half_bin_width;
+ upper_limit -=2;
+ }
+
+ if (lower_slack >= 2 * half_bin_width)
+ {
+ lower_slack -= 2 * half_bin_width;
+ lower_limit +=2;
+ }
+
+ *adj_min = lower_limit * half_bin_width;
+ *adj_max = upper_limit * half_bin_width;
+
+ testing_assert (*adj_max > max);
+ testing_assert (*adj_min <= min);
+
+ return (upper_limit - lower_limit) / 2.0;
+}
+
+
+
+struct histogram *
+histogram_create (double bin_width, double min, double max)
+{
+ const int MAX_BINS = 25;
+ struct histogram *h;
+ struct statistic *stat;
+ int bins;
+ double adjusted_min, adjusted_max;
+
+ if (max == min)
+ {
+ msg (MW, _("Not creating histogram because the data contains less than 2 distinct values"));
+ return NULL;
+ }
+
+ assert (bin_width > 0);
+
+ bin_width = chart_rounded_tick (bin_width);
+ bins = adjust_bin_ranges (bin_width, min, max, &adjusted_min, &adjusted_max);
+
+ /* Force the number of bins to lie in a sensible range. */
+ if (bins > MAX_BINS)