File: init.c

package info (click to toggle)
gnushogi 1.2p03-6
  • links: PTS
  • area: main
  • in suites: hamm, slink
  • size: 796 kB
  • ctags: 1,240
  • sloc: ansic: 13,484; makefile: 266; sh: 2
file content (1146 lines) | stat: -rw-r--r-- 27,384 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
/*
 * init.c - C source for GNU SHOGI
 *
 * Copyright (c) 1993, 1994, 1995 Matthias Mutz
 *
 * GNU SHOGI is based on GNU CHESS
 *
 * Copyright (c) 1988,1989,1990 John Stanback
 * Copyright (c) 1992 Free Software Foundation
 *
 * This file is part of GNU SHOGI.
 *
 * GNU Shogi is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 1, or (at your option)
 * any later version.
 *
 * GNU Shogi is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with GNU Shogi; see the file COPYING.  If not, write to
 * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
 */
 
#include "gnushogi.h"



#if defined HASGETTIMEOFDAY && !defined THINK_C
#include <sys/time.h>
#endif

#if defined THINK_C
#include <time.h>
#endif

#if !defined SIGTERM
#include <signal.h>
#endif

#include "pattern.h"


unsigned int ttbllimit;

/* .... MOVE GENERATION VARIABLES AND INITIALIZATIONS .... */


#ifdef THINK_C                
#define abs(a) (((a)<0)?-(a):(a))
#endif
#if !defined(MSDOS) || defined(__GO32__)
#define max(a,b) (((a)<(b))?(b):(a))
#endif
#define odd(a) ((a) & 1)


const small_short piece_of_ptype[NO_PTYPE_PIECES] =
{ pawn, lance, knight, silver, gold, bishop, rook, pbishop, prook, king,
    pawn, lance, knight, silver, gold };


const small_short side_of_ptype[NO_PTYPE_PIECES] =
{ black, black, black, black, black, black, black, black, black, black,
    white, white, white, white, white };

#ifdef SAVE_NEXTPOS
const small_short psweep[NO_PTYPE_PIECES] =
{ false, true, false, false, false, true, true, true, true, false,
    false, true, false, false, false };
#endif

const small_short sweep[NO_PIECES] =
{ false, false, true, false, false, false, true, true,  
  false, false, false, false, true, true, false };


#if !defined EXTLANGFILE

char far *CP[CPSIZE] = 

{             
/* 000:eng: */ "",
#ifdef LANGFILE
#include LANGFILE
#else
#include "gnushogi.lng"
#endif
};

#else

char far *CP[CPSIZE];

#endif


short
ptype_distance (short ptyp, short f, short t)

/*
 * Determine the minimum number of moves for a piece from
 * square "f" to square "t". If the piece cannot reach "t",
 * the count is set to CANNOT_REACH.
 */

#define csquare(sq) ((side == black) ? sq : (NO_SQUARES-1-sq))
#define crow(sq) row(csquare(sq))
#define ccol(sq) column(csquare(sq))

{
  short side, piece;
  short colf, colt, rowf, rowt, dcol, drow;

  if ( f == t )
    return (0);

  piece = piece_of_ptype[ptyp];
  side  = side_of_ptype[ptyp];

  dcol = (colt = ccol(t)) - (colf = ccol(f));
  drow = (rowt = crow(t)) - (rowf = crow(f));

  switch ( piece ) {

    case pawn:
	if ( (dcol != 0) || (drow < 1) )
	  return (CANNOT_REACH);
	else
	  return (drow);

    case lance:
	if ( (dcol != 0) || (drow < 1) )
	  return (CANNOT_REACH);
	else
	  return (1);

    case knight:
	if ( odd(drow) || (odd(drow / 2) != odd(dcol)) )
	  return (CANNOT_REACH);
	else if ( (drow == 0) || ((drow / 2) < abs(dcol)) )
	  return (CANNOT_REACH);
	else
	  return (drow / 2);

    case silver:
	if ( drow > 0 ) {
	  if ( odd(drow) == odd(dcol) )
	    return max(abs(drow),abs(dcol));
	  else
	    if ( abs(dcol) <= drow )
	      return (drow);
	    else
	      return (max(abs(drow),abs(dcol))+1);
	} else {
	  if ( odd(drow) == odd(dcol) )
	    return (max(abs(drow),abs(dcol)));
	  else
	    return (max(abs(drow)+1,abs(dcol))+1);
	};

    case gold:
    case ppawn:
    case pknight:
    case plance:
    case psilver:
	if ( abs(dcol) == 0 )
	  return (abs(drow));
	else if ( drow >= 0 )
	  return max(drow,abs(dcol));
	else
	  return (abs(dcol)-drow);

    case bishop:
	if ( odd(dcol) != odd(drow) )
	  return (CANNOT_REACH);
	else
	  return ((abs(dcol) == abs(drow)) ? 1 : 2);

    case pbishop:
	if ( odd(dcol) != odd(drow) )
	  if ( (abs(dcol) <= 1) && (abs(drow) <= 1) )
	    return (1);
	  else if ( abs(abs(dcol) - abs(drow)) == 1 )
	    return (2);
	  else
	    return (3);
	else
	  return ((abs(dcol) == abs(drow)) ? 1 : 2);

    case rook:
	if ( (dcol == 0) || (drow == 0) )
	  return (1);
	else
	  return (2);

    case prook:
	if ( (dcol == 0) || (drow == 0) )
	  return (1);
	else if ( (abs(dcol) == 1) && (abs(drow) == 1) )
	  return (1);
	else
	  return (2);

    case king:
	return max(abs(drow),abs(dcol));

    default:
	/* should never occur */
	return (CANNOT_REACH);

  }

}


