#==============================================================================|
#  ** Script Info                                                              |
#------------------------------------------------------------------------------|
#  * Script Name                                                               |
#    DoubleX RMVXA Linked Battlers Compatibility                               |
#------------------------------------------------------------------------------|
#  * Functions                                                                 |
#    Fixes compatibility issues in DoubleX RMVXA Linked Battlers               |
#    Scripts Addressed:                                                        |
#    1. DoubleX RMVXA Dynamic Data                                             |
#    2. Mr.Bubble's Tactics Ogre PSP Crafting System                           |
#    3. Theolized Sideview Battle System                                       |
#    4. Tsukihime's Instance Items                                             |
#------------------------------------------------------------------------------|
#  * Terms Of Use                                                              |
#    You shall keep this script's Script Info part's contents intact           |
#    You shalln't claim that this script is written by anyone other than       |
#    DoubleX or his aliases                                                    |
#    None of the above applies to DoubleX or his aliases                       |
#------------------------------------------------------------------------------|
#  * Prerequisites                                                             |
#    Scripts:                                                                  |
#    1. DoubleX RMVXA Linked Battlers                                          |
#------------------------------------------------------------------------------|
#  * Instructions                                                              |
#    1. Open the script editor and put this script into an open slot between   |
#       Linked Battlers and Main, save to take effect.                         |
#------------------------------------------------------------------------------|
#  * Links                                                                     |
#    Script Usage 101:                                                         |
#    1. forums.rpgmakerweb.com/index.php?/topic/32752-rmvxa-script-usage-101/  |
#    2. rpgmakervxace.net/topic/27475-rmvxa-script-usage-101/                  |
#    This script:                                                              |
#    1. [url]http://pastebin.com/X9j9aAeL[/url]                                           |
#------------------------------------------------------------------------------|
#  * Authors                                                                   |
#    DoubleX                                                                   |
#------------------------------------------------------------------------------|
#  * Changelog                                                                 |
#    v1.00a(GMT 1000 12-8-2015):                                               |
#    1. 1st version of this script finished                                    |
#==============================================================================|

($doublex_rmvxa ||= {})[:Linked_Battlers_Compatibility] = "v1.00a"

#==============================================================================|
#  ** Script Implementations                                                   |
#     You need not edit this part as it's about how this script works          |
#------------------------------------------------------------------------------|
#  * Script Support Info:                                                      |
#    1. Prerequisites                                                          |
#       - Decent understanding of how the addressed scripts work               |
#    2. Method documentation                                                   |
#       - The 1st part describes why this method's rewritten/aliased for       |
#         rewritten/aliased methods or what the method does for new methods    |
#       - The 2nd part describes what the arguments of the method are          |
#       - The 3rd part informs which version rewritten, aliased or created this|
#         method                                                               |
#       - The 4th part informs whether the method's rewritten or new           |
#       - The 5th part describes how this method works for new methods only,   |
#         and describes the parts added, removed or rewritten for rewritten or |
#         aliased methods only                                                 |
#       Example:                                                               |
# #--------------------------------------------------------------------------| |
# #  Why rewrite/alias/What this method does                                 | |
# #--------------------------------------------------------------------------| |
# # *argv: What these variables are                                            |
# # &argb: What this block is                                                  |
# def def_name(*argv, &argb) # Version X+; Rewrite/New                         |
#   # Added/Removed/Rewritten to do something/How this method works            |
#   def_name_code                                                              |
#   #                                                                          |
# end # def_name                                                               |
#------------------------------------------------------------------------------|

if $doublex_rmvxa[:Linked_Battlers]

if $doublex_rmvxa[:Dynamic_Data] || $imported["TH_InstanceItems"] || 
$imported[:TSBS]

  # Stores the object block clearance and reset methods
  CLEAR_RESET_LINKED_BATTLERS_BLOCKS = %Q(
def clear_linked_battlers_blocks(obj, copy = true)
  #{$imported["BubsTOCrafting"] ? %Q(
  if copy && obj.ingredient_list
    obj.ingredient_list.each { |ingredient|
      clear_linked_battlers_blocks(ingredient) if ingredient.is_a?(RPG::State)
    }
  end
  ) : %Q()}
  obj.linked_battlers = []
end

