MODULE MFILECPY;

   FROM SeqIO IMPORT
      FILE, FileState, Open, Create, Close, Read, Write, EOF;

   FROM Terminal IMPORT
      ReadString, WriteLn, WriteString;

   FROM Strings IMPORT
      STRING;
   

   VAR
      inFILE, outFILE : FILE;
      name, BAKname : STRING;   (* file names *)
      c : CHAR;


   PROCEDURE MakeBAK (in : STRING; VAR out : STRING; tag : STRING);

      VAR
         i, j : CARDINAL;
      
      BEGIN
         i := 0;
         WHILE (in[i] # 0C) AND (in[i] # '.') DO
            out[i] := in[i];
            INC (i);
         END;

         j := 0;
         WHILE tag[j] # 0C DO
            out[i] := tag[j];
            INC (i);   INC (j);
         END;

         out[i] := 0C;   (* add NULL terminator *)
      END MakeBAK;      
            


BEGIN
   WriteString ('File Backup Utility');   WriteLn;   WriteLn;
   WriteString ('Enter filename: ');
   ReadString (name);   WriteLn;
   MakeBAK (name, BAKname, '.bak');

   IF Create (outFILE, BAKname) = FileOK THEN
      IF Open (inFILE, name) = FileOK THEN
         WHILE NOT EOF (inFILE) DO
            Read (inFILE, c);
            Write (outFILE, c);
         END;

         IF (Close (inFILE) <> FileOK) OR (Close (outFILE) <> FileOK) THEN
            WriteString ('Error closing files...');   WriteLn;
         ELSE
            WriteString (BAKname);   WriteString (' completed.');   WriteLn;
         END;
      ELSE
         IF Close (outFILE) <> FileOK THEN
            (* do nothing *)
         END;
         WriteString ('Error creating new file...');   WriteLn;
      END;
   ELSE
      WriteString ('Error opening file...');   WriteLn;
   END;
END MFILECPY.