#ifdef SAVE_DISTDATA 
short distance (short a, short b) 
{ 
  return (short)computed_distance(a,b);
}
#else                
short distance (short a, short b)
{
  return (use_distdata ? (short)(*distdata)[(int)a][(int)b] : (short)computed_distance(a,b));
}
#endif                         


#ifdef SAVE_PTYPE_DISTDATA
short piece_distance(short side,short piece,short f,short t)
{
  return ((f > NO_SQUARES) ? (short)1 : (short)ptype_distance(ptype[side][piece],f,t));
}
#else
short piece_distance(short side,short piece,short f,short t)
{
  return ((f > NO_SQUARES) ? (short)1 : 
                 (use_ptype_distdata ? (short)(*ptype_distdata[ptype[side][piece]])[f][t] :
     			               (short)ptype_distance(ptype[side][piece],f,t)));
}
#endif                      


void
Initialize_dist (void)
{
  register short a, b, d, di, ptyp;
#ifndef SAVE_DISTDATA  
  for (a = 0; a < NO_SQUARES; a++)
    for (b = 0; b < NO_SQUARES; b++)
      {
        d = abs (column (a) - column (b));
	di = abs (row (a) - row (b));
	(*distdata)[a][b] = (small_short)((d > di) ? d : di);
      } 
#endif
#ifndef SAVE_PTYPE_DISTDATA
  for (ptyp = 0; ptyp < NO_PTYPE_PIECES; ptyp++)
    {
      for (a = 0; a < NO_SQUARES; a++)
        for (b = 0; b < NO_SQUARES; b++)
          (*ptype_distdata[ptyp])[a][b] = ptype_distance(ptyp,a,b);
    }
#endif
}


/*
 * nextpos[piece][from-square] , nextdir[piece][from-square] gives vector of
 * positions reachable from from-square in ppos with piece such that the
 * sequence	ppos = nextpos[piece][from-square]; pdir =
 * nextdir[piece][from-square]; u = ppos[sq]; do { u = ppos[u]; if(color[u]
 * != neutral) u = pdir[u]; } while (sq != u); will generate the sequence of
 * all squares reachable from sq.
 *
 * If the path is blocked u = pdir[sq] will generate the continuation of the
 * sequence in other directions.
 */


/*                                           
 * ptype is used to separate black and white pawns, like this; ptyp =
 * ptype[side][piece] piece can be used directly in nextpos/nextdir when
 * generating moves for pieces that are not white pawns.
 */

const small_short ptype[2][NO_PIECES] =
{ ptype_no_piece, ptype_pawn, ptype_lance, ptype_knight, 
    ptype_silver, ptype_gold, ptype_bishop, ptype_rook,
    ptype_gold, ptype_gold, ptype_gold, ptype_gold, 
    ptype_pbishop, ptype_prook, ptype_king,
  ptype_no_piece, ptype_wpawn, ptype_wlance, ptype_wknight, 
    ptype_wsilver, ptype_wgold, ptype_bishop, ptype_rook,
    ptype_wgold, ptype_wgold, ptype_wgold, ptype_wgold, 
    ptype_pbishop, ptype_prook, ptype_king};

const small_short promoted[NO_PIECES] =
{ no_piece, ppawn, plance, pknight, psilver, gold, pbishop, prook,
    ppawn, plance, pknight, psilver, pbishop, prook, king };
    
