File: TextRider.Mod

package info (click to toggle)
oo2c32 1.5.0-1
  • links: PTS
  • area: main
  • in suites: potato
  • size: 8,748 kB
  • ctags: 5,415
  • sloc: ansic: 95,007; sh: 473; makefile: 344; perl: 57; lisp: 21
file content (1617 lines) | stat: -rw-r--r-- 47,622 bytes parent folder | download | duplicates (2)
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
(*	$Id: TextRider.Mod,v 1.27 1999/11/14 17:56:17 ooc-devel Exp $	*)
MODULE TextRider [OOC_EXTENSIONS];

(*
    TextRider -  Text-based input/output of Oberon variables.       
    Copyright (C) 1998, 1999  Michael van Acken
    Copyright (C) 1997  Michael Griebling
 
    This module is free software; you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as 
    published by the Free Software Foundation; either version 2 of the
    License, or (at your option) any later version.
 
    This module 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 Lesser General Public License for more details.
 
    You should have received a copy of the GNU Lesser General Public
    License along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

*)

IMPORT
  Ascii, Channel, CharClass, Strings, LRealStr, RealStr, IntStr, 
  LRealConv, ConvTypes, Msg;

CONST
  done* = Channel.done;
  invalidFormat* = Channel.invalidFormat;
  valueOutOfRange* = 1;

  (* Scanner types *)
  undefined*=-1;
  char*=0; string*=1; int*=2; real*=3; bool*=4; set*=5;
  tab*=6; line*=7; ident*=8; error*=9; invalid*=10;
  
  (* Writer options *)
  noBuffering*=0;        (* when set output is not buffered.  This allows
                            interactive output prompts to appear as soon as
                            they are written *)

  (* Reader/Scanner options *)
  returnCtrlChars*=0;    (* when set returns EOL & TAB characters; otherwise
                            they are treated like whitespace *)
                           
  (* additional Scanner options *)
  interpretBools*=1;     (* when set returns truth values of the strings "TRUE"
                            and "FALSE"; otherwise returns the strings *)
  interpretSets*=2;      (* when set returns a set value of the string set
                            representation; otherwise returns the brace and
                            comma characters, and the numbers individually *)
  interpretStrings*=3;   (* when set returns a complete string contained
                            within open and closing quotes; otherwise returns
                            the quote characters and string contents as
                            separate tokens. *)
  useSignedNumbers*=4;   (* when set returns a complete signed number;
                            otherwise returns the sign characters and the
                            number tokens separately. *)
                            
  defReaderOptions*  = {};
  defWriterOptions*  = {};
  defScannerOptions* = defReaderOptions + {interpretBools..useSignedNumbers};

CONST
  maxLengthEol* = 2; (* system dependent, >= 2 *)
  maxLookahead = 2;  (* must be >= maxLengthEol and >=2 *)
  
