Home | History | Annotate | Line # | Download | only in gomoku
pickmove.c revision 1.54
      1 /*	$NetBSD: pickmove.c,v 1.54 2022/05/29 11:36:12 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.54 2022/05/29 11:36:12 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 					/* XXX: suspicious use of 'n' */
    312 					n = (spot_index)(sp - board);
    313 					BIT_SET(tmpmap, n);
    314 				}
    315 			}
    316 			/*
    317 			 * Try combining other frames that intersect
    318 			 * at this spot.
    319 			 */
    320 			makecombo2(cbp, sp, i, cb.s);
    321 		}
    322 		if (cp->s == 0x101 && color != nextcolor) {
    323 			if (nforce == 0)
    324 				memcpy(forcemap, tmpmap, sizeof(tmpmap));
    325 			else {
    326 				for (i = 0; (unsigned int)i < MAPSZ; i++)
    327 					forcemap[i] &= tmpmap[i];
    328 			}
    329 		}
    330 		/* mark frame as having been processed */
    331 		board[cbp->c_vertex].s_flags |= MFLAG << r;
    332 	} while ((cbp = cbp->c_next) != ecbp);
    333 
    334 	/*
    335 	 * Try to make new 3rd level combos, 4th level, etc.
    336 	 * Limit the search depth early in the game.
    337 	 */
    338 	/* LINTED 117: bitwise '>>' on signed value possibly nonportable */
    339 	for (unsigned int level = 2;
    340 	     level <= 1 + game.nmoves / 2 && combolen > n; level++) {
    341 		if (level >= 9)
    342 			break;	/* Do not think too long. */
    343 		if (debug != 0) {
    344 			debuglog("%cL%u %d %d %d", "BW"[color],
    345 			    level, combolen - n, combocnt, elistcnt);
    346 			refresh();
    347 		}
    348 		n = combolen;
    349 		addframes(level);
    350 	}
    351 
    352 	/* scan for combos at empty spots */
    353 	for (unsigned pos = PT(BSZ, BSZ + 1); pos-- > PT(1, 1); ) {
    354 		sp = &board[pos];
    355 		for (struct elist *ep = sp->s_empty; ep != NULL; ep = nep) {
    356 			cbp = ep->e_combo;
    357 			if (cbp->c_combo.s <= sp->s_combo[color].s) {
    358 				if (cbp->c_combo.s != sp->s_combo[color].s) {
    359 					sp->s_combo[color].s = cbp->c_combo.s;
    360 					sp->s_level[color] = cbp->c_nframes;
    361 				} else if (cbp->c_nframes < sp->s_level[color])
    362 					sp->s_level[color] = cbp->c_nframes;
    363 			}
    364 			nep = ep->e_next;
    365 			free(ep);
    366 			elistcnt--;
    367 		}
    368 		sp->s_empty = NULL;
    369 		for (struct elist *ep = sp->s_nempty; ep != NULL; ep = nep) {
    370 			cbp = ep->e_combo;
    371 			if (cbp->c_combo.s <= sp->s_combo[color].s) {
    372 				if (cbp->c_combo.s != sp->s_combo[color].s) {
    373 					sp->s_combo[color].s = cbp->c_combo.s;
    374 					sp->s_level[color] = cbp->c_nframes;
    375 				} else if (cbp->c_nframes < sp->s_level[color])
    376 					sp->s_level[color] = cbp->c_nframes;
    377 			}
    378 			nep = ep->e_next;
    379 			free(ep);
    380 			elistcnt--;
    381 		}
    382 		sp->s_nempty = NULL;
    383 	}
    384 
    385 	/* remove old combos */
    386 	if ((cbp = sortcombos) != NULL) {
    387 		struct combostr *ncbp;
    388 
    389 		/* scan the list */
    390 		ecbp = cbp;
    391 		do {
    392 			ncbp = cbp->c_next;
    393 			free(cbp);
    394 			combocnt--;
    395 		} while ((cbp = ncbp) != ecbp);
    396 		sortcombos = NULL;
    397 	}
    398 	combolen = 0;
    399 
    400 #ifdef DEBUG
    401 	if (combocnt != 0) {
    402 		debuglog("scanframes: %c combocnt %d", "BW"[color],
    403 			combocnt);
    404 		whatsup(0);
    405 	}
    406 	if (elistcnt != 0) {
    407 		debuglog("scanframes: %c elistcnt %d", "BW"[color],
    408 			elistcnt);
    409 		whatsup(0);
    410 	}
    411 #endif
    412 }
    413 
    414 /*
    415  * Compute all level 2 combos of frames intersecting spot 'osp'
    416  * within the frame 'ocbp' and combo value 'cv'.
    417  */
    418 static void
    419 makecombo2(struct combostr *ocbp, struct spotstr *osp, int off, int cv)
    420 {
    421 	struct combostr *ncbp;
    422 	int c;
    423 	int baseB, fcnt, emask, n;
    424 	union comboval ocb, fcb;
    425 	struct combostr **scbpp, *fcbp;
    426 	char tmp[128];
    427 
    428 	/* try to combine a new frame with those found so far */
    429 	ocb.s = cv;
    430 	baseB = ocb.cv_force + ocb.cv_win - 1;
    431 	fcnt = ocb.cv_force - 2;
    432 	emask = fcnt != 0 ? ((ocb.cv_win != 0 ? 0x1E : 0x1F) & ~(1 << off)) : 0;
    433 	for (int r = 4; --r >= 0; ) {		/* for each direction */
    434 	    /* don't include frames that overlap in the same direction */
    435 	    if (r == ocbp->c_dir)
    436 		continue;
    437 	    int d = dd[r];
    438 	    /*
    439 	     * Frame A combined with B is the same value as B combined with A
    440 	     * so skip frames that have already been processed (MFLAG).
    441 	     * Also skip blocked frames (BFLAG) and frames that are <1,x>
    442 	     * since combining another frame with it isn't valid.
    443 	     */
    444 	    int bmask = (BFLAG | FFLAG | MFLAG) << r;
    445 	    struct spotstr *fsp = osp;
    446 	    for (int f = 0; f < 5; f++, fsp -= d) {	/* for each frame */
    447 		if (fsp->s_occ == BORDER)
    448 		    break;
    449 		if ((fsp->s_flags & bmask) != 0)
    450 		    continue;
    451 
    452 		/* don't include frames of the wrong color */
    453 		fcb.s = fsp->s_fval[curcolor][r].s;
    454 		if (fcb.cv_force >= 6)
    455 		    continue;
    456 
    457 		/*
    458 		 * Get the combo value for this frame.
    459 		 * If this is the end point of the frame,
    460 		 * use the closed ended value for the frame.
    461 		 */
    462 		if ((f == 0 && fcb.cv_win != 0) || fcb.s == 0x101) {
    463 		    fcb.cv_force++;
    464 		    fcb.cv_win = 0;
    465 		}
    466 
    467 		/* compute combo value */
    468 		c = fcb.cv_force + ocb.cv_force - 3;
    469 		if (c > 4)
    470 		    continue;
    471 		n = fcb.cv_force + fcb.cv_win - 1;
    472 		if (baseB < n)
    473 		    n = baseB;
    474 
    475 		/* make a new combo! */
    476 		ncbp = (struct combostr *)malloc(sizeof(struct combostr) +
    477 		    2 * sizeof(struct combostr *));
    478 		if (ncbp == NULL)
    479 		    panic("Out of memory!");
    480 		scbpp = (void *)(ncbp + 1);
    481 		fcbp = &frames[fsp->s_frame[r]];
    482 		if (ocbp < fcbp) {
    483 		    scbpp[0] = ocbp;
    484 		    scbpp[1] = fcbp;
    485 		} else {
    486 		    scbpp[0] = fcbp;
    487 		    scbpp[1] = ocbp;
    488 		}
    489 		ncbp->c_combo.cv_force = c;
    490 		ncbp->c_combo.cv_win = n;
    491 		ncbp->c_link[0] = ocbp;
    492 		ncbp->c_link[1] = fcbp;
    493 		ncbp->c_linkv[0].s = ocb.s;
    494 		ncbp->c_linkv[1].s = fcb.s;
    495 		ncbp->c_voff[0] = off;
    496 		ncbp->c_voff[1] = f;
    497 		ncbp->c_vertex = (spot_index)(osp - board);
    498 		ncbp->c_nframes = 2;
    499 		ncbp->c_dir = 0;
    500 		ncbp->c_frameindex = 0;
    501 		ncbp->c_flags = ocb.cv_win != 0 ? C_OPEN_0 : 0;
    502 		if (fcb.cv_win != 0)
    503 		    ncbp->c_flags |= C_OPEN_1;
    504 		ncbp->c_framecnt[0] = fcnt;
    505 		ncbp->c_emask[0] = emask;
    506 		ncbp->c_framecnt[1] = fcb.cv_force - 2;
    507 		ncbp->c_emask[1] = ncbp->c_framecnt[1] != 0 ?
    508 		    ((fcb.cv_win != 0 ? 0x1E : 0x1F) & ~(1 << f)) : 0;
    509 		combocnt++;
    510 
    511 		if ((c == 1 && debug > 1) || debug > 3) {
    512 		    debuglog("%c c %d %d m %x %x o %d %d",
    513 			"bw"[curcolor],
    514 			ncbp->c_framecnt[0], ncbp->c_framecnt[1],
    515 			ncbp->c_emask[0], ncbp->c_emask[1],
    516 			ncbp->c_voff[0], ncbp->c_voff[1]);
    517 		    printcombo(ncbp, tmp, sizeof(tmp));
    518 		    debuglog("%s", tmp);
    519 		}
    520 		if (c > 1) {
    521 		    /* record the empty spots that will complete this combo */
    522 		    makeempty(ncbp);
    523 
    524 		    /* add the new combo to the end of the list */
    525 		    appendcombo(ncbp, curcolor);
    526 		} else {
    527 		    updatecombo(ncbp, curcolor);
    528 		    free(ncbp);
    529 		    combocnt--;
    530 		}
    531 #ifdef DEBUG
    532 		if ((c == 1 && debug > 1) || debug > 5) {
    533 		    markcombo(ncbp);
    534 		    bdisp();
    535 		    whatsup(0);
    536 		    clearcombo(ncbp, 0);
    537 		}
    538 #endif /* DEBUG */
    539 	    }
    540 	}
    541 }
    542 
    543 /*
    544  * Scan the sorted list of frames and try to add a frame to
    545  * combinations of 'level' number of frames.
    546  */
    547 static void
    548 addframes(unsigned int level)
    549 {
    550 	struct combostr *cbp, *ecbp;
    551 	struct spotstr *fsp;
    552 	struct elist *nep;
    553 	int i, r;
    554 	struct combostr **cbpp, *pcbp;
    555 	union comboval fcb, cb;
    556 
    557 	curlevel = level;
    558 
    559 	/* scan for combos at empty spots */
    560 	i = curcolor;
    561 	for (unsigned pos = PT(BSZ, BSZ + 1); pos-- > PT(1, 1); ) {
    562 		struct spotstr *sp = &board[pos];
    563 		for (struct elist *ep = sp->s_empty; ep != NULL; ep = nep) {
    564 			cbp = ep->e_combo;
    565 			if (cbp->c_combo.s <= sp->s_combo[i].s) {
    566 				if (cbp->c_combo.s != sp->s_combo[i].s) {
    567 					sp->s_combo[i].s = cbp->c_combo.s;
    568 					sp->s_level[i] = cbp->c_nframes;
    569 				} else if (cbp->c_nframes < sp->s_level[i])
    570 					sp->s_level[i] = cbp->c_nframes;
    571 			}
    572 			nep = ep->e_next;
    573 			free(ep);
    574 			elistcnt--;
    575 		}
    576 		sp->s_empty = sp->s_nempty;
    577 		sp->s_nempty = NULL;
    578 	}
    579 
    580 	/* try to add frames to the uncompleted combos at level curlevel */
    581 	cbp = ecbp = sortframes[curcolor];
    582 	do {
    583 		fsp = &board[cbp->c_vertex];
    584 		r = cbp->c_dir;
    585 		/* skip frames that are part of a <1,x> combo */
    586 		if ((fsp->s_flags & (FFLAG << r)) != 0)
    587 			continue;
    588 
    589 		/*
    590 		 * Don't include <1,x> combo frames,
    591 		 * treat it as a closed three in a row instead.
    592 		 */
    593 		fcb.s = fsp->s_fval[curcolor][r].s;
    594 		if (fcb.s == 0x101)
    595 			fcb.s = 0x200;
    596 
    597 		/*
    598 		 * If this is an open-ended frame, use
    599 		 * the combo value with the end closed.
    600 		 */
    601 		if (fsp->s_occ == EMPTY) {
    602 			if (fcb.cv_win != 0) {
    603 				cb.cv_force = fcb.cv_force + 1;
    604 				cb.cv_win = 0;
    605 			} else
    606 				cb.s = fcb.s;
    607 			makecombo(cbp, fsp, 0, cb.s);
    608 		}
    609 
    610 		/*
    611 		 * The next four spots are handled the same for both
    612 		 * open and closed ended frames.
    613 		 */
    614 		int d = dd[r];
    615 		struct spotstr *sp = fsp + d;
    616 		for (i = 1; i < 5; i++, sp += d) {
    617 			if (sp->s_occ != EMPTY)
    618 				continue;
    619 			makecombo(cbp, sp, i, fcb.s);
    620 		}
    621 	} while ((cbp = cbp->c_next) != ecbp);
    622 
    623 	/* put all the combos in the hash list on the sorted list */
    624 	cbpp = &hashcombos[FAREA];
    625 	do {
    626 		cbp = *--cbpp;
    627 		if (cbp == NULL)
    628 			continue;
    629 		*cbpp = NULL;
    630 		ecbp = sortcombos;
    631 		if (ecbp == NULL)
    632 			sortcombos = cbp;
    633 		else {
    634 			/* append to sort list */
    635 			pcbp = ecbp->c_prev;
    636 			pcbp->c_next = cbp;
    637 			ecbp->c_prev = cbp->c_prev;
    638 			cbp->c_prev->c_next = ecbp;
    639 			cbp->c_prev = pcbp;
    640 		}
    641 	} while (cbpp != hashcombos);
    642 }
    643 
    644 /*
    645  * Compute all level N combos of frames intersecting spot 'osp'
    646  * within the frame 'ocbp' and combo value 'cv'.
    647  */
    648 static void
    649 makecombo(struct combostr *ocbp, struct spotstr *osp, int off, int cv)
    650 {
    651 	struct combostr *cbp;
    652 	struct spotstr *sp;
    653 	struct combostr **scbpp;
    654 	int baseB, fcnt, emask, verts;
    655 	union comboval ocb;
    656 	struct overlap_info vertices[1];
    657 	char tmp[128];
    658 
    659 	/*
    660 	 * XXX: when I made functions static gcc started warning about
    661 	 * some members of vertices[0] maybe being used uninitialized.
    662 	 * For now, I'm just going to clear it rather than wade through
    663 	 * the logic to find out whether gcc or the code is wrong. I
    664 	 * wouldn't be surprised if it were the code though. - dholland
    665 	 */
    666 	memset(vertices, 0, sizeof(vertices));
    667 
    668 	ocb.s = cv;
    669 	baseB = ocb.cv_force + ocb.cv_win - 1;
    670 	fcnt = ocb.cv_force - 2;
    671 	emask = fcnt != 0 ? ((ocb.cv_win != 0 ? 0x1E : 0x1F) & ~(1 << off)) : 0;
    672 	for (struct elist *ep = osp->s_empty; ep != NULL; ep = ep->e_next) {
    673 	    /* check for various kinds of overlap */
    674 	    cbp = ep->e_combo;
    675 	    verts = checkframes(cbp, ocbp, osp, cv, vertices);
    676 	    if (verts < 0)
    677 		continue;
    678 
    679 	    /* check to see if this frame forms a valid loop */
    680 	    if (verts > 0) {
    681 		sp = &board[vertices[0].o_intersect];
    682 #ifdef DEBUG
    683 		if (sp->s_occ != EMPTY) {
    684 		    debuglog("loop: %c %s", "BW"[curcolor],
    685 			stoc((spot_index)(sp - board)));
    686 		    whatsup(0);
    687 		}
    688 #endif
    689 		/*
    690 		 * It is a valid loop if the intersection spot
    691 		 * of the frame we are trying to attach is one
    692 		 * of the completion spots of the combostr
    693 		 * we are trying to attach the frame to.
    694 		 */
    695 		for (struct elist *nep = sp->s_empty;
    696 			nep != NULL; nep = nep->e_next) {
    697 		    if (nep->e_combo == cbp)
    698 			goto fnd;
    699 		    if (nep->e_combo->c_nframes < cbp->c_nframes)
    700 			break;
    701 		}
    702 		/* frame overlaps but not at a valid spot */
    703 		continue;
    704 	    fnd:
    705 		;
    706 	    }
    707 
    708 	    /* compute the first half of the combo value */
    709 	    int c = cbp->c_combo.cv_force + ocb.cv_force - verts - 3;
    710 	    if (c > 4)
    711 		continue;
    712 
    713 	    /* compute the second half of the combo value */
    714 	    int n = ep->e_fval.cv_force + ep->e_fval.cv_win - 1;
    715 	    if (baseB < n)
    716 		n = baseB;
    717 
    718 	    /* make a new combo! */
    719 	    struct combostr *ncbp = malloc(sizeof(struct combostr) +
    720 		(cbp->c_nframes + 1) * sizeof(struct combostr *));
    721 	    if (ncbp == NULL)
    722 		panic("Out of memory!");
    723 	    scbpp = (void *)(ncbp + 1);
    724 	    if (sortcombo(scbpp, (void *)(cbp + 1), ocbp)) {
    725 		free(ncbp);
    726 		continue;
    727 	    }
    728 	    combocnt++;
    729 
    730 	    ncbp->c_combo.cv_force = c;
    731 	    ncbp->c_combo.cv_win = n;
    732 	    ncbp->c_link[0] = cbp;
    733 	    ncbp->c_link[1] = ocbp;
    734 	    ncbp->c_linkv[1].s = ocb.s;
    735 	    ncbp->c_voff[1] = off;
    736 	    ncbp->c_vertex = (spot_index)(osp - board);
    737 	    ncbp->c_nframes = cbp->c_nframes + 1;
    738 	    ncbp->c_flags = ocb.cv_win != 0 ? C_OPEN_1 : 0;
    739 	    ncbp->c_frameindex = ep->e_frameindex;
    740 	    /*
    741 	     * Update the completion spot mask of the frame we
    742 	     * are attaching 'ocbp' to so the intersection isn't
    743 	     * listed twice.
    744 	     */
    745 	    ncbp->c_framecnt[0] = ep->e_framecnt;
    746 	    ncbp->c_emask[0] = ep->e_emask;
    747 	    if (verts != 0) {
    748 		ncbp->c_flags |= C_LOOP;
    749 		ncbp->c_dir = vertices[0].o_frameindex;
    750 		ncbp->c_framecnt[1] = fcnt - 1;
    751 		if (ncbp->c_framecnt[1] != 0) {
    752 		    n = (vertices[0].o_intersect - ocbp->c_vertex) /
    753 			dd[ocbp->c_dir];
    754 		    ncbp->c_emask[1] = emask & ~(1 << n);
    755 		} else
    756 		    ncbp->c_emask[1] = 0;
    757 		ncbp->c_voff[0] = vertices[0].o_off;
    758 	    } else {
    759 		ncbp->c_dir = 0;
    760 		ncbp->c_framecnt[1] = fcnt;
    761 		ncbp->c_emask[1] = emask;
    762 		ncbp->c_voff[0] = ep->e_off;
    763 	    }
    764 
    765 	    if ((c == 1 && debug > 1) || debug > 3) {
    766 		debuglog("%c v%d i%d d%d c %d %d m %x %x o %d %d",
    767 		    "bw"[curcolor], verts, ncbp->c_frameindex, ncbp->c_dir,
    768 		    ncbp->c_framecnt[0], ncbp->c_framecnt[1],
    769 		    ncbp->c_emask[0], ncbp->c_emask[1],
    770 		    ncbp->c_voff[0], ncbp->c_voff[1]);
    771 		printcombo(ncbp, tmp, sizeof(tmp));
    772 		debuglog("%s", tmp);
    773 	    }
    774 	    if (c > 1) {
    775 		/* record the empty spots that will complete this combo */
    776 		makeempty(ncbp);
    777 		combolen++;
    778 	    } else {
    779 		/* update board values */
    780 		updatecombo(ncbp, curcolor);
    781 	    }
    782 #ifdef DEBUG
    783 	    if ((c == 1 && debug > 1) || debug > 4) {
    784 		markcombo(ncbp);
    785 		bdisp();
    786 		whatsup(0);
    787 		clearcombo(ncbp, 0);
    788 	    }
    789 #endif /* DEBUG */
    790 	}
    791 }
    792 
    793 #define MAXDEPTH	100
    794 static struct elist einfo[MAXDEPTH];
    795 static struct combostr *ecombo[MAXDEPTH];	/* separate from elist to save space */
    796 
    797 /*
    798  * Add the combostr 'ocbp' to the empty spots list for each empty spot
    799  * in 'ocbp' that will complete the combo.
    800  */
    801 static void
    802 makeempty(struct combostr *ocbp)
    803 {
    804 	struct combostr *cbp, **cbpp;
    805 	struct elist *ep, *nep;
    806 	struct spotstr *sp;
    807 	int d, emask, i;
    808 	int nframes;
    809 	char tmp[128];
    810 
    811 	if (debug > 2) {
    812 		printcombo(ocbp, tmp, sizeof(tmp));
    813 		debuglog("E%c %s", "bw"[curcolor], tmp);
    814 	}
    815 
    816 	/* should never happen but check anyway */
    817 	if ((nframes = ocbp->c_nframes) >= MAXDEPTH)
    818 		return;
    819 
    820 	/*
    821 	 * The lower level combo can be pointed to by more than one
    822 	 * higher level 'struct combostr' so we can't modify the
    823 	 * lower level. Therefore, higher level combos store the
    824 	 * real mask of the lower level frame in c_emask[0] and the
    825 	 * frame number in c_frameindex.
    826 	 *
    827 	 * First we traverse the tree from top to bottom and save the
    828 	 * connection info. Then we traverse the tree from bottom to
    829 	 * top overwriting lower levels with the newer emask information.
    830 	 */
    831 	ep = &einfo[nframes];
    832 	cbpp = &ecombo[nframes];
    833 	for (cbp = ocbp; cbp->c_link[1] != NULL; cbp = cbp->c_link[0]) {
    834 		ep--;
    835 		ep->e_combo = cbp;
    836 		*--cbpp = cbp->c_link[1];
    837 		ep->e_off = cbp->c_voff[1];
    838 		ep->e_frameindex = cbp->c_frameindex;
    839 		ep->e_fval.s = cbp->c_linkv[1].s;
    840 		ep->e_framecnt = cbp->c_framecnt[1];
    841 		ep->e_emask = cbp->c_emask[1];
    842 	}
    843 	cbp = ep->e_combo;
    844 	ep--;
    845 	ep->e_combo = cbp;
    846 	*--cbpp = cbp->c_link[0];
    847 	ep->e_off = cbp->c_voff[0];
    848 	ep->e_frameindex = 0;
    849 	ep->e_fval.s = cbp->c_linkv[0].s;
    850 	ep->e_framecnt = cbp->c_framecnt[0];
    851 	ep->e_emask = cbp->c_emask[0];
    852 
    853 	/* now update the emask info */
    854 	int n = 0;
    855 	for (i = 2, ep += 2; i < nframes; i++, ep++) {
    856 		cbp = ep->e_combo;
    857 		nep = &einfo[ep->e_frameindex];
    858 		nep->e_framecnt = cbp->c_framecnt[0];
    859 		nep->e_emask = cbp->c_emask[0];
    860 
    861 		if ((cbp->c_flags & C_LOOP) != 0) {
    862 			n++;
    863 			/*
    864 			 * Account for the fact that this frame connects
    865 			 * to a previous one (thus forming a loop).
    866 			 */
    867 			nep = &einfo[cbp->c_dir];
    868 			if (--nep->e_framecnt != 0)
    869 				nep->e_emask &= ~(1 << cbp->c_voff[0]);
    870 			else
    871 				nep->e_emask = 0;
    872 		}
    873 	}
    874 
    875 	/*
    876 	 * We only need to update the emask values of "complete" loops
    877 	 * to include the intersection spots.
    878 	 */
    879 	if (n != 0 && ocbp->c_combo.cv_force == 2) {
    880 		/* process loops from the top down */
    881 		ep = &einfo[nframes];
    882 		do {
    883 			ep--;
    884 			cbp = ep->e_combo;
    885 			if ((cbp->c_flags & C_LOOP) == 0)
    886 				continue;
    887 
    888 			/*
    889 			 * Update the emask values to include the
    890 			 * intersection spots.
    891 			 */
    892 			nep = &einfo[cbp->c_dir];
    893 			nep->e_framecnt = 1;
    894 			nep->e_emask = 1 << cbp->c_voff[0];
    895 			ep->e_framecnt = 1;
    896 			ep->e_emask = 1 << ep->e_off;
    897 			ep = &einfo[ep->e_frameindex];
    898 			do {
    899 				ep->e_framecnt = 1;
    900 				ep->e_emask = 1 << ep->e_off;
    901 				ep = &einfo[ep->e_frameindex];
    902 			} while (ep > nep);
    903 		} while (ep != einfo);
    904 	}
    905 
    906 	/* check all the frames for completion spots */
    907 	for (i = 0, ep = einfo, cbpp = ecombo; i < nframes; i++, ep++, cbpp++) {
    908 		/* skip this frame if there are no incomplete spots in it */
    909 		if ((emask = ep->e_emask) == 0)
    910 			continue;
    911 		cbp = *cbpp;
    912 		sp = &board[cbp->c_vertex];
    913 		d = dd[cbp->c_dir];
    914 		for (int off = 0, m = 1; off < 5; off++, sp += d, m <<= 1) {
    915 			if (sp->s_occ != EMPTY || (emask & m) == 0)
    916 				continue;
    917 
    918 			/* add the combo to the list of empty spots */
    919 			nep = (struct elist *)malloc(sizeof(struct elist));
    920 			if (nep == NULL)
    921 				panic("Out of memory!");
    922 			nep->e_combo = ocbp;
    923 			nep->e_off = off;
    924 			nep->e_frameindex = i;
    925 			if (ep->e_framecnt > 1) {
    926 				nep->e_framecnt = ep->e_framecnt - 1;
    927 				nep->e_emask = emask & ~m;
    928 			} else {
    929 				nep->e_framecnt = 0;
    930 				nep->e_emask = 0;
    931 			}
    932 			nep->e_fval.s = ep->e_fval.s;
    933 			if (debug > 2) {
    934 				debuglog("e %s o%d i%d c%d m%x %x",
    935 				    stoc((spot_index)(sp - board)),
    936 				    nep->e_off,
    937 				    nep->e_frameindex,
    938 				    nep->e_framecnt,
    939 				    nep->e_emask,
    940 				    nep->e_fval.s);
    941 			}
    942 
    943 			/* sort by the number of frames in the combo */
    944 			nep->e_next = sp->s_nempty;
    945 			sp->s_nempty = nep;
    946 			elistcnt++;
    947 		}
    948 	}
    949 }
    950 
    951 /*
    952  * Update the board value based on the combostr.
    953  * This is called only if 'cbp' is a <1,x> combo.
    954  * We handle things differently depending on whether the next move
    955  * would be trying to "complete" the combo or trying to block it.
    956  */
    957 static void
    958 updatecombo(struct combostr *cbp, int color)
    959 {
    960 	struct combostr *tcbp;
    961 	int nframes, flags;
    962 	union comboval cb;
    963 
    964 	flags = 0;
    965 	/* save the top level value for the whole combo */
    966 	cb.cv_force = cbp->c_combo.cv_force;
    967 	nframes = cbp->c_nframes;
    968 
    969 	if (color != nextcolor)
    970 		memset(tmpmap, 0, sizeof(tmpmap));
    971 
    972 	for (; (tcbp = cbp->c_link[1]) != NULL; cbp = cbp->c_link[0]) {
    973 		flags = cbp->c_flags;
    974 		cb.cv_win = cbp->c_combo.cv_win;
    975 		if (color == nextcolor) {
    976 			/* update the board value for the vertex */
    977 			struct spotstr *sp = &board[cbp->c_vertex];
    978 			sp->s_nforce[color]++;
    979 			if (cb.s <= sp->s_combo[color].s) {
    980 				if (cb.s != sp->s_combo[color].s) {
    981 					sp->s_combo[color].s = cb.s;
    982 					sp->s_level[color] = nframes;
    983 				} else if (nframes < sp->s_level[color])
    984 					sp->s_level[color] = nframes;
    985 			}
    986 		} else {
    987 			/* update the board values for each spot in frame */
    988 			spot_index s = tcbp->c_vertex;
    989 			struct spotstr *sp = &board[s];
    990 			int d = dd[tcbp->c_dir];
    991 			int i = (flags & C_OPEN_1) != 0 ? 6 : 5;
    992 			for (; --i >= 0; sp += d, s += d) {
    993 				if (sp->s_occ != EMPTY)
    994 					continue;
    995 				sp->s_nforce[color]++;
    996 				if (cb.s <= sp->s_combo[color].s) {
    997 					if (cb.s != sp->s_combo[color].s) {
    998 						sp->s_combo[color].s = cb.s;
    999 						sp->s_level[color] = nframes;
   1000 					} else if (nframes < sp->s_level[color])
   1001 						sp->s_level[color] = nframes;
   1002 				}
   1003 				BIT_SET(tmpmap, s);
   1004 			}
   1005 		}
   1006 
   1007 		/* mark the frame as being part of a <1,x> combo */
   1008 		board[tcbp->c_vertex].s_flags |= FFLAG << tcbp->c_dir;
   1009 	}
   1010 
   1011 	if (color != nextcolor) {
   1012 		/* update the board values for each spot in frame */
   1013 		spot_index s = cbp->c_vertex;
   1014 		struct spotstr *sp = &board[s];
   1015 		int d = dd[cbp->c_dir];
   1016 		int i = (flags & C_OPEN_0) != 0 ? 6 : 5;
   1017 		for (; --i >= 0; sp += d, s += d) {
   1018 			if (sp->s_occ != EMPTY)
   1019 				continue;
   1020 			sp->s_nforce[color]++;
   1021 			if (cb.s <= sp->s_combo[color].s) {
   1022 				if (cb.s != sp->s_combo[color].s) {
   1023 					sp->s_combo[color].s = cb.s;
   1024 					sp->s_level[color] = nframes;
   1025 				} else if (nframes < sp->s_level[color])
   1026 					sp->s_level[color] = nframes;
   1027 			}
   1028 			BIT_SET(tmpmap, s);
   1029 		}
   1030 		if (nforce == 0)
   1031 			memcpy(forcemap, tmpmap, sizeof(tmpmap));
   1032 		else {
   1033 			for (i = 0; (unsigned int)i < MAPSZ; i++)
   1034 				forcemap[i] &= tmpmap[i];
   1035 		}
   1036 		nforce++;
   1037 	}
   1038 
   1039 	/* mark the frame as being part of a <1,x> combo */
   1040 	board[cbp->c_vertex].s_flags |= FFLAG << cbp->c_dir;
   1041 }
   1042 
   1043 /*
   1044  * Add combo to the end of the list.
   1045  */
   1046 static void
   1047 appendcombo(struct combostr *cbp, int color __unused)
   1048 {
   1049 	struct combostr *pcbp, *ncbp;
   1050 
   1051 	combolen++;
   1052 	ncbp = sortcombos;
   1053 	if (ncbp == NULL) {
   1054 		sortcombos = cbp;
   1055 		cbp->c_next = cbp;
   1056 		cbp->c_prev = cbp;
   1057 		return;
   1058 	}
   1059 	pcbp = ncbp->c_prev;
   1060 	cbp->c_next = ncbp;
   1061 	cbp->c_prev = pcbp;
   1062 	ncbp->c_prev = cbp;
   1063 	pcbp->c_next = cbp;
   1064 }
   1065 
   1066 /*
   1067  * Return zero if it is valid to combine frame 'fcbp' with the frames
   1068  * in 'cbp' and forms a linked chain of frames (i.e., a tree; no loops).
   1069  * Return positive if combining frame 'fcbp' to the frames in 'cbp'
   1070  * would form some kind of valid loop. Also return the intersection spots
   1071  * in 'vertices[]' beside the known intersection at spot 'osp'.
   1072  * Return -1 if 'fcbp' should not be combined with 'cbp'.
   1073  * 'cv' is the combo value for frame 'fcbp'.
   1074  */
   1075 static int
   1076 checkframes(struct combostr *cbp, struct combostr *fcbp, struct spotstr *osp,
   1077 	    int cv, struct overlap_info *vertices)
   1078 {
   1079 	struct combostr *tcbp, *lcbp;
   1080 	int i, n, mask, flags, verts, myindex, fcnt;
   1081 	union comboval cb;
   1082 	u_char *str;
   1083 
   1084 	lcbp = NULL;
   1085 	flags = 0;
   1086 
   1087 	cb.s = cv;
   1088 	fcnt = cb.cv_force - 2;
   1089 	verts = 0;
   1090 	myindex = cbp->c_nframes;
   1091 	n = (frame_index)(fcbp - frames) * FAREA;
   1092 	str = &overlap[n];
   1093 	spot_index *ip = &intersect[n];
   1094 	/*
   1095 	 * i == which overlap bit to test based on whether 'fcbp' is
   1096 	 * an open or closed frame.
   1097 	 */
   1098 	i = cb.cv_win != 0 ? 2 : 0;
   1099 	for (; (tcbp = cbp->c_link[1]) != NULL;
   1100 	    lcbp = cbp, cbp = cbp->c_link[0]) {
   1101 		if (tcbp == fcbp)
   1102 			return -1;	/* fcbp is already included */
   1103 
   1104 		/* check for intersection of 'tcbp' with 'fcbp' */
   1105 		myindex--;
   1106 		mask = str[tcbp - frames];
   1107 		flags = cbp->c_flags;
   1108 		n = i + ((flags & C_OPEN_1) != 0 ? 1 : 0);
   1109 		if ((mask & (1 << n)) != 0) {
   1110 			/*
   1111 			 * The two frames are not independent if they
   1112 			 * both lie in the same line and intersect at
   1113 			 * more than one point.
   1114 			 */
   1115 			if (tcbp->c_dir == fcbp->c_dir &&
   1116 			    (mask & (0x10 << n)) != 0)
   1117 				return -1;
   1118 			/*
   1119 			 * If this is not the spot we are attaching
   1120 			 * 'fcbp' to, and it is a reasonable intersection
   1121 			 * spot, then there might be a loop.
   1122 			 */
   1123 			spot_index s = ip[tcbp - frames];
   1124 			if (osp != &board[s]) {
   1125 				/* check to see if this is a valid loop */
   1126 				if (verts != 0)
   1127 					return -1;
   1128 				if (fcnt == 0 || cbp->c_framecnt[1] == 0)
   1129 					return -1;
   1130 				/*
   1131 				 * Check to be sure the intersection is not
   1132 				 * one of the end points if it is an
   1133 				 * open-ended frame.
   1134 				 */
   1135 				if ((flags & C_OPEN_1) != 0 &&
   1136 				    (s == tcbp->c_vertex ||
   1137 				     s == tcbp->c_vertex + 5 * dd[tcbp->c_dir]))
   1138 					return -1;	/* invalid overlap */
   1139 				if (cb.cv_win != 0 &&
   1140 				    (s == fcbp->c_vertex ||
   1141 				     s == fcbp->c_vertex + 5 * dd[fcbp->c_dir]))
   1142 					return -1;	/* invalid overlap */
   1143 
   1144 				vertices->o_intersect = s;
   1145 				vertices->o_off = (s - tcbp->c_vertex) /
   1146 					dd[tcbp->c_dir];
   1147 				vertices->o_frameindex = myindex;
   1148 				verts++;
   1149 			}
   1150 		}
   1151 		n = i + ((flags & C_OPEN_0) != 0 ? 1 : 0);
   1152 	}
   1153 	if (cbp == fcbp)
   1154 		return -1;	/* fcbp is already included */
   1155 
   1156 	/* check for intersection of 'cbp' with 'fcbp' */
   1157 	mask = str[cbp - frames];
   1158 	if ((mask & (1 << n)) != 0) {
   1159 		/*
   1160 		 * The two frames are not independent if they
   1161 		 * both lie in the same line and intersect at
   1162 		 * more than one point.
   1163 		 */
   1164 		if (cbp->c_dir == fcbp->c_dir && (mask & (0x10 << n)) != 0)
   1165 			return -1;
   1166 		/*
   1167 		 * If this is not the spot we are attaching
   1168 		 * 'fcbp' to, and it is a reasonable intersection
   1169 		 * spot, then there might be a loop.
   1170 		 */
   1171 		spot_index s = ip[cbp - frames];
   1172 		if (osp != &board[s]) {
   1173 			/* check to see if this is a valid loop */
   1174 			if (verts != 0)
   1175 				return -1;
   1176 			if (fcnt == 0 || lcbp->c_framecnt[0] == 0)
   1177 				return -1;
   1178 			/*
   1179 			 * Check to be sure the intersection is not
   1180 			 * one of the end points if it is an open-ended
   1181 			 * frame.
   1182 			 */
   1183 			if ((flags & C_OPEN_0) != 0 &&
   1184 			    (s == cbp->c_vertex ||
   1185 			     s == cbp->c_vertex + 5 * dd[cbp->c_dir]))
   1186 				return -1;	/* invalid overlap */
   1187 			if (cb.cv_win != 0 &&
   1188 			    (s == fcbp->c_vertex ||
   1189 			     s == fcbp->c_vertex + 5 * dd[fcbp->c_dir]))
   1190 				return -1;	/* invalid overlap */
   1191 
   1192 			vertices->o_intersect = s;
   1193 			vertices->o_off = (s - cbp->c_vertex) /
   1194 				dd[cbp->c_dir];
   1195 			vertices->o_frameindex = 0;
   1196 			verts++;
   1197 		}
   1198 	}
   1199 	return verts;
   1200 }
   1201 
   1202 /*
   1203  * Merge sort the frame 'fcbp' and the sorted list of frames 'cbpp' and
   1204  * store the result in 'scbpp'. 'curlevel' is the size of the 'cbpp' array.
   1205  * Return true if this list of frames is already in the hash list.
   1206  * Otherwise, add the new combo to the hash list.
   1207  */
   1208 static bool
   1209 sortcombo(struct combostr **scbpp, struct combostr **cbpp,
   1210 	  struct combostr *fcbp)
   1211 {
   1212 	struct combostr **spp, **cpp;
   1213 	struct combostr *cbp, *ecbp;
   1214 	int inx;
   1215 
   1216 #ifdef DEBUG
   1217 	if (debug > 3) {
   1218 		char buf[128];
   1219 		size_t pos;
   1220 
   1221 		debuglog("sortc: %s%c l%u", stoc(fcbp->c_vertex),
   1222 			pdir[fcbp->c_dir], curlevel);
   1223 		pos = 0;
   1224 		for (cpp = cbpp; cpp < cbpp + curlevel; cpp++) {
   1225 			snprintf(buf + pos, sizeof(buf) - pos, " %s%c",
   1226 				stoc((*cpp)->c_vertex), pdir[(*cpp)->c_dir]);
   1227 			pos += strlen(buf + pos);
   1228 		}
   1229 		debuglog("%s", buf);
   1230 	}
   1231 #endif /* DEBUG */
   1232 
   1233 	/* first build the new sorted list */
   1234 	unsigned int n = curlevel + 1;
   1235 	spp = scbpp + n;
   1236 	cpp = cbpp + curlevel;
   1237 	do {
   1238 		cpp--;
   1239 		if (fcbp > *cpp) {
   1240 			*--spp = fcbp;
   1241 			do {
   1242 				*--spp = *cpp;
   1243 			} while (cpp-- != cbpp);
   1244 			goto inserted;
   1245 		}
   1246 		*--spp = *cpp;
   1247 	} while (cpp != cbpp);
   1248 	*--spp = fcbp;
   1249 inserted:
   1250 
   1251 	/* now check to see if this list of frames has already been seen */
   1252 	cbp = hashcombos[inx = (frame_index)(*scbpp - frames)];
   1253 	if (cbp == NULL) {
   1254 		/*
   1255 		 * Easy case, this list hasn't been seen.
   1256 		 * Add it to the hash list.
   1257 		 */
   1258 		fcbp = (void *)((char *)scbpp - sizeof(struct combostr));
   1259 		hashcombos[inx] = fcbp;
   1260 		fcbp->c_next = fcbp->c_prev = fcbp;
   1261 		return false;
   1262 	}
   1263 	ecbp = cbp;
   1264 	do {
   1265 		cbpp = (void *)(cbp + 1);
   1266 		cpp = cbpp + n;
   1267 		spp = scbpp + n;
   1268 		cbpp++;	/* first frame is always the same */
   1269 		do {
   1270 			if (*--spp != *--cpp)
   1271 				goto next;
   1272 		} while (cpp != cbpp);
   1273 		/* we found a match */
   1274 #ifdef DEBUG
   1275 		if (debug > 3) {
   1276 			char buf[128];
   1277 			size_t pos;
   1278 
   1279 			debuglog("sort1: n%u", n);
   1280 			pos = 0;
   1281 			for (cpp = scbpp; cpp < scbpp + n; cpp++) {
   1282 				snprintf(buf + pos, sizeof(buf) - pos, " %s%c",
   1283 					stoc((*cpp)->c_vertex),
   1284 					pdir[(*cpp)->c_dir]);
   1285 				pos += strlen(buf + pos);
   1286 			}
   1287 			debuglog("%s", buf);
   1288 			printcombo(cbp, buf, sizeof(buf));
   1289 			debuglog("%s", buf);
   1290 			cbpp--;
   1291 			pos = 0;
   1292 			for (cpp = cbpp; cpp < cbpp + n; cpp++) {
   1293 				snprintf(buf + pos, sizeof(buf) - pos, " %s%c",
   1294 					stoc((*cpp)->c_vertex),
   1295 					pdir[(*cpp)->c_dir]);
   1296 				pos += strlen(buf + pos);
   1297 			}
   1298 			debuglog("%s", buf);
   1299 		}
   1300 #endif /* DEBUG */
   1301 		return true;
   1302 	next:
   1303 		;
   1304 	} while ((cbp = cbp->c_next) != ecbp);
   1305 	/*
   1306 	 * This list of frames hasn't been seen.
   1307 	 * Add it to the hash list.
   1308 	 */
   1309 	ecbp = cbp->c_prev;
   1310 	fcbp = (void *)((char *)scbpp - sizeof(struct combostr));
   1311 	fcbp->c_next = cbp;
   1312 	fcbp->c_prev = ecbp;
   1313 	cbp->c_prev = fcbp;
   1314 	ecbp->c_next = fcbp;
   1315 	return false;
   1316 }
   1317 
   1318 /*
   1319  * Print the combo into string buffer 'buf'.
   1320  */
   1321 #if !defined(DEBUG)
   1322 static
   1323 #endif
   1324 void
   1325 printcombo(struct combostr *cbp, char *buf, size_t max)
   1326 {
   1327 	struct combostr *tcbp;
   1328 	size_t pos = 0;
   1329 
   1330 	snprintf(buf + pos, max - pos, "%x/%d",
   1331 	    cbp->c_combo.s, cbp->c_nframes);
   1332 	pos += strlen(buf + pos);
   1333 
   1334 	for (; (tcbp = cbp->c_link[1]) != NULL; cbp = cbp->c_link[0]) {
   1335 		snprintf(buf + pos, max - pos, " %s%c%x",
   1336 		    stoc(tcbp->c_vertex), pdir[tcbp->c_dir], cbp->c_flags);
   1337 		pos += strlen(buf + pos);
   1338 	}
   1339 	snprintf(buf + pos, max - pos, " %s%c",
   1340 	    stoc(cbp->c_vertex), pdir[cbp->c_dir]);
   1341 }
   1342 
   1343 #ifdef DEBUG
   1344 void
   1345 markcombo(struct combostr *ocbp)
   1346 {
   1347 	struct combostr *cbp, **cbpp;
   1348 	struct elist *ep, *nep;
   1349 	struct spotstr *sp;
   1350 	int d, m, i;
   1351 	int nframes;
   1352 	int cmask, omask;
   1353 
   1354 	/* should never happen but check anyway */
   1355 	if ((nframes = ocbp->c_nframes) >= MAXDEPTH)
   1356 		return;
   1357 
   1358 	/*
   1359 	 * The lower level combo can be pointed to by more than one
   1360 	 * higher level 'struct combostr' so we can't modify the
   1361 	 * lower level. Therefore, higher level combos store the
   1362 	 * real mask of the lower level frame in c_emask[0] and the
   1363 	 * frame number in c_frameindex.
   1364 	 *
   1365 	 * First we traverse the tree from top to bottom and save the
   1366 	 * connection info. Then we traverse the tree from bottom to
   1367 	 * top overwriting lower levels with the newer emask information.
   1368 	 */
   1369 	ep = &einfo[nframes];
   1370 	cbpp = &ecombo[nframes];
   1371 	for (cbp = ocbp; cbp->c_link[1] != NULL; cbp = cbp->c_link[0]) {
   1372 		ep--;
   1373 		ep->e_combo = cbp;
   1374 		*--cbpp = cbp->c_link[1];
   1375 		ep->e_off = cbp->c_voff[1];
   1376 		ep->e_frameindex = cbp->c_frameindex;
   1377 		ep->e_fval.s = cbp->c_linkv[1].s;
   1378 		ep->e_framecnt = cbp->c_framecnt[1];
   1379 		ep->e_emask = cbp->c_emask[1];
   1380 	}
   1381 	cbp = ep->e_combo;
   1382 	ep--;
   1383 	ep->e_combo = cbp;
   1384 	*--cbpp = cbp->c_link[0];
   1385 	ep->e_off = cbp->c_voff[0];
   1386 	ep->e_frameindex = 0;
   1387 	ep->e_fval.s = cbp->c_linkv[0].s;
   1388 	ep->e_framecnt = cbp->c_framecnt[0];
   1389 	ep->e_emask = cbp->c_emask[0];
   1390 
   1391 	/* now update the emask info */
   1392 	int n = 0;
   1393 	for (i = 2, ep += 2; i < nframes; i++, ep++) {
   1394 		cbp = ep->e_combo;
   1395 		nep = &einfo[ep->e_frameindex];
   1396 		nep->e_framecnt = cbp->c_framecnt[0];
   1397 		nep->e_emask = cbp->c_emask[0];
   1398 
   1399 		if ((cbp->c_flags & C_LOOP) != 0) {
   1400 			n++;
   1401 			/*
   1402 			 * Account for the fact that this frame connects
   1403 			 * to a previous one (thus forming a loop).
   1404 			 */
   1405 			nep = &einfo[cbp->c_dir];
   1406 			if (--nep->e_framecnt != 0)
   1407 				nep->e_emask &= ~(1 << cbp->c_voff[0]);
   1408 			else
   1409 				nep->e_emask = 0;
   1410 		}
   1411 	}
   1412 
   1413 	/*
   1414 	 * We only need to update the emask values of "complete" loops
   1415 	 * to include the intersection spots.
   1416 	 */
   1417 	if (n != 0 && ocbp->c_combo.cv_force == 2) {
   1418 		/* process loops from the top down */
   1419 		ep = &einfo[nframes];
   1420 		do {
   1421 			ep--;
   1422 			cbp = ep->e_combo;
   1423 			if ((cbp->c_flags & C_LOOP) == 0)
   1424 				continue;
   1425 
   1426 			/*
   1427 			 * Update the emask values to include the
   1428 			 * intersection spots.
   1429 			 */
   1430 			nep = &einfo[cbp->c_dir];
   1431 			nep->e_framecnt = 1;
   1432 			nep->e_emask = 1 << cbp->c_voff[0];
   1433 			ep->e_framecnt = 1;
   1434 			ep->e_emask = 1 << ep->e_off;
   1435 			ep = &einfo[ep->e_frameindex];
   1436 			do {
   1437 				ep->e_framecnt = 1;
   1438 				ep->e_emask = 1 << ep->e_off;
   1439 				ep = &einfo[ep->e_frameindex];
   1440 			} while (ep > nep);
   1441 		} while (ep != einfo);
   1442 	}
   1443 
   1444 	/* mark all the frames with the completion spots */
   1445 	for (i = 0, ep = einfo, cbpp = ecombo; i < nframes; i++, ep++, cbpp++) {
   1446 		m = ep->e_emask;
   1447 		cbp = *cbpp;
   1448 		sp = &board[cbp->c_vertex];
   1449 		d = dd[cbp->c_dir];
   1450 		cmask = CFLAG << cbp->c_dir;
   1451 		omask = (IFLAG | CFLAG) << cbp->c_dir;
   1452 		int off = ep->e_fval.cv_win != 0 ? 6 : 5;
   1453 		/* LINTED 117: bitwise '>>' on signed value possibly nonportable */
   1454 		for (; --off >= 0; sp += d, m >>= 1)
   1455 			sp->s_flags |= (m & 1) != 0 ? omask : cmask;
   1456 	}
   1457 }
   1458 
   1459 void
   1460 clearcombo(struct combostr *cbp, int open)
   1461 {
   1462 	struct combostr *tcbp;
   1463 
   1464 	for (; (tcbp = cbp->c_link[1]) != NULL; cbp = cbp->c_link[0]) {
   1465 		clearcombo(tcbp, cbp->c_flags & C_OPEN_1);
   1466 		open = cbp->c_flags & C_OPEN_0;
   1467 	}
   1468 
   1469 	struct spotstr *sp = &board[cbp->c_vertex];
   1470 	int d = dd[cbp->c_dir];
   1471 	int mask = ~((IFLAG | CFLAG) << cbp->c_dir);
   1472 	int n = open != 0 ? 6 : 5;
   1473 	for (; --n >= 0; sp += d)
   1474 		sp->s_flags &= mask;
   1475 }
   1476 #endif /* DEBUG */
   1477