const small_short unpromoted[NO_PIECES] =
{ no_piece, pawn, lance, knight, silver, gold, bishop, rook,
    pawn, lance, knight, silver, bishop, rook, king };
    
const small_short is_promoted[NO_PIECES] =
{ false, false, false, false, false, false, false, false,
    true, true, true, true, true, true, false };

/* data used to generate nextpos/nextdir */
#if !defined SAVE_NEXTPOS
static
#endif 
const small_short direc[NO_PTYPE_PIECES][8] =
{
   11,  0,  0,  0,  0,  0,  0,  0 ,   /*  0 ptype_pawn */
   11,  0,  0,  0,  0,  0,  0,  0 ,   /*  1 ptype_lance */
   21, 23,  0,  0,  0,  0,  0,  0 ,   /*  2 ptype_knight */
   10, 11, 12,-12,-10,  0,  0,  0 ,   /*  3 ptype_silver */
   10, 11, 12, -1,  1,-11,  0,  0 ,   /*  4 ptype_gold */
   10, 12,-12,-10,  0,  0,  0,  0 ,   /*  5 ptype_bishop */
   11, -1,  1,-11,  0,  0,  0,  0 ,   /*  6 ptype_rook */
   10, 12,-12,-10, 11, -1,  1,-11 ,   /*  7 ptype_pbishop */
   11, -1,  1,-11, 10, 12,-12,-10 ,   /*  8 ptype_prook */
   10, 11, 12, -1,  1,-12,-11,-10 ,   /*  9 ptype_king */
  -11,  0,  0,  0,  0,  0,  0,  0 ,   /* 10 ptype_wpawn */
  -11,  0,  0,  0,  0,  0,  0,  0 ,   /* 11 ptype_wlance */
  -21,-23,  0,  0,  0,  0,  0,  0 ,   /* 12 ptype_wknight */
  -10,-11,-12, 12, 10,  0,  0,  0 ,   /* 13 ptype_wsilver */
  -10,-11,-12,  1, -1, 11,  0,  0 };  /* 14 ptype_wgold */


small_short diagonal(short d) 
{ return(abs(d) == 10 || abs(d) == 12);
}

   
static const small_short max_steps[NO_PTYPE_PIECES] = 
{1, 8, 1, 1, 1, 8, 8, 8, 8, 1, 1, 8, 1, 1, 1 };

const small_short nunmap[(NO_COLS+2)*(NO_ROWS+4)] =
{
  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
  -1,  0,  1,  2,  3,  4,  5,  6,  7,  8, -1,
  -1,  9, 10, 11, 12, 13, 14, 15, 16, 17, -1,
  -1, 18, 19, 20, 21, 22, 23, 24, 25, 26, -1,
  -1, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1,
  -1, 36, 37, 38, 39, 40, 41, 42, 43, 44, -1,
  -1, 45, 46, 47, 48, 49, 50, 51, 52, 53, -1,
  -1, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1,
  -1, 63, 64, 65, 66, 67, 68, 69, 70, 71, -1,
  -1, 72, 73, 74, 75, 76, 77, 78, 79, 80, -1,
  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1};


const small_short inunmap[NO_SQUARES] =
{
  23, 24, 25, 26, 27, 28, 29, 30, 31, 
  34, 35, 36, 37, 38, 39, 40, 41, 42,
  45, 46, 47, 48, 49, 50, 51, 52, 53,
  56, 57, 58, 59, 60, 61, 62, 63, 64,
  67, 68, 69, 70, 71, 72, 73, 74, 75,
  78, 79, 80, 81, 82, 83, 84, 85, 86,
  89, 90, 91, 92, 93, 94, 95, 96, 97,
 100,101,102,103,104,105,106,107,108,
 111,112,113,114,115,116,117,118,119 }; 

int InitFlag = false;


#if defined SAVE_NEXTPOS

short next_direction(short ptyp, short *d, short sq)
{
  short delta, to, sfrom = inunmap[sq];
  do { 
    (*d)++;
    if ( *d >= 8 ) return sq;
    delta = direc[ptyp][*d];
    if ( delta == 0 ) return sq;
    to = nunmap[sfrom + delta];
  } while ( to < 0 );
  return to;  
}

short next_position(short ptyp, short *d, short sq, short u)
{
  if ( *d < 4 && psweep[ptyp] ) {
    short to = nunmap[inunmap[u]+direc[ptyp][*d]];
    if ( to < 0 )
	return next_direction(ptyp,d,sq);
    else
	return to;
  } else {
    return next_direction(ptyp,d,sq);
  } 
}

