                      { --- File operations --- }

procedure open_readfile(var name:filename_string;var diskfile:file_of_text);
begin
assign(diskfile,name);
{$I-} reset(diskfile) {$I+} ;
file_flag:= (IOresult=0);
if not file_flag then prompt_for_esc('File '+name+' not found.');
end; { open_readfile }

procedure open_writefile(var name:filename_string;var diskfile:file_of_text;veto:boolean);
var io_no:integer;
    str2: string[2];
begin
assign(diskfile,name);
{$I-}
reset(diskfile);
file_flag:= (IOresult=0);
yes_flag:=true;
if veto and file_flag then prompt_for_YN('File '+name+' exists. Overwrite',false);
if yes_flag then
    begin
    rewrite(diskfile); io_no:=IOresult; file_flag := (io_no=0);
    if not file_flag then
        case io_no of
        $F1: prompt_for_esc('Directory full. File not opened.');
        else  begin
              Str(io_no:2,str2);
              prompt_for_esc('IO-Error '+str2+'. File not opened.');
              end;
        end;
    end
else begin file_flag:=false; Close(diskfile); end;
{$I+}
end; { open_writefile }

procedure read_text_from_file(var diskfile:file_of_text);
{ Read text file into array substituting cr/lf's with cr's }
label exit;
begin
crflag := false; lfflag := false;
while not eof(diskfile) do
    begin
    if text_end<TEXTLIMIT-1 then
        begin
        read(diskfile,ch);
        if crflag then begin lfflag:= ch=LF; crflag:=false; end
        else crflag:= ch=CR;
        if not lfflag then
            begin text_end:=text_end+1; text[text_end]:=ch; end
        else lfflag:=false;
        end
    else
        begin
        prompt_for_esc('Text buffer too short. File not read completely.');
        goto exit;
        end;
    end;
exit: Close(diskfile);
end; { read_text_from_file }

procedure write_text_to_file(var diskfile:file_of_text;first,last:integer);
{ Write text portion into file substituting cr's with cr/lf's }
label exit;
var i,io_no: integer;
    incomplete: boolean;
    str2: string[2];
begin
incomplete:=false;
{$I-}
for i:=first to last do
    begin
    write(diskfile,text[i]); io_no:=IOresult;
    if (io_no=0) and (eol(i)) then
        begin write(diskfile,LF); io_no:=IOresult; end;
    if io_no<>0 then
        begin
        incomplete:=true; Str(io_no:2,str2);
        prompt_for_esc('Disk IO error '+str2+'. Trying to close file.');
        goto exit;
        end;
   end;
exit:
Close(diskfile); io_no:=IOresult;
if io_no<>0 then prompt_for_esc('Can''t close file. File invalid.')
            else if incomplete then prompt_for_esc('File incomplete.');
{$I+}
end; { write_text_to_file }

