// NB: as of SCS v33.5 SFO needs the ini system to have been installed already (from lib_ini)

ACTION_IF !VARIABLE_IS_SET sfo_installed BEGIN

  OUTER_SET sfo_installed=1


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Sanity check for AUTO_EVAL_STRINGS
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 OUTER_SPRINT var testers
 OUTER_SPRINT players var
 ACTION_IF !"%%players%%" STRING_EQUAL testers BEGIN
      FAIL "AUTO_EVAL_STRINGS is not set (you need to include it in your tp2 preamble to use SFO)"
 END



   //////////////////////////////////////////////////////////////
   /// set the default variables if they're not set already
   //////////////////////////////////////////////////////////////

   ACTION_IF !VARIABLE_IS_SET external_loc BEGIN
      OUTER_SPRINT external_loc weidu_external
   END

   ACTION_IF !VARIABLE_IS_SET tra_base BEGIN
      OUTER_SPRINT tra_base lang
   END

   ACTION_IF !VARIABLE_IS_SET rel_iconv_path BEGIN
      OUTER_SPRINT rel_iconv_path "lang/iconv"
   END

   ACTION_IF !VARIABLE_IS_SET base_language BEGIN
      OUTER_SPRINT base_language english
   END

   //////////////////////////////////////////////////////////////
   /// make the external folders
   //////////////////////////////////////////////////////////////

   MKDIR "%external_loc%"
   MKDIR "%external_loc%/workspace"
   MKDIR "%external_loc%/workspace/ssl_out"
   MKDIR "%external_loc%/data/%MOD_FOLDER%"
   MKDIR "%external_loc%/markers"
   MKDIR "%external_loc%/lang"
   MKDIR "%external_loc%/lang/%MOD_FOLDER%"

   ACTION_IF !FILE_EXISTS "%external_loc%/readme.txt" BEGIN
      COPY + "%MOD_FOLDER%/lib/resource/weidu_external_readme.txt" "%external_loc%/readme.txt"
   END

   //////////////////////////////////////////////////////////////
   /// Set variables for the external locations
   //////////////////////////////////////////////////////////////

   OUTER_SPRINT workspace "%external_loc%/workspace"
   OUTER_SPRINT data_loc_root "%external_loc%/data"
   OUTER_SPRINT data_loc "%external_loc%/data/%MOD_FOLDER%"
   OUTER_SPRINT marker_loc "%external_loc%/markers"
   OUTER_SPRINT ext_lang_loc "%external_loc%/lang/%MOD_FOLDER%"



///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Set default values of control parameters
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 ACTION_IF !VARIABLE_IS_SET ssl_loc BEGIN
      OUTER_SPRINT ssl_loc "ssl"
 END
 ACTION_IF !VARIABLE_IS_SET sfo_loc BEGIN
      OUTER_SPRINT sfo_loc "sfo"
 END
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Get the debug variable from ini; run silent if it's set to zero
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

LAF check_ini STR_VAR ini="debug_variable" RET debug_variable=value END
ACTION_IF debug_variable=0 BEGIN SILENT END

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Set defaults for component_loc and local_loc
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  OUTER_SPRINT ~component_loc~ ~~
  OUTER_SPRINT ~local_loc~ ~~

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////               
/////////////              Define some symbols
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

OUTER_SPRINT ~percentage~ ~%~
OUTER_SPRINT ~atsymbol~ ~@~
OUTER_SPRINT ~tilde~ "~"
OUTER_SPRINT ~minus_one~ "-1"
OUTER_SPRINT ~arrow~ ~=>~

<<<<<<<< .../stratagems-inline/blank
>>>>>>>>

OUTER_SPRINT former "0"
ACTION_FOR_EACH val IN z y x w v u t s r q p o n m l k j i h g f e d c b a 9 8 7 6 5 4 3 2 1 0 BEGIN
    OUTER_SPRINT $alphanumeric_next("%val%") "%former%"
    ACTION_TO_UPPER val
    ACTION_TO_UPPER former
    OUTER_SPRINT $alphanumeric_next("%val%") "%former%"
    OUTER_SPRINT former "%val%"
END