short first_direction(short ptyp, short *d, short sq)
{
  *d = -1;
  return next_direction(ptyp,d,sq);
}

#else

void
Initialize_moves (void)

/*
 * This procedure pre-calculates all moves for every piece from every square.
 * This data is stored in nextpos/nextdir and used later in the move
 * generation routines.
 */

{
  short ptyp, po, p0, d, di, s, delta, i;
  unsigned char far *ppos, *pdir;       
  short dest[8][9];
  short sorted[9];              
  short steps[8];
  short fpo=23,tpo=120;

  for (ptyp = 0; ptyp < NO_PTYPE_PIECES; ptyp++)
    {
      for (po = 0; po < NO_SQUARES; po++)
        for (p0 = 0; p0 < NO_SQUARES; p0++)
	  { 
	    (*nextpos[ptyp])[po][p0] = (unsigned char) po;
	    (*nextdir[ptyp])[po][p0] = (unsigned char) po;
	  }
    }
	
  for (ptyp = 0; ptyp < NO_PTYPE_PIECES; ptyp++) 
    for (po = fpo; po < tpo; po++)
      if (nunmap[po] >= (small_short)0)
	{ 
	  ppos = (*nextpos[ptyp])[nunmap[po]];
	  pdir = (*nextdir[ptyp])[nunmap[po]];
	  /* dest is a function of direction and steps */
	  for (d = 0; d < 8; d++)
	    {
	      dest[d][0] = nunmap[po];
	      delta = direc[ptyp][d];
	      if (delta != 0)
		{
		  p0 = po;
		  for (s = 0; s < max_steps[ptyp]; s++)
		    {
		      p0 = p0 + delta;

		      /*
		       * break if (off board) or (promoted rooks wishes to 
                       * move two steps diagonal) or (promoted
                       * bishops wishes to move two steps non-diagonal) 
		       */                     
		      if ( (nunmap[p0] < (small_short)0) ||
                           ((ptyp == ptype_prook) && (s > 0) && diagonal(delta)) ||
                           ((ptyp == ptype_pbishop) && (s > 0) && !diagonal(delta)) )
			break;
		      else
			dest[d][s] = nunmap[p0];
		    }
		}
	      else
		s = 0;

	      /*
	       * sort dest in number of steps order currently no sort
	       * is done due to compability with the move generation
	       * order in old gnu chess
	       */
	      steps[d] = s;
	      for (di = d; s > 0 && di > 0; di--)
		if (steps[sorted[di - 1]] == 0)	/* should be: < s */
		  sorted[di] = sorted[di - 1];
		else
		  break;
	      sorted[di] = d;
	    }

	  /*
	   * update nextpos/nextdir
	   */
	  p0 = nunmap[po];
	  pdir[p0] = (unsigned char) dest[sorted[0]][0];
	  for (d = 0; d < 8; d++)
	      for (s = 0; s < steps[sorted[d]]; s++)
		  {
		    ppos[p0] = (unsigned char) dest[sorted[d]][s];
		    p0 = dest[sorted[d]][s];
		    if (d < 7)
		      pdir[p0] = (unsigned char) dest[sorted[d + 1]][0];

		    /*
		     * else is already initialized
		     */
		  }
	}

}

#endif


void
NewGame (void)

/*
 * Reset the board and other variables to start a new game.
 */

