+ head_number(state, i, &heads[nheads++]);
+ }
+
+ /* Sort that array:
+ * - heads with preferred colours first, then
+ * - heads with low colours first, then
+ * - large regions first
+ */
+ qsort(heads, nheads, sizeof(struct head_meta), compare_heads);
+
+ /* Remove duplicate-coloured regions. */
+ for (n = nheads-1; n >= 0; n--) { /* order is important! */
+ if ((n != 0) && (heads[n].start == heads[n-1].start)) {
+ /* We have a duplicate-coloured region: since we're
+ * sorted in size order and this is not the first
+ * of its colour it's not the largest: recolour it. */
+ heads[n].start = START(lowest_start(state, heads, nheads));
+ heads[n].preference = -1; /* '-1' means 'was duplicate' */
+ }
+ else if (!heads[n].preference) {
+ assert(heads[n].start == 0);
+ heads[n].start = START(lowest_start(state, heads, nheads));
+ }
+ }
+
+ debug(("Region colouring after duplicate removal:"));
+
+ for (n = 0; n < nheads; n++) {
+ debug((" Chain at (%d,%d) sz %d numbered at %d (colour %d): %s%s",
+ heads[n].i % state->w, heads[n].i / state->w, heads[n].sz,
+ heads[n].start, COLOUR(heads[n].start), heads[n].why,
+ heads[n].preference == 0 ? " (next available)" :
+ heads[n].preference < 0 ? " (duplicate, next available)" : ""));
+
+ nnum = heads[n].start;
+ j = heads[n].i;