TYPE
  Reader* = POINTER TO ReaderDesc;
  ReaderDesc* = RECORD
    res*: Msg.Msg;       (* READ-ONLY *)
    opt-: SET;                  (* current reader options (see above) *)
    byteReader-: Channel.Reader;(* only to be used by extensions of Reader *)
    base-: Channel.Channel;
    
    (* the end of line marker may contain the character 0X, which means its
       length must be stored in a separate field; the eol marker cannot be 
       empty, and it is required to contain control characters with an 
       ASCII code in 00X..1FX  *)
    eol-: ARRAY maxLengthEol OF CHAR;
      (* character sequence of end of line marker; all chars < 20X *)
    eolLen-: INTEGER;
      (* number of characters in `eol'; -1 means auto detect (the default) *)
    deferredEol: BOOLEAN;        (* TRUE iff eol detection is progress *)
    
    (* la: small buffer of characters, used to "peek" to the following
         characters in the input stream; managed as a FIFO 
       laRes: result `res' of read operation for corresponding character of
         `lookahead'
       laLen: number of characters in the lookahead FIFO
         invariant: 0 <= laLen < maxLookahead  *)
    la: ARRAY maxLookahead OF CHAR;
    laRes: ARRAY maxLookahead OF Msg.Msg;
    laLen: INTEGER;
  END;

  Writer* = POINTER TO WriterDesc;
  WriterDesc* = RECORD 
    res*: Msg.Msg;       (* READ-ONLY *)
    opt-: SET;                  (* current writer options (see above) *)
    byteWriter-: Channel.Writer;(* only to be used by extensions of Writer *)
    base-: Channel.Channel;
    
    eol: ARRAY maxLengthEol OF CHAR;
      (* character sequence of end of line marker *)
    eolLen: INTEGER;            (* number of characters in `eol' *)
  END;

  String* = ARRAY 256 OF CHAR;
  Scanner* = POINTER TO ScannerDesc;
  ScannerDesc* = RECORD
    res*: Msg.Msg;       (* READ-ONLY *)
    r-: Reader;      (* attached reader; exported only for extensions of Scanner *)
    base-: Channel.Channel;
    opt-: SET;       (* current scanner options (see above) *)
    type-: INTEGER;  (* scanned token type (see above) *)
    pos-: LONGINT;   (* position of current token in the channel *) 
    lines-: LONGINT; (* total of scanner eol markers; starts at 0 *)
    int-: LONGINT;   (* integer from channel *)
    real-: LONGREAL; (* real from channel *)
    char-: CHAR;     (* char from channel *)
    string-: String; (* string from channel *)
    set-: SET;       (* set from channel *)
    bool-: BOOLEAN;  (* boolean from channel *)
  END;



(*
> > Btw: I did _not_ fix the potential string buffer overruns in ReadLReal
> > and Scanner.ReadNum.
> 
> What should we do about this?  Make it POINTER TO ARRAY OF CHAR?  Or ADT
> Lib's dynamic String type?

IMO, the correct way to do this is to have the procedures accept
strings of arbitrary length, and return the nearest LONGREAL value in
any case.  The trick is to discard stuff like leading zeroes, cutoff
digits beyond the maximum number of significant digits, and to detect
overflows just by counting digits.  With these techniques and
MAX(LONGREAL) < 2E308, one could store any valid read number in a
buffer of 330 characters, and detect overflows and underflows for
longer real strings "by hand".  I implemented something similar for
integers, but it is a little bit more complex for reals.  Right now I
only signal "valueOutOfRange" if the real string is longer than 1023
characters, although I do scan to the end of the number before
reporting this.
*)



TYPE
  ErrorContext = POINTER TO ErrorContextDesc;
  ErrorContextDesc* = RECORD
     (* this record is exported, so that extensions of Channel can access the
        error descriptions by extending `ErrorContextDesc' *)
    (Msg.ContextDesc)
  END;


VAR
  errorContext: ErrorContext;

PROCEDURE GetError (code: Msg.Code): Msg.Msg;
  BEGIN
    RETURN Msg.New (errorContext, code)
  END GetError;

PROCEDURE (context: ErrorContext) GetTemplate* (msg: Msg.Msg; VAR templ: Msg.LString);
  VAR
    str: ARRAY 128 OF CHAR;
  BEGIN
    CASE msg. code OF
    | valueOutOfRange: str := "Number exceeded limits or string was too long"
    ELSE
      context. GetTemplate^ (msg, templ)
    END;
    COPY (str, templ)
  END GetTemplate;



(* Reader methods 
   ------------------------------------------------------------------------ *)

PROCEDURE EolDetect (r: Reader; ch: CHAR);
(* pre: (r. eolLen < 0) & 
        (r. deferredEol OR (ch = Ascii.lf) OR (ch = Ascii.cr)) *)
  BEGIN
    IF (r. res = done) THEN
      IF r. deferredEol THEN  (* previous character was Ascii.cr *)
        IF (ch = Ascii.lf) THEN  (* eol sequence is cr+lf *)
          r. eol[1] := ch;
          r. eolLen := 2
        ELSE  (* eol is just cr *)
          r. eolLen := 1
        END;
        r. deferredEol := FALSE
      ELSE
        r. eol[0] := ch;
        IF (ch = Ascii.lf) THEN  (* eol is just lf *)
          r. eolLen := 1
        ELSE  (* (ch = Ascii.cr) *)
          r. deferredEol := TRUE
        END
      END
    END
  END EolDetect;

PROCEDURE Lookahead (r: Reader; len: INTEGER): BOOLEAN;
(* Tries to read `len' characters past the current position from the input
   stream.  Characters present in the lookahead FIFO are taken into account.
   After successful completion, `len' characters or more are available in
   the lookahead FIFO and result is TRUE.  Less than `len' characters
   may be available if the operation is aborted due to a read error.  In this
   case result is FALSE.  
   pre: (len >= 1) & (r.res = done) & (len <= maxLookahead) 
   post: (r.res = done)  *)
  VAR
    ch: CHAR;
  BEGIN
    ASSERT (r. res = done);
    IF (r. laLen = 0) OR (r. laRes[r. laLen-1] = done) THEN
      WHILE (r. laLen < len) & (r. byteReader. res = done) DO
        r. byteReader. ReadByte (ch);

        IF (r. eolLen < 0) & 
           (r. deferredEol OR (ch = Ascii.lf) OR (ch = Ascii.cr)) THEN
          EolDetect (r,  ch)
        END;

        r. la[r. laLen] := ch;
        r. laRes[r. laLen] := r. byteReader. res;
        INC (r. laLen)
      END
    END;
    RETURN (len <= r. laLen) & (r. laRes[len-1] = done)
  END Lookahead;

PROCEDURE Consume (r: Reader): CHAR;
(* note: it is safe to call this procedure with `r.res#done'
   post: r.res holds the result code for the returned character *)
  VAR
    ch: CHAR;
    i: INTEGER;
  BEGIN
    IF (r. res = done) THEN
      IF (r. laLen > 0) THEN
        ch := r. la[0];
        r. res := r. laRes[0];
        FOR i := 1 TO r. laLen-1 DO
          r. la[i-1] := r. la[i];
          r. laRes[i-1] := r. laRes[i]
        END;
        DEC (r. laLen)
      ELSE
        r. byteReader. ReadByte (ch);

        IF (r. byteReader. res # done) THEN
          r. res := r. byteReader. res;
          ch := 0X
        ELSIF (r. eolLen < 0) & 
              (r. deferredEol OR (ch = Ascii.lf) OR (ch = Ascii.cr)) THEN
          EolDetect (r, ch)
        END
      END
    ELSE
      ch := 0X
    END;
    RETURN ch
  END Consume;



(* The following methods read a value of the given type from the current
   position in the TextReader. Iff the value is invalid for its type, 
   'r.Res' returns 'invalidFormat'.
  *)
  
PROCEDURE (r: Reader) Pos* () : LONGINT;
  BEGIN
    RETURN r.byteReader.Pos()-r. laLen
  END Pos;

PROCEDURE (r: Reader) ClearError*;
  BEGIN
    r. byteReader. ClearError;
    r. res := done;
    r. deferredEol := FALSE
  END ClearError;

PROCEDURE (r: Reader) Available* () : LONGINT;
  VAR
    avail, laChars: LONGINT;
  BEGIN
    avail := r. byteReader. Available();
    laChars := 0;
    WHILE (laChars # r. laLen) & (r. laRes[laChars] = done) DO
      INC (laChars)
    END;
    IF (avail < 0) & (laChars > 0) THEN
      RETURN laChars
    ELSE
      RETURN avail+laChars
    END
  END Available;

PROCEDURE (r: Reader) SetPos* (newPos: LONGINT);
  BEGIN
    IF (r. res = done) THEN
      r. byteReader. SetPos(newPos);
      r. laLen := 0;                     (* lookahead characters not valid *)
      r. deferredEol := FALSE;           (* interrupt any eol detection *)
      r. res := r. byteReader. res
    END
  END SetPos;

PROCEDURE (r: Reader) SetOpts* (opts: SET);
(* Set the reader options `r.opt' which are defined above. *)
  BEGIN
    r.opt:=opts
  END SetOpts;

PROCEDURE (r: Reader) SetEol* (marker: ARRAY OF CHAR; markerLen: INTEGER);
(* Sets new end of line marker.  If the passed string marker does not fit into
   the field `eol', or it does contain a character >= " ", then 
   `r.Res()' is set to `invalidFormat'. 
   
   A marker length `markerLen=-1' enables auto detection of the end-of-line
   convention used by the channel.  The channel is required to use one of the
   following eol markers:
     LF      used by Unix
     CR      used by MacOS
     CR/LF   used by MS-DOS and Windows
     
   Enabling auto detection introduces a (small) inconsistency: if the first 
   line of the channel ends with a <CR>, then skipping over the complete eol 
   marker of this line is not done at once iff the next character is a <LF>. 
   All reading procedures except for `ReadChar' will automatically skip the
   spurious <LF>.
   
   Example: 
     Input is "line1<CR><LF>line2".
     The first ReadLine leaves the reading position between <CR> and <LF>,
     and a second ReadLine skips automagically the <LF> and returns "line2".
     But if the second operation is a ReadChar, it will return <LF>, not
     "l".
     
   The reason for this is that ReadChar is the only operation that can look
   at parts of an multi-byte end-of-line marker, while such a marker is an 
   atomic entity for all other read operations if the channel is read 
   sequentially.
   
   pre: (r.Res() = done) & 
        ((markerLen = -1) OR (1 <= markerLen < LEN (marker))) &
        (markerLen <= maxLengthEol) & (for all i: marker[i] < 20X) *)
  VAR
    i: INTEGER;
  BEGIN
    IF (r. res = done) THEN
      IF (markerLen < 1) & (markerLen # -1) OR (markerLen > maxLengthEol) THEN
        r. res := GetError (invalidFormat)
      ELSE
        FOR i := 0 TO markerLen-1 DO
          IF (marker[i] >= 20X) THEN
            r. res := GetError (invalidFormat)
          END;
          r. eol[i] := marker[i]
        END;
        r. eolLen := markerLen
      END
    END
  END SetEol;

PROCEDURE (r: Reader) ReadChar* (VAR ch: CHAR);
(* Read a character.  NOTE: no new characters will be read
   if an error has occurred. *)
  BEGIN
    ch := Consume (r)
  END ReadChar;
  
PROCEDURE (r: Reader) Eol*(): BOOLEAN;
(* Return TRUE if the character at the current position is the system-dependent
   end-of-line character sequence or the last character has been read.  
   If `r.res # done', then result is TRUE.  *)
  VAR
    i: INTEGER;
  BEGIN
    IF (r. res = done) THEN
      IF (r. eolLen > 0) THEN
        FOR i := 0 TO r. eolLen-1 DO
          IF Lookahead (r, i+1) THEN
            IF (r. la[i] # r. eol[i]) THEN
              RETURN FALSE
            END
          ELSE
            RETURN (r. laLen = 1)
          END
        END;
        RETURN TRUE
      ELSIF Lookahead (r, 1) THEN
        IF (r. eolLen > 0) THEN
          RETURN r. Eol()  (* the extra lookahead solved our problem *)
        ELSE  (* here holds: `r.la[0] # Ascii.lf' *)
          RETURN (r. la[0] = Ascii.cr)
        END
      ELSE
        RETURN TRUE  (* low-level error for next character *)
      END
    ELSE
      RETURN TRUE
    END
  END Eol;
 
PROCEDURE SkipBlanks (r: Reader);
  VAR
    ch: CHAR;
  BEGIN
    (* note: Ascii.lf must be a whitespace character, or with eol auto 
       detection a ReadFoo procedure may find a spurious Ascii.lf in its 
       input that it should never have seen *)
    IF (r. res = done) THEN
      IF (returnCtrlChars IN r.opt) THEN
        WHILE ~r.  Eol() & Lookahead (r, 1) & 
              (r. la[0] <= " ") &
              (r. la[0] # Ascii.ht) DO
          ch := Consume (r)
        END
      ELSE
        WHILE Lookahead (r, 1) & (r. la[0] <= " ") DO
          ch := Consume (r)
        END
      END
    END
  END SkipBlanks;

PROCEDURE SkipEol (r: Reader);
  VAR
    i: INTEGER;
    ch: CHAR;
  BEGIN
    IF r. Eol() THEN
      FOR i := 1 TO ABS (r. eolLen) DO
        (* note: if r.eolLen<-1 and we are looking at a CR+LF, only the CR 
           will be skipped at this time *)
        ch := Consume (r)
      END
    END
  END SkipEol;

PROCEDURE (r: Reader) ReadLn*;
  VAR 
    ch: CHAR;
  BEGIN
    WHILE ~r. Eol() DO
      ch := Consume (r)
    END;
    SkipEol (r)
  END ReadLn;

PROCEDURE (r: Reader) ReadString* (VAR s: ARRAY OF CHAR);
(* Pre: input = [whitespace] '"' {char} '"' | [whitespace] "'" {char} "'"
   Illegal chars terminate with invalidFormat.
 *)
  VAR
    cnt: INTEGER;
    quote: CHAR;
  BEGIN
    SkipBlanks (r);
    cnt := 0;
    
    IF (r. res = done) & Lookahead (r, 1) THEN
      IF (r. la[0] # '"') & (r. la[0] # "'") THEN
        r. res := GetError (invalidFormat)
      ELSE
        quote := Consume (r);
        LOOP
          IF ~Lookahead (r, 1) THEN
            quote := Consume (r);  (* low-level error *)
            EXIT
          ELSIF (r. la[0] < " ") THEN
            r. res := GetError (invalidFormat);
            EXIT
          ELSIF (r. la[0] = quote) THEN
            quote := Consume (r);  (* end quote *)
            EXIT
          ELSIF (cnt = LEN (s)-1) THEN
            r. res := GetError (valueOutOfRange);
            EXIT
          ELSE
            s[cnt] := Consume (r);
            INC (cnt)
          END
        END
      END
    ELSE
      quote := Consume (r)  (* low-level error *)
    END;
    
    s[cnt] := 0X
  END ReadString;

PROCEDURE (r: Reader) ReadLine* (VAR s: ARRAY OF CHAR);
(* Reads characters until an end of line character is encountered, or the 
   array `s' is full.  CAUTION: If reading multiple lines of input and an
   integer, real, etc. has just been read, the channel may be positioned
   at a eol character and this method will return an empty string. *)
  VAR
    cnt: INTEGER;
    dummy: CHAR;
  BEGIN
    (* check if eol auto detection left us a spurious lf in the input *)
    IF r. deferredEol & Lookahead (r, 1) & (r. la[0] = Ascii.lf) THEN
      dummy := Consume (r)
    END;
    
    (* read in the characters *)
    cnt := 0;
    WHILE ~r. Eol() & Lookahead (r, 1) & (cnt # LEN (s)-1) DO
      s[cnt] := Consume (r);
      INC (cnt)
    END;
    
    IF r. Eol() THEN
      SkipEol (r)
    ELSIF (cnt = LEN (s)-1)  THEN
      r. res := GetError (valueOutOfRange)
    END;
    s[cnt]:=0X (* terminate string *)
  END ReadLine;

PROCEDURE (r: Reader) ReadIdentifier* (VAR s: ARRAY OF CHAR);
(* Pre: input = [whitespace] letter {letter | digit}
 *)
  VAR
    cnt: INTEGER;
    ch: CHAR;
  BEGIN
    SkipBlanks (r);
    cnt := 0;
    
    IF (r. res = done) & Lookahead (r, 1) THEN
      IF ~CharClass.IsLetter(r. la[0]) THEN
        r. res := GetError (invalidFormat)
      ELSE
        s[0] := Consume (r);
        cnt := 1;
        LOOP
          IF ~(Lookahead (r, 1) &
               (CharClass.IsLetter(r. la[0]) OR
                CharClass.IsNumeric(r. la[0]))) THEN
            EXIT
          ELSIF (cnt = LEN (s)-1) THEN
            r. res := GetError (valueOutOfRange);
            EXIT
          ELSE
            s[cnt] := Consume (r);
            INC (cnt)
          END
        END
      END
    ELSE
      ch := Consume (r)  (* low-level error *)
    END;
    
    s[cnt]:=0X (* terminate string *)
  END ReadIdentifier;
 
PROCEDURE (r: Reader) ReadBool* (VAR bool: BOOLEAN);
(* Pre: input=[whitespace] ["TRUE"|"FALSE"]; Post: bool=TRUE iff input="TRUE"
   and bool=FALSE iff input="FALSE"; undefined otherwise *)
  VAR
    ident: ARRAY 8 OF CHAR;
  BEGIN
    r. ReadIdentifier (ident);
    IF (r. res = done) THEN
      IF (ident = "TRUE") THEN
        bool := TRUE
      ELSIF (ident = "FALSE") THEN
        bool := FALSE
      ELSE
        r. res := GetError (invalidFormat)
      END
    END
  END ReadBool;

PROCEDURE HexDigit (ch: CHAR) : BOOLEAN;
  BEGIN
    RETURN ((ch>="0") & (ch<="9")) OR ((ch>="A") & (ch<="F"))
  END HexDigit;

PROCEDURE HexToInt (str: ARRAY OF CHAR; VAR lint: LONGINT): BOOLEAN;
(* Returns the long integer constant `lint' in the string `str' according 
   to the format:
     IntConst = digit {hexdigit}

   Note: 80000000H-FFFFFFFFH are valid inputs which map to the negative
   integers. *)
  CONST
    BASE   = 16;
    MAXPAT = 8000000H;
  VAR
    d, pos: INTEGER;
  BEGIN    
    (* accept the hexadecimal input number *)
    lint:=0; pos:=0;
    LOOP
      (* read a digit *)
      d:=ORD(str[pos]);
      IF d=0 THEN RETURN TRUE
      ELSIF CharClass.IsNumeric(CHR(d)) THEN DEC(d, ORD("0"))
      ELSE (* A-F *) DEC(d, ORD("A")-10)
      END;
      
      (* check for overflow and adjustment *)
      IF (lint>=MAXPAT*2) OR (lint<0) THEN 
        RETURN FALSE (* overflow *)
      ELSIF (lint>=MAXPAT) & (d>=8) THEN 
        DEC(lint, MAXPAT*2)                          (* adjustment *)
      END;

      (* build up the number *)
      lint:=BASE*lint+d; 
      INC(pos)
    END
  END HexToInt;

PROCEDURE (r: Reader) ReadLInt* (VAR lint: LONGINT);
(* Returns the long integer constant n at the current position according to the
   format:
           IntConst = [whitespace] ["+"|"-"] digit {digit}        
*)
  CONST
    (* 2^31 has 11 digits, plus sign, plus 0, plus 0X = 14 *)
    buffer = 14;
  VAR
    str: ARRAY buffer OF CHAR;
    ch: CHAR;
    pos: INTEGER;
    res: SHORTINT;
    ignoreZeros: BOOLEAN;
  BEGIN 
    SkipBlanks (r);
    pos := 0;

    IF (r. res = done) & Lookahead (r, 1) THEN
      IF (r. la[0] = "+") OR (r. la[0] = "-") THEN
        str[0] := Consume (r);
        INC (pos);
        IF ~Lookahead (r, 1) THEN
          ch := Consume (r);         (* low-level error *)
          RETURN
        END
      END;
      
      IF CharClass.IsNumeric(r. la[0]) THEN
        str[pos] := "0";
        INC (pos);
        ignoreZeros := TRUE;
        LOOP
          IF ~(Lookahead (r, 1) & CharClass.IsNumeric(r. la[0])) THEN
            EXIT
          ELSE
            (* accumulate the digits; avoid overflow because of excessive 
               leading zeros *)
            ch := Consume (r);
            IF ~ignoreZeros OR (ch # "0") THEN
              IF (pos # buffer) THEN
                str[pos] := ch;
                INC (pos)
              END;
              ignoreZeros := FALSE
            END
          END
        END;
        
        (* convert to an integer *)
        IF (pos = buffer) THEN
          res := IntStr.strOutOfRange
        ELSE
          str[pos] := 0X; 
          IntStr.StrToInt (str, lint, res)
        END;

        (* set errors -- if needed *)
        IF (res = IntStr.strOutOfRange) THEN
          r. res := GetError (valueOutOfRange)
        ELSIF (res # IntStr.strAllRight) THEN
          r. res := GetError (invalidFormat)
        END
      ELSE
        r. res := GetError (invalidFormat)
      END
    ELSE
      ch := Consume (r)  (* low-level error *)
    END
  END ReadLInt;
  
PROCEDURE (r: Reader) ReadHex* (VAR lint: LONGINT);
(* Returns the long integer constant n at the current position according to the
   format:
     IntConst = [whitespace] digit {hexdigit}
                where hexDigit = "0".."9" | "A".."F" 
   Note: Numbers in the range 80000000H-FFFFFFFFH are read in as negative
   numbers.  If numbers like 80H-FFH are to be interpreted as negatives for
   SHORTINTs then neg = lint-100H or 8000H-FFFFH are to be interpreted as 
   negatives for INTEGERs then neg = lint-10000H.
*)
  CONST
    (* 2^32 has 8 digits, plus two digits, plus 0X = 11 *)
    buffer = 11;
  VAR
    str: ARRAY buffer OF CHAR;
    ch: CHAR;
    pos: INTEGER;
    ignoreZeros: BOOLEAN;
  BEGIN 
    SkipBlanks (r);
    pos := 0;

    IF (r. res = done) & Lookahead (r, 1) THEN
      IF CharClass.IsNumeric(r. la[0]) THEN
        str[pos] := "0";
        INC (pos);
        ignoreZeros := TRUE;
        LOOP
          IF ~(Lookahead (r, 1) & HexDigit (r. la[0])) THEN
            EXIT
          ELSE
            (* accumulate the digits; avoid overflow because of excessive 
               leading zeros *)
            ch := Consume (r);
            IF ~ignoreZeros OR (ch # "0") THEN
              IF (pos # buffer) THEN
                str[pos] := ch;
                INC (pos)
              END;
              ignoreZeros := FALSE
            END
          END
        END;
        
        (* convert to integer *)
        IF (pos = buffer) THEN
          r. res := GetError (valueOutOfRange)
        ELSE
          str[pos] := 0X;
          IF ~HexToInt(str, lint) THEN
            r. res := GetError (valueOutOfRange)
          END
        END
      ELSE
        r. res := GetError (invalidFormat)
      END
    ELSE
      ch := Consume (r)  (* low-level error *)
    END
  END ReadHex;

PROCEDURE (r: Reader) ReadInt * (VAR int: INTEGER);
(* as ReadLInt *)
  VAR
    lint: LONGINT;
  BEGIN
    r.ReadLInt(lint);
    IF (lint>MAX(INTEGER)) OR (lint<MIN(INTEGER)) THEN
      r. res := GetError (valueOutOfRange)
    ELSE
      int := SHORT(lint)
    END
  END ReadInt;

PROCEDURE (r: Reader) ReadSInt * (VAR sint: SHORTINT);
(* as ReadLInt *)
  VAR
    lint: LONGINT;
  BEGIN
    r.ReadLInt(lint);
    IF (lint>MAX(SHORTINT)) OR (lint<MIN(SHORTINT)) THEN
      r. res := GetError (valueOutOfRange)
    ELSE
      sint := SHORT(SHORT(lint))
    END
  END ReadSInt;

PROCEDURE (r: Reader) ReadLReal* (VAR lreal: LONGREAL);
(* Returns the long real constant `lreal' at the current position according to the 
   format:
     LongRealConst = [whitespace] ["+" | "-"] digit {digit} ["." {digit} [exponent]]
   where exponent = ("E" | "D") ("+" | "-") digit {digit}
   
   Note: Because of implementation restrictions, a real representation with 
   more than 1023 characters causes an `invalidFormat' error.
*)
  CONST
    buffer = 1024;
  VAR
    str: ARRAY buffer OF CHAR;
    res: SHORTINT;
    class: ConvTypes.ScanClass;
    state: ConvTypes.ScanState;
    pos: INTEGER;
    ch: CHAR;
  BEGIN    
    (* use state machine to ensure valid input *)
    SkipBlanks(r);
    pos := 0;
    
    IF (r. res = done) & Lookahead (r, 1) THEN
      LRealConv.ScanReal(r. la[0], class, state);
      
      IF (class = ConvTypes.valid) THEN
        str[0] := Consume (r);
        INC (pos);
        LOOP
          IF ~Lookahead (r, 1) THEN
            EXIT
          ELSE
            state.p (r. la[0], class, state);
            IF (class = ConvTypes.valid) THEN
              IF (pos < buffer) THEN
                str[pos] := Consume (r)
              END;
              INC (pos)
            ELSE
              EXIT
            END
          END
        END;
        
        IF (pos < buffer) THEN
          (* convert the real string *)
          str[pos] := 0X;
          LRealStr.StrToReal(str, lreal, res);

          (* set errors -- if needed *)
          IF (res = LRealStr.strOutOfRange) THEN
            r. res := GetError (valueOutOfRange)
          ELSIF (res # LRealStr.strAllRight) THEN
            r. res := GetError (invalidFormat)
          END
        ELSE
          r. res := GetError (invalidFormat)
        END
        
      ELSE
        r. res := GetError (invalidFormat)
      END
    ELSE
      ch := Consume (r)  (* low-level error *)
    END
  END ReadLReal;

PROCEDURE (r: Reader) ReadReal* (VAR real: REAL);
(* as ReadLReal *) 
  VAR
    n: LONGREAL;
    
  PROCEDURE ValidReal (value: LONGREAL): BOOLEAN;
  (* Returns TRUE iff `value' is mapped onto the range MIN(REAL)..MAX(REAL) if
     it would be converted to a REAL value.  Rounding to nearest/evan is 
     assumed.  Note that this depends on REAL being IEEE single precision.  
     The same code is used in the OOC frontend (module StdTypes.ValidReal).  *)
    CONST
      eps = 1.0141204801825835D+31;
      (* equals 2^103, half of the difference between two consecutive IEEE 
         single precision floating point numbers with maximum exponent *)
    BEGIN
      RETURN (MIN (REAL)-eps < value) & (value < MAX (REAL)+eps)
    END ValidReal;

  BEGIN
    r.ReadLReal(n);
    IF ValidReal (n) THEN
      real := SHORT(n)
    ELSE
      r. res := GetError (valueOutOfRange)
    END
  END ReadReal;

PROCEDURE (r: Reader) ReadSet* (VAR s: SET);
(* Read a set described in mathematical set notation into 's'.
   Pre: "{Element, ..., Element}"; Post: s={Element, ..., Element}
   where Element = number [".." number] and 0 <= number <= 31 *)
  VAR
    ch: CHAR;

  PROCEDURE ReadRange (): SET;
    VAR
      low, high: SHORTINT;
    BEGIN
      r. ReadSInt (low);
      high := low;
      
      IF (r. res = done) THEN
        IF ((low < 0) OR (low > MAX (SET))) THEN
          r. res := GetError (valueOutOfRange);
          RETURN {}
        ELSIF Lookahead (r, 2) & (r. la[0] = ".") & (r. la[1] = ".") THEN
          ch := Consume (r);
          ch := Consume (r);
          SkipBlanks (r);
          r. ReadSInt (high);
          IF (r. res = done) & 
             ((high < 0) OR (high > MAX (SET)) OR (high < low)) THEN
            r. res := GetError (valueOutOfRange);
            RETURN {}
          END
        END
      END;
      SkipBlanks (r);
      RETURN {low..high}
    END ReadRange;

  BEGIN
    (* ensure a valid start *)
    SkipBlanks (r);
    
    IF (r. res = done) & Lookahead (r, 1) THEN
      IF (r. la[0] = "{") THEN
        s := {};
        ch := Consume (r);
        SkipBlanks (r);
        IF (r. res = done) & Lookahead (r, 1) THEN
          IF (r. la[0] # "}") THEN
            s := s + ReadRange();
            WHILE (r. res = done) & Lookahead (r, 1) & (r. la[0] = ",") DO
              ch := Consume (r);
              SkipBlanks (r);
              s := s + ReadRange()
            END
          END;
          IF (r. res = done) & (r. la[0] = "}") THEN
            ch := Consume (r)
          ELSE
            r. res := GetError (invalidFormat)
          END
        ELSE
          ch := Consume (r)  (* low-level error *)
        END
      ELSE
        r. res := GetError (invalidFormat)
      END
    ELSE
      ch := Consume (r)  (* low-level error *)
    END
  END ReadSet;
 

(* Scanner methods 
   ------------------------------------------------------------------------ *)
   
PROCEDURE SkipSpaces (s: Scanner);
(* Skip white space as defined by the scanner options.  *)
  VAR
    ch: CHAR;
  BEGIN  (* pre: (s. res = done) *)
    (* note: Ascii.lf must be a whitespace character, or with eol auto 
       detection a ReadFoo procedure may find a spurious Ascii.lf in its 
       input that it should never have seen *)
    ASSERT (s. res = done);
    IF (returnCtrlChars IN s. opt) THEN
      WHILE ~s. r.  Eol() & Lookahead (s. r, 1) & 
            (s. r. la[0] <= " ") &
            (s. r. la[0] # Ascii.ht) DO
        ch := Consume (s. r)
      END
    ELSE
      WHILE Lookahead (s. r, 1) & (s. r. la[0] <= " ") DO
        IF s. r. Eol() THEN
          INC (s. lines);
          SkipEol (s. r)
        ELSE
          ch := Consume (s. r)
        END
      END
    END;
    s. res := s. r. res
  END SkipSpaces;

PROCEDURE (s: Scanner) Pos* () : LONGINT;
(* Position of the look-ahead character *)
  BEGIN
    RETURN s.r.Pos()
  END Pos;
  
PROCEDURE (s: Scanner) ClearError*;
  BEGIN
    s. r. ClearError;
    s. res := done;
    s. type := undefined
  END ClearError;

PROCEDURE (s: Scanner) Available* () : LONGINT;
(* Position of the look-ahead character *)
  BEGIN
    RETURN s.r.Available()
  END Available;

PROCEDURE (s: Scanner) SetPos* (pos: LONGINT);
  BEGIN
    IF (s. res = done) THEN
      s. r. SetPos(pos);
      s. res := s. r. res
    END
  END SetPos;

(* Scan for the next token *)
PROCEDURE (s: Scanner) Scan*;
(* Note: Because of implementation restrictions, a real representation with 
   more than 1023 characters causes an `invalidFormat' error.  *)
  CONST
    buffer = 1024;
  VAR
    ch: CHAR; str: ARRAY buffer OF CHAR; pos: INTEGER; res: SHORTINT;
    
  PROCEDURE ReadNum;
  (* pre: current lookahead character is digit or sign *)
    PROCEDURE Get;
      VAR
        dummy: BOOLEAN;
      BEGIN
        IF (pos < buffer) THEN
          str[pos] := Consume (s. r)
        END; 
        INC (pos);
        IF (s. r. res = done) THEN
          dummy := Lookahead (s. r, 1)
        ELSE
          s. r. la[0] := 0X
        END
      END Get;
    
    PROCEDURE LA (): CHAR;
      BEGIN
        RETURN s. r. la[0]
      END LA;
    
    BEGIN
      IF (s. r. res = done) & Lookahead (s. r, 1) THEN
        pos:=0;
        
        IF (LA() = "-") OR (LA() = "+") THEN
          Get
        END;

        (* read leading digits *)
        IF ~CharClass.IsNumeric (LA()) THEN
          s. res := GetError (invalidFormat);
          RETURN
        ELSE
          WHILE HexDigit (LA()) DO Get END
        END;

        (* check for reals or hexadecimals *)
        IF (LA() = ".") THEN  (* real number *)
          s.type:=real;
          Get;
          (* read trailing digits *)
          WHILE CharClass.IsNumeric (LA()) DO Get END;
          (* read the exponent *)
          IF (LA() = "E") OR (LA() = "e") THEN
            Get;
            IF (pos-1 < buffer) THEN str[pos-1] := "E" END;
            IF (LA() = "-") OR (LA() = "+") THEN Get END;
            (* read leading digits *)
            IF ~CharClass.IsNumeric (LA()) THEN
              s. res := GetError (invalidFormat);
              RETURN
            ELSE
              WHILE CharClass.IsNumeric (LA()) DO Get END
            END
          END;

          (* convert to real *)
          IF (pos < buffer) THEN
            str[pos]:=0X;
            LRealStr.StrToReal(str, s.real, res);

            (* set errors -- if needed *)
            IF (res # LRealStr.strAllRight) THEN
              s. res := GetError (invalidFormat)
            END
          ELSE
            s. res := GetError (invalidFormat)
          END
          
        ELSIF (LA() = "H") THEN (* hexadecimal integer *)
          s.type:=int; str[pos]:=0X; 
          IF ~HexToInt (str, s. int) THEN
            s. res := GetError (invalidFormat)
          END;
          Get  (* get rid of "H" *)

        ELSE (* just an integer *)
          s.type:=int;
          str[pos]:=0X;
          IntStr.StrToInt(str, s.int, res);
          IF res#IntStr.strAllRight THEN 
            s. res := GetError (invalidFormat)
          END             
        END
      END
    END ReadNum;
    
  PROCEDURE SetType (type: SHORTINT);
    BEGIN
      s. type := type
    END SetType;
  
  BEGIN
    IF (s. type < error) THEN  (* `error' and `invalid' are sticky *)
      (* if `s.type' does not signal an error, then `s.res=done' *)
      SkipSpaces (s); 

      IF (s. res = done) & Lookahead (s. r, 1) THEN
        s.pos:=s.Pos();

        IF s. r. Eol() THEN
          s. type := line;
          SkipEol (s. r);
          INC (s. lines)
        ELSE
          CASE s. r. la[0] OF
          | '"', "'":
            IF (interpretStrings IN s. opt) THEN
              s. r. ReadString (s. string); 
              SetType (string)
            ELSE
              s. r. ReadChar (s.char);
              SetType (char)
            END
          | "a".."z", "A".."Z": 
            s. r. ReadIdentifier (s. string);
            IF (s. r. res = done) & (interpretBools IN s.opt) &
               ((s. string = "TRUE") OR (s. string="FALSE")) THEN
              s. bool := (s. string = "TRUE");
              SetType (bool)
            ELSE
              SetType (ident)
            END
          | "+", "-":
            IF (useSignedNumbers IN s.opt) THEN
              ReadNum
            ELSE
              s. r. ReadChar (s.char);
              SetType (char)
            END
          | "0".."9": (* integer or real *)
            ReadNum
          | "{":
            IF (interpretSets IN s. opt) THEN
              s. r. ReadSet (s. set); 
              SetType (set)
            ELSE
              s. r. ReadChar (s.char);
              SetType (char)
            END
          ELSE
            s. r. ReadChar (s.char);
            IF (s. char = Ascii.ht) THEN
              SetType (tab)
            ELSE
              SetType (char)
            END
          END
        END
      ELSE
        ch := Consume (s. r)  (* low-level error *)
      END;

      IF (s. r. res # done) & (s. res = done) THEN
          s. res := s. r. res
      END;
      IF (s. res # done) & (s. res. context = errorContext) &
         ((s. res. code = invalidFormat) OR
          (s. res. code = valueOutOfRange)) THEN
        s. type := invalid
      ELSE
        s. type := error
      END
    END
  END Scan;

(* Set the scanner options `s.opt' which are defined above. *)
PROCEDURE (s: Scanner) SetOpts* (opts: SET);
  BEGIN
    s.opt:=opts;
    s.r.opt:=opts*{returnCtrlChars}  (* adjust the reader options as well *)
  END SetOpts;

PROCEDURE (s: Scanner) SetEol* (marker: ARRAY OF CHAR; markerLen: INTEGER);
(* As Reader.SetEol.  *)
  BEGIN
    s. r. SetEol (marker, markerLen)
  END SetEol;


(* Writer methods 
   ------------------------------------------------------------------------ *)

(* The following write methods write the value as a string to the 
   underlying Channel.
 *)
 
PROCEDURE (w: Writer) Pos* () : LONGINT;
  BEGIN
    RETURN w.byteWriter.Pos()
  END Pos;

PROCEDURE (w: Writer) SetPos* (newPos: LONGINT);
  BEGIN
    IF (w. res = done) THEN
      w.byteWriter.SetPos(newPos);
      w. res := w. byteWriter. res
    END
  END SetPos;

PROCEDURE (w: Writer) ClearError*;
  BEGIN
    w.byteWriter.ClearError;
    w.res := done
  END ClearError;

PROCEDURE (w: Writer) SetOpts* (opts: SET);
(* Set the writer options `w.opt' which are defined above. *)
  BEGIN
    w.opt:=opts
  END SetOpts;

PROCEDURE (w: Writer) SetEol* (marker: ARRAY OF CHAR; markerLen: INTEGER);
(* Sets new end of line marker.  If the passed string marker does not fit into
   the field `eol', then `w.res' is set to `invalidFormat'.  The empty
   marker is permitted.  The default value for newly created writer is 
   `CharClass.systemEol'.
   pre: (w.res = done) & (0 <= markerLen < LEN (marker)) &
        (markerLen <= maxLengthEol)  *)
  VAR
    i: INTEGER;
  BEGIN
    IF (w. res = done) THEN
      IF (markerLen < 0) OR (markerLen > maxLengthEol) THEN
        w. res := GetError (invalidFormat)
      ELSE
        FOR i := 0 TO markerLen-1 DO
          w. eol[i] := marker[i]
        END;
        w. eolLen := markerLen
      END
    END
  END SetEol;

(* The terminating 0X is not written *)
PROCEDURE (w: Writer) WriteString*(s[NO_COPY]: ARRAY OF CHAR);
  BEGIN
    IF (w. res = done) THEN
      w. byteWriter. WriteBytes (s, 0, Strings.Length (s));
      w. res := w. byteWriter. res;
      IF (noBuffering IN w.opt) & (w. res = done) THEN
        w. base. Flush;
        w. res := w. base. res
      END
    END
  END WriteString;

PROCEDURE (w: Writer) WriteBool*(bool: BOOLEAN);
  BEGIN
    IF bool THEN w. WriteString ("TRUE")
    ELSE w. WriteString ("FALSE")
    END
  END WriteBool;
  
PROCEDURE (w: Writer) WriteChar*(ch: CHAR);
  BEGIN
    IF (w. res = done) THEN
      w.byteWriter.WriteByte(ch);
      IF (noBuffering IN w.opt) & (w. res = done) THEN
        w. base. Flush;
        w. res := w. base. res
      END
    END
  END WriteChar;
  
PROCEDURE WritePad (w: Writer; n: LONGINT);
  BEGIN
    (* output padding *)
    WHILE n>0 DO w.WriteChar(" "); DEC(n) END  
  END WritePad;
  
(* Convert 'sint' to a string of at least 'n' chars and write it to the
   underlying channel. If 'n' is too small it will be extended. If 'n'
   is greater then nessesary spaces will be added after the number, i.e.
   it is left justified. *)
PROCEDURE (w: Writer) WriteLInt*(lint: LONGINT; n: LONGINT);
  VAR
    val: ARRAY 16 OF CHAR;
  BEGIN
    (* convert to a string *)
    IntStr.IntToStr(lint, val);
    
    (* output any required padding *)
    WritePad(w, n-Strings.Length(val));
    
    (* output the string *)
    w.WriteString(val)
  END WriteLInt;
  
PROCEDURE (w: Writer) WriteSInt* (sint: SHORTINT; n: LONGINT);
  BEGIN
    w.WriteLInt(sint, n)
  END WriteSInt;

PROCEDURE (w: Writer) WriteInt* (int: INTEGER; n: LONGINT);
  BEGIN
    w.WriteLInt(int, n)
  END WriteInt;
 
(* Write `lint' as a heximal number using `d' digits. 
   If `d' <= 0 then `lint' is written using 8 digits. *)
PROCEDURE (w: Writer) WriteHex* (lint: LONGINT; d: LONGINT);
  PROCEDURE WriteHexDigits(w: Writer; VAR n: LONGINT; digits: LONGINT);
    CONST
      BASE=16;
    VAR
      dig: LONGINT;
    BEGIN
      (* output padding digits *)
      WHILE digits>8 DO 
        IF n<0 THEN w.WriteChar("F") ELSE w.WriteChar("0") END;
        DEC(digits)
      END;

      (* output the actual number *)
      WHILE digits>0 DO
        DEC(digits);
        dig := ASH(n, -4*digits) MOD BASE;
        IF dig<=9 THEN w.WriteChar(CHR(ORD("0") + dig)) 
        ELSE w.WriteChar(CHR(ORD("A") - 10 + dig)) 
        END
      END
    END WriteHexDigits;

  BEGIN
    IF d<=0 THEN d:=8 END;
    WriteHexDigits(w, lint, d)
  END WriteHex;

PROCEDURE (w: Writer) WriteLReal*(lreal: LONGREAL; n, k: LONGINT);
 (* The call to WriteLongReal(lreal, n, k) shall write to the underlying
    channel a formatted string corresponding to the value of `lreal' in
    floating-point form.  A sign shall be included only for negative
    values.  One significant digit shall be included in the whole number
    part.  The signed exponent part shall be included only if the exponent
    value is not 0.  If the value of `k' is greater than 0, that
    number of significant digits shall be included, otherwise an
    implementation-defined number of significant digits shall be
    included.  The decimal point shall not be included if there are no
    significant digits in the fractional part.  The complete formatted
    number will be right-justified in a field of width `n'.  If 'n' is 
    too small it will be extended.
    
    For example: (n=9)
    
    value:     3923009     39.23009     0.0003923009
      k
      1             4E+6        4E+1         4E-4 
      2           3.9E+6      3.9E+1       3.9E-4
      5        3.9230E+6   3.9230E+1    3.9230E-4
 *)
  VAR
    val: ARRAY 128 OF CHAR;
  BEGIN
    (* convert to a string *)
    LRealStr.RealToFloat(lreal, SHORT(k), val);
    
    (* output any required padding *)
    WritePad(w, n-Strings.Length(val));

    (* output the string *)
    w.WriteString(val);
  END WriteLReal;

PROCEDURE (w: Writer) WriteReal*(real: REAL; n, k: LONGINT);
(* As WriteLReal *)
  VAR
    val: ARRAY 128 OF CHAR;
  BEGIN
    (* convert to a string *)
    RealStr.RealToFloat(real, SHORT(k), val);
    
    (* output any required padding *)
    WritePad(w, n-Strings.Length(val));

    (* output the string *)
    w.WriteString(val)
  END WriteReal;

PROCEDURE (w: Writer) WriteLRealFix*(VAR lreal: LONGREAL; n, k: LONGINT);
 (* 
    The call WriteLRealFix(lreal, n, k) shall output to the underlying
    channel the formatted string corresponding to the value of `lreal' in
    fixed-point form.  A sign shall be included only for negative values.
    At least one digit shall be included in the whole number part.  The
    value shall be rounded to the given value of `k' relative to the
    decimal point.  The decimal point shall be suppressed if `k' is
    less than 0. The complete formatted number will be right-justified 
    in a field of width `n'.  If 'n' is too small it will be extended.
    
    For example: (n=12)
    
    value:        3923009         3.923009   0.0003923009
      k
     -5             3920000             0          0 
     -2             3923010             0          0
     -1             3923009             4          0 
      0            3923009.            4.         0. 
      1           3923009.0           3.9        0.0
      4        3923009.0000        3.9230     0.0004       
 *)
  VAR
    val: ARRAY 128 OF CHAR;
  BEGIN
    (* convert to a string *)
    LRealStr.RealToFixed(lreal, SHORT(k), val);
    
    (* output any required padding *)
    WritePad(w, n-Strings.Length(val));
    
    (* output the string *)
    w.WriteString(val)
  END WriteLRealFix;

PROCEDURE (w: Writer) WriteRealFix*(real: REAL; n, k: LONGINT);
(* As WriteLongRealFix *)
  VAR
    val: ARRAY 128 OF CHAR;
  BEGIN
    (* convert to a string *)
    RealStr.RealToFixed(real, SHORT(k), val);
    
    (* output any required padding *)
    WritePad(w, n-Strings.Length(val));
    
    (* output the string *)
    w.WriteString(val)
  END WriteRealFix;

PROCEDURE (w: Writer) WriteLRealEng*(VAR lreal: LONGREAL; n, k: LONGINT);
 (* 
    Converts the value of real to floating-point string form, with 
    `k' significant figures, and writes the resultant value,
    right-justified in a field of width `n' to the underlying channel.
    If 'n' is too small it will be extended. The number is scaled with 
    one to three digits in the whole number part and with an exponent 
    that is a multiple of three.
     
    For example: n=9
    
    value:     3923009     39.23009   0.0003923009
      k
      1             4E+6        40         400E-6 
      2           3.9E+6        39         390E-6
      5        3.9230E+6    39.230      392.30E-6     
  *)
  VAR
    val: ARRAY 128 OF CHAR;
  BEGIN
    (* convert to a string *)
    LRealStr.RealToEng(lreal, SHORT(k), val);
    
    (* output any required padding *)
    WritePad(w, n-Strings.Length(val));
    
    (* output the string *)
    w.WriteString(val)
  END WriteLRealEng;

PROCEDURE (w: Writer) WriteRealEng*(real: REAL; n, k: LONGINT);
(* As WriteLRealEng *)
  VAR
    val: ARRAY 128 OF CHAR;
  BEGIN
    (* convert to a string *)
    RealStr.RealToEng(real, SHORT(k), val);
    
    (* output any required padding *)
    WritePad(w, n-Strings.Length(val));
    
    (* output the string *)
    w.WriteString(val)
  END WriteRealEng;
  
PROCEDURE (w: Writer) WriteSet*(s: SET);
(* Write 's' in mathematical set notation.
   Pre: x = {Element, ..., Element}; Post: write "{Element, ..., Element}" 
   where Element = number [".." number] and 0 <= number <= 31 *)
  VAR
    bit, lo: SHORTINT; addComma: BOOLEAN;
  BEGIN
    w.WriteChar("{"); bit:=0; addComma:=FALSE;
    WHILE bit<=MAX(SET) DO      
      IF bit IN s THEN
        lo:=bit;
        WHILE (bit<MAX(SET)) & (bit+1 IN s) DO INC(bit) END; (* check for runs *)
        
        (* output the set element(s) *)
        IF addComma THEN w.WriteString(", ") ELSE addComma:=TRUE END;
        w.WriteInt(lo, 0);
        IF lo<bit THEN
          w.WriteString(".."); w.WriteInt(bit, 0)
        END
      END;
      INC(bit)
    END;
    w.WriteChar("}");
  END WriteSet;
 
PROCEDURE (w: Writer) WriteLn*;
(* Write a newline *)
  VAR
    i: INTEGER;
  BEGIN
    FOR i := 0 TO w. eolLen-1 DO
      w. WriteChar (w.eol[i])
    END
  END WriteLn;


(* Reader Procedures
   ------------------------------------------------------------------------ *)

PROCEDURE InitReader* (r: Reader; ch: Channel.Channel);
  BEGIN
    r. res := done;
    r. opt := defReaderOptions;
    r. byteReader := ch.NewReader();
    r. base := ch;
    r. eolLen := -1;
    r. deferredEol := FALSE;
    r. laLen := 0
  END InitReader;

PROCEDURE ConnectReader*(ch: Channel.Channel): Reader;
  VAR
    r: Reader;
  BEGIN
    NEW(r);
    InitReader (r, ch);
    IF (r. byteReader = NIL) THEN
      RETURN NIL
    ELSE
      RETURN r
    END
  END ConnectReader;
  
(* Writer Procedures
   ------------------------------------------------------------------------ *)

PROCEDURE InitWriter* (w: Writer; ch: Channel.Channel);
  VAR
    i: INTEGER;
  BEGIN
    w. res := done;
    w. opt := defWriterOptions;
    w. byteWriter := ch.NewWriter();
    w. base := ch;
    w. eolLen := Strings.Length (CharClass.systemEol);
    FOR i := 0 TO w. eolLen-1 DO
      w. eol[i] := CharClass.systemEol[i]
    END
  END InitWriter;

PROCEDURE ConnectWriter*(ch: Channel.Channel): Writer;
  VAR
    w: Writer;
  BEGIN
    NEW(w);
    InitWriter (w, ch);
    IF (w. byteWriter = NIL) THEN
      RETURN NIL
    ELSE
      RETURN w
    END
  END ConnectWriter;

(* Scanner Procedures
   ------------------------------------------------------------------------ *)

PROCEDURE InitScanner* (s: Scanner; ch: Channel.Channel);
  BEGIN
    s. res := done;
    s.r:=ConnectReader(ch);
    s.opt:=defScannerOptions;
    s.type:=undefined;
    s.lines:=0;
    s. base := ch;
  END InitScanner;

PROCEDURE ConnectScanner*(ch: Channel.Channel): Scanner;
  VAR
    s: Scanner;
  BEGIN
    NEW(s);
    InitScanner (s, ch);
    IF (s. r = NIL) THEN
      RETURN NIL
    ELSE
      RETURN s
    END
  END ConnectScanner;

BEGIN
  NEW (errorContext);
  Msg.InitContext (errorContext, "OOC:Core:TextRider")
END TextRider.