aboutsummaryrefslogtreecommitdiff
path: root/engines/glk/alan2/main.cpp
blob: 7f1aa8da0525e3cc5e8ad295a74d6760d3387591 (plain)
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
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
/* ScummVM - Graphic Adventure Engine
 *
 * ScummVM is the legal property of its developers, whose names
 * are too numerous to list here. Please refer to the COPYRIGHT
 * file distributed with this source distribution.
 *
 * This program 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 2
 * of the License, or (at your option) any later version.
 *
 * This program 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 this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 */

#define V27COMPATIBLE

#include "glk/alan2/sysdep.h"

#include "glk/alan2/types.h"
#include "glk/alan2/main.h"

//#include <time.h>
#ifdef USE_READLINE
#include "glk/alan2/readline.h"
#endif

#ifdef HAVE_SHORT_FILENAMES
#include "glk/alan2/av.h"
#else
#include "glk/alan2/alan_version.h"
#endif

#include "glk/alan2/args.h"
#include "glk/alan2/parse.h"
#include "glk/alan2/inter.h"
#include "glk/alan2/rules.h"
#ifdef REVERSED
#include "glk/alan2/reverse.h"
#endif
#include "glk/alan2/debug.h"
#include "glk/alan2/stack.h"
#include "glk/alan2/exe.h"
#include "glk/alan2/term.h"

#ifdef GLK
#include "common/file.h"
#include "glk/alan2/alan2.h"
#include "glk/alan2/glkio.h"
#endif

