Home | History | Annotate | Line # | Download | only in gomoku
pickmove.c revision 1.53
      1 /*	$NetBSD: pickmove.c,v 1.53 2022/05/29 10:37:21 rillig Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1994
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Ralph Campbell.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. Neither the name of the University nor the names of its contributors
     19  *    may be used to endorse or promote products derived from this software
     20  *    without specific prior written permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32  * SUCH DAMAGE.
     33  */
     34 
     35 #include <sys/cdefs.h>
     36 /*	@(#)pickmove.c	8.2 (Berkeley) 5/3/95	*/
     37 __RCSID("$NetBSD: pickmove.c,v 1.53 2022/05/29 10:37:21 rillig Exp $");
     38 
     39 #include <stdlib.h>
     40 #include <string.h>
     41 #include <curses.h>
     42 #include <limits.h>
     43 
     44 #include "gomoku.h"
     45 
     46 #define BITS_PER_INT	(sizeof(int) * CHAR_BIT)
     47 #define MAPSZ		(BAREA / BITS_PER_INT)
     48 
     49 #define BIT_SET(a, b)	((a)[(unsigned int)(b)/BITS_PER_INT] |= (1 << ((unsigned int)(b) % BITS_PER_INT)))
     50 #define BIT_TEST(a, b)	(((a)[(unsigned int)(b)/BITS_PER_INT] & (1 << ((unsigned int)(b) % BITS_PER_INT))) != 0)
     51 
     52 /*
     53  * This structure is used to store overlap information between frames.
     54  */
     55 struct overlap_info {
     56 	int		o_intersect;	/* intersection spot */
     57 	u_char		o_off;		/* offset in frame of intersection */
     58 	u_char		o_frameindex;	/* intersection frame index */
     59 };
     60 
     61 static struct combostr *hashcombos[FAREA];/* hash list for finding duplicates */
     62 static struct combostr *sortcombos;	/* combos at higher levels */
     63 static int combolen;			/* number of combos in sortcombos */
     64 static int nextcolor;			/* color of next move */
     65 static int elistcnt;			/* count of struct elist allocated */
     66 static int combocnt;			/* count of struct combostr allocated */
     67 static int forcemap[MAPSZ];		/* map for blocking <1,x> combos */
     68 static int tmpmap[MAPSZ];		/* map for blocking <1,x> combos */
     69 static int nforce;			/* count of opponent <1,x> combos */
     70 
     71 static bool better(spot_index, spot_index, int);
     72 static void scanframes(int);
     73 static void makecombo2(struct combostr *, struct spotstr *, int, int);
     74 static void addframes(unsigned int);
     75 static void makecombo(struct combostr *, struct spotstr *, int, int);
     76 static void appendcombo(struct combostr *, int);
     77 static void updatecombo(struct combostr *, int);
     78 static void makeempty(struct combostr *);
     79 static int checkframes(struct combostr *, struct combostr *, struct spotstr *,
     80 		    int, struct overlap_info *);
     81 static bool sortcombo(struct combostr **, struct combostr **, struct combostr *);
     82 #if !defined(DEBUG)
     83 static void printcombo(struct combostr *, char *, size_t);
     84 #endif
     85 
     86 int
     87 pickmove(int us)
     88 {
     89 
     90 	/* first move is easy */
     91 	if (game.nmoves == 0)
     92 		return PT((BSZ + 1) / 2, (BSZ + 1) / 2);
     93 
     94 	/* initialize all the board values */
     95 	for (unsigned pos = PT(BSZ, BSZ + 1); pos-- > PT(1, 1); ) {
     96 		struct spotstr *sp = &board[pos];
     97 		sp->s_combo[BLACK].s = 0x601;
     98 		sp->s_combo[WHITE].s = 0x601;
     99 		sp->s_level[BLACK] = 255;
    100 		sp->s_level[WHITE] = 255;
    101 		sp->s_nforce[BLACK] = 0;
    102 		sp->s_nforce[WHITE] = 0;
    103 		sp->s_flags &= ~(FFLAGALL | MFLAGALL);
    104 	}
    105 	nforce = 0;
    106 	memset(forcemap, 0, sizeof(forcemap));
    107 
    108 	/* compute new values */
    109 	nextcolor = us;
    110 	/*
    111 	 * TODO: Scanning for both frames misses that after loading the game
    112 	 *  K10 J9 M10 J10 O10 J11 Q10 J8 and playing K9, there are 2
    113 	 *  immediate winning moves J12 and J7. Finding the winning move
    114 	 *  takes too long.
    115 	 */
    116 	scanframes(BLACK);
    117 	scanframes(WHITE);
    118 
    119 	/* find the spot with the highest value */
    120 	spot_index s = PT(BSZ, BSZ);
    121 	spot_index s1 = s;
    122 	spot_index s2 = s;
    123 	for ( ; s-- > PT(1, 1); ) {
    124 		struct spotstr *sp = &board[s];
    125 		if (sp->s_occ != EMPTY)
    126 			continue;
    127 		if (debug != 0 && (sp->s_combo[BLACK].cv_force == 1 ||
    128 		    sp->s_combo[WHITE].cv_force == 1)) {
    129 			debuglog("- %s %x/%d %d %x/%d %d %d",
    130 			    stoc(s),
    131 			    sp->s_combo[BLACK].s, sp->s_level[BLACK],
    132 			    sp->s_nforce[BLACK],
    133 			    sp->s_combo[WHITE].s, sp->s_level[WHITE],
    134 			    sp->s_nforce[WHITE],
    135 			    sp->s_wval);
    136 		}
    137 		/* pick the best black move */
    138 		if (better(s, s1, BLACK))
    139 			s1 = s;
    140 		/* pick the best white move */
    141 		if (better(s, s2, WHITE))
    142 			s2 = s;
    143 	}
    144 
    145 	if (debug != 0) {
    146 		const struct spotstr *sp1 = &board[s1], *sp2 = &board[s2];
    147 		debuglog("B %s %x/%d %d %x/%d %d %d",
    148 		    stoc(s1),
    149 		    sp1->s_combo[BLACK].s, sp1->s_level[BLACK],
    150 		    sp1->s_nforce[BLACK],
    151 		    sp1->s_combo[WHITE].s, sp1->s_level[WHITE],
    152 		    sp1->s_nforce[WHITE], sp1->s_wval);
    153 		debuglog("W %s %x/%d %d %x/%d %d %d",
    154 		    stoc(s2),
    155 		    sp2->s_combo[WHITE].s, sp2->s_level[WHITE],
    156 		    sp2->s_nforce[WHITE],
    157 		    sp2->s_combo[BLACK].s, sp2->s_level[BLACK],
    158 		    sp2->s_nforce[BLACK], sp2->s_wval);
    159 		/*
    160 		 * Check for more than one force that can't
    161 		 * all be blocked with one move.
    162 		 */
    163 		spot_index m = us == BLACK ? s2 : s1;
    164 		int them = us != BLACK ? BLACK : WHITE;
    165 		if (board[m].s_combo[them].cv_force == 1 &&
    166 		    !BIT_TEST(forcemap, m))
    167 			debuglog("*** Can't be blocked");
    168 	}
    169 
    170 	union comboval *Ocp, *Tcp;
    171 	if (us == BLACK) {
    172 		Ocp = &board[s1].s_combo[BLACK];
    173 		Tcp = &board[s2].s_combo[WHITE];
    174 	} else {
    175 		Tcp = &board[s1].s_combo[BLACK];
    176 		Ocp = &board[s2].s_combo[WHITE];
    177 
    178 		spot_index tmp = s1;
    179 		s1 = s2;
    180 		s2 = tmp;
    181 	}
    182 	/*
    183 	 * Block their combo only if we have to (i.e., if they are one move
    184 	 * away from completing a force, and we don't have a force that
    185 	 * we can complete which takes fewer moves to win).
    186 	 */
    187 	if (Tcp->cv_force <= 1 && (Ocp->cv_force > 1 ||
    188 	    Tcp->cv_force + Tcp->cv_win < Ocp->cv_force + Ocp->cv_win))
    189 		return s2;
    190 	return s1;
    191 }
    192 
    193 /*
    194  * Return true if spot 'sp' is better than spot 'sp1' for color 'us'.
    195  */
    196 static bool
    197 better(spot_index s, spot_index s1, int us)
    198 {
    199 	const struct spotstr *sp = &board[s], *sp1 = &board[s1];
    200 
    201 	if (/* .... */ sp->s_combo[us].s != sp1->s_combo[us].s)
    202 		return sp->s_combo[us].s < sp1->s_combo[us].s;
    203 	if (/* .... */ sp->s_level[us] != sp1->s_level[us])
    204 		return sp->s_level[us] < sp1->s_level[us];
    205 	if (/* .... */ sp->s_nforce[us] != sp1->s_nforce[us])
    206 		return sp->s_nforce[us] > sp1->s_nforce[us];
    207 
    208 	int them = us != BLACK ? BLACK : WHITE;
    209 	if (BIT_TEST(forcemap, s) != BIT_TEST(forcemap, s1))
    210 		return BIT_TEST(forcemap, s);
    211 
    212 	if (/* .... */ sp->s_combo[them].s != sp1->s_combo[them].s)
    213 		return sp->s_combo[them].s < sp1->s_combo[them].s;
    214 	if (/* .... */ sp->s_level[them] != sp1->s_level[them])
    215 		return sp->s_level[them] < sp1->s_level[them];
    216 	if (/* .... */ sp->s_nforce[them] != sp1->s_nforce[them])
    217 		return sp->s_nforce[them] > sp1->s_nforce[them];
    218 
    219 	if (/* .... */ sp->s_wval != sp1->s_wval)
    220 		return sp->s_wval > sp1->s_wval;
    221 
    222 	return (random() & 1) != 0;
    223 }
    224 
    225 static int curcolor;	/* implicit parameter to makecombo() */
    226 static unsigned int curlevel;	/* implicit parameter to makecombo() */
    227 
    228 /*
    229  * Scan the sorted list of non-empty frames and
    230  * update the minimum combo values for each empty spot.
    231  * Also, try to combine frames to find more complex (chained) moves.
    232  */
    233 static void
    234 scanframes(int color)
    235 {
    236 	struct combostr *ecbp;
    237 	struct spotstr *sp;
    238 	union comboval *cp;
    239 	struct elist *nep;
    240 	int i, r, n;
    241 	union comboval cb;
    242 
    243 	curcolor = color;
    244 
    245 	/* check for empty list of frames */
    246 	struct combostr *cbp = sortframes[color];
    247 	if (cbp == NULL)
    248 		return;
    249 
    250 	/* quick check for four in a row */
    251 	sp = &board[cbp->c_vertex];
    252 	cb.s = sp->s_fval[color][cbp->c_dir].s;
    253 	if (cb.s < 0x101) {
    254 		int delta = dd[cbp->c_dir];
    255 		for (i = 5 + cb.cv_win; --i >= 0; sp += delta) {
    256 			if (sp->s_occ != EMPTY)
    257 				continue;
    258 			sp->s_combo[color].s = cb.s;
    259 			sp->s_level[color] = 1;
    260 		}
    261 		return;
    262 	}
    263 
    264 	/*
    265 	 * Update the minimum combo value for each spot in the frame
    266 	 * and try making all combinations of two frames intersecting at
    267 	 * an empty spot.
    268 	 */
    269 	n = combolen;
    270 	ecbp = cbp;
    271 	do {
    272 		sp = &board[cbp->c_vertex];
    273 		cp = &sp->s_fval[color][r = cbp->c_dir];
    274 		int delta = dd[r];
    275 		if (cp->cv_win != 0) {
    276 			/*
    277 			 * Since this is the first spot of an open-ended
    278 			 * frame, we treat it as a closed frame.
    279 			 */
    280 			cb.cv_force = cp->cv_force + 1;
    281 			cb.cv_win = 0;
    282 			if (cb.s < sp->s_combo[color].s) {
    283 				sp->s_combo[color].s = cb.s;
    284 				sp->s_level[color] = 1;
    285 			}
    286 			/*
    287 			 * Try combining other frames that intersect
    288 			 * at this spot.
    289 			 */
    290 			makecombo2(cbp, sp, 0, cb.s);
    291 			if (cp->s != 0x101)
    292 				cb.s = cp->s;
    293 			else if (color != nextcolor)
    294 				memset(tmpmap, 0, sizeof(tmpmap));
    295 			sp += delta;
    296 			i = 1;
    297 		} else {
    298 			cb.s = cp->s;
    299 			i = 0;
    300 		}
    301 		for (; i < 5; i++, sp += delta) {	/* for each spot */
    302 			if (sp->s_occ != EMPTY)
    303 				continue;
    304 			if (cp->s < sp->s_combo[color].s) {
    305 				sp->s_combo[color].s = cp->s;
    306 				sp->s_level[color] = 1;
    307 			}
    308 			if (cp->s == 0x101) {
    309 				sp->s_nforce[color]++;
    310 				if (color != nextcolor) {
    311 					n = (int)(sp - board);
    312 					BIT_SET(tmpmap, n);
    313 				}
    314 			}
    315 			/*
    316 			 * Try combining other frames that intersect
    317 			 * at this spot.
    318 			 */
    319 			makecombo2(cbp, sp, i, cb.s);
    320 		}
    321 		if (cp->s == 0x101 && color != nextcolor) {
    322 			if (nforce == 0)
    323 				memcpy(forcemap, tmpmap, sizeof(tmpmap));
    324 			else {
    325 				for (i = 0; (unsigned int)i < MAPSZ; i++)
    326 					forcemap[i] &= tmpmap[i];
    327 			}
    328 		}
    329 		/* mark frame as having been processed */
    330 		board[cbp->c_vertex].s_flags |= MFLAG << r;
    331 	} while ((cbp = cbp->c_next) != ecbp);
    332 
    333 	/*
    334 	 * Try to make new 3rd level combos, 4th level, etc.
    335 	 * Limit the search depth early in the game.
    336 	 */
    337 	/* LINTED 117: bitwise '>>' on signed value possibly nonportable */
    338 	for (unsigned int level = 2;
    339 	     level <= 1 + game.nmoves / 2 && combolen > n; level++) {
    340 		if (level >= 9)
    341 			break;	/* Do not think too long. */
    342 		if (debug != 0) {
    343 			debuglog("%cL%u %d %d %d", "BW"[color],
    344 			    level, combolen - n, combocnt, elistcnt);
    345 			refresh();
    346 		}
    347 		n = combolen;
    348 		addframes(level);
    349 	}
    350 
    351 	/* scan for combos at empty spots */
    352 	for (unsigned pos = PT(BSZ, BSZ + 1); pos-- > PT(1, 1); ) {
    353 		sp = &board[pos];
    354 		for (struct elist *ep = sp->s_empty; ep != NULL; ep = nep) {
    355 			cbp = ep->e_combo;
    356 			if (cbp->c_combo.s <= sp->s_combo[color].s) {
    357 				if (cbp->c_combo.s != sp->s_combo[color].s) {
    358 					sp->s_combo[color].s = cbp->c_combo.s;
    359 					sp->s_level[color] = cbp->c_nframes;
    360 				} else if (cbp->c_nframes < sp->s_level[color])
    361 					sp->s_level[color] = cbp->c_nframes;
    362 			}
    363 			nep = ep->e_next;
    364 			free(ep);
    365 			elistcnt--;
    366 		}
    367 		sp->s_empty = NULL;
    368 		for (struct elist *ep = sp->s_nempty; ep != NULL; ep = nep) {
    369 			cbp = ep->e_combo;
    370 			if (cbp->c_combo.s <= sp->s_combo[color].s) {
    371 				if (cbp->c_combo.s != sp->s_combo[color].s) {
    372 					sp->s_combo[color].s = cbp->c_combo.s;
    373 					sp->s_level[color] = cbp->c_nframes;
    374 				} else if (cbp->c_nframes < sp->s_level[color])
    375 					sp->s_level[color] = cbp->c_nframes;
    376 			}
    377 			nep = ep->e_next;
    378 			free(ep);
    379 			elistcnt--;
    380 		}
    381 		sp->s_nempty = NULL;
    382 	}
    383 
    384 	/* remove old combos */
    385 	if ((cbp = sortcombos) != NULL) {
    386 		struct combostr *ncbp;
    387 
    388 		/* scan the list */
    389 		ecbp = cbp;
    390 		do {
    391 			ncbp = cbp->c_next;
    392 			free(cbp);
    393 			combocnt--;
    394 		} while ((cbp = ncbp) != ecbp);
    395 		sortcombos = NULL;
    396 	}
    397 	combolen = 0;
    398 
    399 #ifdef DEBUG
    400 	if (combocnt != 0) {
    401 		debuglog("scanframes: %c combocnt %d", "BW"[color],
    402 			combocnt);
    403 		whatsup(0);
    404 	}
    405 	if (elistcnt != 0) {
    406 		debuglog("scanframes: %c elistcnt %d", "BW"[color],
    407 			elistcnt);
    408 		whatsup(0);
    409 	}
    410 #endif
    411 }
    412 
    413 /*
    414  * Compute all level 2 combos of frames intersecting spot 'osp'
    415  * within the frame 'ocbp' and combo value 'cv'.
    416  */
    417 static void
    418 makecombo2(struct combostr *ocbp, struct spotstr *osp, int off, int cv)
    419 {
    420 	struct combostr *ncbp;
    421 	int c;
    422 	int baseB, fcnt, emask, n;
    423 	union comboval ocb, fcb;
    424 	struct combostr **scbpp, *fcbp;
    425 	char tmp[128];
    426 
    427 	/* try to combine a new frame with those found so far */
    428 	ocb.s = cv;
    429 	baseB = ocb.cv_force + ocb.cv_win - 1;
    430 	fcnt = ocb.cv_force - 2;
    431 	emask = fcnt != 0 ? ((ocb.cv_win != 0 ? 0x1E : 0x1F) & ~(1 << off)) : 0;
    432 	for (int r = 4; --r >= 0; ) {		/* for each direction */
    433 	    /* don't include frames that overlap in the same direction */
    434 	    if (r == ocbp->c_dir)
    435 		continue;
    436 	    int d = dd[r];
    437 	    /*
    438 	     * Frame A combined with B is the same value as B combined with A
    439 	     * so skip frames that have already been processed (MFLAG).
    440 	     * Also skip blocked frames (BFLAG) and frames that are <1,x>
    441 	     * since combining another frame with it isn't valid.
    442 	     */
    443 	    int bmask = (BFLAG | FFLAG | MFLAG) << r;
    444 	    struct spotstr *fsp = osp;
    445 	    for (int f = 0; f < 5; f++, fsp -= d) {	/* for each frame */
    446 		if (fsp->s_occ == BORDER)
    447 		    break;
    448 		if ((fsp->s_flags & bmask) != 0)
    449 		    continue;
    450 
    451 		/* don't include frames of the wrong color */
    452 		fcb.s = fsp->s_fval[curcolor][r].s;
    453 		if (fcb.cv_force >= 6)
    454 		    continue;
    455 
    456 		/*
    457 		 * Get the combo value for this frame.
    458 		 * If this is the end point of the frame,
    459 		 * use the closed ended value for the frame.
    460 		 */
    461 		if ((f == 0 && fcb.cv_win != 0) || fcb.s == 0x101) {
    462 		    fcb.cv_force++;
    463 		    fcb.cv_win = 0;
    464 		}
    465 
    466 		/* compute combo value */
    467 		c = fcb.cv_force + ocb.cv_force - 3;
    468 		if (c > 4)
    469 		    continue;
    470 		n = fcb.cv_force + fcb.cv_win - 1;
    471 		if (baseB < n)
    472 		    n = baseB;
    473 
    474 		/* make a new combo! */
    475 		ncbp = (struct combostr *)malloc(sizeof(struct combostr) +
    476 		    2 * sizeof(struct combostr *));
    477 		if (ncbp == NULL)
    478 		    panic("Out of memory!");
    479 		scbpp = (void *)(ncbp + 1);
    480 		fcbp = &frames[fsp->s_frame[r]];
    481 		if (ocbp < fcbp) {
    482 		    scbpp[0] = ocbp;
    483 		    scbpp[1] = fcbp;
    484 		} else {
    485 		    scbpp[0] = fcbp;
    486 		    scbpp[1] = ocbp;
    487 		}
    488 		ncbp->c_combo.cv_force = c;
    489 		ncbp->c_combo.cv_win = n;
    490 		ncbp->c_link[0] = ocbp;
    491 		ncbp->c_link[1] = fcbp;
    492 		ncbp->c_linkv[0].s = ocb.s;
    493 		ncbp->c_linkv[1].s = fcb.s;
    494 		ncbp->c_voff[0] = off;
    495 		ncbp->c_voff[1] = f;
    496 		ncbp->c_vertex = (u_short)(osp - board);
    497 		ncbp->c_nframes = 2;
    498 		ncbp->c_dir = 0;
    499 		ncbp->c_frameindex = 0;
    500 		ncbp->c_flags = ocb.cv_win != 0 ? C_OPEN_0 : 0;
    501 		if (fcb.cv_win != 0)
    502 		    ncbp->c_flags |= C_OPEN_1;
    503 		ncbp->c_framecnt[0] = fcnt;
    504 		ncbp->c_emask[0] = emask;
    505 		ncbp->c_framecnt[1] = fcb.cv_force - 2;
    506 		ncbp->c_emask[1] = ncbp->c_framecnt[1] != 0 ?
    507 		    ((fcb.cv_win != 0 ? 0x1E : 0x1F) & ~(1 << f)) : 0;
    508 		combocnt++;
    509 
    510 		if ((c == 1 && debug > 1) || debug > 3) {
    511 		    debuglog("%c c %d %d m %x %x o %d %d",
    512 			"bw"[curcolor],
    513 			ncbp->c_framecnt[0], ncbp->c_framecnt[1],
    514 			ncbp->c_emask[0], ncbp->c_emask[1],
    515 			ncbp->c_voff[0], ncbp->c_voff[1]);
    516 		    printcombo(ncbp, tmp, sizeof(tmp));
    517 		    debuglog("%s", tmp);
    518 		}
    519 		if (c > 1) {
    520 		    /* record the empty spots that will complete this combo */
    521 		    makeempty(ncbp);
    522 
    523 		    /* add the new combo to the end of the list */
    524 		    appendcombo(ncbp, curcolor);
    525 		} else {
    526 		    updatecombo(ncbp, curcolor);
    527 		    free(ncbp);
    528 		    combocnt--;
    529 		}
    530 #ifdef DEBUG
    531 		if ((c == 1 && debug > 1) || debug > 5) {
    532 		    markcombo(ncbp);
    533 		    bdisp();
    534 		    whatsup(0);
    535 		    clearcombo(ncbp, 0);
    536 		}
    537 #endif /* DEBUG */
    538 	    }
    539 	}
    540 }
    541 
    542 /*
    543  * Scan the sorted list of frames and try to add a frame to
    544  * combinations of 'level' number of frames.
    545  */
    546 static void
    547 addframes(unsigned int level)
    548 {
    549 	struct combostr *cbp, *ecbp;
    550 	struct spotstr *fsp;
    551 	struct elist *nep;
    552 	int i, r;
    553 	struct combostr **cbpp, *pcbp;
    554 	union comboval fcb, cb;
    555 
    556 	curlevel = level;
    557 
    558 	/* scan for combos at empty spots */
    559 	i = curcolor;
    560 	for (unsigned pos = PT(BSZ, BSZ + 1); pos-- > PT(1, 1); ) {
    561 		struct spotstr *sp = &board[pos];
    562 		for (struct elist *ep = sp->s_empty; ep != NULL; ep = nep) {
    563 			cbp = ep->e_combo;
    564 			if (cbp->c_combo.s <= sp->s_combo[i].s) {
    565 				if (cbp->c_combo.s != sp->s_combo[i].s) {
    566 					sp->s_combo[i].s = cbp->c_combo.s;
    567 					sp->s_level[i] = cbp->c_nframes;
    568 				} else if (cbp->c_nframes < sp->s_level[i])
    569 					sp->s_level[i] = cbp->c_nframes;
    570 			}
    571 			nep = ep->e_next;
    572 			free(ep);
    573 			elistcnt--;
    574 		}
    575 		sp->s_empty = sp->s_nempty;
    576 		sp->s_nempty = NULL;
    577 	}
    578 
    579 	/* try to add frames to the uncompleted combos at level curlevel */
    580 	cbp = ecbp = sortframes[curcolor];
    581 	do {
    582 		fsp = &board[cbp->c_vertex];
    583 		r = cbp->c_dir;
    584 		/* skip frames that are part of a <1,x> combo */
    585 		if ((fsp->s_flags & (FFLAG << r)) != 0)
    586 			continue;
    587 
    588 		/*
    589 		 * Don't include <1,x> combo frames,
    590 		 * treat it as a closed three in a row instead.
    591 		 */
    592 		fcb.s = fsp->s_fval[curcolor][r].s;
    593 		if (fcb.s == 0x101)
    594 			fcb.s = 0x200;
    595 
    596 		/*
    597 		 * If this is an open-ended frame, use
    598 		 * the combo value with the end closed.
    599 		 */
    600 		if (fsp->s_occ == EMPTY) {
    601 			if (fcb.cv_win != 0) {
    602 				cb.cv_force = fcb.cv_force + 1;
    603 				cb.cv_win = 0;
    604 			} else
    605 				cb.s = fcb.s;
    606 			makecombo(cbp, fsp, 0, cb.s);
    607 		}
    608 
    609 		/*
    610 		 * The next four spots are handled the same for both
    611 		 * open and closed ended frames.
    612 		 */
    613 		int d = dd[r];
    614 		struct spotstr *sp = fsp + d;
    615 		for (i = 1; i < 5; i++, sp += d) {
    616 			if (sp->s_occ != EMPTY)
    617 				continue;
    618 			makecombo(cbp, sp, i, fcb.s);
    619 		}
    620 	} while ((cbp = cbp->c_next) != ecbp);
    621 
    622 	/* put all the combos in the hash list on the sorted list */
    623 	cbpp = &hashcombos[FAREA];
    624 	do {
    625 		cbp = *--cbpp;
    626 		if (cbp == NULL)
    627 			continue;
    628 		*cbpp = NULL;
    629 		ecbp = sortcombos;
    630 		if (ecbp == NULL)
    631 			sortcombos = cbp;
    632 		else {
    633 			/* append to sort list */
    634 			pcbp = ecbp->c_prev;
    635 			pcbp->c_next = cbp;
    636 			ecbp->c_prev = cbp->c_prev;
    637 			cbp->c_prev->c_next = ecbp;
    638 			cbp->c_prev = pcbp;
    639 		}
    640 	} while (cbpp != hashcombos);
    641 }
    642 
    643 /*
    644  * Compute all level N combos of frames intersecting spot 'osp'
    645  * within the frame 'ocbp' and combo value 'cv'.
    646  */
    647 static void
    648 makecombo(struct combostr *ocbp, struct spotstr *osp, int off, int cv)
    649 {
    650 	struct combostr *cbp;
    651 	struct spotstr *sp;
    652 	struct combostr **scbpp;
    653 	int baseB, fcnt, emask, verts;
    654 	union comboval ocb;
    655 	struct overlap_info vertices[1];
    656 	char tmp[128];
    657 
    658 	/*
    659 	 * XXX: when I made functions static gcc started warning about
    660 	 * some members of vertices[0] maybe being used uninitialized.
    661 	 * For now, I'm just going to clear it rather than wade through
    662 	 * the logic to find out whether gcc or the code is wrong. I
    663 	 * wouldn't be surprised if it were the code though. - dholland
    664 	 */
    665 	memset(vertices, 0, sizeof(vertices));
    666 
    667 	ocb.s = cv;
    668 	baseB = ocb.cv_force + ocb.cv_win - 1;
    669 	fcnt = ocb.cv_force - 2;
    670 	emask = fcnt != 0 ? ((ocb.cv_win != 0 ? 0x1E : 0x1F) & ~(1 << off)) : 0;
    671 	for (struct elist *ep = osp->s_empty; ep != NULL; ep = ep->e_next) {
    672 	    /* check for various kinds of overlap */
    673 	    cbp = ep->e_combo;
    674 	    verts = checkframes(cbp, ocbp, osp, cv, vertices);
    675 	    if (verts < 0)
    676 		continue;
    677 
    678 	    /* check to see if this frame forms a valid loop */
    679 	    if (verts > 0) {
    680 		sp = &board[vertices[0].o_intersect];
    681 #ifdef DEBUG
    682 		if (sp->s_occ != EMPTY) {
    683 		    debuglog("loop: %c %s", "BW"[curcolor],
    684 			stoc((int)(sp - board)));
    685 		    whatsup(0);
    686 		}
    687 #endif
    688 		/*
    689 		 * It is a valid loop if the intersection spot
    690 		 * of the frame we are trying to attach is one
    691 		 * of the completion spots of the combostr
    692 		 * we are trying to attach the frame to.
    693 		 */
    694 		for (struct elist *nep = sp->s_empty;
    695 			nep != NULL; nep = nep->e_next) {
    696 		    if (nep->e_combo == cbp)
    697 			goto fnd;
    698 		    if (nep->e_combo->c_nframes < cbp->c_nframes)
    699 			break;
    700 		}
    701 		/* frame overlaps but not at a valid spot */
    702 		continue;
    703 	    fnd:
    704 		;
    705 	    }
    706 
    707 	    /* compute the first half of the combo value */
    708 	    int c = cbp->c_combo.cv_force + ocb.cv_force - verts - 3;
    709 	    if (c > 4)
    710 		continue;
    711 
    712 	    /* compute the second half of the combo value */
    713 	    int n = ep->e_fval.cv_force + ep->e_fval.cv_win - 1;
    714 	    if (baseB < n)
    715 		n = baseB;
    716 
    717 	    /* make a new combo! */
    718 	    struct combostr *ncbp = malloc(sizeof(struct combostr) +
    719 		(cbp->c_nframes + 1) * sizeof(struct combostr *));
    720 	    if (ncbp == NULL)
    721 		panic("Out of memory!");
    722 	    scbpp = (void *)(ncbp + 1);
    723 	    if (sortcombo(scbpp, (void *)(cbp + 1), ocbp)) {
    724 		free(ncbp);
    725 		continue;
    726 	    }
    727 	    combocnt++;
    728 
    729 	    ncbp->c_combo.cv_force = c;
    730 	    ncbp->c_combo.cv_win = n;
    731 	    ncbp->c_link[0] = cbp;
    732 	    ncbp->c_link[1] = ocbp;
    733 	    ncbp->c_linkv[1].s = ocb.s;
    734 	    ncbp->c_voff[1] = off;
    735 	    ncbp->c_vertex = (u_short)(osp - board);
    736 	    ncbp->c_nframes = cbp->c_nframes + 1;
    737 	    ncbp->c_flags = ocb.cv_win != 0 ? C_OPEN_1 : 0;
    738 	    ncbp->c_frameindex = ep->e_frameindex;
    739 	    /*
    740 	     * Update the completion spot mask of the frame we
    741 	     * are attaching 'ocbp' to so the intersection isn't
    742 	     * listed twice.
    743 	     */
    744 	    ncbp->c_framecnt[0] = ep->e_framecnt;
    745 	    ncbp->c_emask[0] = ep->e_emask;
    746 	    if (verts != 0) {
    747 		ncbp->c_flags |= C_LOOP;
    748 		ncbp->c_dir = vertices[0].o_frameindex;
    749 		ncbp->c_framecnt[1] = fcnt - 1;
    750 		if (ncbp->c_framecnt[1] != 0) {
    751 		    n = (vertices[0].o_intersect - ocbp->c_vertex) /
    752 			dd[ocbp->c_dir];
    753 		    ncbp->c_emask[1] = emask & ~(1 << n);
    754 		} else
    755 		    ncbp->c_emask[1] = 0;
    756 		ncbp->c_voff[0] = vertices[0].o_off;
    757 	    } else {
    758 		ncbp->c_dir = 0;
    759 		ncbp->c_framecnt[1] = fcnt;
    760 		ncbp->c_emask[1] = emask;
    761 		ncbp->c_voff[0] = ep->e_off;
    762 	    }
    763 
    764 	    if ((c == 1 && debug > 1) || debug > 3) {
    765 		debuglog("%c v%d i%d d%d c %d %d m %x %x o %d %d",
    766 		    "bw"[curcolor], verts, ncbp->c_frameindex, ncbp->c_dir,
    767 		    ncbp->c_framecnt[0], ncbp->c_framecnt[1],
    768 		    ncbp->c_emask[0], ncbp->c_emask[1],
    769 		    ncbp->c_voff[0], ncbp->c_voff[1]);
    770 		printcombo(ncbp, tmp, sizeof(tmp));
    771 		debuglog("%s", tmp);
    772 	    }
    773 	    if (c > 1) {
    774 		/* record the empty spots that will complete this combo */
    775 		makeempty(ncbp);
    776 		combolen++;
    777 	    } else {
    778 		/* update board values */
    779 		updatecombo(ncbp, curcolor);
    780 	    }
    781 #ifdef DEBUG
    782 	    if ((c == 1 && debug > 1) || debug > 4) {
    783 		markcombo(ncbp);
    784 		bdisp();
    785 		whatsup(0);
    786 		clearcombo(ncbp, 0);
    787 	    }
    788 #endif /* DEBUG */
    789 	}
    790 }
    791 
    792 #define MAXDEPTH	100
    793 static struct elist einfo[MAXDEPTH];
    794 static struct combostr *ecombo[MAXDEPTH];	/* separate from elist to save space */
    795 
    796 /*
    797  * Add the combostr 'ocbp' to the empty spots list for each empty spot
    798  * in 'ocbp' that will complete the combo.
    799  */
    800 static void
    801 makeempty(struct combostr *ocbp)
    802 {
    803 	struct combostr *cbp, **cbpp;
    804 	struct elist *ep, *nep;
    805 	struct spotstr *sp;
    806 	int d, emask, i;
    807 	int nframes;
    808 	char tmp[128];
    809 
    810 	if (debug > 2) {
    811 		printcombo(ocbp, tmp, sizeof(tmp));
    812 		debuglog("E%c %s", "bw"[curcolor], tmp);
    813 	}
    814 
    815 	/* should never happen but check anyway */
    816 	if ((nframes = ocbp->c_nframes) >= MAXDEPTH)
    817 		return;
    818 
    819 	/*
    820 	 * The lower level combo can be pointed to by more than one
    821 	 * higher level 'struct combostr' so we can't modify the
    822 	 * lower level. Therefore, higher level combos store the
    823 	 * real mask of the lower level frame in c_emask[0] and the
    824 	 * frame number in c_frameindex.
    825 	 *
    826 	 * First we traverse the tree from top to bottom and save the
    827 	 * connection info. Then we traverse the tree from bottom to
    828 	 * top overwriting lower levels with the newer emask information.
    829 	 */
    830 	ep = &einfo[nframes];
    831 	cbpp = &ecombo[nframes];
    832 	for (cbp = ocbp; cbp->c_link[1] != NULL; cbp = cbp->c_link[0]) {
    833 		ep--;
    834 		ep->e_combo = cbp;
    835 		*--cbpp = cbp->c_link[1];
    836 		ep->e_off = cbp->c_voff[1];
    837 		ep->e_frameindex = cbp->c_frameindex;
    838 		ep->e_fval.s = cbp->c_linkv[1].s;
    839 		ep->e_framecnt = cbp->c_framecnt[1];
    840 		ep->e_emask = cbp->c_emask[1];
    841 	}
    842 	cbp = ep->e_combo;
    843 	ep--;
    844 	ep->e_combo = cbp;
    845 	*--cbpp = cbp->c_link[0];
    846 	ep->e_off = cbp->c_voff[0];
    847 	ep->e_frameindex = 0;
    848 	ep->e_fval.s = cbp->c_linkv[0].s;
    849 	ep->e_framecnt = cbp->c_framecnt[0];
    850 	ep->e_emask = cbp->c_emask[0];
    851 
    852 	/* now update the emask info */
    853 	int n = 0;
    854 	for (i = 2, ep += 2; i < nframes; i++, ep++) {
    855 		cbp = ep->e_combo;
    856 		nep = &einfo[ep->e_frameindex];
    857 		nep->e_framecnt = cbp->c_framecnt[0];
    858 		nep->e_emask = cbp->c_emask[0];
    859 
    860 		if ((cbp->c_flags & C_LOOP) != 0) {
    861 			n++;
    862 			/*
    863 			 * Account for the fact that this frame connects
    864 			 * to a previous one (thus forming a loop).
    865 			 */
    866 			nep = &einfo[cbp->c_dir];
    867 			if (--nep->e_framecnt != 0)
    868 				nep->e_emask &= ~(1 << cbp->c_voff[0]);
    869 			else
    870 				nep->e_emask = 0;
    871 		}
    872 	}
    873 
    874 	/*
    875 	 * We only need to update the emask values of "complete" loops
    876 	 * to include the intersection spots.
    877 	 */
    878 	if (n != 0 && ocbp->c_combo.cv_force == 2) {
    879 		/* process loops from the top down */
    880 		ep = &einfo[nframes];
    881 		do {
    882 			ep--;
    883 			cbp = ep->e_combo;
    884 			if ((cbp->c_flags & C_LOOP) == 0)
    885 				continue;
    886 
    887 			/*
    888 			 * Update the emask values to include the
    889 			 * intersection spots.
    890 			 */
    891 			nep = &einfo[cbp->c_dir];
    892 			nep->e_framecnt = 1;
    893 			nep->e_emask = 1 << cbp->c_voff[0];
    894 			ep->e_framecnt = 1;
    895 			ep->e_emask = 1 << ep->e_off;
    896 			ep = &einfo[ep->e_frameindex];
    897 			do {
    898 				ep->e_framecnt = 1;
    899 				ep->e_emask = 1 << ep->e_off;
    900 				ep = &einfo[ep->e_frameindex];
    901 			} while (ep > nep);
    902 		} while (ep != einfo);
    903 	}
    904 
    905 	/* check all the frames for completion spots */
    906 	for (i = 0, ep = einfo, cbpp = ecombo; i < nframes; i++, ep++, cbpp++) {
    907 		/* skip this frame if there are no incomplete spots in it */
    908 		if ((emask = ep->e_emask) == 0)
    909 			continue;
    910 		cbp = *cbpp;
    911 		sp = &board[cbp->c_vertex];
    912 		d = dd[cbp->c_dir];
    913 		for (int off = 0, m = 1; off < 5; off++, sp += d, m <<= 1) {
    914 			if (sp->s_occ != EMPTY || (emask & m) == 0)
    915 				continue;
    916 
    917 			/* add the combo to the list of empty spots */
    918 			nep = (struct elist *)malloc(sizeof(struct elist));
    919 			if (nep == NULL)
    920 				panic("Out of memory!");
    921 			nep->e_combo = ocbp;
    922 			nep->e_off = off;
    923 			nep->e_frameindex = i;
    924 			if (ep->e_framecnt > 1) {
    925 				nep->e_framecnt = ep->e_framecnt - 1;
    926 				nep->e_emask = emask & ~m;
    927 			} else {
    928 				nep->e_framecnt = 0;
    929 				nep->e_emask = 0;
    930 			}
    931 			nep->e_fval.s = ep->e_fval.s;
    932 			if (debug > 2) {
    933 				debuglog("e %s o%d i%d c%d m%x %x",
    934 				    stoc((int)(sp - board)),
    935 				    nep->e_off,
    936 				    nep->e_frameindex,
    937 				    nep->e_framecnt,
    938 				    nep->e_emask,
    939 				    nep->e_fval.s);
    940 			}
    941 
    942 			/* sort by the number of frames in the combo */
    943 			nep->e_next = sp->s_nempty;
    944 			sp->s_nempty = nep;
    945 			elistcnt++;
    946 		}
    947 	}
    948 }
    949 
    950 /*
    951  * Update the board value based on the combostr.
    952  * This is called only if 'cbp' is a <1,x> combo.
    953  * We handle things differently depending on whether the next move
    954  * would be trying to "complete" the combo or trying to block it.
    955  */
    956 static void
    957 updatecombo(struct combostr *cbp, int color)
    958 {
    959 	struct combostr *tcbp;
    960 	int nframes, flags;
    961 	union comboval cb;
    962 
    963 	flags = 0;
    964 	/* save the top level value for the whole combo */
    965 	cb.cv_force = cbp->c_combo.cv_force;
    966 	nframes = cbp->c_nframes;
    967 
    968 	if (color != nextcolor)
    969 		memset(tmpmap, 0, sizeof(tmpmap));
    970 
    971 	for (; (tcbp = cbp->c_link[1]) != NULL; cbp = cbp->c_link[0]) {
    972 		flags = cbp->c_flags;
    973 		cb.cv_win = cbp->c_combo.cv_win;
    974 		if (color == nextcolor) {
    975 			/* update the board value for the vertex */
    976 			struct spotstr *sp = &board[cbp->c_vertex];
    977 			sp->s_nforce[color]++;
    978 			if (cb.s <= sp->s_combo[color].s) {
    979 				if (cb.s != sp->s_combo[color].s) {
    980 					sp->s_combo[color].s = cb.s;
    981 					sp->s_level[color] = nframes;
    982 				} else if (nframes < sp->s_level[color])
    983 					sp->s_level[color] = nframes;
    984 			}
    985 		} else {
    986 			/* update the board values for each spot in frame */
    987 			spot_index s = tcbp->c_vertex;
    988 			struct spotstr *sp = &board[s];
    989 			int d = dd[tcbp->c_dir];
    990 			int i = (flags & C_OPEN_1) != 0 ? 6 : 5;
    991 			for (; --i >= 0; sp += d, s += d) {
    992 				if (sp->s_occ != EMPTY)
    993 					continue;
    994 				sp->s_nforce[color]++;
    995 				if (cb.s <= sp->s_combo[color].s) {
    996 					if (cb.s != sp->s_combo[color].s) {
    997 						sp->s_combo[color].s = cb.s;
    998 						sp->s_level[color] = nframes;
    999 					} else if (nframes < sp->s_level[color])
   1000 						sp->s_level[color] = nframes;
   1001 				}
   1002 				BIT_SET(tmpmap, s);
   1003 			}
   1004 		}
   1005 
   1006 		/* mark the frame as being part of a <1,x> combo */
   1007 		board[tcbp->c_vertex].s_flags |= FFLAG << tcbp->c_dir;
   1008 	}
   1009 
   1010 	if (color != nextcolor) {
   1011 		/* update the board values for each spot in frame */
   1012 		spot_index s = cbp->c_vertex;
   1013 		struct spotstr *sp = &board[s];
   1014 		int d = dd[cbp->c_dir];
   1015 		int i = (flags & C_OPEN_0) != 0 ? 6 : 5;
   1016 		for (; --i >= 0; sp += d, s += d) {
   1017 			if (sp->s_occ != EMPTY)
   1018 				continue;
   1019 			sp->s_nforce[color]++;
   1020 			if (cb.s <= sp->s_combo[color].s) {
   1021 				if (cb.s != sp->s_combo[color].s) {
   1022 					sp->s_combo[color].s = cb.s;
   1023 					sp->s_level[color] = nframes;
   1024 				} else if (nframes < sp->s_level[color])
   1025 					sp->s_level[color] = nframes;
   1026 			}
   1027 			BIT_SET(tmpmap, s);
   1028 		}
   1029 		if (nforce == 0)
   1030 			memcpy(forcemap, tmpmap, sizeof(tmpmap));
   1031 		else {
   1032 			for (i = 0; (unsigned int)i < MAPSZ; i++)
   1033 				forcemap[i] &= tmpmap[i];
   1034 		}
   1035 		nforce++;
   1036 	}
   1037 
   1038 	/* mark the frame as being part of a <1,x> combo */
   1039 	board[cbp->c_vertex].s_flags |= FFLAG << cbp->c_dir;
   1040 }
   1041 
   1042 /*
   1043  * Add combo to the end of the list.
   1044  */
   1045 static void
   1046 appendcombo(struct combostr *cbp, int color __unused)
   1047 {
   1048 	struct combostr *pcbp, *ncbp;
   1049 
   1050 	combolen++;
   1051 	ncbp = sortcombos;
   1052 	if (ncbp == NULL) {
   1053 		sortcombos = cbp;
   1054 		cbp->c_next = cbp;
   1055 		cbp->c_prev = cbp;
   1056 		return;
   1057 	}
   1058 	pcbp = ncbp->c_prev;
   1059 	cbp->c_next = ncbp;
   1060 	cbp->c_prev = pcbp;
   1061 	ncbp->c_prev = cbp;
   1062 	pcbp->c_next = cbp;
   1063 }
   1064 
   1065 /*
   1066  * Return zero if it is valid to combine frame 'fcbp' with the frames
   1067  * in 'cbp' and forms a linked chain of frames (i.e., a tree; no loops).
   1068  * Return positive if combining frame 'fcbp' to the frames in 'cbp'
   1069  * would form some kind of valid loop. Also return the intersection spots
   1070  * in 'vertices[]' beside the known intersection at spot 'osp'.
   1071  * Return -1 if 'fcbp' should not be combined with 'cbp'.
   1072  * 'cv' is the combo value for frame 'fcbp'.
   1073  */
   1074 static int
   1075 checkframes(struct combostr *cbp, struct combostr *fcbp, struct spotstr *osp,
   1076 	    int cv, struct overlap_info *vertices)
   1077 {
   1078 	struct combostr *tcbp, *lcbp;
   1079 	int i, n, mask, flags, verts, myindex, fcnt;
   1080 	union comboval cb;
   1081 	u_char *str;
   1082 
   1083 	lcbp = NULL;
   1084 	flags = 0;
   1085 
   1086 	cb.s = cv;
   1087 	fcnt = cb.cv_force - 2;
   1088 	verts = 0;
   1089 	myindex = cbp->c_nframes;
   1090 	n = (int)(fcbp - frames) * FAREA;
   1091 	str = &overlap[n];
   1092 	spot_index *ip = &intersect[n];
   1093 	/*
   1094 	 * i == which overlap bit to test based on whether 'fcbp' is
   1095 	 * an open or closed frame.
   1096 	 */
   1097 	i = cb.cv_win != 0 ? 2 : 0;
   1098 	for (; (tcbp = cbp->c_link[1]) != NULL;
   1099 	    lcbp = cbp, cbp = cbp->c_link[0]) {
   1100 		if (tcbp == fcbp)
   1101 			return -1;	/* fcbp is already included */
   1102 
   1103 		/* check for intersection of 'tcbp' with 'fcbp' */
   1104 		myindex--;
   1105 		mask = str[tcbp - frames];
   1106 		flags = cbp->c_flags;
   1107 		n = i + ((flags & C_OPEN_1) != 0 ? 1 : 0);
   1108 		if ((mask & (1 << n)) != 0) {
   1109 			/*
   1110 			 * The two frames are not independent if they
   1111 			 * both lie in the same line and intersect at
   1112 			 * more than one point.
   1113 			 */
   1114 			if (tcbp->c_dir == fcbp->c_dir &&
   1115 			    (mask & (0x10 << n)) != 0)
   1116 				return -1;
   1117 			/*
   1118 			 * If this is not the spot we are attaching
   1119 			 * 'fcbp' to, and it is a reasonable intersection
   1120 			 * spot, then there might be a loop.
   1121 			 */
   1122 			spot_index s = ip[tcbp - frames];
   1123 			if (osp != &board[s]) {
   1124 				/* check to see if this is a valid loop */
   1125 				if (verts != 0)
   1126 					return -1;
   1127 				if (fcnt == 0 || cbp->c_framecnt[1] == 0)
   1128 					return -1;
   1129 				/*
   1130 				 * Check to be sure the intersection is not
   1131 				 * one of the end points if it is an
   1132 				 * open-ended frame.
   1133 				 */
   1134 				if ((flags & C_OPEN_1) != 0 &&
   1135 				    (s == tcbp->c_vertex ||
   1136 				     s == tcbp->c_vertex + 5 * dd[tcbp->c_dir]))
   1137 					return -1;	/* invalid overlap */
   1138 				if (cb.cv_win != 0 &&
   1139 				    (s == fcbp->c_vertex ||
   1140 				     s == fcbp->c_vertex + 5 * dd[fcbp->c_dir]))
   1141 					return -1;	/* invalid overlap */
   1142 
   1143 				vertices->o_intersect = s;
   1144 				vertices->o_off = (s - tcbp->c_vertex) /
   1145 					dd[tcbp->c_dir];
   1146 				vertices->o_frameindex = myindex;
   1147 				verts++;
   1148 			}
   1149 		}
   1150 		n = i + ((flags & C_OPEN_0) != 0 ? 1 : 0);
   1151 	}
   1152 	if (cbp == fcbp)
   1153 		return -1;	/* fcbp is already included */
   1154 
   1155 	/* check for intersection of 'cbp' with 'fcbp' */
   1156 	mask = str[cbp - frames];
   1157 	if ((mask & (1 << n)) != 0) {
   1158 		/*
   1159 		 * The two frames are not independent if they
   1160 		 * both lie in the same line and intersect at
   1161 		 * more than one point.
   1162 		 */
   1163 		if (cbp->c_dir == fcbp->c_dir && (mask & (0x10 << n)) != 0)
   1164 			return -1;
   1165 		/*
   1166 		 * If this is not the spot we are attaching
   1167 		 * 'fcbp' to, and it is a reasonable intersection
   1168 		 * spot, then there might be a loop.
   1169 		 */
   1170 		spot_index s = ip[cbp - frames];
   1171 		if (osp != &board[s]) {
   1172 			/* check to see if this is a valid loop */
   1173 			if (verts != 0)
   1174 				return -1;
   1175 			if (fcnt == 0 || lcbp->c_framecnt[0] == 0)
   1176 				return -1;
   1177 			/*
   1178 			 * Check to be sure the intersection is not
   1179 			 * one of the end points if it is an open-ended
   1180 			 * frame.
   1181 			 */
   1182 			if ((flags & C_OPEN_0) != 0 &&
   1183 			    (s == cbp->c_vertex ||
   1184 			     s == cbp->c_vertex + 5 * dd[cbp->c_dir]))
   1185 				return -1;	/* invalid overlap */
   1186 			if (cb.cv_win != 0 &&
   1187 			    (s == fcbp->c_vertex ||
   1188 			     s == fcbp->c_vertex + 5 * dd[fcbp->c_dir]))
   1189 				return -1;	/* invalid overlap */
   1190 
   1191 			vertices->o_intersect = s;
   1192 			vertices->o_off = (s - cbp->c_vertex) /
   1193 				dd[cbp->c_dir];
   1194 			vertices->o_frameindex = 0;
   1195 			verts++;
   1196 		}
   1197 	}
   1198 	return verts;
   1199 }
   1200 
   1201 /*
   1202  * Merge sort the frame 'fcbp' and the sorted list of frames 'cbpp' and
   1203  * store the result in 'scbpp'. 'curlevel' is the size of the 'cbpp' array.
   1204  * Return true if this list of frames is already in the hash list.
   1205  * Otherwise, add the new combo to the hash list.
   1206  */
   1207 static bool
   1208 sortcombo(struct combostr **scbpp, struct combostr **cbpp,
   1209 	  struct combostr *fcbp)
   1210 {
   1211 	struct combostr **spp, **cpp;
   1212 	struct combostr *cbp, *ecbp;
   1213 	int inx;
   1214 
   1215 #ifdef DEBUG
   1216 	if (debug > 3) {
   1217 		char buf[128];
   1218 		size_t pos;
   1219 
   1220 		debuglog("sortc: %s%c l%u", stoc(fcbp->c_vertex),
   1221 			pdir[fcbp->c_dir], curlevel);
   1222 		pos = 0;
   1223 		for (cpp = cbpp; cpp < cbpp + curlevel; cpp++) {
   1224 			snprintf(buf + pos, sizeof(buf) - pos, " %s%c",
   1225 				stoc((*cpp)->c_vertex), pdir[(*cpp)->c_dir]);
   1226 			pos += strlen(buf + pos);
   1227 		}
   1228 		debuglog("%s", buf);
   1229 	}
   1230 #endif /* DEBUG */
   1231 
   1232 	/* first build the new sorted list */
   1233 	unsigned int n = curlevel + 1;
   1234 	spp = scbpp + n;
   1235 	cpp = cbpp + curlevel;
   1236 	do {
   1237 		cpp--;
   1238 		if (fcbp > *cpp) {
   1239 			*--spp = fcbp;
   1240 			do {
   1241 				*--spp = *cpp;
   1242 			} while (cpp-- != cbpp);
   1243 			goto inserted;
   1244 		}
   1245 		*--spp = *cpp;
   1246 	} while (cpp != cbpp);
   1247 	*--spp = fcbp;
   1248 inserted:
   1249 
   1250 	/* now check to see if this list of frames has already been seen */
   1251 	cbp = hashcombos[inx = (int)(*scbpp - frames)];
   1252 	if (cbp == NULL) {
   1253 		/*
   1254 		 * Easy case, this list hasn't been seen.
   1255 		 * Add it to the hash list.
   1256 		 */
   1257 		fcbp = (void *)((char *)scbpp - sizeof(struct combostr));
   1258 		hashcombos[inx] = fcbp;
   1259 		fcbp->c_next = fcbp->c_prev = fcbp;
   1260 		return false;
   1261 	}
   1262 	ecbp = cbp;
   1263 	do {
   1264 		cbpp = (void *)(cbp + 1);
   1265 		cpp = cbpp + n;
   1266 		spp = scbpp + n;
   1267 		cbpp++;	/* first frame is always the same */
   1268 		do {
   1269 			if (*--spp != *--cpp)
   1270 				goto next;
   1271 		} while (cpp != cbpp);
   1272 		/* we found a match */
   1273 #ifdef DEBUG
   1274 		if (debug > 3) {
   1275 			char buf[128];
   1276 			size_t pos;
   1277 
   1278 			debuglog("sort1: n%u", n);
   1279 			pos = 0;
   1280 			for (cpp = scbpp; cpp < scbpp + n; cpp++) {
   1281 				snprintf(buf + pos, sizeof(buf) - pos, " %s%c",
   1282 					stoc((*cpp)->c_vertex),
   1283 					pdir[(*cpp)->c_dir]);
   1284 				pos += strlen(buf + pos);
   1285 			}
   1286 			debuglog("%s", buf);
   1287 			printcombo(cbp, buf, sizeof(buf));
   1288 			debuglog("%s", buf);
   1289 			cbpp--;
   1290 			pos = 0;
   1291 			for (cpp = cbpp; cpp < cbpp + n; cpp++) {
   1292 				snprintf(buf + pos, sizeof(buf) - pos, " %s%c",
   1293 					stoc((*cpp)->c_vertex),
   1294 					pdir[(*cpp)->c_dir]);
   1295 				pos += strlen(buf + pos);
   1296 			}
   1297 			debuglog("%s", buf);
   1298 		}
   1299 #endif /* DEBUG */
   1300 		return true;
   1301 	next:
   1302 		;
   1303 	} while ((cbp = cbp->c_next) != ecbp);
   1304 	/*
   1305 	 * This list of frames hasn't been seen.
   1306 	 * Add it to the hash list.
   1307 	 */
   1308 	ecbp = cbp->c_prev;
   1309 	fcbp = (void *)((char *)scbpp - sizeof(struct combostr));
   1310 	fcbp->c_next = cbp;
   1311 	fcbp->c_prev = ecbp;
   1312 	cbp->c_prev = fcbp;
   1313 	ecbp->c_next = fcbp;
   1314 	return false;
   1315 }
   1316 
   1317 /*
   1318  * Print the combo into string buffer 'buf'.
   1319  */
   1320 #if !defined(DEBUG)
   1321 static
   1322 #endif
   1323 void
   1324 printcombo(struct combostr *cbp, char *buf, size_t max)
   1325 {
   1326 	struct combostr *tcbp;
   1327 	size_t pos = 0;
   1328 
   1329 	snprintf(buf + pos, max - pos, "%x/%d",
   1330 	    cbp->c_combo.s, cbp->c_nframes);
   1331 	pos += strlen(buf + pos);
   1332 
   1333 	for (; (tcbp = cbp->c_link[1]) != NULL; cbp = cbp->c_link[0]) {
   1334 		snprintf(buf + pos, max - pos, " %s%c%x",
   1335 		    stoc(tcbp->c_vertex), pdir[tcbp->c_dir], cbp->c_flags);
   1336 		pos += strlen(buf + pos);
   1337 	}
   1338 	snprintf(buf + pos, max - pos, " %s%c",
   1339 	    stoc(cbp->c_vertex), pdir[cbp->c_dir]);
   1340 }
   1341 
   1342 #ifdef DEBUG
   1343 void
   1344 markcombo(struct combostr *ocbp)
   1345 {
   1346 	struct combostr *cbp, **cbpp;
   1347 	struct elist *ep, *nep;
   1348 	struct spotstr *sp;
   1349 	int d, m, i;
   1350 	int nframes;
   1351 	int cmask, omask;
   1352 
   1353 	/* should never happen but check anyway */
   1354 	if ((nframes = ocbp->c_nframes) >= MAXDEPTH)
   1355 		return;
   1356 
   1357 	/*
   1358 	 * The lower level combo can be pointed to by more than one
   1359 	 * higher level 'struct combostr' so we can't modify the
   1360 	 * lower level. Therefore, higher level combos store the
   1361 	 * real mask of the lower level frame in c_emask[0] and the
   1362 	 * frame number in c_frameindex.
   1363 	 *
   1364 	 * First we traverse the tree from top to bottom and save the
   1365 	 * connection info. Then we traverse the tree from bottom to
   1366 	 * top overwriting lower levels with the newer emask information.
   1367 	 */
   1368 	ep = &einfo[nframes];
   1369 	cbpp = &ecombo[nframes];
   1370 	for (cbp = ocbp; cbp->c_link[1] != NULL; cbp = cbp->c_link[0]) {
   1371 		ep--;
   1372 		ep->e_combo = cbp;
   1373 		*--cbpp = cbp->c_link[1];
   1374 		ep->e_off = cbp->c_voff[1];
   1375 		ep->e_frameindex = cbp->c_frameindex;
   1376 		ep->e_fval.s = cbp->c_linkv[1].s;
   1377 		ep->e_framecnt = cbp->c_framecnt[1];
   1378 		ep->e_emask = cbp->c_emask[1];
   1379 	}
   1380 	cbp = ep->e_combo;
   1381 	ep--;
   1382 	ep->e_combo = cbp;
   1383 	*--cbpp = cbp->c_link[0];
   1384 	ep->e_off = cbp->c_voff[0];
   1385 	ep->e_frameindex = 0;
   1386 	ep->e_fval.s = cbp->c_linkv[0].s;
   1387 	ep->e_framecnt = cbp->c_framecnt[0];
   1388 	ep->e_emask = cbp->c_emask[0];
   1389 
   1390 	/* now update the emask info */
   1391 	int n = 0;
   1392 	for (i = 2, ep += 2; i < nframes; i++, ep++) {
   1393 		cbp = ep->e_combo;
   1394 		nep = &einfo[ep->e_frameindex];
   1395 		nep->e_framecnt = cbp->c_framecnt[0];
   1396 		nep->e_emask = cbp->c_emask[0];
   1397 
   1398 		if ((cbp->c_flags & C_LOOP) != 0) {
   1399 			n++;
   1400 			/*
   1401 			 * Account for the fact that this frame connects
   1402 			 * to a previous one (thus forming a loop).
   1403 			 */
   1404 			nep = &einfo[cbp->c_dir];
   1405 			if (--nep->e_framecnt != 0)
   1406 				nep->e_emask &= ~(1 << cbp->c_voff[0]);
   1407 			else
   1408 				nep->e_emask = 0;
   1409 		}
   1410 	}
   1411 
   1412 	/*
   1413 	 * We only need to update the emask values of "complete" loops
   1414 	 * to include the intersection spots.
   1415 	 */
   1416 	if (n != 0 && ocbp->c_combo.cv_force == 2) {
   1417 		/* process loops from the top down */
   1418 		ep = &einfo[nframes];
   1419 		do {
   1420 			ep--;
   1421 			cbp = ep->e_combo;
   1422 			if ((cbp->c_flags & C_LOOP) == 0)
   1423 				continue;
   1424 
   1425 			/*
   1426 			 * Update the emask values to include the
   1427 			 * intersection spots.
   1428 			 */
   1429 			nep = &einfo[cbp->c_dir];
   1430 			nep->e_framecnt = 1;
   1431 			nep->e_emask = 1 << cbp->c_voff[0];
   1432 			ep->e_framecnt = 1;
   1433 			ep->e_emask = 1 << ep->e_off;
   1434 			ep = &einfo[ep->e_frameindex];
   1435 			do {
   1436 				ep->e_framecnt = 1;
   1437 				ep->e_emask = 1 << ep->e_off;
   1438 				ep = &einfo[ep->e_frameindex];
   1439 			} while (ep > nep);
   1440 		} while (ep != einfo);
   1441 	}
   1442 
   1443 	/* mark all the frames with the completion spots */
   1444 	for (i = 0, ep = einfo, cbpp = ecombo; i < nframes; i++, ep++, cbpp++) {
   1445 		m = ep->e_emask;
   1446 		cbp = *cbpp;
   1447 		sp = &board[cbp->c_vertex];
   1448 		d = dd[cbp->c_dir];
   1449 		cmask = CFLAG << cbp->c_dir;
   1450 		omask = (IFLAG | CFLAG) << cbp->c_dir;
   1451 		int off = ep->e_fval.cv_win != 0 ? 6 : 5;
   1452 		/* LINTED 117: bitwise '>>' on signed value possibly nonportable */
   1453 		for (; --off >= 0; sp += d, m >>= 1)
   1454 			sp->s_flags |= (m & 1) != 0 ? omask : cmask;
   1455 	}
   1456 }
   1457 
   1458 void
   1459 clearcombo(struct combostr *cbp, int open)
   1460 {
   1461 	struct combostr *tcbp;
   1462 
   1463 	for (; (tcbp = cbp->c_link[1]) != NULL; cbp = cbp->c_link[0]) {
   1464 		clearcombo(tcbp, cbp->c_flags & C_OPEN_1);
   1465 		open = cbp->c_flags & C_OPEN_0;
   1466 	}
   1467 
   1468 	struct spotstr *sp = &board[cbp->c_vertex];
   1469 	int d = dd[cbp->c_dir];
   1470 	int mask = ~((IFLAG | CFLAG) << cbp->c_dir);
   1471 	int n = open != 0 ? 6 : 5;
   1472 	for (; --n >= 0; sp += d)
   1473 		sp->s_flags &= mask;
   1474 }
   1475 #endif /* DEBUG */
   1476