-- TexFile.mesa

-- last written by Doug Wyatt, January 19, 1980  12:22 AM

DIRECTORY
	TexFileDefs: FROM "TexFileDefs",
	TexStringDefs: FROM "TexStringDefs",
	AltoFileDefs: FROM "AltoFileDefs",
	SegmentDefs: FROM "SegmentDefs";

TexFile: PROGRAM
IMPORTS TexStringDefs,SegmentDefs
EXPORTS TexFileDefs =
BEGIN OPEN SegmentDefs,TexFileDefs;

LookupFailed: PUBLIC SIGNAL[name: STRING] = CODE;

Access: PROCEDURE[rw: ReadWrite] RETURNS[AccessOptions] = INLINE
	BEGIN RETURN[IF rw=read THEN Read ELSE Write+Append] END;

Version: PROCEDURE[rw: ReadWrite] RETURNS[VersionOptions] = INLINE
	BEGIN RETURN[IF rw=read THEN OldFileOnly ELSE DefaultVersion] END;

-- open the given file; SIGNAL LookupFailed if unsuccessful
OpenFile: PUBLIC PROCEDURE[filename: STRING, rw: ReadWrite]
	RETURNS[FileHandle] =
	BEGIN
	fh: FileHandle;
	fh←NewFile[name: filename, access: Access[rw], version: Version[rw]
		!FileNameError => ERROR LookupFailed[filename]];
	RETURN[fh];
	END;

OpenFileFromFP: PUBLIC PROCEDURE[fp: POINTER TO AltoFileDefs.FP, rw: ReadWrite]
	RETURNS[FileHandle] =
	BEGIN
	fh: FileHandle;
	fh←InsertFile[fp: fp, access: Access[rw]];
	RETURN[fh];
	END;

-- if filename has no extension, append a "." and the given extension
DefaultExtension: PUBLIC PROCEDURE[filename,extension: STRING] =
	BEGIN OPEN TexStringDefs;
	i: CARDINAL;
	FOR i IN[0..filename.length) DO IF filename[i]='. THEN RETURN ENDLOOP;
	AppendChar[filename,'.]; AppendString[filename,extension];
	END;

-- strip filename's extension, if any
StripExtension: PUBLIC PROCEDURE[filename: STRING] =
	BEGIN
	i: CARDINAL;
	FOR i IN[0..filename.length)
		DO
		IF filename[i]='. THEN BEGIN filename.length←i; EXIT END;
		ENDLOOP;
	END;

-- append filename's name and extension to name and ext respectively
NameAndExtension: PUBLIC PROCEDURE[filename,name,ext: STRING] =
	BEGIN OPEN TexStringDefs;
	c: CHARACTER;
	s: STRING←name;
	i: CARDINAL;
	FOR i IN[0..filename.length)
		DO
		SELECT (c←filename[i]) FROM
			'. => s←ext; -- end of name part, switch to extension
			'! => EXIT; -- ignore version number at end of filename
			ENDCASE => IF s#NIL THEN AppendChar[s,c];
		ENDLOOP;
	END;

END.