{
  short l, c, p, max_opening_sequence;
#ifdef HASGETTIMEOFDAY
  struct timeval tv;
#endif
  compptr = oppptr = 0;
  stage = 0; stage2 = -1;	/* the game is not yet started */
  flag.illegal = flag.mate = flag.post = flag.quit = flag.reverse = flag.bothsides = flag.onemove = flag.force = false;
  flag.material = flag.coords = flag.hash = flag.easy = flag.beep = flag.rcptr = true;
  flag.stars = flag.shade = flag.back = flag.musttimeout = false;
  flag.gamein = false;
#if defined(MSDOS) && !defined(SEVENBIT)
  flag.rv = false;
#else
  flag.rv = true;
#endif /* MSDOS && !SEVENBIT */
  mycnt1 = mycnt2 = 0;
  GenCnt = NodeCnt = et0 = dither =  XCmore = 0;
  znodes = ZNODES;
  WAwindow = WAWNDW;
  WBwindow = WBWNDW;
  BAwindow = BAWNDW;
  BBwindow = BBWNDW;
  xwndw = BXWNDW;
  if (!MaxSearchDepth)
    MaxSearchDepth = MAXDEPTH - 1;
  contempt = 0;
  GameCnt = 0;
  Game50 = 1;
  CptrFlag[0] = TesujiFlag[0] = false;
  hint = OPENING_HINT;
  ZeroRPT ();
  GameType[0] = GameType[1] = UNKNOWN;
  Pscore[0] = Tscore[0] = (SCORE_LIMIT+3000);
  opponent = player = black;
  computer = white;
  for (l = 0; l < TREE; l++)
    Tree[l].f = Tree[l].t = 0;
  gsrand ((unsigned int) 1);
  if (!InitFlag)
    {            
      for (c = black; c <= white; c++)
	for (p = pawn; p <= king; p++)
	  for (l = 0; l < NO_SQUARES; l++)
	    {
	      (*hashcode)[c][p][l].key = (((unsigned long) urand ()));
	      (*hashcode)[c][p][l].key += (((unsigned long) urand ()) << 16);
	      (*hashcode)[c][p][l].bd = (((unsigned long) urand ()));
	      (*hashcode)[c][p][l].bd += (((unsigned long) urand ()) << 16);
#ifdef LONG64
	      (*hashcode)[c][p][l].key += (((unsigned long) urand ()) << 32);
	      (*hashcode)[c][p][l].key += (((unsigned long) urand ()) << 48);
	      (*hashcode)[c][p][l].bd += (((unsigned long) urand ()) << 32);
	      (*hashcode)[c][p][l].bd += (((unsigned long) urand ()) << 48);
#endif
	    }           
      for (c = black; c <= white; c++)
	for (p = pawn; p <= king; p++)
	  for (l = 0; l < MAX_CAPTURED; l++)
	    {
	      (*drop_hashcode)[c][p][l].key = (((unsigned long) urand ()));
	      (*drop_hashcode)[c][p][l].key += (((unsigned long) urand ()) << 16);
	      (*drop_hashcode)[c][p][l].bd = (((unsigned long) urand ()));
	      (*drop_hashcode)[c][p][l].bd += (((unsigned long) urand ()) << 16);
#ifdef LONG64
	      (*drop_hashcode)[c][p][l].key += (((unsigned long) urand ()) << 32);
	      (*drop_hashcode)[c][p][l].key += (((unsigned long) urand ()) << 48);
	      (*drop_hashcode)[c][p][l].bd += (((unsigned long) urand ()) << 32);
	      (*drop_hashcode)[c][p][l].bd += (((unsigned long) urand ()) << 48);
#endif
	    }
    }
  for (l = 0; l < NO_SQUARES; l++)
    {
      board[l] = Stboard[l];
      color[l] = Stcolor[l];
      Mvboard[l] = 0;
    }
  ClearCaptured ();
  ClrScreen ();
  InitializeStats ();
#ifdef HASGETTIMEOFDAY
  gettimeofday(&tv, NULL);
  time0 = tv.tv_sec*100+tv.tv_usec/10000;
#elif defined THINK_C
  time0 = time (0);
#else
  time0 = time ((long *) 0);
#endif
  /* resetting reference time */
  ElapsedTime (COMPUTE_AND_INIT_MODE);
  flag.regularstart = true;
  Book = BOOKFAIL;
  if (!InitFlag)
    {
      char sx[256];
      strcpy(sx,CP[169]);
      if (TCflag)
	SetTimeControl ();
      else if (MaxResponseTime == 0)
	SelectLevel (sx);
      UpdateDisplay (0, 0, 1, 0);
      GetOpenings ();
      GetOpeningPatterns (&max_opening_sequence);
#ifdef DEBUG
      /* ShowOpeningPatterns (max_opening_sequence); */
#endif
      InitFlag = true;
    }
#if ttblsz
  if(TTadd){ZeroTTable (); TTadd = 0;}
#endif /* ttblsz */
  hashbd = hashkey = 0;
  return;
}              