///////////////////////////////////////////////////
// check what install we're running on
///////////////////////////////////////////////////

  ACTION_IF debug_variable=3 BEGIN
     PRINT "checking for game type: press a key to continue"
     ACTION_READLN blook
     SILENT
  END

  OUTER_SET enhanced_edition = ( GAME_IS ~bgee bg2ee eet iwdee~ ? 1 : 0)
  OUTER_SET is_bg1 = ( GAME_IS ~bgee tutu tutu_totsc bgt eet~ ? 1 : 0)
  OUTER_SET is_bg2 = ( GAME_IS ~tutu tutu_totsc bgee iwdee~ ? 0 : 1)
  OUTER_SET is_iwd = ( GAME_IS iwdee ? 1 : 0)
  OUTER_SET is_tutu = ( GAME_IS ~tutu tutu_totsc~ ? 1 : 0)
  OUTER_SET is_eet = ( GAME_IS ~eet~ ? 1 : 0)

  OUTER_SET has_sod = ( GAME_INCLUDES ~sod~ ? 1 : 0)
  OUTER_SET has_tob = ( GAME_INCLUDES ~tob~ ? 1 : 0)
  OUTER_SET has_totsc = ( GAME_INCLUDES ~totsc~ ? 1 : 0)

  ACTION_IF !VARIABLE_IS_SET tutu_var BEGIN
     ACTION_IF is_tutu BEGIN
        OUTER_SPRINT tutu_var "_"
     END ELSE BEGIN
        OUTER_SPRINT tutu_var ""
     END
  END
  
  ACTION_IF GAME_IS "eet" BEGIN
     OUTER_SPRINT eet_var "_"
  END ELSE BEGIN
     OUTER_SPRINT eet_var ""
  END

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// a few resource fixes
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// correct missing section in kensai clab file
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  ACTION_IF debug_variable=3 BEGIN
     PRINT "Fixing KENSAI: press a key to continue"
     ACTION_READLN blook
     SILENT
  END

COPY_EXISTING clabfi04.2da override
   // diagnostic: can we read entry 40 from the second row with at least 10 entries?
   PATCH_SILENT
   PATCH_TRY
      READ_2DA_ENTRY 1 40 10 blah
   WITH DEFAULT
      SET_2DA_ENTRY 1 39 40 "**** ****"
      PRETTY_PRINT_2DA
   END
BUT_ONLY

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Some IDS entries are present on some but not all versions of the game
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////


  ACTION_IF debug_variable=3 BEGIN
     PRINT "systematising ids files: press a key to continue"
     ACTION_READLN blook
     SILENT
  END

ACTION_IF !FILE_EXISTS "override/soundoff.ids" BEGIN
   COPY_EXISTING soundoff.ids override
END

ACTION_DEFINE_ASSOCIATIVE_ARRAY soundoff_ids_missing BEGIN
   9=>BATTLE_CRY
   10=>BATTLE_CRY2
   11=>BATTLE_CRY3
   12=>BATTLE_CRY4
   13=>BATTLE_CRY5
END

ACTION_PHP_EACH soundoff_ids_missing AS code=>name BEGIN
      ACTION_IF !FILE_CONTAINS_EVALUATED ("override/soundoff.ids" "%code%[ %TAB%]+%name%") BEGIN
         APPEND "soundoff.ids" "%code% %name%"
      END
END

ACTION_IF enhanced_edition BEGIN
  ACTION_DEFINE_ASSOCIATIVE_ARRAY object_ids_missing BEGIN
      94 => LastKilled
      95 => NearestAllyOf
      96 => SecondNearestAllyOf
      97 => ThirdNearestAllyOf
      98 => FourthNearestAllyOf
      99 => FifthNearestAllyOf
      100 => SixthNearestAllyOf
      101 => SeventhNearestAllyOf
      102 => EighthNearestAllyOf
      103 => NinthNearestAllyOf
      104 => TenthNearestAllyOf
      105 => FarthestEnemyOf
      106 => SecondFarthestEnemyOf
      107 => ThirdFarthestEnemyOf
      108 => FourthFarthestEnemyOf
      109 => FifthFarthestEnemyOf
      110 => SixthFarthestEnemyOf
      111 => SeventhFarthestEnemyOf
      112 => EighthFarthestEnemyOf
      113 => NinthFarthestEnemyOf
      114 => TenthFarthestEnemyOf
  END
  ACTION_PHP_EACH object_ids_missing AS code=>name BEGIN
      ACTION_IF !FILE_CONTAINS_EVALUATED ("override/object.ids" "%code%[ %TAB%]+%name%") BEGIN
         APPEND "object.ids" "%code% %name%"
      END
  END

