/* 
    Backs up the current file to the directory specified by the BAKDIR
    environment variable when ME is exiting.
    This allows you to avoid messing up your root directory with .BAK
    files. Remember to alter the CONFIG.ME file so that it no longer creates 
   .BAK files upon exit
   
    Written by Jim Mochel of The Oakland Group
*/

init()
{
  add_hook(1, "backup");		/* hook called when ME exits */
}

backup()
{
  string dir;
  string file;
  int posn;

  dir = getenv("BAKDIR");	/* Get the directory for .BAK files */

  /*
   * If the directory does not end with a \ , add it on to the directory 
   */
  if ((posn = search_string(dir, "\\$")) <= 0)
    dir = strcat(dir, "\\");

  /*
   * If the filename has an extension, alter it to .BAK 
   */
  posn = index(filename(), ".");

  if (posn > 0)
    file = strcat(substr(filename(), 1, posn - 1), ".BAK");
  else
    file = strcat(filename(), ".BAK");

  /*
   * Create the full filename including path 
   */
  file = strcat(dir, file);

  /*
   * Save the backup file 
   */
  writefile(file);
}
