PROGRAM WordCount (Input,Output,InData);

(* David Wills
   CMIS 150  University of Maryland
   SHAPE  Term 5  1991
   Turbo Pascal 5.5  *)

(* This program counts the number of words in a file or in the Input.
  A word is any sequence of non-blank characters. *)


VAR
   InData : Text;      (* Input file *)
   InFileName : String; (* Name of input file.  Input by user *)
   Source, Answer : Char;
   Again : Boolean;
   Number : Integer;



FUNCTION Count (VAR Source : Text) : Integer;

Const
   Blank = ' ';

Var
   Num : Integer;
   Ch : Char;
   InWord : Boolean;

Begin
   Num := 0;

   WHILE NOT EOF(Source) DO
    Begin
      InWord := False;
      WHILE NOT EOLN(Source) DO
        Begin
          Read(Source,Ch);
          IF (Ch <> Blank) THEN
            Begin
             IF NOT InWord THEN
              Begin
                Num := Num + 1;
                InWord := True;
              End
            End
          ELSE
            IF InWord THEN
               InWord := False;
        End;
      Readln(Source);
    End;
   Count := Num;
End;




BEGIN
   Again := True;
   WHILE Again DO
     Begin
       Write('Input from File or from Input? (F or I) ');
       Readln(Source);
       IF (Source = 'F') OR (Source = 'f') THEN
        Begin
         (* Get input file name from user.  Prepare file for reading *)
         Write('Enter name of file: ');
         Readln(InFileName);
         Assign(InData,InFileName);
         Reset(InData);
         Writeln('Number of words in this file is: ',Count(InData));
        End
       ELSE
        Begin
         Writeln('Start entering text.  Terminate with Ctrl-z.');
         Writeln('Number of words input is: ',Count(Input));
        End;
       Write('Another run? (Y or N) ');
       Readln(Answer);
       IF (Answer <> 'Y') AND (Answer <> 'y') THEN
          Again := False;
     End;

END.