(* Fileop.Mod 
Mark Pavlidis pavlidmh@mcmaster.ca 
Modified by: Yamama Khadduri
McMaster University 
SFWR 2A04 Turorial 
2002-11-15 
A simple example of reading and writing to a file with Strings and Integers*)

MODULE Fileop;

IMPORT Out,Files,Texts,Strings;

PROCEDURE Rfile*;
VAR	x	: INTEGER;				(* sum *)
	T	: Texts.Text;				(* pointer to a rec in Texts. *)
	S	: Texts.Scanner;			(* rec in Texts *)
	Fbin, Fstr	: Files.File;			(* pointer to rec in Files. for Binary and for String *)
	Rbin, Rstr	: Files.Rider; 			(* rec, access mechanism for files *)
	xstr : ARRAY 32 OF CHAR;			(* array to save strings *)
			
BEGIN   
	NEW(T);					(* new text *)
	Texts.Open(T,"infile.txt");		(* open text T from file "name" *)
	Fbin := Files.New("bin-outfile");	(* create new file named bin-outfile. references it under Fbin *)
	Fstr := Files.New("str-outfile");	(* create new file named str_outfile. references it under Fstr *)
	Files.Set(Rbin, Fbin, 0);		(* poition the rider (Rbin) at certain position(0) in file (Fbin) *)
	Files.Set(Rstr, Fstr, 0);
	Texts.OpenScanner(S, T, 0);		(* start text stream - open text scanner (S) and set at position (0) in text (T) *)
	Texts.Scan(S);				(* read first number *)
	WHILE (S.class # Texts.Inval) DO
		x := 0;
		WHILE (S.class = Texts.Int) DO	(* loop till the end of line where class is not an Int *)
			x := x + SHORT(S.i);
			Texts.Scan(S);		(* read second number and on *)
		END;
		Files.WriteInt(Rbin, x); 	(* WriteInt writes to a file in binary format *)
		Strings.IntToStr(x, xstr);	(* convert integer to string *)
		Files.WriteString(Rstr,"SUM = ");  (* write the string to the file *)
		Files.WriteString(Rstr, xstr);	(* write the value of SUM as a character *)
		Files.WriteString(Rstr, 0DX);	(* write a line feed to the file *)
		Texts.Scan(S);
	END;
	Files.Register(Fstr);			(* write the files to disk *)
	Files.Register(Fbin);
	Fstr:= Files.Old("str-outfile");       	(* open existing character file *)
	Fbin := Files.Old("bin-outfile"); 	(* open existing binary file *)
	Files.Set(Rstr,Fstr,0);
	Files.ReadString(Rstr, xstr);		(* output: 'SUM = ' *)
	Out.Ln;
	Out.String(xstr);
	Files.ReadString(Rstr, xstr);		(* read the value of SUM *)
	Out.String(xstr);			(* output: result of SUM *)
	Files.Set(Rbin,Fbin,0);
	Out.Ln;
	Out.String("Sum in Binary file = ");
	Files.ReadInt(Rbin, x);			(* read the value of SUM in binary *)
	Out.Int(x, 1);				(* output *)
END Rfile;

END Fileop.   
