
Program WC;

USES
{ Turbo Power Object Professional units }
  OpDos,
  OpString;

CONST
  BlockSize = 61440;

TYPE
  BlockType  = array [1 .. BlockSize] of char;

VAR
  FileName     : string;
  Block        : BlockType;
  ReadFile     : file;
  Fsize,
  Fpos         : longint;
  NumRead      : word;

  WordCount    : longint;
  Loop         : longint;

  Ch           : char;
  CharFlag     : boolean;
  PredCharFlag : boolean;
  CommentCtr   : integer;

BEGIN
  writeln ('WC 1.0, word counter, written by David Gerrold');

  if ParamCount <> 1 then begin
    writeln ('USAGE:  WC <filename>');
    halt;
    end;

  FileName := StUpCase (ParamStr (1));
  if not ExistFile (FileName) then begin
    writeln ('Sorry, can''t find ''', FileName, '''.');
    halt;
    end;

  assign (ReadFile, Filename);
  reset (ReadFile, 1);
  Fsize := filesize (ReadFile);
  WriteLn ('Estimated word count:  ',
           trim (LongIntForm ('###,###,###', Fsize div 6)));

  WordCount   := 0;
  Fpos        := 0;
  CommentCtr  := 0;

  while
    Fpos < Fsize
  do begin
    BlockRead(ReadFile,Block,sizeof(BlockType),NumRead);
    write ('.');
    Loop := 0;

    repeat
      inc (Loop);
      inc (Fpos);
      PredCharFlag := CharFlag;

      Ch := Block [Loop];
      CharFlag :=
        ((Ch >= 'a') and (Ch <= 'z')) or
        ((Ch >= 'A') and (Ch <= 'Z')) or
        ((Ch >= '0') and (Ch <= '9')) or
        (Ch = #39);

      if CommentCtr = 0 then
        if
          not CharFlag and
          PredCharFlag
        then
          inc (WordCount);

      Case Block [Loop] of
        ^N : if CommentCtr > 0 then dec (CommentCtr);
        ^O : inc (CommentCtr);
        end;
    until
      (Loop > BlockSize) or
      (Fpos >= Fsize);
    end;

  Close (ReadFile);
  writeln;
  writeln ('Total words in file:  ',
           trim (LongIntForm ('###,###,###', WordCount)));
END.
