//
// Example location script for 2BrightSparks SyncBackPro: Game Saves.
//
// SBLang=Pascal
//
// http://www.2BrightSparks.com/
// November 2026
//
// Game Saves finds where the games on this PC keep their saved games and
// shows each one as a folder named after the game, so one profile backs up
// every game's saves:
//
//   \Minecraft\New World\level.dat
//   \Stardew Valley\Farm_123456789\...
//   \Portal 2\...                      (Steam Cloud saves)
//
// It looks in:
//
//   - Saved Games (C:\Users\<you>\Saved Games), a folder per game
//   - Documents\My Games, a folder per game
//   - Steam: the saves Steam keeps for each game (userdata), named after
//     the game
//   - Games made with Unreal Engine (%LOCALAPPDATA%\<Game>\Saved\SaveGames)
//     and Unity (%USERPROFILE%\AppData\LocalLow\<Company>\<Game>, the ones
//     that have a Player.log, which is itself left out)
//   - Well-known places of popular games that use none of those, e.g.
//     Minecraft, Stardew Valley, Factorio, The Sims 4, Baldur's Gate 3
//
// and in any folders you add on the Game Saves page of the profile setup.
// Environment variables work in those, e.g. %APPDATA%\MyGame\saves. Games
// you do not want can be left out (by the name shown) on the same page, and
// finding the games can be turned off to use only your own folders.
//
// Two games with the same name get (2), (3) and so on. A folder found twice
// is shown once. Folders that are junctions or symbolic links are not
// followed.
//
// Using it
// --------
// Make a new Backup profile that copies FROM Game Saves, with the path \, TO
// a folder such as D:\Game Saves\. Turn on versioning to keep older saves. A
// location script is always the destination of a profile, so SyncBack sets
// it up as "destination to source" for you.
//
// Restoring
// ---------
// Game Saves is read-only unless you tick "Allow restoring" on its page of
// the profile setup. Then a profile can copy TO it: make a second profile,
// a Backup from D:\Game Saves\ to Game Saves, and run it (or restore with the
// first profile) to put saves back where each game keeps them. Close the
// games first. A game's own folder (the top folders) cannot be made or
// removed.
//
// It needs no Insider Access.
//
var
  gFSO, gGames, gLoaded, gNames, gFolders;

const
  READ_ONLY = 'Game Saves is read-only (tick "Allow restoring" on its page of the profile setup to copy saves back)';

//
// This is a location script with a page in the profile setup
//
function Description(var ScriptType): String;
begin
  Result:='Game Saves';
  ScriptType:=SCRIPTTYPE_LOCATION + SCRIPTTYPE_CONFIG;
end;

function Install(Interactive);
begin
  Result:='';
end;

procedure Uninstall;
begin
end;

function FilesToExport(Interactive, Cnt);
begin
  Result:='';
end;

//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------

function ExpandEnv(s);
var
  Shell;
begin
  Shell:=CreateOleObject('WScript.Shell');
  Result:=Shell.ExpandEnvironmentStrings(s);
  Shell:=Unassigned;
end;

function Documents;
var
  Shell;
begin
  Shell:=CreateOleObject('WScript.Shell');
  Result:=IncludeTrailingPathDelimiter(Shell.SpecialFolders('MyDocuments'));
  Shell:=Unassigned;
end;