int
Initialize_data (void)
{
  size_t n;
  int i;   
  char buffer[60],buf2[60];
  int doit = true;

  {
    small_short x = -1;
    if ( x >= 0 ) {
      ShowMessage("datatype 'small_short' is unsigned; check gnushogi.h\n");
      return(1);
    }
  }

  n = sizeof(struct leaf) * (size_t)TREE;
  Tree = HEAP_ALLOC(n);
  if ( ! Tree ) {
    sprintf(buffer,"Cannot allocate %ld bytes for search tree",n);
    ShowMessage (buffer);
    return(1);
  } else {
#if defined DEBUG
    printf("Tree memory: %ld\n",(long)n); 
#endif
  }          

  n = sizeof(hashcode_array);
  hashcode = HEAP_ALLOC(n);
  if ( !hashcode ) {
    sprintf(buffer,"Cannot allocate %ld bytes for hashcode",n);
    ShowMessage(buffer);
    return(1);
  } else {
#if defined DEBUG
    printf("hashcode memory: %ld\n",(long)n); 
#endif
  }       

  n = sizeof(drop_hashcode_array);
  drop_hashcode = HEAP_ALLOC(n);
  if ( !drop_hashcode ) {
    sprintf(buffer,"Cannot allocate %ld bytes for drop_hashcode",n);
    ShowMessage(buffer);
    return(1);
  } else { 
#if defined DEBUG
    printf("drop_hashcode memory: %ld\n",(long)n); 
#endif                                             
  }

  n = sizeof(struct GameRec) * (size_t)(MAXMOVES + MAXDEPTH);
  GameList = HEAP_ALLOC(n);
  if ( !GameList ) {
    sprintf(buffer,"Cannot allocate %ld bytes for game record",n);
    ShowMessage(buffer);
    return(1);
  } else {
#ifdef DEBUG
    printf("GameList memory: %ld\n",(long)n); 
#endif
  }

#if !defined SAVE_NEXTPOS
  n = sizeof(next_array);
  for ( i=0; i<NO_PTYPE_PIECES; i++ ) {
    nextdir[i] = use_nextpos ? HEAP_ALLOC(n) : NULL;
    if ( !nextdir[i] ) {
      if ( use_nextpos ) {
        sprintf(buffer,"cannot allocate %ld space for nextdir %d",(long)(n),i);
        ShowMessage (buffer);
      }
      nextdir[i] = NULL;
      use_nextpos = false;
    }
    nextpos[i] = use_nextpos ? HEAP_ALLOC(n) : NULL;
    if ( !nextpos[i] ) {
      if ( use_nextpos ) {
        sprintf(buffer,"cannot allocate %ld space for nextpos %d",(long)(n),i);
        ShowMessage (buffer);
      }
      use_nextpos = false;
    }
  } 
  if ( !use_nextpos ) {
    return(1);
  } else {
#if defined DEBUG
    printf("nextdir+nextpos memory: %ld\n",(long)(n*2*NO_PTYPE_PIECES)); 
#endif 
  }
#endif

  n = sizeof(value_array);
  value = HEAP_ALLOC(n);
  if ( !value ) {
    ShowMessage("cannot allocate value space");
    return(1);
  } else {
#if defined DEBUG
    printf("value memory: %ld\n",(long)n); 
#endif
  }
  n = sizeof(fscore_array);
  fscore = HEAP_ALLOC(n);
  if ( !fscore ) {
    ShowMessage("cannot allocate fscore space");
    return(1);
  } else {
#if defined DEBUG
    printf("fscore memory: %ld\n",(long)n); 
#endif
  }

#if defined HISTORY
  n = sizeof_history;
  history = HEAP_ALLOC(n);
  if ( !history ) {
    sprintf(buffer,"Cannot allocate %ld bytes for history table",sizeof_history);
    ShowMessage(buffer);
    use_history = false;
  } else {
#if defined DEBUG
    printf("history memory: %ld\n",(long)n);
#endif      
  }
#endif

#if defined CACHE
  n = sizeof(struct etable) * (size_t)ETABLE;
  for ( i=0; i<2; i++ ) {
    etab[i] = use_etable ? HEAP_ALLOC(n) : 0;
    if ( !etab[i] ) {
      sprintf(buffer,"Cannot allocate %ld bytes for cache table i",n,i);
      ShowMessage (buffer);
      use_etable = false;
    }
  }
#if defined DEBUG
  if ( use_etable )
    printf("etab memory: %ld (etable=%ld ETABLE=%ld)\n",
      (long)(n*2),(long)sizeof(struct etable),(long)ETABLE); 
#endif
#endif

#if ttblsz

  if (rehash < 0)
    rehash = MAXrehash;
    
   n = sizeof(struct hashentry)*(ttblsize+rehash);
#ifdef DEBUG 
   printf("ttblsize = %ld rehash = %ld n = %ld\n",(long)ttblsize,(long)rehash,(long)n);
#endif
  while ( doit && ttblsize > MINTTABLE ) {
#ifdef DEBUG
    printf("try to allocate %d bytes for transposition table\n",(long)2*n);
#endif
    ttable[0] = HEAP_ALLOC(n);
    ttable[1] = ttable[0] ? HEAP_ALLOC(n) : NULL;
    if ( !ttable[0] || !ttable[1] ) {
      if ( !ttable[0] ) {
        HEAP_FREE(ttable[0]);
      }
      if ( !ttable[1] ) {
        HEAP_FREE(ttable[1]);
      }
      ttblsize = ttblsize >> 1;
      n = sizeof(struct hashentry)*(ttblsize+rehash);
    } else doit = false; 
  }
  if ( ttblsize <= MINTTABLE ) {
    use_ttable = false;        
  }
  if ( use_ttable ) {
#if defined DEBUG
    sprintf(buffer,"ttable's memory: %ld, ttblsize=%ld rehash=%ld",
		(long)2*n,(long)ttblsize,(long)rehash);
    ShowMessage(buffer);
#endif
    ttbllimit = ttblsize<<1 - ttblsize>>2;
#ifdef DEBUG_TTABLE
    printf("ttbllimit = %ld\n",(long)ttbllimit);
#endif
  } else {
    sprintf(buffer,"Cannot allocate %ld bytes for transposition table",(long)(2*n));
    ShowMessage (buffer);
    ttable[0] = ttable[1] = NULL;
  }
#endif /* ttblsz */

#if !defined SAVE_DISTDATA
  n = sizeof(distdata_array);
  distdata = HEAP_ALLOC(n);
  if ( !distdata )
    {
      ShowMessage("cannot allocate distdata space...");
      use_distdata = false;
    }
  else
    {
#if defined DEBUG
      printf("distdata memory: %ld\n",(long)n);
#endif
    }
#endif

#if !defined SAVE_PTYPE_DISTDATA
  n = sizeof(distdata_array);
  for ( i=0; i<NO_PTYPE_PIECES; i++ ) {
    ptype_distdata[i] = use_ptype_distdata ? HEAP_ALLOC(n) : 0;
    if ( !ptype_distdata[i] ) {
      sprintf(buffer,"cannot allocate %ld bytes for ptype_distdata %d...",(long)n,i);
      use_ptype_distdata = false;
    }
  }
#ifdef DEBUG
  if ( use_ptype_distdata ) {
    printf("ptype_distdata memory: %ld\n",(long)(n*NO_PTYPE_PIECES));
  }
#endif          
#endif

return(0);
}