END

ACTION_IF !FILE_EXISTS "override/spell.ids" BEGIN
       COPY_EXISTING spell.ids override
END

ACTION_DEFINE_ASSOCIATIVE_ARRAY spell_ids_missing BEGIN
   4611=>DRUID_SHAPESHIFT_BROWNBEAR
   4612=>DRUID_SHAPESHIFT_WOLF
   4613=>DRUID_SHAPESHIFT_BLACKBEAR    
   4632=>AVENGER_SHAPESHIFT_SWORDSPIDER
   4633=>AVENGER_SHAPESHIFT_BABYWYVERN
   4634=>AVENGER_SHAPESHIFT_FIRESALAMANDER
   2490=>WIZARD_POLYMORPH_NATURAL_FORM
   2491=>DRUID_SHAPESHIFT_NATURAL_FORM
   2493=>WIZARD_POLYMORPH_FLIND
   2494=>WIZARD_POLYMORPH_OGRE
   2495=>WIZARD_POLYMORPH_SPIDER
   2496=>WIZARD_POLYMORPH_MUSTARD_JELLY
   2497=>WIZARD_POLYMORPH_BROWN_BEAR
   2498=>WIZARD_POLYMORPH_BLACK_BEAR
   2499=>WIZARD_POLYMORPH_WOLF
   4732=>HELM_TRUE_SIGHT
   3101=>INNATE_CURE_LIGHT_WOUNDS
   3102=>INNATE_SLOW_POISON
   3103=>INNATE_DRAW_UPON_HOLY_MIGHT
   3104=>INNATE_LARLOCHS_MINOR_DRAIN
   3105=>INNATE_HORROR
   3106=>INNATE_VAMPIRIC_TOUCH
   4212=>PALADIN_DETECT_EVIL
   4213=>PALADIN_PROTECTION_FROM_EVIL
   4721=>TALOS_STORMSHIELD
   4722=>TALOS_LIGHTNING_BOLT
   2921=>WIZARD_IMPROVED_ALACRITY
   2222=>WIZARD_CHAOS_SHIELD
   2723=>WIZARD_IMPROVED_CHAOS_SHIELD
   1718=>CLERIC_SYMBOL_STUN
   1719=>CLERIC_SYMBOL_DEATH
   3996=>TANARI_DEATH_GAZE
   3997=>TANARI_VAMPIRIC_TOUCH
   3998=>TANARI_SILENCE
   3999=>TANARI_PARALYZE
   3701=>DEATHKNIGHT_FIREBALL
   2931=>SUCCUBUS_TELEPORT
   2985=>RED_HOLY_MIGHT
   3890=>DEMON_FEAR
END
ACTION_IF GAME_IS iwdee BEGIN
   ACTION_DEFINE_ASSOCIATIVE_ARRAY spell_ids_missing BEGIN
      1716=>CLERIC_SYMBOL_HOPELESSNESS
      1714=>CLERIC_SYMBOL_PAIN
      3137=>BEHOLDER_ANTIMAGIC_RAY
      3141=>BEHOLDER_CHARM_PERSON
      3142=>BEHOLDER_SLEEP
      3143=>BEHOLDER_FLESH_TO_STONE
      3144=>BEHOLDER_DISINTEGRATE
      3145=>BEHOLDER_FEAR
      3146=>BEHOLDER_SLOW
      3147=>BEHOLDER_CAUSE_SERIOUS_WOUNDS
      3148=>BEHOLDER_DEATH_RAY
   END
END
ACTION_PHP_EACH spell_ids_missing AS code=>name BEGIN
      ACTION_IF !FILE_CONTAINS_EVALUATED ("override/spell.ids" "%code%[ %TAB%]+%name%") BEGIN
         APPEND "spell.ids" "%code% %name%"
      END