function CleanPath(P);
begin
  while (Pos('\\', P) > 0) do
    P:=ReplaceStr(P, '\\', '\');
  Result:=P;
end;

function IsRoot(P);
begin
  P:=CleanPath(P);
  Result:=(P = '') or (P = '\');
end;

// Folder attributes: a junction or symbolic link is a reparse point (1024)
function IsLink(Attrs);
begin
  Result:=((Attrs div 1024) mod 2) = 1;
end;

function IsDeviceName(N);
var
  B;
begin
  B:=UpperCase(N);
  if (Pos('.', B) > 0) then
    B:=Copy(B, 1, Pos('.', B) - 1);
  B:=Trim(B);
  Result:=(B = 'CON') or (B = 'PRN') or (B = 'AUX') or (B = 'NUL') or
    ((Length(B) = 4) and ((Copy(B, 1, 3) = 'COM') or (Copy(B, 1, 3) = 'LPT')) and
     (Copy(B, 4, 1) >= '0') and (Copy(B, 4, 1) <= '9'));
end;

// A game's name as a folder name: Halo: Reach -> Halo - Reach
function SafeName(s);
var
  i, c, r;
begin
  r:='';
  s:=ReplaceStr(s, ':', ' -');
  for i:=1 to Length(s) do begin
    c:=Copy(s, i, 1);
    if (Pos(c, '\/*?"<>|') > 0) or (Ord(c) < 32) then
      r:=r + ' '
    else
      r:=r + c;
  end;
  while (Pos('  ', r) > 0) do
    r:=ReplaceStr(r, '  ', ' ');
  r:=Trim(r);
  while (r <> '') and ((Copy(r, Length(r), 1) = '.') or (Copy(r, Length(r), 1) = ' ')) do
    r:=Copy(r, 1, Length(r) - 1);
  if (r <> '') and IsDeviceName(r) then
    r:=r + '_';
  Result:=r;
end;

// Files that are not saves
function LeftOut(Name);
var
  U;
begin
  U:=UpperCase(Name);
  Result:=(U = 'PLAYER.LOG') or (U = 'PLAYER-PREV.LOG') or (U = 'DESKTOP.INI');
end;

function Restoring;
begin
  Result:=(UpperCase(SBVariables.GetProperty('GameSavesRestore', 'N', FALSE)) = 'Y');
end;

//-----------------------------------------------------------------------------
// Finding the games: gGames has a line per game, <name> <tab> <folder\>
//-----------------------------------------------------------------------------

function GameName(i);
begin
  Result:=Copy(gGames[i], 1, Pos(#9, gGames[i]) - 1);
end;

function GameFolder(i);
begin
  Result:=Copy(gGames[i], Pos(#9, gGames[i]) + 1, Length(gGames[i]));
end;

procedure AddGame(Name, Folder);
var
  i, N, k, Skip, U;
begin
  Folder:=Trim(Folder);
  if (Folder = '') or not gFSO.FolderExists(Folder) then
    Exit;
  Folder:=IncludeTrailingPathDelimiter(gFSO.GetFolder(Folder).Path);
  N:=SafeName(Name);
  if (N = '') then
    Exit;

  // A folder found twice, or inside one already found, is shown once
  U:=UpperCase(Folder);
  for i:=0 to gFolders.Count - 1 do
    if (Pos(gFolders[i], U) = 1) or (Pos(U, gFolders[i]) = 1) then
      Exit;
  gFolders.Add(U);

  // Each game a different name (games left out keep theirs, so the names
  // of the others do not change)
  k:=1;
  Name:=N;
  while (gNames.IndexOf(UpperCase(N)) >= 0) do begin
    k:=k + 1;
    N:=Name + ' (' + IntToStr(k) + ')';
  end;
  gNames.Add(UpperCase(N));

  // Games you have asked to leave out
  Skip:=TStringList.Create;
  try
    Skip.StrictDelimiter:=TRUE;
    Skip.Delimiter:=';';
    Skip.DelimitedText:=SBVariables.GetProperty('GameSavesSkip', '', FALSE);
    for i:=0 to Skip.Count - 1 do
      if (UpperCase(Trim(Skip[i])) = UpperCase(N)) then
        Exit;
  finally
    Skip.Free;
  end;
  gGames.Add(N + #9 + Folder);
end;

// Every sub-folder of Dir as a game (Saved Games, My Games)
procedure AddEachFolder(Dir);
var
  Folder, Sub, SubEnum;
begin
  if not gFSO.FolderExists(Dir) then
    Exit;
  Folder:=gFSO.GetFolder(Dir);
  SubEnum:=TEnumVariant.Create(Folder.SubFolders);
  try
    while SubEnum.ForEach(Sub) do
      if not IsLink(Sub.Attributes) then
        AddGame(Sub.Name, Sub.Path);
  finally
    SubEnum.Free;
  end;
end;

// The value of "Key" on a line of a Steam .vdf or .acf file, e.g.
//   "name"		"Portal 2"
function VdfValue(Line, Key);
var
  s;
begin
  Result:='';
  s:=Trim(Line);
  if (Pos('"' + UpperCase(Key) + '"', UpperCase(s)) <> 1) then
    Exit;
  s:=Trim(Copy(s, Length(Key) + 3, Length(s)));
  if (Copy(s, 1, 1) = '"') and (Copy(s, Length(s), 1) = '"') then
    Result:=ReplaceStr(Copy(s, 2, Length(s) - 2), '\\', '\');
end;

// The name of Steam game AppID, from its appmanifest in any library
function SteamGameName(Libraries, AppID);
var
  i, L, j, F, V;
begin
  Result:='';
  L:=TStringList.Create;
  try
    for i:=0 to Libraries.Count - 1 do begin
      F:=Libraries[i] + 'steamapps\appmanifest_' + AppID + '.acf';
      if gFSO.FileExists(F) then begin
        L.Text:=ReadStringFromFile(F);
        for j:=0 to L.Count - 1 do begin
          V:=VdfValue(L[j], 'name');
          if (V <> '') then begin
            Result:=V;
            Exit;
          end;
        end;
      end;
    end;
  finally
    L.Free;
  end;
end;

// Steam Cloud saves: <Steam>\userdata\<user>\<app id>\remote
procedure AddSteam;
var
  Shell, Steam, Libraries, L, i, V, Users, UserEnum, User, AppEnum, App, Name, Skip;
begin
  Steam:='';
  try
    Shell:=CreateOleObject('WScript.Shell');
    Steam:=Shell.RegRead('HKCU\Software\Valve\Steam\SteamPath');
  except
    Steam:='';
  end;
  Shell:=Unassigned;
  Steam:=Trim(ReplaceStr(VarToStr(Steam), '/', '\'));
  if (Steam = '') or not gFSO.FolderExists(Steam + '\userdata') then
    Exit;
  Steam:=IncludeTrailingPathDelimiter(Steam);

  Libraries:=TStringList.Create;
  L:=TStringList.Create;
  try
    Libraries.Add(Steam);
    if gFSO.FileExists(Steam + 'steamapps\libraryfolders.vdf') then begin
      L.Text:=ReadStringFromFile(Steam + 'steamapps\libraryfolders.vdf');
      for i:=0 to L.Count - 1 do begin
        V:=VdfValue(L[i], 'path');
        if (V <> '') then
          Libraries.Add(IncludeTrailingPathDelimiter(V));
      end;
    end;

    // Not games: the Steam client (7), screenshots (760) and controller
    // settings (241100)
    Skip:=';7;760;241100;';
    Users:=gFSO.GetFolder(Steam + 'userdata').SubFolders;
    UserEnum:=TEnumVariant.Create(Users);
    try
      while UserEnum.ForEach(User) do begin
        AppEnum:=TEnumVariant.Create(User.SubFolders);
        try
          while AppEnum.ForEach(App) do
            if (Pos(';' + App.Name + ';', Skip) = 0) and gFSO.FolderExists(App.Path + '\remote') then begin
              Name:=SteamGameName(Libraries, App.Name);
              if (Name = '') then
                Name:='Steam app ' + App.Name;
              if (Users.Count > 1) then
                Name:=Name + ' (Steam user ' + User.Name + ')';
              AddGame(Name, App.Path + '\remote');
            end;
        finally
          AppEnum.Free;
        end;
      end;
    finally
      UserEnum.Free;
    end;
  finally
    L.Free;
    Libraries.Free;
  end;
end;

// Unreal Engine games: %LOCALAPPDATA%\<Game>\Saved\SaveGames
procedure AddUnreal;
var
  Dir, Folder, Sub, SubEnum;
begin
  Dir:=ExpandEnv('%LOCALAPPDATA%');
  if not gFSO.FolderExists(Dir) then
    Exit;
  Folder:=gFSO.GetFolder(Dir);
  SubEnum:=TEnumVariant.Create(Folder.SubFolders);
  try
    while SubEnum.ForEach(Sub) do
      if gFSO.FolderExists(Sub.Path + '\Saved\SaveGames') then
        AddGame(Sub.Name, Sub.Path + '\Saved\SaveGames');
  finally
    SubEnum.Free;
  end;
end;

// Unity games: %USERPROFILE%\AppData\LocalLow\<Company>\<Game> with a
// Player.log
procedure AddUnity;
var
  Dir, Folder, Company, CompanyEnum, Game, GameEnum;
begin
  Dir:=ExpandEnv('%USERPROFILE%\AppData\LocalLow');
  if not gFSO.FolderExists(Dir) then
    Exit;
  Folder:=gFSO.GetFolder(Dir);
  CompanyEnum:=TEnumVariant.Create(Folder.SubFolders);
  try
    while CompanyEnum.ForEach(Company) do begin
      GameEnum:=TEnumVariant.Create(Company.SubFolders);
      try
        while GameEnum.ForEach(Game) do
          if gFSO.FileExists(Game.Path + '\Player.log') or gFSO.FileExists(Game.Path + '\Player-prev.log') then
            AddGame(Game.Name, Game.Path);
      finally
        GameEnum.Free;
      end;
    end;
  finally
    CompanyEnum.Free;
  end;
end;

// Popular games that keep their saves somewhere of their own
procedure AddKnown;
var
  Docs;
begin
  Docs:=Documents;
  AddGame('Minecraft', ExpandEnv('%APPDATA%\.minecraft\saves'));
  AddGame('Minecraft (Bedrock)', ExpandEnv('%LOCALAPPDATA%\Packages\Microsoft.MinecraftUWP_8wekyb3d8bbwe\LocalState\games\com.mojang\minecraftWorlds'));
  AddGame('Stardew Valley', ExpandEnv('%APPDATA%\StardewValley\Saves'));
  AddGame('Factorio', ExpandEnv('%APPDATA%\Factorio\saves'));
  AddGame('Elden Ring', ExpandEnv('%APPDATA%\EldenRing'));
  AddGame('Dark Souls III', ExpandEnv('%APPDATA%\DarkSoulsIII'));
  AddGame('Baldur''s Gate 3', ExpandEnv('%LOCALAPPDATA%\Larian Studios\Baldur''s Gate 3\PlayerProfiles'));
  AddGame('The Sims 4', Docs + 'Electronic Arts\The Sims 4\saves');
  AddGame('The Witcher 3', Docs + 'The Witcher 3\gamesaves');
  AddGame('Grand Theft Auto V', Docs + 'Rockstar Games\GTA V\Profiles');
  AddGame('Red Dead Redemption 2', Docs + 'Rockstar Games\Red Dead Redemption 2\Profiles');
  AddGame('Don''t Starve Together', Docs + 'Klei\DoNotStarveTogether');
  AddGame('Euro Truck Simulator 2', Docs + 'Euro Truck Simulator 2\profiles');
end;

procedure FindGames;
var
  L, i, P;
begin
  if (VarToStr(gLoaded) = 'Y') then
    gGames.Free;
  gGames:=TStringList.Create;
  gLoaded:='Y';
  // Every name and folder found, games left out included
  gNames:=TStringList.Create;
  gFolders:=TStringList.Create;
  L:=TStringList.Create;
  try
    // Your own folders first, so their names win
    L.StrictDelimiter:=TRUE;
    L.Delimiter:=';';
    L.DelimitedText:=SBVariables.GetProperty('GameSavesOther', '', FALSE);
    for i:=0 to L.Count - 1 do begin
      P:=Pos('=', L[i]);
      if (P > 1) then
        AddGame(Trim(Copy(L[i], 1, P - 1)), ExpandEnv(Trim(Copy(L[i], P + 1, Length(L[i])))));
    end;

    if (UpperCase(SBVariables.GetProperty('GameSavesFind', 'Y', FALSE)) <> 'N') then begin
      AddKnown;
      AddEachFolder(ExpandEnv('%USERPROFILE%\Saved Games'));
      AddEachFolder(Documents + 'My Games');
      AddSteam;
      AddUnreal;
      AddUnity;
    end;
  finally
    L.Free;
    gFolders.Free;
    gNames.Free;
  end;
end;

// The game a location path is in (-1 if none: the root, or no such game)
function GameIndex(P);
var
  i, First;
begin
  Result:=-1;
  P:=CleanPath(P);
  while (Copy(P, 1, 1) = '\') do
    P:=Copy(P, 2, Length(P));
  if (Pos('\', P) > 0) then
    First:=Copy(P, 1, Pos('\', P) - 1)
  else
    First:=P;
  if (First = '') then
    Exit;
  for i:=0 to gGames.Count - 1 do
    if (UpperCase(GameName(i)) = UpperCase(First)) then begin
      Result:=i;
      Exit;
    end;
end;

// The real file or folder for a location path (blank for the root, or a
// game that is not there)
function RealOf(P);
var
  i, Rest;
begin
  Result:='';
  i:=GameIndex(P);
  if (i < 0) then
    Exit;
  P:=CleanPath(P);
  while (Copy(P, 1, 1) = '\') do
    P:=Copy(P, 2, Length(P));
  if (Pos('\', P) > 0) then
    Rest:=Copy(P, Pos('\', P) + 1, Length(P))
  else
    Rest:='';
  Result:=GameFolder(i) + Rest;
end;

// Is P a game's own (top) folder?
function IsGameFolder(P);
var
  s;
begin
  s:=CleanPath(P);
  while (Copy(s, 1, 1) = '\') do
    s:=Copy(s, 2, Length(s));
  while (Copy(s, Length(s), 1) = '\') do
    s:=Copy(s, 1, Length(s) - 1);
  Result:=(s <> '') and (Pos('\', s) = 0) and (GameIndex(P) >= 0);
end;

//-----------------------------------------------------------------------------
// Connecting
//-----------------------------------------------------------------------------

function LocConnect(MainThread);
begin
  gFSO:=CreateOleObject('Scripting.FileSystemObject');
  FindGames;
  Result:='';
end;

function LocDisconnect;
begin
  if (VarToStr(gLoaded) = 'Y') then
    gGames.Free;
  gLoaded:='';
  gFSO:=Unassigned;
  Result:='';
end;

function LocScanPrepare;
begin
  Result:='';
end;

function LocConnected;
begin
  Result:='';
end;

function LocReconnect;
begin
  Result:='';
end;

//-----------------------------------------------------------------------------
// Reading
//-----------------------------------------------------------------------------

function LocDirExists(FullPath);
var
  R;
begin
  Result:='';
  if IsRoot(FullPath) then
    Exit;
  R:=RealOf(FullPath);
  if (R = '') or not gFSO.FolderExists(R) then
    Result:='Folder does not exist';
end;

function LocFileExists(FullPath);
var
  R;
begin
  R:=RealOf(FullPath);
  if (R <> '') and gFSO.FileExists(R) and not LeftOut(ExtractFileName(R)) then
    Result:=''
  else
    Result:='File does not exist';
end;

function LocScanList(FullPath);
var
  i, R, Folder, Item, ItemEnum;
begin
  Result:='';
  if IsRoot(FullPath) then begin
    for i:=0 to gGames.Count - 1 do begin
      Folder:=gFSO.GetFolder(GameFolder(i));
      if not SBLocation.AddDirEx2(GameName(i), 16, Folder.DateLastModified, Folder.DateCreated, '') then
        Exit;
    end;
    Exit;
  end;

  R:=RealOf(FullPath);
  if (R = '') or not gFSO.FolderExists(R) then begin
    Result:='Folder does not exist';
    Exit;
  end;
  Folder:=gFSO.GetFolder(R);
  ItemEnum:=TEnumVariant.Create(Folder.SubFolders);
  try
    while ItemEnum.ForEach(Item) do
      if not IsLink(Item.Attributes) then
        if not SBLocation.AddDirEx2(Item.Name, Item.Attributes, Item.DateLastModified, Item.DateCreated, '') then
          Exit;
  finally
    ItemEnum.Free;
  end;
  ItemEnum:=TEnumVariant.Create(Folder.Files);
  try
    while ItemEnum.ForEach(Item) do
      if not LeftOut(Item.Name) then
        if not SBLocation.AddFileEx(Item.Name, '', VarToInt64(Item.Size), Item.Attributes,
          Item.DateLastModified, Item.DateCreated, '') then
          Exit;
  finally
    ItemEnum.Free;
  end;
end;

function LocGet(fromFName, toFName);
var
  R, Err;
begin
  R:=RealOf(fromFName);
  if (R = '') or not gFSO.FileExists(R) then begin
    Result:='File does not exist';
    Exit;
  end;
  Err:=CopyFile(R, toFName);
  if (Err = 0) then
    Result:=''
  else
    Result:=SysErrorMessage(Err);
end;

function LocCRC32(FullPath; var CRC32);
var
  R;
begin
  R:=RealOf(FullPath);
  if (R = '') or not gFSO.FileExists(R) then begin
    Result:='File does not exist';
    Exit;
  end;
  CRC32:=SBSystem.CRC32(R);
  Result:='';
end;

function LocGetAttributes(Filename; var Attrs);
var
  R;
begin
  Result:='';
  if IsRoot(Filename) then begin
    Attrs:=16;
    Exit;
  end;
  R:=RealOf(Filename);
  if (R <> '') and gFSO.FileExists(R) then
    Attrs:=gFSO.GetFile(R).Attributes
  else if (R <> '') and gFSO.FolderExists(R) then
    Attrs:=gFSO.GetFolder(R).Attributes
  else
    Result:='File or folder does not exist';
end;

function LocFreeSpace;
begin
  Result:=-1;
end;

//
// CAN_USEATTRIBUTES = 32, CAN_EXACTDATETIME = 64, CAN_CHANGEATTRIBUTES = 128,
// CAN_CHANGEDATETIME = 256, CAN_HAVEEMPTYPATH = 1024, CAN_USECRC32 = 262144
//
function LocAbilities;
begin
  Result:=CAN_USEATTRIBUTES + CAN_HAVEEMPTYPATH + CAN_USECRC32;
  if Restoring then
    Result:=Result + CAN_EXACTDATETIME + CAN_CHANGEATTRIBUTES + CAN_CHANGEDATETIME;
end;

//-----------------------------------------------------------------------------
// Writing (restoring): only with "Allow restoring" ticked
//-----------------------------------------------------------------------------

procedure ForceDir(D);
var
  P;
begin
  D:=ExcludeTrailingPathDelimiter(D);
  if (D = '') or DirectoryExists(D) then
    Exit;
  P:=ExtractFilePath(D);
  if (P <> '') and (ExcludeTrailingPathDelimiter(P) <> D) then
    ForceDir(P);
  CreateDir(D);
end;

function LocMakeDir(FullPath);
var
  R;
begin
  Result:='';
  if IsRoot(FullPath) then
    Exit;
  R:=RealOf(FullPath);
  if (R <> '') and gFSO.FolderExists(R) then
    Exit;
  if not Restoring then
    Result:=READ_ONLY
  else if (R = '') then
    Result:='Game Saves: there is no game called ' + Copy(CleanPath(FullPath), 2, Length(FullPath)) + ' on this PC'
  else begin
    ForceDir(R);
    if not gFSO.FolderExists(R) then
      Result:='Game Saves: cannot create the folder ' + R;
  end;
end;

function LocRemoveDir(FullPath);
var
  R, F;
begin
  Result:='';
  if not Restoring then begin
    Result:=READ_ONLY;
    Exit;
  end;
  if IsRoot(FullPath) or IsGameFolder(FullPath) then begin
    Result:='Game Saves: a game''s own folder cannot be removed';
    Exit;
  end;
  R:=RealOf(FullPath);
  if (R = '') or not gFSO.FolderExists(R) then
    Exit;
  F:=gFSO.GetFolder(R);
  if (F.Files.Count > 0) or (F.SubFolders.Count > 0) then begin
    Result:='Directory is not empty';
    Exit;
  end;
  if not RemoveDir(ExcludeTrailingPathDelimiter(R)) then
    Result:='Game Saves: cannot remove the folder ' + R;
end;

function LocRenameDir(FromPath, ToPath);
var
  F, T;
begin
  if not Restoring then begin
    Result:=READ_ONLY;
    Exit;
  end;
  if IsGameFolder(FromPath) or IsGameFolder(ToPath) or (GameIndex(FromPath) <> GameIndex(ToPath)) then begin
    Result:='Game Saves: a folder can only be moved inside the same game';
    Exit;
  end;
  F:=ExcludeTrailingPathDelimiter(RealOf(FromPath));
  T:=ExcludeTrailingPathDelimiter(RealOf(ToPath));
  if (F = '') or (T = '') or not RenameFile(F, T) then
    Result:='Game Saves: cannot move the folder ' + F + ' to ' + T
  else
    Result:='';
end;

function LocRenameFile(FromName, ToName);
var
  F, T;
begin
  if not Restoring then begin
    Result:=READ_ONLY;
    Exit;
  end;
  if (GameIndex(FromName) < 0) or (GameIndex(FromName) <> GameIndex(ToName)) then begin
    Result:='Game Saves: a file can only be moved inside the same game';
    Exit;
  end;
  F:=RealOf(FromName);
  T:=RealOf(ToName);
  if gFSO.FileExists(T) then
    gFSO.DeleteFile(T, TRUE);
  if not RenameFile(F, T) then
    Result:='Game Saves: cannot rename ' + F + ' to ' + T
  else
    Result:='';
end;

function LocDeleteFile(FullPath; var DoesNotExist);
var
  R;
begin
  Result:='';
  R:=RealOf(FullPath);
  DoesNotExist:=(R = '') or not gFSO.FileExists(R);
  if DoesNotExist then
    Exit;
  if not Restoring then begin
    Result:=READ_ONLY;
    Exit;
  end;
  try
    gFSO.DeleteFile(R, TRUE);
  except
    Result:='Game Saves: cannot delete ' + R;
  end;
end;

function LocSetModDateTime(FullPath, ModDateTime);
var
  R;
begin
  if not Restoring then begin
    Result:=READ_ONLY;
    Exit;
  end;
  Result:='';
  R:=RealOf(FullPath);
  if (R <> '') and gFSO.FileExists(R) and (ModDateTime > 1.0) then
    SBSystem.SetLastModDateTime(R, ModDateTime);
end;

function LocSetCreateDateTime(FullPath, CreateDateTime);
var
  R;
begin
  if not Restoring then begin
    Result:=READ_ONLY;
    Exit;
  end;
  Result:='';
  R:=RealOf(FullPath);
  if (R <> '') and gFSO.FileExists(R) and (CreateDateTime > 1.0) then
    SBSystem.SetCreateDateTime(R, CreateDateTime);
end;

function LocSetAttributes(Filename, Attrs);
var
  R;
begin
  if not Restoring then begin
    Result:=READ_ONLY;
    Exit;
  end;
  Result:='';
  R:=RealOf(Filename);
  // Only read-only, hidden, system and archive
  if (R <> '') and gFSO.FileExists(R) and (Attrs >= 0) then
    gFSO.GetFile(R).Attributes:=Attrs and 39;
end;

//
// Copy a save back. With a safe copy it goes in under a temporary name, and
// SyncBack renames it (LocRenameFile) once it is there.
//
function LocPutEx(fromFName, toFName, fromAttrs, fromDateTime, fromCreateDateTime, fromFileSize, fromNTFSSec, DoSafeCopy; var SafeFName);
var
  Target, R, Err;
begin
  SafeFName:='';
  if not Restoring then begin
    Result:=READ_ONLY;
    Exit;
  end;
  // \Game\file or deeper: not in the root
  if (GameIndex(toFName) < 0) or (Pos('\', Copy(CleanPath(toFName), 2, Length(toFName))) = 0) then begin
    Result:='Game Saves: files can only go inside a game''s folder';
    Exit;
  end;
  if DoSafeCopy then begin
    Target:=toFName + '.$$$';
    SafeFName:=Target;
  end else
    Target:=toFName;
  R:=RealOf(Target);
  if not gFSO.FolderExists(ExtractFilePath(R)) then begin
    Result:='Folder does not exist';
    Exit;
  end;
  if gFSO.FileExists(R) then
    gFSO.GetFile(R).Attributes:=0;
  Err:=CopyFile(fromFName, R);
  if (Err <> 0) then begin
    Result:=SysErrorMessage(Err);
    Exit;
  end;
  if (fromDateTime > 1.0) then
    SBSystem.SetLastModDateTime(R, fromDateTime);
  Result:='';
end;

//-----------------------------------------------------------------------------
// The Game Saves page in the profile setup
//-----------------------------------------------------------------------------

// Only in profiles that use Game Saves as their location
function ConfigWantSetupNode(IsGroup);
begin
  Result:=not IsGroup and SBProfile.UsesScript;
end;

function ConfigNodeCaption;
begin
  Result:='Game Saves';
end;

function ConfigCanRevert;
begin
  Result:=TRUE;
end;

function ConfigCanClose;
begin
  Result:=TRUE;
end;

procedure ConfigFactoryDefaults;
begin
  SBVariables.DeleteProperty('GameSavesFind');
  SBVariables.DeleteProperty('GameSavesOther');
  SBVariables.DeleteProperty('GameSavesSkip');
  SBVariables.DeleteProperty('GameSavesRestore');
end;

procedure ConfigSetupDisplay;
begin
  SBProfile.AddLabel('The saved games of every game on this PC, a folder per game.', 20);
  SBProfile.AddCheckbox('Find the games (Saved Games, My Games, Steam, Unreal and Unity games, and well-known games)', 1);
  SBProfile.AddEdit('Other save folders, as Game=folder;Game=folder (e.g. My Game=%APPDATA%\MyGame\saves)', 4000, FALSE, FALSE, 2);
  SBProfile.AddEdit('Games to leave out, separated by ;', 4000, FALSE, FALSE, 3);
  SBProfile.AddCheckbox('Allow restoring (copying saves back to the games). Close the games first.', 4);
end;

function ConfigLoadSettings;
begin
  Result:='';
  SBProfile.SetCheckbox(UpperCase(SBVariables.GetProperty('GameSavesFind', 'Y', FALSE)) <> 'N', 1);
  SBProfile.SetEdit(SBVariables.GetProperty('GameSavesOther', '', FALSE), 2);
  SBProfile.SetEdit(SBVariables.GetProperty('GameSavesSkip', '', FALSE), 3);
  SBProfile.SetCheckbox(Restoring, 4);
end;

// Store a setting in the profile. One that has never been set and is still
// the default is left unset, so just looking at this page and pressing Cancel
// does not count as a change to the profile.
procedure SaveSetting(Name, Value, Default);
begin
  if (SBVariables.GetProperty(Name, '!NOTSET!', FALSE) = '!NOTSET!') and (Value = Default) then
    Exit;
  SBVariables.SetProperty(Name, Value);
end;

function YN(B);
begin
  if B then
    Result:='Y'
  else
    Result:='N';
end;

function ConfigSaveSettings(Silent);
var
  L, i;
begin
  Result:='';
  L:=TStringList.Create;
  try
    L.StrictDelimiter:=TRUE;
    L.Delimiter:=';';
    L.DelimitedText:=Trim(SBProfile.GetEdit(2));
    for i:=0 to L.Count - 1 do
      if (Trim(L[i]) <> '') and (Pos('=', L[i]) < 2) then begin
        Result:='Game Saves: write each other save folder as Game=folder, e.g. My Game=%APPDATA%\MyGame\saves';
        Exit;
      end;
  finally
    L.Free;
  end;
  SaveSetting('GameSavesFind', YN(SBProfile.GetCheckbox(1)), 'Y');
  SaveSetting('GameSavesOther', Trim(SBProfile.GetEdit(2)), '');
  SaveSetting('GameSavesSkip', Trim(SBProfile.GetEdit(3)), '');
  SaveSetting('GameSavesRestore', YN(SBProfile.GetCheckbox(4)), 'N');
end;

procedure ConfigUpdateConditionals;
begin
end;