#if defined EXTLANGFILE

                    

#ifdef OLDLANGFILE

void
InitConst (char *lang)
{
  FILE *constfile;
  char s[256];
  char sl[5];
  char buffer[120];
  int len, entry;
  char *p, *q;
  constfile = fopen (LANGFILE, "r");
  if (!constfile)
    {
      ShowMessage ("NO LANGFILE");
      exit (1);
    }
  while (fgets (s, sizeof (s), constfile))
    {
      if (s[0] == '!')
	continue;
      len = strlen (s);
      for (q = &s[len]; q > &s[8]; q--)
	if (*q == '}')
	  break;
      if (q == &s[8])
	{
	  ShowMessage("{ error in cinstfile");
	  exit (1);
	}
      *q = '\0';
      if (s[3] != ':' || s[7] != ':' || s[8] != '{')
	{
	  sprintf (buffer,"Langfile format error %s", s);
	  ShowMessage(buffer);
	  exit (1);
	}
      s[3] = s[7] = '\0';
      if (lang == NULL)
	{
	  lang = sl;
	  strcpy (sl, &s[4]);
	}
      if (strcmp (&s[4], lang))
	continue;
      entry = atoi (s);
      if (entry < 0 || entry >= CPSIZE)
	{
	  ShowMessage("Langfile number error");
	  exit (1);
	}
      for (q = p = &s[9]; *p; p++)
	{
	  if (*p != '\\')
	    {
	      *q++ = *p;
	    }
	  else if (*(p + 1) == 'n')
	    {
	      *q++ = '\n';
	      p++;
	    }
	}
      *q = '\0';
      if (entry < 0 || entry > 255)
	{
	  sprintf (buffer,"Langfile error %d\n", entry);
          ShowMessage(buffer);
	  exit (0);
	}
      CP[entry] = (char far *) GLOBAL_ALLOC ((unsigned) strlen (&s[9]) + 1);
      if (CP[entry] == NULL)
	{
	  char buffer[80];
	  sprintf(buffer,"CP MALLOC, entry %d",entry);
	  perror (buffer);
	  exit (0);
	}
      strcpy (CP[entry], &s[9]);

    }
  fclose (constfile);
}                    

#else

