
program two_side(input, output);

const
  MaxLines = 66;
  MaxColumns = 132;
type
  vstring = varying [MaxColumns] of char;
  page_ptr = ^pages;
  pages = record
            next : page_ptr;
            nlines : integer;
            lines : array [1..MaxLines] of vstring;
	  end;

var
  in_file, front_file, back_file : vstring;
  ifile, ffile, bfile : text;
  first_ptr, cur_ptr : page_ptr;
  i : integer;

procedure OpenFiles;
begin
  writeln('      Two Sided Print');
  write('Input file :');
  readln(in_file);
  open(ifile, in_file, old, default := '.lis');
  reset(ifile);
  i := index(in_file, '.');
  if i = 0 then i := length(in_file) else i := pred(i);
  front_file := substr(in_file, 1, i);
  back_file := front_file + '.bk';
  front_file := front_file + '.frt';
  writeln(' Files ', front_file, ' and ', back_file, ' will be created.');
  open(ffile, front_file, new);
  rewrite(ffile);
  open(bfile, back_file, new);
  rewrite(bfile);
end;

procedure NewHead( var ptr : page_ptr );
var
  sptr : page_ptr;
begin
  sptr := ptr;
  new(ptr);
  ptr^.next := sptr;
end;

procedure CreateList;
const
  ff = chr(12);
var
  n : integer;
  front, eop : boolean;
  l : vstring;
begin
  cur_ptr := nil;
  eop := true;
  front := true;
  n := 0;
  while not(eof(ifile)) do begin
    readln(ifile, l);
    n := succ(n);
    if front then writeln(ffile, l)
    else begin
      if eop then NewHead( cur_ptr );
      cur_ptr^.lines[n] := l;
    end;
    eop := (n>=MaxLines) or (index(l, ff)>0);
    if eop then begin
      if not front then cur_ptr^.nlines := n;
      n := 0;
      front := not front;
    end;
  end;
  if not(eop) and not(front) then cur_ptr^.nlines := n;
  if (front <> eop) then begin
    NewHead(cur_ptr);
    cur_ptr^.lines[31] := '                       This page intentionally left blank.';
    cur_ptr^.lines[63] := ff;
    cur_ptr^.nlines := 63;
  end;
  close(ifile);
  close(ffile);
end;

procedure CreateBack;
begin
  while cur_ptr <> nil do with cur_ptr^ do begin
    for i := 1 to nlines do writeln(bfile, lines[i]);
    cur_ptr := next;
  end;
  close(bfile);
end;

begin
  OpenFiles;
  CreateList;
  CreateBack;
end.
