Fix bug in setting up w3 and w4 games
[capablanca.git] / lasker-2.2.3 / src / gameproc.c
1 /*
2    Copyright (c) 1993 Richard V. Nash.
3    Copyright (c) 2000 Dan Papasian
4    Copyright (C) Andrew Tridgell 2002
5    
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2 of the License, or
9    (at your option) any later version.
10    
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15    
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 */
20
21 #include "includes.h"
22
23 /*Let users know that someone is available (format the message)*/
24 static void getavailmess(int p, char* message)
25 {
26         struct player *pp = &player_globals.parray[p];
27         char titles[100];
28
29         titles [0]='\0';
30         AddPlayerLists(p,titles);
31         sprintf (message,"%s%s Blitz (%s), Std (%s), Wild (%s), Light(%s), Bug(%s)\n"
32                  "  is now available for matches.",
33                  pp->name, titles,
34         ratstrii(pp->b_stats.rating, p),
35         ratstrii(pp->s_stats.rating, p),
36         ratstrii(pp->w_stats.rating, p),
37         ratstrii(pp->l_stats.rating, p),
38         ratstrii(pp->bug_stats.rating, p));
39 }
40
41 void getnotavailmess(int p, char* message)
42 {
43         struct player *pp = &player_globals.parray[p];
44         char titles[100];
45
46         titles[0]='\0';
47         AddPlayerLists(p,titles);
48         sprintf (message,"%s%s is no longer available for matches.",
49                  pp->name, titles);
50 }
51
52 void announce_avail(int p)
53 {
54         struct player *pp = &player_globals.parray[p];
55         char avail[200];
56         int p1;
57         if ((pp->game < 0) && (CheckPFlag(p, PFLAG_OPEN))) {
58                 getavailmess (p,avail);
59                 
60                 for (p1 = 0; p1 < player_globals.p_num; p1++) {
61                         if (p == p1)
62                                 continue;
63                         if (player_globals.parray[p1].status != PLAYER_PROMPT)
64                                 continue;
65                         if (CheckPFlag(p1, PFLAG_AVAIL) && CheckPFlag(p1, PFLAG_OPEN)
66                             && (player_globals.parray[p1].game < 0))
67                                 if (((pp->b_stats.rating <= player_globals.parray[p1].availmax) && (pp->b_stats.rating >= player_globals.parray[p1].availmin)) || (!player_globals.parray[p1].availmax))
68                                         pprintf_prompt (p1,"\n%s\n",avail);
69                 }
70         }
71 }
72
73 void announce_notavail(int p)
74 {
75         struct player *pp = &player_globals.parray[p];
76         char avail[200];
77         int p1;
78         
79         getnotavailmess (p,avail);
80         
81         for (p1 = 0; p1 < player_globals.p_num; p1++) {
82                 if (p == p1)
83                         continue;
84                 if (player_globals.parray[p1].status != PLAYER_PROMPT)
85                         continue;
86                 if (CheckPFlag(p1, PFLAG_AVAIL) && CheckPFlag(p1, PFLAG_OPEN)
87                     && (player_globals.parray[p1].game < 0))
88                         if (((pp->b_stats.rating <= player_globals.parray[p1].availmax) && (pp->b_stats.rating >= player_globals.parray[p1].availmin)) || (!player_globals.parray[p1].availmax))
89                                 pprintf_prompt (p1,"\n%s\n",avail);
90         }
91 }
92
93 void game_ended(int g, int winner, int why)
94 {
95   struct game *gg = &game_globals.garray[g];
96   char outstr[200];
97   char avail_black[200]; /* for announcing white/black avail */
98   char avail_white[200];
99   char avail_bugwhite[200];
100   char avail_bugblack[200];
101   char tmp[200];
102   int p;
103   int gl = gg->link;
104   int rate_change = 0;
105   int isDraw = 0;
106   int whiteResult;
107   char winSymbol[10];
108   char EndSymbol[10];
109   char *NameOfWinner, *NameOfLoser;
110   int beingplayed = 0;          /* i.e. it wasn't loaded for adjudication */
111   int print_avail = 0;
112
113   avail_white[0] = '\0';
114   avail_black[0] = '\0';
115   avail_bugwhite[0] = '\0';
116   avail_bugblack[0] = '\0';
117
118   beingplayed = (player_globals.parray[gg->black].game == g);
119
120   sprintf(outstr, "\n{Game %d (%s vs. %s) ", g + 1,
121           player_globals.parray[gg->white].name,
122           player_globals.parray[gg->black].name);
123   gg->result = why;
124   gg->winner = winner;
125   if (winner == WHITE) {
126     whiteResult = RESULT_WIN;
127     strcpy(winSymbol, "1-0");
128     NameOfWinner = player_globals.parray[gg->white].name;
129     NameOfLoser = player_globals.parray[gg->black].name;
130   } else {
131     whiteResult = RESULT_LOSS;
132     strcpy(winSymbol, "0-1");
133     NameOfWinner = player_globals.parray[gg->black].name;
134     NameOfLoser = player_globals.parray[gg->white].name;
135   }
136   switch (why) {
137   case END_CHECKMATE:
138     sprintf(tmp, "%s checkmated} %s", NameOfLoser, winSymbol);
139     strcpy(EndSymbol, "Mat");
140     rate_change = 1;
141     break;
142   case END_BARE:
143     sprintf(tmp, "%s bared} %s", NameOfLoser, winSymbol);
144     strcpy(EndSymbol, "Bar");
145     rate_change = 1;
146     break;
147   case END_PERPETUAL:
148     sprintf(tmp, "%s perpetually checking} %s", NameOfLoser, winSymbol);
149     strcpy(EndSymbol, "Per");
150     rate_change = 1;
151     break;
152   case END_RESIGN:
153     sprintf(tmp, "%s resigns} %s", NameOfLoser, winSymbol);
154     strcpy(EndSymbol, "Res");
155     rate_change = 1;
156     break;
157   case END_FLAG:
158     sprintf(tmp, "%s forfeits on time} %s", NameOfLoser, winSymbol);
159     strcpy(EndSymbol, "Fla");
160     rate_change = 1;
161     break;
162   case END_STALEMATE:
163     sprintf(tmp, "Game drawn by stalemate} 1/2-1/2");
164     isDraw = 1;
165     strcpy(EndSymbol, "Sta");
166     rate_change = 1;
167     whiteResult = RESULT_DRAW;
168     break;
169   case END_AGREEDDRAW:
170     sprintf(tmp, "Game drawn by mutual agreement} 1/2-1/2");
171     isDraw = 1;
172     strcpy(EndSymbol, "Agr");
173     rate_change = 1;
174     whiteResult = RESULT_DRAW;
175     break;
176   case END_BOTHFLAG:
177     sprintf(tmp, "Game drawn because both players ran out of time} 1/2-1/2");
178     isDraw = 1;
179     strcpy(EndSymbol, "Fla");
180     rate_change = 1;
181     whiteResult = RESULT_DRAW;
182     break;
183   case END_REPETITION:
184     sprintf(tmp, "Game drawn by repetition} 1/2-1/2");
185     isDraw = 1;
186     strcpy(EndSymbol, "Rep");
187     rate_change = 1;
188     whiteResult = RESULT_DRAW;
189     break;
190   case END_50MOVERULE:
191     sprintf(tmp, "Game drawn by the 50 move rule} 1/2-1/2");
192     isDraw = 1;
193     strcpy(EndSymbol, "50");
194     rate_change = 1;
195     whiteResult = RESULT_DRAW;
196     break;
197   case END_ADJOURN:
198     if (gl >= 0) {
199       sprintf(tmp, "Bughouse game aborted.} *");
200       whiteResult = RESULT_ABORT;
201     } else {
202     sprintf(tmp, "Game adjourned by mutual agreement} *");
203     game_save(g);
204     }
205     break;
206   case END_LOSTCONNECTION:
207     sprintf(tmp, "%s lost connection; game ", NameOfWinner);
208     if (CheckPFlag(gg->white, PFLAG_REG)
209         && CheckPFlag(gg->black, PFLAG_REG)
210         && gl < 0) {
211       sprintf(tmp, "adjourned} *");
212       game_save(g);
213     } else
214       sprintf(tmp, "aborted} *");
215     whiteResult = RESULT_ABORT;
216     break;
217   case END_ABORT:
218     sprintf(tmp, "Game aborted by mutual agreement} *");
219     whiteResult = RESULT_ABORT;
220     break;
221   case END_COURTESY:
222     sprintf(tmp, "Game courtesyaborted by %s} *", NameOfWinner);
223     whiteResult = RESULT_ABORT;
224     break;
225   case END_COURTESYADJOURN:
226     if (gl >= 0) {
227       sprintf(tmp, "Bughouse game courtesyaborted by %s.} *", NameOfWinner);
228       whiteResult = RESULT_ABORT;
229     } else {
230     sprintf(tmp, "Game courtesyadjourned by %s} *", NameOfWinner);
231     game_save(g);
232     }
233     break;
234   case END_NOMATERIAL:
235     /* Draw by insufficient material (e.g., lone K vs. lone K) */
236     sprintf(tmp, "Neither player has mating material} 1/2-1/2");
237     isDraw = 1;
238     strcpy(EndSymbol, "NM ");
239     rate_change = 1;
240     whiteResult = RESULT_DRAW;
241     break;
242   case END_FLAGNOMATERIAL:
243     sprintf(tmp, "%s ran out of time and %s has no material to mate} 1/2-1/2",
244             NameOfLoser, NameOfWinner);
245     isDraw = 1;
246     strcpy(EndSymbol, "TM ");
247     rate_change = 1;
248     whiteResult = RESULT_DRAW;
249     break;
250   case END_ADJWIN:
251     sprintf(tmp, "%s wins by adjudication} %s", NameOfWinner, winSymbol);
252     strcpy(EndSymbol, "Adj");
253     rate_change = 1;
254     break;
255   case END_ADJDRAW:
256     sprintf(tmp, "Game drawn by adjudication} 1/2-1/2");
257     isDraw = 1;
258     strcpy(EndSymbol, "Adj");
259     rate_change = 1;
260     whiteResult = RESULT_DRAW;
261     break;
262   case END_ADJABORT:
263     sprintf(tmp, "Game aborted by adjudication} *");
264     whiteResult = RESULT_ABORT;
265     break;
266   default:
267     sprintf(tmp, "Hmm, the game ended and I don't know why} *");
268     break;
269   }
270   strcat(outstr, tmp);
271
272   if (CheckPFlag(gg->white, PFLAG_TOURNEY) &&
273       CheckPFlag(gg->black, PFLAG_TOURNEY)) {
274           /* mamer wants more info */
275           sprintf(tmp," [%d %d %d %d %d]",
276                   gg->wInitTime/(60*10), gg->wIncrement/10, gg->rated, gg->private, (int)gg->type);
277           strcat(outstr, tmp);
278   }
279
280   strcat(outstr, "\n");
281
282   if (gg->rated && rate_change && gg->type != TYPE_BUGHOUSE)
283     /* Adjust ratings; bughouse gets done later. */
284     rating_update(g, -1);
285
286   if (beingplayed) {
287     int printed = 0;
288     int avail_printed = 0;
289
290     pprintf_noformat(gg->white, outstr);
291     pprintf_noformat(gg->black, outstr);
292     Bell (gg->white);
293     Bell (gg->black);
294
295     gg->link = -1;              /*IanO: avoids recursion */
296     if (gl >= 0 && game_globals.garray[gl].link >= 0) {
297       pprintf_noformat(game_globals.garray[gl].white, outstr);
298       pprintf_noformat(game_globals.garray[gl].black, outstr);
299       if (CheckPFlag(game_globals.garray[gl].white, PFLAG_OPEN)) {
300         getavailmess (game_globals.garray[gl].white, avail_bugwhite);
301         print_avail = 1;
302       }
303       if (CheckPFlag(game_globals.garray[gl].black, PFLAG_OPEN)) {
304         getavailmess (game_globals.garray[gl].black, avail_bugblack);
305         print_avail = 1;
306       }
307       if ((gg->rated) && (rate_change)) {
308         /* Adjust ratings */
309         rating_update(g, gl);
310       }
311       game_ended(gl, CToggle(winner), why);
312     }
313
314     if ((player_num_active_boards(gg->white) <= 1) /* not a simul or */
315          && CheckPFlag(gg->white, PFLAG_OPEN)) {   /* simul is over? */
316       getavailmess (gg->white,avail_white);
317       print_avail = 1;
318     } else {    /* Part of an ongoing simul!  Let's shrink the array. */
319       
320     }
321     
322     if (CheckPFlag(gg->black, PFLAG_OPEN)) {
323       getavailmess (gg->black,avail_black);
324       print_avail = 1;
325     }
326
327     for (p = 0; p < player_globals.p_num; p++) {
328       struct player *pp = &player_globals.parray[p];
329       if ((p == gg->white) || (p == gg->black))
330         continue;
331       if (pp->status != PLAYER_PROMPT)
332         continue;
333
334       if (CheckPFlag(p, PFLAG_GIN) || player_is_observe(p, g)) {
335         pprintf_noformat(p, outstr);
336         printed = 1;
337       }
338
339       if (CheckPFlag(p, PFLAG_AVAIL) && (CheckPFlag(p, PFLAG_OPEN)) && (pp->game < 0) && (print_avail)) {
340         if (((player_globals.parray[gg->white].b_stats.rating <= pp->availmax) && (player_globals.parray[gg->white].b_stats.rating >= pp->availmin)) || (!pp->availmax)) {
341           pprintf (p,"\n%s",avail_white);
342           avail_printed = 1;
343         }
344         if (((player_globals.parray[gg->black].b_stats.rating <= pp->availmax) && (player_globals.parray[gg->black].b_stats.rating >= pp->availmin)) || (!pp->availmax)) {
345           pprintf (p,"\n%s",avail_black);
346           avail_printed = 1;
347         }
348         if (gl == -1) /* bughouse ? */ {
349           if (((player_globals.parray[game_globals.garray[gl].white].b_stats.rating <= pp->availmax) && (player_globals.parray[game_globals.garray[gl].white].b_stats.rating >= pp->availmin)) || (!pp->availmax)) {
350             pprintf (p,"\n%s",avail_bugwhite);
351             avail_printed = 1;
352           }
353           if (((player_globals.parray[game_globals.garray[gl].black].b_stats.rating <= pp->availmax) && (player_globals.parray[game_globals.garray[gl].black].b_stats.rating >= pp->availmin)) || (!pp->availmax)) {
354             pprintf (p,"\n%s",avail_bugblack);
355             avail_printed = 1;
356           }
357         }
358         if (avail_printed) {
359           avail_printed = 0;
360           printed = 1; 
361           pprintf (p,"\n");
362         }
363       }
364
365       if (printed) {
366         send_prompt(p);
367         printed = 0;
368       }
369     }
370
371     if (!(gg->rated && rate_change)) {
372       pprintf(gg->white, "No ratings adjustment done.\n");
373       pprintf(gg->black, "No ratings adjustment done.\n");
374     } 
375   }
376
377   if (rate_change && gl < 0)
378     game_write_complete(g, isDraw, EndSymbol);
379   /* Mail off the moves */
380   if (CheckPFlag(gg->white, PFLAG_AUTOMAIL)) {
381     pcommand(gg->white, "mailmoves");
382   }
383   if (CheckPFlag(gg->black, PFLAG_AUTOMAIL)) {
384     pcommand(gg->black, "mailmoves");
385   }
386   if (!((player_globals.parray[gg->white].simul_info != NULL) &&
387          (player_globals.parray[gg->white].simul_info->numBoards))) {
388     player_globals.parray[gg->white].num_white++;
389     PFlagOFF(gg->white, PFLAG_LASTBLACK);
390     player_globals.parray[gg->black].num_black++;
391     PFlagON(gg->black, PFLAG_LASTBLACK);
392   }
393   player_globals.parray[gg->white].last_opponent = 
394           strdup(gg->black_name);
395   player_globals.parray[gg->black].last_opponent = 
396           strdup(gg->white_name);
397   if (beingplayed) {
398     player_globals.parray[gg->white].game = -1;
399     player_globals.parray[gg->black].game = -1;
400     player_globals.parray[gg->white].opponent = -1;
401     player_globals.parray[gg->black].opponent = -1;
402     if (gg->white != command_globals.commanding_player)
403       send_prompt(gg->white);
404     if (gg->black != command_globals.commanding_player)
405       send_prompt(gg->black);
406     if ((player_globals.parray[gg->white].simul_info != NULL) && 
407          (player_globals.parray[gg->white].simul_info->numBoards))
408       player_simul_over(gg->white, g, whiteResult);
409   }
410   game_finish(g); 
411 }
412
413 static int was_promoted(struct game *g, int f, int r)
414 {
415 #define BUGHOUSE_PAWN_REVERT 1
416 #ifdef BUGHOUSE_PAWN_REVERT
417   int i;
418
419   for (i = g->numHalfMoves-2; i > 0; i -= 2) {
420     if (g->moveList[i].toFile == f && g->moveList[i].toRank == r) {
421       if (g->moveList[i].piecePromotionTo) {
422         switch(g->moveList[i].moveString[0]) { // [HGM] return original piece type rather than just TRUE
423           case 'P': return PAWN;
424           case 'N': return HONORABLEHORSE; // !!! this is Shogi, so no KNIGHT !!!
425           case 'B': return BISHOP;
426           case 'R': return ROOK;
427           case 'L': return LANCE;
428           case 'S': return SILVER;
429           default:  return GOLD;
430         }
431       }
432       if (g->moveList[i].fromFile == ALG_DROP)
433         return 0;
434       f = g->moveList[i].fromFile;
435       r = g->moveList[i].fromRank;
436     }
437   }
438 #endif
439   return 0;
440 }
441
442 int pIsPlaying (int p)
443 {
444         struct player *pp = &player_globals.parray[p];
445         int g = pp->game;
446         int p1 = pp->opponent;
447         
448         if (g < 0 || game_globals.garray[g].status != GAME_ACTIVE) {
449                 pprintf (p, "You are not playing a game.\n");
450                 return 0;
451         } 
452
453         if (game_globals.garray[g].white != p && game_globals.garray[g].black != p) {
454                 /* oh oh; big bad game bug. */
455                 d_printf("BUG:  Player %s playing game %d according to player_globals.parray,"
456                          "\n      but not according to game_globals.garray.\n", pp->name, g+1);
457                 pprintf (p, "Disconnecting you from game number %d.\n", g+1);
458                 pp->game = -1;
459                 if (p1 >= 0 && player_globals.parray[p1].game == g
460                     && game_globals.garray[g].white != p1 && game_globals.garray[g].black != p1) {
461                         pprintf (p1, "Disconnecting you from game number %d.\n", g+1);
462                         player_globals.parray[p1].game = -1;
463                 }
464                 return 0;
465         }
466         return 1;
467 }
468
469 /* add clock increments */
470 static void game_add_increment(struct player *pp, struct game *gg)
471 {
472         /* no update on first move */
473         if (gg->game_state.moveNum == 1) return;
474
475         if (net_globals.con[pp->socket]->timeseal) {    /* does he use timeseal? */
476                 if (pp->side == WHITE) {
477                         gg->wRealTime += gg->wIncrement * 100;
478                         gg->wTime = gg->wRealTime / 100;        /* remember to conv to
479                                                                                                    tenth secs */
480                 } else if (pp->side == BLACK) {
481                         gg->bRealTime += gg->bIncrement * 100;  /* conv to ms */
482                         gg->bTime = gg->bRealTime / 100;        /* remember to conv to
483                                                                                                    tenth secs */
484                 }
485         } else {
486                 if (gg->game_state.onMove == BLACK) {
487                         gg->bTime += gg->bIncrement;
488                 }
489                 if (gg->game_state.onMove == WHITE) {
490                         gg->wTime += gg->wIncrement;
491                 }
492         }
493 }
494
495 /* updates clocks for a game with timeseal */
496 void timeseal_update_clocks(struct player *pp, struct game *gg)
497 {
498         /* no update on first move */
499         if (gg->game_state.moveNum == 1) return;
500
501         if (pp->side == WHITE) {
502                 gg->wLastRealTime = gg->wRealTime;
503                 gg->wTimeWhenMoved = net_globals.con[pp->socket]->time;
504                 if (((gg->wTimeWhenMoved - gg->wTimeWhenReceivedMove) < 0) ||
505                     (gg->wTimeWhenReceivedMove == 0)) {
506                         /* might seem weird - but could be caused by a person moving BEFORE
507                            he receives the board pos (this is possible due to lag) but it's
508                            safe to say he moved in 0 secs :-) */
509                         gg->wTimeWhenReceivedMove = gg->wTimeWhenMoved;
510                 } else {
511                         gg->wRealTime -= gg->wTimeWhenMoved - gg->wTimeWhenReceivedMove;
512                 }
513         } else if (pp->side == BLACK) {
514                 gg->bLastRealTime = gg->bRealTime;
515                 gg->bTimeWhenMoved = net_globals.con[pp->socket]->time;
516                 if (((gg->bTimeWhenMoved - gg->bTimeWhenReceivedMove) < 0) ||
517                     (gg->bTimeWhenReceivedMove == 0)) {
518                         /* might seem weird - but could be caused by a person moving BEFORE
519                            he receives the board pos (this is possible due to lag) but it's
520                            safe to say he moved in 0 secs :-) */
521                         gg->bTimeWhenReceivedMove = gg->bTimeWhenMoved;
522                 } else {
523                         gg->bRealTime -= gg->bTimeWhenMoved - gg->bTimeWhenReceivedMove;
524                 }
525         }
526 }
527
528
529 void process_move(int p, char *command)
530 {
531   struct player *pp = &player_globals.parray[p];
532   struct game *gg;
533   int g, result, len, i, f;
534   struct move_t move;
535   unsigned now = 0;
536
537   if (pp->game < 0) {
538     pprintf(p, "You are not playing or examining a game.\n");
539     return;
540   }
541   decline_withdraw_offers(p, -1, -PEND_SIMUL,DO_DECLINE);
542
543   g = pp->game;
544   gg = &game_globals.garray[g];
545
546   if (gg->status == GAME_SETUP) {
547     if (!attempt_drop(p,g,command)) {
548       pprintf(p, "You are still setting up the position.\n");
549       pprintf(p, "Type: 'setup done' when you are finished editing.\n");
550     } else
551     send_board_to(g, p); 
552     return;
553   }
554
555   if (gg->status != GAME_EXAMINE) {
556     if (!pIsPlaying(p)) return;
557
558     if (pp->side != gg->game_state.onMove) {
559       pprintf(p, "It is not your move.\n");
560       return;
561     }
562     if (gg->clockStopped) {
563       pprintf(p, "Game clock is paused, use \"unpause\" to resume.\n");
564       return;
565     }
566   }
567   pp->promote = NOPIECE; // [HGM] this seemed to be uninitialized, which caused spurious promotion in Shogi
568   if ((len = strlen(command)) > 1) {
569     if (command[len - 2] == '=' || gg->game_state.drops == 2 && command[len - 2] == '/') { // [HGM] encode gating as promotion
570 printf("promo '%s'\n", command);
571       switch (tolower(command[len - 1])) {
572       case 'n':
573         pp->promote = KNIGHT;
574         break;
575       case 'b':
576         pp->promote = BISHOP;
577         break;
578       case 'r':
579         pp->promote = ROOK;
580         break;
581       case 'a':
582         pp->promote = CARDINAL;
583         break;
584       case 'c':
585         pp->promote = MARSHALL;
586         break;
587       case 'm':
588         pp->promote = MAN;
589         break;
590       case 'q':
591         pp->promote = QUEEN;
592         break;
593       // courier promotion
594       case 'f':
595         pp->promote = FERZ2;
596         break;
597       // Superchess promotions
598       case 'e':
599         pp->promote = EMPRESS;
600         break;
601       case 's':
602         pp->promote = PRINCESS;
603         break;
604       case 'v':
605         pp->promote = CENTAUR;
606         break;
607       case 'w':
608         pp->promote = WOODY;
609         break;
610       case 'o':
611         pp->promote = SQUIRREL;
612         break;
613       case 'g':
614         pp->promote = MASTODON;
615         break;
616       case 'l':
617         pp->promote = LIEUTENANT;
618         break;
619       case 'k':
620         pp->promote = KING;
621         break;
622       // Shogi promotions
623       case 'h':
624         pp->promote = DRAGONHORSE;
625         break;
626       case 'd':
627         pp->promote = DRAGONKING;
628         break;
629       case '^':
630       case '+':
631         pp->promote = GOLD;
632         break;
633       case '=':
634         pp->promote = NOPIECE;
635         break;
636       default:
637         pprintf(p, "Don't understand that move.\n");
638         return;
639         break;
640       }
641     }
642   }
643
644   switch (parse_move(command, &gg->game_state, &move, pp->promote)) {
645   case MOVE_ILLEGAL:
646     pprintf(p, "Illegal move.\n");
647     return;
648     break;
649   case MOVE_AMBIGUOUS:
650     pprintf(p, "Ambiguous move.\n");
651     return;
652     break;
653   default:
654     break;
655   }
656
657   if (gg->status == GAME_EXAMINE) {
658     gg->numHalfMoves++;
659     if (gg->numHalfMoves > gg->examMoveListSize) {
660       gg->examMoveListSize += 20;       /* Allocate 20 moves at a time */
661       gg->examMoveList = (struct move_t *) realloc(gg->examMoveList, sizeof(struct move_t) * gg->examMoveListSize);
662     }
663     result = execute_move(&gg->game_state, &move, 1);
664     move.atTime = now;
665     move.tookTime = 0;
666     MakeFENpos(g, move.FENpos);
667     gg->examMoveList[gg->numHalfMoves - 1] = move;
668     /* roll back time */
669     if (gg->game_state.onMove == WHITE) {
670       gg->wTime += (gg->lastDecTime - gg->lastMoveTime);
671     } else {
672       gg->bTime += (gg->lastDecTime - gg->lastMoveTime);
673     }
674     now = tenth_secs();
675     if (gg->numHalfMoves == 0)
676       gg->timeOfStart = now;
677     gg->lastMoveTime = now;
678     gg->lastDecTime = now;
679
680   } else {                      /* real game */
681     i = pp->opponent;
682     if ((player_globals.parray[i].simul_info != NULL) && (player_globals.parray[i].simul_info->numBoards &&
683          (player_globals.parray[i].simul_info->boards[player_globals.parray[i].simul_info->onBoard] != g))) {
684       pprintf(p, "It isn't your turn: wait until the simul giver is at your board.\n");
685       return;
686     }
687     if (net_globals.con[pp->socket]->timeseal) {        /* does he use timeseal? */
688             timeseal_update_clocks(pp, &game_globals.garray[g]);
689     }
690     /* we need to reset the opp's time for receiving the board since the
691        timeseal decoder only alters the time if it's 0 Otherwise the time
692        would be changed if the player did a refresh which would screw up
693        the timings */
694     if (pp->side == WHITE) {
695       gg->bTimeWhenReceivedMove = 0;
696     } else {
697       gg->wTimeWhenReceivedMove = 0;
698     }
699
700     game_update_time(g);
701     game_add_increment(pp, gg);
702
703     /* Do the move */
704     gg->numHalfMoves++;
705     if (gg->numHalfMoves > gg->moveListSize) {
706       gg->moveListSize += 20;   /* Allocate 20 moves at a time */
707       gg->moveList = (struct move_t *) realloc(gg->moveList, sizeof(struct move_t) * gg->moveListSize);
708     }
709     result = execute_move(&gg->game_state, &move, 1);
710     if (result == MOVE_OK && (gg->link >= 0 || gg->game_state.holdings) && move.pieceCaptured != NOPIECE) {
711       /* transfer captured piece to partner */
712       /* check if piece reverts to a pawn */
713       int victim = move.pieceCaptured, partner = gg->link, demoted;
714       // [HGM] zh: if not Bughouse, the game_state.holdings field decides what happens
715       if(gg->link < 0) { 
716         partner = g; // pieces stay with current board
717         if(gg->game_state.holdings == -1) victim ^= WHITE|BLACK; // flip color
718       } 
719       if (demoted = was_promoted(&game_globals.garray[g], move.toFile, move.toRank))
720         update_holding(partner, colorval(victim) | demoted); // [HGM] was_promoted now returns original piece type
721       else
722         update_holding(partner, victim);
723     }
724     now = tenth_secs();
725     move.atTime = now;
726     if (gg->numHalfMoves > 1) {
727       move.tookTime = move.atTime - gg->lastMoveTime;
728     } else {
729       move.tookTime = move.atTime - gg->startTime;
730     }
731     gg->lastMoveTime = now;
732     gg->lastDecTime = now;
733     move.wTime = gg->wTime;
734     move.bTime = gg->bTime;
735
736     if (net_globals.con[pp->socket]->timeseal) {        /* does he use timeseal? */
737       if (pp->side == WHITE) {
738         move.tookTime = (game_globals.garray[pp->game].wTimeWhenMoved -
739                          game_globals.garray[pp->game].wTimeWhenReceivedMove) / 100;
740       } else {
741         move.tookTime = (game_globals.garray[pp->game].bTimeWhenMoved -
742                          game_globals.garray[pp->game].bTimeWhenReceivedMove) / 100;
743       }
744     }
745
746     if (gg->numHalfMoves <= 2) {
747             move.tookTime = 0;
748     }
749
750     MakeFENpos(g, move.FENpos);
751     gg->moveList[gg->numHalfMoves - 1] = move;
752   }
753
754   send_boards(g);
755
756   if (result == MOVE_ILLEGAL) {
757     pprintf(p, "Internal error, illegal move accepted!\n");
758   }
759   if ((result == MOVE_OK) && (gg->status == GAME_EXAMINE)) {
760     int p1;
761
762     for (p1 = 0; p1 < player_globals.p_num; p1++) {
763       if (player_globals.parray[p1].status != PLAYER_PROMPT)
764         continue;
765       if (player_is_observe(p1, g) || player_globals.parray[p1].game == g) {
766         pprintf(p1, "%s moves: %s\n", pp->name, move.algString);
767       }
768     }
769   }
770   if (result == MOVE_CHECKMATE) {
771     if (gg->status == GAME_EXAMINE) {
772       int p1;
773
774       for (p1 = 0; p1 < player_globals.p_num; p1++) {
775         if (player_globals.parray[p1].status != PLAYER_PROMPT)
776           continue;
777         if (player_is_observe(p1, g) || player_globals.parray[p1].game == g) {
778           pprintf(p1, "%s has been checkmated.\n",
779                   (CToggle(gg->game_state.onMove) == BLACK) ? "White" : "Black");
780         }
781       }
782     } else {
783       game_ended(g, CToggle(gg->game_state.onMove), END_CHECKMATE);
784     }
785   }
786   if (result == MOVE_STALEMATE) {
787     if (gg->status == GAME_EXAMINE) {
788       int p1;
789
790       for (p1 = 0; p1 < player_globals.p_num; p1++) {
791         if (player_globals.parray[p1].status != PLAYER_PROMPT)
792           continue;
793         if (player_is_observe(p1, g) || player_globals.parray[p1].game == g) {
794           pprintf(p1, "Stalemate.\n");
795         }
796       }
797     } else {
798       game_ended(g, CToggle(gg->game_state.onMove), END_STALEMATE);
799     }
800   }
801   if (result == MOVE_NOMATERIAL) {
802     if (gg->status == GAME_EXAMINE) {
803       int p1;
804
805       for (p1 = 0; p1 < player_globals.p_num; p1++) {
806         if (player_globals.parray[p1].status != PLAYER_PROMPT)
807           continue;
808         if (player_is_observe(p1, g) || player_globals.parray[p1].game == g) {
809           pprintf(p1, "No mating material.\n");
810         }
811       }
812     } else {
813       game_ended(g, CToggle(gg->game_state.onMove), END_NOMATERIAL);
814     }
815   }
816   if (result == MOVE_BARE) {
817     if (gg->status == GAME_EXAMINE) {
818       int p1;
819
820       for (p1 = 0; p1 < player_globals.p_num; p1++) {
821         if (player_globals.parray[p1].status != PLAYER_PROMPT)
822           continue;
823         if (player_is_observe(p1, g) || player_globals.parray[p1].game == g) {
824           pprintf(p1, "%s bared.\n",
825                   (gg->game_state.onMove == BLACK) ? "White" : "Black");
826         }
827       }
828     } else {
829       game_ended(g, gg->game_state.onMove, END_BARE);
830     }
831   }
832 }
833
834 int com_resign(int p, param_list param)
835 {
836   struct player *pp = &player_globals.parray[p];
837   int g, o, oconnected;
838
839   if (param[0].type == TYPE_NULL) {
840     g = pp->game;
841     if (!pIsPlaying(p))
842       return COM_OK;
843     else {
844       decline_withdraw_offers(p, -1, -1, DO_DECLINE);
845       game_ended(g, (game_globals.garray[g].white == p) ? BLACK : WHITE, END_RESIGN);
846     }
847   } else if (FindPlayer(p, param[0].val.word, &o, &oconnected)) {
848     g = game_new();
849     if (game_read(g, p, o) < 0) {
850       if (game_read(g, o, p) < 0) {
851         pprintf(p, "You have no stored game with %s\n", player_globals.parray[o].name);
852         if (!oconnected)
853           player_remove(o);
854         return COM_OK;
855       } else {
856         game_globals.garray[g].white = o;
857         game_globals.garray[g].black = p;
858       }
859     } else {
860       game_globals.garray[g].white = p;
861       game_globals.garray[g].black = o;
862     }
863     pprintf(p, "You resign your stored game with %s\n", player_globals.parray[o].name);
864     pcommand(p, "message %s I have resigned our stored game \"%s vs. %s.\"",
865              player_globals.parray[o].name,
866              player_globals.parray[game_globals.garray[g].white].name,
867              player_globals.parray[game_globals.garray[g].black].name);
868     game_delete(game_globals.garray[g].white, game_globals.garray[g].black);
869     game_ended(g, (game_globals.garray[g].white == p) ? BLACK : WHITE, END_RESIGN);
870     if (!oconnected)
871       player_remove(o);
872   }
873   return COM_OK;
874 }
875
876 static int Check50MoveRule (int p, int g)
877 {
878   int num_reversible = game_globals.garray[g].numHalfMoves;
879
880   if (game_globals.garray[g].game_state.lastIrreversable >= 0) {
881     num_reversible -= game_globals.garray[g].game_state.lastIrreversable;
882   }
883   if (num_reversible > 99) {
884     game_ended(g, (game_globals.garray[g].white == p) ? BLACK : WHITE, END_50MOVERULE);
885     return 1;
886   }
887   return 0;
888 }
889
890 static int perp_check(struct game g, int first, int third)
891 {
892   struct game_state_t gs = g.game_state; // current position, both first and last of loop
893   int half_move, no_perp = 0;
894 printf("perp %d %d\n",first,third);
895   for(half_move=first+1; half_move<third; half_move++) {
896     gs.onMove = CToggle(gs.onMove);
897     if(!in_check(&gs)) no_perp |= (half_move&1) + 1; // 1 = white not in check, 2 = black not in check
898     gs.onMove = CToggle(gs.onMove);
899 printf("move%d, p=%d\n",half_move,no_perp);
900     if(no_perp == 3) break;
901     execute_move(&gs, &g.moveList[half_move], 0);
902   }
903   if(no_perp == (third&1) + 1) return END_NOTENDED;  // stm was checking, other not: defer judgement
904   if(no_perp == 2 - (third&1)) return END_PERPETUAL; // stm was not checking, other was: stm wins
905   if(no_perp == 0) return END_REPETITION; // mutual perpertual check, draw
906   // here we should check for chasing
907   return END_REPETITION;
908 }
909
910 static char *GetFENpos (int g, int half_move)
911 {
912   if (half_move < 0)
913     return game_globals.garray[g].FENstartPos;
914   else return game_globals.garray[g].moveList[half_move].FENpos;
915 }
916
917 static int CheckRepetition (int p, int g)
918 {
919   struct player *pp = &player_globals.parray[p];
920   struct pending* pend;
921   int move_num, s1, s2, result = END_REPETITION;
922   int flag1 = 1, flag2 = 1;
923   int numPly = game_globals.garray[g].numHalfMoves;
924   char *pos1 = GetFENpos (g, numPly - 1); // current position
925   char *pos2 = "";
926   char *pos;
927
928   if (numPly < 8)  /* can't have three repeats any quicker. */
929     return 0;
930
931   if((game_globals.garray[g].white == p) != (numPly&1)) { // claimer has the move
932     pos2 = pos1;
933     pos1 = GetFENpos (g, numPly - 2); // also check position before opponent's move (which could have pre-empted him)
934   } // pos1 is now always a position where the opponent has the move
935
936   for (move_num = numPly - 2; // [HGM] FEN stored in moveList[numHalfMoves-1] !
937        move_num >= game_globals.garray[g].game_state.lastIrreversable - 1; move_num--) {
938     pos = GetFENpos (g, move_num);
939     if (strlen(pos1) == strlen(pos) && !strcmp(pos1, pos))
940       flag1++ == 2 && (s1 = move_num);
941     if (strlen(pos2) == strlen(pos) && !strcmp(pos2, pos))
942       flag2++ == 2 && (s2 = move_num); // remember start of last two loops
943 printf("%2d. %d-%d '%s' '%s' '%s'\n", move_num, flag1, flag2, pos1,pos2,pos);
944   }
945   if (flag1 >= 3 || flag2 >= 3) {
946     if ((pend = find_pend(pp->opponent, p, PEND_DRAW)) != NULL) {
947       delete_pending(pend);
948       decline_withdraw_offers(p, -1, -1,DO_DECLINE);
949     }
950     if(game_globals.garray[g].game_state.palace) { // [HGM] in Xiangqi we have to test for perpetuals to determine the outcome
951       if(flag2 >= 3) result = perp_check(game_globals.garray[g], s2, numPly);
952       else  result = perp_check(game_globals.garray[g], s1, numPly - (pos2[0] != 0));
953       if(result == END_NOTENDED) {
954         pprintf(p, "Perpetuals can be claimed only during the turn of the winner\n");
955         return 1;
956       }
957       game_ended(g, (numPly&1) ? BLACK : WHITE, result); // stm wins
958       return 1;
959     }
960     game_ended(g, (game_globals.garray[g].white == p) ? BLACK : WHITE, result);
961     return 1;
962   }
963   else return 0;
964 }
965
966 int com_draw(int p, param_list param)
967 {
968   struct player *pp = &player_globals.parray[p];
969   struct pending* pend;
970   int p1, g = pp->game;
971
972   if (!pIsPlaying(p)) {
973     return COM_OK;
974   }
975   if (Check50MoveRule (p, g) || CheckRepetition(p, g)) {
976     return COM_OK;
977   }
978   p1 = pp->opponent;
979
980   if ((player_globals.parray[p1].simul_info != NULL) && (player_globals.parray[p1].simul_info->numBoards &&
981         player_globals.parray[p1].simul_info->boards[player_globals.parray[p1].simul_info->onBoard] != g)) {
982     pprintf(p, "You can only make requests when the simul player is at your board.\n");
983     return COM_OK;
984   }
985
986   if ((pend = (find_pend(pp->opponent, p, PEND_DRAW))) != NULL) {
987     delete_pending(pend);
988     decline_withdraw_offers(p, -1, -1,DO_DECLINE);
989     game_ended(g, (game_globals.garray[g].white == p) ? BLACK : WHITE, END_AGREEDDRAW);
990   } else {
991     pprintf(pp->opponent, "\n");
992     pprintf_highlight(pp->opponent, "%s", pp->name);
993     pprintf_prompt(pp->opponent, " offers you a draw.\n");
994     pprintf(p, "Draw request sent.\n");
995     add_request(p, pp->opponent, PEND_DRAW);
996   }
997   return COM_OK;
998 }
999
1000 int com_pause(int p, param_list param)
1001 {
1002   struct player *pp = &player_globals.parray[p];
1003   int g, now;
1004   struct pending* pend;
1005
1006   if (!pIsPlaying(p)) {
1007     return COM_OK;
1008   }
1009   g = pp->game;
1010   if (game_globals.garray[g].wTime == 0) {
1011     pprintf(p, "You can't pause untimed games.\n");
1012     return COM_OK;
1013   }
1014   if (game_globals.garray[g].clockStopped) {
1015     pprintf(p, "Game is already paused, use \"unpause\" to resume.\n");
1016     return COM_OK;
1017   }
1018   if ((pend = find_pend(pp->opponent, p, PEND_PAUSE)) != NULL) {
1019     delete_pending(pend);
1020     game_globals.garray[g].clockStopped = 1;
1021     /* Roll back the time */
1022     if (game_globals.garray[g].game_state.onMove == WHITE) {
1023       game_globals.garray[g].wTime += (game_globals.garray[g].lastDecTime - game_globals.garray[g].lastMoveTime);
1024     } else {
1025       game_globals.garray[g].bTime += (game_globals.garray[g].lastDecTime - game_globals.garray[g].lastMoveTime);
1026     }
1027     now = tenth_secs();
1028     if (game_globals.garray[g].numHalfMoves == 0)
1029       game_globals.garray[g].timeOfStart = now;
1030     game_globals.garray[g].lastMoveTime = now;
1031     game_globals.garray[g].lastDecTime = now;
1032     send_boards(g);
1033     pprintf_prompt(pp->opponent, "\n%s accepted pause. Game clock paused.\n",
1034                    pp->name);
1035     pprintf(p, "Game clock paused.\n");
1036   } else {
1037     pprintf(pp->opponent, "\n");
1038     pprintf_highlight(pp->opponent, "%s", pp->name);
1039     pprintf_prompt(pp->opponent, " requests to pause the game.\n");
1040     pprintf(p, "Pause request sent.\n");
1041     add_request(p, pp->opponent, PEND_PAUSE);
1042   }
1043   return COM_OK;
1044 }
1045
1046 int com_unpause(int p, param_list param)
1047 {
1048   struct player *pp = &player_globals.parray[p];
1049   int g;
1050   int now;
1051   struct pending* pend;
1052
1053   if (!pIsPlaying(p)) {
1054     return COM_OK;
1055   }
1056
1057   g = pp->game;
1058
1059   if (!game_globals.garray[g].clockStopped) {
1060     pprintf(p, "Game is not paused.\n");
1061     return COM_OK;
1062   }
1063   if ((pend = find_pend(pp->opponent, p, PEND_UNPAUSE)) != NULL) {
1064     delete_pending(pend);
1065     game_globals.garray[g].clockStopped = 0;
1066     now = tenth_secs();
1067     if (game_globals.garray[g].numHalfMoves == 0)
1068       game_globals.garray[g].timeOfStart = now;
1069     game_globals.garray[g].lastMoveTime = now;
1070     game_globals.garray[g].lastDecTime = now;
1071     send_boards(g);
1072     pprintf(p, "Game clock resumed.\n");
1073     pprintf_prompt(pp->opponent, "\nGame clock resumed.\n");
1074   } else {
1075     pprintf(pp->opponent, "\n");
1076     pprintf_highlight(pp->opponent, "%s", pp->name);
1077     pprintf_prompt(pp->opponent, " requests to unpause the game.\n");
1078     pprintf(p, "Unpause request sent.\n");
1079     add_request(p, pp->opponent, PEND_UNPAUSE);
1080   }
1081   return COM_OK;
1082 }
1083
1084 int com_abort(int p, param_list param)
1085 {
1086   struct player *pp = &player_globals.parray[p];
1087   struct pending* pend;
1088   int p1, g, myColor, yourColor, myGTime, yourGTime;
1089   int courtesyOK = 1;
1090
1091   g = pp->game;
1092   if (!pIsPlaying(p))
1093     return COM_OK;
1094
1095   p1 = pp->opponent;
1096   if (p == game_globals.garray[g].white) {
1097     myColor = WHITE;
1098     yourColor = BLACK;
1099     myGTime = game_globals.garray[g].wTime;
1100     yourGTime = game_globals.garray[g].bTime;
1101   } else {
1102     myColor = BLACK;
1103     yourColor = WHITE;
1104     myGTime = game_globals.garray[g].bTime;
1105     yourGTime = game_globals.garray[g].wTime;
1106   }
1107   if ((player_globals.parray[p1].simul_info != NULL) && 
1108      (player_globals.parray[p1].simul_info->numBoards &&
1109         player_globals.parray[p1].simul_info->boards[player_globals.parray[p1].simul_info->onBoard] != g)) {
1110     pprintf(p, "You can only make requests when the simul player is at your board.\n");
1111     return COM_OK;
1112   }
1113   if ((pend = find_pend(p1, p, PEND_ABORT)) != NULL) {
1114     delete_pending(pend);
1115     decline_withdraw_offers(p, -1, -1,DO_DECLINE);
1116     game_ended(g, yourColor, END_ABORT);
1117   } else {
1118     game_update_time(g);
1119
1120     if (net_globals.con[pp->socket]->timeseal
1121         && game_globals.garray[g].game_state.onMove == myColor
1122         && game_globals.garray[g].flag_pending == FLAG_ABORT) {
1123       /* It's my move, opponent has asked for abort; I lagged out,
1124          my timeseal prevented courtesyabort, and I am sending an abort
1125          request before acknowledging (and processing) my opponent's
1126          courtesyabort.  OK, let's abort already :-). */
1127       decline_withdraw_offers(p, -1, -1,DO_DECLINE);
1128       game_ended(g, yourColor, END_ABORT);
1129     }
1130
1131     if (net_globals.con[player_globals.parray[p1].socket]->timeseal) {  /* opp uses timeseal? */
1132
1133       int yourRealTime = (myColor == WHITE  ?  game_globals.garray[g].bRealTime
1134                                             :  game_globals.garray[g].wRealTime);
1135       if (myGTime > 0 && yourGTime <= 0 && yourRealTime > 0) {
1136         /* Override courtesyabort; opponent still has time.  Check for lag. */
1137         courtesyOK = 0;
1138
1139         if (game_globals.garray[g].game_state.onMove != myColor
1140             && game_globals.garray[g].flag_pending != FLAG_CHECKING) {
1141           /* Opponent may be lagging; let's ask. */
1142           game_globals.garray[g].flag_pending = FLAG_ABORT;
1143           game_globals.garray[g].flag_check_time = time(0);
1144           pprintf(p, "Opponent has timeseal; trying to courtesyabort.\n");
1145           pprintf(p1, "\n[G]\n");
1146           return COM_OK;
1147         }
1148       }
1149     }
1150
1151     if (myGTime > 0 && yourGTime <= 0 && courtesyOK) {
1152       /* player wants to abort + opponent is out of time = courtesyabort */
1153       pprintf(p, "Since you have time, and your opponent has none, the game has been aborted.");
1154       pprintf(p1, "Your opponent has aborted the game rather than calling your flag.");
1155       decline_withdraw_offers(p, -1, -1, DO_DECLINE);
1156       game_ended(g, myColor, END_COURTESY);
1157     } else {
1158       pprintf(p1, "\n");
1159       pprintf_highlight(p1, "%s", pp->name);
1160       pprintf(p1, " would like to abort the game; ");
1161       pprintf_prompt(p1, "type \"abort\" to accept.\n");
1162       pprintf(p, "Abort request sent.\n");
1163       add_request(p, p1, PEND_ABORT);
1164     }
1165   }
1166   return COM_OK;
1167 }
1168
1169 static int player_has_mating_material(struct game_state_t *gs, int color)
1170 {
1171   int i, j;
1172   int piece;
1173   int minor_pieces = 0;
1174
1175   for (i = 0; i < gs->files; i++)
1176     for (j = 0; j < gs->ranks; j++) {
1177       piece = gs->board[i][j];
1178       switch (piecetype(piece)) {
1179       case BISHOP:
1180       case KNIGHT:
1181         if (iscolor(piece, color))
1182           minor_pieces++;
1183         break;
1184       case KING:
1185       case NOPIECE:
1186         break;
1187       default:
1188         if (iscolor(piece, color))
1189           return 1;
1190       }
1191     }
1192   return ((minor_pieces > 1) ? 1 : 0);
1193 }
1194
1195 int com_flag(int p, param_list param)
1196 {
1197         struct player *pp = &player_globals.parray[p];
1198         struct game *gg;
1199         int g;
1200         int myColor;
1201
1202         if (!pIsPlaying(p)) {
1203                 return COM_OK;
1204         }
1205         g = pp->game;
1206
1207         gg = &game_globals.garray[g];
1208
1209         myColor = (p == gg->white ? WHITE : BLACK);
1210         if (gg->type == TYPE_UNTIMED) {
1211                 pprintf(p, "You can't flag an untimed game.\n");
1212                 return COM_OK;
1213         }
1214         if (gg->numHalfMoves < 2) {
1215                 pprintf(p, "You cannot flag before both players have moved.\nUse abort instead.\n");
1216                 return COM_OK;
1217         }
1218         game_update_time(g);
1219         
1220         {
1221                 int myTime, yourTime, opp = pp->opponent, serverTime;
1222                 
1223                 if (net_globals.con[pp->socket]->timeseal) {    /* does caller use timeseal? */
1224                         myTime = (myColor==WHITE?gg->wRealTime:gg->bRealTime);
1225                 } else {
1226                         myTime = (myColor == WHITE?gg->wTime:gg->bTime);
1227                 }
1228                 serverTime = (myColor == WHITE?gg->bTime:gg->wTime);
1229                 
1230                 if (net_globals.con[player_globals.parray[opp].socket]->timeseal) {     /* opp uses timeseal? */
1231                         yourTime = (myColor == WHITE?gg->bRealTime:gg->wRealTime);
1232                 } else {
1233                         yourTime = serverTime;
1234                 }
1235
1236                 /* the clocks to compare are now in myTime and yourTime */
1237                 if ((myTime <= 0) && (yourTime <= 0)) {
1238                         decline_withdraw_offers(p, -1, -1,DO_DECLINE);
1239                         game_ended(g, myColor, END_BOTHFLAG);
1240                         return COM_OK;
1241                 }
1242
1243                 if (yourTime > 0) {
1244                         /* Opponent still has time, but if that's only because s/he
1245                          * may be lagging, we should ask for an acknowledgement and then
1246                          * try to call the flag. */
1247                         
1248                         if (serverTime <= 0 && gg->game_state.onMove != myColor
1249                             && gg->flag_pending != FLAG_CHECKING) {                             
1250                                 /* server time thinks opponent is down, but RealTIme disagrees.
1251                                  * ask client to acknowledge it's alive. */                             
1252                                 gg->flag_pending = FLAG_CALLED;
1253                                 gg->flag_check_time = time(0);
1254                                 pprintf(p, "Opponent has timeseal; checking if (s)he's lagging.\n");
1255                                 pprintf (opp, "\n[G]\n");
1256                                 return COM_OK;
1257                         }
1258                         
1259                         /* if we're here, it means one of:
1260                          * 1. the server agrees opponent has time, whether lagging or not.
1261                          * 2. opp. has timeseal (if yourTime != serverTime), had time left
1262                          *    after the last move (yourTime > 0), and it's still your move.
1263                          * 3. we're currently checking a flag call after having receiving
1264                          *    acknowledgement from the other timeseal (and would have reset
1265                          *    yourTime if the flag were down). */
1266                         
1267                         pprintf(p, "Your opponent is not out of time!\n");
1268                         return COM_OK;
1269                 }
1270         }
1271         
1272         decline_withdraw_offers(p, -1, -1,DO_DECLINE);
1273         if (player_has_mating_material(&gg->game_state, myColor))
1274                 game_ended(g, myColor, END_FLAG);
1275         else
1276                 game_ended(g, myColor, END_FLAGNOMATERIAL);
1277         return COM_OK;
1278 }
1279
1280 int com_adjourn(int p, param_list param)
1281 {
1282   struct player *pp = &player_globals.parray[p];
1283   struct pending* pend;
1284   int p1, g, myColor, yourColor;
1285
1286   if (!pIsPlaying(p))
1287     return COM_OK;
1288
1289   p1 = pp->opponent;
1290   g = pp->game;
1291   if (!CheckPFlag(p, PFLAG_REG) || !CheckPFlag(p, PFLAG_REG)) {
1292     pprintf(p, "Both players must be registered to adjourn a game.  Use \"abort\".\n");
1293     return COM_OK;
1294   }
1295   if (game_globals.garray[g].link >= 0) {
1296     pprintf(p, "Bughouse games cannot be adjourned.\n");
1297     return COM_OK;
1298   }
1299   myColor = (p == game_globals.garray[g].white ? WHITE : BLACK);
1300   yourColor = (myColor == WHITE ? BLACK : WHITE);
1301
1302   if ((pend = find_pend(p1, p, PEND_ADJOURN)) != NULL) {
1303     delete_pending(pend);
1304     decline_withdraw_offers(p, -1, -1,DO_DECLINE);
1305     game_ended(pp->game, yourColor, END_ADJOURN);
1306   } else {
1307     game_update_time(g);
1308     if (((myColor == WHITE) && (game_globals.garray[g].wTime > 0) && (game_globals.garray[g].bTime <= 0))
1309         || ((myColor == BLACK) && (game_globals.garray[g].bTime > 0) && (game_globals.garray[g].wTime <= 0))) {
1310 /* player wants to adjourn + opponent is out of time = courtesyadjourn */
1311       pprintf(p, "Since you have time, and your opponent has none, the game has been adjourned.");
1312       pprintf(p1, "Your opponent has adjourned the game rather than calling your flag.");
1313       decline_withdraw_offers(p, -1, -1,DO_DECLINE);
1314       game_ended(g, myColor, END_COURTESYADJOURN);
1315     } else {
1316       pprintf(p1, "\n");
1317       pprintf_highlight(p1, "%s", pp->name);
1318       pprintf(p1, " would like to adjourn the game; ");
1319       pprintf_prompt(p1, "type \"adjourn\" to accept.\n");
1320       pprintf(p, "Adjourn request sent.\n");
1321       add_request(p, p1, PEND_ADJOURN);
1322     }
1323   }
1324   return COM_OK;
1325 }
1326
1327 int com_takeback(int p, param_list param)
1328 {
1329   struct player *pp = &player_globals.parray[p];
1330   int nHalfMoves = 1, g, i, p1, pend_half_moves;
1331   struct pending* from;
1332
1333   if (!pIsPlaying(p))
1334     return COM_OK;
1335
1336   p1 = pp->opponent;
1337   if ((player_globals.parray[p1].simul_info != NULL) && 
1338      (player_globals.parray[p1].simul_info->numBoards &&
1339         player_globals.parray[p1].simul_info->boards[player_globals.parray[p1].simul_info->onBoard] !=
1340         pp->game)) {
1341     pprintf(p, "You can only make requests when the simul player is at your board.\n");
1342     return COM_OK;
1343   }
1344
1345   g = pp->game;
1346   if (game_globals.garray[g].link >= 0) {
1347     pprintf(p, "Takeback not implemented for bughouse games yet.\n");
1348     return COM_OK;
1349   }
1350   if (param[0].type == TYPE_INT) {
1351     nHalfMoves = param[0].val.integer;
1352     if (nHalfMoves <= 0) {
1353       pprintf (p,"You can't takeback less than 1 move.\n");
1354       return COM_OK;
1355     }
1356   }
1357   if ((from = find_pend(pp->opponent, p, PEND_TAKEBACK)) != NULL) {
1358     pend_half_moves = from->wtime;
1359     delete_pending(from);
1360     if (pend_half_moves == nHalfMoves) {
1361       /* Doing the takeback */
1362       decline_withdraw_offers(p, -1, -PEND_SIMUL,DO_DECLINE);
1363       for (i = 0; i < nHalfMoves; i++) {
1364         if (backup_move(g, REL_GAME) != MOVE_OK) {
1365           pprintf(game_globals.garray[g].white, "Can only backup %d moves\n", i);
1366           pprintf(game_globals.garray[g].black, "Can only backup %d moves\n", i);
1367           break;
1368         }
1369       }
1370
1371       game_globals.garray[g].wTimeWhenReceivedMove = 0;
1372       game_globals.garray[g].bTimeWhenReceivedMove = 0;
1373
1374       send_boards(g);
1375     } else {
1376
1377       if (!game_globals.garray[g].numHalfMoves) {
1378         pprintf(p, "There are no moves in your game.\n");
1379         pprintf_prompt(pp->opponent, "\n%s has declined the takeback request.\n", 
1380                        pp->name);
1381         return COM_OK;
1382       }
1383  
1384       if (game_globals.garray[g].numHalfMoves < nHalfMoves) {
1385         pprintf(p, "There are only %d half moves in your game.\n", game_globals.garray[g].numHalfMoves);
1386         pprintf_prompt(pp->opponent, "\n%s has declined the takeback request.\n", 
1387                        pp->name);
1388         return COM_OK;
1389       }
1390       pprintf(p, "You disagree on the number of half-moves to takeback.\n");
1391       pprintf(p, "Alternate takeback request sent.\n");
1392       pprintf_prompt(pp->opponent, "\n%s proposes a different number (%d) of half-move(s).\n", pp->name, nHalfMoves);
1393       from = add_request(p, pp->opponent, PEND_TAKEBACK);
1394       from->wtime = nHalfMoves;
1395     }
1396   } else {
1397
1398     if (!game_globals.garray[g].numHalfMoves) {
1399       pprintf(p, "There are no moves in your game.\n");
1400       return COM_OK;
1401     }
1402     if (game_globals.garray[g].numHalfMoves < nHalfMoves) {
1403       pprintf(p, "There are only %d half moves in your game.\n", game_globals.garray[g].numHalfMoves);
1404       return COM_OK;
1405     }
1406     pprintf(pp->opponent, "\n");
1407     pprintf_highlight(pp->opponent, "%s", pp->name);
1408     pprintf_prompt(pp->opponent, " would like to take back %d half move(s).\n",
1409            nHalfMoves);
1410     pprintf(p, "Takeback request sent.\n");
1411     from = add_request(p, pp->opponent, PEND_TAKEBACK);
1412     from->wtime = nHalfMoves;
1413   }
1414   return COM_OK;
1415 }
1416
1417
1418 int com_switch(int p, param_list param)
1419 {
1420   struct player *pp = &player_globals.parray[p];
1421   int g = pp->game, tmp, now, p1;
1422   char *strTmp;
1423   struct pending* pend;
1424
1425   if (!pIsPlaying(p))
1426     return COM_OK;
1427
1428   p1 = pp->opponent;
1429   if ((player_globals.parray[p1].simul_info != NULL) && (player_globals.parray[p1].simul_info->numBoards &&
1430         player_globals.parray[p1].simul_info->boards[player_globals.parray[p1].simul_info->onBoard] != g)) {
1431     pprintf(p, "You can only make requests when the simul player is at your board.\n");
1432     return COM_OK;
1433   }
1434
1435   if (game_globals.garray[g].link >= 0) {
1436     pprintf(p, "Switch not implemented for bughouse games.\n");
1437     return COM_OK;
1438   }
1439   if ((pend = find_pend(pp->opponent, p, PEND_SWITCH)) != NULL) {
1440     delete_pending(pend);
1441     /* Doing the switch */
1442     decline_withdraw_offers(p, -1, -PEND_SIMUL,DO_DECLINE);
1443
1444     tmp = game_globals.garray[g].white;
1445     game_globals.garray[g].white = game_globals.garray[g].black;
1446     game_globals.garray[g].black = tmp;
1447     pp->side = (pp->side == WHITE) ? BLACK : WHITE;
1448     strTmp = strdup(game_globals.garray[g].white_name);
1449     strcpy(game_globals.garray[g].white_name, game_globals.garray[g].black_name);
1450     strcpy(game_globals.garray[g].black_name, strTmp);
1451     free(strTmp);
1452
1453     player_globals.parray[pp->opponent].side =
1454       (player_globals.parray[pp->opponent].side == WHITE) ? BLACK : WHITE;
1455     /* Roll back the time */
1456     if (game_globals.garray[g].game_state.onMove == WHITE) {
1457       game_globals.garray[g].wTime += (game_globals.garray[g].lastDecTime - game_globals.garray[g].lastMoveTime);
1458     } else {
1459       game_globals.garray[g].bTime += (game_globals.garray[g].lastDecTime - game_globals.garray[g].lastMoveTime);
1460     }
1461     now = tenth_secs();
1462     if (game_globals.garray[g].numHalfMoves == 0)
1463       game_globals.garray[g].timeOfStart = now;
1464     game_globals.garray[g].lastMoveTime = now;
1465     game_globals.garray[g].lastDecTime = now;
1466     send_boards(g);
1467     return COM_OK;
1468   }
1469   if (game_globals.garray[g].rated && game_globals.garray[g].numHalfMoves > 0) {
1470     pprintf(p, "You cannot switch sides once a rated game is underway.\n");
1471     return COM_OK;
1472   }
1473   pprintf(pp->opponent, "\n");
1474   pprintf_highlight(pp->opponent, "%s", pp->name);
1475   pprintf_prompt(pp->opponent, " would like to switch sides.\nType \"accept\" to switch sides, or \"decline\" to refuse.\n");
1476   pprintf(p, "Switch request sent.\n");
1477   add_request(p, pp->opponent, PEND_SWITCH);
1478   return COM_OK;
1479 }
1480
1481 int com_time(int p, param_list param)
1482 {
1483   struct player *pp = &player_globals.parray[p];
1484   int p1, g;
1485
1486   if (param[0].type == TYPE_NULL) {
1487     g = pp->game;
1488     if (!pIsPlaying(p))
1489       return COM_OK;
1490   } else {
1491     g = GameNumFromParam(p, &p1, &param[0]);
1492     if (g < 0)
1493       return COM_OK;
1494   }
1495   if ((g < 0) || (g >= game_globals.g_num) || (game_globals.garray[g].status != GAME_ACTIVE)) {
1496     pprintf(p, "There is no such game.\n");
1497     return COM_OK;
1498   }
1499   game_update_time(g);
1500   pprintf(p, "White (%s) : %d mins, %d secs\n",
1501           player_globals.parray[game_globals.garray[g].white].name,
1502           game_globals.garray[g].wTime / 600,
1503           (game_globals.garray[g].wTime - ((game_globals.garray[g].wTime / 600) * 600)) / 10);
1504   pprintf(p, "Black (%s) : %d mins, %d secs\n",
1505           player_globals.parray[game_globals.garray[g].black].name,
1506           game_globals.garray[g].bTime / 600,
1507           (game_globals.garray[g].bTime - ((game_globals.garray[g].bTime / 600) * 600)) / 10);
1508   return COM_OK;
1509 }
1510
1511 int com_ptime(int p, param_list param)
1512 {
1513   struct player *pp = &player_globals.parray[p];
1514   int retval, part = pp->partner;
1515
1516   if (part < 0) {
1517     pprintf(p, "You do not have a partner.\n");
1518     return COM_OK;
1519   }
1520   retval = pcommand (p, "time %s", player_globals.parray[part].name);
1521   if (retval == COM_OK)
1522     return COM_OK_NOPROMPT;
1523   else
1524     return retval;
1525 }
1526
1527 int com_boards(int p, param_list param)
1528 {
1529   char *category = NULL;
1530   char dname[MAX_FILENAME_SIZE];
1531   DIR *dirp;
1532   struct dirent *dp;
1533
1534   if (param[0].type == TYPE_WORD)
1535     category = param[0].val.word;
1536   if (category) {
1537     pprintf(p, "Boards Available For Category %s:\n", category);
1538     sprintf(dname, "%s/%s", BOARD_DIR, category);
1539   } else {
1540     pprintf(p, "Categories Available:\n");
1541     sprintf(dname, "%s", BOARD_DIR);
1542   }
1543   dirp = opendir(dname);
1544   if (!dirp) {
1545     pprintf(p, "No such category %s, try \"boards\".\n", category);
1546     return COM_OK;
1547   }
1548
1549 /* YUK! what a mess, how about printing an ordered directory? - DAV*/
1550
1551   for (dp = readdir(dirp); dp != NULL; dp = readdir(dirp)) {
1552     if (!strcmp(dp->d_name, "."))
1553       continue;
1554     if (!strcmp(dp->d_name, ".."))
1555       continue;
1556     pprintf(p, "%s\n", dp->d_name);
1557   }
1558   closedir(dirp);
1559   return COM_OK;
1560 }
1561
1562 int com_simmatch(int p, param_list param)
1563 {
1564   struct player *pp = &player_globals.parray[p];
1565   int p1, g, adjourned;
1566   int num;
1567   char tmp[100];
1568   struct pending* pend;
1569   char* board = NULL;
1570   char* category = NULL;
1571   char fname[MAX_FILENAME_SIZE];
1572
1573   if (pp->game >=0) {
1574     if (game_globals.garray[pp->game].status == GAME_EXAMINE) {
1575       pprintf(p, "You are still examining a game.\n");
1576       return COM_OK;
1577     }
1578     if (game_globals.garray[pp->game].status == GAME_SETUP) {
1579       pprintf(p, "You are still setting up a position.\n");
1580       return COM_OK;
1581     }
1582   } 
1583   p1 = player_find_part_login(param[0].val.word);
1584   if (p1 < 0) {
1585     pprintf(p, "No user named \"%s\" is logged in.\n", param[0].val.word);
1586     return COM_OK;
1587   }
1588   if (p == p1) {
1589     pprintf(p, "You can't simmatch yourself!\n");
1590     return COM_OK;
1591   }
1592   if ((pend = find_pend(p1, p, PEND_SIMUL)) != NULL) {
1593
1594     /* Accepting Simul ! */
1595
1596     if ((pp->simul_info != NULL) && 
1597        (pp->simul_info->numBoards >= MAX_SIMUL)) {
1598       pprintf(p, "You are already playing the maximum of %d boards.\n", MAX_SIMUL);
1599       pprintf(p1, "Simul request removed, boards filled.\n");
1600       delete_pending(pend);
1601       return COM_OK;
1602     }
1603     unobserveAll(p);            /* stop observing when match starts */
1604     unobserveAll(p1);
1605
1606     g = game_new();
1607     adjourned = 0;
1608     if (game_read(g, p, p1) >= 0) {
1609       adjourned = 1;
1610       delete_pending(pend);
1611     }
1612
1613     if (!adjourned) {           /* no adjourned game, so begin a new game */
1614
1615       if ((pend->category != NULL) && (pend->board_type != NULL)) {
1616         board = strdup(pend->category);
1617         category = strdup(pend->board_type);
1618       } 
1619
1620       delete_pending(pend);
1621
1622       if (create_new_match(g,p, p1, 0, 0, 0, 0, 0, ((board == NULL) ? "\0" : board), ((category == NULL) ? "\0" : category), 1,1) == COM_FAILED) {
1623         pprintf(p, "There was a problem creating the new match.\n");
1624         pprintf_prompt(p1, "There was a problem creating the new match.\n");
1625         game_remove(g);
1626
1627         if (board != NULL) {
1628           free (board);
1629           free (category);
1630         }
1631         return COM_OK;
1632       }
1633
1634       if (board != NULL) {
1635         free (board);
1636         free (category);
1637       }
1638
1639     } else {                    /* resume adjourned game */
1640       game_delete(p, p1);
1641
1642       sprintf(tmp, "{Game %d (%s vs. %s) Continuing %s %s simul.}\n", g + 1, pp->name, player_globals.parray[p1].name, rstr[game_globals.garray[g].rated], bstr[game_globals.garray[g].type]);
1643       pprintf(p, tmp);
1644       pprintf(p1, tmp);
1645
1646       game_globals.garray[g].white = p;
1647       game_globals.garray[g].black = p1;
1648       game_globals.garray[g].status = GAME_ACTIVE;
1649       game_globals.garray[g].startTime = tenth_secs();
1650       game_globals.garray[g].lastMoveTime = game_globals.garray[g].startTime;
1651       game_globals.garray[g].lastDecTime = game_globals.garray[g].startTime;
1652       pp->game = g;
1653       pp->opponent = p1;
1654       pp->side = WHITE;
1655       player_globals.parray[p1].game = g;
1656       player_globals.parray[p1].opponent = p;
1657       player_globals.parray[p1].side = BLACK;
1658       send_boards(g);
1659     }
1660
1661     if (pp->simul_info == NULL) {
1662       pp->simul_info = (struct simul_info_t *) malloc(sizeof(struct simul_info_t));
1663       pp->simul_info->numBoards = 0;
1664       pp->simul_info->onBoard = 0;
1665       pp->simul_info->num_wins = pp->simul_info->num_draws
1666         = pp->simul_info->num_losses = 0;
1667     }
1668     num = pp->simul_info->numBoards;
1669     /*    pp->simul_info->results[num] = -1; */
1670     pp->simul_info->boards[num] = pp->game;
1671     pp->simul_info->numBoards++;
1672     if (pp->simul_info->numBoards > 1 &&
1673         pp->simul_info->onBoard >= 0)
1674       player_goto_board(p, pp->simul_info->onBoard);
1675     else
1676       pp->simul_info->onBoard = 0;
1677     return COM_OK;
1678   }
1679   if (find_pend(-1, p, PEND_SIMUL) != NULL) {
1680     pprintf(p, "You cannot be the simul giver and request to join another simul.\nThat would just be too confusing for me and you.\n");
1681     return COM_OK;
1682   }
1683   if (pp->simul_info != NULL) {
1684     if (pp->simul_info->numBoards) {
1685       pprintf(p, "You cannot be the simul giver and request to join another simul.\nThat would just be too confusing for me and you.\n");
1686       return COM_OK;
1687     }
1688   }
1689   if (pp->game >=0) {
1690     pprintf(p, "You are already playing a game.\n");
1691     return COM_OK;
1692   }
1693   if (!CheckPFlag(p1, PFLAG_SIMOPEN)) {
1694     pprintf_highlight(p, "%s", player_globals.parray[p1].name);
1695     pprintf(p, " is not open to receiving simul requests.\n");
1696     return COM_OK;
1697   }
1698   if ((player_globals.parray[p1].simul_info != NULL) && (player_globals.parray[p1].simul_info->numBoards >= MAX_SIMUL)) {
1699     pprintf_highlight(p, "%s", player_globals.parray[p1].name);
1700     pprintf(p, " is already playing the maximum of %d boards.\n", MAX_SIMUL);
1701     return COM_OK;
1702   }
1703
1704 /* loon: checking for some crazy situations we can't allow :) */
1705
1706   if ((player_globals.parray[p1].simul_info != NULL) && (player_globals.parray[p1].game >=0) && (player_globals.parray[p1].simul_info->numBoards == 0)) {
1707     pprintf_highlight(p, "%s", player_globals.parray[p1].name);
1708     if (player_globals.parray[game_globals.garray[player_globals.parray[p1].game].white].simul_info->numBoards) {
1709       pprintf(p, " is playing in ");
1710       pprintf_highlight(p, "%s", player_globals.parray[player_globals.parray[p1].opponent].name);
1711       pprintf(p, "'s simul, and can't accept.\n");
1712     } else {
1713       pprintf(p, " can't begin a simul while playing a non-simul game.\n");
1714     }
1715     return COM_OK;
1716   }
1717
1718   g = game_new();               /* Check if an adjourned untimed game */
1719   adjourned = ((game_read(g, p, p1) < 0) && (game_read(g, p1, p) < 0)) ? 0 : 1;
1720   if (adjourned) {
1721     if (!(game_globals.garray[g].type == TYPE_UNTIMED))
1722       adjourned = 0;
1723   }
1724   game_remove(g);
1725
1726   pend = add_request(p, p1, PEND_SIMUL);
1727
1728   if ((param[1].type == TYPE_WORD) && (param[2].type == TYPE_WORD)) {
1729
1730     sprintf(fname, "%s/%s/%s", BOARD_DIR, param[1].val.word , param[2].val.word);
1731     if (!file_exists(fname)) {
1732       pprintf(p, "No such category/board: %s/%s\n", param[1].val.word , param[2].val.word);
1733       return COM_OK;
1734     }
1735     pend->category = strdup(param[1].val.word);
1736     pend->board_type = strdup(param[2].val.word);
1737   } else {
1738     pend->category = NULL;
1739     pend->board_type = NULL;
1740   }
1741  
1742   pprintf(p1, "\n");
1743   pprintf_highlight(p1, "%s", pp->name);
1744   if (adjourned) {
1745     pprintf_prompt(p1, " requests to continue an adjourned simul game.\n");
1746     pprintf(p, "Request to resume simul sent. Adjourned game found.\n");
1747   } else {
1748     if (pend->category == NULL)
1749       pprintf_prompt(p1, " requests to join a simul match with you.\n");
1750     else
1751       pprintf_prompt(p1, " requests to join a %s %s simul match with you.\n",
1752                 pend->category,pend->board_type);
1753     pprintf(p, "Simul match request sent.\n");
1754   }
1755   return COM_OK;
1756 }
1757
1758 int com_goboard(int p, param_list param)
1759 {
1760   struct player *pp = &player_globals.parray[p];
1761   int on, g, p1, gamenum;
1762
1763   if (pp->simul_info == NULL) {
1764     pprintf(p, "You are not giving a simul.\n");
1765     return COM_OK;
1766   }
1767
1768   if (!pp->simul_info->numBoards) {
1769     pprintf(p, "You are not giving a simul.\n");
1770     return COM_OK;
1771   }
1772
1773   if (param[0].type == TYPE_WORD) {
1774
1775     p1 = player_find_part_login(param[0].val.word);
1776     if (p1 < 0) {
1777       pprintf(p, "No user named \"%s\" is logged in.\n", param[0].val.word);
1778       return COM_OK;
1779     }
1780     if (p == p1) {
1781       pprintf(p, "You can't goboard yourself!\n");
1782       return COM_OK;
1783     }
1784
1785     gamenum = player_globals.parray[p1].game;
1786     if (gamenum < 0) {
1787       pprintf (p,"%s is not playing a game.\n", player_globals.parray[p1].login);
1788       return COM_OK;
1789     }
1790
1791   } else { 
1792     gamenum = param[0].val.integer - 1;
1793     if (gamenum < 0)
1794       gamenum = 0;
1795   }
1796
1797   on = pp->simul_info->onBoard;
1798   g = pp->simul_info->boards[on];
1799   if (gamenum == g) {
1800     pprintf(p, "You are already at that board!\n");
1801     return COM_OK;
1802   }
1803   if (pp->simul_info->numBoards > 1) {
1804     decline_withdraw_offers(p, -1, -PEND_SIMUL,DO_DECLINE);
1805     if (player_goto_simulgame_bynum(p, gamenum) !=-1) {
1806       if (g >= 0) {
1807         pprintf(game_globals.garray[g].black, "\n");
1808         pprintf_highlight(game_globals.garray[g].black, "%s", pp->name);
1809         pprintf_prompt(game_globals.garray[g].black, " has moved away from your board.\n");
1810       }
1811     } else
1812     pprintf(p, "You are not playing that game/person.\n");
1813   } else
1814     pprintf(p, "You are only playing one board!\n");
1815   return COM_OK;
1816 }
1817
1818 int com_simnext(int p, param_list param)
1819 {
1820   struct player *pp = &player_globals.parray[p];
1821   int on, g;
1822
1823   if (pp->simul_info == NULL) {
1824     pprintf(p, "You are not giving a simul.\n");
1825     return COM_OK;
1826   }
1827
1828   if (!pp->simul_info->numBoards) {
1829     pprintf(p, "You are not giving a simul.\n");
1830     return COM_OK;
1831   }
1832
1833   if (pp->simul_info->numBoards > 1) {
1834     decline_withdraw_offers(p, -1, -PEND_SIMUL,DO_DECLINE);
1835     on = pp->simul_info->onBoard;
1836     g = pp->simul_info->boards[on];
1837     if (g >= 0) {
1838       pprintf(game_globals.garray[g].black, "\n");
1839       pprintf_highlight(game_globals.garray[g].black, "%s", pp->name);
1840       pprintf_prompt(game_globals.garray[g].black, " is moving away from your board.\n");
1841       player_goto_next_board(p);
1842     }
1843   } else
1844     pprintf(p, "You are only playing one board!\n");
1845   return COM_OK;
1846 }
1847
1848 int com_simprev(int p, param_list param)
1849 {
1850   struct player *pp = &player_globals.parray[p];
1851   int on, g;
1852
1853   if (pp->simul_info == NULL) {
1854     pprintf(p, "You are not giving a simul.\n");
1855     return COM_OK;
1856   }
1857
1858   if (!pp->simul_info->numBoards) {
1859     pprintf(p, "You are not giving a simul.\n");
1860     return COM_OK;
1861   }
1862   if (pp->simul_info->numBoards > 1) {
1863     decline_withdraw_offers(p, -1, -PEND_SIMUL,DO_DECLINE);
1864     on = pp->simul_info->onBoard;
1865     g = pp->simul_info->boards[on];
1866     if (g >= 0) {
1867       pprintf(game_globals.garray[g].black, "\n");
1868       pprintf_highlight(game_globals.garray[g].black, "%s", pp->name);
1869       pprintf_prompt(game_globals.garray[g].black, " is moving back to the previous board.\n");
1870     }
1871     player_goto_prev_board(p);
1872   } else
1873     pprintf(p, "You are only playing one board!\n");
1874   return COM_OK;
1875 }
1876
1877 int com_simgames(int p, param_list param)
1878 {
1879   int p1 = p;
1880
1881   if (param[0].type == TYPE_WORD) {
1882     if ((p1 = player_find_part_login(param[0].val.word)) < 0) {
1883       pprintf(p, "No player named %s is logged in.\n", param[0].val.word);
1884       return COM_OK;
1885     }
1886   }
1887   if (p1 == p)
1888     pprintf(p, "You are playing %d simultaneous games.\n",
1889             player_num_active_boards(p1));
1890   else
1891     pprintf(p, "%s is playing %d simultaneous games.\n", player_globals.parray[p1].name,
1892             player_num_active_boards(p1));
1893   return COM_OK;
1894 }
1895
1896 int com_simpass(int p, param_list param)
1897 {
1898   struct player *pp = &player_globals.parray[p];
1899   int g, p1, on;
1900
1901   if (!pIsPlaying(p))
1902     return COM_OK;
1903
1904   g = pp->game;
1905   p1 = game_globals.garray[g].white;
1906
1907   if (player_globals.parray[p1].simul_info == NULL) {
1908     pprintf(p, "You are not participating in a simul.\n");
1909     return COM_OK;
1910   }
1911
1912   if (!player_globals.parray[p1].simul_info->numBoards) {
1913     pprintf(p, "You are not participating in a simul.\n");
1914     return COM_OK;
1915   }
1916   if (p == p1) {
1917     pprintf(p, "You are the simul holder and cannot pass!\n");
1918     return COM_OK;
1919   }
1920   if (player_num_active_boards(p1) == 1) {
1921     pprintf(p, "This is the only game, so passing is futile.\n");
1922     return COM_OK;
1923   }
1924   on = player_globals.parray[p1].simul_info->onBoard;
1925   if (player_globals.parray[p1].simul_info->boards[on] != g) {
1926     pprintf(p, "You cannot pass until the simul holder arrives!\n");
1927     return COM_OK;
1928   }
1929   if (game_globals.garray[g].passes >= MAX_SIMPASS) {
1930     Bell (p);
1931     pprintf(p, "You have reached your maximum of %d pass(es).\n", MAX_SIMPASS);
1932     pprintf(p, "Please move IMMEDIATELY!\n");
1933     pprintf_highlight(p1, "%s", pp->name);
1934     pprintf_prompt(p1, " tried to pass, but is out of passes.\n");
1935     return COM_OK;
1936   }
1937   decline_withdraw_offers(p, -1, -PEND_SIMUL,DO_DECLINE);
1938
1939   game_globals.garray[g].passes++;
1940   pprintf(p, "You have passed and have %d pass(es) left.\n",
1941           (MAX_SIMPASS - game_globals.garray[g].passes));
1942   pprintf_highlight(p1, "%s", pp->name);
1943   pprintf_prompt(p1, " has decided to pass and has %d pass(es) left.\n",
1944                  (MAX_SIMPASS - game_globals.garray[g].passes));
1945   player_goto_next_board(p1);
1946   return COM_OK;
1947 }
1948
1949 int com_simabort(int p, param_list param)
1950 {
1951   struct player *pp = &player_globals.parray[p];
1952
1953   if (pp->simul_info == NULL) {
1954     pprintf(p, "You are not giving a simul.\n");
1955     return COM_OK;
1956   }
1957
1958   if (!pp->simul_info->numBoards) {
1959     pprintf(p, "You are not giving a simul.\n");
1960     return COM_OK;
1961   }
1962   decline_withdraw_offers(p, -1, -PEND_SIMUL,DO_DECLINE);
1963   game_ended(pp->simul_info->boards[pp->simul_info->onBoard],
1964              WHITE, END_ABORT);
1965   return COM_OK;
1966 }
1967
1968 int com_simallabort(int p, param_list param)
1969 {
1970   struct player *pp = &player_globals.parray[p];
1971   int i;
1972
1973   if (pp->simul_info == NULL) {
1974     pprintf(p, "You are not giving a simul.\n");
1975     return COM_OK;
1976   }
1977
1978   if (!pp->simul_info->numBoards) {
1979     pprintf(p, "You are not giving a simul.\n");
1980     return COM_OK;
1981   }
1982
1983   decline_withdraw_offers(p, -1, -PEND_SIMUL,DO_DECLINE);
1984   for (i = 0; i < pp->simul_info->numBoards; i++)
1985     if (pp->simul_info->boards[i] >= 0)
1986       game_ended(pp->simul_info->boards[i],
1987                  WHITE, END_ABORT);
1988
1989   return COM_OK;
1990 }
1991
1992 int com_simadjourn(int p, param_list param)
1993 {
1994   struct player *pp = &player_globals.parray[p];
1995
1996   if (pp->simul_info == NULL) {
1997     pprintf(p, "You are not giving a simul.\n");
1998     return COM_OK;
1999   }
2000
2001   if (!pp->simul_info->numBoards) {
2002     pprintf(p, "You are not giving a simul.\n");
2003     return COM_OK;
2004   }
2005   decline_withdraw_offers(p, -1, -PEND_SIMUL,DO_DECLINE);
2006   game_ended(pp->simul_info->boards[pp->simul_info->onBoard],
2007              WHITE, END_ADJOURN);
2008   return COM_OK;
2009 }
2010
2011 int com_simalladjourn(int p, param_list param)
2012 {
2013   struct player *pp = &player_globals.parray[p];
2014   int i;
2015
2016   if (pp->simul_info == NULL) {
2017     pprintf(p, "You are not giving a simul.\n");
2018     return COM_OK;
2019   }
2020
2021   if (!pp->simul_info->numBoards) {
2022     pprintf(p, "You are not giving a simul.\n");
2023     return COM_OK;
2024   }
2025   decline_withdraw_offers(p, -1, -PEND_SIMUL,DO_DECLINE);
2026   for (i = 0; i < pp->simul_info->numBoards; i++)
2027     if (pp->simul_info->boards[i] >= 0)
2028       game_ended(pp->simul_info->boards[i],
2029                  WHITE, END_ADJOURN);
2030
2031   return COM_OK;
2032 }
2033
2034 int com_moretime(int p, param_list param)
2035 {
2036   struct player *pp = &player_globals.parray[p];
2037   int g, increment;
2038
2039   if ((pp->game >=0) &&((game_globals.garray[pp->game].status == GAME_EXAMINE) ||
2040         (game_globals.garray[pp->game].status == GAME_SETUP))) {
2041     pprintf(p, "You cannot use moretime in an examined game.\n");
2042     return COM_OK;
2043   }
2044   increment = param[0].val.integer;
2045   if (increment <= 0) {
2046     pprintf(p, "Moretime requires an integer value greater than zero.\n");
2047     return COM_OK;
2048   }
2049   if (!pIsPlaying(p))
2050     return COM_OK;
2051  
2052   if (increment > 600) {
2053     pprintf(p, "Moretime has a maximum limit of 600 seconds.\n");
2054     increment = 600;
2055   }
2056   g = pp->game;
2057   if (game_globals.garray[g].white == p) {
2058     game_globals.garray[g].bTime += increment * 10;
2059     game_globals.garray[g].bRealTime += increment * 10 * 100;
2060     pprintf(p, "%d seconds were added to your opponents clock\n",
2061             increment);
2062     pprintf_prompt(pp->opponent,
2063                    "\nYour opponent has added %d seconds to your clock.\n",
2064                    increment);
2065   }
2066   if (game_globals.garray[g].black == p) {
2067     game_globals.garray[g].wTime += increment * 10;;
2068     game_globals.garray[g].wRealTime += increment * 10 * 100;
2069     pprintf(p, "%d seconds were added to your opponents clock\n",
2070             increment);
2071     pprintf_prompt(pp->opponent,
2072                    "\nYour opponent has added %d seconds to your clock.\n",
2073                    increment);
2074   }
2075   return COM_OK;
2076 }
2077