void
InitConst (char *lang)
{
  FILE *constfile;
  char s[256];
  char sl[5];
  char buffer[120];
  int len, entry;
  char *p, *q;
  constfile = fopen (LANGFILE, "r");
  if (!constfile)
    {
      ShowMessage ("NO LANGFILE");
      exit (1);
    }
  while (fgets (s, sizeof (s), constfile))
    {
      if (s[0] == '!')
	continue;
      len = strlen (s);
      if (len > 3 && s[3] == ':' || len > 7 && s[7] == ':' ) 
	{
	  ShowMessage("old Langfile error"); 
	  exit (1);
	}
      if (len <= 15)
	{
	  ShowMessage("length error in Langfile");
	  exit (1);
	}
      for (q = &s[len]; q > &s[15]; q--)
	if (*q == '"')
	  break;
      if (q == &s[15])
	{
	  ShowMessage("\" error in Langfile");
	  exit (1);
	}
      *q = '\0';
      if (s[6] != ':' || s[10] != ':' || s[15] != '"')
	{
	  sprintf (buffer,"Langfile format error %s", s);
	  ShowMessage(buffer);
	  exit (1);
	}
      s[6] = s[10] = '\0';
      if (lang == NULL)
	{
	  lang = sl;
	  strcpy (sl, &s[7]);
	}     
      if (strcmp (&s[7], lang))
	continue;
      entry = atoi (&s[3]);
      if (entry < 0 || entry >= CPSIZE)
	{
	  ShowMessage("Langfile number error");
	  exit (1);
	} 
      for (q = p = &s[16]; *p; p++)
	{
	  if (*p != '\\')
	    {
	      *q++ = *p;
	    }
	  else if (*(p + 1) == 'n')
	    {
	      *q++ = '\n';
	      p++;
	    }
	}
      *q = '\0';
      if (entry < 0 || entry > 255)
	{
	  sprintf (buffer,"Langfile error %d\n", entry);
          ShowMessage(buffer);
	  exit (0);
	}
      CP[entry] = (char far *) GLOBAL_ALLOC ((unsigned) strlen (&s[16]) + 1);
      if (CP[entry] == NULL)
	{
	  char buffer[80];
	  sprintf(buffer,"CP MALLOC, entry %d",entry);
	  perror (buffer);
	  exit (0);
	}
      strcpy (CP[entry], &s[16]);

    }
  fclose (constfile);
}                    

#endif

#endif


int
InitMain (void)
{
#if defined THINK_C
  gsrand (starttime = ((unsigned int) time ((time_t *) 0)));	/* init urand */
#else
  gsrand (starttime = ((unsigned int) time ((long *) 0)));	/* init urand */
#endif

#if ttblsz
  ttblsize = ttblsz;
  rehash = -1;
#endif /* ttblsz */      

  if ( Initialize_data() != 0 )
    return(1);

#if defined EXTLANGFILE
  InitConst (Lang);    
#endif

  strcpy(ColorStr[0],CP[118]);
  strcpy(ColorStr[1],CP[119]);

  XC = 0;
  MaxResponseTime = 0;

#if defined XSHOGI
  signal (SIGTERM, TerminateSearch);
#endif

#if defined XSHOGI
  TCflag = true;
  TCmoves = 40;
  TCminutes = 5;
  TCseconds = 0;
  TCadd = 0;
  OperatorTime = 0;
#else
  TCflag = false;
  OperatorTime = 0;
#endif
  
  Initialize ();
  Initialize_dist ();
  Initialize_eval ();
#if !defined SAVE_NEXTPOS
  Initialize_moves ();
#endif

  NewGame ();

  flag.easy = ahead;
  flag.hash = hash;
  if (xwin)
    xwndw = atoi (xwin);

#ifdef HASHFILE
  hashfile = NULL;
#endif

#if ttblsz
#ifdef HASHFILE
  hashfile = fopen (HASHFILE, RWA_ACC);
  if (hashfile)
    {
      fseek (hashfile, 0L, SEEK_END);
      filesz = ftell (hashfile) / sizeof (struct fileentry) - 1 - MAXrehash;
              hashmask = filesz>>1;
	      hashbase = hashmask+1;
    }               
#endif /* HASHFILE */
#endif /* ttblsz */

  savefile[0] = '\0';
  listfile[0] = '\0';

  return(0);

}


void
ExitMain (void)
{
#if ttblsz
#ifdef HASHFILE
  if (hashfile)
    fclose (hashfile);
#endif /* HASHFILE */
#endif /* ttblsz */

  ExitChess ();
}