END


ACTION_IF enhanced_edition BEGIN
 ACTION_DEFINE_ASSOCIATIVE_ARRAY spell_ids_missing_ee BEGIN
   4238=>SUN_SOUL_FLAMING_FISTS
   4103=>BLACKGUARD_AURA_OF_DESPAIR
   4935=>BLACKGUARD_SUMMON_FALLEN_DEVA
 END
 ACTION_PHP_EACH spell_ids_missing_ee AS code=>name BEGIN
      ACTION_IF !FILE_CONTAINS_EVALUATED ("override/spell.ids" "%code%[ %TAB%]+%name%") BEGIN
         APPEND "spell.ids" "%code% %name%"
      END
 END
 
 // do a few systematic fixes:
 // remove IWDification/IWDEE non-BG2-style SYMBOLS
 // eliminate M&G's pathological WIZARD_ references to SPCL spells

 COPY_EXISTING "spell.ids" override
     REPLACE_TEXTUALLY "SYMBOL_OF_" "SYMBOL_"
     SET index=0
     REPLACE_EVALUATE
     "\(4[0-9][0-9][0-9]\) +\(WIZARD\|CLERIC\)_.*"
     BEGIN
       SET index +=1
     END
     "%MATCH1% BROKEN_REFERENCE_%index%"
 BUT_ONLY


 // don't sort it, because (a) sorting spell.ids takes nontrivial time, and (b) we'll do it in DS anyway

END
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// some third-party mods unhelpfully map WIZARD_DISPEL_MAGIC to SPWI326; change this back
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  ACTION_IF debug_variable=3 BEGIN
     PRINT "Remapping DISPEL_MAGIC: press a key to continue"
     ACTION_READLN blook
     SILENT
  END

ACTION_IF enhanced_edition BEGIN
  COPY_EXISTING spell.ids override
          REPLACE_TEXTUALLY "23[0-9][0-9] +WIZARD_DISPEL_MAGIC" "2302 WIZARD_DISPEL_MAGIC"
  BUT_ONLY
END

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// in case Fixpack hasn't already done it, disable the 0-byte items & broken areas (we do this here for the benefit of the count section)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  ACTION_IF debug_variable=3 BEGIN
     PRINT "Disabling broken stuff: press a key to continue"
     ACTION_READLN blook
     SILENT
  END


ACTION_FOR_EACH bad IN "iplot01k.itm" "iplot04g.itm" "iplot04h.itm" "iplot04i.itm" "xr2400.are" "xr2600.are" BEGIN
  ACTION_IF FILE_EXISTS_IN_GAME "%bad%" BEGIN
   ACTION_TRY
       COPY_EXISTING "%bad%" override
            READ_BYTE 0x0 0
       BUT_ONLY
   WITH DEFAULT
       DISABLE_FROM_KEY "%bad%"
   END
  END
END


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Determine status of auto-built functions
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

ACTION_IF FILE_EXISTS "%MOD_FOLDER%/%sfo_loc%/SFO_autofunc.tpa" BEGIN
   INCLUDE "%MOD_FOLDER%/%sfo_loc%/SFO_autofunc.tpa"
   OUTER_SET SFO_reserved_build_function_control=2
END ELSE BEGIN
   OUTER_SET SFO_reserved_build_function_control=1
END


///////////////////////////////////////////////////
// include core function library
///////////////////////////////////////////////////

  ACTION_IF debug_variable=3 BEGIN
     PRINT "SFO setup done, starting core library install (general files): press a key to continue"
     ACTION_READLN blook
     SILENT
  END
  ACTION_BASH_FOR ~%MOD_FOLDER%/%sfo_loc%/general~ ~lib_.*\.tpa~ BEGIN
         ACTION_IF "%BASH_FOR_EXT%" STRING_EQUAL_CASE TPA BEGIN
			//PRINT "%BASH_FOR_RES%"
			INCLUDE ~%MOD_FOLDER%/%sfo_loc%/general/%BASH_FOR_RES%.tpa~
         END
  END