def reset_linked_battlers_blocks(obj, copy = true)
  #{$imported["BubsTOCrafting"] ? %Q(
  if copy && obj.ingredient_list
    obj.ingredient_list.each { |ingredient|
      reset_linked_battlers_blocks(ingredient) if ingredient.is_a?(RPG::State)
    }
  end
  ) : %Q()}
  obj.reset_notetags_linked_battlers
end
  )

end # if $doublex_rmvxa[:Dynamic_Data] || $imported["TH_InstanceItems"] || 
# $imported[:TSBS]

if $imported["TH_InstanceItems"]

class << DataManager

  #----------------------------------------------------------------------------|
  #  Clears and resets all linked battler blocks right before and after saving |
  #----------------------------------------------------------------------------|
  alias save_game_without_rescue_linked_battlers_1 save_game_without_rescue
  def save_game_without_rescue
    # Added
    [InstanceManager.weapons, InstanceManager.armors, 
     InstanceManager.items].each { |data|
      data.each_value { |obj| clear_linked_battlers_blocks(obj) if obj }
    }
    $game_party.clear_linked_battlers_blocks
    #
    save_game_without_rescue_linked_battlers_1
    #
    [InstanceManager.weapons, InstanceManager.armors, 
     InstanceManager.items].each { |data|
      data.each_value { |obj| reset_linked_battlers_blocks(obj) if obj }
    }
    $game_party.reset_linked_battlers_blocks
    #
  end # save_game_without_rescue

  #----------------------------------------------------------------------------|
  #  Resets all linked battler blocks right after loading                      |
  #----------------------------------------------------------------------------|
  alias extract_save_contents_linked_battlers_1 extract_save_contents
  def extract_save_contents(contents)
    extract_save_contents_linked_battlers_1(contents)
    # Added
    [InstanceManager.weapons, InstanceManager.armors, 
     InstanceManager.items].each { |data|
      data.each_value { |obj| reset_linked_battlers_blocks(obj) if obj }
    }
    $game_party.reset_linked_battlers_blocks
    #
  end # extract_save_contents

  #----------------------------------------------------------------------------|
  #  Clears and resets all blocks contained by the passed object               |
  #----------------------------------------------------------------------------|
  module_eval(CLEAR_RESET_LINKED_BATTLERS_BLOCKS) # New

end # DataManager

class << InstanceManager

  #----------------------------------------------------------------------------|
  #  Clears and resets all blocks right before and after using Marshal         |
  #----------------------------------------------------------------------------|
  alias make_full_copy_linked_battlers make_full_copy
  def make_full_copy(obj)
    # Added
    state = obj.is_a?(RPG::State)
    clear_linked_battlers_blocks(obj) if state
    #
    clone = make_full_copy_linked_battlerss(obj) # Rewritten
    # Added
    reset_linked_battlers_blocks(obj) if state
    reset_linked_battlers_blocks(clone) if state
    clone
    #
  end # make_full_copy

  #----------------------------------------------------------------------------|
  #  Clears and resets all blocks contained by the passed object               |
  #----------------------------------------------------------------------------|
  module_eval(CLEAR_RESET_LINKED_BATTLERS_BLOCKS) # New

end # InstanceManager

class Game_Party < Game_Unit

  #----------------------------------------------------------------------------|
  #  Clears all stored blocks as notetag values of all instance items          |
  #----------------------------------------------------------------------------|
  def clear_linked_battlers_blocks # New
    [@item_list, @weapon_list, @armor_list].each { |data|
      data.each { |obj| clear_linked_battlers_blocks(obj) if obj }
    }
  end # clear_linked_battlers_blocks

  #----------------------------------------------------------------------------|
  #  Resets all stored blocks as notetag values of all instance items          |
  #----------------------------------------------------------------------------|
  def reset_linked_battlers_blocks # New
    [@item_list, @weapon_list, @armor_list].each { |data|
      data.each { |obj| reset_linked_battlers_blocks(obj) if obj }
    }
  end # reset_linked_battlers_blocks

  #----------------------------------------------------------------------------|
  #  Clears and resets all blocks contained by the passed object               |
  #----------------------------------------------------------------------------|
  module_eval(CLEAR_RESET_LINKED_BATTLERS_BLOCKS) # New

end # Game_Party

end # if $imported["TH_InstanceItems"]

if $imported[:TSBS]