namespace Glk {
namespace Alan2 {

/* PUBLIC DATA */

/* The Amachine memory */
Aword *memory;
//static AcdHdr dummyHeader;	/* Dummy to use until memory allocated */
AcdHdr *header;

int memTop;			    /* Top of load memory */

int conjWord;			/* First conjunction in dictonary, for ',' */


/* Amachine variables */
CurVars cur;

/* Amachine structures */
WrdElem *dict;			/* Dictionary pointer */
ActElem *acts;			/* Actor table pointer */
LocElem *locs;			/* Location table pointer */
VrbElem *vrbs;			/* Verb table pointer */
StxElem *stxs;			/* Syntax table pointer */
ObjElem *objs;			/* Object table pointer */
CntElem *cnts;			/* Container table pointer */
RulElem *ruls;			/* Rule table pointer */
EvtElem *evts;			/* Event table pointer */
MsgElem *msgs;			/* Message table pointer */
Aword *scores;			/* Score table pointer */
Aword *freq;			/* Cumulative character frequencies */

int dictsize;

Boolean verbose = FALSE;
Boolean errflg = TRUE;
Boolean trcflg = FALSE;
Boolean dbgflg = FALSE;
Boolean stpflg = FALSE;
Boolean logflg = FALSE;
Boolean statusflg = TRUE;
Boolean fail = FALSE;
Boolean anyOutput = FALSE;


/* The files and filenames */
const char *advnam;
Common::File *txtfil;
Common::WriteStream *logfil;


/* Screen formatting info */
int col, lin;
int paglen, pagwidth;

Boolean needsp = FALSE;
Boolean skipsp = FALSE;

/* Restart jump buffer */
//jmp_buf restart_label;


/* PRIVATE DATA */
//static jmp_buf jmpbuf;		/* Error return long jump buffer */



/*======================================================================

  terminate()

  Terminate the execution of the adventure, e.g. close windows,
  return buffers...

 */
void terminate(int code) {
#ifdef __amiga__
#ifdef AZTEC_C
#include <fcntl.h>
  extern struct _dev *_devtab;
  char buf[85];
  
  if (con) { /* Running from WB, created a console so kill it */
    /* Running from WB, so we created a console and
       hacked the Aztec C device table to use it for all I/O
       so now we need to make it close it (once!) */
    _devtab[1].fd = _devtab[2].fd = 0;
  } else
#else
  /* Geek Gadgets GCC */
#include <workbench/startup.h>
#include <clib/dos_protos.h>
#include <clib/intuition_protos.h>

  if (_WBenchMsg != NULL) {
    Close(window);
    if (_WBenchMsg->sm_ArgList != NULL)
      UnLock(CurrentDir(cd));
  } else
#endif
#endif
    newline();
  free(memory);
  if (logflg)
    fclose(logfil);

#ifdef __MWERKS__
  printf("Command-Q to close window.");
#endif

#ifdef GLK
  g_vm->glk_exit();
#else
  exit(code);
#endif
}

/*======================================================================

  usage()

  */
void usage() {
  printf("Usage:\n\n");
  printf("    %s [<switches>] <adventure>\n\n", PROGNAME);
  printf("where the possible optional switches are:\n");
#ifdef GLK
  g_vm->glk_set_style(style_Preformatted);
#endif
  printf("    -v    verbose mode\n");
  printf("    -l    log player commands and game output to a file\n");
  printf("    -i    ignore version and checksum errors\n");
  printf("    -n    no Status Line\n");
  printf("    -d    enter debug mode\n");
  printf("    -t    trace game execution\n");
  printf("    -s    single instruction trace\n");
#ifdef GLK
  g_vm->glk_set_style(style_Normal);
#endif
}


/*======================================================================

  syserr()

  Print a little text blaming the user for the system error.

 */
void syserr(const char *str) {
#ifdef GLK
	::error("%s", str);
#else
  output("$n$nAs you enter the twilight zone of Adventures, you stumble \
and fall to your knees. In front of you, you can vaguely see the outlines \
of an Adventure that never was.$n$nSYSTEM ERROR: ");
  output(str);
  output("$n$n");

  if (logflg)
    fclose(logfil);
  newline();

#ifdef __amiga__
#ifdef AZTEC_C
  {
    char buf[80];

    if (con) { /* Running from WB, wait for user ack. */
      printf("press RETURN to quit");
      gets(buf);
    }
  }
#endif
#endif

  terminate(0);
#endif
}


/*======================================================================

  error()

  Print an error message, force new player input and abort.

  */
void error(MsgKind msgno /* IN - The error message number */) {
  if (msgno != MSGMAX)
    prmsg(msgno);
  wrds[wrdidx] = EOF;		/* Force new player input */
  dscrstkp = 0;			/* Reset describe stack */
  
	//longjmp(jmpbuf,TRUE);
  ::error("Error occurred");
}


/*======================================================================

  statusline()

  Print the the status line on the top of the screen.

  */
void statusline() {
#ifdef GLK
  uint glkWidth;
  char line[100];
  int pcol = col;
  uint i;

  if (NULL == glkStatusWin)
    return;

  g_vm->glk_set_window(glkStatusWin);
  g_vm->glk_window_clear(glkStatusWin);
  g_vm->glk_window_get_size(glkStatusWin, &glkWidth, NULL);

  g_vm->glk_set_style(style_User1);
  for (i = 0; i < glkWidth; i++)
	  g_vm->glk_put_char(' ');

  col = 1;
  g_vm->glk_window_move_cursor(glkStatusWin, 1, 0);
needsp = FALSE;
  say(where(HERO));
  if (header->maxscore > 0)
    sprintf(line, "Score %d(%d)/%d moves", cur.score, (int)header->maxscore, cur.tick);
  else
    sprintf(line, "%d moves", cur.tick);
  g_vm->glk_window_move_cursor(glkStatusWin, glkWidth - col - strlen(line), 0);
  printf(line);
  needsp = FALSE;

  col = pcol;

  g_vm->glk_set_window(glkMainWin);
#else
#ifdef HAVE_ANSI
  char line[100];
  int i;
  int pcol = col;

  if (!statusflg) return;
  /* ansi_position(1,1); ansi_bold_on(); */
  printf("\x1b[1;1H");
  printf("\x1b[7m");
  col = 1;
  say(where(HERO));
  if (header->maxscore > 0)
    sprintf(line, "Score %ld(%ld)/%ld moves", cur.score, (int)header->maxscore, cur.tick);
  else
    sprintf(line, "%ld moves", cur.tick);
  for (i=0; i < pagwidth - col - strlen(line); i++) putchar(' ');
  printf(line);
  printf("\x1b[m");
  printf("\x1b[%d;1H", paglen);
  needsp = FALSE;

  col = pcol;
#endif
#endif
}


/*======================================================================

  logprint()

  Print some text and log it if logging is on.

 */
void logprint(char str[]) {
  printf(str);
  if (logflg)
    fprintf(logfil, "%s", str);
}


/*======================================================================

  newline()

  Make a newline, but check for screen full.

 */
void newline() {
#ifdef GLK
	g_vm->glk_put_char('\n');
#else
  char buf[256];
  
  col = 1;
  if (lin >= paglen - 1) {
    logprint("\n");
    needsp = FALSE;
    prmsg(M_MORE);
#ifdef USE_READLINE
    (void) readline(buf);
#else
    fgets(buf, 256, stdin);
#endif
    getPageSize();
    lin = 0;
  } else
    logprint("\n");
  
  lin++;
  needsp = FALSE;
#endif
}


/*======================================================================

  para()

  Make a new paragraph, i.e one empty line (one or two newlines).

 */
void para() {
  if (col != 1)
    newline();
  newline();
}


/*======================================================================

  clear()

  Clear the screen.

 */
void clear() {
#ifdef GLK
	g_vm->glk_window_clear(glkMainWin);
#else
#ifdef HAVE_ANSI
  if (!statusflg) return;
  printf("\x1b[2J");
  printf("\x1b[%d;1H", paglen);
#endif
#endif
}


/*======================================================================

  allocate()

  Safely allocate new memory.

*/
void *allocate(unsigned long len /* IN - Length to allocate */) {
  void *p = (void *)malloc((size_t)len);

  if (p == NULL)
    syserr("Out of memory.");

  return p;
}


/*----------------------------------------------------------------------

  just()

  Justify a string so that it wraps at end of screen.

 */
static void just(char str[]) {
#ifdef GLK
  logprint(str);
#else
  int i;
  char ch;
  
  if (col >= pagwidth && !skipsp)
    newline();

  while (strlen(str) > pagwidth - col) {
    i = pagwidth - col - 1;
    while (!isSpace(str[i]) && i > 0) /* First find wrap point */
      i--;
    if (i == 0 && col == 1)	/* If it doesn't fit at all */
      /* Wrap immediately after this word */
      while (!isSpace(str[i]) && str[i] != '\0')
	i++;
    if (i > 0) {		/* If it fits ... */
      ch = str[i];		/* Save space or NULL */
      str[i] = '\0';		/* Terminate string */
      logprint(str);		/* and print it */
      skipsp = FALSE;		/* If skipping, now we're done */
      str[i] = ch;		/* Restore character */
      /* Skip white after printed portion */
      for (str = &str[i]; isSpace(str[0]) && str[0] != '\0'; str++);
    }
    newline();			/* Then start a new line */
  }
  logprint(str);			/* Print tail */
  col = col + strlen(str);	/* Update column */
#endif
}


/*----------------------------------------------------------------------

  space()

  Output a space if needed.

 */
static void space() {
  if (skipsp)
    skipsp = FALSE;
  else {
    if (needsp) {
      logprint(" ");
      col++;
    }
  }
  needsp = FALSE;
}


/*----------------------------------------------------------------------

  sayparam()

  A parameter needs to be said, check for words the player used and use
  them if possible.

*/
static void sayparam(int p) {
  int i;

  for (i = 0; i <= p; i++)
    if (params[i].code == EOF)
      syserr("Nonexistent parameter referenced.");

  if (params[p].firstWord == EOF) /* Any words he used? */
    say(params[p].code);
  else				/* Yes, so use them... */
    for (i = params[p].firstWord; i <= params[p].lastWord; i++) {
      just((char *)addrTo(dict[wrds[i]].wrd));
      if (i < params[p].lastWord)
	just(" ");
    }
}


/*----------------------------------------------------------------------

  prsym()

  Print an expanded symbolic reference.

  N = newline
  I = indent on a new line
  P = new paragraph
  L = current location name
  O = current object -> first parameter!
  V = current verb
  A = current actor
  T = tabulation
  $ = no space needed after this
 */
static void prsym(
	char *str	/* IN - The string starting with '$' */
) {
  switch (toLower(str[1])) {
  case 'n':
    newline();
    needsp = FALSE;
    break;
  case 'i':
    newline();
    logprint("    ");
    col = 5;
    needsp = FALSE;
    break;
  case 'o':
    sayparam(0);
    needsp = TRUE;		/* We did print something non-white */
    break;
  case '1':
  case '2':
  case '3':
  case '4':
  case '5':
  case '6':
  case '7':
  case '8':
  case '9':
    sayparam(str[1]-'1');
    needsp = TRUE;		/* We did print something non-white */
    break;
  case 'l':
    say(cur.loc);
    needsp = TRUE;		/* We did print something non-white */
    break;
  case 'a':
    say(cur.act);
    needsp = TRUE;		/* We did print something non-white */
    break;
  case 'v':
    just((char *)addrTo(dict[vrbwrd].wrd));
    needsp = TRUE;		/* We did print something non-white */
    break;
  case 'p':
    para();
    needsp = FALSE;
    break;
  case 't': {
    int i;
    int spaces = 4-(col-1)%4;
    
    for (i = 0; i<spaces; i++) logprint(" ");
    col = col + spaces;
    needsp = FALSE;
    break;
  }
  case '$':
    skipsp = TRUE;
    break;
  default:
    logprint("$");
    break;
  }
}



/*======================================================================

  output()

  Output a string to suit the screen. Any symbolic inserts ('$') are
  recogniced and performed.

 */
void output(char original[]) {
  char ch;
  char *str, *copy;
  char *symptr;

  copy = strdup(original);
  str = copy;

  if (str[0] != '$' || str[1] != '$')
    space();			/* Output space if needed (& not inhibited) */

  while ((symptr = strchr(str, '$')) != (char *) NULL) {
    ch = *symptr;		/* Terminate before symbol */
    *symptr = '\0';
    if (strlen(str) > 0) {
      just(str);		/* Output part before '$' */
      if (str[strlen(str)-1] == ' ')
	needsp = FALSE;
    }
    *symptr = ch;		/* restore '$' */
    prsym(symptr);		/* Print the symbolic reference */
    str = &symptr[2];		/* Advance to after symbol and continue */
  }
  if (str[0] != 0) {
    just(str);			/* Output trailing part */
    skipsp = FALSE;
    if (str[strlen(str)-1] != ' ')
      needsp = TRUE;
  }
  anyOutput = TRUE;
  free(copy);
}


/*======================================================================

  prmsg()

  Print a message from the message table.
  
  */
void prmsg(MsgKind msg /* IN - message number */) {
  interpret(msgs[msg].stms);
}


/*----------------------------------------------------------------------*\

  Various check functions

  endOfTable()
  isObj, isLoc, isAct, IsCnt & isNum

\*----------------------------------------------------------------------*/

/* How to know we are at end of a table */
Boolean eot(Aword *adr) {
  return *adr == EOF;
}

Boolean isObj(Aword x) {
  return x >= OBJMIN && x <= OBJMAX;
}

Boolean isCnt(Aword x) {
  return (x >= CNTMIN && x <= CNTMAX) ||
    (isObj(x) && objs[x-OBJMIN].cont != 0) ||
    (isAct(x) && acts[x-ACTMIN].cont != 0);
}

Boolean isAct(Aword x) {
  return x >= ACTMIN && x <= ACTMAX;
}

Boolean isLoc(Aword x) {
  return x >= LOCMIN && x <= LOCMAX;
}

Boolean isNum(Aword x) {
  return x >= LITMIN && x <= LITMAX && litValues[x-LITMIN].type == TYPNUM;
}

Boolean isStr(Aword x) {
  return x >= LITMIN && x <= LITMAX && litValues[x-LITMIN].type == TYPSTR;
}

Boolean isLit(Aword x) {
  return x >= LITMIN && x <= LITMAX;
}


/*======================================================================

  exitto()

  Is there an exit from one location to another?

  */
Boolean exitto(int to, int from) {
  ExtElem *ext;

  if (locs[from-LOCMIN].exts == 0)
    return(FALSE); /* No exits */

  for (ext = (ExtElem *) addrTo(locs[from-LOCMIN].exts); !endOfTable(ext); ext++)
    if (ext->next == to)
      return(TRUE);

  return(FALSE);
}


#ifdef CHECKOBJ
/*======================================================================

  checkobj()

  Check that the object given is valid, else print an error message
  or find out what he wanted.

  This routine is not used any longer, kept for sentimental reasons ;-)

  */
void checkobj(obj)
     Aword *obj;
{
  Aword oldobj;
  
  if (*obj != EOF)
    return;
  
  oldobj = EOF;
  for (cur.obj = OBJMIN; cur.obj <= OBJMAX; cur.obj++) {
    /* If an object is present and it is possible to perform his action */
    if (isHere(cur.obj) && possible())
      if (oldobj == EOF)
	oldobj = cur.obj;
      else
	error(WANT);          /* And we didn't find multiple objects */
    }
  
  if (oldobj == EOF)
    error(WANT);              /* But we found ONE */
  
  *obj = cur.obj = oldobj;    
  output("($o)");             /* Then he surely meant this object */
}
#endif




/*----------------------------------------------------------------------
  count()

  Count the number of items in a container.

  */
static int count(int cnt /* IN - the container to count */) {
  int i, j = 0;
  
  for (i = OBJMIN; i <= OBJMAX; i++)
    if (in(i, cnt))
      /* Then it's in this container also */
      j++;
  return(j);
}


/*----------------------------------------------------------------------
  sumatr()

  Sum the values of one attribute in a container. Recursively.

  */
static int sumatr(
     Aword atr,			/* IN - the attribute to sum over */
     Aword cnt			/* IN - the container to sum */
) {
  int i;
  int sum = 0;

  for (i = OBJMIN; i <= OBJMAX; i++)
    if (objs[i-OBJMIN].loc == cnt) {	/* Then it's in this container */
      if (objs[i-OBJMIN].cont != 0)	/* This is also a container! */
	sum = sum + sumatr(atr, i);
      sum = sum + attribute(i, atr);
    }
  return(sum);
}


/*======================================================================
  checklim()

  Checks if a limit for a container is exceeded.

  */
Boolean checklim(
     Aword cnt,			/* IN - Container code */
     Aword obj			/* IN - The object to add */
) {
  LimElem *lim;
  Aword props;

  fail = TRUE;
  if (!isCnt(cnt))
    syserr("Checking limits for a non-container.");

  /* Find the container properties */
  if (isObj(cnt))
      props = objs[cnt-OBJMIN].cont;
  else if (isAct(cnt))
      props = acts[cnt-ACTMIN].cont;
  else
    props = cnt;

  if (cnts[props-CNTMIN].lims != 0) { /* Any limits at all? */
    for (lim = (LimElem *) addrTo(cnts[props-CNTMIN].lims); !endOfTable(lim); lim++)
      if (lim->atr == 0) {
	if (count(cnt) >= lim->val) {
	  interpret(lim->stms);
	  return(TRUE);		/* Limit check failed */
	}
      } else {
	if (sumatr(lim->atr, cnt) + attribute(obj, lim->atr) > lim->val) {
	  interpret(lim->stms);
	  return(TRUE);
	}
      }
  }
  fail = FALSE;
  return(FALSE);
}


/*----------------------------------------------------------------------*\

  Action routines

\*----------------------------------------------------------------------*/



/*----------------------------------------------------------------------
  trycheck()

  Tries a check, returns TRUE if it passed, FALSE else.

  */
static Boolean trycheck(
     Aaddr adr,			/* IN - ACODE address to check table */
     Boolean act		/* IN - Act if it fails ? */
) {
  ChkElem *chk;

  chk = (ChkElem *) addrTo(adr);
  if (chk->exp == 0) {
    interpret(chk->stms);
    return(FALSE);
  } else {
    while (!endOfTable(chk)) {
      interpret(chk->exp);
      if (!(Abool)pop()) {
	if (act)
	  interpret(chk->stms);
	return(FALSE);
      }
      chk++;
    }
    return(TRUE);
  }
}


/*======================================================================
  go()

  Move hero in a direction.

  */
void go(int dir) {
  ExtElem *ext;
  Boolean ok;
  Aword oldloc;

  ext = (ExtElem *) addrTo(locs[cur.loc-LOCMIN].exts);
  if (locs[cur.loc-LOCMIN].exts != 0)
    while (!endOfTable(ext)) {
      if (ext->code == dir) {
	ok = TRUE;
	if (ext->checks != 0) {
	  if (trcflg) {
	    printf("\n<EXIT %d (%s) from %d (", dir,
		   (char *)addrTo(dict[wrds[wrdidx-1]].wrd), cur.loc);
	    debugsay(cur.loc);
	    printf("), Checking:>\n");
	  }
	  ok = trycheck(ext->checks, TRUE);
	}
	if (ok) {
	  oldloc = cur.loc;
	  if (ext->action != 0) {
	    if (trcflg) {
	      printf("\n<EXIT %d (%s) from %d (", dir, 
		     (char *)addrTo(dict[wrds[wrdidx-1]].wrd), cur.loc);
	      debugsay(cur.loc);
	      printf("), Executing:>\n");
	    }	    
	    interpret(ext->action);
	  }
	  /* Still at the same place? */
	  if (where(HERO) == oldloc) {
	    if (trcflg) {
	      printf("\n<EXIT %d (%s) from %d (", dir, 
		     (char *)addrTo(dict[wrds[wrdidx-1]].wrd), cur.loc);
	      debugsay(cur.loc);
	      printf("), Moving:>\n");
	    }
	    locate(HERO, ext->next);
	  }
	}
	return;
      }
      ext++;
    }
  error(M_NO_WAY);
}


/*----------------------------------------------------------------------

  findalt()

  Find the verb alternative wanted in a verb list and return
  the address to it.

 */
static AltElem *findalt(
     Aword vrbsadr,		/* IN - Address to start of list */
     Aword param		/* IN - Which parameter to match */
) {
  VrbElem *vrb;
  AltElem *alt;

  if (vrbsadr == 0)
    return(NULL);

  for (vrb = (VrbElem *) addrTo(vrbsadr); !endOfTable(vrb); vrb++)
    if (vrb->code == cur.vrb) {
      for (alt = (AltElem *) addrTo(vrb->alts); !endOfTable(alt); alt++)
	if (alt->param == param || alt->param == 0)
	  return alt;
      return NULL;
    }
  return NULL;
}


/*======================================================================

  possible()

  Check if current action is possible according to the CHECKs.

  */
Boolean possible() {
  AltElem *alt[MAXPARAMS+2];	/* List of alt-pointers, one for each param */
  int i;			/* Parameter index */
  
  fail = FALSE;
  alt[0] = findalt(header->vrbs, 0);
  /* Perform global checks */
  if (alt[0] != 0 && alt[0]->checks != 0) {
    if (!trycheck(alt[0]->checks, FALSE)) return FALSE;
    if (fail) return FALSE;
  }
  
  /* Now CHECKs in this location */
  alt[1] = findalt(locs[cur.loc-LOCMIN].vrbs, 0);
  if (alt[1] != 0 && alt[1]->checks != 0)
    if (!trycheck(alt[1]->checks, FALSE))
      return FALSE;
  
  for (i = 0; params[i].code != EOF; i++) {
    alt[i+2] = findalt(objs[params[i].code-OBJMIN].vrbs, i+1);
    /* CHECKs in a possible parameter */
    if (alt[i+2] != 0 && alt[i+2]->checks != 0)
      if (!trycheck(alt[i+2]->checks, FALSE))
	return FALSE;
  }

  for (i = 0; i < 2 || params[i-2].code != EOF; i++)
    if (alt[i] != 0 && alt[i]->action != 0)
      break;
  if (i >= 2 && params[i-2].code == EOF)
    /* Didn't find any code for this verb/object combination */
    return FALSE;
  else
    return TRUE;
}


/*----------------------------------------------------------------------

  do_it()

  Execute the action commanded by hero.

  */
static void do_it() {
  AltElem *alt[MAXPARAMS+2];	/* List of alt-pointers, one for each param */
  Boolean done[MAXPARAMS+2];	/* Is it done */
  int i;			/* Parameter index */
  char trace[80];		/* Trace string buffer */
  
  fail = FALSE;
  alt[0] = findalt(header->vrbs, 0);
  /* Perform global checks */
  if (alt[0] != 0 && alt[0]->checks != 0) {
    if (trcflg)
      printf("\n<VERB %d, CHECK, GLOBAL:>\n", cur.vrb);
    if (!trycheck(alt[0]->checks, TRUE)) return;
    if (fail) return;
  }
  
  /* Now CHECKs in this location */
  alt[1] = findalt(locs[cur.loc-LOCMIN].vrbs, 0);
  if (alt[1] != 0 && alt[1]->checks != 0) {
    if (trcflg)
      printf("\n<VERB %d, CHECK, in LOCATION:>\n", cur.vrb);
    if (!trycheck(alt[1]->checks, TRUE)) return;
    if (fail) return;
  }
  
  for (i = 0; params[i].code != EOF; i++) {
    if (isLit(params[i].code))
      alt[i+2] = 0;
    else {
      if (isObj(params[i].code))
	alt[i+2] = findalt(objs[params[i].code-OBJMIN].vrbs, i+1);
      else if (isAct(params[i].code))
	alt[i+2] = findalt(acts[params[i].code-ACTMIN].vrbs, i+1);
      else
	syserr("Illegal parameter type.");
      /* CHECKs in the parameters */
      if (alt[i+2] != 0 && alt[i+2]->checks != 0) {
	if (trcflg)
	  printf("\n<VERB %d, CHECK, in Parameter #%d:>\n", cur.vrb, i);
	if (!trycheck(alt[i+2]->checks, TRUE)) return;
	if (fail) return;
      }
    }
  }

  /* Check for anything to execute... */
  for (i = 0; i < 2 || params[i-2].code != EOF; i++)
    if (alt[i] != 0 && alt[i]->action != 0)
      break;
  if (i >= 2 && params[i-2].code == EOF)
    /* Didn't find any code for this verb/object combination */
    error(M_CANT0);
  
  /* Perform actions! */
  
  /* First try any BEFORE or ONLY from outside in */
  done[0] = FALSE;
  done[1] = FALSE;
  for (i = 2; params[i-2].code != EOF; i++)
    done[i] = FALSE;
  i--;
  while (i >= 0) {
    if (alt[i] != 0)
      if (alt[i]->qual == (Aword)Q_BEFORE || alt[i]->qual == (Aword)Q_ONLY) {
	if (alt[i]->action != 0) {
	  if (trcflg) {
	    if (i == 0)
	      strcpy(trace, "GLOBAL");
	    else if (i == 1)
	      strcpy(trace, "in LOCATION");
	    else
	      sprintf(trace, "in PARAMETER %d", i-1);
	    if (alt[i]->qual == (Aword)Q_BEFORE)
	      printf("\n<VERB %d, %s (BEFORE), Body:>\n", cur.vrb, trace);
	    else
	      printf("\n<VERB %d, %s (ONLY), Body:>\n", cur.vrb, trace);
	  }
	  interpret(alt[i]->action);
	  if (fail) return;
	  if (alt[i]->qual == (Aword)Q_ONLY) return;
	}
	done[i] = TRUE;
      }
    i--;
  }
  
  /* Then execute any not declared as AFTER, i.e. the default */
  for (i = 0; i < 2 || params[i-2].code != EOF; i++) {
    if (alt[i] != 0)
      if (alt[i]->qual != (Aword)Q_AFTER) {
	if (!done[i] && alt[i]->action != 0) {
	  if (trcflg) {
	    if (i == 0)
	      strcpy(trace, "GLOBAL");
	    else if (i == 1)
	      strcpy(trace, "in LOCATION");
	    else
	      sprintf(trace, "in PARAMETER %d", i-1);
	    printf("\n<VERB %d, %s, Body:>\n", cur.vrb, trace);
	  }
	  interpret(alt[i]->action);
	  if (fail) return;
	}
	done[i] = TRUE;
      }
  }

  /* Finally, the ones declared as after */
  i--;
  while (i >= 0) {
    if (alt[i] != 0)
      if (!done[i] && alt[i]->action != 0) {
	if (trcflg) {
	  if (i == 0)
	    strcpy(trace, "GLOBAL");
	  else if (i == 1)
	    strcpy(trace, "in LOCATION");
	  else
	    sprintf(trace, "in PARAMETER %d", i-1);
	  printf("\n<VERB %d, %s (AFTER), Body:>\n", cur.vrb, trace);
	}
	interpret(alt[i]->action);
	if (fail) return;
      }
    i--;
  }
}


/*======================================================================

  action()

  Execute all activities commanded. Handles possible multiple actions
  such as THEM or lists of objects.

  */
void action(ParamElem plst[] /* IN - Plural parameter list */) {
  int i, mpos;
  char marker[10];

  if (plural) {
    /*
       The code == 0 means this is a multiple position. We must loop
       over this position (and replace it by each present in the plst)
     */
    for (mpos = 0; params[mpos].code != 0; mpos++); /* Find multiple position */
    sprintf(marker, "($%d)", mpos+1); /* Prepare a printout with $1/2/3 */
    for (i = 0; plst[i].code != EOF; i++) {
      params[mpos] = plst[i];
      output(marker);
      do_it();
      if (plst[i+1].code != EOF)
        para();
    }
    params[mpos].code = 0;
  } else
    do_it();
}


/*----------------------------------------------------------------------*\

  Event Handling

  eventchk()

\*----------------------------------------------------------------------*/


/*----------------------------------------------------------------------
  eventchk()

  Check if any events are pending. If so execute them.
  */
static void eventchk() {
  while (etop != 0 && eventq[etop-1].time == cur.tick) {
    etop--;
    if (isLoc(eventq[etop].where))
      cur.loc = eventq[etop].where;
    else
      cur.loc = where(eventq[etop].where);
    if (trcflg) {
      printf("\n<EVENT %d (at ", eventq[etop].event);
      debugsay(cur.loc);
      printf("):>\n");
    }
    interpret(evts[eventq[etop].event-EVTMIN].code);
  }
}


/*----------------------------------------------------------------------*\

  Main program and initialisation

  codfil
  filenames

  checkvers()
  load()
  checkdebug()
  initheader()
  initstrings()
  start()
  init()
  main()

\*----------------------------------------------------------------------*/


Common::SeekableReadStream *codfil;
char codfnm[256];
static char txtfnm[256];
static char logfnm[256];


/*----------------------------------------------------------------------

  checkvers()

 */
static void checkvers(AcdHdr *header) {
  char vers[4];
  char state[2];

  /* Construct our own version */
  vers[0] = alan.version.version;
  vers[1] = alan.version.revision;

  /* Check version of .ACD file */
  if (dbgflg) {
    state[0] = header->vers[3];
    state[1] = '\0';
    printf("<Version of '%s' is %d.%d(%d)%s>",
	   advnam,
	   (int)(header->vers[0]),
	   (int)(header->vers[1]),
	   (int)(header->vers[2]),
	   (header->vers[3])==0? "": state);
    newline();
  }

  /* Compatible if version and revision match... */
  if (strncmp(header->vers, vers, 2) != 0) {
#ifdef V25COMPATIBLE
    if (header->vers[0] == 2 && header->vers[1] == 5) /* Check for 2.5 version */
      /* This we can convert later if needed... */;
    else
#endif
#ifdef V27COMPATIBLE
    if (header->vers[0] == 2 && header->vers[1] == 7) /* Check for 2.7 version */
      /* This we can convert later if needed... */;
    else
#endif
      if (errflg) {
	char str[80];
	sprintf(str, "Incompatible version of ACODE program. Game is %ld.%ld, interpreter %ld.%ld.",
		(long) (header->vers[0]),
		(long) (header->vers[1]),
		(long) alan.version.version,
		(long) alan.version.revision);
	syserr(str);
      } else
	output("<WARNING! Incompatible version of ACODE program.>\n");
  }
}


/*----------------------------------------------------------------------

  load()

 */
static void load() {
  AcdHdr tmphdr;
  Aword crc = 0;
  int i;
  char err[100];

  Aword *ptr = (Aword *)&tmphdr + 1;
  codfil->seek(0);
  codfil->read(&tmphdr.vers[0], 4);
  for (i = 1; i < sizeof(tmphdr) / sizeof(Aword); ++i, ++ptr)
	  *ptr = codfil->readUint32BE();
  checkvers(&tmphdr);

  /* Allocate and load memory */

  /* No memory allocated yet? */
  if (memory == NULL) {
#ifdef V25COMPATIBLE
    if (tmphdr.vers[0] == 2 && tmphdr.vers[1] == 5)
      /* We need some more memory to expand 2.5 format*/
      memory = allocate((tmphdr.size+tmphdr.objmax-tmphdr.objmin+1+2)*sizeof(Aword));
    else
#endif
      memory = (Aword *)allocate(tmphdr.size * sizeof(Aword));
  }
  memTop = tmphdr.size;
  header = (AcdHdr *) addrTo(0);

  if ((tmphdr.size * sizeof(Aword)) > codfil->size())
	  ::error("Header size is greater than filesize");

  codfil->seek(0);
  codfil->read(&header->vers[0], 4);
  for (i = 1, ptr = memory + 1; i < tmphdr.size; ++i, ++ptr)
	  *ptr = codfil->readUint32LE();

  /* Calculate checksum */
  for (i = sizeof(tmphdr)/sizeof(Aword); i < memTop; i++) {
    crc += memory[i]&0xff;
    crc += (memory[i]>>8)&0xff;
    crc += (memory[i]>>16)&0xff;
    crc += (memory[i]>>24)&0xff;
#ifdef CRCLOG
    printf("%6x\t%6lx\t%6lx\n", i, crc, memory[i]);
#endif
  }
  if (crc != tmphdr.acdcrc) {
    sprintf(err, "Checksum error in .ACD file (0x%lx instead of 0x%lx).",
	    (unsigned long) crc, (unsigned long) tmphdr.acdcrc);
    if (errflg)
      syserr(err);
    else {
      output("<WARNING! $$");
      output(err);
      output("$$ Ignored, proceed at your own risk.>$n");
    }
  }

#if defined(SCUMM_LITTLE_ENDIAN)
  if (dbgflg||trcflg||stpflg)
    output("<Hmm, this is a little-endian machine, fixing byte ordering....");
  reverseACD(tmphdr.vers[0] == 2 && tmphdr.vers[1] == 5); /* Reverse all words in the ACD file */
  if (dbgflg||trcflg||stpflg)
    output("OK.>$n");
#endif

#ifdef V25COMPATIBLE
  /* Check for 2.5 version */
  if (tmphdr.vers[0] == 2 && tmphdr.vers[1] == 5) {
    if (dbgflg||trcflg||stpflg)
      output("<Hmm, this is a v2.5 game, please wait while I convert it...");
    c25to26ACD();
    if (dbgflg||trcflg||stpflg)
      output("OK.>$n");
  }
#endif

}


/*----------------------------------------------------------------------

  checkdebug()

 */
static void checkdebug() {
  /* Make sure he can't debug if not allowed! */
  if (!header->debug) {
    if (dbgflg|trcflg|stpflg)
      printf("<Sorry, '%s' is not compiled for debug!>\n", advnam);
    para();
    dbgflg = FALSE;
    trcflg = FALSE;
    stpflg = FALSE;
  }

#ifndef GLK
  if (dbgflg)			/* If debugging */
    srand(0);			/* use no randomization */
  else
    srand(time(0));		/* seed random generator */
#endif
}


/*----------------------------------------------------------------------

  initheader()

 */
static void initheader() {
  dict = (WrdElem *) addrTo(header->dict);
  /* Find out number of entries in dictionary */
  for (dictsize = 0; !endOfTable(&dict[dictsize]); dictsize++);
  vrbs = (VrbElem *) addrTo(header->vrbs);
  stxs = (StxElem *) addrTo(header->stxs);
  locs = (LocElem *) addrTo(header->locs);
  acts = (ActElem *) addrTo(header->acts);
  objs = (ObjElem *) addrTo(header->objs);
  evts = (EvtElem *) addrTo(header->evts);
  cnts = (CntElem *) addrTo(header->cnts);
  ruls = (RulElem *) addrTo(header->ruls);
  msgs = (MsgElem *) addrTo(header->msgs);
  scores = (Aword *) addrTo(header->scores);

  if (header->pack)
    freq = (Aword *) addrTo(header->freq);
}


/*----------------------------------------------------------------------

  initstrings()

  */
static void initstrings() {
  IniElem *init;

  for (init = (IniElem *) addrTo(header->init); !endOfTable(init); init++) {
    getstr(init->fpos, init->len);
    memory[init->adr] = pop();
  }
}


/*----------------------------------------------------------------------

  start()

 */
static void start() {
  int startloc;

  cur.tick = -1;
  cur.loc = startloc = where(HERO);
  cur.act = HERO;
  cur.score = 0;
  if (trcflg)
    printf("\n<START:>\n");
  interpret(header->start);
  para();

  acts[HERO-ACTMIN].loc = 0;
  locate(HERO, startloc);
}



/*----------------------------------------------------------------------
  init()

  Initialization, program load etc.

  */
static void init() {
  int i;

  /* Initialise some status */
  etop = 0;			/* No pending events */
  looking = FALSE;		/* Not looking now */
  dscrstkp = 0;			/* No describe in progress */

  load();

  initheader();
  checkdebug();

  /* Initialise string attributes */
  initstrings();

  getPageSize();

  /* Find first conjunction and use that for ',' handling */
  for (i = 0; i < dictsize; i++)
    if (isConj(i)) {
      conjWord = i;
      break;
    }

  /* Start the adventure */
  clear();
  start();
}



/*----------------------------------------------------------------------
  movactor()

  Let the current actor move. If player, ask him.

 */
static void movactor() {
  ScrElem *scr;
  StepElem *step;
  ActElem *act = (ActElem *) &acts[cur.act-ACTMIN];

  cur.loc = where(cur.act);
  if (cur.act == HERO) {
    parse();
	if (g_vm->shouldQuit())
		return;
	fail = FALSE;			/* fail only aborts one actor */
    rules();
  } else if (act->script != 0) {
    for (scr = (ScrElem *) addrTo(act->scradr); !endOfTable(scr); scr++)
      if (scr->code == act->script) {
	/* Find correct step in the list by indexing */
	step = (StepElem *) addrTo(scr->steps);
	step = (StepElem *) &step[act->step];
	/* Now execute it, maybe. First check wait count */
	if (step->after > act->count) {
	  /* Wait some more */
	  if (trcflg) {
	    printf("\n<ACTOR %d, ", cur.act);
	    debugsay(cur.act);
	    printf(" (at ");
	    debugsay(cur.loc);
	    printf("), SCRIPT %ld, STEP %ld, Waiting %ld more>\n",
		   act->script, act->step+1, step->after-act->count);
	  }
	  act->count++;
	  rules();
	  return;
	} else
	  act->count = 0;
	/* Then check possible expression */
	if (step->exp != 0) {
	  if (trcflg) {
	    printf("\n<ACTOR %d, ", cur.act);
	    debugsay(cur.act);
	    printf(" (at ");
	    debugsay(cur.loc);
	    printf("), SCRIPT %ld, STEP %ld, Evaluating:>\n",
		   act->script, act->step+1);
	  }
	  interpret(step->exp);
	  if (!(Abool)pop()) {
	    rules();
	    return; /* Hadn't happened yet */
	  }
	}
	/* OK, so finally let him do his thing */
	act->step++;		/* Increment step number before executing... */
	if (trcflg) {
	  printf("\n<ACTOR %d, ", cur.act);
	  debugsay(cur.act);
	  printf(" (at ");
	  debugsay(cur.loc);
	  printf("), SCRIPT %ld, STEP %ld, Executing:>\n",
		 act->script, act->step);
	}
	interpret(step->stm);
	step++;
	/* ... so that we can see if he is USEing another script now */
	if (act->step != 0 && endOfTable(step))
	  /* No more steps in this script, so stop him */
	  act->script = 0;
	fail = FALSE;			/* fail only aborts one actor */
	rules();
	return;
      }
    syserr("Unknown actor script.");
  } else if (trcflg) {
    printf("\n<ACTOR %d, ", cur.act);
    debugsay(cur.act);
    printf(" (at ");
    debugsay(cur.loc);
    printf("), Idle>\n");
    rules();
    return;
  }
}

/*----------------------------------------------------------------------

  openFiles()

  Open the necessary files.

  */
static void openFiles() {
  char str[256];
  char *usr = "";
  time_t tick;

#ifndef GLK
  /* Open Acode file */
  strcpy(codfnm, advnam);
  strcat(codfnm, ".acd");

  if ((codfil = fopen(codfnm, READ_MODE)) == NULL) {
    strcpy(str, "Can't open adventure code file '");
    strcat(str, codfnm);
    strcat(str, "'.");
    syserr(str);
  }
#endif

#ifdef GARGLK
	{
		char *s = strrchr(codfnm, '\\');
		if (!s) s = strrchr(codfnm, '/');
		g_vm->garglk_set_story_name(s ? s + 1 : codfnm);
	}
#endif

	/* Open Text file */
	strcpy(txtfnm, advnam);
	strcat(txtfnm, ".dat");
  
	Common::File *f = new Common::File();
	if (!f->open(txtfnm)) {
		delete f;
		Common::String s = Common::String::format("Can't open adventure text data file '%s'.", txtfnm);
		::error(s.c_str());
	}

	// If logging open log file
	if (logflg) {
		sprintf(logfnm, "%s.log", advnam);
		logfil = g_system->getSavefileManager()->openForSaving(logfnm);

		logflg = logfil != nullptr;
	}
}
    

/*======================================================================

  run()

  Run the adventure

  */
void run() {
	openFiles();

	// Set default line and column
	col = lin = 1;

	//setjmp(restart_label);	/* Return here if he wanted to restart */

	init();			/* Load, initialise and start the adventure */

	while (TRUE) {
#ifdef MALLOC
		if (malloc_verify() == 0) syserr("Error in heap.");
#endif
		if (dbgflg)
			debug();

		eventchk();
		cur.tick++;
		//    (void) setjmp(jmpbuf);

		// Move all characters
		for (cur.act = ACTMIN; cur.act <= ACTMAX; cur.act++) {
			movactor();
			if (g_vm->shouldQuit())
				return;
		}
	}
}

} // End of namespace Alan2
} // End of namespace Glk