persistidents 0

checkinit mapstartalways [numAutoSaves = 0; autoSaveCheck]
checkinit onNewMap [numAutoSaves = 0; autoSaveCheck]
check2init autosavemap 0           // Autosavemap system disabled by default
check2init timeBetAutoSaves 300000 // Autosave once every 5 minutes.
check2init numAutoSaveBackups 3    // Make a map .bak every 3 autosaves (15 minutes) by default

const autoSaveCheck [ if $autosavemap [ sleep $timeBetAutoSaves doAutoSave ] ]

const execAutoSave [
  ++ numAutoSaves
  oldmapbackups = $mapbackupsonsave
  if (|| (!= $numAutoSaveBackups $numAutoSaves) (= $numAutoSaveBackups 0)) [ mapbackupsonsave 0 ] [ numAutoSaves = 0 ] // Temporarily turn off map backups to avoid clutter.
  savemap (curmap 1)
  mapbackupsonsave $oldmapbackups
  echo (blue)The map was automatically saved. (white)Next auto-save in (divf $timeBetAutoSaves 60000) minutes.
]

const doAutoSave [
  if $autosavemap [
    if (&& (! (strstr $defaultmaps (curmap 1))) (strlen (curmap 1))) [
      if $editing execAutoSave [
        if (= $gamemode (modenum coop)) execAutoSave
      ]
    ]
  ]
  autoSaveCheck
]

addListOnQuit [autoSaveCheck execAutoSave doAutoSave numAutoSaves oldmapbackups]

persistidents 1