///////////////////////////////////////////////////
// include file-specific function library
///////////////////////////////////////////////////

  ACTION_IF debug_variable=3 BEGIN
     PRINT "Continuing core library install (filetype-specific files): press a key to continue"
     ACTION_READLN blook
     SILENT
  END
  ACTION_BASH_FOR ~%MOD_FOLDER%/%sfo_loc%/filetype~ ~lib_.*\.tpa~ BEGIN
         ACTION_IF "%BASH_FOR_EXT%" STRING_EQUAL_CASE TPA BEGIN
			 INCLUDE ~%MOD_FOLDER%/%sfo_loc%/filetype/%BASH_FOR_RES%.tpa~
         END
  END


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// If appropriate, copy over autofunc library
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

ACTION_IF !FILE_EXISTS "%MOD_FOLDER%/%sfo_loc%/SFO_autofunc.tpa" BEGIN
   ACTION_IF FILE_EXISTS "%workspace%/SFO_autofunc.tpa" BEGIN
      COPY + "%workspace%/SFO_autofunc.tpa" "%MOD_FOLDER%/%sfo_loc%/SFO_autofunc.tpa"
   END
END
 
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Initialise SSL variables
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

OUTER_SPRINT ~sslvariables~ ~%percentage%MOD_FOLDER%percentage%=%MOD_FOLDER%&%percentage%tutu_var%percentage%=%tutu_var%~
OUTER_SPRINT ssllibrary ""

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Define hotkey code
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  ACTION_FOR_EACH hotkey IN A B C D E F G H I J K L M N O P Q R S T U V W X Y Z BEGIN
     LAF check_ini INT_VAR silent=1  STR_VAR ini="hot_key_%hotkey%" RET value END
     ACTION_IF "%value%" STRING_EQUAL_CASE "0" BEGIN
            OUTER_SPRINT "hot_key_%hotkey%" "%hotkey%"
     END ELSE BEGIN
            OUTER_SPRINT "hot_key_%hotkey%" "%value%"
     END
  END

  DEFINE_PATCH_FUNCTION ssl_hotkey_swap BEGIN
     REPLACE_EVALUATE "HotKey(\([A-Z]\))" 
     BEGIN
         SPRINT value EVAL "%hot_key_%MATCH1%%"
     END
     ~HotKey(%value%)~
  END

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Define swap code to move between EE and vanilla SSL
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  DEFINE_PATCH_FUNCTION ssl_ee_to_vanilla  BEGIN
     // SPLSTATE to ToBeX extended stats
     REPLACE_TEXTUALLY "!CheckSpellState(\([^,]*\),\([^)]*\))" "CheckStat(\1,0,\2)"
     REPLACE_TEXTUALLY "CheckSpellState(\([^,]*\),\([^)]*\))" "CheckStatGT(\1,0,\2)"
     // vanilla doesn't have RunAwayFromNoLeaveArea
     REPLACE_TEXTUALLY RunAwayFromNoLeaveArea RunAwayFrom
     REPLACE_TEXTUALLY NinthFarthestEnemyOf NearestEnemyOf
     REPLACE_TEXTUALLY EighthFarthestEnemyOf NearestEnemyOf
     REPLACE_TEXTUALLY SeventhFarthestEnemyOf NearestEnemyOf
     REPLACE_TEXTUALLY SixthFarthestEnemyOf NearestEnemyOf
     REPLACE_TEXTUALLY FifthFarthestEnemyOf SecondNearestEnemyOf
     REPLACE_TEXTUALLY FourthFarthestEnemyOf ThirdNearestEnemyOf
     REPLACE_TEXTUALLY ThirdFarthestEnemyOf FourthNearestEnemyOf
     REPLACE_TEXTUALLY SecondFarthestEnemyOf FifthNearestEnemyOf
     REPLACE_TEXTUALLY FarthestEnemyOf SixthNearestEnemyOf
     REPLACE_TEXTUALLY "NearestAllyOf(Myself)" "NearestMyGroupOfType([0.0])"
     REPLACE_TEXTUALLY "NightmareModeOn()" "False()"


  END
  ACTION_IF debug_variable=3 BEGIN
     PRINT "SFO installed: press a key to continue"
     ACTION_READLN blook
     SILENT
  END



END
VERBOSE



