MODULE wordcount; (*DEE 2015-11-25/2016-08-23/2018-06-02/2018-09-22*) (*See Exercise 1-4 in Software Tools.*) FROM ST IMPORT error, getarg, getc, putc; FROM STchars IMPORT character, BLANK, ENDFILE, MINUS, NEWLINE, TAB; FROM STstrings IMPORT MAXSTR, putdec, string; VAR cmd: string; (* command type *) nc, nl, nw: INTEGER; (* TODO: these should be able to be combined, instead of using -a. *) PROCEDURE help; BEGIN error('usage: wordcount [ -a | -c | -l | -w ]') END help; (* wordcount: count words, characters, and lines in standard input *) PROCEDURE wordcount; VAR c: character; inword: BOOLEAN; BEGIN nl := 0; nw := 0; nc := 0; inword := FALSE; WHILE (getc(c) # ENDFILE) DO IF (c = BLANK) OR (c = NEWLINE) OR (c = TAB) THEN inword := FALSE; IF (c = NEWLINE) THEN INC(nl) END ELSIF ~inword THEN inword := TRUE; INC(nw) END; INC(nc) END END wordcount; BEGIN IF getarg(1, cmd, MAXSTR) THEN IF (cmd[1] # MINUS) THEN help (* PIM4 doesn't require VAL, but PIM3 and ISO/IEC 10514-1:1996 do. *) ELSIF (cmd[2] = VAL(INTEGER, ORD('l'))) THEN wordcount; putdec(nl,1) ELSIF (cmd[2] = VAL(INTEGER, ORD('w'))) THEN wordcount; putdec(nw, 1) ELSIF (cmd[2] = VAL(INTEGER, ORD('c'))) THEN wordcount; putdec(nc,1) ELSIF (cmd[2] = VAL(INTEGER, ORD('a'))) THEN wordcount; putdec(nl, 8); putdec(nw, 8); putdec(nc, 8) ELSE help END ELSE wordcount; putdec(nw, 1); (* Remain compatible with Software Tools wordcount. *) END; putc(NEWLINE) END wordcount.