#------------------------------------------------------------------------------|
#  Clears and resets all blocks right before and after using Marshal           |
#------------------------------------------------------------------------------|
alias copy_linked_battlers copy
def copy(obj)
  # Added
  state = obj.is_a?(RPG::State)
  clear_linked_battlers_blocks(obj) if state
  #
  clone = copy_linked_battlers(obj) # Rewritten
  # Added
  reset_linked_battlers_blocks(obj) if state
  reset_linked_battlers_blocks(clone) if state
  clone
  #
end # copy

#------------------------------------------------------------------------------|
#  Clears and resets all blocks contained by the passed object                 |
#------------------------------------------------------------------------------|
eval(CLEAR_RESET_LINKED_BATTLERS_BLOCKS) # New

end # $imported[:TSBS]

if $doublex_rmvxa[:Dynamic_Data]

class << DataManager

  #----------------------------------------------------------------------------|
  #  Clears and resets all linked battler blocks right before and after saving |
  #----------------------------------------------------------------------------|
  alias save_game_without_rescue_linked_battlers_2 save_game_without_rescue
  def save_game_without_rescue(index)
    # Added
    $data_states.each { |obj| clear_linked_battlers_blocks(obj, false) if obj }
    #
    save_game_without_rescue_linked_battlers_2(index)
    # Added
    $data_states.each { |obj| reset_linked_battlers_blocks(obj, false) if obj }
    #
  end # save_game_without_rescue

  #----------------------------------------------------------------------------|
  #  Resets all linked battler blocks right after loading                      |
  #----------------------------------------------------------------------------|
  alias extract_save_contents_linked_battlers_2 extract_save_contents
  def extract_save_contents(contents)
    extract_save_contents_linked_battlers_2(contents)
    # Added
    $data_states.each { |obj| reset_linked_battlers_blocks(obj, false) if obj }
    #
  end # extract_save_contents

  #----------------------------------------------------------------------------|
  #  Clears and resets all blocks contained by the passed object               |
  #----------------------------------------------------------------------------|
  module_eval(CLEAR_RESET_LINKED_BATTLERS_BLOCKS) # New

end # DataManager

class RPG::State < RPG::BaseItem

  #----------------------------------------------------------------------------|
  #  New public instance variable                                              |
  #----------------------------------------------------------------------------|
  attr_accessor :linked_battlers_string # The notetag values as strings

  #----------------------------------------------------------------------------|
  #  Stores all notetag values in the string form as well                      |
  #----------------------------------------------------------------------------|
  alias load_notetags_linked_battlers_compatibility load_notetags_linked_battlers
  def load_notetags_linked_battlers
    load_notetags_linked_battlers_compatibility
    # Added
    @linked_battlers_string = []
    lb = "DoubleX_RMVXA::Linked_Battlers::"
    @note.split(/[\r\n]+/).each { |line|
      case line
      when /<linked battlers:\s*(\w+)\s*,\s*(\w+)\s*,\s*(\w+)\s*>/
        @linked_battlers_string  << 
        [eval("#{lb}#{$1}"), eval("#{lb}#{$2}"), eval("#{lb}#{$3}")]
      end
    }
    #
  end # load_notetags_linked_battlers

  #----------------------------------------------------------------------------|
  #  Resets all blocks used by the notetag values of the passed notetag        |
  #----------------------------------------------------------------------------|
  def reset_notetags_linked_battlers
    @linked_battlers_string.each { |linked_battler_string|
      @linked_battlers << []
      @linked_battlers[-1] << eval("-> battler, target { target.instance_exec { 
      #{linked_battler_string[0]} } }")
      @linked_battlers[-1] << eval("-> target { target.instance_exec { 
      #{linked_battler_string[1]} } }")
      @linked_battlers[-1] << eval("-> battler, target { target.instance_exec { 
      #{linked_battler_string[2]} } }")
    }
  end # reset_notetags_linked_battlers

end # RPG::State

end # if $doublex_rmvxa[:Dynamic_Data]

#------------------------------------------------------------------------------|

else

  # Informs users that they didn't place Linked Battlers above this script
  msgbox("To use DoubleX RMVXA Linked Battlers Compatibility, " + 
         "put it below:\n DoubleX RMVXA State Triggers\n but above Main")

end # if $doublex_rmvxa[:Linked_Battlers]

#==============================================================================|