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